@temporary-name/server 0.0.1-alpha.0cb08cf84b740850e7d8dcd1d8b87f78af26071b

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -0
  3. package/dist/adapters/aws-lambda/index.d.mts +26 -0
  4. package/dist/adapters/aws-lambda/index.d.ts +26 -0
  5. package/dist/adapters/aws-lambda/index.mjs +30 -0
  6. package/dist/adapters/fastify/index.d.mts +23 -0
  7. package/dist/adapters/fastify/index.d.ts +23 -0
  8. package/dist/adapters/fastify/index.mjs +30 -0
  9. package/dist/adapters/fetch/index.d.mts +28 -0
  10. package/dist/adapters/fetch/index.d.ts +28 -0
  11. package/dist/adapters/fetch/index.mjs +32 -0
  12. package/dist/adapters/node/index.d.mts +26 -0
  13. package/dist/adapters/node/index.d.ts +26 -0
  14. package/dist/adapters/node/index.mjs +30 -0
  15. package/dist/handler/index.d.mts +22 -0
  16. package/dist/handler/index.d.ts +22 -0
  17. package/dist/handler/index.mjs +8 -0
  18. package/dist/helpers/index.d.mts +149 -0
  19. package/dist/helpers/index.d.ts +149 -0
  20. package/dist/helpers/index.mjs +142 -0
  21. package/dist/index.d.mts +395 -0
  22. package/dist/index.d.ts +395 -0
  23. package/dist/index.mjs +831 -0
  24. package/dist/openapi/index.d.mts +167 -0
  25. package/dist/openapi/index.d.ts +167 -0
  26. package/dist/openapi/index.mjs +15 -0
  27. package/dist/shared/server.BOkueCuE.d.ts +39 -0
  28. package/dist/shared/server.BTVDgKdb.d.mts +9552 -0
  29. package/dist/shared/server.BTVDgKdb.d.ts +9552 -0
  30. package/dist/shared/server.C1RJffw4.mjs +30 -0
  31. package/dist/shared/server.CWiZN27E.d.mts +39 -0
  32. package/dist/shared/server.CjPiuQYH.d.mts +51 -0
  33. package/dist/shared/server.CjPiuQYH.d.ts +51 -0
  34. package/dist/shared/server.D7jtfDRy.mjs +288 -0
  35. package/dist/shared/server.JwVIEHL6.mjs +386 -0
  36. package/dist/shared/server.RQr7F4gX.mjs +1292 -0
  37. package/package.json +87 -0
@@ -0,0 +1,30 @@
1
+ import { parse, serialize } from 'cookie';
2
+
3
+ function setCookie(headers, name, value, options = {}) {
4
+ if (headers === void 0) {
5
+ return;
6
+ }
7
+ const cookieString = serialize(name, value, {
8
+ path: "/",
9
+ ...options
10
+ });
11
+ headers.append("Set-Cookie", cookieString);
12
+ }
13
+ function getCookie(headers, name, options = {}) {
14
+ if (headers === void 0) {
15
+ return void 0;
16
+ }
17
+ const cookieHeader = headers.get("cookie");
18
+ if (cookieHeader === null) {
19
+ return void 0;
20
+ }
21
+ return parse(cookieHeader, options)[name];
22
+ }
23
+ function deleteCookie(headers, name, options = {}) {
24
+ return setCookie(headers, name, "", {
25
+ ...options,
26
+ maxAge: 0
27
+ });
28
+ }
29
+
30
+ export { deleteCookie as d, getCookie as g, setCookie as s };
@@ -0,0 +1,39 @@
1
+ import { HTTPPath, StandardResponse, StandardLazyRequest } from '@temporary-name/shared';
2
+ import { C as Context, I as ImplementedResource, a as InferResourceContext } from './server.BTVDgKdb.mjs';
3
+
4
+ interface StandardHandleOptions<T extends Context> {
5
+ prefix?: HTTPPath;
6
+ context: T;
7
+ }
8
+ type StandardHandleResult = {
9
+ matched: true;
10
+ response: StandardResponse;
11
+ } | {
12
+ matched: false;
13
+ response: undefined;
14
+ };
15
+ declare class StandardHandler<T extends ImplementedResource> {
16
+ private readonly matcher;
17
+ constructor(resources: T[]);
18
+ handle(request: StandardLazyRequest, options: StandardHandleOptions<InferResourceContext<T>>): Promise<StandardHandleResult>;
19
+ }
20
+
21
+ type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (object extends T ? {
22
+ context?: T;
23
+ } : {
24
+ context: T;
25
+ });
26
+ declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
27
+ /**
28
+ * {@link https://github.com/unjs/rou3}
29
+ *
30
+ * @internal
31
+ */
32
+ declare function toRou3Pattern(path: HTTPPath): string;
33
+ /**
34
+ * @internal
35
+ */
36
+ declare function decodeParams(params: Record<string, string>): Record<string, string>;
37
+
38
+ export { StandardHandler as b, decodeParams as d, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
39
+ export type { FriendlyStandardHandleOptions as F, StandardHandleOptions as S, StandardHandleResult as a };
@@ -0,0 +1,51 @@
1
+ import { JSONSchema, SchemaConverter } from '@temporary-name/server/openapi';
2
+
3
+ interface ZodToJsonSchemaConverterOptions {
4
+ /**
5
+ * Max depth of lazy type.
6
+ *
7
+ * Used anyJsonSchema (`{}`) when exceed max depth
8
+ *
9
+ * @default 2
10
+ */
11
+ maxLazyDepth?: number;
12
+ /**
13
+ * Max depth of nested types.
14
+ *
15
+ * Used anyJsonSchema (`{}`) when exceed max depth
16
+ *
17
+ * @default 10
18
+ */
19
+ maxStructureDepth?: number;
20
+ /**
21
+ * The schema to be used to represent the any | unknown type.
22
+ *
23
+ * @default { }
24
+ */
25
+ anyJsonSchema?: Exclude<JSONSchema, boolean>;
26
+ /**
27
+ * The schema to be used when the Zod schema is unsupported.
28
+ *
29
+ * @default { not: {} }
30
+ */
31
+ unsupportedJsonSchema?: Exclude<JSONSchema, boolean>;
32
+ /**
33
+ * The schema to be used to represent the undefined type.
34
+ *
35
+ * @default { not: {} }
36
+ */
37
+ undefinedJsonSchema?: Exclude<JSONSchema, boolean>;
38
+ }
39
+ declare class ZodToJsonSchemaConverter {
40
+ #private;
41
+ private readonly maxLazyDepth;
42
+ private readonly maxStructureDepth;
43
+ private readonly anyJsonSchema;
44
+ private readonly unsupportedJsonSchema;
45
+ private readonly undefinedJsonSchema;
46
+ constructor(options?: ZodToJsonSchemaConverterOptions);
47
+ convert: SchemaConverter;
48
+ }
49
+
50
+ export { ZodToJsonSchemaConverter as a };
51
+ export type { ZodToJsonSchemaConverterOptions as Z };
@@ -0,0 +1,51 @@
1
+ import { JSONSchema, SchemaConverter } from '@temporary-name/server/openapi';
2
+
3
+ interface ZodToJsonSchemaConverterOptions {
4
+ /**
5
+ * Max depth of lazy type.
6
+ *
7
+ * Used anyJsonSchema (`{}`) when exceed max depth
8
+ *
9
+ * @default 2
10
+ */
11
+ maxLazyDepth?: number;
12
+ /**
13
+ * Max depth of nested types.
14
+ *
15
+ * Used anyJsonSchema (`{}`) when exceed max depth
16
+ *
17
+ * @default 10
18
+ */
19
+ maxStructureDepth?: number;
20
+ /**
21
+ * The schema to be used to represent the any | unknown type.
22
+ *
23
+ * @default { }
24
+ */
25
+ anyJsonSchema?: Exclude<JSONSchema, boolean>;
26
+ /**
27
+ * The schema to be used when the Zod schema is unsupported.
28
+ *
29
+ * @default { not: {} }
30
+ */
31
+ unsupportedJsonSchema?: Exclude<JSONSchema, boolean>;
32
+ /**
33
+ * The schema to be used to represent the undefined type.
34
+ *
35
+ * @default { not: {} }
36
+ */
37
+ undefinedJsonSchema?: Exclude<JSONSchema, boolean>;
38
+ }
39
+ declare class ZodToJsonSchemaConverter {
40
+ #private;
41
+ private readonly maxLazyDepth;
42
+ private readonly maxStructureDepth;
43
+ private readonly anyJsonSchema;
44
+ private readonly unsupportedJsonSchema;
45
+ private readonly undefinedJsonSchema;
46
+ constructor(options?: ZodToJsonSchemaConverterOptions);
47
+ convert: SchemaConverter;
48
+ }
49
+
50
+ export { ZodToJsonSchemaConverter as a };
51
+ export type { ZodToJsonSchemaConverterOptions as Z };
@@ -0,0 +1,288 @@
1
+ import { parseHTTPEndpoint, HTTPMethods } from '@temporary-name/shared';
2
+ import * as z from '@temporary-name/zod';
3
+
4
+ function apiResource(name, config) {
5
+ const { methods, ...restConfig } = config;
6
+ return { name, methods, config: restConfig };
7
+ }
8
+ function lazyResource(loader, endpoints) {
9
+ return { endpoints, loader };
10
+ }
11
+ function isLazyResource(resource) {
12
+ return "loader" in resource;
13
+ }
14
+ function unlazyResources(resources) {
15
+ return Promise.all(
16
+ resources.map(async (resource) => {
17
+ if (!isLazyResource(resource)) {
18
+ return resource;
19
+ }
20
+ const apiResource2 = await resource.loader();
21
+ validateLazyLoadedResource(resource, apiResource2);
22
+ return apiResource2;
23
+ })
24
+ );
25
+ }
26
+ function validateLazyLoadedResource(lazyResource2, loadedResource) {
27
+ const { endpoints } = lazyResource2;
28
+ const loadedLength = Object.keys(loadedResource.methods).length;
29
+ const endpointsLength = Object.keys(endpoints).length;
30
+ if (loadedLength !== endpointsLength) {
31
+ throw new Error(
32
+ `lazyResource loader returned an object with ${loadedLength} item(s), but the endpoints object has ${endpointsLength} item(s). These must match.`
33
+ );
34
+ }
35
+ for (const methodName in endpoints) {
36
+ const endpoint = endpoints[methodName];
37
+ const method = loadedResource.methods[methodName];
38
+ if (method === void 0) {
39
+ throw new Error(
40
+ `lazyResource endpoint "${methodName}" does not have a corresponding method in the object returned by the loader`
41
+ );
42
+ }
43
+ const [httpMethod, httpPath] = parseHTTPEndpoint(endpoint);
44
+ const { methodConfig } = method["~def"];
45
+ if (methodConfig.method !== httpMethod || methodConfig.path !== httpPath) {
46
+ throw new Error(
47
+ `lazyResource endpoint "${methodName}" routes to "${httpMethod} ${httpPath}", but the corresponding method from its loader routes to "${methodConfig.method} ${methodConfig.path}"`
48
+ );
49
+ }
50
+ }
51
+ }
52
+
53
+ class ValidationError extends Error {
54
+ issues;
55
+ data;
56
+ constructor(options) {
57
+ super("Validation error");
58
+ this.issues = options.issues;
59
+ this.data = options.data;
60
+ }
61
+ }
62
+ class ApiError extends Error {
63
+ extra;
64
+ constructor(...args) {
65
+ const { message, cause, ...extra } = args[0] ?? {};
66
+ super(message, { cause });
67
+ this.message = message ?? this.constructor.defaultMessage;
68
+ this.extra = extra;
69
+ }
70
+ static get defaultMessage() {
71
+ return this.type.split("_").map((word) => word[0]?.toUpperCase() + word.slice(1)).join(" ");
72
+ }
73
+ toJSON() {
74
+ const devExtra = {};
75
+ if (process.env.NODE_ENV === "development" && this.cause) {
76
+ devExtra.dev_only_details = this.cause instanceof Error ? { name: this.cause.name, message: this.cause.message, stack: this.cause.stack } : { cause: this.cause };
77
+ }
78
+ return {
79
+ ...devExtra,
80
+ type: this.constructor.type,
81
+ message: this.message,
82
+ ...this.extra
83
+ };
84
+ }
85
+ }
86
+ function safeTraverseData(data, path) {
87
+ let current = data;
88
+ for (const segment of path) {
89
+ if (current && typeof current === "object" && Object.prototype.hasOwnProperty.call(current, segment)) {
90
+ current = current[segment];
91
+ } else {
92
+ return null;
93
+ }
94
+ }
95
+ if (Array.isArray(current)) {
96
+ return "an array";
97
+ } else if (typeof current === "object") {
98
+ return "an object";
99
+ }
100
+ return `${typeof current}: ${JSON.stringify(current)}`;
101
+ }
102
+ function detailsFromValidationError(error) {
103
+ const issue = error.issues[0];
104
+ if (!issue) {
105
+ console.warn("ValidationError has no issues");
106
+ return null;
107
+ }
108
+ const param = issue.path.slice(1).join(".");
109
+ const location = issue.path[0];
110
+ if (issue.code === "invalid_type") {
111
+ const actualValue = safeTraverseData(error.data, issue.path);
112
+ if (actualValue === null) {
113
+ return {
114
+ code: "parameter_missing",
115
+ message: `Missing required parameter of type ${issue.expected}: ${String(issue.path.at(-1))}`,
116
+ location,
117
+ param
118
+ };
119
+ }
120
+ return {
121
+ code: "invalid_type",
122
+ message: `Expected ${issue.expected}, received ${actualValue}`,
123
+ location,
124
+ param
125
+ };
126
+ }
127
+ return {
128
+ code: issue.code,
129
+ message: issue.message,
130
+ param,
131
+ location
132
+ };
133
+ }
134
+ class BadRequestError extends ApiError {
135
+ static status = 400;
136
+ static type = "bad_request";
137
+ static extraSchema = {
138
+ code: z.string(),
139
+ param: z.string().optional(),
140
+ location: z.string().optional()
141
+ };
142
+ toJSON() {
143
+ if (this.cause instanceof ValidationError) {
144
+ return {
145
+ ...super.toJSON(),
146
+ ...detailsFromValidationError(this.cause) ?? {}
147
+ };
148
+ }
149
+ return super.toJSON();
150
+ }
151
+ }
152
+ class UnauthorizedError extends ApiError {
153
+ static status = 401;
154
+ static type = "unauthorized";
155
+ }
156
+ class ForbiddenError extends ApiError {
157
+ static status = 403;
158
+ static type = "forbidden";
159
+ }
160
+ class NotFoundError extends ApiError {
161
+ static status = 404;
162
+ static type = "not_found";
163
+ }
164
+ class MethodNotAllowedError extends ApiError {
165
+ static status = 405;
166
+ static type = "method_not_allowed";
167
+ }
168
+ class NotAcceptableError extends ApiError {
169
+ static status = 406;
170
+ static type = "not_acceptable";
171
+ }
172
+ class RequestTimeoutError extends ApiError {
173
+ static status = 408;
174
+ static type = "request_timeout";
175
+ }
176
+ class ConflictError extends ApiError {
177
+ static status = 409;
178
+ static type = "conflict";
179
+ }
180
+ class PreconditionFailedError extends ApiError {
181
+ static status = 412;
182
+ static type = "precondition_failed";
183
+ }
184
+ class ContentTooLargeError extends ApiError {
185
+ static status = 413;
186
+ static type = "content_too_large";
187
+ }
188
+ class UnsupportedMediaTypeError extends ApiError {
189
+ static status = 415;
190
+ static type = "unsupported_media_type";
191
+ }
192
+ class UnprocessableContentError extends ApiError {
193
+ static status = 422;
194
+ static type = "unprocessable_content";
195
+ }
196
+ class TooManyRequestsError extends ApiError {
197
+ static status = 429;
198
+ static type = "too_many_requests";
199
+ }
200
+ class InternalServerError extends ApiError {
201
+ static status = 500;
202
+ static type = "internal_server_error";
203
+ }
204
+ class NotImplementedError extends ApiError {
205
+ static status = 501;
206
+ static type = "not_implemented";
207
+ }
208
+ class BadGatewayError extends ApiError {
209
+ static status = 502;
210
+ static type = "bad_gateway";
211
+ }
212
+ class ServiceUnavailableError extends ApiError {
213
+ static status = 503;
214
+ static type = "service_unavailable";
215
+ }
216
+ class GatewayTimeoutError extends ApiError {
217
+ static status = 504;
218
+ static type = "gateway_timeout";
219
+ }
220
+ function isApiErrorStatus(status) {
221
+ return status < 200 || status >= 400;
222
+ }
223
+ function toApiError(error) {
224
+ if (error instanceof ApiError) {
225
+ return error;
226
+ }
227
+ return new InternalServerError({
228
+ cause: error
229
+ });
230
+ }
231
+ function encodeError(error) {
232
+ return {
233
+ status: error.constructor.status,
234
+ headers: new Headers(),
235
+ body: { error: error.toJSON() }
236
+ };
237
+ }
238
+
239
+ function wrapShape(schema) {
240
+ return schema instanceof z.core.$ZodType ? schema : z.object(schema);
241
+ }
242
+ const zEmptyObject = z.object({});
243
+
244
+ const endpointRegex = new RegExp(`^(${HTTPMethods.join("|")})`);
245
+ function isDevelopment() {
246
+ return process.env.NODE_ENV === "development";
247
+ }
248
+ function standardizeHTTPPath(path) {
249
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
250
+ }
251
+ function getDynamicParams(path) {
252
+ return path ? standardizeHTTPPath(path).match(/\/\{[^}]+\}/g)?.map((v) => ({
253
+ raw: v,
254
+ name: v.match(/\{\+?([^}]+)\}/)[1]
255
+ })) : void 0;
256
+ }
257
+ function parseEndpointDefinition(endpoint, schema) {
258
+ let pathSchema;
259
+ const [method, path] = parseHTTPEndpoint(endpoint);
260
+ const pathParamNames = getDynamicParams(path)?.map((p) => p.name) ?? [];
261
+ let schemaKeys;
262
+ if (schema instanceof z.core.$ZodType) {
263
+ if (schema instanceof z.core.$ZodObject) {
264
+ schemaKeys = Object.keys(schema._zod.def.shape);
265
+ pathSchema = schema;
266
+ } else {
267
+ throw new Error(
268
+ `Path schema for endpoint "${endpoint}" must be a ZodObject schema (or object where each value is a ZodType).`
269
+ );
270
+ }
271
+ } else if (typeof schema === "object") {
272
+ schemaKeys = Object.keys(schema);
273
+ pathSchema = z.object(schema);
274
+ } else if (schema !== void 0) {
275
+ throw new Error(
276
+ `Path schema for endpoint "${endpoint}" must be a ZodObject schema (or object where each value is a ZodType).`
277
+ );
278
+ } else {
279
+ schemaKeys = [];
280
+ pathSchema = zEmptyObject;
281
+ }
282
+ if (pathParamNames.length !== schemaKeys.length || !pathParamNames.every((name) => schemaKeys.includes(name))) {
283
+ throw new Error(`Path schema keys do not match dynamic parameters in endpoint "${endpoint}".`);
284
+ }
285
+ return { method, path, pathSchema };
286
+ }
287
+
288
+ export { ApiError as A, BadRequestError as B, ConflictError as C, ForbiddenError as F, GatewayTimeoutError as G, InternalServerError as I, MethodNotAllowedError as M, NotFoundError as N, PreconditionFailedError as P, RequestTimeoutError as R, ServiceUnavailableError as S, TooManyRequestsError as T, UnauthorizedError as U, ValidationError as V, apiResource as a, NotAcceptableError as b, ContentTooLargeError as c, UnsupportedMediaTypeError as d, encodeError as e, UnprocessableContentError as f, getDynamicParams as g, NotImplementedError as h, isLazyResource as i, BadGatewayError as j, isApiErrorStatus as k, lazyResource as l, endpointRegex as m, isDevelopment as n, parseEndpointDefinition as p, standardizeHTTPPath as s, toApiError as t, unlazyResources as u, validateLazyLoadedResource as v, wrapShape as w, zEmptyObject as z };