elysia 1.4.29 → 1.4.31

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.
@@ -7,76 +7,32 @@ import {
7
7
  ValidationError
8
8
  } from "./error.mjs";
9
9
  import { parseQuery } from "./parse-query.mjs";
10
- import { getSchemaProperties } from "./schema.mjs";
11
- import { hasSetImmediate, redirect, StatusMap, signCookie } from "./utils.mjs";
12
- const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), isDangerousKey = (key) => {
13
- if (DANGEROUS_KEYS.has(key)) return !0;
14
- const match = key.match(ARRAY_INDEX_REGEX);
15
- return match ? DANGEROUS_KEYS.has(match[1]) : !1;
16
- }, parseArrayKey = (key) => {
17
- const match = key.match(ARRAY_INDEX_REGEX);
18
- return match ? {
19
- name: match[1],
20
- index: parseInt(match[2], 10)
21
- } : null;
22
- }, parseObjectString = (entry) => {
23
- if (!(typeof entry != "string" || entry.charCodeAt(0) !== 123))
24
- try {
25
- const parsed = JSON.parse(entry);
26
- if (parsed && typeof parsed == "object" && !Array.isArray(parsed))
27
- return parsed;
28
- } catch {
29
- return;
30
- }
31
- }, setNestedValue = (obj, path, value) => {
32
- const keys = path.split("."), lastKey = keys.pop();
33
- if (isDangerousKey(lastKey) || keys.some(isDangerousKey)) return;
34
- let current = obj;
35
- for (const key of keys) {
36
- const arrayInfo2 = parseArrayKey(key);
37
- if (arrayInfo2) {
38
- Array.isArray(current[arrayInfo2.name]) || (current[arrayInfo2.name] = []);
39
- const existing = current[arrayInfo2.name][arrayInfo2.index], isFile = typeof File < "u" && existing instanceof File;
40
- (!existing || typeof existing != "object" || Array.isArray(existing) || isFile) && (current[arrayInfo2.name][arrayInfo2.index] = parseObjectString(existing) ?? {}), current = current[arrayInfo2.name][arrayInfo2.index];
41
- } else
42
- (!current[key] || typeof current[key] != "object") && (current[key] = {}), current = current[key];
43
- }
44
- const arrayInfo = parseArrayKey(lastKey);
45
- arrayInfo ? (Array.isArray(current[arrayInfo.name]) || (current[arrayInfo.name] = []), current[arrayInfo.name][arrayInfo.index] = value) : current[lastKey] = value;
46
- }, normalizeFormValue = (value) => {
47
- if (value.length === 1) {
48
- const stringValue2 = value[0];
49
- if (typeof stringValue2 == "string" && (stringValue2.charCodeAt(0) === 123 || stringValue2.charCodeAt(0) === 91))
50
- try {
51
- const parsed2 = JSON.parse(stringValue2);
52
- if (parsed2 && typeof parsed2 == "object")
53
- return parsed2;
54
- } catch {
55
- }
56
- return value[0];
57
- }
58
- const stringValue = value.find(
59
- (entry) => typeof entry == "string"
60
- );
61
- if (!stringValue || typeof File > "u") return value;
62
- const files = value.filter((entry) => entry instanceof File);
63
- if (!files.length || stringValue.charCodeAt(0) !== 123) return value;
64
- let parsed;
65
- try {
66
- parsed = JSON.parse(stringValue);
67
- } catch {
68
- return value;
69
- }
70
- return typeof parsed != "object" || parsed === null ? value : (!("file" in parsed) && files.length === 1 ? parsed.file = files[0] : !("files" in parsed) && files.length > 1 && (parsed.files = files), parsed);
71
- }, injectDefaultValues = (typeChecker, obj) => {
72
- let schema = typeChecker.schema;
73
- if (!schema) return;
74
- schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
75
- const properties = getSchemaProperties(schema);
76
- if (properties)
77
- for (const [key, keySchema] of Object.entries(properties))
78
- obj[key] ??= keySchema.default;
79
- }, createDynamicHandler = (app) => {
10
+ import { parseFormData } from "./form-data.mjs";
11
+ import {
12
+ applySchemaDefaults,
13
+ getSchemaProperties
14
+ } from "./schema.mjs";
15
+ import {
16
+ hasSetImmediate,
17
+ mergeCookie,
18
+ redirect,
19
+ safeAssign,
20
+ StatusMap,
21
+ signCookie
22
+ } from "./utils.mjs";
23
+ async function validateStandardSchema(type, validator, value) {
24
+ const result = await validator.Validate(value);
25
+ if (result.issues)
26
+ throw new ValidationError(
27
+ type,
28
+ validator,
29
+ value,
30
+ !1,
31
+ result.issues
32
+ );
33
+ return result.value;
34
+ }
35
+ const createDynamicHandler = (app) => {
80
36
  const { mapResponse, mapEarlyResponse } = app["~adapter"].handler, defaultHeader = app.setHeaders;
81
37
  return async (request) => {
82
38
  const url = request.url, s = url.indexOf("/", 11), qi = url.indexOf("?", s + 1), path = qi === -1 ? url.substring(s) : url.substring(s, qi), set = {
@@ -111,10 +67,10 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
111
67
  if (!handler)
112
68
  throw context.query = qi === -1 ? {} : parseQuery(url.substring(qi + 1)), new NotFoundError();
113
69
  const { handle, validator, content, route } = handler.store;
114
- if (hooks = handler.store.hooks, hooks.config?.mount)
115
- return await hooks.config.mount(request);
70
+ hooks = handler.store.hooks;
71
+ const isMount = !!hooks.config?.mount;
116
72
  let body;
117
- if (request.method !== "GET" && request.method !== "HEAD")
73
+ if (!isMount && request.method !== "GET" && request.method !== "HEAD")
118
74
  if (content)
119
75
  switch (content) {
120
76
  case "application/json":
@@ -130,17 +86,7 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
130
86
  body = await request.arrayBuffer();
131
87
  break;
132
88
  case "multipart/form-data": {
133
- body = {};
134
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
135
- form.forEach((v, k) => {
136
- const list = grouped.get(k);
137
- list ? list.push(v) : grouped.set(k, [v]);
138
- });
139
- for (const [key, value] of grouped) {
140
- if (body[key]) continue;
141
- const finalValue = normalizeFormValue(value);
142
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
143
- }
89
+ body = parseFormData(await request.formData());
144
90
  break;
145
91
  }
146
92
  }
@@ -173,17 +119,9 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
173
119
  break;
174
120
  case "formdata":
175
121
  case "multipart/form-data": {
176
- body = {};
177
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
178
- form.forEach((v, k) => {
179
- const list = grouped.get(k);
180
- list ? list.push(v) : grouped.set(k, [v]);
181
- });
182
- for (const [key, value] of grouped) {
183
- if (body[key]) continue;
184
- const finalValue = normalizeFormValue(value);
185
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
186
- }
122
+ body = parseFormData(
123
+ await request.formData()
124
+ );
187
125
  break;
188
126
  }
189
127
  default: {
@@ -224,17 +162,9 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
224
162
  body = await request.arrayBuffer();
225
163
  break;
226
164
  case "multipart/form-data": {
227
- body = {};
228
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
229
- form.forEach((v, k) => {
230
- const list = grouped.get(k);
231
- list ? list.push(v) : grouped.set(k, [v]);
232
- });
233
- for (const [key, value] of grouped) {
234
- if (body[key]) continue;
235
- const finalValue = normalizeFormValue(value);
236
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
237
- }
165
+ body = parseFormData(
166
+ await request.formData()
167
+ );
238
168
  break;
239
169
  }
240
170
  }
@@ -243,29 +173,29 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
243
173
  context.route = route, context.body = body, context.params = handler?.params || void 0, context.query = qi === -1 ? {} : parseQuery(url.substring(qi + 1)), context.headers = {};
244
174
  for (const [key, value] of request.headers.entries())
245
175
  context.headers[key] = value;
246
- const cookieMeta = {
247
- domain: app.config.cookie?.domain ?? // @ts-expect-error
176
+ const cookieValidator = validator?.createCookie?.(), defaultCookie = hooks.config?.cookie ? mergeCookie(app.config.cookie ?? {}, hooks.config.cookie) : app.config.cookie, cookieMeta = {
177
+ domain: defaultCookie?.domain ?? // @ts-expect-error
248
178
  validator?.cookie?.config.domain,
249
- expires: app.config.cookie?.expires ?? // @ts-expect-error
179
+ expires: defaultCookie?.expires ?? // @ts-expect-error
250
180
  validator?.cookie?.config.expires,
251
- httpOnly: app.config.cookie?.httpOnly ?? // @ts-expect-error
181
+ httpOnly: defaultCookie?.httpOnly ?? // @ts-expect-error
252
182
  validator?.cookie?.config.httpOnly,
253
- maxAge: app.config.cookie?.maxAge ?? // @ts-expect-error
183
+ maxAge: defaultCookie?.maxAge ?? // @ts-expect-error
254
184
  validator?.cookie?.config.maxAge,
255
185
  // @ts-expect-error
256
- path: app.config.cookie?.path ?? validator?.cookie?.config.path,
257
- priority: app.config.cookie?.priority ?? // @ts-expect-error
186
+ path: defaultCookie?.path ?? validator?.cookie?.config.path,
187
+ priority: defaultCookie?.priority ?? // @ts-expect-error
258
188
  validator?.cookie?.config.priority,
259
- partitioned: app.config.cookie?.partitioned ?? // @ts-expect-error
189
+ partitioned: defaultCookie?.partitioned ?? // @ts-expect-error
260
190
  validator?.cookie?.config.partitioned,
261
- sameSite: app.config.cookie?.sameSite ?? // @ts-expect-error
191
+ sameSite: defaultCookie?.sameSite ?? // @ts-expect-error
262
192
  validator?.cookie?.config.sameSite,
263
- secure: app.config.cookie?.secure ?? // @ts-expect-error
193
+ secure: defaultCookie?.secure ?? // @ts-expect-error
264
194
  validator?.cookie?.config.secure,
265
- secrets: app.config.cookie?.secrets ?? // @ts-expect-error
195
+ secrets: defaultCookie?.secrets ?? // @ts-expect-error
266
196
  validator?.cookie?.config.secrets,
267
197
  // @ts-expect-error
268
- sign: app.config.cookie?.sign ?? validator?.cookie?.config.sign
198
+ sign: defaultCookie?.sign ?? validator?.cookie?.config.sign
269
199
  }, cookieHeaderValue = request.headers.get("cookie");
270
200
  context.cookie = await parseCookie(
271
201
  context.set,
@@ -273,11 +203,23 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
273
203
  cookieMeta
274
204
  );
275
205
  const headerValidator = validator?.createHeaders?.();
276
- headerValidator && injectDefaultValues(headerValidator, context.headers);
206
+ headerValidator?.hasDefault && (context.headers = applySchemaDefaults(
207
+ headerValidator,
208
+ context.headers,
209
+ !0
210
+ ));
277
211
  const paramsValidator = validator?.createParams?.();
278
- paramsValidator && injectDefaultValues(paramsValidator, context.params);
212
+ paramsValidator?.hasDefault && (context.params = applySchemaDefaults(
213
+ paramsValidator,
214
+ context.params,
215
+ !0
216
+ ));
279
217
  const queryValidator = validator?.createQuery?.();
280
- if (queryValidator && injectDefaultValues(queryValidator, context.query), hooks.transform)
218
+ if (queryValidator?.hasDefault && (context.query = applySchemaDefaults(
219
+ queryValidator,
220
+ context.query,
221
+ !0
222
+ )), hooks.transform)
281
223
  for (let i = 0; i < hooks.transform.length; i++) {
282
224
  const hook = hooks.transform[i];
283
225
  let response2 = hook.fn(context);
@@ -286,27 +228,42 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
286
228
  if (result)
287
229
  return context.response = result;
288
230
  }
289
- hook.subType === "derive" && Object.assign(context, response2);
231
+ hook.subType === "derive" && safeAssign(context, response2);
290
232
  }
291
233
  if (validator) {
292
234
  if (headerValidator) {
293
235
  const _header = structuredClone(context.headers);
294
236
  for (const [key, value] of request.headers)
295
237
  _header[key] = value;
296
- if (validator.headers.Check(_header) === !1)
238
+ if (headerValidator.provider === "standard")
239
+ context.headers = await validateStandardSchema(
240
+ "header",
241
+ headerValidator,
242
+ _header
243
+ );
244
+ else if (validator.headers.Check(_header) === !1)
297
245
  throw new ValidationError(
298
246
  "header",
299
247
  validator.headers,
300
248
  _header
301
249
  );
302
250
  } else validator.headers?.Decode && (context.headers = validator.headers.Decode(context.headers));
303
- if (paramsValidator?.Check(context.params) === !1)
304
- throw new ValidationError(
251
+ if (paramsValidator?.provider === "standard")
252
+ context.params = await validateStandardSchema(
305
253
  "params",
306
- validator.params,
254
+ paramsValidator,
307
255
  context.params
308
256
  );
309
- if (validator.params?.Decode && (context.params = validator.params.Decode(context.params)), validator.query?.schema) {
257
+ else {
258
+ if (paramsValidator?.Check(context.params) === !1)
259
+ throw new ValidationError(
260
+ "params",
261
+ validator.params,
262
+ context.params
263
+ );
264
+ validator.params?.Decode && (context.params = validator.params.Decode(context.params));
265
+ }
266
+ if (validator.query?.schema) {
310
267
  let schema = validator.query.schema;
311
268
  schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
312
269
  const properties = getSchemaProperties(schema);
@@ -316,31 +273,61 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
316
273
  (value.type === "array" || value.items?.type === "string") && typeof context.query[property] == "string" && context.query[property] && (context.query[property] = context.query[property].split(","));
317
274
  }
318
275
  }
319
- if (queryValidator?.Check(context.query) === !1)
320
- throw new ValidationError(
276
+ if (queryValidator?.provider === "standard")
277
+ context.query = await validateStandardSchema(
321
278
  "query",
322
- validator.query,
279
+ queryValidator,
323
280
  context.query
324
281
  );
325
- if (validator.query?.Decode && (context.query = validator.query.Decode(context.query)), validator.createCookie?.()) {
282
+ else {
283
+ if (queryValidator?.Check(context.query) === !1)
284
+ throw new ValidationError(
285
+ "query",
286
+ validator.query,
287
+ context.query
288
+ );
289
+ validator.query?.Decode && (context.query = validator.query.Decode(context.query));
290
+ }
291
+ if (cookieValidator) {
326
292
  let cookieValue = {};
327
293
  for (const [key, value] of Object.entries(context.cookie))
328
294
  cookieValue[key] = value.value;
329
- if (validator.cookie.Check(cookieValue) === !1)
330
- throw new ValidationError(
295
+ if (cookieValidator.provider === "standard") {
296
+ cookieValue = await validateStandardSchema(
331
297
  "cookie",
332
- validator.cookie,
298
+ cookieValidator,
333
299
  cookieValue
334
300
  );
335
- validator.cookie?.Decode && (cookieValue = validator.cookie.Decode(
336
- cookieValue
337
- ));
301
+ for (const key of Object.keys(cookieValue))
302
+ context.cookie[key].value = cookieValue[key];
303
+ } else {
304
+ if (cookieValidator.Check(cookieValue) === !1)
305
+ throw new ValidationError(
306
+ "cookie",
307
+ cookieValidator,
308
+ cookieValue
309
+ );
310
+ if (cookieValidator.Decode) {
311
+ cookieValue = cookieValidator.Decode(cookieValue);
312
+ for (const key of Object.keys(cookieValue))
313
+ context.cookie[key].value = cookieValue[key];
314
+ }
315
+ }
338
316
  }
339
- if (validator.createBody?.()?.Check(body) === !1)
340
- throw new ValidationError("body", validator.body, body);
341
- if (validator.body?.Decode) {
342
- let decoded = validator.body.Decode(body);
343
- decoded instanceof Promise && (decoded = await decoded), context.body = decoded?.value ?? decoded;
317
+ const bodyValidator = validator.createBody?.();
318
+ if (bodyValidator?.hasDefault && (body = applySchemaDefaults(bodyValidator, body), context.body = body), bodyValidator?.provider === "standard")
319
+ context.body = await validateStandardSchema(
320
+ "body",
321
+ bodyValidator,
322
+ body
323
+ );
324
+ else {
325
+ if (bodyValidator?.Check(body) === !1)
326
+ throw new ValidationError("body", validator.body, body);
327
+ if (validator.body?.Decode) {
328
+ let decoded = validator.body.Decode(body);
329
+ decoded instanceof Promise && (decoded = await decoded), context.body = decoded?.value ?? decoded;
330
+ }
344
331
  }
345
332
  }
346
333
  if (hooks.beforeHandle)
@@ -353,7 +340,7 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
353
340
  return context.response = result;
354
341
  }
355
342
  if (hook.subType === "resolve") {
356
- Object.assign(context, response2);
343
+ safeAssign(context, response2);
357
344
  continue;
358
345
  }
359
346
  if (response2 !== void 0) {
@@ -379,7 +366,13 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
379
366
  const isCustomStatuResponse = response2 instanceof ElysiaCustomStatusResponse, status2 = isCustomStatuResponse ? response2.code : set.status ? typeof set.status == "string" ? StatusMap[set.status] : set.status : 200;
380
367
  isCustomStatuResponse && (set.status = status2, response2 = response2.response);
381
368
  const responseValidator = validator?.createResponse?.()?.[status2];
382
- if (responseValidator?.Check(response2) === !1)
369
+ if (responseValidator?.provider === "standard")
370
+ response2 = await validateStandardSchema(
371
+ "response",
372
+ responseValidator,
373
+ response2
374
+ );
375
+ else if (responseValidator?.Check(response2) === !1)
383
376
  if (responseValidator?.Clean)
384
377
  try {
385
378
  const temp = responseValidator.Clean(response2);
@@ -415,7 +408,13 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
415
408
  const isCustomStatuResponse = response instanceof ElysiaCustomStatusResponse, status2 = isCustomStatuResponse ? response.code : set.status ? typeof set.status == "string" ? StatusMap[set.status] : set.status : 200;
416
409
  isCustomStatuResponse && (set.status = status2, response = response.response);
417
410
  const responseValidator = validator?.createResponse?.()?.[status2];
418
- if (responseValidator?.Check(response) === !1)
411
+ if (responseValidator?.provider === "standard")
412
+ response = await validateStandardSchema(
413
+ "response",
414
+ responseValidator,
415
+ response
416
+ );
417
+ else if (responseValidator?.Check(response) === !1)
419
418
  if (responseValidator?.Clean)
420
419
  try {
421
420
  const temp = responseValidator.Clean(response);
@@ -457,7 +456,9 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
457
456
  secret
458
457
  );
459
458
  } else {
460
- const properties = getSchemaProperties(validator?.cookie?.schema);
459
+ const properties = getSchemaProperties(
460
+ validator?.cookie?.schema
461
+ );
461
462
  if (secret)
462
463
  for (const name of cookieMeta.sign)
463
464
  !properties || !(name in properties) || context.set.cookie[name]?.value && (context.set.cookie[name].value = await signCookie(
package/dist/error.d.ts CHANGED
@@ -107,6 +107,16 @@ interface ValueErrorWithSummary extends ValueError {
107
107
  summary?: string;
108
108
  }
109
109
  export declare const mapValueError: (error: ValueError | undefined) => ValueErrorWithSummary | undefined;
110
+ /**
111
+ * Maximum amount of validation error
112
+ */
113
+ export declare const MAX_ERRORS = 64;
114
+ export declare const MAX_VALIDATION_ERROR_DEPTH = 16;
115
+ export declare const MAX_VALIDATION_ERROR_NODES = 8192;
116
+ export declare const MAX_VALIDATION_ERROR_ENTRIES = 4096;
117
+ export declare const MAX_VALIDATION_ERROR_CONTAINER_ENTRIES = 512;
118
+ export declare const MAX_VALIDATION_ERROR_STRING_LENGTH = 4096;
119
+ export declare const MAX_VALIDATION_ERROR_OUTPUT_LENGTH = 65536;
110
120
  export declare class InvalidFileType extends Error {
111
121
  property: string;
112
122
  expected: string | string[];
@@ -174,24 +184,6 @@ export declare class ValidationError extends Error {
174
184
  * })
175
185
  * ```
176
186
  */
177
- detail(message: unknown, allowUnsafeValidatorDetails?: boolean): string | {
178
- type: string;
179
- on: string;
180
- found: unknown;
181
- message: unknown;
182
- property?: undefined;
183
- summary?: undefined;
184
- expected?: undefined;
185
- errors?: undefined;
186
- } | {
187
- type: string;
188
- on: string;
189
- property: string;
190
- message: unknown;
191
- summary: string | undefined;
192
- found: unknown;
193
- expected: unknown;
194
- errors: ValueErrorWithSummary[];
195
- };
187
+ detail(message: unknown, allowUnsafeValidatorDetails?: boolean): unknown;
196
188
  }
197
189
  export {};