Socket
Socket
Sign inDemoInstall

elysia

Package Overview
Dependencies
Maintainers
1
Versions
409
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

elysia - npm Package Compare versions

Comparing version 1.0.0-exp.13 to 1.0.0-exp.14

dist/cjs/dynamic-handle-BOErSqze.d.ts

2

dist/bun/index.d.ts
import 'bun';
import 'memoirist';
export { Static, TSchema } from '@sinclair/typebox';
export { Q as AfterHandler, a0 as BodyHandler, ad as Checksum, C as ComposedHandler, aE as Context, f as Cookie, d as CookieOptions, D as DefinitionBase, E as Elysia, n as ElysiaConfig, a3 as ErrorHandler, A as HTTPMethod, H as Handler, B as InputSchema, a7 as InternalRoute, I as InternalServerError, m as InvalidCookieSignature, y as LifeCycleEvent, L as LifeCycleStore, a8 as ListenCallback, a6 as LocalHook, o as MaybePromise, F as MergeSchema, N as NotFoundError, K as OptionalHandler, P as ParseError, aF as PreContext, a1 as PreHandler, t as RouteBase, v as RouteSchema, S as SchemaValidator, s as SingletonBase, Z as TraceEvent, b as TraceHandler, _ as TraceProcess, T as TraceReporter, c as TraceStream, w as UnwrapRoute, U as UnwrapSchema, V as ValidationError, X as VoidHandler, E as default, l as error, ar as getResponseSchemaValidator, aq as getSchemaValidator, b4 as mapCompactResponse, b3 as mapEarlyResponse, b2 as mapResponse, al as mergeDeep, ap as mergeHook, an as mergeObjectArray, aG as t } from './dynamic-handle-O2HN1QLh.js';
export { K as AfterHandler, $ as BodyHandler, ac as Checksum, C as ComposedHandler, aD as Context, e as Cookie, c as CookieOptions, D as DefinitionBase, E as Elysia, m as ElysiaConfig, a2 as ErrorHandler, z as HTTPMethod, H as Handler, A as InputSchema, a6 as InternalRoute, I as InternalServerError, l as InvalidCookieSignature, x as LifeCycleEvent, L as LifeCycleStore, a7 as ListenCallback, a5 as LocalHook, n as MaybePromise, B as MergeSchema, N as NotFoundError, J as OptionalHandler, P as ParseError, aE as PreContext, a0 as PreHandler, s as RouteBase, u as RouteSchema, S as SchemaValidator, r as SingletonBase, Y as TraceEvent, T as TraceHandler, Z as TraceProcess, a as TraceReporter, b as TraceStream, v as UnwrapRoute, U as UnwrapSchema, V as ValidationError, W as VoidHandler, E as default, k as error, ap as getResponseSchemaValidator, ao as getSchemaValidator, aR as mapCompactResponse, aQ as mapEarlyResponse, aP as mapResponse, an as mergeHook, al as mergeObjectArray, aF as t } from './dynamic-handle-BOErSqze.js';
import '@sinclair/typebox/compiler';

@@ -6,0 +6,0 @@ import 'openapi-types';

@@ -1,3 +0,4 @@

import { E as Elysia, L as LifeCycleStore, S as SchemaValidator, H as Handler, a as Sucrose, C as ComposedHandler } from './dynamic-handle-O2HN1QLh.js';
import { E as Elysia, L as LifeCycleStore, S as SchemaValidator, H as Handler, C as ComposedHandler } from './dynamic-handle-BOErSqze.js';
import { TAnySchema } from '@sinclair/typebox';
import { Sucrose } from './sucrose.js';
import 'bun';

@@ -31,3 +32,4 @@ import 'memoirist';

declare const composeErrorHandler: (app: Elysia<any, any, any, any, any, any, any, any>) => any;
declare const jitRoute: (index: number) => string;
export { composeErrorHandler, composeGeneralHandler, composeHandler, hasProperty, hasReturn, hasTransform, hasType, isAsync };
export { composeErrorHandler, composeGeneralHandler, composeHandler, hasProperty, hasReturn, hasTransform, hasType, isAsync, jitRoute };

@@ -1,2 +0,2 @@

export { aE as Context, aF as PreContext } from './dynamic-handle-O2HN1QLh.js';
export { aD as Context, aE as PreContext } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

@@ -1,2 +0,2 @@

export { f as Cookie, d as CookieOptions, e as ElysiaCookie, g as createCookieJar, p as parseCookie } from './dynamic-handle-O2HN1QLh.js';
export { e as Cookie, c as CookieOptions, d as ElysiaCookie, f as createCookieJar, p as parseCookie } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

@@ -39,11 +39,12 @@ "use strict";

var import_cookie2 = require("cookie");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
var import_fast_decode_uri_component2 = __toESM(require("fast-decode-uri-component"));
// src/utils.ts
var import_typebox = require("@sinclair/typebox");
var import_value2 = require("@sinclair/typebox/value");
var import_compiler = require("@sinclair/typebox/compiler");
var import_typebox2 = require("@sinclair/typebox");
var import_value4 = require("@sinclair/typebox/value");
var import_compiler2 = require("@sinclair/typebox/compiler");
var import_deepmerge2 = __toESM(require("deepmerge"));
// src/handler.ts
var import_cookie = require("cookie");
// src/index.ts
var import_eventemitter3 = __toESM(require("eventemitter3"));

@@ -64,7 +65,312 @@ // src/error.ts

};
var ValidationError = class _ValidationError extends Error {
constructor(type, validator, value) {
if (typeof value === "object" && ELYSIA_RESPONSE in value)
value = value.response;
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value.Value.Errors(validator, value).First();
const customError = error2?.schema.error ? typeof error2.schema.error === "function" ? error2.schema.error(type, validator, value) : error2.schema.error : void 0;
const accessor = error2?.path?.slice(1) || "root";
let message = "";
if (customError) {
message = typeof customError === "object" ? JSON.stringify(customError) : customError + "";
} else if (isProduction) {
message = JSON.stringify({
type,
message: error2?.message
});
} else {
message = JSON.stringify(
{
type,
at: accessor,
message: error2?.message,
expected: import_value.Value.Create(
// @ts-ignore private field
validator.schema
),
found: value,
errors: [...validator.Errors(value)]
},
null,
2
);
}
super(message);
this.type = type;
this.validator = validator;
this.value = value;
this.code = "VALIDATION";
this.status = 400;
Object.setPrototypeOf(this, _ValidationError.prototype);
}
get all() {
return [...this.validator.Errors(this.value)];
}
static simplifyModel(validator) {
const model = "schema" in validator ? validator.schema : validator;
try {
return import_value.Value.Create(model);
} catch {
return model;
}
}
get model() {
return _ValidationError.simplifyModel(this.validator);
}
toResponse(headers) {
return new Response(this.message, {
status: 400,
headers: {
...headers,
"content-type": "application/json"
}
});
}
};
// src/index.ts
var import_deepmerge = __toESM(require("deepmerge"));
// src/handler.ts
var import_cookie = require("cookie");
var hasHeaderShorthand = "toJSON" in new Headers();
// src/compose.ts
var import_value2 = require("@sinclair/typebox/value");
var import_fast_querystring = require("fast-querystring");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
var headersHasToJSON = new Headers().toJSON;
var KindSymbol = Symbol.for("TypeBox.Kind");
var TransformSymbol = Symbol.for("TypeBox.Transform");
// src/dynamic-handle.ts
var import_fast_querystring2 = require("fast-querystring");
// src/type-system.ts
var import_system = require("@sinclair/typebox/system");
var import_typebox = require("@sinclair/typebox");
var import_value3 = require("@sinclair/typebox/value");
var import_system2 = require("@sinclair/typebox/system");
var import_compiler = require("@sinclair/typebox/compiler");
try {
import_system.TypeSystem.Format(
"email",
(value) => /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(
value
)
);
import_system.TypeSystem.Format(
"uuid",
(value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value
)
);
import_system.TypeSystem.Format(
"date",
(value) => !Number.isNaN(new Date(value).getTime())
);
import_system.TypeSystem.Format(
"date-time",
(value) => !Number.isNaN(new Date(value).getTime())
);
} catch {
}
var t = Object.assign({}, import_typebox.Type);
var parseFileUnit = (size) => {
if (typeof size === "string")
switch (size.slice(-1)) {
case "k":
return +size.slice(0, size.length - 1) * 1024;
case "m":
return +size.slice(0, size.length - 1) * 1048576;
default:
return +size;
}
return size;
};
var validateFile = (options, value) => {
if (!(value instanceof Blob))
return false;
if (options.minSize && value.size < parseFileUnit(options.minSize))
return false;
if (options.maxSize && value.size > parseFileUnit(options.maxSize))
return false;
if (options.extension)
if (typeof options.extension === "string") {
if (!value.type.startsWith(options.extension))
return false;
} else {
for (let i = 0; i < options.extension.length; i++)
if (value.type.startsWith(options.extension[i]))
return true;
return false;
}
return true;
};
var Files = import_system.TypeSystem.Type(
"Files",
(options, value) => {
if (!Array.isArray(value))
return validateFile(options, value);
if (options.minItems && value.length < options.minItems)
return false;
if (options.maxItems && value.length > options.maxItems)
return false;
for (let i = 0; i < value.length; i++)
if (!validateFile(options, value[i]))
return false;
return true;
}
);
if (!import_typebox.FormatRegistry.Get("numeric"))
import_typebox.FormatRegistry.Set("numeric", (value) => !!value && !isNaN(+value));
if (!import_typebox.FormatRegistry.Get("boolean"))
import_typebox.FormatRegistry.Set(
"boolean",
(value) => value === "true" || value === "false"
);
if (!import_typebox.FormatRegistry.Get("ObjectString"))
import_typebox.FormatRegistry.Set("ObjectString", (value) => {
let start = value.charCodeAt(0);
if (start === 9 || start === 10 || start === 32)
start = value.trimStart().charCodeAt(0);
if (start !== 123 && start !== 91)
return false;
try {
JSON.parse(value);
return true;
} catch {
return false;
}
});
var ElysiaType = {
Numeric: (property) => {
const schema = import_typebox.Type.Number(property);
return t.Transform(
t.Union(
[
t.String({
format: "numeric",
default: 0
}),
t.Number(property)
],
property
)
).Decode((value) => {
const number = +value;
if (isNaN(number))
return value;
if (property && !import_value3.Value.Check(schema, number))
throw new ValidationError("property", schema, number);
return number;
}).Encode((value) => value);
},
BooleanString: (property) => {
const schema = import_typebox.Type.Boolean(property);
return t.Transform(
t.Union(
[
t.String({
format: "boolean",
default: false
}),
t.Boolean(property)
],
property
)
).Decode((value) => {
if (typeof value === "string")
return value === "true";
if (property && !import_value3.Value.Check(schema, value))
throw new ValidationError("property", schema, value);
return value;
}).Encode((value) => value);
},
ObjectString: (properties, options) => t.Transform(
t.Union(
[
t.String({
format: "ObjectString",
default: ""
}),
t.Object(properties, options)
],
options
)
).Decode((value) => {
if (typeof value === "string")
try {
return JSON.parse(value);
} catch {
return value;
}
return value;
}).Encode((value) => JSON.stringify(value)),
File: import_system.TypeSystem.Type("File", validateFile),
Files: (options = {}) => t.Transform(t.Union([Files(options)])).Decode((value) => {
if (Array.isArray(value))
return value;
return [value];
}).Encode((value) => value),
Nullable: (schema) => t.Union([t.Null(), schema]),
/**
* Allow Optional, Nullable and Undefined
*/
MaybeEmpty: (schema) => t.Union([t.Null(), t.Undefined(), schema]),
Cookie: (properties, options) => t.Object(properties, options)
};
t.BooleanString = ElysiaType.BooleanString;
t.ObjectString = ElysiaType.ObjectString;
t.Numeric = ElysiaType.Numeric;
t.File = (arg = {}) => ElysiaType.File({
default: "File",
...arg,
extension: arg?.type,
type: "string",
format: "binary"
});
t.Files = (arg = {}) => ElysiaType.Files({
...arg,
elysiaMeta: "Files",
default: "Files",
extension: arg?.type,
type: "array",
items: {
...arg,
default: "Files",
type: "string",
format: "binary"
}
});
t.Nullable = (schema) => ElysiaType.Nullable(schema);
t.MaybeEmpty = ElysiaType.MaybeEmpty;
t.Cookie = ElysiaType.Cookie;
// src/utils.ts
var primitiveHooks = [
"start",
"request",
"parse",
"transform",
"resolve",
"beforeHandle",
"afterHandle",
"onResponse",
"mapResponse",
"trace",
"error",
"stop",
"body",
"headers",
"params",
"query",
"response",
"type",
"detail"
];
var primitiveHookMap = primitiveHooks.reduce(
(acc, x2) => (acc[x2] = true, acc),
{}
);
var isBun = typeof Bun !== "undefined";

@@ -97,5 +403,3 @@ var hasHash = isBun && typeof Bun.hash === "function";

);
const hmacArray = Array.from(new Uint8Array(hmacBuffer));
const digest = btoa(String.fromCharCode(...hmacArray));
return `${val}.${removeTrailingEquals(digest)}`;
return val + "." + removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"));
};

@@ -262,3 +566,3 @@ var unsignCookie = async (input, secret) => {

for (const [name, v] of Object.entries(cookies)) {
let value = (0, import_fast_decode_uri_component.default)(v);
let value = (0, import_fast_decode_uri_component2.default)(v);
if (sign === true || sign?.includes(name)) {

@@ -265,0 +569,0 @@ if (!secret)

@@ -1,2 +0,2 @@

export { b6 as DynamicHandler, b8 as createDynamicErrorHandler, b7 as createDynamicHandler } from './dynamic-handle-O2HN1QLh.js';
export { aT as DynamicHandler, aV as createDynamicErrorHandler, aU as createDynamicHandler } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

@@ -42,124 +42,12 @@ "use strict";

// src/utils.ts
var import_typebox = require("@sinclair/typebox");
var import_value = require("@sinclair/typebox/value");
var import_compiler = require("@sinclair/typebox/compiler");
var isBun = typeof Bun !== "undefined";
var hasHash = isBun && typeof Bun.hash === "function";
var StatusMap = {
Continue: 100,
"Switching Protocols": 101,
Processing: 102,
"Early Hints": 103,
OK: 200,
Created: 201,
Accepted: 202,
"Non-Authoritative Information": 203,
"No Content": 204,
"Reset Content": 205,
"Partial Content": 206,
"Multi-Status": 207,
"Already Reported": 208,
"Multiple Choices": 300,
"Moved Permanently": 301,
Found: 302,
"See Other": 303,
"Not Modified": 304,
"Temporary Redirect": 307,
"Permanent Redirect": 308,
"Bad Request": 400,
Unauthorized: 401,
"Payment Required": 402,
Forbidden: 403,
"Not Found": 404,
"Method Not Allowed": 405,
"Not Acceptable": 406,
"Proxy Authentication Required": 407,
"Request Timeout": 408,
Conflict: 409,
Gone: 410,
"Length Required": 411,
"Precondition Failed": 412,
"Payload Too Large": 413,
"URI Too Long": 414,
"Unsupported Media Type": 415,
"Range Not Satisfiable": 416,
"Expectation Failed": 417,
"I'm a teapot": 418,
"Misdirected Request": 421,
"Unprocessable Content": 422,
Locked: 423,
"Failed Dependency": 424,
"Too Early": 425,
"Upgrade Required": 426,
"Precondition Required": 428,
"Too Many Requests": 429,
"Request Header Fields Too Large": 431,
"Unavailable For Legal Reasons": 451,
"Internal Server Error": 500,
"Not Implemented": 501,
"Bad Gateway": 502,
"Service Unavailable": 503,
"Gateway Timeout": 504,
"HTTP Version Not Supported": 505,
"Variant Also Negotiates": 506,
"Insufficient Storage": 507,
"Loop Detected": 508,
"Not Extended": 510,
"Network Authentication Required": 511
};
function removeTrailingEquals(digest) {
let trimmedDigest = digest;
while (trimmedDigest.endsWith("=")) {
trimmedDigest = trimmedDigest.slice(0, -1);
}
return trimmedDigest;
}
var encoder = new TextEncoder();
var signCookie = async (val, secret) => {
if (typeof val !== "string")
throw new TypeError("Cookie value must be provided as a string.");
if (secret === null)
throw new TypeError("Secret key must be provided.");
const secretKey = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const hmacBuffer = await crypto.subtle.sign(
"HMAC",
secretKey,
encoder.encode(val)
);
const hmacArray = Array.from(new Uint8Array(hmacBuffer));
const digest = btoa(String.fromCharCode(...hmacArray));
return `${val}.${removeTrailingEquals(digest)}`;
};
var unsignCookie = async (input, secret) => {
if (typeof input !== "string")
throw new TypeError("Signed cookie string must be provided.");
if (null === secret)
throw new TypeError("Secret key must be provided.");
const tentativeValue = input.slice(0, input.lastIndexOf("."));
const expectedInput = await signCookie(tentativeValue, secret);
return expectedInput === input ? tentativeValue : false;
};
var isNumericString = (message) => {
if (message.length < 16)
return message.trim().length !== 0 && !Number.isNaN(Number(message));
if (message.length === 16) {
const numVal = Number(message);
if (numVal.toString() === message)
return message.trim().length !== 0 && !Number.isNaN(numVal);
}
return false;
};
var import_typebox2 = require("@sinclair/typebox");
var import_value4 = require("@sinclair/typebox/value");
var import_compiler2 = require("@sinclair/typebox/compiler");
var import_deepmerge2 = __toESM(require("deepmerge"));
// src/cookies.ts
var import_cookie = require("cookie");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
// src/index.ts
var import_eventemitter3 = __toESM(require("eventemitter3"));
// src/error.ts
var import_value2 = require("@sinclair/typebox/value");
var import_value = require("@sinclair/typebox/value");
var env = typeof Bun !== "undefined" ? Bun.env : typeof process !== "undefined" ? process?.env : void 0;

@@ -188,5 +76,5 @@ var ERROR_CODE = Symbol("ElysiaErrorCode");

value = value.response;
const error = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value2.Value.Errors(validator, value).First();
const customError = error?.schema.error ? typeof error.schema.error === "function" ? error.schema.error(type, validator, value) : error.schema.error : void 0;
const accessor = error?.path?.slice(1) || "root";
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value.Value.Errors(validator, value).First();
const customError = error2?.schema.error ? typeof error2.schema.error === "function" ? error2.schema.error(type, validator, value) : error2.schema.error : void 0;
const accessor = error2?.path?.slice(1) || "root";
let message = "";

@@ -198,3 +86,3 @@ if (customError) {

type,
message: error?.message
message: error2?.message
});

@@ -206,4 +94,4 @@ } else {

at: accessor,
message: error?.message,
expected: import_value2.Value.Create(
message: error2?.message,
expected: import_value.Value.Create(
// @ts-ignore private field

@@ -233,3 +121,3 @@ validator.schema

try {
return import_value2.Value.Create(model);
return import_value.Value.Create(model);
} catch {

@@ -253,3 +141,13 @@ return model;

// src/index.ts
var import_deepmerge = __toESM(require("deepmerge"));
// src/compose.ts
var import_value2 = require("@sinclair/typebox/value");
var import_fast_querystring = require("fast-querystring");
var import_fast_decode_uri_component2 = __toESM(require("fast-decode-uri-component"));
// src/cookies.ts
var import_cookie = require("cookie");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
var Cookie = class {

@@ -451,2 +349,345 @@ constructor(name, jar, initial = {}) {

// src/compose.ts
var headersHasToJSON = new Headers().toJSON;
var KindSymbol = Symbol.for("TypeBox.Kind");
var TransformSymbol = Symbol.for("TypeBox.Transform");
// src/type-system.ts
var import_system = require("@sinclair/typebox/system");
var import_typebox = require("@sinclair/typebox");
var import_value3 = require("@sinclair/typebox/value");
var import_system2 = require("@sinclair/typebox/system");
var import_compiler = require("@sinclair/typebox/compiler");
try {
import_system.TypeSystem.Format(
"email",
(value) => /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(
value
)
);
import_system.TypeSystem.Format(
"uuid",
(value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value
)
);
import_system.TypeSystem.Format(
"date",
(value) => !Number.isNaN(new Date(value).getTime())
);
import_system.TypeSystem.Format(
"date-time",
(value) => !Number.isNaN(new Date(value).getTime())
);
} catch {
}
var t = Object.assign({}, import_typebox.Type);
var parseFileUnit = (size) => {
if (typeof size === "string")
switch (size.slice(-1)) {
case "k":
return +size.slice(0, size.length - 1) * 1024;
case "m":
return +size.slice(0, size.length - 1) * 1048576;
default:
return +size;
}
return size;
};
var validateFile = (options, value) => {
if (!(value instanceof Blob))
return false;
if (options.minSize && value.size < parseFileUnit(options.minSize))
return false;
if (options.maxSize && value.size > parseFileUnit(options.maxSize))
return false;
if (options.extension)
if (typeof options.extension === "string") {
if (!value.type.startsWith(options.extension))
return false;
} else {
for (let i = 0; i < options.extension.length; i++)
if (value.type.startsWith(options.extension[i]))
return true;
return false;
}
return true;
};
var Files = import_system.TypeSystem.Type(
"Files",
(options, value) => {
if (!Array.isArray(value))
return validateFile(options, value);
if (options.minItems && value.length < options.minItems)
return false;
if (options.maxItems && value.length > options.maxItems)
return false;
for (let i = 0; i < value.length; i++)
if (!validateFile(options, value[i]))
return false;
return true;
}
);
if (!import_typebox.FormatRegistry.Get("numeric"))
import_typebox.FormatRegistry.Set("numeric", (value) => !!value && !isNaN(+value));
if (!import_typebox.FormatRegistry.Get("boolean"))
import_typebox.FormatRegistry.Set(
"boolean",
(value) => value === "true" || value === "false"
);
if (!import_typebox.FormatRegistry.Get("ObjectString"))
import_typebox.FormatRegistry.Set("ObjectString", (value) => {
let start = value.charCodeAt(0);
if (start === 9 || start === 10 || start === 32)
start = value.trimStart().charCodeAt(0);
if (start !== 123 && start !== 91)
return false;
try {
JSON.parse(value);
return true;
} catch {
return false;
}
});
var ElysiaType = {
Numeric: (property) => {
const schema = import_typebox.Type.Number(property);
return t.Transform(
t.Union(
[
t.String({
format: "numeric",
default: 0
}),
t.Number(property)
],
property
)
).Decode((value) => {
const number = +value;
if (isNaN(number))
return value;
if (property && !import_value3.Value.Check(schema, number))
throw new ValidationError("property", schema, number);
return number;
}).Encode((value) => value);
},
BooleanString: (property) => {
const schema = import_typebox.Type.Boolean(property);
return t.Transform(
t.Union(
[
t.String({
format: "boolean",
default: false
}),
t.Boolean(property)
],
property
)
).Decode((value) => {
if (typeof value === "string")
return value === "true";
if (property && !import_value3.Value.Check(schema, value))
throw new ValidationError("property", schema, value);
return value;
}).Encode((value) => value);
},
ObjectString: (properties, options) => t.Transform(
t.Union(
[
t.String({
format: "ObjectString",
default: ""
}),
t.Object(properties, options)
],
options
)
).Decode((value) => {
if (typeof value === "string")
try {
return JSON.parse(value);
} catch {
return value;
}
return value;
}).Encode((value) => JSON.stringify(value)),
File: import_system.TypeSystem.Type("File", validateFile),
Files: (options = {}) => t.Transform(t.Union([Files(options)])).Decode((value) => {
if (Array.isArray(value))
return value;
return [value];
}).Encode((value) => value),
Nullable: (schema) => t.Union([t.Null(), schema]),
/**
* Allow Optional, Nullable and Undefined
*/
MaybeEmpty: (schema) => t.Union([t.Null(), t.Undefined(), schema]),
Cookie: (properties, options) => t.Object(properties, options)
};
t.BooleanString = ElysiaType.BooleanString;
t.ObjectString = ElysiaType.ObjectString;
t.Numeric = ElysiaType.Numeric;
t.File = (arg = {}) => ElysiaType.File({
default: "File",
...arg,
extension: arg?.type,
type: "string",
format: "binary"
});
t.Files = (arg = {}) => ElysiaType.Files({
...arg,
elysiaMeta: "Files",
default: "Files",
extension: arg?.type,
type: "array",
items: {
...arg,
default: "Files",
type: "string",
format: "binary"
}
});
t.Nullable = (schema) => ElysiaType.Nullable(schema);
t.MaybeEmpty = ElysiaType.MaybeEmpty;
t.Cookie = ElysiaType.Cookie;
// src/utils.ts
var primitiveHooks = [
"start",
"request",
"parse",
"transform",
"resolve",
"beforeHandle",
"afterHandle",
"onResponse",
"mapResponse",
"trace",
"error",
"stop",
"body",
"headers",
"params",
"query",
"response",
"type",
"detail"
];
var primitiveHookMap = primitiveHooks.reduce(
(acc, x2) => (acc[x2] = true, acc),
{}
);
var isBun = typeof Bun !== "undefined";
var hasHash = isBun && typeof Bun.hash === "function";
var StatusMap = {
Continue: 100,
"Switching Protocols": 101,
Processing: 102,
"Early Hints": 103,
OK: 200,
Created: 201,
Accepted: 202,
"Non-Authoritative Information": 203,
"No Content": 204,
"Reset Content": 205,
"Partial Content": 206,
"Multi-Status": 207,
"Already Reported": 208,
"Multiple Choices": 300,
"Moved Permanently": 301,
Found: 302,
"See Other": 303,
"Not Modified": 304,
"Temporary Redirect": 307,
"Permanent Redirect": 308,
"Bad Request": 400,
Unauthorized: 401,
"Payment Required": 402,
Forbidden: 403,
"Not Found": 404,
"Method Not Allowed": 405,
"Not Acceptable": 406,
"Proxy Authentication Required": 407,
"Request Timeout": 408,
Conflict: 409,
Gone: 410,
"Length Required": 411,
"Precondition Failed": 412,
"Payload Too Large": 413,
"URI Too Long": 414,
"Unsupported Media Type": 415,
"Range Not Satisfiable": 416,
"Expectation Failed": 417,
"I'm a teapot": 418,
"Misdirected Request": 421,
"Unprocessable Content": 422,
Locked: 423,
"Failed Dependency": 424,
"Too Early": 425,
"Upgrade Required": 426,
"Precondition Required": 428,
"Too Many Requests": 429,
"Request Header Fields Too Large": 431,
"Unavailable For Legal Reasons": 451,
"Internal Server Error": 500,
"Not Implemented": 501,
"Bad Gateway": 502,
"Service Unavailable": 503,
"Gateway Timeout": 504,
"HTTP Version Not Supported": 505,
"Variant Also Negotiates": 506,
"Insufficient Storage": 507,
"Loop Detected": 508,
"Not Extended": 510,
"Network Authentication Required": 511
};
function removeTrailingEquals(digest) {
let trimmedDigest = digest;
while (trimmedDigest.endsWith("=")) {
trimmedDigest = trimmedDigest.slice(0, -1);
}
return trimmedDigest;
}
var encoder = new TextEncoder();
var signCookie = async (val, secret) => {
if (typeof val !== "string")
throw new TypeError("Cookie value must be provided as a string.");
if (secret === null)
throw new TypeError("Secret key must be provided.");
const secretKey = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const hmacBuffer = await crypto.subtle.sign(
"HMAC",
secretKey,
encoder.encode(val)
);
return val + "." + removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"));
};
var unsignCookie = async (input, secret) => {
if (typeof input !== "string")
throw new TypeError("Signed cookie string must be provided.");
if (null === secret)
throw new TypeError("Secret key must be provided.");
const tentativeValue = input.slice(0, input.lastIndexOf("."));
const expectedInput = await signCookie(tentativeValue, secret);
return expectedInput === input ? tentativeValue : false;
};
var isNumericString = (message) => {
if (message.length < 16)
return message.trim().length !== 0 && !Number.isNaN(Number(message));
if (message.length === 16) {
const numVal = Number(message);
if (numVal.toString() === message)
return message.trim().length !== 0 && !Number.isNaN(numVal);
}
return false;
};
// src/handler.ts

@@ -1022,7 +1263,7 @@ var hasHeaderShorthand = "toJSON" in new Headers();

};
var errorToResponse = (error, set) => new Response(
var errorToResponse = (error2, set) => new Response(
JSON.stringify({
name: error?.name,
message: error?.message,
cause: error?.cause
name: error2?.name,
message: error2?.message,
cause: error2?.cause
}),

@@ -1036,3 +1277,3 @@ {

// src/dynamic-handle.ts
var import_fast_querystring = require("fast-querystring");
var import_fast_querystring2 = require("fast-querystring");
var createDynamicHandler = (app) => async (request) => {

@@ -1047,6 +1288,8 @@ const url = request.url, s = url.indexOf("/", 11), qi = url.indexOf("?", s + 1), path = qi === -1 ? url.substring(s) : url.substring(s, qi);

{},
app.decorator,
// @ts-expect-error
app.singleton.decorator,
{
set,
store: app.store,
// @ts-expect-error
store: app.singleton.store,
request,

@@ -1082,3 +1325,3 @@ path,

case "application/x-www-form-urlencoded":
body = (0, import_fast_querystring.parse)(await request.text());
body = (0, import_fast_querystring2.parse)(await request.text());
break;

@@ -1126,3 +1369,3 @@ case "application/octet-stream":

case "application/x-www-form-urlencoded":
body = (0, import_fast_querystring.parse)(await request.text());
body = (0, import_fast_querystring2.parse)(await request.text());
break;

@@ -1152,3 +1395,3 @@ case "application/octet-stream":

context.params = handler?.params || void 0;
context.query = qi === -1 ? {} : (0, import_fast_querystring.parse)(url.substring(qi + 1));
context.query = qi === -1 ? {} : (0, import_fast_querystring2.parse)(url.substring(qi + 1));
context.headers = {};

@@ -1293,6 +1536,6 @@ for (const [key, value] of request.headers.entries())

return mapResponse(response, context.set);
} catch (error) {
if (error.status)
set.status = error.status;
return app.handleError(context, error);
} catch (error2) {
if (error2.status)
set.status = error2.status;
return app.handleError(context, error2);
} finally {

@@ -1303,4 +1546,4 @@ for (const onResponse of app.event.onResponse)

};
var createDynamicErrorHandler = (app) => async (context, error) => {
const errorContext = Object.assign(context, { error, code: error.code });
var createDynamicErrorHandler = (app) => async (context, error2) => {
const errorContext = Object.assign(context, { error: error2, code: error2.code });
errorContext.set = context.set;

@@ -1315,6 +1558,6 @@ for (let i = 0; i < app.event.error.length; i++) {

return new Response(
typeof error.cause === "string" ? error.cause : error.message,
typeof error2.cause === "string" ? error2.cause : error2.message,
{
headers: context.set.headers,
status: error.status ?? 500
status: error2.status ?? 500
}

@@ -1321,0 +1564,0 @@ );

import '@sinclair/typebox/compiler';
import '@sinclair/typebox';
export { i as ELYSIA_RESPONSE, h as ERROR_CODE, k as ElysiaErrors, I as InternalServerError, m as InvalidCookieSignature, N as NotFoundError, P as ParseError, V as ValidationError, l as error, j as isProduction } from './dynamic-handle-O2HN1QLh.js';
export { h as ELYSIA_RESPONSE, g as ERROR_CODE, j as ElysiaErrors, I as InternalServerError, l as InvalidCookieSignature, N as NotFoundError, P as ParseError, V as ValidationError, k as error, i as isProduction } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -5,0 +5,0 @@ import 'memoirist';

@@ -44,9 +44,14 @@ "use strict";

module.exports = __toCommonJS(error_exports);
var import_value2 = require("@sinclair/typebox/value");
var import_value4 = require("@sinclair/typebox/value");
// src/utils.ts
var import_typebox = require("@sinclair/typebox");
var import_value = require("@sinclair/typebox/value");
var import_compiler = require("@sinclair/typebox/compiler");
var import_typebox2 = require("@sinclair/typebox");
var import_value3 = require("@sinclair/typebox/value");
var import_compiler2 = require("@sinclair/typebox/compiler");
var import_deepmerge2 = __toESM(require("deepmerge"));
// src/index.ts
var import_eventemitter3 = __toESM(require("eventemitter3"));
var import_deepmerge = __toESM(require("deepmerge"));
// src/handler.ts

@@ -62,3 +67,240 @@ var import_cookie2 = require("cookie");

// src/compose.ts
var import_value = require("@sinclair/typebox/value");
var import_fast_querystring = require("fast-querystring");
var import_fast_decode_uri_component2 = __toESM(require("fast-decode-uri-component"));
var headersHasToJSON = new Headers().toJSON;
var KindSymbol = Symbol.for("TypeBox.Kind");
var TransformSymbol = Symbol.for("TypeBox.Transform");
// src/dynamic-handle.ts
var import_fast_querystring2 = require("fast-querystring");
// src/type-system.ts
var import_system = require("@sinclair/typebox/system");
var import_typebox = require("@sinclair/typebox");
var import_value2 = require("@sinclair/typebox/value");
var import_system2 = require("@sinclair/typebox/system");
var import_compiler = require("@sinclair/typebox/compiler");
try {
import_system.TypeSystem.Format(
"email",
(value) => /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(
value
)
);
import_system.TypeSystem.Format(
"uuid",
(value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value
)
);
import_system.TypeSystem.Format(
"date",
(value) => !Number.isNaN(new Date(value).getTime())
);
import_system.TypeSystem.Format(
"date-time",
(value) => !Number.isNaN(new Date(value).getTime())
);
} catch {
}
var t = Object.assign({}, import_typebox.Type);
var parseFileUnit = (size) => {
if (typeof size === "string")
switch (size.slice(-1)) {
case "k":
return +size.slice(0, size.length - 1) * 1024;
case "m":
return +size.slice(0, size.length - 1) * 1048576;
default:
return +size;
}
return size;
};
var validateFile = (options, value) => {
if (!(value instanceof Blob))
return false;
if (options.minSize && value.size < parseFileUnit(options.minSize))
return false;
if (options.maxSize && value.size > parseFileUnit(options.maxSize))
return false;
if (options.extension)
if (typeof options.extension === "string") {
if (!value.type.startsWith(options.extension))
return false;
} else {
for (let i = 0; i < options.extension.length; i++)
if (value.type.startsWith(options.extension[i]))
return true;
return false;
}
return true;
};
var Files = import_system.TypeSystem.Type(
"Files",
(options, value) => {
if (!Array.isArray(value))
return validateFile(options, value);
if (options.minItems && value.length < options.minItems)
return false;
if (options.maxItems && value.length > options.maxItems)
return false;
for (let i = 0; i < value.length; i++)
if (!validateFile(options, value[i]))
return false;
return true;
}
);
if (!import_typebox.FormatRegistry.Get("numeric"))
import_typebox.FormatRegistry.Set("numeric", (value) => !!value && !isNaN(+value));
if (!import_typebox.FormatRegistry.Get("boolean"))
import_typebox.FormatRegistry.Set(
"boolean",
(value) => value === "true" || value === "false"
);
if (!import_typebox.FormatRegistry.Get("ObjectString"))
import_typebox.FormatRegistry.Set("ObjectString", (value) => {
let start = value.charCodeAt(0);
if (start === 9 || start === 10 || start === 32)
start = value.trimStart().charCodeAt(0);
if (start !== 123 && start !== 91)
return false;
try {
JSON.parse(value);
return true;
} catch {
return false;
}
});
var ElysiaType = {
Numeric: (property) => {
const schema = import_typebox.Type.Number(property);
return t.Transform(
t.Union(
[
t.String({
format: "numeric",
default: 0
}),
t.Number(property)
],
property
)
).Decode((value) => {
const number = +value;
if (isNaN(number))
return value;
if (property && !import_value2.Value.Check(schema, number))
throw new ValidationError("property", schema, number);
return number;
}).Encode((value) => value);
},
BooleanString: (property) => {
const schema = import_typebox.Type.Boolean(property);
return t.Transform(
t.Union(
[
t.String({
format: "boolean",
default: false
}),
t.Boolean(property)
],
property
)
).Decode((value) => {
if (typeof value === "string")
return value === "true";
if (property && !import_value2.Value.Check(schema, value))
throw new ValidationError("property", schema, value);
return value;
}).Encode((value) => value);
},
ObjectString: (properties, options) => t.Transform(
t.Union(
[
t.String({
format: "ObjectString",
default: ""
}),
t.Object(properties, options)
],
options
)
).Decode((value) => {
if (typeof value === "string")
try {
return JSON.parse(value);
} catch {
return value;
}
return value;
}).Encode((value) => JSON.stringify(value)),
File: import_system.TypeSystem.Type("File", validateFile),
Files: (options = {}) => t.Transform(t.Union([Files(options)])).Decode((value) => {
if (Array.isArray(value))
return value;
return [value];
}).Encode((value) => value),
Nullable: (schema) => t.Union([t.Null(), schema]),
/**
* Allow Optional, Nullable and Undefined
*/
MaybeEmpty: (schema) => t.Union([t.Null(), t.Undefined(), schema]),
Cookie: (properties, options) => t.Object(properties, options)
};
t.BooleanString = ElysiaType.BooleanString;
t.ObjectString = ElysiaType.ObjectString;
t.Numeric = ElysiaType.Numeric;
t.File = (arg = {}) => ElysiaType.File({
default: "File",
...arg,
extension: arg?.type,
type: "string",
format: "binary"
});
t.Files = (arg = {}) => ElysiaType.Files({
...arg,
elysiaMeta: "Files",
default: "Files",
extension: arg?.type,
type: "array",
items: {
...arg,
default: "Files",
type: "string",
format: "binary"
}
});
t.Nullable = (schema) => ElysiaType.Nullable(schema);
t.MaybeEmpty = ElysiaType.MaybeEmpty;
t.Cookie = ElysiaType.Cookie;
// src/utils.ts
var primitiveHooks = [
"start",
"request",
"parse",
"transform",
"resolve",
"beforeHandle",
"afterHandle",
"onResponse",
"mapResponse",
"trace",
"error",
"stop",
"body",
"headers",
"params",
"query",
"response",
"type",
"detail"
];
var primitiveHookMap = primitiveHooks.reduce(
(acc, x2) => (acc[x2] = true, acc),
{}
);
var isBun = typeof Bun !== "undefined";

@@ -174,3 +416,3 @@ var hasHash = isBun && typeof Bun.hash === "function";

value = value.response;
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value2.Value.Errors(validator, value).First();
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value4.Value.Errors(validator, value).First();
const customError = error2?.schema.error ? typeof error2.schema.error === "function" ? error2.schema.error(type, validator, value) : error2.schema.error : void 0;

@@ -192,3 +434,3 @@ const accessor = error2?.path?.slice(1) || "root";

message: error2?.message,
expected: import_value2.Value.Create(
expected: import_value4.Value.Create(
// @ts-ignore private field

@@ -218,3 +460,3 @@ validator.schema

try {
return import_value2.Value.Create(model);
return import_value4.Value.Create(model);
} catch {

@@ -221,0 +463,0 @@ return model;

@@ -1,2 +0,2 @@

export { b5 as errorToResponse, a$ as isNotEmpty, b4 as mapCompactResponse, b3 as mapEarlyResponse, b2 as mapResponse, b0 as parseSetCookies, b1 as serializeCookie } from './dynamic-handle-O2HN1QLh.js';
export { aS as errorToResponse, aM as isNotEmpty, aR as mapCompactResponse, aQ as mapEarlyResponse, aP as mapResponse, aN as parseSetCookies, aO as serializeCookie } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

@@ -45,77 +45,12 @@ "use strict";

// src/utils.ts
var import_typebox = require("@sinclair/typebox");
var import_value = require("@sinclair/typebox/value");
var import_compiler = require("@sinclair/typebox/compiler");
var isBun = typeof Bun !== "undefined";
var hasHash = isBun && typeof Bun.hash === "function";
var StatusMap = {
Continue: 100,
"Switching Protocols": 101,
Processing: 102,
"Early Hints": 103,
OK: 200,
Created: 201,
Accepted: 202,
"Non-Authoritative Information": 203,
"No Content": 204,
"Reset Content": 205,
"Partial Content": 206,
"Multi-Status": 207,
"Already Reported": 208,
"Multiple Choices": 300,
"Moved Permanently": 301,
Found: 302,
"See Other": 303,
"Not Modified": 304,
"Temporary Redirect": 307,
"Permanent Redirect": 308,
"Bad Request": 400,
Unauthorized: 401,
"Payment Required": 402,
Forbidden: 403,
"Not Found": 404,
"Method Not Allowed": 405,
"Not Acceptable": 406,
"Proxy Authentication Required": 407,
"Request Timeout": 408,
Conflict: 409,
Gone: 410,
"Length Required": 411,
"Precondition Failed": 412,
"Payload Too Large": 413,
"URI Too Long": 414,
"Unsupported Media Type": 415,
"Range Not Satisfiable": 416,
"Expectation Failed": 417,
"I'm a teapot": 418,
"Misdirected Request": 421,
"Unprocessable Content": 422,
Locked: 423,
"Failed Dependency": 424,
"Too Early": 425,
"Upgrade Required": 426,
"Precondition Required": 428,
"Too Many Requests": 429,
"Request Header Fields Too Large": 431,
"Unavailable For Legal Reasons": 451,
"Internal Server Error": 500,
"Not Implemented": 501,
"Bad Gateway": 502,
"Service Unavailable": 503,
"Gateway Timeout": 504,
"HTTP Version Not Supported": 505,
"Variant Also Negotiates": 506,
"Insufficient Storage": 507,
"Loop Detected": 508,
"Not Extended": 510,
"Network Authentication Required": 511
};
var encoder = new TextEncoder();
var import_typebox2 = require("@sinclair/typebox");
var import_value4 = require("@sinclair/typebox/value");
var import_compiler2 = require("@sinclair/typebox/compiler");
var import_deepmerge2 = __toESM(require("deepmerge"));
// src/cookies.ts
var import_cookie = require("cookie");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
// src/index.ts
var import_eventemitter3 = __toESM(require("eventemitter3"));
// src/error.ts
var import_value2 = require("@sinclair/typebox/value");
var import_value = require("@sinclair/typebox/value");
var env = typeof Bun !== "undefined" ? Bun.env : typeof process !== "undefined" ? process?.env : void 0;

@@ -125,4 +60,78 @@ var ERROR_CODE = Symbol("ElysiaErrorCode");

var isProduction = (env?.NODE_ENV ?? env?.ENV) === "production";
var ValidationError = class _ValidationError extends Error {
constructor(type, validator, value) {
if (typeof value === "object" && ELYSIA_RESPONSE in value)
value = value.response;
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value.Value.Errors(validator, value).First();
const customError = error2?.schema.error ? typeof error2.schema.error === "function" ? error2.schema.error(type, validator, value) : error2.schema.error : void 0;
const accessor = error2?.path?.slice(1) || "root";
let message = "";
if (customError) {
message = typeof customError === "object" ? JSON.stringify(customError) : customError + "";
} else if (isProduction) {
message = JSON.stringify({
type,
message: error2?.message
});
} else {
message = JSON.stringify(
{
type,
at: accessor,
message: error2?.message,
expected: import_value.Value.Create(
// @ts-ignore private field
validator.schema
),
found: value,
errors: [...validator.Errors(value)]
},
null,
2
);
}
super(message);
this.type = type;
this.validator = validator;
this.value = value;
this.code = "VALIDATION";
this.status = 400;
Object.setPrototypeOf(this, _ValidationError.prototype);
}
get all() {
return [...this.validator.Errors(this.value)];
}
static simplifyModel(validator) {
const model = "schema" in validator ? validator.schema : validator;
try {
return import_value.Value.Create(model);
} catch {
return model;
}
}
get model() {
return _ValidationError.simplifyModel(this.validator);
}
toResponse(headers) {
return new Response(this.message, {
status: 400,
headers: {
...headers,
"content-type": "application/json"
}
});
}
};
// src/index.ts
var import_deepmerge = __toESM(require("deepmerge"));
// src/compose.ts
var import_value2 = require("@sinclair/typebox/value");
var import_fast_querystring = require("fast-querystring");
var import_fast_decode_uri_component2 = __toESM(require("fast-decode-uri-component"));
// src/cookies.ts
var import_cookie = require("cookie");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
var Cookie = class {

@@ -236,2 +245,303 @@ constructor(name, jar, initial = {}) {

// src/compose.ts
var headersHasToJSON = new Headers().toJSON;
var KindSymbol = Symbol.for("TypeBox.Kind");
var TransformSymbol = Symbol.for("TypeBox.Transform");
// src/dynamic-handle.ts
var import_fast_querystring2 = require("fast-querystring");
// src/type-system.ts
var import_system = require("@sinclair/typebox/system");
var import_typebox = require("@sinclair/typebox");
var import_value3 = require("@sinclair/typebox/value");
var import_system2 = require("@sinclair/typebox/system");
var import_compiler = require("@sinclair/typebox/compiler");
try {
import_system.TypeSystem.Format(
"email",
(value) => /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(
value
)
);
import_system.TypeSystem.Format(
"uuid",
(value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value
)
);
import_system.TypeSystem.Format(
"date",
(value) => !Number.isNaN(new Date(value).getTime())
);
import_system.TypeSystem.Format(
"date-time",
(value) => !Number.isNaN(new Date(value).getTime())
);
} catch {
}
var t = Object.assign({}, import_typebox.Type);
var parseFileUnit = (size) => {
if (typeof size === "string")
switch (size.slice(-1)) {
case "k":
return +size.slice(0, size.length - 1) * 1024;
case "m":
return +size.slice(0, size.length - 1) * 1048576;
default:
return +size;
}
return size;
};
var validateFile = (options, value) => {
if (!(value instanceof Blob))
return false;
if (options.minSize && value.size < parseFileUnit(options.minSize))
return false;
if (options.maxSize && value.size > parseFileUnit(options.maxSize))
return false;
if (options.extension)
if (typeof options.extension === "string") {
if (!value.type.startsWith(options.extension))
return false;
} else {
for (let i = 0; i < options.extension.length; i++)
if (value.type.startsWith(options.extension[i]))
return true;
return false;
}
return true;
};
var Files = import_system.TypeSystem.Type(
"Files",
(options, value) => {
if (!Array.isArray(value))
return validateFile(options, value);
if (options.minItems && value.length < options.minItems)
return false;
if (options.maxItems && value.length > options.maxItems)
return false;
for (let i = 0; i < value.length; i++)
if (!validateFile(options, value[i]))
return false;
return true;
}
);
if (!import_typebox.FormatRegistry.Get("numeric"))
import_typebox.FormatRegistry.Set("numeric", (value) => !!value && !isNaN(+value));
if (!import_typebox.FormatRegistry.Get("boolean"))
import_typebox.FormatRegistry.Set(
"boolean",
(value) => value === "true" || value === "false"
);
if (!import_typebox.FormatRegistry.Get("ObjectString"))
import_typebox.FormatRegistry.Set("ObjectString", (value) => {
let start = value.charCodeAt(0);
if (start === 9 || start === 10 || start === 32)
start = value.trimStart().charCodeAt(0);
if (start !== 123 && start !== 91)
return false;
try {
JSON.parse(value);
return true;
} catch {
return false;
}
});
var ElysiaType = {
Numeric: (property) => {
const schema = import_typebox.Type.Number(property);
return t.Transform(
t.Union(
[
t.String({
format: "numeric",
default: 0
}),
t.Number(property)
],
property
)
).Decode((value) => {
const number = +value;
if (isNaN(number))
return value;
if (property && !import_value3.Value.Check(schema, number))
throw new ValidationError("property", schema, number);
return number;
}).Encode((value) => value);
},
BooleanString: (property) => {
const schema = import_typebox.Type.Boolean(property);
return t.Transform(
t.Union(
[
t.String({
format: "boolean",
default: false
}),
t.Boolean(property)
],
property
)
).Decode((value) => {
if (typeof value === "string")
return value === "true";
if (property && !import_value3.Value.Check(schema, value))
throw new ValidationError("property", schema, value);
return value;
}).Encode((value) => value);
},
ObjectString: (properties, options) => t.Transform(
t.Union(
[
t.String({
format: "ObjectString",
default: ""
}),
t.Object(properties, options)
],
options
)
).Decode((value) => {
if (typeof value === "string")
try {
return JSON.parse(value);
} catch {
return value;
}
return value;
}).Encode((value) => JSON.stringify(value)),
File: import_system.TypeSystem.Type("File", validateFile),
Files: (options = {}) => t.Transform(t.Union([Files(options)])).Decode((value) => {
if (Array.isArray(value))
return value;
return [value];
}).Encode((value) => value),
Nullable: (schema) => t.Union([t.Null(), schema]),
/**
* Allow Optional, Nullable and Undefined
*/
MaybeEmpty: (schema) => t.Union([t.Null(), t.Undefined(), schema]),
Cookie: (properties, options) => t.Object(properties, options)
};
t.BooleanString = ElysiaType.BooleanString;
t.ObjectString = ElysiaType.ObjectString;
t.Numeric = ElysiaType.Numeric;
t.File = (arg = {}) => ElysiaType.File({
default: "File",
...arg,
extension: arg?.type,
type: "string",
format: "binary"
});
t.Files = (arg = {}) => ElysiaType.Files({
...arg,
elysiaMeta: "Files",
default: "Files",
extension: arg?.type,
type: "array",
items: {
...arg,
default: "Files",
type: "string",
format: "binary"
}
});
t.Nullable = (schema) => ElysiaType.Nullable(schema);
t.MaybeEmpty = ElysiaType.MaybeEmpty;
t.Cookie = ElysiaType.Cookie;
// src/utils.ts
var primitiveHooks = [
"start",
"request",
"parse",
"transform",
"resolve",
"beforeHandle",
"afterHandle",
"onResponse",
"mapResponse",
"trace",
"error",
"stop",
"body",
"headers",
"params",
"query",
"response",
"type",
"detail"
];
var primitiveHookMap = primitiveHooks.reduce(
(acc, x2) => (acc[x2] = true, acc),
{}
);
var isBun = typeof Bun !== "undefined";
var hasHash = isBun && typeof Bun.hash === "function";
var StatusMap = {
Continue: 100,
"Switching Protocols": 101,
Processing: 102,
"Early Hints": 103,
OK: 200,
Created: 201,
Accepted: 202,
"Non-Authoritative Information": 203,
"No Content": 204,
"Reset Content": 205,
"Partial Content": 206,
"Multi-Status": 207,
"Already Reported": 208,
"Multiple Choices": 300,
"Moved Permanently": 301,
Found: 302,
"See Other": 303,
"Not Modified": 304,
"Temporary Redirect": 307,
"Permanent Redirect": 308,
"Bad Request": 400,
Unauthorized: 401,
"Payment Required": 402,
Forbidden: 403,
"Not Found": 404,
"Method Not Allowed": 405,
"Not Acceptable": 406,
"Proxy Authentication Required": 407,
"Request Timeout": 408,
Conflict: 409,
Gone: 410,
"Length Required": 411,
"Precondition Failed": 412,
"Payload Too Large": 413,
"URI Too Long": 414,
"Unsupported Media Type": 415,
"Range Not Satisfiable": 416,
"Expectation Failed": 417,
"I'm a teapot": 418,
"Misdirected Request": 421,
"Unprocessable Content": 422,
Locked: 423,
"Failed Dependency": 424,
"Too Early": 425,
"Upgrade Required": 426,
"Precondition Required": 428,
"Too Many Requests": 429,
"Request Header Fields Too Large": 431,
"Unavailable For Legal Reasons": 451,
"Internal Server Error": 500,
"Not Implemented": 501,
"Bad Gateway": 502,
"Service Unavailable": 503,
"Gateway Timeout": 504,
"HTTP Version Not Supported": 505,
"Variant Also Negotiates": 506,
"Insufficient Storage": 507,
"Loop Detected": 508,
"Not Extended": 510,
"Network Authentication Required": 511
};
var encoder = new TextEncoder();
// src/handler.ts

@@ -807,7 +1117,7 @@ var hasHeaderShorthand = "toJSON" in new Headers();

};
var errorToResponse = (error, set) => new Response(
var errorToResponse = (error2, set) => new Response(
JSON.stringify({
name: error?.name,
message: error?.message,
cause: error?.cause
name: error2?.name,
message: error2?.message,
cause: error2?.cause
}),

@@ -814,0 +1124,0 @@ {

import 'bun';
import 'memoirist';
export { Static, TSchema } from '@sinclair/typebox';
export { Q as AfterHandler, a0 as BodyHandler, ad as Checksum, C as ComposedHandler, aE as Context, f as Cookie, d as CookieOptions, D as DefinitionBase, E as Elysia, n as ElysiaConfig, a3 as ErrorHandler, A as HTTPMethod, H as Handler, B as InputSchema, a7 as InternalRoute, I as InternalServerError, m as InvalidCookieSignature, y as LifeCycleEvent, L as LifeCycleStore, a8 as ListenCallback, a6 as LocalHook, o as MaybePromise, F as MergeSchema, N as NotFoundError, K as OptionalHandler, P as ParseError, aF as PreContext, a1 as PreHandler, t as RouteBase, v as RouteSchema, S as SchemaValidator, s as SingletonBase, Z as TraceEvent, b as TraceHandler, _ as TraceProcess, T as TraceReporter, c as TraceStream, w as UnwrapRoute, U as UnwrapSchema, V as ValidationError, X as VoidHandler, E as default, l as error, ar as getResponseSchemaValidator, aq as getSchemaValidator, b4 as mapCompactResponse, b3 as mapEarlyResponse, b2 as mapResponse, al as mergeDeep, ap as mergeHook, an as mergeObjectArray, aG as t } from './dynamic-handle-O2HN1QLh.js';
export { K as AfterHandler, $ as BodyHandler, ac as Checksum, C as ComposedHandler, aD as Context, e as Cookie, c as CookieOptions, D as DefinitionBase, E as Elysia, m as ElysiaConfig, a2 as ErrorHandler, z as HTTPMethod, H as Handler, A as InputSchema, a6 as InternalRoute, I as InternalServerError, l as InvalidCookieSignature, x as LifeCycleEvent, L as LifeCycleStore, a7 as ListenCallback, a5 as LocalHook, n as MaybePromise, B as MergeSchema, N as NotFoundError, J as OptionalHandler, P as ParseError, aE as PreContext, a0 as PreHandler, s as RouteBase, u as RouteSchema, S as SchemaValidator, r as SingletonBase, Y as TraceEvent, T as TraceHandler, Z as TraceProcess, a as TraceReporter, b as TraceStream, v as UnwrapRoute, U as UnwrapSchema, V as ValidationError, W as VoidHandler, E as default, k as error, ap as getResponseSchemaValidator, ao as getSchemaValidator, aR as mapCompactResponse, aQ as mapEarlyResponse, aP as mapResponse, an as mergeHook, al as mergeObjectArray, aF as t } from './dynamic-handle-BOErSqze.js';
import '@sinclair/typebox/compiler';

@@ -6,0 +6,0 @@ import 'openapi-types';

@@ -1,2 +0,2 @@

export { a as Sucrose, aL as bracketPairRange, aM as bracketPairRangeReverse, aR as extractMainParameter, aQ as findAlias, aO as findParameterReference, aP as findTraceParameterReference, aS as inferBodyReference, aV as inferTraceBodyReference, aT as removeDefaultParameter, aN as retrieveRootParamters, aK as separateFunction, aW as sucrose, aX as sucroseTrace, aU as validateInferencedQueries } from './dynamic-handle-O2HN1QLh.js';
import { L as LifeCycleStore, H as Handler, T as TraceHandler } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -9,1 +9,104 @@ import 'memoirist';

import '@sinclair/typebox/system';
declare namespace Sucrose {
interface Inference {
queries: string[];
unknownQueries: boolean;
query: boolean;
headers: boolean;
body: boolean;
cookie: boolean;
set: boolean;
}
interface LifeCycle extends Partial<LifeCycleStore> {
handler?: Handler;
}
interface TraceInference {
request: boolean;
parse: boolean;
transform: boolean;
handle: boolean;
beforeHandle: boolean;
afterHandle: boolean;
error: boolean;
context: boolean;
store: boolean;
set: boolean;
}
}
/**
* Separate stringified function body and paramter
*
* @example
* ```typescript
* separateFunction('async ({ hello }) => { return hello }') // => ['({ hello })', '{ return hello }']
* ```
*/
declare const separateFunction: (code: string) => [string, string];
/**
* Get range between bracket pair
*
* @example
* ```typescript
* bracketPairRange('hello: { world: { a } }, elysia') // [6, 20]
* ```
*/
declare const bracketPairRange: (parameter: string) => [number, number];
/**
* Similar to `bracketPairRange` but in reverse order
* Get range between bracket pair from end to beginning
*
* @example
* ```typescript
* bracketPairRange('hello: { world: { a } }, elysia') // [6, 20]
* ```
*/
declare const bracketPairRangeReverse: (parameter: string) => [number, number];
/**
* Retrieve only root paramters of a function
*
* @example
* ```typescript
* retrieveRootParameters('({ hello: { world: { a } }, elysia })') // => 'hello elysia'
* ```
*/
declare const retrieveRootParamters: (parameter: string) => string;
/**
* Find inference from parameter
*
* @param parameter stringified parameter
*/
declare const findParameterReference: (parameter: string, inference: Sucrose.Inference) => string;
/**
* Find inference from parameter
*
* @param parameter stringified parameter
*/
declare const findTraceParameterReference: (parameter: string, inference: Sucrose.TraceInference) => string;
/**
* Find alias of variable from function body
*
* @example
* ```typescript
* findAlias('body', '{ const a = body, b = body }') // => ['a', 'b']
* ```
*/
declare const findAlias: (type: string, body: string, depth?: number) => string[];
declare const extractMainParameter: (parameter: string) => string | undefined;
/**
* Analyze if context is mentioned in body
*/
declare const inferBodyReference: (code: string, aliases: string[], inference: Sucrose.Inference) => string[];
declare const removeDefaultParameter: (parameter: string) => string;
declare const validateInferencedQueries: (queries: string[]) => boolean;
/**
* Analyze if context is mentioned in body
*/
declare const inferTraceBodyReference: (code: string, aliases: string[], inference: Sucrose.TraceInference) => string[];
declare const sucrose: (lifeCycle: Sucrose.LifeCycle, inference?: Sucrose.Inference) => Sucrose.Inference;
/**
* Analyze if context is mentioned in body in a trace
*/
declare const sucroseTrace: (traces: TraceHandler[], inference?: Sucrose.TraceInference) => Sucrose.TraceInference;
export { Sucrose, bracketPairRange, bracketPairRangeReverse, extractMainParameter, findAlias, findParameterReference, findTraceParameterReference, inferBodyReference, inferTraceBodyReference, removeDefaultParameter, retrieveRootParamters, separateFunction, sucrose, sucroseTrace, validateInferencedQueries };

@@ -1,2 +0,2 @@

import { T as TraceReporter, b as TraceHandler, c as TraceStream } from './dynamic-handle-O2HN1QLh.js';
import { a as TraceReporter, T as TraceHandler, b as TraceStream } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

import '@sinclair/typebox';
export { TypeCheck, TypeCompiler } from '@sinclair/typebox/compiler';
export { aI as ElysiaType, aH as ElysiaTypeOptions, aJ as TCookie, aG as t } from './dynamic-handle-O2HN1QLh.js';
export { aH as ElysiaType, aG as ElysiaTypeOptions, aI as TCookie, aF as t } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -5,0 +5,0 @@ export { TypeSystem, TypeSystemDuplicateFormat, TypeSystemDuplicateTypeKind, TypeSystemPolicy } from '@sinclair/typebox/system';

@@ -45,12 +45,17 @@ "use strict";

var import_typebox2 = require("@sinclair/typebox");
var import_value3 = require("@sinclair/typebox/value");
var import_value4 = require("@sinclair/typebox/value");
// src/error.ts
var import_value2 = require("@sinclair/typebox/value");
var import_value3 = require("@sinclair/typebox/value");
// src/utils.ts
var import_typebox = require("@sinclair/typebox");
var import_value = require("@sinclair/typebox/value");
var import_value2 = require("@sinclair/typebox/value");
var import_compiler = require("@sinclair/typebox/compiler");
var import_deepmerge2 = __toESM(require("deepmerge"));
// src/index.ts
var import_eventemitter3 = __toESM(require("eventemitter3"));
var import_deepmerge = __toESM(require("deepmerge"));
// src/handler.ts

@@ -66,3 +71,39 @@ var import_cookie2 = require("cookie");

// src/compose.ts
var import_value = require("@sinclair/typebox/value");
var import_fast_querystring = require("fast-querystring");
var import_fast_decode_uri_component2 = __toESM(require("fast-decode-uri-component"));
var headersHasToJSON = new Headers().toJSON;
var KindSymbol = Symbol.for("TypeBox.Kind");
var TransformSymbol = Symbol.for("TypeBox.Transform");
// src/dynamic-handle.ts
var import_fast_querystring2 = require("fast-querystring");
// src/utils.ts
var primitiveHooks = [
"start",
"request",
"parse",
"transform",
"resolve",
"beforeHandle",
"afterHandle",
"onResponse",
"mapResponse",
"trace",
"error",
"stop",
"body",
"headers",
"params",
"query",
"response",
"type",
"detail"
];
var primitiveHookMap = primitiveHooks.reduce(
(acc, x2) => (acc[x2] = true, acc),
{}
);
var isBun = typeof Bun !== "undefined";

@@ -81,5 +122,5 @@ var hasHash = isBun && typeof Bun.hash === "function";

value = value.response;
const error = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value2.Value.Errors(validator, value).First();
const customError = error?.schema.error ? typeof error.schema.error === "function" ? error.schema.error(type, validator, value) : error.schema.error : void 0;
const accessor = error?.path?.slice(1) || "root";
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value3.Value.Errors(validator, value).First();
const customError = error2?.schema.error ? typeof error2.schema.error === "function" ? error2.schema.error(type, validator, value) : error2.schema.error : void 0;
const accessor = error2?.path?.slice(1) || "root";
let message = "";

@@ -91,3 +132,3 @@ if (customError) {

type,
message: error?.message
message: error2?.message
});

@@ -99,4 +140,4 @@ } else {

at: accessor,
message: error?.message,
expected: import_value2.Value.Create(
message: error2?.message,
expected: import_value3.Value.Create(
// @ts-ignore private field

@@ -126,3 +167,3 @@ validator.schema

try {
return import_value2.Value.Create(model);
return import_value3.Value.Create(model);
} catch {

@@ -258,3 +299,3 @@ return model;

return value;
if (property && !import_value3.Value.Check(schema, number))
if (property && !import_value4.Value.Check(schema, number))
throw new ValidationError("property", schema, number);

@@ -280,3 +321,3 @@ return number;

return value === "true";
if (property && !import_value3.Value.Check(schema, value))
if (property && !import_value4.Value.Check(schema, value))
throw new ValidationError("property", schema, value);

@@ -283,0 +324,0 @@ return value;

@@ -1,2 +0,2 @@

export { a9 as AddPrefix, aa as AddPrefixCapitalize, ab as AddSuffix, ac as AddSuffixCapitalize, Q as AfterHandler, ae as BaseMacro, a0 as BodyHandler, ad as Checksum, ai as ComposeElysiaResponse, C as ComposedHandler, z as ContentType, ah as CreateEden, D as DefinitionBase, n as ElysiaConfig, a3 as ErrorHandler, G as GetPathParameter, a2 as GracefulHandler, A as HTTPMethod, H as Handler, J as InlineHandler, B as InputSchema, a7 as InternalRoute, a4 as Isolate, y as LifeCycleEvent, L as LifeCycleStore, a8 as ListenCallback, a6 as LocalHook, ag as MacroManager, af as MacroToProperty, W as MapResponse, M as MaybeArray, o as MaybePromise, aj as MergeElysiaInstances, F as MergeSchema, u as MetadataBase, a5 as NoInfer, O as ObjectValues, K as OptionalHandler, a1 as PreHandler, q as Prettify, r as Prettify2, R as Reconcile, t as RouteBase, v as RouteSchema, S as SchemaValidator, s as SingletonBase, Z as TraceEvent, b as TraceHandler, $ as TraceListener, _ as TraceProcess, T as TraceReporter, c as TraceStream, Y as TransformHandler, x as UnwrapGroupGuardRoute, w as UnwrapRoute, U as UnwrapSchema, X as VoidHandler } from './dynamic-handle-O2HN1QLh.js';
export { a8 as AddPrefix, a9 as AddPrefixCapitalize, aa as AddSuffix, ab as AddSuffixCapitalize, K as AfterHandler, ad as BaseMacro, $ as BodyHandler, ac as Checksum, ah as ComposeElysiaResponse, C as ComposedHandler, y as ContentType, ag as CreateEden, D as DefinitionBase, m as ElysiaConfig, a2 as ErrorHandler, G as GetPathParameter, a1 as GracefulHandler, z as HTTPMethod, H as Handler, F as InlineHandler, A as InputSchema, a6 as InternalRoute, a3 as Isolate, x as LifeCycleEvent, L as LifeCycleStore, a7 as ListenCallback, a5 as LocalHook, af as MacroManager, ae as MacroToProperty, Q as MapResponse, M as MaybeArray, n as MaybePromise, ai as MergeElysiaInstances, B as MergeSchema, t as MetadataBase, a4 as NoInfer, O as ObjectValues, J as OptionalHandler, a0 as PreHandler, o as Prettify, q as Prettify2, R as Reconcile, s as RouteBase, u as RouteSchema, S as SchemaValidator, r as SingletonBase, Y as TraceEvent, T as TraceHandler, _ as TraceListener, Z as TraceProcess, a as TraceReporter, b as TraceStream, X as TransformHandler, w as UnwrapGroupGuardRoute, v as UnwrapRoute, U as UnwrapSchema, W as VoidHandler } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import '@sinclair/typebox';

import '@sinclair/typebox';
import '@sinclair/typebox/compiler';
export { ay as HTTPStatusName, ax as StatusMap, av as asGlobal, au as asGlobalHook, as as checksum, aC as createMacroManager, aw as filterGlobalHook, ar as getResponseSchemaValidator, aq as getSchemaValidator, aD as isNumericString, am as mergeCookie, al as mergeDeep, ap as mergeHook, at as mergeLifeCycle, an as mergeObjectArray, ao as primitiveHooks, ak as replaceUrlPath, az as signCookie, aB as traceBackMacro, aA as unsignCookie } from './dynamic-handle-O2HN1QLh.js';
export { ax as HTTPStatusName, aw as StatusMap, au as asGlobal, at as asGlobalHook, aq as checksum, aB as createMacroManager, av as filterGlobalHook, ar as getCookieValidator, ap as getResponseSchemaValidator, ao as getSchemaValidator, aC as isNumericString, ak as mergeCookie, an as mergeHook, as as mergeLifeCycle, al as mergeObjectArray, am as primitiveHooks, aj as replaceUrlPath, ay as signCookie, aA as traceBackMacro, az as unsignCookie } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -5,0 +5,0 @@ import 'memoirist';

@@ -39,2 +39,3 @@ "use strict";

filterGlobalHook: () => filterGlobalHook,
getCookieValidator: () => getCookieValidator,
getResponseSchemaValidator: () => getResponseSchemaValidator,

@@ -44,3 +45,2 @@ getSchemaValidator: () => getSchemaValidator,

mergeCookie: () => mergeCookie,
mergeDeep: () => mergeDeep,
mergeHook: () => mergeHook,

@@ -56,13 +56,10 @@ mergeLifeCycle: () => mergeLifeCycle,

module.exports = __toCommonJS(utils_exports);
var import_typebox = require("@sinclair/typebox");
var import_value2 = require("@sinclair/typebox/value");
var import_compiler = require("@sinclair/typebox/compiler");
var import_typebox2 = require("@sinclair/typebox");
var import_value4 = require("@sinclair/typebox/value");
var import_compiler2 = require("@sinclair/typebox/compiler");
var import_deepmerge2 = __toESM(require("deepmerge"));
// src/handler.ts
var import_cookie2 = require("cookie");
// src/index.ts
var import_eventemitter3 = __toESM(require("eventemitter3"));
// src/cookies.ts
var import_cookie = require("cookie");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
// src/error.ts

@@ -74,4 +71,78 @@ var import_value = require("@sinclair/typebox/value");

var isProduction = (env?.NODE_ENV ?? env?.ENV) === "production";
var ValidationError = class _ValidationError extends Error {
constructor(type, validator, value) {
if (typeof value === "object" && ELYSIA_RESPONSE in value)
value = value.response;
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value.Value.Errors(validator, value).First();
const customError = error2?.schema.error ? typeof error2.schema.error === "function" ? error2.schema.error(type, validator, value) : error2.schema.error : void 0;
const accessor = error2?.path?.slice(1) || "root";
let message = "";
if (customError) {
message = typeof customError === "object" ? JSON.stringify(customError) : customError + "";
} else if (isProduction) {
message = JSON.stringify({
type,
message: error2?.message
});
} else {
message = JSON.stringify(
{
type,
at: accessor,
message: error2?.message,
expected: import_value.Value.Create(
// @ts-ignore private field
validator.schema
),
found: value,
errors: [...validator.Errors(value)]
},
null,
2
);
}
super(message);
this.type = type;
this.validator = validator;
this.value = value;
this.code = "VALIDATION";
this.status = 400;
Object.setPrototypeOf(this, _ValidationError.prototype);
}
get all() {
return [...this.validator.Errors(this.value)];
}
static simplifyModel(validator) {
const model = "schema" in validator ? validator.schema : validator;
try {
return import_value.Value.Create(model);
} catch {
return model;
}
}
get model() {
return _ValidationError.simplifyModel(this.validator);
}
toResponse(headers) {
return new Response(this.message, {
status: 400,
headers: {
...headers,
"content-type": "application/json"
}
});
}
};
// src/index.ts
var import_deepmerge = __toESM(require("deepmerge"));
// src/handler.ts
var import_cookie2 = require("cookie");
// src/cookies.ts
var import_cookie = require("cookie");
var import_fast_decode_uri_component = __toESM(require("fast-decode-uri-component"));
// src/handler.ts
var hasHeaderShorthand = "toJSON" in new Headers();

@@ -84,4 +155,215 @@ var isNotEmpty = (obj) => {

// src/compose.ts
var import_value2 = require("@sinclair/typebox/value");
var import_fast_querystring = require("fast-querystring");
var import_fast_decode_uri_component2 = __toESM(require("fast-decode-uri-component"));
var headersHasToJSON = new Headers().toJSON;
var KindSymbol = Symbol.for("TypeBox.Kind");
var TransformSymbol = Symbol.for("TypeBox.Transform");
// src/dynamic-handle.ts
var import_fast_querystring2 = require("fast-querystring");
// src/type-system.ts
var import_system = require("@sinclair/typebox/system");
var import_typebox = require("@sinclair/typebox");
var import_value3 = require("@sinclair/typebox/value");
var import_system2 = require("@sinclair/typebox/system");
var import_compiler = require("@sinclair/typebox/compiler");
try {
import_system.TypeSystem.Format(
"email",
(value) => /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(
value
)
);
import_system.TypeSystem.Format(
"uuid",
(value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value
)
);
import_system.TypeSystem.Format(
"date",
(value) => !Number.isNaN(new Date(value).getTime())
);
import_system.TypeSystem.Format(
"date-time",
(value) => !Number.isNaN(new Date(value).getTime())
);
} catch {
}
var t = Object.assign({}, import_typebox.Type);
var parseFileUnit = (size) => {
if (typeof size === "string")
switch (size.slice(-1)) {
case "k":
return +size.slice(0, size.length - 1) * 1024;
case "m":
return +size.slice(0, size.length - 1) * 1048576;
default:
return +size;
}
return size;
};
var validateFile = (options, value) => {
if (!(value instanceof Blob))
return false;
if (options.minSize && value.size < parseFileUnit(options.minSize))
return false;
if (options.maxSize && value.size > parseFileUnit(options.maxSize))
return false;
if (options.extension)
if (typeof options.extension === "string") {
if (!value.type.startsWith(options.extension))
return false;
} else {
for (let i = 0; i < options.extension.length; i++)
if (value.type.startsWith(options.extension[i]))
return true;
return false;
}
return true;
};
var Files = import_system.TypeSystem.Type(
"Files",
(options, value) => {
if (!Array.isArray(value))
return validateFile(options, value);
if (options.minItems && value.length < options.minItems)
return false;
if (options.maxItems && value.length > options.maxItems)
return false;
for (let i = 0; i < value.length; i++)
if (!validateFile(options, value[i]))
return false;
return true;
}
);
if (!import_typebox.FormatRegistry.Get("numeric"))
import_typebox.FormatRegistry.Set("numeric", (value) => !!value && !isNaN(+value));
if (!import_typebox.FormatRegistry.Get("boolean"))
import_typebox.FormatRegistry.Set(
"boolean",
(value) => value === "true" || value === "false"
);
if (!import_typebox.FormatRegistry.Get("ObjectString"))
import_typebox.FormatRegistry.Set("ObjectString", (value) => {
let start = value.charCodeAt(0);
if (start === 9 || start === 10 || start === 32)
start = value.trimStart().charCodeAt(0);
if (start !== 123 && start !== 91)
return false;
try {
JSON.parse(value);
return true;
} catch {
return false;
}
});
var ElysiaType = {
Numeric: (property) => {
const schema = import_typebox.Type.Number(property);
return t.Transform(
t.Union(
[
t.String({
format: "numeric",
default: 0
}),
t.Number(property)
],
property
)
).Decode((value) => {
const number = +value;
if (isNaN(number))
return value;
if (property && !import_value3.Value.Check(schema, number))
throw new ValidationError("property", schema, number);
return number;
}).Encode((value) => value);
},
BooleanString: (property) => {
const schema = import_typebox.Type.Boolean(property);
return t.Transform(
t.Union(
[
t.String({
format: "boolean",
default: false
}),
t.Boolean(property)
],
property
)
).Decode((value) => {
if (typeof value === "string")
return value === "true";
if (property && !import_value3.Value.Check(schema, value))
throw new ValidationError("property", schema, value);
return value;
}).Encode((value) => value);
},
ObjectString: (properties, options) => t.Transform(
t.Union(
[
t.String({
format: "ObjectString",
default: ""
}),
t.Object(properties, options)
],
options
)
).Decode((value) => {
if (typeof value === "string")
try {
return JSON.parse(value);
} catch {
return value;
}
return value;
}).Encode((value) => JSON.stringify(value)),
File: import_system.TypeSystem.Type("File", validateFile),
Files: (options = {}) => t.Transform(t.Union([Files(options)])).Decode((value) => {
if (Array.isArray(value))
return value;
return [value];
}).Encode((value) => value),
Nullable: (schema) => t.Union([t.Null(), schema]),
/**
* Allow Optional, Nullable and Undefined
*/
MaybeEmpty: (schema) => t.Union([t.Null(), t.Undefined(), schema]),
Cookie: (properties, options) => t.Object(properties, options)
};
t.BooleanString = ElysiaType.BooleanString;
t.ObjectString = ElysiaType.ObjectString;
t.Numeric = ElysiaType.Numeric;
t.File = (arg = {}) => ElysiaType.File({
default: "File",
...arg,
extension: arg?.type,
type: "string",
format: "binary"
});
t.Files = (arg = {}) => ElysiaType.Files({
...arg,
elysiaMeta: "Files",
default: "Files",
extension: arg?.type,
type: "array",
items: {
...arg,
default: "Files",
type: "string",
format: "binary"
}
});
t.Nullable = (schema) => ElysiaType.Nullable(schema);
t.MaybeEmpty = ElysiaType.MaybeEmpty;
t.Cookie = ElysiaType.Cookie;
// src/utils.ts
var isObject = (item) => item && typeof item === "object" && !Array.isArray(item);
var replaceUrlPath = (url, pathname) => {

@@ -92,49 +374,24 @@ const urlObject = new URL(url);

};
var isClass = (v) => typeof v === "function" && /^\s*class\s+/.test(v.toString()) || // Handle import * as Sentry from '@sentry/bun'
// This also handle [object Date], [object Array]
// and FFI value like [object Prisma]
v.toString().startsWith("[object ") || // If object prototype is not pure, then probably a class-like object
isNotEmpty(Object.getPrototypeOf(v));
var mergeDeep = (target, source, {
skipKeys
} = {}) => {
if (isObject(target) && isObject(source))
for (const [key, value] of Object.entries(source)) {
if (skipKeys?.includes(key))
continue;
if (!isObject(value)) {
target[key] = value;
continue;
}
if (!(key in target)) {
target[key] = value;
continue;
}
if (isClass(value)) {
target[key] = value;
continue;
}
target[key] = mergeDeep(
target[key],
value
);
}
return target;
var mergeCookie = (a, b) => {
const { properties: _, ...target } = a ?? {};
const { properties: __, ...source } = b ?? {};
return (0, import_deepmerge2.default)(target, source);
};
var mergeCookie = (target, source) => mergeDeep(target, source, {
skipKeys: ["properties"]
});
var mergeObjectArray = (a, b) => {
var mergeObjectArray = (a = [], b = []) => {
if (!a)
return [];
const array = [...Array.isArray(a) ? a : [a]];
const array = [];
const checksums = [];
for (const item of array) {
if (item.$elysiaChecksum)
checksums.push(item.$elysiaChecksum);
if (!Array.isArray(a))
a = [a];
if (!Array.isArray(b))
b = [b];
for (const item2 of a) {
array.push(item2);
if (item2.$elysiaChecksum)
checksums.push(item2.$elysiaChecksum);
}
for (const item of Array.isArray(b) ? b : [b]) {
if (!checksums.includes(item?.$elysiaChecksum)) {
array.push(item);
}
for (const item2 of b) {
if (!checksums.includes(item2?.$elysiaChecksum))
array.push(item2);
}

@@ -164,2 +421,6 @@ return array;

];
var primitiveHookMap = primitiveHooks.reduce(
(acc, x2) => (acc[x2] = true, acc),
{}
);
var mergeHook = (a, b) => {

@@ -181,3 +442,3 @@ return {

type: a?.type || b?.type,
detail: mergeDeep(
detail: (0, import_deepmerge2.default)(
// @ts-ignore

@@ -188,22 +449,10 @@ b?.detail ?? {},

),
parse: mergeObjectArray(a?.parse ?? [], b?.parse ?? []),
transform: mergeObjectArray(a?.transform ?? [], b?.transform ?? []),
beforeHandle: mergeObjectArray(
a?.beforeHandle ?? [],
b?.beforeHandle ?? []
),
afterHandle: mergeObjectArray(
a?.afterHandle ?? [],
b?.afterHandle ?? []
),
onResponse: mergeObjectArray(
a?.onResponse ?? [],
b?.onResponse ?? []
),
mapResponse: mergeObjectArray(
a?.mapResponse ?? [],
b?.mapResponse ?? []
),
trace: mergeObjectArray(a?.trace ?? [], b?.trace ?? []),
error: mergeObjectArray(a?.error ?? [], b?.error ?? [])
parse: mergeObjectArray(a?.parse, b?.parse),
transform: mergeObjectArray(a?.transform, b?.transform),
beforeHandle: mergeObjectArray(a?.beforeHandle, b?.beforeHandle),
afterHandle: mergeObjectArray(a?.afterHandle, b?.afterHandle),
onResponse: mergeObjectArray(a?.onResponse, b?.onResponse),
mapResponse: mergeObjectArray(a?.mapResponse, b?.mapResponse),
trace: mergeObjectArray(a?.trace, b?.trace),
error: mergeObjectArray(a?.error, b?.error)
};

@@ -230,7 +479,7 @@ };

code: "",
Check: (value) => import_value2.Value.Check(schema, value),
Errors: (value) => import_value2.Value.Errors(schema, value),
Check: (value) => import_value4.Value.Check(schema, value),
Errors: (value) => import_value4.Value.Errors(schema, value),
Code: () => ""
};
return import_compiler.TypeCompiler.Compile(schema, Object.values(models));
return import_compiler2.TypeCompiler.Compile(schema, Object.values(models));
};

@@ -255,9 +504,9 @@ var getResponseSchemaValidator = (s, {

code: "",
Check: (value) => import_value2.Value.Check(schema, value),
Errors: (value) => import_value2.Value.Errors(schema, value),
Check: (value) => import_value4.Value.Check(schema, value),
Errors: (value) => import_value4.Value.Errors(schema, value),
Code: () => ""
};
return import_compiler.TypeCompiler.Compile(schema, references);
return import_compiler2.TypeCompiler.Compile(schema, references);
};
if (import_typebox.Kind in maybeSchemaOrRecord) {
if (import_typebox2.Kind in maybeSchemaOrRecord) {
if ("additionalProperties" in maybeSchemaOrRecord === false)

@@ -276,3 +525,3 @@ maybeSchemaOrRecord.additionalProperties = additionalProperties;

schema.type === "object" && "additionalProperties" in schema === false;
record[+status] = import_typebox.Kind in schema ? compile(schema, Object.values(models)) : schema;
record[+status] = import_typebox2.Kind in schema ? compile(schema, Object.values(models)) : schema;
}

@@ -283,3 +532,3 @@ return void 0;

maybeNameOrSchema.additionalProperties = additionalProperties;
record[+status] = import_typebox.Kind in maybeNameOrSchema ? compile(maybeNameOrSchema, Object.values(models)) : maybeNameOrSchema;
record[+status] = import_typebox2.Kind in maybeNameOrSchema ? compile(maybeNameOrSchema, Object.values(models)) : maybeNameOrSchema;
});

@@ -298,6 +547,44 @@ return record;

};
var getCookieValidator = ({
validator,
defaultConfig = {},
config,
dynamic,
models
}) => {
let cookieValidator = getSchemaValidator(validator, {
dynamic,
models,
additionalProperties: true
});
if (isNotEmpty(defaultConfig)) {
if (cookieValidator) {
cookieValidator.schema = mergeCookie(
// @ts-expect-error private
cookieValidator.schema,
config
);
} else {
cookieValidator = getSchemaValidator(t.Cookie({}, defaultConfig), {
dynamic,
models,
additionalProperties: true
});
}
}
return cookieValidator;
};
var mergeLifeCycle = (a, b, checksum2) => {
const injectChecksum = (x2) => {
if (checksum2 && !x2.$elysiaChecksum)
x2.$elysiaChecksum = checksum2;
if (!x2)
return;
if (!Array.isArray(x2)) {
if (checksum2 && !x2.$elysiaChecksum)
item.$elysiaChecksum = checksum2;
return x2;
}
for (const item2 of x2) {
if (checksum2 && !item2.$elysiaChecksum)
item2.$elysiaChecksum = checksum2;
}
return x2;

@@ -308,43 +595,26 @@ };

...b,
start: mergeObjectArray(
a.start,
("start" in b ? b.start ?? [] : []).map(injectChecksum)
),
request: mergeObjectArray(
a.request,
("request" in b ? b.request ?? [] : []).map(injectChecksum)
),
parse: mergeObjectArray(
a.parse,
"parse" in b ? b?.parse ?? [] : []
).map(injectChecksum),
transform: mergeObjectArray(
a.transform,
(b?.transform ?? []).map(injectChecksum)
),
start: mergeObjectArray(a.start, injectChecksum(b?.start)),
request: mergeObjectArray(a.request, injectChecksum(b?.request)),
parse: mergeObjectArray(a.parse, injectChecksum(b?.parse)),
transform: mergeObjectArray(a.transform, injectChecksum(b?.transform)),
beforeHandle: mergeObjectArray(
a.beforeHandle,
(b?.beforeHandle ?? []).map(injectChecksum)
injectChecksum(b?.beforeHandle)
),
afterHandle: mergeObjectArray(
a.afterHandle,
(b?.afterHandle ?? []).map(injectChecksum)
injectChecksum(b?.afterHandle)
),
mapResponse: mergeObjectArray(
a.mapResponse,
(b?.mapResponse ?? []).map(injectChecksum)
injectChecksum(b?.mapResponse)
),
onResponse: mergeObjectArray(
a.onResponse,
(b?.onResponse ?? []).map(injectChecksum)
injectChecksum(b?.onResponse)
),
// Already merged on Elysia._use, also logic is more complicated, can't directly merge
trace: a.trace,
error: mergeObjectArray(
a.error,
(b?.error ?? []).map(injectChecksum)
),
stop: mergeObjectArray(
a.stop,
("stop" in b ? b.stop ?? [] : []).map(injectChecksum)
)
error: mergeObjectArray(a.error, injectChecksum(b?.error)),
stop: mergeObjectArray(a.stop, injectChecksum(b?.stop))
};

@@ -377,11 +647,16 @@ };

}
if (!Array.isArray(fn))
fn = [fn];
return fn.map((x2) => {
if (!Array.isArray(fn)) {
if (inject)
fn.$elysiaHookType = "global";
else
fn.$elysiaHookType = void 0;
return fn;
}
for (const x2 of fn) {
if (inject)
x2.$elysiaHookType = "global";
else
x2.$elysiaHookType = void 0;
return x2;
});
}
return fn;
};

@@ -394,6 +669,12 @@ var filterGlobal = (fn) => {

}
return fn.filter(
// @ts-expect-error
(x2) => x2.$elysiaHookType === "global" && x2.$elysiaScoped !== true
);
const array = [];
if (!Array.isArray(fn)) {
if (fn.$elysiaHookType === "global" && fn.$elysiaScoped !== true)
return fn;
return [];
}
for (const x2 of fn)
if (x2.$elysiaHookType === "global" && x2.$elysiaScoped !== true)
array.push(x2);
return array;
};

@@ -502,5 +783,3 @@ var filterGlobalHook = (hook) => {

);
const hmacArray = Array.from(new Uint8Array(hmacBuffer));
const digest = btoa(String.fromCharCode(...hmacArray));
return `${val}.${removeTrailingEquals(digest)}`;
return val + "." + removeTrailingEquals(Buffer.from(hmacBuffer).toString("base64"));
};

@@ -520,3 +799,3 @@ var unsignCookie = async (input, secret) => {

for (const [key, value] of Object.entries(property)) {
if (primitiveHooks.includes(key) || !(key in extension))
if (key in primitiveHookMap || !(key in extension))
continue;

@@ -604,2 +883,3 @@ const v = extension[key];

filterGlobalHook,
getCookieValidator,
getResponseSchemaValidator,

@@ -609,3 +889,2 @@ getSchemaValidator,

mergeCookie,
mergeDeep,
mergeHook,

@@ -612,0 +891,0 @@ mergeLifeCycle,

import 'bun';
import '@sinclair/typebox';
import '@sinclair/typebox/compiler';
export { aZ as ElysiaWS, aY as websocket } from '../dynamic-handle-O2HN1QLh.js';
export { aK as ElysiaWS, aJ as websocket } from '../dynamic-handle-BOErSqze.js';
import 'memoirist';

@@ -6,0 +6,0 @@ import 'openapi-types';

@@ -39,9 +39,14 @@ "use strict";

// src/error.ts
var import_value2 = require("@sinclair/typebox/value");
var import_value4 = require("@sinclair/typebox/value");
// src/utils.ts
var import_typebox = require("@sinclair/typebox");
var import_value = require("@sinclair/typebox/value");
var import_compiler = require("@sinclair/typebox/compiler");
var import_typebox2 = require("@sinclair/typebox");
var import_value3 = require("@sinclair/typebox/value");
var import_compiler2 = require("@sinclair/typebox/compiler");
var import_deepmerge2 = __toESM(require("deepmerge"));
// src/index.ts
var import_eventemitter3 = __toESM(require("eventemitter3"));
var import_deepmerge = __toESM(require("deepmerge"));
// src/handler.ts

@@ -57,3 +62,240 @@ var import_cookie2 = require("cookie");

// src/compose.ts
var import_value = require("@sinclair/typebox/value");
var import_fast_querystring = require("fast-querystring");
var import_fast_decode_uri_component2 = __toESM(require("fast-decode-uri-component"));
var headersHasToJSON = new Headers().toJSON;
var KindSymbol = Symbol.for("TypeBox.Kind");
var TransformSymbol = Symbol.for("TypeBox.Transform");
// src/dynamic-handle.ts
var import_fast_querystring2 = require("fast-querystring");
// src/type-system.ts
var import_system = require("@sinclair/typebox/system");
var import_typebox = require("@sinclair/typebox");
var import_value2 = require("@sinclair/typebox/value");
var import_system2 = require("@sinclair/typebox/system");
var import_compiler = require("@sinclair/typebox/compiler");
try {
import_system.TypeSystem.Format(
"email",
(value) => /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(
value
)
);
import_system.TypeSystem.Format(
"uuid",
(value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value
)
);
import_system.TypeSystem.Format(
"date",
(value) => !Number.isNaN(new Date(value).getTime())
);
import_system.TypeSystem.Format(
"date-time",
(value) => !Number.isNaN(new Date(value).getTime())
);
} catch {
}
var t = Object.assign({}, import_typebox.Type);
var parseFileUnit = (size) => {
if (typeof size === "string")
switch (size.slice(-1)) {
case "k":
return +size.slice(0, size.length - 1) * 1024;
case "m":
return +size.slice(0, size.length - 1) * 1048576;
default:
return +size;
}
return size;
};
var validateFile = (options, value) => {
if (!(value instanceof Blob))
return false;
if (options.minSize && value.size < parseFileUnit(options.minSize))
return false;
if (options.maxSize && value.size > parseFileUnit(options.maxSize))
return false;
if (options.extension)
if (typeof options.extension === "string") {
if (!value.type.startsWith(options.extension))
return false;
} else {
for (let i = 0; i < options.extension.length; i++)
if (value.type.startsWith(options.extension[i]))
return true;
return false;
}
return true;
};
var Files = import_system.TypeSystem.Type(
"Files",
(options, value) => {
if (!Array.isArray(value))
return validateFile(options, value);
if (options.minItems && value.length < options.minItems)
return false;
if (options.maxItems && value.length > options.maxItems)
return false;
for (let i = 0; i < value.length; i++)
if (!validateFile(options, value[i]))
return false;
return true;
}
);
if (!import_typebox.FormatRegistry.Get("numeric"))
import_typebox.FormatRegistry.Set("numeric", (value) => !!value && !isNaN(+value));
if (!import_typebox.FormatRegistry.Get("boolean"))
import_typebox.FormatRegistry.Set(
"boolean",
(value) => value === "true" || value === "false"
);
if (!import_typebox.FormatRegistry.Get("ObjectString"))
import_typebox.FormatRegistry.Set("ObjectString", (value) => {
let start = value.charCodeAt(0);
if (start === 9 || start === 10 || start === 32)
start = value.trimStart().charCodeAt(0);
if (start !== 123 && start !== 91)
return false;
try {
JSON.parse(value);
return true;
} catch {
return false;
}
});
var ElysiaType = {
Numeric: (property) => {
const schema = import_typebox.Type.Number(property);
return t.Transform(
t.Union(
[
t.String({
format: "numeric",
default: 0
}),
t.Number(property)
],
property
)
).Decode((value) => {
const number = +value;
if (isNaN(number))
return value;
if (property && !import_value2.Value.Check(schema, number))
throw new ValidationError("property", schema, number);
return number;
}).Encode((value) => value);
},
BooleanString: (property) => {
const schema = import_typebox.Type.Boolean(property);
return t.Transform(
t.Union(
[
t.String({
format: "boolean",
default: false
}),
t.Boolean(property)
],
property
)
).Decode((value) => {
if (typeof value === "string")
return value === "true";
if (property && !import_value2.Value.Check(schema, value))
throw new ValidationError("property", schema, value);
return value;
}).Encode((value) => value);
},
ObjectString: (properties, options) => t.Transform(
t.Union(
[
t.String({
format: "ObjectString",
default: ""
}),
t.Object(properties, options)
],
options
)
).Decode((value) => {
if (typeof value === "string")
try {
return JSON.parse(value);
} catch {
return value;
}
return value;
}).Encode((value) => JSON.stringify(value)),
File: import_system.TypeSystem.Type("File", validateFile),
Files: (options = {}) => t.Transform(t.Union([Files(options)])).Decode((value) => {
if (Array.isArray(value))
return value;
return [value];
}).Encode((value) => value),
Nullable: (schema) => t.Union([t.Null(), schema]),
/**
* Allow Optional, Nullable and Undefined
*/
MaybeEmpty: (schema) => t.Union([t.Null(), t.Undefined(), schema]),
Cookie: (properties, options) => t.Object(properties, options)
};
t.BooleanString = ElysiaType.BooleanString;
t.ObjectString = ElysiaType.ObjectString;
t.Numeric = ElysiaType.Numeric;
t.File = (arg = {}) => ElysiaType.File({
default: "File",
...arg,
extension: arg?.type,
type: "string",
format: "binary"
});
t.Files = (arg = {}) => ElysiaType.Files({
...arg,
elysiaMeta: "Files",
default: "Files",
extension: arg?.type,
type: "array",
items: {
...arg,
default: "Files",
type: "string",
format: "binary"
}
});
t.Nullable = (schema) => ElysiaType.Nullable(schema);
t.MaybeEmpty = ElysiaType.MaybeEmpty;
t.Cookie = ElysiaType.Cookie;
// src/utils.ts
var primitiveHooks = [
"start",
"request",
"parse",
"transform",
"resolve",
"beforeHandle",
"afterHandle",
"onResponse",
"mapResponse",
"trace",
"error",
"stop",
"body",
"headers",
"params",
"query",
"response",
"type",
"detail"
];
var primitiveHookMap = primitiveHooks.reduce(
(acc, x2) => (acc[x2] = true, acc),
{}
);
var isBun = typeof Bun !== "undefined";

@@ -72,5 +314,5 @@ var hasHash = isBun && typeof Bun.hash === "function";

value = value.response;
const error = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value2.Value.Errors(validator, value).First();
const customError = error?.schema.error ? typeof error.schema.error === "function" ? error.schema.error(type, validator, value) : error.schema.error : void 0;
const accessor = error?.path?.slice(1) || "root";
const error2 = isProduction ? void 0 : "Errors" in validator ? validator.Errors(value).First() : import_value4.Value.Errors(validator, value).First();
const customError = error2?.schema.error ? typeof error2.schema.error === "function" ? error2.schema.error(type, validator, value) : error2.schema.error : void 0;
const accessor = error2?.path?.slice(1) || "root";
let message = "";

@@ -82,3 +324,3 @@ if (customError) {

type,
message: error?.message
message: error2?.message
});

@@ -90,4 +332,4 @@ } else {

at: accessor,
message: error?.message,
expected: import_value2.Value.Create(
message: error2?.message,
expected: import_value4.Value.Create(
// @ts-ignore private field

@@ -117,3 +359,3 @@ validator.schema

try {
return import_value2.Value.Create(model);
return import_value4.Value.Create(model);
} catch {

@@ -120,0 +362,0 @@ return model;

import 'bun';
import '@sinclair/typebox';
import '@sinclair/typebox/compiler';
export { a_ as WS } from '../dynamic-handle-O2HN1QLh.js';
export { aL as WS } from '../dynamic-handle-BOErSqze.js';
import 'memoirist';

@@ -6,0 +6,0 @@ import 'openapi-types';

@@ -1,3 +0,4 @@

import { E as Elysia, L as LifeCycleStore, S as SchemaValidator, H as Handler, a as Sucrose, C as ComposedHandler } from './dynamic-handle-O2HN1QLh.js';
import { E as Elysia, L as LifeCycleStore, S as SchemaValidator, H as Handler, C as ComposedHandler } from './dynamic-handle-BOErSqze.js';
import { TAnySchema } from '@sinclair/typebox';
import { Sucrose } from './sucrose.js';
import 'bun';

@@ -31,3 +32,4 @@ import 'memoirist';

declare const composeErrorHandler: (app: Elysia<any, any, any, any, any, any, any, any>) => any;
declare const jitRoute: (index: number) => string;
export { composeErrorHandler, composeGeneralHandler, composeHandler, hasProperty, hasReturn, hasTransform, hasType, isAsync };
export { composeErrorHandler, composeGeneralHandler, composeHandler, hasProperty, hasReturn, hasTransform, hasType, isAsync, jitRoute };

@@ -1,2 +0,2 @@

export { aE as Context, aF as PreContext } from './dynamic-handle-O2HN1QLh.js';
export { aD as Context, aE as PreContext } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

@@ -1,2 +0,2 @@

export { f as Cookie, d as CookieOptions, e as ElysiaCookie, g as createCookieJar, p as parseCookie } from './dynamic-handle-O2HN1QLh.js';
export { e as Cookie, c as CookieOptions, d as ElysiaCookie, f as createCookieJar, p as parseCookie } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

@@ -1,2 +0,2 @@

export { b6 as DynamicHandler, b8 as createDynamicErrorHandler, b7 as createDynamicHandler } from './dynamic-handle-O2HN1QLh.js';
export { aT as DynamicHandler, aV as createDynamicErrorHandler, aU as createDynamicHandler } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

import '@sinclair/typebox/compiler';
import '@sinclair/typebox';
export { i as ELYSIA_RESPONSE, h as ERROR_CODE, k as ElysiaErrors, I as InternalServerError, m as InvalidCookieSignature, N as NotFoundError, P as ParseError, V as ValidationError, l as error, j as isProduction } from './dynamic-handle-O2HN1QLh.js';
export { h as ELYSIA_RESPONSE, g as ERROR_CODE, j as ElysiaErrors, I as InternalServerError, l as InvalidCookieSignature, N as NotFoundError, P as ParseError, V as ValidationError, k as error, i as isProduction } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -5,0 +5,0 @@ import 'memoirist';

@@ -1,2 +0,2 @@

export { b5 as errorToResponse, a$ as isNotEmpty, b4 as mapCompactResponse, b3 as mapEarlyResponse, b2 as mapResponse, b0 as parseSetCookies, b1 as serializeCookie } from './dynamic-handle-O2HN1QLh.js';
export { aS as errorToResponse, aM as isNotEmpty, aR as mapCompactResponse, aQ as mapEarlyResponse, aP as mapResponse, aN as parseSetCookies, aO as serializeCookie } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

import 'bun';
import 'memoirist';
export { Static, TSchema } from '@sinclair/typebox';
export { Q as AfterHandler, a0 as BodyHandler, ad as Checksum, C as ComposedHandler, aE as Context, f as Cookie, d as CookieOptions, D as DefinitionBase, E as Elysia, n as ElysiaConfig, a3 as ErrorHandler, A as HTTPMethod, H as Handler, B as InputSchema, a7 as InternalRoute, I as InternalServerError, m as InvalidCookieSignature, y as LifeCycleEvent, L as LifeCycleStore, a8 as ListenCallback, a6 as LocalHook, o as MaybePromise, F as MergeSchema, N as NotFoundError, K as OptionalHandler, P as ParseError, aF as PreContext, a1 as PreHandler, t as RouteBase, v as RouteSchema, S as SchemaValidator, s as SingletonBase, Z as TraceEvent, b as TraceHandler, _ as TraceProcess, T as TraceReporter, c as TraceStream, w as UnwrapRoute, U as UnwrapSchema, V as ValidationError, X as VoidHandler, E as default, l as error, ar as getResponseSchemaValidator, aq as getSchemaValidator, b4 as mapCompactResponse, b3 as mapEarlyResponse, b2 as mapResponse, al as mergeDeep, ap as mergeHook, an as mergeObjectArray, aG as t } from './dynamic-handle-O2HN1QLh.js';
export { K as AfterHandler, $ as BodyHandler, ac as Checksum, C as ComposedHandler, aD as Context, e as Cookie, c as CookieOptions, D as DefinitionBase, E as Elysia, m as ElysiaConfig, a2 as ErrorHandler, z as HTTPMethod, H as Handler, A as InputSchema, a6 as InternalRoute, I as InternalServerError, l as InvalidCookieSignature, x as LifeCycleEvent, L as LifeCycleStore, a7 as ListenCallback, a5 as LocalHook, n as MaybePromise, B as MergeSchema, N as NotFoundError, J as OptionalHandler, P as ParseError, aE as PreContext, a0 as PreHandler, s as RouteBase, u as RouteSchema, S as SchemaValidator, r as SingletonBase, Y as TraceEvent, T as TraceHandler, Z as TraceProcess, a as TraceReporter, b as TraceStream, v as UnwrapRoute, U as UnwrapSchema, V as ValidationError, W as VoidHandler, E as default, k as error, ap as getResponseSchemaValidator, ao as getSchemaValidator, aR as mapCompactResponse, aQ as mapEarlyResponse, aP as mapResponse, an as mergeHook, al as mergeObjectArray, aF as t } from './dynamic-handle-BOErSqze.js';
import '@sinclair/typebox/compiler';

@@ -6,0 +6,0 @@ import 'openapi-types';

@@ -1,2 +0,2 @@

export { a as Sucrose, aL as bracketPairRange, aM as bracketPairRangeReverse, aR as extractMainParameter, aQ as findAlias, aO as findParameterReference, aP as findTraceParameterReference, aS as inferBodyReference, aV as inferTraceBodyReference, aT as removeDefaultParameter, aN as retrieveRootParamters, aK as separateFunction, aW as sucrose, aX as sucroseTrace, aU as validateInferencedQueries } from './dynamic-handle-O2HN1QLh.js';
import { L as LifeCycleStore, H as Handler, T as TraceHandler } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -9,1 +9,104 @@ import 'memoirist';

import '@sinclair/typebox/system';
declare namespace Sucrose {
interface Inference {
queries: string[];
unknownQueries: boolean;
query: boolean;
headers: boolean;
body: boolean;
cookie: boolean;
set: boolean;
}
interface LifeCycle extends Partial<LifeCycleStore> {
handler?: Handler;
}
interface TraceInference {
request: boolean;
parse: boolean;
transform: boolean;
handle: boolean;
beforeHandle: boolean;
afterHandle: boolean;
error: boolean;
context: boolean;
store: boolean;
set: boolean;
}
}
/**
* Separate stringified function body and paramter
*
* @example
* ```typescript
* separateFunction('async ({ hello }) => { return hello }') // => ['({ hello })', '{ return hello }']
* ```
*/
declare const separateFunction: (code: string) => [string, string];
/**
* Get range between bracket pair
*
* @example
* ```typescript
* bracketPairRange('hello: { world: { a } }, elysia') // [6, 20]
* ```
*/
declare const bracketPairRange: (parameter: string) => [number, number];
/**
* Similar to `bracketPairRange` but in reverse order
* Get range between bracket pair from end to beginning
*
* @example
* ```typescript
* bracketPairRange('hello: { world: { a } }, elysia') // [6, 20]
* ```
*/
declare const bracketPairRangeReverse: (parameter: string) => [number, number];
/**
* Retrieve only root paramters of a function
*
* @example
* ```typescript
* retrieveRootParameters('({ hello: { world: { a } }, elysia })') // => 'hello elysia'
* ```
*/
declare const retrieveRootParamters: (parameter: string) => string;
/**
* Find inference from parameter
*
* @param parameter stringified parameter
*/
declare const findParameterReference: (parameter: string, inference: Sucrose.Inference) => string;
/**
* Find inference from parameter
*
* @param parameter stringified parameter
*/
declare const findTraceParameterReference: (parameter: string, inference: Sucrose.TraceInference) => string;
/**
* Find alias of variable from function body
*
* @example
* ```typescript
* findAlias('body', '{ const a = body, b = body }') // => ['a', 'b']
* ```
*/
declare const findAlias: (type: string, body: string, depth?: number) => string[];
declare const extractMainParameter: (parameter: string) => string | undefined;
/**
* Analyze if context is mentioned in body
*/
declare const inferBodyReference: (code: string, aliases: string[], inference: Sucrose.Inference) => string[];
declare const removeDefaultParameter: (parameter: string) => string;
declare const validateInferencedQueries: (queries: string[]) => boolean;
/**
* Analyze if context is mentioned in body
*/
declare const inferTraceBodyReference: (code: string, aliases: string[], inference: Sucrose.TraceInference) => string[];
declare const sucrose: (lifeCycle: Sucrose.LifeCycle, inference?: Sucrose.Inference) => Sucrose.Inference;
/**
* Analyze if context is mentioned in body in a trace
*/
declare const sucroseTrace: (traces: TraceHandler[], inference?: Sucrose.TraceInference) => Sucrose.TraceInference;
export { Sucrose, bracketPairRange, bracketPairRangeReverse, extractMainParameter, findAlias, findParameterReference, findTraceParameterReference, inferBodyReference, inferTraceBodyReference, removeDefaultParameter, retrieveRootParamters, separateFunction, sucrose, sucroseTrace, validateInferencedQueries };

@@ -1,2 +0,2 @@

import { T as TraceReporter, b as TraceHandler, c as TraceStream } from './dynamic-handle-O2HN1QLh.js';
import { a as TraceReporter, T as TraceHandler, b as TraceStream } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import 'memoirist';

import '@sinclair/typebox';
export { TypeCheck, TypeCompiler } from '@sinclair/typebox/compiler';
export { aI as ElysiaType, aH as ElysiaTypeOptions, aJ as TCookie, aG as t } from './dynamic-handle-O2HN1QLh.js';
export { aH as ElysiaType, aG as ElysiaTypeOptions, aI as TCookie, aF as t } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -5,0 +5,0 @@ export { TypeSystem, TypeSystemDuplicateFormat, TypeSystemDuplicateTypeKind, TypeSystemPolicy } from '@sinclair/typebox/system';

@@ -1,2 +0,2 @@

export { a9 as AddPrefix, aa as AddPrefixCapitalize, ab as AddSuffix, ac as AddSuffixCapitalize, Q as AfterHandler, ae as BaseMacro, a0 as BodyHandler, ad as Checksum, ai as ComposeElysiaResponse, C as ComposedHandler, z as ContentType, ah as CreateEden, D as DefinitionBase, n as ElysiaConfig, a3 as ErrorHandler, G as GetPathParameter, a2 as GracefulHandler, A as HTTPMethod, H as Handler, J as InlineHandler, B as InputSchema, a7 as InternalRoute, a4 as Isolate, y as LifeCycleEvent, L as LifeCycleStore, a8 as ListenCallback, a6 as LocalHook, ag as MacroManager, af as MacroToProperty, W as MapResponse, M as MaybeArray, o as MaybePromise, aj as MergeElysiaInstances, F as MergeSchema, u as MetadataBase, a5 as NoInfer, O as ObjectValues, K as OptionalHandler, a1 as PreHandler, q as Prettify, r as Prettify2, R as Reconcile, t as RouteBase, v as RouteSchema, S as SchemaValidator, s as SingletonBase, Z as TraceEvent, b as TraceHandler, $ as TraceListener, _ as TraceProcess, T as TraceReporter, c as TraceStream, Y as TransformHandler, x as UnwrapGroupGuardRoute, w as UnwrapRoute, U as UnwrapSchema, X as VoidHandler } from './dynamic-handle-O2HN1QLh.js';
export { a8 as AddPrefix, a9 as AddPrefixCapitalize, aa as AddSuffix, ab as AddSuffixCapitalize, K as AfterHandler, ad as BaseMacro, $ as BodyHandler, ac as Checksum, ah as ComposeElysiaResponse, C as ComposedHandler, y as ContentType, ag as CreateEden, D as DefinitionBase, m as ElysiaConfig, a2 as ErrorHandler, G as GetPathParameter, a1 as GracefulHandler, z as HTTPMethod, H as Handler, F as InlineHandler, A as InputSchema, a6 as InternalRoute, a3 as Isolate, x as LifeCycleEvent, L as LifeCycleStore, a7 as ListenCallback, a5 as LocalHook, af as MacroManager, ae as MacroToProperty, Q as MapResponse, M as MaybeArray, n as MaybePromise, ai as MergeElysiaInstances, B as MergeSchema, t as MetadataBase, a4 as NoInfer, O as ObjectValues, J as OptionalHandler, a0 as PreHandler, o as Prettify, q as Prettify2, R as Reconcile, s as RouteBase, u as RouteSchema, S as SchemaValidator, r as SingletonBase, Y as TraceEvent, T as TraceHandler, _ as TraceListener, Z as TraceProcess, a as TraceReporter, b as TraceStream, X as TransformHandler, w as UnwrapGroupGuardRoute, v as UnwrapRoute, U as UnwrapSchema, W as VoidHandler } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -3,0 +3,0 @@ import '@sinclair/typebox';

import '@sinclair/typebox';
import '@sinclair/typebox/compiler';
export { ay as HTTPStatusName, ax as StatusMap, av as asGlobal, au as asGlobalHook, as as checksum, aC as createMacroManager, aw as filterGlobalHook, ar as getResponseSchemaValidator, aq as getSchemaValidator, aD as isNumericString, am as mergeCookie, al as mergeDeep, ap as mergeHook, at as mergeLifeCycle, an as mergeObjectArray, ao as primitiveHooks, ak as replaceUrlPath, az as signCookie, aB as traceBackMacro, aA as unsignCookie } from './dynamic-handle-O2HN1QLh.js';
export { ax as HTTPStatusName, aw as StatusMap, au as asGlobal, at as asGlobalHook, aq as checksum, aB as createMacroManager, av as filterGlobalHook, ar as getCookieValidator, ap as getResponseSchemaValidator, ao as getSchemaValidator, aC as isNumericString, ak as mergeCookie, an as mergeHook, as as mergeLifeCycle, al as mergeObjectArray, am as primitiveHooks, aj as replaceUrlPath, ay as signCookie, aA as traceBackMacro, az as unsignCookie } from './dynamic-handle-BOErSqze.js';
import 'bun';

@@ -5,0 +5,0 @@ import 'memoirist';

import 'bun';
import '@sinclair/typebox';
import '@sinclair/typebox/compiler';
export { aZ as ElysiaWS, aY as websocket } from '../dynamic-handle-O2HN1QLh.js';
export { aK as ElysiaWS, aJ as websocket } from '../dynamic-handle-BOErSqze.js';
import 'memoirist';

@@ -6,0 +6,0 @@ import 'openapi-types';

import 'bun';
import '@sinclair/typebox';
import '@sinclair/typebox/compiler';
export { a_ as WS } from '../dynamic-handle-O2HN1QLh.js';
export { aL as WS } from '../dynamic-handle-BOErSqze.js';
import 'memoirist';

@@ -6,0 +6,0 @@ import 'openapi-types';

{
"name": "elysia",
"description": "Ergonomic Framework for Human",
"version": "1.0.0-exp.13",
"version": "1.0.0-exp.14",
"author": {

@@ -112,2 +112,3 @@ "name": "saltyAom",

"cookie": "^0.6.0",
"deepmerge": "^4.3.1",
"eventemitter3": "^5.0.1",

@@ -114,0 +115,0 @@ "fast-decode-uri-component": "^1.0.1",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc