hoa 0.3.2 → 0.3.4

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.
@@ -0,0 +1,335 @@
1
+ const require_lib_utils = require('./lib/utils.cjs');
2
+
3
+ //#region src/response.js
4
+ /**
5
+ * @typedef {Object} ResJSON
6
+ * @property {number} status - Response status code
7
+ * @property {string} statusText - Response status text
8
+ * @property {Record<string, string|string[]>} headers - Response headers
9
+ */
10
+ /**
11
+ * @class HoaResponse
12
+ */
13
+ var HoaResponse = class {
14
+ /**
15
+ * Expose a plain object snapshot of response headers.
16
+ * Uses the Web Standard Headers API internally for proper header handling.
17
+ * Returns a plain object representation where header names are normalized.
18
+ *
19
+ * @returns {Record<string, string>} Object with all response headers
20
+ * @public
21
+ */
22
+ get headers() {
23
+ this._headers = this._headers || new Headers();
24
+ return Object.fromEntries(this._headers.entries());
25
+ }
26
+ /**
27
+ * Set the response headers.
28
+ * Accepts either a Headers object or a plain object/array of header entries.
29
+ * This replaces all existing headers with the new ones.
30
+ *
31
+ * @param {Headers|Record<string, string>|Array<[string, string]>} val - Headers to set
32
+ * @public
33
+ */
34
+ set headers(val) {
35
+ if (val instanceof Headers) this._headers = val;
36
+ else this._headers = new Headers(val);
37
+ }
38
+ /**
39
+ * Get a response header value by name (case-insensitive).
40
+ * Uses the Web Standard Headers API for proper header retrieval.
41
+ * Special-cases "referer/referrer" for compatibility.
42
+ * Returns null for empty or whitespace-only field names.
43
+ *
44
+ * @param {string} field - The header name
45
+ * @returns {string|null} The header value or null if not found
46
+ * @public
47
+ */
48
+ get(field) {
49
+ if (!field) return null;
50
+ this._headers = this._headers || new Headers();
51
+ switch (field = field.toLowerCase()) {
52
+ case "referer":
53
+ case "referrer": return this._headers.get("referrer") ?? this._headers.get("referer");
54
+ default: return this._headers.get(field);
55
+ }
56
+ }
57
+ /**
58
+ * Get all Set-Cookie header values as an array.
59
+ * Returns all Set-Cookie headers that will be sent with the response.
60
+ *
61
+ * @returns {string[]} Array of Set-Cookie header values
62
+ * @public
63
+ */
64
+ getSetCookie() {
65
+ this._headers = this._headers || new Headers();
66
+ return this._headers.getSetCookie();
67
+ }
68
+ /**
69
+ * Check if a response header is present.
70
+ * Uses the Web Standard Headers API for case-insensitive header checking.
71
+ *
72
+ * @param {string} field - The header name to check
73
+ * @returns {boolean} True if the header exists
74
+ * @public
75
+ */
76
+ has(field) {
77
+ if (!field) return false;
78
+ this._headers = this._headers || new Headers();
79
+ return this._headers.has(field);
80
+ }
81
+ /**
82
+ * Set response header(s) using the Web Standard Headers API.
83
+ * Accepts various input formats:
84
+ * - Single key/value pair
85
+ * - Plain object with multiple headers
86
+ * Replaces existing header values.
87
+ *
88
+ * @param {string|Record<string,string>} field - Header name or headers object
89
+ * @param {string} [val] - Header value when field is a string
90
+ * @public
91
+ */
92
+ set(field, val) {
93
+ if (!field) return;
94
+ this._headers = this._headers || new Headers();
95
+ if (typeof field === "string") this._headers.set(field, val);
96
+ else Object.keys(field).forEach((header) => this._headers.set(header, field[header]));
97
+ }
98
+ /**
99
+ * Append a response header value using the Web Standard Headers API.
100
+ * Does not replace existing values, but appends to them.
101
+ * This is useful for headers that can have multiple values like Set-Cookie.
102
+ *
103
+ * @param {string|Record<string,string>} field - The header name or headers object
104
+ * @param {string} [val] - The value to append when field is a string
105
+ * @public
106
+ */
107
+ append(field, val) {
108
+ if (!field) return;
109
+ this._headers = this._headers || new Headers();
110
+ if (typeof field === "string") this._headers.append(field, val);
111
+ else Object.keys(field).forEach((header) => this._headers.append(header, field[header]));
112
+ }
113
+ /**
114
+ * Delete a response header by name using the Web Standard Headers API.
115
+ * Header deletion is case-insensitive.
116
+ *
117
+ * @param {string} field - The header name to delete
118
+ * @public
119
+ */
120
+ delete(field) {
121
+ if (!field) return;
122
+ this._headers = this._headers || new Headers();
123
+ this._headers.delete(field);
124
+ }
125
+ /**
126
+ * Get the response status code.
127
+ * Defaults to 404 if not explicitly set.
128
+ *
129
+ * @returns {number} The HTTP status code
130
+ * @public
131
+ */
132
+ get status() {
133
+ return this._status || 404;
134
+ }
135
+ /**
136
+ * Set the response status code.
137
+ * Automatically clears body for status codes that should not have content.
138
+ *
139
+ * @param {number} val - The HTTP status code (100-599)
140
+ * @throws {TypeError}
141
+ * @public
142
+ */
143
+ set status(val) {
144
+ if (!Number.isInteger(val)) throw new TypeError("status code must be an integer");
145
+ if (val < 100 || val > 1e3) throw new TypeError(`invalid status code: ${val}`);
146
+ this._status = val;
147
+ this._explicitStatus = true;
148
+ if (!this._explicitStatusText) this._statusText = require_lib_utils.statusTextMapping[val];
149
+ if (this.body && require_lib_utils.statusEmptyMapping[val]) this.body = null;
150
+ }
151
+ /**
152
+ * Get the response status text.
153
+ *
154
+ * @returns {string} The statusText (e.g., 'OK', 'Not Found')
155
+ * @public
156
+ */
157
+ get statusText() {
158
+ if (this._explicitStatusText) return this._statusText;
159
+ return this._statusText || (this._statusText = require_lib_utils.statusTextMapping[this.status]);
160
+ }
161
+ /**
162
+ * Set a custom response status text.
163
+ *
164
+ * @param {string} val - The custom status text
165
+ * @public
166
+ */
167
+ set statusText(val) {
168
+ this._statusText = val;
169
+ this._explicitStatusText = true;
170
+ }
171
+ /**
172
+ * Get the response body.
173
+ *
174
+ * @returns {any} The response body content
175
+ * @public
176
+ */
177
+ get body() {
178
+ return this._body;
179
+ }
180
+ /**
181
+ * Set response body with automatic content-type detection.
182
+ * Supports various body types and automatically sets appropriate headers.
183
+ * When set to null/undefined, if current Content-Type is application/json,
184
+ * body becomes the literal string 'null'; otherwise status is set to 204 and
185
+ * Content-Type/Transfer-Encoding are removed.
186
+ *
187
+ * @param {string|Object|ReadableStream|Blob|Response|ArrayBuffer|TypedArray|FormData|URLSearchParams|null} val - The response body
188
+ * @public
189
+ */
190
+ set body(val) {
191
+ this._body = val;
192
+ if (val == null) {
193
+ if (!require_lib_utils.statusEmptyMapping[this.status]) {
194
+ if (this.type === "application/json") {
195
+ this._body = "null";
196
+ return;
197
+ }
198
+ this.status = 204;
199
+ }
200
+ if (val === null) this._explicitNullBody = true;
201
+ this.delete("Content-Type");
202
+ this.delete("Content-Length");
203
+ this.delete("Transfer-Encoding");
204
+ return;
205
+ }
206
+ if (!this._explicitStatus) this.status = 200;
207
+ const noType = !this.has("Content-Type");
208
+ if (typeof val === "string") {
209
+ if (noType) this.type = /^\s*</.test(val) ? "html" : "text";
210
+ return;
211
+ }
212
+ if (val instanceof Blob || val instanceof ArrayBuffer || ArrayBuffer.isView(val) || val instanceof ReadableStream) {
213
+ if (noType) if (val instanceof Blob && val.type) this.set("Content-Type", val.type);
214
+ else this.type = "bin";
215
+ return;
216
+ }
217
+ if (val instanceof FormData) return;
218
+ if (val instanceof URLSearchParams) {
219
+ if (noType) this.type = "form";
220
+ return;
221
+ }
222
+ if (val instanceof Response) {
223
+ if (noType) this.type = "bin";
224
+ this.status = val.status;
225
+ for (const [k, v] of val.headers) this.set(k, v);
226
+ return;
227
+ }
228
+ if (!this.type || !/\bjson\b/i.test(this.type)) this.type = "json";
229
+ }
230
+ /**
231
+ * Perform an HTTP redirect to the specified URL.
232
+ * Automatically sets the Location header and appropriate status code.
233
+ * Absolute URLs are normalized and Location value is URL-encoded.
234
+ *
235
+ * @param {string} url - The URL to redirect to (absolute or relative)
236
+ * @public
237
+ */
238
+ redirect(url) {
239
+ if (/^https?:\/\//i.test(url)) url = new URL(url).toString();
240
+ this.set("Location", require_lib_utils.encodeUrl(url));
241
+ if (!require_lib_utils.statusRedirectMapping[this.status]) this.status = 302;
242
+ this.type = "text";
243
+ this.body = `Redirecting to ${url}.`;
244
+ }
245
+ /**
246
+ * Perform a special-cased "back" redirect using the Referrer header.
247
+ * When Referrer is not present or unsafe, falls back to the provided alternative or "/".
248
+ * Only redirects to same-origin referrers for security.
249
+ * If referrer is an absolute URL with different origin or an invalid URL, falls back.
250
+ *
251
+ * @param {string} [alt='/'] - Alternative URL when referrer is unavailable or unsafe
252
+ * @public
253
+ */
254
+ back(alt) {
255
+ const referrer = this.req.get("Referrer");
256
+ if (referrer) {
257
+ if (referrer.startsWith("/")) {
258
+ this.redirect(referrer);
259
+ return;
260
+ }
261
+ if (new URL(referrer, this.req.href).origin === this.req.origin) {
262
+ this.redirect(referrer);
263
+ return;
264
+ }
265
+ }
266
+ this.redirect(alt || "/");
267
+ }
268
+ /**
269
+ * Get the response Content-Type without parameters.
270
+ * Returns only the media type without parameters (e.g., 'application/json').
271
+ *
272
+ * @returns {string|null} The content type, or null if not set
273
+ * @public
274
+ */
275
+ get type() {
276
+ const type = this.get("Content-Type");
277
+ if (!type) return null;
278
+ return type.split(";", 1)[0];
279
+ }
280
+ /**
281
+ * Set the response Content-Type.
282
+ * Supports both full MIME types and shorthand aliases.
283
+ *
284
+ * @param {string} type - The content type or alias (e.g., 'json', 'html', 'application/json')
285
+ * @public
286
+ */
287
+ set type(val) {
288
+ if (!val) return;
289
+ val = require_lib_utils.commonTypeMapping[val] || val;
290
+ this.set("Content-Type", val);
291
+ }
292
+ /**
293
+ * Get the response Content-Length as a number.
294
+ * Returns the parsed Content-Length header value, or calculates it from the body if available.
295
+ *
296
+ * @returns {number|null} The content length in bytes, or null if not determinable
297
+ * @public
298
+ */
299
+ get length() {
300
+ if (this.has("Content-Length")) return Number.parseInt(this.get("Content-Length"), 10) || 0;
301
+ if (this.body == null || this.body instanceof ReadableStream || this.body instanceof FormData || this.body instanceof Response) return null;
302
+ if (typeof this.body === "string") return new TextEncoder().encode(this.body).length;
303
+ if (this.body instanceof Blob) return this.body.size;
304
+ if (this.body instanceof ArrayBuffer) return this.body.byteLength;
305
+ if (ArrayBuffer.isView(this.body)) return this.body.byteLength;
306
+ if (this.body instanceof URLSearchParams) return new TextEncoder().encode(this.body.toString()).length;
307
+ return new TextEncoder().encode(JSON.stringify(this.body)).length;
308
+ }
309
+ /**
310
+ * Set the response Content-Length header.
311
+ * Only sets the header if Transfer-Encoding is not present.
312
+ *
313
+ * @param {number|string} val - The content length in bytes
314
+ * @public
315
+ */
316
+ set length(val) {
317
+ if (!this.has("Transfer-Encoding")) this.set("Content-Length", val);
318
+ }
319
+ /**
320
+ * Return JSON representation of the response.
321
+ *
322
+ * @returns {ResJSON} JSON representation of response
323
+ * @public
324
+ */
325
+ toJSON() {
326
+ return {
327
+ status: this.status,
328
+ statusText: this.statusText,
329
+ headers: this.headers
330
+ };
331
+ }
332
+ };
333
+
334
+ //#endregion
335
+ module.exports = HoaResponse;
@@ -0,0 +1,152 @@
1
+ import { statusEmptyMapping, statusTextMapping } from "./lib/utils.mjs";
2
+ import HttpError from "./lib/http-error.mjs";
3
+
4
+ //#region src/context.js
5
+ /**
6
+ * @typedef {Object} CtxJSON
7
+ * @property {ReturnType<import('./hoa.js').default.prototype.toJSON>} app
8
+ * @property {ReturnType<import('./request.js').default.prototype.toJSON>} req
9
+ * @property {ReturnType<import('./response.js').default.prototype.toJSON>} res
10
+ */
11
+ /**
12
+ * @class HoaContext
13
+ */
14
+ var HoaContext = class {
15
+ /**
16
+ * Create a context for a single HTTP request.
17
+ *
18
+ * @param {Object} [options={}]
19
+ * @param {Request} [options.request] - Web Standard Request
20
+ * @param {any} [options.env] - Environment (platform-specific)
21
+ * @param {any} [options.executionCtx] - Execution context (platform-specific)
22
+ * @public
23
+ */
24
+ constructor(options = {}) {
25
+ this.request = options.request;
26
+ this.env = options.env;
27
+ this.executionCtx = options.executionCtx;
28
+ this.state = Object.create(null);
29
+ }
30
+ /**
31
+ * Throw an HttpError.
32
+ *
33
+ * @param {number} status - HTTP status code
34
+ * @param {string|{message?: string, cause?: any, headers?: HeadersInit}} [messageOrOptions] - Error message or options object
35
+ * @throws {HttpError}
36
+ * @public
37
+ */
38
+ throw(...args) {
39
+ throw new HttpError(...args);
40
+ }
41
+ /**
42
+ * Assert condition or throw an HttpError.
43
+ *
44
+ * @param {any} value - Condition to assert
45
+ * @param {...any} args - Arguments passed to HttpError constructor
46
+ * @throws {HttpError}
47
+ * @public
48
+ */
49
+ assert(value, ...args) {
50
+ if (value) return;
51
+ throw new HttpError(...args);
52
+ }
53
+ /**
54
+ * Default error handling and response builder.
55
+ *
56
+ * @param {Error} err - Error to handle
57
+ * @returns {Response} Web Standard Response object
58
+ * @private
59
+ */
60
+ onerror(err) {
61
+ const { res } = this;
62
+ if (!(Object.prototype.toString.call(err) === "[object Error]" || err instanceof Error)) err = /* @__PURE__ */ new Error(`non-error thrown: ${JSON.stringify(err)}`);
63
+ this.app.onerror(err, this);
64
+ res.headers = new Headers();
65
+ res.set(err.headers);
66
+ res.type = "text";
67
+ let status = err.status || err.statusCode;
68
+ if (typeof status !== "number" || !statusTextMapping[status]) status = 500;
69
+ const message = statusTextMapping[status];
70
+ const msg = err.expose ? err.message : message;
71
+ res.status = status;
72
+ res.body = msg;
73
+ return new Response(res.body, {
74
+ status: res.status,
75
+ headers: res._headers
76
+ });
77
+ }
78
+ /**
79
+ * Build Web Standard Response from current context state.
80
+ * Handles various body types, HEAD requests, and status-specific behaviors.
81
+ *
82
+ * @returns {Response} Web Standard Response object
83
+ * @public
84
+ */
85
+ get response() {
86
+ const { res, req } = this;
87
+ let body = res.body;
88
+ if (req.method === "HEAD") {
89
+ if (!res.has("Content-Length")) {
90
+ const contentLength = res.length;
91
+ if (Number.isInteger(contentLength)) res.length = contentLength;
92
+ }
93
+ return new Response(null, {
94
+ status: res.status,
95
+ statusText: res.statusText,
96
+ headers: res._headers
97
+ });
98
+ }
99
+ if (statusEmptyMapping[res.status]) {
100
+ res.body = null;
101
+ return new Response(null, {
102
+ status: res.status,
103
+ statusText: res.statusText,
104
+ headers: res._headers
105
+ });
106
+ }
107
+ if (body == null) {
108
+ if (res._explicitNullBody) {
109
+ res.delete("Content-Type");
110
+ res.delete("Transfer-Encoding");
111
+ res.set("Content-Length", "0");
112
+ }
113
+ return new Response(null, {
114
+ status: res.status,
115
+ statusText: res.statusText,
116
+ headers: res._headers
117
+ });
118
+ }
119
+ if (typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof ReadableStream || body instanceof FormData || body instanceof URLSearchParams) return new Response(body, {
120
+ status: res.status,
121
+ statusText: res.statusText,
122
+ headers: res._headers
123
+ });
124
+ if (body instanceof Response) return new Response(body.body, {
125
+ status: res.status,
126
+ statusText: res.statusText,
127
+ headers: res._headers
128
+ });
129
+ body = JSON.stringify(body);
130
+ return new Response(body, {
131
+ status: res.status,
132
+ statusText: res.statusText,
133
+ headers: res._headers
134
+ });
135
+ }
136
+ /**
137
+ * Return JSON representation of the context.
138
+ *
139
+ * @returns {CtxJSON} JSON representation of context
140
+ * @public
141
+ */
142
+ toJSON() {
143
+ return {
144
+ app: this.app.toJSON(),
145
+ req: this.req.toJSON(),
146
+ res: this.res.toJSON()
147
+ };
148
+ }
149
+ };
150
+
151
+ //#endregion
152
+ export { HoaContext as default };
@@ -0,0 +1,148 @@
1
+ import { statusEmptyMapping, statusRedirectMapping, statusTextMapping } from "./lib/utils.mjs";
2
+ import HttpError from "./lib/http-error.mjs";
3
+ import HoaContext from "./context.mjs";
4
+ import compose from "./lib/compose.mjs";
5
+ import HoaRequest from "./request.mjs";
6
+ import HoaResponse from "./response.mjs";
7
+
8
+ //#region src/hoa.js
9
+ /**
10
+ * @typedef {Object} AppJSON
11
+ * @property {string} name - Application name
12
+ */
13
+ /**
14
+ * @class Hoa
15
+ * @property {string} name - Application name
16
+ * @property {boolean} [silent] - Suppress error console output when true
17
+ */
18
+ var Hoa = class Hoa {
19
+ /**
20
+ * Create an Hoa instance.
21
+ *
22
+ * @param {Object} [options={}] - Application options
23
+ * @param {string} [options.name='Hoa'] - Application name for identification
24
+ */
25
+ constructor(options = {}) {
26
+ this.name = options.name || "Hoa";
27
+ this.HoaContext = HoaContext;
28
+ this.HoaRequest = HoaRequest;
29
+ this.HoaResponse = HoaResponse;
30
+ this.middlewares = [];
31
+ this.fetch = this.fetch.bind(this);
32
+ }
33
+ /**
34
+ * Extend the application with a plugin initializer.
35
+ *
36
+ * @param {HoaExtension} fn - Plugin function that receives the app instance
37
+ * @returns {Hoa} The Hoa instance for method chaining
38
+ * @throws {TypeError}
39
+ * @public
40
+ */
41
+ extend(fn) {
42
+ if (typeof fn !== "function") throw new TypeError("extend() must receive a function!");
43
+ fn(this);
44
+ return this;
45
+ }
46
+ /**
47
+ * Register a middleware. Executed in registration order.
48
+ *
49
+ * @param {HoaMiddleware} fn - Middleware function
50
+ * @returns {Hoa} The Hoa instance for method chaining
51
+ * @throws {TypeError}
52
+ * @public
53
+ */
54
+ use(fn) {
55
+ if (typeof fn !== "function") throw new TypeError("use() must receive a function!");
56
+ this.middlewares.push(fn);
57
+ this._composedMiddleware = null;
58
+ return this;
59
+ }
60
+ /**
61
+ * Web Standards fetch handler - main entry point for HTTP requests.
62
+ * Compatible with Cloudflare Workers, Deno, and other Web Standards environments.
63
+ *
64
+ * @param {Request} request - Web Standard Request object
65
+ * @param {any} [env] - Environment variables (platform-specific)
66
+ * @param {any} [executionCtx] - Execution context (platform-specific)
67
+ * @returns {Promise<Response>} Web Standard Response object
68
+ * @public
69
+ */
70
+ fetch(request, env, executionCtx) {
71
+ const ctx = this.createContext(request, env, executionCtx);
72
+ if (!this._composedMiddleware) this._composedMiddleware = compose(this.middlewares);
73
+ return this.handleRequest(ctx, this._composedMiddleware);
74
+ }
75
+ /**
76
+ * Handle incoming request through the middleware stack.
77
+ * Manages error handling and response building.
78
+ *
79
+ * @param {HoaContext} ctx - Request context
80
+ * @param {HoaMiddleware} middlewareFn - Composed middleware function
81
+ * @returns {Promise<Response>} Web Standard Response object
82
+ * @private
83
+ */
84
+ handleRequest(ctx, middlewareFn) {
85
+ return middlewareFn(ctx).then(() => ctx.response).catch((err) => ctx.onerror(err));
86
+ }
87
+ /**
88
+ * Create context for incoming request with linked request/response objects.
89
+ * Establishes the context chain: ctx ↔ req ↔ res ↔ app
90
+ *
91
+ * @param {Request} request - Web Standard Request object
92
+ * @param {any} [env] - Environment variables
93
+ * @param {any} [executionCtx] - Execution context
94
+ * @returns {HoaContext} Created context instance
95
+ * @private
96
+ */
97
+ createContext(request, env, executionCtx) {
98
+ const ctx = new this.HoaContext({
99
+ request,
100
+ env,
101
+ executionCtx
102
+ });
103
+ const req = ctx.req = new this.HoaRequest();
104
+ const res = ctx.res = new this.HoaResponse();
105
+ ctx.app = req.app = res.app = this;
106
+ req.ctx = res.ctx = ctx;
107
+ req.res = res;
108
+ res.req = req;
109
+ return ctx;
110
+ }
111
+ /**
112
+ * Default error handler for unhandled application errors.
113
+ * Logs errors to console unless they're client errors (4xx) or explicitly exposed.
114
+ *
115
+ * @param {Error} err - Error to handle
116
+ * @param {HoaContext} [ctx] - Request context (optional)
117
+ * @returns {void}
118
+ * @throws {TypeError}
119
+ * @private
120
+ */
121
+ onerror(err, ctx) {
122
+ if (!(Object.prototype.toString.call(err) === "[object Error]" || err instanceof Error)) throw new TypeError(`non-error thrown: ${JSON.stringify(err)}`);
123
+ if (err.status === 404 || err.expose) return;
124
+ if (this.silent) return;
125
+ console.error(err);
126
+ }
127
+ /**
128
+ * ESM/CJS interop helper for default exports.
129
+ *
130
+ * @returns {typeof Hoa} The Hoa class
131
+ * @static
132
+ */
133
+ static get default() {
134
+ return Hoa;
135
+ }
136
+ /**
137
+ * Return JSON representation of the app.
138
+ *
139
+ * @returns {AppJSON} JSON representation of application
140
+ * @public
141
+ */
142
+ toJSON() {
143
+ return { name: this.name };
144
+ }
145
+ };
146
+
147
+ //#endregion
148
+ export { Hoa, Hoa as default, HoaContext, HoaRequest, HoaResponse, HttpError, compose, statusEmptyMapping, statusRedirectMapping, statusTextMapping };
@@ -0,0 +1,34 @@
1
+ //#region src/lib/compose.js
2
+ /**
3
+ * Compose middleware functions into a single dispatcher.
4
+ *
5
+ * @param {HoaMiddleware[]} middlewares - Array of middleware functions
6
+ * @returns {HoaMiddleware} Composed middleware function
7
+ * @private
8
+ */
9
+ const composeSlim = (middlewares) => async (ctx, next) => {
10
+ const dispatch = (i) => async () => {
11
+ const fn = i === middlewares.length ? next : middlewares[i];
12
+ if (!fn) return;
13
+ return await fn(ctx, dispatch(i + 1));
14
+ };
15
+ return dispatch(0)();
16
+ };
17
+ /**
18
+ * Compose multiple middleware functions into one.
19
+ * Validates input, flattens nested arrays, and returns a composed dispatcher.
20
+ *
21
+ * @param {HoaMiddleware[]|HoaMiddleware[][]} middlewares - Array of middleware functions or nested arrays
22
+ * @returns {HoaMiddleware} Composed middleware function
23
+ * @throws {TypeError}
24
+ * @public
25
+ */
26
+ function compose(middlewares) {
27
+ if (!Array.isArray(middlewares)) throw new TypeError("compose() must receive an array of middleware functions!");
28
+ middlewares = middlewares.flat();
29
+ for (const middleware of middlewares) if (typeof middleware !== "function") throw new TypeError("Middleware must be composed of functions!");
30
+ return composeSlim(middlewares);
31
+ }
32
+
33
+ //#endregion
34
+ export { compose as default };