@dunx/http 2.4.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +31 -909
  2. package/dist/chunk-25g22350.js +58 -0
  3. package/dist/chunk-ywdpxbkf.js +1573 -0
  4. package/dist/client/module.d.ts +2 -7
  5. package/dist/client/options.d.ts +12 -0
  6. package/dist/client/service.d.ts +11 -22
  7. package/dist/client.d.ts +8 -2
  8. package/dist/client.js +26 -137
  9. package/dist/compression/compression.d.ts +25 -0
  10. package/dist/compression/module.d.ts +20 -0
  11. package/dist/compression/negotiate.d.ts +12 -0
  12. package/dist/compression/options.d.ts +61 -0
  13. package/dist/health/indicators.d.ts +5 -10
  14. package/dist/index.d.ts +24 -20
  15. package/dist/index.js +325 -1366
  16. package/dist/internal.d.ts +36 -0
  17. package/dist/internal.js +89 -0
  18. package/dist/route/decorators.d.ts +6 -6
  19. package/dist/route/marker.d.ts +13 -0
  20. package/dist/route/metadata.d.ts +6 -9
  21. package/dist/route/schema.d.ts +59 -29
  22. package/dist/server/application.d.ts +33 -89
  23. package/dist/server/client-address.d.ts +6 -13
  24. package/dist/server/errors.d.ts +24 -55
  25. package/dist/server/request-id.d.ts +6 -11
  26. package/dist/server/request-logging.d.ts +33 -91
  27. package/dist/server/routes.d.ts +8 -20
  28. package/dist/server/trace-context.d.ts +47 -0
  29. package/dist/static/files.d.ts +5 -13
  30. package/dist/static/module.d.ts +10 -19
  31. package/dist/throttle/guard.d.ts +6 -9
  32. package/dist/throttle/module.d.ts +6 -8
  33. package/dist/throttle/store.d.ts +11 -20
  34. package/dist/ws/middleware.d.ts +12 -21
  35. package/dist/ws/redis-relay.d.ts +9 -19
  36. package/package.json +7 -3
  37. package/dist/chunk-sz4pvqxy.js +0 -111
  38. package/dist/chunk-sz4pvqxy.js.map +0 -10
  39. package/dist/client.js.map +0 -15
  40. package/dist/index.js.map +0 -53
@@ -0,0 +1,1573 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __name = (target, name) => {
6
+ Object.defineProperty(target, "name", {
7
+ value: name,
8
+ enumerable: false,
9
+ configurable: true
10
+ });
11
+ return target;
12
+ };
13
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
14
+ var __typeError = (msg) => {
15
+ throw TypeError(msg);
16
+ };
17
+ var __defNormalProp = (obj, key, value) => (key in obj) ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
18
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
19
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
20
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
21
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
22
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
23
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
24
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
25
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
26
+ var __expectFn = (fn) => fn !== undefined && typeof fn !== "function" ? __typeError("Function expected") : fn;
27
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({
28
+ kind: __decoratorStrings[kind],
29
+ name,
30
+ metadata,
31
+ addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null))
32
+ });
33
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
34
+ var __runInitializers = (array, flags, self, value) => {
35
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length;i < n; i++)
36
+ flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
37
+ return value;
38
+ };
39
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
40
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
41
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
42
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
43
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : {
44
+ get [name]() {
45
+ return __privateGet(this, extra);
46
+ },
47
+ set [name](x) {
48
+ __privateSet(this, extra, x);
49
+ }
50
+ }, name));
51
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
52
+ for (var i = decorators.length - 1;i >= 0; i--) {
53
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
54
+ if (k) {
55
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => (name in x) };
56
+ if (k ^ 3)
57
+ access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
58
+ if (k > 2)
59
+ access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
60
+ }
61
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? undefined : { get: desc.get, set: desc.set } : target, ctx);
62
+ done._ = 1;
63
+ if (k ^ 4 || it === undefined)
64
+ __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
65
+ else if (typeof it !== "object" || it === null)
66
+ __typeError("Object expected");
67
+ else
68
+ __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
69
+ }
70
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
71
+ };
72
+
73
+ // src/route/discover.ts
74
+ import { markedMethods } from "@dunx/core";
75
+
76
+ // src/server/status.ts
77
+ var HttpStatusCode = Object.freeze({
78
+ OK: 200,
79
+ CREATED: 201,
80
+ ACCEPTED: 202,
81
+ NO_CONTENT: 204,
82
+ MOVED_PERMANENTLY: 301,
83
+ FOUND: 302,
84
+ NOT_MODIFIED: 304,
85
+ TEMPORARY_REDIRECT: 307,
86
+ PERMANENT_REDIRECT: 308,
87
+ BAD_REQUEST: 400,
88
+ UNAUTHORIZED: 401,
89
+ PAYMENT_REQUIRED: 402,
90
+ FORBIDDEN: 403,
91
+ NOT_FOUND: 404,
92
+ METHOD_NOT_ALLOWED: 405,
93
+ NOT_ACCEPTABLE: 406,
94
+ REQUEST_TIMEOUT: 408,
95
+ CONFLICT: 409,
96
+ GONE: 410,
97
+ PRECONDITION_FAILED: 412,
98
+ PAYLOAD_TOO_LARGE: 413,
99
+ URI_TOO_LONG: 414,
100
+ UNSUPPORTED_MEDIA_TYPE: 415,
101
+ IM_A_TEAPOT: 418,
102
+ UNPROCESSABLE_ENTITY: 422,
103
+ TOO_MANY_REQUESTS: 429,
104
+ INTERNAL_SERVER_ERROR: 500,
105
+ NOT_IMPLEMENTED: 501,
106
+ BAD_GATEWAY: 502,
107
+ SERVICE_UNAVAILABLE: 503,
108
+ GATEWAY_TIMEOUT: 504
109
+ });
110
+
111
+ // src/route/marker.ts
112
+ var ROUTE = Symbol.for("dunx.route");
113
+ var CONTROLLER = Symbol.for("dunx.controller");
114
+ var defaultStatusFor = (method) => method === "POST" ? HttpStatusCode.CREATED : HttpStatusCode.OK;
115
+ var resolvePath = (path) => typeof path === "function" ? path() : path;
116
+ var markRoute = (target, meta) => {
117
+ Object.defineProperty(target, ROUTE, { value: meta, configurable: true });
118
+ };
119
+ var routeMetaOf = (value) => typeof value === "function" ? value[ROUTE] : undefined;
120
+ var markController = (target, prefix) => {
121
+ Object.defineProperty(target, CONTROLLER, {
122
+ value: prefix,
123
+ configurable: true
124
+ });
125
+ };
126
+ var prefixOf = (target) => target[CONTROLLER] ?? "";
127
+
128
+ // src/route/metadata.ts
129
+ var META = Symbol.for("dunx.meta");
130
+ var GUARDS = Symbol.for("dunx.guards");
131
+ var metaKey = (name) => ({
132
+ name,
133
+ id: Symbol(name)
134
+ });
135
+ var write = (target, key, value) => {
136
+ const record = new Map(target[META]);
137
+ record.set(key.id, value);
138
+ Object.defineProperty(target, META, { value: record, configurable: true });
139
+ };
140
+ var meta = (key, value) => (target) => {
141
+ write(target, key, value);
142
+ return target;
143
+ };
144
+ var ROLES = metaKey("roles");
145
+ var PUBLIC = metaKey("public");
146
+ var HIDDEN = metaKey("hidden");
147
+ var UNMATCHED = metaKey("unmatched");
148
+ var Roles = (...roles) => meta(ROLES, roles);
149
+ var Public = () => meta(PUBLIC, true);
150
+ var ApiHidden = () => meta(HIDDEN, true);
151
+ var UseGuards = (...guards) => (target) => {
152
+ const existing = target[GUARDS] ?? [];
153
+ const merged = Object.hasOwn(target, GUARDS) ? [...guards, ...existing] : [...existing, ...guards];
154
+ Object.defineProperty(target, GUARDS, {
155
+ value: merged,
156
+ configurable: true
157
+ });
158
+ return target;
159
+ };
160
+ var guardsOf = (target) => target[GUARDS] ?? [];
161
+ var metaOf = (target) => target[META];
162
+ var mergeMeta = (...targets) => {
163
+ const merged = new Map;
164
+ for (const target of targets) {
165
+ const record = target[META];
166
+ if (record)
167
+ for (const [id, value] of record)
168
+ merged.set(id, value);
169
+ }
170
+ return merged;
171
+ };
172
+
173
+ // src/route/discover.ts
174
+ var joinPath = (prefix, path) => {
175
+ const joined = `/${prefix}/${path}`.replace(/\/{2,}/g, "/");
176
+ return joined.length > 1 ? joined.replace(/\/$/, "") : "/";
177
+ };
178
+ var discoverRoutes = (instance) => {
179
+ const klass = instance.constructor;
180
+ const prefix = prefixOf(klass);
181
+ const classGuards = guardsOf(klass);
182
+ const members = instance;
183
+ return markedMethods(Object.getPrototypeOf(instance), routeMetaOf).map(({ name, meta: meta2, value: marked }) => ({
184
+ method: meta2.method,
185
+ path: joinPath(prefix, resolvePath(meta2.path)),
186
+ controller: klass.name,
187
+ handlerName: name,
188
+ handler: members[name].bind(instance),
189
+ options: meta2.options,
190
+ meta: mergeMeta(klass, marked),
191
+ classMeta: metaOf(klass),
192
+ guards: [...classGuards, ...guardsOf(marked)]
193
+ }));
194
+ };
195
+ // src/inspect.ts
196
+ import {
197
+ collectModules,
198
+ dependenciesOf,
199
+ readControllers
200
+ } from "@dunx/core";
201
+
202
+ // src/ws/discover.ts
203
+ import {
204
+ AppError,
205
+ classOf,
206
+ markedMethods as markedMethods2
207
+ } from "@dunx/core";
208
+
209
+ // src/ws/marker.ts
210
+ var HANDLER = Symbol.for("dunx.ws.handler");
211
+ var GATEWAY = Symbol.for("dunx.ws.gateway");
212
+ var HandlerKind = Object.freeze({
213
+ UPGRADE: "upgrade",
214
+ OPEN: "open",
215
+ MESSAGE: "message",
216
+ CLOSE: "close",
217
+ DRAIN: "drain",
218
+ PING: "ping",
219
+ PONG: "pong"
220
+ });
221
+ var markHandler = (target, meta2) => {
222
+ Object.defineProperty(target, HANDLER, { value: meta2, configurable: true });
223
+ };
224
+ var handlerMetaOf = (value) => typeof value === "function" ? value[HANDLER] : undefined;
225
+ var markGateway = (target, path) => {
226
+ Object.defineProperty(target, GATEWAY, { value: path, configurable: true });
227
+ };
228
+ var gatewayPathOf = (target) => target[GATEWAY] ?? "/";
229
+ var isGateway = (target) => target[GATEWAY] !== undefined;
230
+
231
+ // src/ws/discover.ts
232
+ var normalizePath = (path) => {
233
+ const joined = `/${path}`.replace(/\/{2,}/g, "/");
234
+ return joined.length > 1 ? joined.replace(/\/$/, "") : "/";
235
+ };
236
+ var eachHandler = (start) => markedMethods2(start, handlerMetaOf);
237
+ var discoverGateway = (instance) => {
238
+ const klass = instance.constructor;
239
+ const members = instance;
240
+ return {
241
+ name: klass.name,
242
+ path: normalizePath(gatewayPathOf(klass)),
243
+ handlers: eachHandler(Object.getPrototypeOf(instance)).map(({ name, meta: meta2 }) => ({
244
+ kind: meta2.kind,
245
+ event: meta2.event,
246
+ method: name,
247
+ invoke: members[name].bind(instance)
248
+ }))
249
+ };
250
+ };
251
+ var findHandlerMethod = (ctor) => eachHandler(ctor.prototype)[0]?.name;
252
+ var discoverGateways = (modules, resolve) => {
253
+ const discovered = [];
254
+ for (const module of modules) {
255
+ for (const entry of module.options.providers ?? []) {
256
+ const candidate = classOf(entry);
257
+ if (!candidate)
258
+ continue;
259
+ if (isGateway(candidate.ctor)) {
260
+ discovered.push(discoverGateway(resolve(candidate.token)));
261
+ continue;
262
+ }
263
+ const orphan = findHandlerMethod(candidate.ctor);
264
+ if (orphan !== undefined) {
265
+ throw new AppError(`${candidate.ctor.name}.${orphan}() is a websocket handler, but ` + `${candidate.ctor.name} is not a gateway. Decorate the class with ` + "@Gateway(path), or drop the handler decorator.");
266
+ }
267
+ }
268
+ }
269
+ return discovered;
270
+ };
271
+
272
+ // src/inspect.ts
273
+ var vendorOf = (schema) => schema?.["~standard"]?.vendor;
274
+ var validatesIn = (options) => {
275
+ const body = vendorOf(options?.body);
276
+ const query = vendorOf(options?.query);
277
+ const params = vendorOf(options?.params);
278
+ return {
279
+ ...body === undefined ? {} : { body },
280
+ ...query === undefined ? {} : { query },
281
+ ...params === undefined ? {} : { params }
282
+ };
283
+ };
284
+ var rolesIn = (route) => {
285
+ const roles = route.meta?.get(ROLES.id);
286
+ if (roles === undefined || roles === null)
287
+ return null;
288
+ return (Array.isArray(roles) ? roles : [roles]).map(String);
289
+ };
290
+ var nodeFor = (route, module) => ({
291
+ method: route.method,
292
+ path: route.path,
293
+ controller: route.controller,
294
+ handler: route.handlerName,
295
+ module,
296
+ public: route.meta?.get(PUBLIC.id) === true,
297
+ roles: rolesIn(route),
298
+ guards: (route.guards ?? []).map((guard) => guard.name),
299
+ hidden: route.meta?.get(HIDDEN.id) === true,
300
+ validates: validatesIn(route.options),
301
+ status: route.options?.status ?? null,
302
+ responses: Object.keys(route.options?.response ?? {}).map(Number)
303
+ });
304
+ var routesOf = (root) => collectModules(root).flatMap((module) => readControllers(module).flatMap((controller) => {
305
+ const { prototype } = controller;
306
+ return discoverRoutes(Object.create(prototype)).map((route) => nodeFor(route, module.name));
307
+ }));
308
+ var gatewayFor = (ctor, module) => {
309
+ const { name, path, handlers } = discoverGateway(Object.create(ctor.prototype));
310
+ return {
311
+ name,
312
+ path,
313
+ module,
314
+ dependencies: dependenciesOf(ctor),
315
+ handlers: handlers.map((handler) => ({
316
+ kind: handler.kind,
317
+ event: handler.event ?? null,
318
+ method: handler.method
319
+ }))
320
+ };
321
+ };
322
+ var classOf2 = (entry) => {
323
+ if (typeof entry === "function")
324
+ return entry;
325
+ return entry.provider.kind === "class" ? entry.provider.ctor : undefined;
326
+ };
327
+ var gatewaysOf = (root) => collectModules(root).flatMap((module) => (module.options.providers ?? []).map(classOf2).filter((ctor) => ctor !== undefined).filter(isGateway).map((ctor) => gatewayFor(ctor, module.name)));
328
+ // src/server/context.ts
329
+ var EMPTY = new Map;
330
+ var buildContext = (route) => {
331
+ const record = route.meta ?? EMPTY;
332
+ return Object.freeze({
333
+ controller: route.controller,
334
+ handler: route.handlerName,
335
+ method: route.method,
336
+ path: route.path,
337
+ parsesBody: route.options?.body !== undefined,
338
+ get: (key) => record.get(key.id)
339
+ });
340
+ };
341
+ // src/server/cors.ts
342
+ var ORIGIN = "access-control-allow-origin";
343
+ var allowedOrigin = (options, requested) => {
344
+ const origin = options.origin ?? "*";
345
+ if (typeof origin === "string") {
346
+ if (origin !== "*")
347
+ return origin === requested ? origin : undefined;
348
+ if (!options.credentials)
349
+ return "*";
350
+ return requested ?? undefined;
351
+ }
352
+ if (requested === null)
353
+ return;
354
+ const allowed = typeof origin === "function" ? origin(requested) : origin.includes(requested);
355
+ return allowed ? requested : undefined;
356
+ };
357
+ var applyCors = (options, req, response) => {
358
+ const origin = allowedOrigin(options, req.headers.get("origin"));
359
+ if (origin === undefined)
360
+ return response;
361
+ response.headers.set(ORIGIN, origin);
362
+ if (origin !== "*")
363
+ response.headers.append("vary", "Origin");
364
+ if (options.credentials) {
365
+ response.headers.set("access-control-allow-credentials", "true");
366
+ }
367
+ if (options.exposedHeaders?.length) {
368
+ response.headers.set("access-control-expose-headers", options.exposedHeaders.join(", "));
369
+ }
370
+ return response;
371
+ };
372
+ var withCors = (options, handler) => {
373
+ return async (req) => applyCors(options, req, await handler(req));
374
+ };
375
+ var preflight = (options, methods) => {
376
+ const allowMethods = (options.methods ?? methods).join(", ");
377
+ return async (req) => {
378
+ const response = applyCors(options, req, new Response(null, { status: HttpStatusCode.NO_CONTENT }));
379
+ if (!response.headers.has(ORIGIN))
380
+ return response;
381
+ response.headers.set("access-control-allow-methods", allowMethods);
382
+ const allowHeaders = options.allowedHeaders ?? (req.headers.get("access-control-request-headers") ?? "").split(",").map((header) => header.trim()).filter((header) => header.length > 0);
383
+ if (allowHeaders.length > 0) {
384
+ response.headers.set("access-control-allow-headers", allowHeaders.join(", "));
385
+ }
386
+ if (options.maxAge !== undefined) {
387
+ response.headers.set("access-control-max-age", String(options.maxAge));
388
+ }
389
+ return response;
390
+ };
391
+ };
392
+ // src/server/errors.ts
393
+ import { AppError as AppError2, ConsoleLogger } from "@dunx/core";
394
+ class HttpError extends AppError2 {
395
+ status;
396
+ name = "HttpError";
397
+ headers;
398
+ constructor(status, message, options) {
399
+ super(message, options);
400
+ this.status = status;
401
+ this.headers = options?.headers;
402
+ }
403
+ }
404
+ Object.defineProperty(HttpError, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "readonly status: number" }, { unresolved: "message: string" }, { unresolved: "options?: HttpErrorOptions" }] });
405
+
406
+ class ValidationError extends HttpError {
407
+ source;
408
+ issues;
409
+ name = "ValidationError";
410
+ constructor(source, issues) {
411
+ super(HttpStatusCode.BAD_REQUEST, `Invalid ${source}`);
412
+ this.source = source;
413
+ this.issues = issues;
414
+ }
415
+ }
416
+ Object.defineProperty(ValidationError, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "readonly source: InputSource" }, { unresolved: "readonly issues: readonly ValidationIssue[]" }] });
417
+
418
+ class ErrorFilter {
419
+ }
420
+ var isErrorFilter = (handler) => typeof handler === "function" && typeof handler.prototype?.catch === "function";
421
+ var toErrorMapper = (handler, resolve) => isErrorFilter(handler) ? (error, req) => resolve(handler).catch(error, req) : handler;
422
+ var errorMapper = (logger) => (error) => {
423
+ if (error instanceof ValidationError) {
424
+ return Response.json({ error: error.message, status: error.status, issues: error.issues }, {
425
+ status: error.status,
426
+ ...error.headers && { headers: error.headers }
427
+ });
428
+ }
429
+ if (error instanceof HttpError) {
430
+ return Response.json({ error: error.message, status: error.status }, {
431
+ status: error.status,
432
+ ...error.headers && { headers: error.headers }
433
+ });
434
+ }
435
+ logger.error("Unhandled error", error);
436
+ return Response.json({
437
+ error: "Internal Server Error",
438
+ status: HttpStatusCode.INTERNAL_SERVER_ERROR
439
+ }, { status: HttpStatusCode.INTERNAL_SERVER_ERROR });
440
+ };
441
+ var defaultErrorMapper = errorMapper(new ConsoleLogger);
442
+ // src/server/middleware.ts
443
+ var compose = (middleware, ctx, handler) => middleware.reduceRight((next, current) => (req) => current.handle(req, ctx, () => next(req)), handler);
444
+ // src/server/routes.ts
445
+ import { AppError as AppError3 } from "@dunx/core";
446
+
447
+ // src/server/raw-body.ts
448
+ var WANTED = Symbol.for("dunx.http.rawBody.wanted");
449
+ var TEXT = Symbol.for("dunx.http.rawBody.text");
450
+
451
+ class RawBody {
452
+ static want(req) {
453
+ req[WANTED] = true;
454
+ }
455
+ static wanted(req) {
456
+ return req[WANTED] === true;
457
+ }
458
+ static record(req, text) {
459
+ req[TEXT] = text;
460
+ }
461
+ static read(req) {
462
+ return req[TEXT];
463
+ }
464
+ }
465
+
466
+ // src/server/input.ts
467
+ var grouped = (entries) => {
468
+ const collected = {};
469
+ entries.forEach((value, key) => {
470
+ const existing = collected[key];
471
+ if (existing === undefined)
472
+ collected[key] = value;
473
+ else if (Array.isArray(existing))
474
+ existing.push(value);
475
+ else
476
+ collected[key] = [existing, value];
477
+ });
478
+ return collected;
479
+ };
480
+ var asJson = (req) => req.json();
481
+ var asUrlEncoded = async (req) => grouped(new URLSearchParams(await req.text()));
482
+ var asMultipart = async (req) => grouped(await req.formData());
483
+ var asText = (req) => req.text();
484
+ var parserFor = (media) => {
485
+ if (media === "application/json" || media.endsWith("+json"))
486
+ return asJson;
487
+ if (media === "application/x-www-form-urlencoded")
488
+ return asUrlEncoded;
489
+ if (media === "multipart/form-data")
490
+ return asMultipart;
491
+ if (media.startsWith("text/"))
492
+ return asText;
493
+ return;
494
+ };
495
+ var JSON_MEDIA = "application/json";
496
+ var mediaTypeOf = (req) => {
497
+ const header = req.headers.get("content-type");
498
+ if (header === JSON_MEDIA || header === null)
499
+ return JSON_MEDIA;
500
+ const end = header.indexOf(";");
501
+ const media = (end === -1 ? header : header.slice(0, end)).trim();
502
+ return media === "" ? JSON_MEDIA : media.toLowerCase();
503
+ };
504
+ var flatten = (issue) => {
505
+ const path = issue.path?.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
506
+ return path === undefined || path === "" ? { message: issue.message } : { message: issue.message, path };
507
+ };
508
+ var accept = (source, result) => {
509
+ if (result.issues !== undefined) {
510
+ throw new ValidationError(source, result.issues.map(flatten));
511
+ }
512
+ return result.value;
513
+ };
514
+ var fillWith = (draft, source, schema, value) => {
515
+ const result = schema["~standard"].validate(value);
516
+ if (result instanceof Promise) {
517
+ return result.then((settled) => {
518
+ draft[source] = accept(source, settled);
519
+ return draft;
520
+ });
521
+ }
522
+ draft[source] = accept(source, result);
523
+ return draft;
524
+ };
525
+ var bodyFill = (schema) => (draft) => {
526
+ const media = mediaTypeOf(draft.req);
527
+ const parse = parserFor(media);
528
+ if (parse === undefined) {
529
+ throw new HttpError(HttpStatusCode.UNSUPPORTED_MEDIA_TYPE, `Unsupported content type "${media}". Declared bodies accept ` + "application/json, application/x-www-form-urlencoded, multipart/form-data or text/*.");
530
+ }
531
+ const read = parse === asJson && RawBody.wanted(draft.req) ? draft.req.text().then((text) => {
532
+ RawBody.record(draft.req, text);
533
+ return JSON.parse(text);
534
+ }) : parse(draft.req);
535
+ return read.then((value) => fillWith(draft, "body", schema, value), (error) => {
536
+ throw new HttpError(HttpStatusCode.BAD_REQUEST, `Malformed ${media} body`, { cause: error });
537
+ });
538
+ };
539
+ var searchOf = (url) => {
540
+ const start = url.indexOf("?");
541
+ if (start === -1)
542
+ return "";
543
+ const end = url.indexOf("#", start + 1);
544
+ return end === -1 ? url.slice(start + 1) : url.slice(start + 1, end);
545
+ };
546
+ var queryFill = (schema) => (draft) => {
547
+ const params = new URLSearchParams(searchOf(draft.req.url));
548
+ return fillWith(draft, "query", schema, grouped(params));
549
+ };
550
+ var paramsFill = (schema) => (draft) => fillWith(draft, "params", schema, draft.req.params);
551
+ var then = (first, second) => (draft) => {
552
+ const started = first(draft);
553
+ return started instanceof Promise ? started.then(second) : second(started);
554
+ };
555
+ var buildInputReader = (options) => {
556
+ const fills = [];
557
+ if (options?.body !== undefined)
558
+ fills.push(bodyFill(options.body));
559
+ if (options?.query !== undefined)
560
+ fills.push(queryFill(options.query));
561
+ if (options?.params !== undefined)
562
+ fills.push(paramsFill(options.params));
563
+ if (fills.length === 0)
564
+ return (req) => ({ req });
565
+ const fill = fills.reduce(then);
566
+ return (req) => fill({ req });
567
+ };
568
+
569
+ // src/server/request-id.ts
570
+ var REQUEST_ID_HEADER = "x-request-id";
571
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
572
+ var traceId = (inbound) => inbound !== null && inbound.length === 36 && UUID.test(inbound) ? inbound : crypto.randomUUID();
573
+ var ID = Symbol.for("dunx.http.requestId");
574
+
575
+ class RequestIds {
576
+ static assign(req) {
577
+ const id = traceId(req.headers.get(REQUEST_ID_HEADER));
578
+ req[ID] = id;
579
+ return id;
580
+ }
581
+ static stamp(response, req) {
582
+ const id = req[ID];
583
+ if (id !== undefined)
584
+ response.headers.set(REQUEST_ID_HEADER, id);
585
+ return response;
586
+ }
587
+ }
588
+
589
+ // src/server/routes.ts
590
+ var construct = (guard) => new guard;
591
+ var toResponse = (value, status) => {
592
+ if (value instanceof Response)
593
+ return value;
594
+ if (value === undefined || value === null) {
595
+ return new Response(null, { status: HttpStatusCode.NO_CONTENT });
596
+ }
597
+ return Response.json(value, { status });
598
+ };
599
+ var statusFor = (route) => route.options?.status ?? defaultStatusFor(route.method);
600
+ var assertNoCollisions = (discovered) => {
601
+ const owners = new Map;
602
+ for (const route of discovered) {
603
+ const key = `${route.method} ${route.path}`;
604
+ const owner = `${route.controller}.${route.handlerName}`;
605
+ const existing = owners.get(key);
606
+ if (existing !== undefined) {
607
+ throw new AppError3(`Route collision: ${key} is declared by ${existing} and by ${owner}. ` + "Bun would keep only one of them.");
608
+ }
609
+ owners.set(key, owner);
610
+ }
611
+ };
612
+ var assertNoGatewayCollisions = (discovered, gatewayPaths) => {
613
+ const gateways = new Set(gatewayPaths);
614
+ for (const route of discovered) {
615
+ if (gateways.has(route.path)) {
616
+ throw new AppError3(`Gateway path collision: ${route.path} is served by a gateway and by ` + `${route.controller}.${route.handlerName}(). The upgrade is a route too, ` + "so one of them would be dropped.");
617
+ }
618
+ }
619
+ };
620
+ var withUpgradeRoutes = (routes, gateways) => {
621
+ const merged = { ...routes };
622
+ for (const [path, upgrade] of gateways)
623
+ merged[path] = { GET: upgrade };
624
+ return merged;
625
+ };
626
+ var unmatchedContext = (req, isPublic) => Object.freeze({
627
+ controller: "(unmatched)",
628
+ handler: "(none)",
629
+ method: req.method,
630
+ path: new URL(req.url).pathname,
631
+ parsesBody: false,
632
+ get: (key) => {
633
+ if (key.id === UNMATCHED.id)
634
+ return true;
635
+ if (key.id === PUBLIC.id && isPublic)
636
+ return true;
637
+ return;
638
+ }
639
+ });
640
+ var buildFallback = (middleware = [], onError = defaultErrorMapper, cors, notFound = "guarded") => {
641
+ const miss = () => {
642
+ throw new HttpError(HttpStatusCode.NOT_FOUND, "NOT_FOUND");
643
+ };
644
+ const run = async (req) => {
645
+ try {
646
+ return await compose(middleware, unmatchedContext(req, notFound === "public"), miss)(req);
647
+ } catch (error) {
648
+ return RequestIds.stamp(onError(error, req), req);
649
+ }
650
+ };
651
+ return cors ? withCors(cors, run) : run;
652
+ };
653
+ var directOr = (guarded, route, read, status, onError, noMiddleware) => {
654
+ if (!noMiddleware)
655
+ return guarded;
656
+ const settle = (value, req) => {
657
+ try {
658
+ return toResponse(value, status);
659
+ } catch (error) {
660
+ return onError(error, req);
661
+ }
662
+ };
663
+ const invoke = (input, req) => {
664
+ try {
665
+ const value = route.handler(input);
666
+ return value instanceof Promise ? value.then((resolved) => settle(resolved, req), (error) => onError(error, req)) : settle(value, req);
667
+ } catch (error) {
668
+ return onError(error, req);
669
+ }
670
+ };
671
+ return (req) => {
672
+ try {
673
+ const input = read(req);
674
+ return input instanceof Promise ? input.then((resolved) => invoke(resolved, req), (error) => onError(error, req)) : invoke(input, req);
675
+ } catch (error) {
676
+ return onError(error, req);
677
+ }
678
+ };
679
+ };
680
+ var buildRoutes = (discovered, middleware = [], onError = defaultErrorMapper, cors, resolve = construct) => {
681
+ assertNoCollisions(discovered);
682
+ const routes = {};
683
+ const instances = new Map;
684
+ const guardOf = (guard, from) => {
685
+ const existing = instances.get(guard);
686
+ if (existing)
687
+ return existing;
688
+ const created = resolve(guard, from);
689
+ instances.set(guard, created);
690
+ return created;
691
+ };
692
+ for (const route of discovered) {
693
+ const read = buildInputReader(route.options);
694
+ const status = statusFor(route);
695
+ const chain = [
696
+ ...middleware,
697
+ ...(route.moduleMiddleware ?? []).map((entry) => guardOf(entry, route.module)),
698
+ ...(route.guards ?? []).map((guard) => guardOf(guard, route.module))
699
+ ];
700
+ const chained = compose(chain, buildContext(route), async (req) => toResponse(await route.handler(await read(req)), status));
701
+ const guarded = async (req) => {
702
+ try {
703
+ return await chained(req);
704
+ } catch (error) {
705
+ return RequestIds.stamp(onError(error, req), req);
706
+ }
707
+ };
708
+ const byMethod = routes[route.path] ??= {};
709
+ byMethod[route.method] = cors ? withCors(cors, guarded) : directOr(guarded, route, read, status, onError, chain.length === 0);
710
+ }
711
+ if (cors) {
712
+ for (const byMethod of Object.values(routes)) {
713
+ byMethod.OPTIONS = preflight(cors, Object.keys(byMethod));
714
+ }
715
+ }
716
+ return routes;
717
+ };
718
+ // src/static/options.ts
719
+ class StaticOptions {
720
+ root;
721
+ path;
722
+ maxAge;
723
+ immutable;
724
+ constructor(init) {
725
+ this.root = init.root;
726
+ this.path = normalizePrefix(init.path ?? "/");
727
+ this.maxAge = init.maxAge ?? 60;
728
+ this.immutable = init.immutable ?? (() => false);
729
+ }
730
+ }
731
+ Object.defineProperty(StaticOptions, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "init: StaticOptionsInit" }] });
732
+ var normalizePrefix = (path) => {
733
+ const trimmed = path.split("/").filter(Boolean).join("/");
734
+ return trimmed === "" ? "/" : `/${trimmed}`;
735
+ };
736
+ // src/compression/negotiate.ts
737
+ var quality = (params) => {
738
+ for (const param of params) {
739
+ const [key, value] = param.split("=");
740
+ if (key?.trim().toLowerCase() !== "q")
741
+ continue;
742
+ const q = Number.parseFloat(value ?? "");
743
+ return Number.isFinite(q) && q >= 0 && q <= 1 ? q : 1;
744
+ }
745
+ return 1;
746
+ };
747
+ var negotiate = (header, offered) => {
748
+ if (header === null)
749
+ return;
750
+ const accepted = new Map;
751
+ for (const element of header.split(",")) {
752
+ const [name, ...params] = element.split(";");
753
+ const token = name?.trim().toLowerCase();
754
+ if (token === undefined || token === "")
755
+ continue;
756
+ accepted.set(token, quality(params));
757
+ }
758
+ const wildcard = accepted.get("*");
759
+ let best;
760
+ let bestQuality = 0;
761
+ for (const encoding of offered) {
762
+ const q = accepted.get(encoding) ?? wildcard ?? 0;
763
+ if (q > bestQuality) {
764
+ best = encoding;
765
+ bestQuality = q;
766
+ }
767
+ }
768
+ return best;
769
+ };
770
+ // src/compression/options.ts
771
+ var CompressionEncoding = Object.freeze({
772
+ ZSTD: "zstd",
773
+ GZIP: "gzip"
774
+ });
775
+ var COMPRESSIBLE = new Set([
776
+ "application/graphql",
777
+ "application/graphql-response+json",
778
+ "application/javascript",
779
+ "application/json",
780
+ "application/manifest+json",
781
+ "application/wasm",
782
+ "application/x-javascript",
783
+ "application/x-ndjson",
784
+ "application/xml",
785
+ "image/svg+xml"
786
+ ]);
787
+ var isCompressibleType = (contentType) => {
788
+ if (contentType === null)
789
+ return false;
790
+ const type = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
791
+ if (type.startsWith("text/"))
792
+ return true;
793
+ if (type.endsWith("+json") || type.endsWith("+xml"))
794
+ return true;
795
+ return COMPRESSIBLE.has(type);
796
+ };
797
+ var encodable = (encoding) => {
798
+ const sync = encoding === CompressionEncoding.ZSTD ? Bun.zstdCompressSync : Bun.gzipSync;
799
+ if (typeof sync !== "function")
800
+ return false;
801
+ try {
802
+ new CompressionStream(encoding);
803
+ return true;
804
+ } catch {
805
+ return false;
806
+ }
807
+ };
808
+
809
+ class CompressionOptions {
810
+ encodings;
811
+ threshold;
812
+ filter;
813
+ constructor(init = {}) {
814
+ this.encodings = init.encodings ?? [
815
+ CompressionEncoding.ZSTD,
816
+ CompressionEncoding.GZIP
817
+ ];
818
+ const missing = this.encodings.filter((encoding) => !encodable(encoding));
819
+ if (missing.length > 0) {
820
+ throw new Error(`Bun ${Bun.version} cannot encode ${missing.join(", ")}. ` + "Pass `encodings` without it, or upgrade Bun.");
821
+ }
822
+ this.threshold = init.threshold ?? 1024;
823
+ this.filter = init.filter ?? isCompressibleType;
824
+ }
825
+ }
826
+ Object.defineProperty(CompressionOptions, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "init: CompressionOptionsInit = {}", optional: true }] });
827
+ // src/ws/envelope.ts
828
+ var encode = (event, data) => JSON.stringify({ event, data });
829
+ var decode = (message) => {
830
+ if (typeof message !== "string")
831
+ return;
832
+ let parsed;
833
+ try {
834
+ parsed = JSON.parse(message);
835
+ } catch {
836
+ return;
837
+ }
838
+ if (typeof parsed !== "object" || parsed === null)
839
+ return;
840
+ const { event, data } = parsed;
841
+ return typeof event === "string" ? { event, data } : undefined;
842
+ };
843
+
844
+ // src/ws/middleware.ts
845
+ var composeSocket = (middleware, ctx) => middleware.reduceRight((next, current) => (frame, run) => current.handle(frame, ctx, () => next(frame, run)), (_frame, run) => run());
846
+ var observe = (next, done) => {
847
+ let result;
848
+ try {
849
+ result = next();
850
+ } catch (error) {
851
+ done(error, undefined);
852
+ throw error;
853
+ }
854
+ if (result instanceof Promise) {
855
+ return result.then((value) => {
856
+ done(undefined, value);
857
+ return value;
858
+ }, (error) => {
859
+ done(error, undefined);
860
+ throw error;
861
+ });
862
+ }
863
+ done(undefined, result);
864
+ return result;
865
+ };
866
+
867
+ // src/ws/runtime.ts
868
+ import { AppError as AppError4 } from "@dunx/core";
869
+ var slotOf = (handler) => handler.kind === HandlerKind.MESSAGE && handler.event !== undefined ? `message ${JSON.stringify(handler.event)}` : handler.kind;
870
+ var buildRuntime = (gateway) => {
871
+ if (gateway.handlers.length === 0) {
872
+ throw new AppError4(`${gateway.name} is registered as a gateway but declares no handlers. ` + "Add an @OnMessage/@OnOpen/... method, or drop the @Gateway decorator.");
873
+ }
874
+ const owners = new Map;
875
+ const events = new Map;
876
+ for (const handler of gateway.handlers) {
877
+ const slot = slotOf(handler);
878
+ const existing = owners.get(slot);
879
+ if (existing) {
880
+ throw new AppError4(`Handler collision in ${gateway.name}: ${slot} is claimed by ` + `${existing.method}() and by ${handler.method}(). One handler per event.`);
881
+ }
882
+ owners.set(slot, handler);
883
+ if (handler.kind === HandlerKind.MESSAGE && handler.event !== undefined) {
884
+ events.set(handler.event, handler.invoke);
885
+ }
886
+ }
887
+ const at = (slot) => owners.get(slot)?.invoke;
888
+ return {
889
+ name: gateway.name,
890
+ path: gateway.path,
891
+ upgrade: at(HandlerKind.UPGRADE),
892
+ open: at(HandlerKind.OPEN),
893
+ close: at(HandlerKind.CLOSE),
894
+ drain: at(HandlerKind.DRAIN),
895
+ ping: at(HandlerKind.PING),
896
+ pong: at(HandlerKind.PONG),
897
+ raw: at(HandlerKind.MESSAGE),
898
+ events
899
+ };
900
+ };
901
+ var buildGateways = (discovered) => {
902
+ const byPath = new Map;
903
+ for (const gateway of discovered) {
904
+ const existing = byPath.get(gateway.path);
905
+ if (existing) {
906
+ throw new AppError4(`Gateway path collision: ${gateway.path} is served by ${existing.name} ` + `and by ${gateway.name}. One gateway per path.`);
907
+ }
908
+ byPath.set(gateway.path, buildRuntime(gateway));
909
+ }
910
+ return byPath;
911
+ };
912
+ var someHandler = (gateways, pick) => {
913
+ for (const gateway of gateways)
914
+ if (pick(gateway) !== undefined)
915
+ return true;
916
+ return false;
917
+ };
918
+
919
+ // src/ws/adapter.ts
920
+ var RUNTIME = Symbol.for("dunx.ws.runtime");
921
+ var UNCLAIMED = Symbol.for("dunx.ws.unclaimed");
922
+ var defaultOnError = (error, socket) => {
923
+ console.error(`[dunx/http] ${socket.data.path} handler failed:`, error);
924
+ };
925
+ var reportedByMiddleware = () => {
926
+ return;
927
+ };
928
+ var unreported = (middleware) => "Socket middleware is installed and none of it sets reportsErrors, so a " + "throwing gateway handler is reported nowhere: the console fallback is off " + "whenever middleware wraps the handler. Set reportsErrors on the one that " + "records a failure, or pass websocket.onError. Installed: " + `${middleware.map((entry) => entry.constructor.name).join(", ")}.`;
929
+ var runtimeOf = (socket) => socket.data[RUNTIME];
930
+ var isBinary = (value) => value instanceof ArrayBuffer || ArrayBuffer.isView(value);
931
+ var replyRaw = (socket, value) => {
932
+ if (value === undefined)
933
+ return;
934
+ socket.send(typeof value === "string" || isBinary(value) ? value : JSON.stringify(value));
935
+ };
936
+ var settle = (result, socket, onError, then2) => {
937
+ if (result instanceof Promise) {
938
+ result.then((value) => {
939
+ if (!then2)
940
+ return;
941
+ try {
942
+ then2(value);
943
+ } catch (error) {
944
+ onError(error, socket);
945
+ }
946
+ }, (error) => onError(error, socket));
947
+ return;
948
+ }
949
+ if (then2)
950
+ then2(result);
951
+ };
952
+ var framing = (kind) => {
953
+ if (kind === HandlerKind.CLOSE) {
954
+ return (args) => ({
955
+ socket: args[0],
956
+ data: { code: args[1], reason: args[2] }
957
+ });
958
+ }
959
+ if (kind === HandlerKind.OPEN || kind === HandlerKind.DRAIN) {
960
+ return (args) => ({ socket: args[0], data: undefined });
961
+ }
962
+ return (args) => ({ socket: args[1], data: args[0] });
963
+ };
964
+ var NOTHING = () => {
965
+ return;
966
+ };
967
+ var through = (gateway, middleware, kind, event, invoke) => {
968
+ const ctx = {
969
+ gateway: gateway.name,
970
+ path: gateway.path,
971
+ kind,
972
+ event
973
+ };
974
+ const dispatch = composeSocket(middleware, ctx);
975
+ const frameOf = framing(kind);
976
+ const run = invoke ?? NOTHING;
977
+ return (...args) => dispatch(frameOf(args), () => run(...args));
978
+ };
979
+ var withMiddleware = (gateway, middleware) => {
980
+ const wrap = (kind, event, invoke) => through(gateway, middleware, kind, event, invoke);
981
+ const optional = (kind, invoke) => invoke === undefined ? undefined : wrap(kind, undefined, invoke);
982
+ return {
983
+ ...gateway,
984
+ open: wrap(HandlerKind.OPEN, undefined, gateway.open),
985
+ close: wrap(HandlerKind.CLOSE, undefined, gateway.close),
986
+ drain: optional(HandlerKind.DRAIN, gateway.drain),
987
+ ping: optional(HandlerKind.PING, gateway.ping),
988
+ pong: optional(HandlerKind.PONG, gateway.pong),
989
+ raw: optional(HandlerKind.MESSAGE, gateway.raw),
990
+ events: new Map([...gateway.events].map(([event, invoke]) => [
991
+ event,
992
+ wrap(HandlerKind.MESSAGE, event, invoke)
993
+ ]))
994
+ };
995
+ };
996
+ var unclaimedDispatch = (gateway, middleware) => (frame, event) => composeSocket(middleware, {
997
+ gateway: gateway.name,
998
+ path: gateway.path,
999
+ kind: HandlerKind.MESSAGE,
1000
+ event
1001
+ })(frame, () => {
1002
+ return;
1003
+ });
1004
+ var buildWebSocket = (discovered, options = {}, middleware = []) => {
1005
+ const byPath = buildGateways(discovered);
1006
+ const wrapped = middleware.length === 0 ? byPath : new Map([...byPath].map(([path, gateway]) => [
1007
+ path,
1008
+ withMiddleware(gateway, middleware)
1009
+ ]));
1010
+ const gateways = [...wrapped.values()];
1011
+ const onError = options.onError ?? (middleware.length === 0 ? defaultOnError : reportedByMiddleware);
1012
+ const reports = options.onError !== undefined || middleware.some((entry) => entry.reportsErrors === true);
1013
+ const { onError: _onError, ...socketOptions } = options;
1014
+ const run = (invoke, args, ws, then2) => {
1015
+ try {
1016
+ settle(invoke(...args), ws, onError, then2);
1017
+ } catch (error) {
1018
+ onError(error, ws);
1019
+ }
1020
+ };
1021
+ const websocket = {
1022
+ ...socketOptions,
1023
+ message(ws, message) {
1024
+ const gateway = runtimeOf(ws);
1025
+ let event;
1026
+ if (gateway.events.size > 0) {
1027
+ const envelope = decode(message);
1028
+ const handler = envelope && gateway.events.get(envelope.event);
1029
+ if (envelope && handler) {
1030
+ run(handler, [envelope.data, ws], ws, (value) => {
1031
+ if (value !== undefined)
1032
+ ws.send(encode(envelope.event, value));
1033
+ });
1034
+ return;
1035
+ }
1036
+ event = envelope?.event;
1037
+ }
1038
+ if (gateway.raw) {
1039
+ run(gateway.raw, [message, ws], ws, (value) => replyRaw(ws, value));
1040
+ return;
1041
+ }
1042
+ const unclaimed2 = ws.data[UNCLAIMED];
1043
+ if (!unclaimed2)
1044
+ return;
1045
+ try {
1046
+ settle(unclaimed2({ socket: ws, data: message }, event), ws, onError, undefined);
1047
+ } catch (error) {
1048
+ onError(error, ws);
1049
+ }
1050
+ },
1051
+ ...someHandler(gateways, (g) => g.open) && {
1052
+ open(ws) {
1053
+ const { open } = runtimeOf(ws);
1054
+ if (open)
1055
+ run(open, [ws], ws, undefined);
1056
+ }
1057
+ },
1058
+ ...someHandler(gateways, (g) => g.close) && {
1059
+ close(ws, code, reason) {
1060
+ const { close } = runtimeOf(ws);
1061
+ if (close)
1062
+ run(close, [ws, code, reason], ws, undefined);
1063
+ }
1064
+ },
1065
+ ...someHandler(gateways, (g) => g.drain) && {
1066
+ drain(ws) {
1067
+ const { drain } = runtimeOf(ws);
1068
+ if (drain)
1069
+ run(drain, [ws], ws, undefined);
1070
+ }
1071
+ },
1072
+ ...someHandler(gateways, (g) => g.ping) && {
1073
+ ping(ws, data) {
1074
+ const { ping } = runtimeOf(ws);
1075
+ if (ping)
1076
+ run(ping, [data, ws], ws, undefined);
1077
+ }
1078
+ },
1079
+ ...someHandler(gateways, (g) => g.pong) && {
1080
+ pong(ws, data) {
1081
+ const { pong } = runtimeOf(ws);
1082
+ if (pong)
1083
+ run(pong, [data, ws], ws, undefined);
1084
+ }
1085
+ }
1086
+ };
1087
+ const unclaimed = new Map(middleware.length === 0 ? [] : gateways.map((gateway) => [
1088
+ gateway,
1089
+ unclaimedDispatch(gateway, middleware)
1090
+ ]));
1091
+ const accept2 = (req, server, gateway, context) => {
1092
+ const fallback = unclaimed.get(gateway);
1093
+ const data = {
1094
+ path: gateway.path,
1095
+ context,
1096
+ id: crypto.randomUUID(),
1097
+ [RUNTIME]: gateway,
1098
+ ...fallback === undefined ? {} : { [UNCLAIMED]: fallback }
1099
+ };
1100
+ return server.upgrade(req, { data }) ? undefined : new Response("Expected a WebSocket upgrade", { status: 426 });
1101
+ };
1102
+ const upgradeHandler = (gateway) => (req, server) => {
1103
+ if (!gateway.upgrade)
1104
+ return accept2(req, server, gateway, undefined);
1105
+ const result = gateway.upgrade(req);
1106
+ if (result instanceof Promise) {
1107
+ return result.then((value) => value instanceof Response ? value : accept2(req, server, gateway, value));
1108
+ }
1109
+ return result instanceof Response ? result : accept2(req, server, gateway, result);
1110
+ };
1111
+ return {
1112
+ websocket,
1113
+ routes: new Map(gateways.map((gateway) => [gateway.path, upgradeHandler(gateway)])),
1114
+ paths: [...byPath.keys()],
1115
+ warnings: middleware.length > 0 && !reports ? [unreported(middleware)] : [],
1116
+ gateways: gateways.map((gateway) => ({
1117
+ name: gateway.name,
1118
+ path: gateway.path,
1119
+ events: [...gateway.events.keys()]
1120
+ }))
1121
+ };
1122
+ };
1123
+ // src/ws/redis-relay.ts
1124
+ import { AppError as AppError5 } from "@dunx/core";
1125
+ var PROTOCOLS = [
1126
+ "redis:",
1127
+ "rediss:",
1128
+ "valkey:",
1129
+ "valkeys:",
1130
+ "redis+tls:",
1131
+ "redis+unix:",
1132
+ "redis+tls+unix:"
1133
+ ];
1134
+ var defaultRelayUrl = () => process.env["VALKEY_URL"] ?? process.env["REDIS_URL"] ?? "redis://localhost:6379";
1135
+ var assertUrl = (url) => {
1136
+ let parsed;
1137
+ try {
1138
+ parsed = new URL(url);
1139
+ } catch {
1140
+ throw new AppError5(`${JSON.stringify(url)} is not a valid URL for the websocket relay. ` + "Expected something like redis://localhost:6379.");
1141
+ }
1142
+ if (!PROTOCOLS.includes(parsed.protocol)) {
1143
+ throw new AppError5(`Unsupported protocol ${JSON.stringify(parsed.protocol)} in ` + `${JSON.stringify(url)}. Expected one of ${PROTOCOLS.join(", ")}.`);
1144
+ }
1145
+ return url;
1146
+ };
1147
+
1148
+ class RedisRelay {
1149
+ #url;
1150
+ #options;
1151
+ #pub;
1152
+ #sub;
1153
+ #channel;
1154
+ constructor(options = {}) {
1155
+ this.#url = assertUrl(options.url ?? defaultRelayUrl());
1156
+ this.#options = {
1157
+ maxRetries: options.maxRetries ?? 0,
1158
+ ...options.connectionTimeout !== undefined && {
1159
+ connectionTimeout: options.connectionTimeout
1160
+ },
1161
+ ...options.tls !== undefined && { tls: options.tls }
1162
+ };
1163
+ }
1164
+ get url() {
1165
+ const parsed = new URL(this.#url);
1166
+ if (parsed.password)
1167
+ parsed.password = "***";
1168
+ return parsed.toString();
1169
+ }
1170
+ async publish(channel, message) {
1171
+ const client = this.#pub ??= new Bun.RedisClient(this.#url, this.#options);
1172
+ try {
1173
+ return await client.publish(channel, message);
1174
+ } catch (error) {
1175
+ if (this.#pub === client) {
1176
+ this.#pub = undefined;
1177
+ client.close();
1178
+ }
1179
+ throw error;
1180
+ }
1181
+ }
1182
+ async subscribe(channel, listener) {
1183
+ const client = this.#sub ??= new Bun.RedisClient(this.#url, this.#options);
1184
+ try {
1185
+ await client.connect();
1186
+ await client.subscribe(channel, listener);
1187
+ this.#channel = channel;
1188
+ } catch (error) {
1189
+ if (this.#sub === client) {
1190
+ this.#sub = undefined;
1191
+ client.close();
1192
+ }
1193
+ throw error;
1194
+ }
1195
+ }
1196
+ async close() {
1197
+ const sub = this.#sub;
1198
+ const channel = this.#channel;
1199
+ this.#pub?.close();
1200
+ this.#pub = undefined;
1201
+ this.#sub = undefined;
1202
+ this.#channel = undefined;
1203
+ if (!sub)
1204
+ return;
1205
+ if (channel !== undefined) {
1206
+ try {
1207
+ await sub.unsubscribe(channel);
1208
+ } catch {}
1209
+ }
1210
+ sub.close();
1211
+ }
1212
+ }
1213
+ Object.defineProperty(RedisRelay, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "options: RedisRelayOptions = {}", optional: true }] });
1214
+ // src/ws/relay.ts
1215
+ var DEFAULT_RELAY_CHANNEL = "dunx:ws";
1216
+ var defaultRelayError = (error, phase) => {
1217
+ console.warn(`[dunx/http] the websocket relay could not ${phase}. Fan-out is local to ` + "this process until it recovers:", error);
1218
+ };
1219
+ var toBytes = (data) => ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
1220
+ var encodeRelay = (origin, topic, data) => typeof data === "string" ? JSON.stringify({ o: origin, t: topic, d: data }) : JSON.stringify({
1221
+ o: origin,
1222
+ t: topic,
1223
+ d: Buffer.from(toBytes(data)).toString("base64"),
1224
+ b: 1
1225
+ });
1226
+ var decodeRelay = (message) => {
1227
+ let parsed;
1228
+ try {
1229
+ parsed = JSON.parse(message);
1230
+ } catch {
1231
+ return;
1232
+ }
1233
+ if (typeof parsed !== "object" || parsed === null)
1234
+ return;
1235
+ const { o, t, d, b } = parsed;
1236
+ if (typeof o !== "string" || typeof t !== "string" || typeof d !== "string") {
1237
+ return;
1238
+ }
1239
+ return { origin: o, topic: t, data: b ? Buffer.from(d, "base64") : d };
1240
+ };
1241
+ // src/health/controller.ts
1242
+ import { inject } from "@dunx/core";
1243
+
1244
+ // src/route/decorators.ts
1245
+ var Controller = (prefix = "") => (target) => {
1246
+ markController(target, prefix);
1247
+ return target;
1248
+ };
1249
+ var verb = (method) => (path = "/", options) => (value, _context) => {
1250
+ markRoute(value, { method, path, options });
1251
+ return value;
1252
+ };
1253
+ var Get = verb("GET");
1254
+ var Post = verb("POST");
1255
+ var Put = verb("PUT");
1256
+ var Patch = verb("PATCH");
1257
+ var Delete = verb("DELETE");
1258
+
1259
+ // src/health/report-schema.ts
1260
+ var state = {
1261
+ type: "string",
1262
+ enum: ["up", "down", "unknown"],
1263
+ description: "`unknown` is not `down`: a probe that timed out has told you nothing."
1264
+ };
1265
+ var HEALTH_REPORT_SCHEMA = Object.freeze({
1266
+ $id: "HealthReport",
1267
+ type: "object",
1268
+ description: "What the probe found. `up` answers 200 and anything else answers 503.",
1269
+ properties: {
1270
+ status: state,
1271
+ draining: {
1272
+ type: "boolean",
1273
+ description: "The process is shutting down, or something holds it out."
1274
+ },
1275
+ uptimeMs: {
1276
+ type: "integer",
1277
+ description: "Measured on a monotonic clock, so it never goes backwards."
1278
+ },
1279
+ checks: {
1280
+ type: "array",
1281
+ items: {
1282
+ type: "object",
1283
+ properties: {
1284
+ name: { type: "string" },
1285
+ state,
1286
+ critical: {
1287
+ type: "boolean",
1288
+ description: "A failure here sheds traffic. Memory and disk do not."
1289
+ },
1290
+ ms: { type: "integer", description: "How long the check took." },
1291
+ detail: {
1292
+ type: "string",
1293
+ description: "A latency, a version, or a failure message."
1294
+ }
1295
+ },
1296
+ required: ["name", "state", "critical", "ms"]
1297
+ }
1298
+ }
1299
+ },
1300
+ required: ["status", "draining", "uptimeMs", "checks"]
1301
+ });
1302
+
1303
+ // src/health/registry.ts
1304
+ var bounded = async (indicator, timeoutMs) => {
1305
+ let timer;
1306
+ const timeout = new Promise((resolve) => {
1307
+ timer = setTimeout(() => resolve({ state: "unknown", detail: `no answer in ${timeoutMs} ms` }), timeoutMs);
1308
+ timer.unref?.();
1309
+ });
1310
+ try {
1311
+ return await Promise.race([
1312
+ Promise.resolve().then(() => indicator.check()).catch((error) => ({
1313
+ state: "down",
1314
+ detail: error instanceof Error ? error.message : String(error)
1315
+ })),
1316
+ timeout
1317
+ ]);
1318
+ } finally {
1319
+ if (timer)
1320
+ clearTimeout(timer);
1321
+ }
1322
+ };
1323
+ var worst = (checks) => {
1324
+ const critical = checks.filter((check) => check.critical);
1325
+ if (critical.some((check) => check.state === "down"))
1326
+ return "down";
1327
+ if (critical.some((check) => check.state === "unknown"))
1328
+ return "unknown";
1329
+ return "up";
1330
+ };
1331
+
1332
+ class HealthOptions {
1333
+ liveness;
1334
+ readiness;
1335
+ timeoutMs;
1336
+ routes;
1337
+ documented;
1338
+ drainDelayMs;
1339
+ constructor(init = {}) {
1340
+ this.liveness = init.liveness ?? [];
1341
+ this.readiness = init.readiness ?? [];
1342
+ this.timeoutMs = init.timeoutMs ?? 2000;
1343
+ this.routes = init.routes ?? true;
1344
+ this.documented = init.documented ?? true;
1345
+ this.drainDelayMs = Math.max(0, init.drainDelayMs ?? 0);
1346
+ }
1347
+ }
1348
+ Object.defineProperty(HealthOptions, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "init: HealthOptionsInit = {}", optional: true }] });
1349
+
1350
+ class HealthRegistry {
1351
+ options;
1352
+ readiness_;
1353
+ #startedAt = performance.now();
1354
+ constructor(options, readiness_) {
1355
+ this.options = options;
1356
+ this.readiness_ = readiness_;
1357
+ }
1358
+ async report(indicators) {
1359
+ const checks = await Promise.all(indicators.map(async (indicator) => {
1360
+ const started = performance.now();
1361
+ const result = await bounded(indicator, this.options.timeoutMs);
1362
+ return {
1363
+ name: indicator.name,
1364
+ state: result.state,
1365
+ critical: indicator.critical,
1366
+ ms: Math.round(performance.now() - started),
1367
+ ...result.detail === undefined ? {} : { detail: result.detail }
1368
+ };
1369
+ }));
1370
+ return {
1371
+ status: worst(checks),
1372
+ draining: this.readiness_.draining,
1373
+ uptimeMs: Math.round(performance.now() - this.#startedAt),
1374
+ checks
1375
+ };
1376
+ }
1377
+ liveness() {
1378
+ return this.report(this.options.liveness);
1379
+ }
1380
+ async readiness() {
1381
+ const report = await this.report(this.options.readiness);
1382
+ if (!this.readiness_.draining)
1383
+ return report;
1384
+ return {
1385
+ ...report,
1386
+ status: "down",
1387
+ checks: [
1388
+ {
1389
+ name: "readiness",
1390
+ state: "down",
1391
+ critical: true,
1392
+ ms: 0,
1393
+ detail: this.readiness_.reason ?? "not accepting traffic"
1394
+ },
1395
+ ...report.checks
1396
+ ]
1397
+ };
1398
+ }
1399
+ }
1400
+ Object.defineProperty(HealthRegistry, Symbol.for("dunx.deps"), { value: () => [HealthOptions, { unresolved: "private readonly readiness_: Readiness", typeOnly: "Readiness" }] });
1401
+
1402
+ // src/health/controller.ts
1403
+ var probeResponses = {
1404
+ response: { 200: HEALTH_REPORT_SCHEMA, 503: HEALTH_REPORT_SCHEMA }
1405
+ };
1406
+ var answer = (report) => Response.json(report, { status: report.status === "up" ? 200 : 503 });
1407
+ var _dec = [
1408
+ Controller("health")
1409
+ ];
1410
+ var _dec2 = [
1411
+ Public(),
1412
+ Get("/live", probeResponses)
1413
+ ];
1414
+ var _dec3 = [
1415
+ Public(),
1416
+ Get("/ready", probeResponses)
1417
+ ];
1418
+ var _health = new WeakMap;
1419
+ var _init = __decoratorStart(undefined);
1420
+
1421
+ class HealthController {
1422
+ constructor() {
1423
+ __privateAdd(this, _health, inject(HealthRegistry));
1424
+ __runInitializers(_init, 5, this);
1425
+ }
1426
+ async live() {
1427
+ return answer(await __privateGet(this, _health).liveness());
1428
+ }
1429
+ async ready() {
1430
+ return answer(await __privateGet(this, _health).readiness());
1431
+ }
1432
+ }
1433
+ __decorateElement(_init, 1, "live", _dec2, HealthController);
1434
+ __decorateElement(_init, 1, "ready", _dec3, HealthController);
1435
+ HealthController = __decorateElement(_init, 0, "HealthController", _dec, HealthController);
1436
+ __runInitializers(_init, 1, HealthController);
1437
+ __decoratorMetadata(_init, HealthController);
1438
+ let _HealthController = HealthController;
1439
+ var _dec = [
1440
+ ApiHidden()
1441
+ ];
1442
+ var _base = HealthController;
1443
+ var _init = __decoratorStart(_base);
1444
+
1445
+ class HiddenHealthController extends _base {
1446
+ }
1447
+ HiddenHealthController = __decorateElement(_init, 0, "HiddenHealthController", _dec, HiddenHealthController);
1448
+ __runInitializers(_init, 1, HiddenHealthController);
1449
+ __decoratorMetadata(_init, HiddenHealthController);
1450
+ let _HiddenHealthController = HiddenHealthController;
1451
+ // src/client/errors.ts
1452
+ import { AppError as AppError6 } from "@dunx/core";
1453
+
1454
+ class FetchError extends AppError6 {
1455
+ status;
1456
+ statusText;
1457
+ body;
1458
+ response;
1459
+ name = "FetchError";
1460
+ constructor(status, statusText, body, response) {
1461
+ super(`HTTP ${status} ${statusText} from ${response.method} ${response.url}`);
1462
+ this.status = status;
1463
+ this.statusText = statusText;
1464
+ this.body = body;
1465
+ this.response = response;
1466
+ }
1467
+ }
1468
+ Object.defineProperty(FetchError, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "readonly status: number" }, { unresolved: "readonly statusText: string" }, { unresolved: "readonly body: unknown" }, { unresolved: `readonly response: {
1469
+ readonly method: string;
1470
+ readonly url: string;
1471
+ readonly headers: Headers;
1472
+ }` }] });
1473
+
1474
+ class FetchTransportError extends AppError6 {
1475
+ response;
1476
+ aborted;
1477
+ name = "FetchTransportError";
1478
+ constructor(response, aborted, options) {
1479
+ super(`${response.method} ${response.url} failed: ${aborted ? "aborted" : "transport error"}`, options);
1480
+ this.response = response;
1481
+ this.aborted = aborted;
1482
+ }
1483
+ }
1484
+ Object.defineProperty(FetchTransportError, Symbol.for("dunx.deps"), { value: () => [{ unresolved: "readonly response: { readonly method: string; readonly url: string }" }, { unresolved: "readonly aborted: boolean" }, ErrorOptions] });
1485
+
1486
+ // src/client/retry.ts
1487
+ var uniform = () => {
1488
+ const buffer = new Uint32Array(1);
1489
+ crypto.getRandomValues(buffer);
1490
+ return (buffer[0] ?? 0) / 2 ** 32;
1491
+ };
1492
+ var backoffDelay = (attempt, { baseMs, power = 2, jitterMs = 1000, maxMs = 30000 }) => Math.min(baseMs * power ** attempt + uniform() * jitterMs, maxMs);
1493
+ var retryAfterMs = (headers, now = Date.now()) => {
1494
+ const header = headers.get("retry-after");
1495
+ if (header === null)
1496
+ return;
1497
+ const seconds = Number(header);
1498
+ if (Number.isFinite(seconds))
1499
+ return Math.max(0, seconds * 1000);
1500
+ const at = Date.parse(header);
1501
+ return Number.isNaN(at) ? undefined : Math.max(0, at - now);
1502
+ };
1503
+ var isRetryableStatus = (status) => status >= HttpStatusCode.INTERNAL_SERVER_ERROR || status === HttpStatusCode.REQUEST_TIMEOUT || status === HttpStatusCode.TOO_MANY_REQUESTS;
1504
+ var decide = (error, attempt, options) => {
1505
+ const {
1506
+ retryDelayMs = 1000,
1507
+ backoff,
1508
+ shouldRetryOnStatus = isRetryableStatus,
1509
+ respectRetryAfter = true
1510
+ } = options;
1511
+ const computed = backoffDelay(attempt, { baseMs: retryDelayMs, ...backoff });
1512
+ if (error instanceof FetchTransportError) {
1513
+ return { retry: !error.aborted, delayMs: computed };
1514
+ }
1515
+ if (error instanceof FetchError) {
1516
+ if (!shouldRetryOnStatus(error.status))
1517
+ return { retry: false, delayMs: 0 };
1518
+ const asked = respectRetryAfter ? retryAfterMs(error.response.headers) : undefined;
1519
+ const maxMs = backoff?.maxMs ?? 30000;
1520
+ return {
1521
+ retry: true,
1522
+ delayMs: asked === undefined ? computed : Math.min(asked, maxMs)
1523
+ };
1524
+ }
1525
+ return { retry: true, delayMs: computed };
1526
+ };
1527
+ var executeWithRetry = async (operation, options = {}) => {
1528
+ const { maxRetries = 3, onAttempt, onError, onSuccess } = options;
1529
+ let lastError;
1530
+ for (let attempt = 0;attempt <= maxRetries; attempt += 1) {
1531
+ onAttempt?.(attempt + 1, attempt > 0);
1532
+ try {
1533
+ const result = await operation();
1534
+ onSuccess?.(result, attempt + 1);
1535
+ return result;
1536
+ } catch (error) {
1537
+ lastError = error;
1538
+ const { retry, delayMs } = decide(error, attempt, options);
1539
+ const willRetry = retry && attempt < maxRetries;
1540
+ onError?.(error, attempt + 1, willRetry);
1541
+ if (!willRetry)
1542
+ throw error;
1543
+ await Bun.sleep(delayMs);
1544
+ }
1545
+ }
1546
+ throw lastError;
1547
+ };
1548
+ // src/client/json.ts
1549
+ var safeStringify = (value) => {
1550
+ const seen = new WeakSet;
1551
+ return JSON.stringify(value, (_key, entry) => {
1552
+ if (typeof entry === "object" && entry !== null) {
1553
+ if (seen.has(entry))
1554
+ return "[Circular]";
1555
+ seen.add(entry);
1556
+ }
1557
+ return entry;
1558
+ });
1559
+ };
1560
+ var isPlainObject = (value) => {
1561
+ if (typeof value !== "object" || value === null)
1562
+ return false;
1563
+ const proto = Object.getPrototypeOf(value);
1564
+ return proto === Object.prototype || proto === null;
1565
+ };
1566
+ var isJsonBody = (payload) => {
1567
+ if (payload === null || payload === undefined)
1568
+ return false;
1569
+ if (typeof payload !== "object")
1570
+ return typeof payload !== "string";
1571
+ return !(payload instanceof FormData || payload instanceof URLSearchParams || payload instanceof Blob || payload instanceof ArrayBuffer || payload instanceof ReadableStream || ArrayBuffer.isView(payload));
1572
+ };
1573
+ export { __decoratorStart, __decoratorMetadata, __runInitializers, __decorateElement, HttpStatusCode, defaultStatusFor, Controller, Get, Post, Put, Patch, Delete, metaKey, meta, ROLES, PUBLIC, HIDDEN, UNMATCHED, Roles, Public, ApiHidden, UseGuards, guardsOf, metaOf, mergeMeta, HttpError, ValidationError, ErrorFilter, isErrorFilter, toErrorMapper, errorMapper, defaultErrorMapper, joinPath, discoverRoutes, encode, decode, HandlerKind, markHandler, markGateway, isGateway, composeSocket, observe, buildRuntime, buildGateways, buildWebSocket, normalizePath, discoverGateway, discoverGateways, DEFAULT_RELAY_CHANNEL, defaultRelayError, encodeRelay, decodeRelay, RawBody, REQUEST_ID_HEADER, RequestIds, buildContext, withCors, preflight, compose, assertNoCollisions, assertNoGatewayCollisions, withUpgradeRoutes, buildFallback, buildRoutes, StaticOptions, normalizePrefix, negotiate, CompressionEncoding, isCompressibleType, CompressionOptions, defaultRelayUrl, RedisRelay, HEALTH_REPORT_SCHEMA, HealthOptions, HealthRegistry, HealthController, HiddenHealthController, routesOf, gatewaysOf, FetchError, FetchTransportError, backoffDelay, retryAfterMs, isRetryableStatus, executeWithRetry, safeStringify, isPlainObject, isJsonBody };