@wooksjs/event-http 0.5.20 → 0.5.25

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.
package/dist/index.cjs CHANGED
@@ -1,1034 +1,1031 @@
1
- 'use strict';
1
+ "use strict";
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
2
23
 
3
- var eventCore = require('@wooksjs/event-core');
4
- var url = require('url');
5
- var http = require('http');
6
- var wooks = require('wooks');
7
- var stream = require('stream');
24
+ //#endregion
25
+ const __wooksjs_event_core = __toESM(require("@wooksjs/event-core"));
26
+ const buffer = __toESM(require("buffer"));
27
+ const url = __toESM(require("url"));
28
+ const http = __toESM(require("http"));
29
+ const wooks = __toESM(require("wooks"));
30
+ const stream = __toESM(require("stream"));
8
31
 
32
+ //#region packages/event-http/src/event-http.ts
9
33
  function createHttpContext(data, options) {
10
- return eventCore.createAsyncEventContext({
11
- event: {
12
- ...data,
13
- type: 'HTTP',
14
- },
15
- options,
16
- });
34
+ return (0, __wooksjs_event_core.createAsyncEventContext)({
35
+ event: {
36
+ ...data,
37
+ type: "HTTP"
38
+ },
39
+ options
40
+ });
17
41
  }
18
42
  function useHttpContext() {
19
- return eventCore.useAsyncEventContext('HTTP');
43
+ return (0, __wooksjs_event_core.useAsyncEventContext)("HTTP");
20
44
  }
21
45
 
46
+ //#endregion
47
+ //#region packages/event-http/src/utils/helpers.ts
22
48
  function escapeRegex(s) {
23
- return s.replace(/[$()*+./?[\\\]^{|}-]/g, '\\$&');
49
+ return s.replace(/[$()*+\-./?[\\\]^{|}]/gu, "\\$&");
24
50
  }
25
51
  function safeDecode(f, v) {
26
- try {
27
- return f(v);
28
- }
29
- catch (error) {
30
- return v;
31
- }
52
+ try {
53
+ return f(v);
54
+ } catch (error) {
55
+ return v;
56
+ }
32
57
  }
33
58
  function safeDecodeURIComponent(uri) {
34
- if (!uri.includes('%')) {
35
- return uri;
36
- }
37
- return safeDecode(decodeURIComponent, uri);
59
+ if (!uri.includes("%")) return uri;
60
+ return safeDecode(decodeURIComponent, uri);
38
61
  }
39
62
 
40
- function convertTime(time, unit = 'ms') {
41
- if (typeof time === 'number') {
42
- return time / units[unit];
43
- }
44
- const rg = /(\d+)(\w+)/g;
45
- let t = 0;
46
- let r;
47
- while ((r = rg.exec(time))) {
48
- t += Number(r[1]) * (units[r[2]] || 0);
49
- }
50
- return t / units[unit];
63
+ //#endregion
64
+ //#region packages/event-http/src/utils/time.ts
65
+ function convertTime(time, unit = "ms") {
66
+ if (typeof time === "number") return time / units[unit];
67
+ const rg = /(\d+)(\w+)/gu;
68
+ let t = 0;
69
+ let r;
70
+ while (r = rg.exec(time)) t += Number(r[1]) * (units[r[2]] || 0);
71
+ return t / units[unit];
51
72
  }
52
73
  const units = {
53
- ms: 1,
54
- s: 1000,
55
- m: 1000 * 60,
56
- h: 1000 * 60 * 60,
57
- d: 1000 * 60 * 60 * 24,
58
- w: 1000 * 60 * 60 * 24 * 7,
59
- M: 1000 * 60 * 60 * 24 * 30,
60
- Y: 1000 * 60 * 60 * 24 * 365,
74
+ ms: 1,
75
+ s: 1e3,
76
+ m: 6e4,
77
+ h: 36e5,
78
+ d: 864e5,
79
+ w: 6048e5,
80
+ M: 2592e6,
81
+ Y: 31536e6
61
82
  };
62
83
 
84
+ //#endregion
85
+ //#region packages/event-http/src/utils/set-cookie.ts
63
86
  function renderCookie(key, data) {
64
- let attrs = '';
65
- for (const [a, v] of Object.entries(data.attrs)) {
66
- const func = cookieAttrFunc[a];
67
- if (typeof func === 'function') {
68
- const val = func(v);
69
- attrs += val ? `; ${val}` : '';
70
- }
71
- else {
72
- throw new TypeError(`Unknown Set-Cookie attribute ${a}`);
73
- }
74
- }
75
- return `${key}=${encodeURIComponent(data.value)}${attrs}`;
87
+ let attrs = "";
88
+ for (const [a, v] of Object.entries(data.attrs)) {
89
+ const func = cookieAttrFunc[a];
90
+ if (typeof func === "function") {
91
+ const val = func(v);
92
+ attrs += val ? `; ${val}` : "";
93
+ } else throw new TypeError(`Unknown Set-Cookie attribute ${a}`);
94
+ }
95
+ return `${key}=${encodeURIComponent(data.value)}${attrs}`;
76
96
  }
77
97
  const cookieAttrFunc = {
78
- expires: (v) => `Expires=${typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString()}`,
79
- maxAge: (v) => `Max-Age=${convertTime(v, 's').toString()}`,
80
- domain: (v) => `Domain=${v}`,
81
- path: (v) => `Path=${v}`,
82
- secure: (v) => (v ? 'Secure' : ''),
83
- httpOnly: (v) => (v ? 'HttpOnly' : ''),
84
- sameSite: (v) => v ? `SameSite=${typeof v === 'string' ? v : 'Strict'}` : '',
98
+ expires: (v) => `Expires=${typeof v === "string" || typeof v === "number" ? new Date(v).toUTCString() : v.toUTCString()}`,
99
+ maxAge: (v) => `Max-Age=${convertTime(v, "s").toString()}`,
100
+ domain: (v) => `Domain=${v}`,
101
+ path: (v) => `Path=${v}`,
102
+ secure: (v) => v ? "Secure" : "",
103
+ httpOnly: (v) => v ? "HttpOnly" : "",
104
+ sameSite: (v) => v ? `SameSite=${typeof v === "string" ? v : "Strict"}` : ""
85
105
  };
86
106
 
87
- const xForwardedFor = 'x-forwarded-for';
107
+ //#endregion
108
+ //#region packages/event-http/src/composables/request.ts
109
+ const xForwardedFor = "x-forwarded-for";
88
110
  function useRequest() {
89
- const { store } = useHttpContext();
90
- const { init } = store('request');
91
- const event = store('event');
92
- const req = event.get('req');
93
- const rawBody = () => init('rawBody', () => new Promise((resolve, reject) => {
94
- let body = Buffer.from('');
95
- req.on('data', chunk => {
96
- body = Buffer.concat([body, chunk]);
97
- });
98
- req.on('error', err => {
99
- reject(err);
100
- });
101
- req.on('end', () => {
102
- resolve(body);
103
- });
104
- }));
105
- const reqId = eventCore.useEventId().getId;
106
- const forwardedIp = () => init('forwardedIp', () => {
107
- if (typeof req.headers[xForwardedFor] === 'string' && req.headers[xForwardedFor]) {
108
- return req.headers[xForwardedFor].split(',').shift()?.trim();
109
- }
110
- else {
111
- return '';
112
- }
113
- });
114
- const remoteIp = () => init('remoteIp', () => req.socket.remoteAddress || req.connection.remoteAddress || '');
115
- function getIp(options) {
116
- if (options?.trustProxy) {
117
- return forwardedIp() || getIp();
118
- }
119
- else {
120
- return remoteIp();
121
- }
122
- }
123
- const getIpList = () => init('ipList', () => ({
124
- remoteIp: req.socket.remoteAddress || req.connection.remoteAddress || '',
125
- forwarded: (req.headers[xForwardedFor] || '').split(',').map(s => s.trim()),
126
- }));
127
- return {
128
- rawRequest: req,
129
- url: req.url,
130
- method: req.method,
131
- headers: req.headers,
132
- rawBody,
133
- reqId,
134
- getIp,
135
- getIpList,
136
- };
111
+ const { store } = useHttpContext();
112
+ const { init } = store("request");
113
+ const event = store("event");
114
+ const req = event.get("req");
115
+ const rawBody = () => init("rawBody", () => new Promise((resolve, reject) => {
116
+ let body = buffer.Buffer.from("");
117
+ req.on("data", (chunk) => {
118
+ body = buffer.Buffer.concat([body, chunk]);
119
+ });
120
+ req.on("error", (err) => {
121
+ reject(err);
122
+ });
123
+ req.on("end", () => {
124
+ resolve(body);
125
+ });
126
+ }));
127
+ const reqId = (0, __wooksjs_event_core.useEventId)().getId;
128
+ const forwardedIp = () => init("forwardedIp", () => {
129
+ if (typeof req.headers[xForwardedFor] === "string" && req.headers[xForwardedFor]) return req.headers[xForwardedFor].split(",").shift()?.trim();
130
+ else return "";
131
+ });
132
+ const remoteIp = () => init("remoteIp", () => req.socket.remoteAddress || req.connection.remoteAddress || "");
133
+ function getIp(options) {
134
+ if (options?.trustProxy) return forwardedIp() || getIp();
135
+ else return remoteIp();
136
+ }
137
+ const getIpList = () => init("ipList", () => ({
138
+ remoteIp: req.socket.remoteAddress || req.connection.remoteAddress || "",
139
+ forwarded: (req.headers[xForwardedFor] || "").split(",").map((s) => s.trim())
140
+ }));
141
+ return {
142
+ rawRequest: req,
143
+ url: req.url,
144
+ method: req.method,
145
+ headers: req.headers,
146
+ rawBody,
147
+ reqId,
148
+ getIp,
149
+ getIpList
150
+ };
137
151
  }
138
152
 
153
+ //#endregion
154
+ //#region packages/event-http/src/composables/headers.ts
139
155
  function useHeaders() {
140
- return useRequest().headers;
156
+ return useRequest().headers;
141
157
  }
142
158
  function useSetHeaders() {
143
- const { store } = useHttpContext();
144
- const setHeaderStore = store('setHeader');
145
- function setHeader(name, value) {
146
- setHeaderStore.set(name, value.toString());
147
- }
148
- function setContentType(value) {
149
- setHeader('content-type', value);
150
- }
151
- function enableCors(origin = '*') {
152
- setHeader('access-control-allow-origin', origin);
153
- }
154
- return {
155
- setHeader,
156
- getHeader: setHeaderStore.get,
157
- removeHeader: setHeaderStore.del,
158
- setContentType,
159
- headers: () => setHeaderStore.value || {},
160
- enableCors,
161
- };
159
+ const { store } = useHttpContext();
160
+ const setHeaderStore = store("setHeader");
161
+ function setHeader(name, value) {
162
+ setHeaderStore.set(name, value.toString());
163
+ }
164
+ function setContentType(value) {
165
+ setHeader("content-type", value);
166
+ }
167
+ function enableCors(origin = "*") {
168
+ setHeader("access-control-allow-origin", origin);
169
+ }
170
+ return {
171
+ setHeader,
172
+ getHeader: setHeaderStore.get,
173
+ removeHeader: setHeaderStore.del,
174
+ setContentType,
175
+ headers: () => setHeaderStore.value || {},
176
+ enableCors
177
+ };
162
178
  }
163
179
  function useSetHeader(name) {
164
- const { store } = useHttpContext();
165
- const { hook } = store('setHeader');
166
- return hook(name);
180
+ const { store } = useHttpContext();
181
+ const { hook } = store("setHeader");
182
+ return hook(name);
167
183
  }
168
184
 
185
+ //#endregion
186
+ //#region packages/event-http/src/composables/cookies.ts
169
187
  function useCookies() {
170
- const { store } = useHttpContext();
171
- const { cookie } = useHeaders();
172
- const { init } = store('cookies');
173
- const getCookie = (name) => init(name, () => {
174
- if (cookie) {
175
- const result = new RegExp(`(?:^|; )${escapeRegex(name)}=(.*?)(?:;?$|; )`, 'i').exec(cookie);
176
- return result?.[1] ? safeDecodeURIComponent(result[1]) : null;
177
- }
178
- else {
179
- return null;
180
- }
181
- });
182
- return {
183
- rawCookies: cookie,
184
- getCookie,
185
- };
188
+ const { store } = useHttpContext();
189
+ const { cookie } = useHeaders();
190
+ const { init } = store("cookies");
191
+ const getCookie = (name) => init(name, () => {
192
+ if (cookie) {
193
+ const result = new RegExp(`(?:^|; )${escapeRegex(name)}=(.*?)(?:;?$|; )`, "i").exec(cookie);
194
+ return result?.[1] ? safeDecodeURIComponent(result[1]) : null;
195
+ } else return null;
196
+ });
197
+ return {
198
+ rawCookies: cookie,
199
+ getCookie
200
+ };
186
201
  }
187
202
  function useSetCookies() {
188
- const { store } = useHttpContext();
189
- const cookiesStore = store('setCookies');
190
- function setCookie(name, value, attrs) {
191
- cookiesStore.set(name, {
192
- value,
193
- attrs: attrs || {},
194
- });
195
- }
196
- function cookies() {
197
- return cookiesStore
198
- .entries()
199
- .filter(a => !!a[1])
200
- .map(([key, value]) => renderCookie(key, value));
201
- }
202
- return {
203
- setCookie,
204
- getCookie: cookiesStore.get,
205
- removeCookie: cookiesStore.del,
206
- clearCookies: cookiesStore.clear,
207
- cookies,
208
- };
203
+ const { store } = useHttpContext();
204
+ const cookiesStore = store("setCookies");
205
+ function setCookie(name, value, attrs) {
206
+ cookiesStore.set(name, {
207
+ value,
208
+ attrs: attrs || {}
209
+ });
210
+ }
211
+ function cookies() {
212
+ return cookiesStore.entries().filter((a) => !!a[1]).map(([key, value]) => renderCookie(key, value));
213
+ }
214
+ return {
215
+ setCookie,
216
+ getCookie: cookiesStore.get,
217
+ removeCookie: cookiesStore.del,
218
+ clearCookies: cookiesStore.clear,
219
+ cookies
220
+ };
209
221
  }
210
222
  function useSetCookie(name) {
211
- const { setCookie, getCookie } = useSetCookies();
212
- const valueHook = eventCore.attachHook({
213
- name,
214
- type: 'cookie',
215
- }, {
216
- get: () => getCookie(name)?.value,
217
- set: (value) => {
218
- setCookie(name, value, getCookie(name)?.attrs);
219
- },
220
- });
221
- return eventCore.attachHook(valueHook, {
222
- get: () => getCookie(name)?.attrs,
223
- set: (attrs) => {
224
- setCookie(name, getCookie(name)?.value || '', attrs);
225
- },
226
- }, 'attrs');
223
+ const { setCookie, getCookie } = useSetCookies();
224
+ const valueHook = (0, __wooksjs_event_core.attachHook)({
225
+ name,
226
+ type: "cookie"
227
+ }, {
228
+ get: () => getCookie(name)?.value,
229
+ set: (value) => {
230
+ setCookie(name, value, getCookie(name)?.attrs);
231
+ }
232
+ });
233
+ return (0, __wooksjs_event_core.attachHook)(valueHook, {
234
+ get: () => getCookie(name)?.attrs,
235
+ set: (attrs) => {
236
+ setCookie(name, getCookie(name)?.value || "", attrs);
237
+ }
238
+ }, "attrs");
227
239
  }
228
240
 
241
+ //#endregion
242
+ //#region packages/event-http/src/composables/header-accept.ts
229
243
  function useAccept() {
230
- const { store } = useHttpContext();
231
- const { accept } = useHeaders();
232
- const accepts = (mime) => {
233
- const { set, get, has } = store('accept');
234
- if (!has(mime)) {
235
- return set(mime, !!(accept && (accept === '*/*' || accept.includes(mime))));
236
- }
237
- return get(mime);
238
- };
239
- return {
240
- accept,
241
- accepts,
242
- acceptsJson: () => accepts('application/json'),
243
- acceptsXml: () => accepts('application/xml'),
244
- acceptsText: () => accepts('text/plain'),
245
- acceptsHtml: () => accepts('text/html'),
246
- };
244
+ const { store } = useHttpContext();
245
+ const { accept } = useHeaders();
246
+ const accepts = (mime) => {
247
+ const { set, get, has } = store("accept");
248
+ if (!has(mime)) return set(mime, !!(accept && (accept === "*/*" || accept.includes(mime))));
249
+ return get(mime);
250
+ };
251
+ return {
252
+ accept,
253
+ accepts,
254
+ acceptsJson: () => accepts("application/json"),
255
+ acceptsXml: () => accepts("application/xml"),
256
+ acceptsText: () => accepts("text/plain"),
257
+ acceptsHtml: () => accepts("text/html")
258
+ };
247
259
  }
248
260
 
261
+ //#endregion
262
+ //#region packages/event-http/src/composables/header-authorization.ts
249
263
  function useAuthorization() {
250
- const { store } = useHttpContext();
251
- const { authorization } = useHeaders();
252
- const { init } = store('authorization');
253
- const authType = () => init('type', () => {
254
- if (authorization) {
255
- const space = authorization.indexOf(' ');
256
- return authorization.slice(0, space);
257
- }
258
- return null;
259
- });
260
- const authRawCredentials = () => init('credentials', () => {
261
- if (authorization) {
262
- const space = authorization.indexOf(' ');
263
- return authorization.slice(space + 1);
264
- }
265
- return null;
266
- });
267
- return {
268
- authorization,
269
- authType,
270
- authRawCredentials,
271
- isBasic: () => authType()?.toLocaleLowerCase() === 'basic',
272
- isBearer: () => authType()?.toLocaleLowerCase() === 'bearer',
273
- basicCredentials: () => init('basicCredentials', () => {
274
- if (authorization) {
275
- const type = authType();
276
- if (type?.toLocaleLowerCase() === 'basic') {
277
- const creds = Buffer.from(authRawCredentials() || '', 'base64').toString('ascii');
278
- const [username, password] = creds.split(':');
279
- return { username, password };
280
- }
281
- }
282
- return null;
283
- }),
284
- };
264
+ const { store } = useHttpContext();
265
+ const { authorization } = useHeaders();
266
+ const { init } = store("authorization");
267
+ const authType = () => init("type", () => {
268
+ if (authorization) {
269
+ const space = authorization.indexOf(" ");
270
+ return authorization.slice(0, space);
271
+ }
272
+ return null;
273
+ });
274
+ const authRawCredentials = () => init("credentials", () => {
275
+ if (authorization) {
276
+ const space = authorization.indexOf(" ");
277
+ return authorization.slice(space + 1);
278
+ }
279
+ return null;
280
+ });
281
+ return {
282
+ authorization,
283
+ authType,
284
+ authRawCredentials,
285
+ isBasic: () => authType()?.toLocaleLowerCase() === "basic",
286
+ isBearer: () => authType()?.toLocaleLowerCase() === "bearer",
287
+ basicCredentials: () => init("basicCredentials", () => {
288
+ if (authorization) {
289
+ const type = authType();
290
+ if (type?.toLocaleLowerCase() === "basic") {
291
+ const creds = buffer.Buffer.from(authRawCredentials() || "", "base64").toString("ascii");
292
+ const [username, password] = creds.split(":");
293
+ return {
294
+ username,
295
+ password
296
+ };
297
+ }
298
+ }
299
+ return null;
300
+ })
301
+ };
285
302
  }
286
303
 
304
+ //#endregion
305
+ //#region packages/event-http/src/utils/cache-control.ts
287
306
  function renderCacheControl(data) {
288
- let attrs = '';
289
- for (const [a, v] of Object.entries(data)) {
290
- if (v === undefined) {
291
- continue;
292
- }
293
- const func = cacheControlFunc[a];
294
- if (typeof func === 'function') {
295
- const val = func(v);
296
- if (val) {
297
- attrs += attrs ? `, ${val}` : val;
298
- }
299
- }
300
- else {
301
- throw new TypeError(`Unknown Cache-Control attribute ${a}`);
302
- }
303
- }
304
- return attrs;
307
+ let attrs = "";
308
+ for (const [a, v] of Object.entries(data)) {
309
+ if (v === undefined) continue;
310
+ const func = cacheControlFunc[a];
311
+ if (typeof func === "function") {
312
+ const val = func(v);
313
+ if (val) attrs += attrs ? `, ${val}` : val;
314
+ } else throw new TypeError(`Unknown Cache-Control attribute ${a}`);
315
+ }
316
+ return attrs;
305
317
  }
306
318
  const cacheControlFunc = {
307
- mustRevalidate: (v) => (v ? 'must-revalidate' : ''),
308
- noCache: (v) => v ? (typeof v === 'string' ? `no-cache="${v}"` : 'no-cache') : '',
309
- noStore: (v) => (v ? 'no-store' : ''),
310
- noTransform: (v) => (v ? 'no-transform' : ''),
311
- public: (v) => (v ? 'public' : ''),
312
- private: (v) => v ? (typeof v === 'string' ? `private="${v}"` : 'private') : '',
313
- proxyRevalidate: (v) => (v ? 'proxy-revalidate' : ''),
314
- maxAge: (v) => `max-age=${convertTime(v, 's').toString()}`,
315
- sMaxage: (v) => `s-maxage=${convertTime(v, 's').toString()}`,
319
+ mustRevalidate: (v) => v ? "must-revalidate" : "",
320
+ noCache: (v) => v ? typeof v === "string" ? `no-cache="${v}"` : "no-cache" : "",
321
+ noStore: (v) => v ? "no-store" : "",
322
+ noTransform: (v) => v ? "no-transform" : "",
323
+ public: (v) => v ? "public" : "",
324
+ private: (v) => v ? typeof v === "string" ? `private="${v}"` : "private" : "",
325
+ proxyRevalidate: (v) => v ? "proxy-revalidate" : "",
326
+ maxAge: (v) => `max-age=${convertTime(v, "s").toString()}`,
327
+ sMaxage: (v) => `s-maxage=${convertTime(v, "s").toString()}`
316
328
  };
317
329
 
318
- const renderAge = (v) => convertTime(v, 's').toString();
319
- const renderExpires = (v) => typeof v === 'string' || typeof v === 'number' ? new Date(v).toUTCString() : v.toUTCString();
320
- const renderPragmaNoCache = (v) => (v ? 'no-cache' : '');
330
+ //#endregion
331
+ //#region packages/event-http/src/composables/header-set-cache-control.ts
332
+ const renderAge = (v) => convertTime(v, "s").toString();
333
+ const renderExpires = (v) => typeof v === "string" || typeof v === "number" ? new Date(v).toUTCString() : v.toUTCString();
334
+ const renderPragmaNoCache = (v) => v ? "no-cache" : "";
321
335
  function useSetCacheControl() {
322
- const { setHeader } = useSetHeaders();
323
- const setAge = (value) => {
324
- setHeader('age', renderAge(value));
325
- };
326
- const setExpires = (value) => {
327
- setHeader('expires', renderExpires(value));
328
- };
329
- const setPragmaNoCache = (value = true) => {
330
- setHeader('pragma', renderPragmaNoCache(value));
331
- };
332
- const setCacheControl = (data) => {
333
- setHeader('cache-control', renderCacheControl(data));
334
- };
335
- return {
336
- setExpires,
337
- setAge,
338
- setPragmaNoCache,
339
- setCacheControl,
340
- };
336
+ const { setHeader } = useSetHeaders();
337
+ const setAge = (value) => {
338
+ setHeader("age", renderAge(value));
339
+ };
340
+ const setExpires = (value) => {
341
+ setHeader("expires", renderExpires(value));
342
+ };
343
+ const setPragmaNoCache = (value = true) => {
344
+ setHeader("pragma", renderPragmaNoCache(value));
345
+ };
346
+ const setCacheControl = (data) => {
347
+ setHeader("cache-control", renderCacheControl(data));
348
+ };
349
+ return {
350
+ setExpires,
351
+ setAge,
352
+ setPragmaNoCache,
353
+ setCacheControl
354
+ };
341
355
  }
342
356
 
357
+ //#endregion
358
+ //#region packages/event-http/src/composables/response.ts
343
359
  function useResponse() {
344
- const { store } = useHttpContext();
345
- const event = store('event');
346
- const res = event.get('res');
347
- const responded = store('response').hook('responded');
348
- const statusCode = store('status').hook('code');
349
- function status(code) {
350
- return (statusCode.value = code ? code : statusCode.value);
351
- }
352
- const rawResponse = (options) => {
353
- if (!options || !options.passthrough) {
354
- responded.value = true;
355
- }
356
- return res;
357
- };
358
- return {
359
- rawResponse,
360
- hasResponded: () => responded.value || !res.writable || res.writableEnded,
361
- status: eventCore.attachHook(status, {
362
- get: () => statusCode.value,
363
- set: (code) => (statusCode.value = code),
364
- }),
365
- };
360
+ const { store } = useHttpContext();
361
+ const event = store("event");
362
+ const res = event.get("res");
363
+ const responded = store("response").hook("responded");
364
+ const statusCode = store("status").hook("code");
365
+ function status(code) {
366
+ return statusCode.value = code ? code : statusCode.value;
367
+ }
368
+ const rawResponse = (options) => {
369
+ if (!options || !options.passthrough) responded.value = true;
370
+ return res;
371
+ };
372
+ return {
373
+ rawResponse,
374
+ hasResponded: () => responded.value || !res.writable || res.writableEnded,
375
+ status: (0, __wooksjs_event_core.attachHook)(status, {
376
+ get: () => statusCode.value,
377
+ set: (code) => statusCode.value = code
378
+ })
379
+ };
366
380
  }
367
381
  function useStatus() {
368
- const { store } = useHttpContext();
369
- return store('status').hook('code');
382
+ const { store } = useHttpContext();
383
+ return store("status").hook("code");
370
384
  }
371
385
 
372
- class WooksURLSearchParams extends url.URLSearchParams {
373
- toJson() {
374
- const json = {};
375
- for (const [key, value] of this.entries()) {
376
- if (isArrayParam(key)) {
377
- const a = (json[key] = (json[key] || []));
378
- a.push(value);
379
- }
380
- else {
381
- json[key] = value;
382
- }
383
- }
384
- return json;
385
- }
386
- }
386
+ //#endregion
387
+ //#region packages/event-http/src/utils/url-search-params.ts
388
+ var WooksURLSearchParams = class extends url.URLSearchParams {
389
+ toJson() {
390
+ const json = {};
391
+ for (const [key, value] of this.entries()) if (isArrayParam(key)) {
392
+ const a = json[key] = json[key] || [];
393
+ a.push(value);
394
+ } else json[key] = value;
395
+ return json;
396
+ }
397
+ };
387
398
  function isArrayParam(name) {
388
- return name.endsWith('[]');
399
+ return name.endsWith("[]");
389
400
  }
390
401
 
402
+ //#endregion
403
+ //#region packages/event-http/src/composables/search-params.ts
391
404
  function useSearchParams() {
392
- const { store } = useHttpContext();
393
- const url = useRequest().url || '';
394
- const { init } = store('searchParams');
395
- const rawSearchParams = () => init('raw', () => {
396
- const i = url.indexOf('?');
397
- return i >= 0 ? url.slice(i) : '';
398
- });
399
- const urlSearchParams = () => init('urlSearchParams', () => new WooksURLSearchParams(rawSearchParams()));
400
- return {
401
- rawSearchParams,
402
- urlSearchParams,
403
- jsonSearchParams: () => urlSearchParams().toJson(),
404
- };
405
+ const { store } = useHttpContext();
406
+ const url$1 = useRequest().url || "";
407
+ const { init } = store("searchParams");
408
+ const rawSearchParams = () => init("raw", () => {
409
+ const i = url$1.indexOf("?");
410
+ return i >= 0 ? url$1.slice(i) : "";
411
+ });
412
+ const urlSearchParams = () => init("urlSearchParams", () => new WooksURLSearchParams(rawSearchParams()));
413
+ return {
414
+ rawSearchParams,
415
+ urlSearchParams,
416
+ jsonSearchParams: () => urlSearchParams().toJson()
417
+ };
405
418
  }
406
419
 
407
- class BaseHttpResponseRenderer {
408
- render(response) {
409
- if (typeof response.body === 'string' ||
410
- typeof response.body === 'boolean' ||
411
- typeof response.body === 'number') {
412
- if (!response.getContentType()) {
413
- response.setContentType('text/plain');
414
- }
415
- return response.body.toString();
416
- }
417
- if (response.body === undefined) {
418
- return '';
419
- }
420
- if (response.body instanceof Uint8Array) {
421
- return response.body;
422
- }
423
- if (typeof response.body === 'object') {
424
- if (!response.getContentType()) {
425
- response.setContentType('application/json');
426
- }
427
- return JSON.stringify(response.body);
428
- }
429
- throw new Error(`Unsupported body format "${typeof response.body}"`);
430
- }
431
- }
420
+ //#endregion
421
+ //#region packages/event-http/src/response/renderer.ts
422
+ var BaseHttpResponseRenderer = class {
423
+ render(response) {
424
+ if (typeof response.body === "string" || typeof response.body === "boolean" || typeof response.body === "number") {
425
+ if (!response.getContentType()) response.setContentType("text/plain");
426
+ return response.body.toString();
427
+ }
428
+ if (response.body === undefined) return "";
429
+ if (response.body instanceof Uint8Array) return response.body;
430
+ if (typeof response.body === "object") {
431
+ if (!response.getContentType()) response.setContentType("application/json");
432
+ return JSON.stringify(response.body);
433
+ }
434
+ throw new Error(`Unsupported body format "${typeof response.body}"`);
435
+ }
436
+ };
432
437
 
438
+ //#endregion
439
+ //#region packages/event-http/src/utils/status-codes.ts
433
440
  const httpStatusCodes = {
434
- 100: 'Continue',
435
- 101: 'Switching protocols',
436
- 102: 'Processing',
437
- 103: 'Early Hints',
438
- 200: 'OK',
439
- 201: 'Created',
440
- 202: 'Accepted',
441
- 203: 'Non-Authoritative Information',
442
- 204: 'No Content',
443
- 205: 'Reset Content',
444
- 206: 'Partial Content',
445
- 207: 'Multi-Status',
446
- 208: 'Already Reported',
447
- 226: 'IM Used',
448
- 300: 'Multiple Choices',
449
- 301: 'Moved Permanently',
450
- 302: 'Found (Previously "Moved Temporarily")',
451
- 303: 'See Other',
452
- 304: 'Not Modified',
453
- 305: 'Use Proxy',
454
- 306: 'Switch Proxy',
455
- 307: 'Temporary Redirect',
456
- 308: 'Permanent Redirect',
457
- 400: 'Bad Request',
458
- 401: 'Unauthorized',
459
- 402: 'Payment Required',
460
- 403: 'Forbidden',
461
- 404: 'Not Found',
462
- 405: 'Method Not Allowed',
463
- 406: 'Not Acceptable',
464
- 407: 'Proxy Authentication Required',
465
- 408: 'Request Timeout',
466
- 409: 'Conflict',
467
- 410: 'Gone',
468
- 411: 'Length Required',
469
- 412: 'Precondition Failed',
470
- 413: 'Payload Too Large',
471
- 414: 'URI Too Long',
472
- 415: 'Unsupported Media Type',
473
- 416: 'Range Not Satisfiable',
474
- 417: 'Expectation Failed',
475
- 418: "I'm a Teapot",
476
- 421: 'Misdirected Request',
477
- 422: 'Unprocessable Entity',
478
- 423: 'Locked',
479
- 424: 'Failed Dependency',
480
- 425: 'Too Early',
481
- 426: 'Upgrade Required',
482
- 428: 'Precondition Required',
483
- 429: 'Too Many Requests',
484
- 431: 'Request Header Fields Too Large',
485
- 451: 'Unavailable For Legal Reasons',
486
- 500: 'Internal Server Error',
487
- 501: 'Not Implemented',
488
- 502: 'Bad Gateway',
489
- 503: 'Service Unavailable',
490
- 504: 'Gateway Timeout',
491
- 505: 'HTTP Version Not Supported',
492
- 506: 'Variant Also Negotiates',
493
- 507: 'Insufficient Storage',
494
- 508: 'Loop Detected',
495
- 510: 'Not Extended',
496
- 511: 'Network Authentication Required',
441
+ 100: "Continue",
442
+ 101: "Switching protocols",
443
+ 102: "Processing",
444
+ 103: "Early Hints",
445
+ 200: "OK",
446
+ 201: "Created",
447
+ 202: "Accepted",
448
+ 203: "Non-Authoritative Information",
449
+ 204: "No Content",
450
+ 205: "Reset Content",
451
+ 206: "Partial Content",
452
+ 207: "Multi-Status",
453
+ 208: "Already Reported",
454
+ 226: "IM Used",
455
+ 300: "Multiple Choices",
456
+ 301: "Moved Permanently",
457
+ 302: "Found (Previously \"Moved Temporarily\")",
458
+ 303: "See Other",
459
+ 304: "Not Modified",
460
+ 305: "Use Proxy",
461
+ 306: "Switch Proxy",
462
+ 307: "Temporary Redirect",
463
+ 308: "Permanent Redirect",
464
+ 400: "Bad Request",
465
+ 401: "Unauthorized",
466
+ 402: "Payment Required",
467
+ 403: "Forbidden",
468
+ 404: "Not Found",
469
+ 405: "Method Not Allowed",
470
+ 406: "Not Acceptable",
471
+ 407: "Proxy Authentication Required",
472
+ 408: "Request Timeout",
473
+ 409: "Conflict",
474
+ 410: "Gone",
475
+ 411: "Length Required",
476
+ 412: "Precondition Failed",
477
+ 413: "Payload Too Large",
478
+ 414: "URI Too Long",
479
+ 415: "Unsupported Media Type",
480
+ 416: "Range Not Satisfiable",
481
+ 417: "Expectation Failed",
482
+ 418: "I'm a Teapot",
483
+ 421: "Misdirected Request",
484
+ 422: "Unprocessable Entity",
485
+ 423: "Locked",
486
+ 424: "Failed Dependency",
487
+ 425: "Too Early",
488
+ 426: "Upgrade Required",
489
+ 428: "Precondition Required",
490
+ 429: "Too Many Requests",
491
+ 431: "Request Header Fields Too Large",
492
+ 451: "Unavailable For Legal Reasons",
493
+ 500: "Internal Server Error",
494
+ 501: "Not Implemented",
495
+ 502: "Bad Gateway",
496
+ 503: "Service Unavailable",
497
+ 504: "Gateway Timeout",
498
+ 505: "HTTP Version Not Supported",
499
+ 506: "Variant Also Negotiates",
500
+ 507: "Insufficient Storage",
501
+ 508: "Loop Detected",
502
+ 510: "Not Extended",
503
+ 511: "Network Authentication Required"
497
504
  };
498
- exports.EHttpStatusCode = void 0;
499
- (function (EHttpStatusCode) {
500
- EHttpStatusCode[EHttpStatusCode["Continue"] = 100] = "Continue";
501
- EHttpStatusCode[EHttpStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
502
- EHttpStatusCode[EHttpStatusCode["Processing"] = 102] = "Processing";
503
- EHttpStatusCode[EHttpStatusCode["EarlyHints"] = 103] = "EarlyHints";
504
- EHttpStatusCode[EHttpStatusCode["OK"] = 200] = "OK";
505
- EHttpStatusCode[EHttpStatusCode["Created"] = 201] = "Created";
506
- EHttpStatusCode[EHttpStatusCode["Accepted"] = 202] = "Accepted";
507
- EHttpStatusCode[EHttpStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
508
- EHttpStatusCode[EHttpStatusCode["NoContent"] = 204] = "NoContent";
509
- EHttpStatusCode[EHttpStatusCode["ResetContent"] = 205] = "ResetContent";
510
- EHttpStatusCode[EHttpStatusCode["PartialContent"] = 206] = "PartialContent";
511
- EHttpStatusCode[EHttpStatusCode["MultiStatus"] = 207] = "MultiStatus";
512
- EHttpStatusCode[EHttpStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
513
- EHttpStatusCode[EHttpStatusCode["IMUsed"] = 226] = "IMUsed";
514
- EHttpStatusCode[EHttpStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
515
- EHttpStatusCode[EHttpStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
516
- EHttpStatusCode[EHttpStatusCode["Found"] = 302] = "Found";
517
- EHttpStatusCode[EHttpStatusCode["SeeOther"] = 303] = "SeeOther";
518
- EHttpStatusCode[EHttpStatusCode["NotModified"] = 304] = "NotModified";
519
- EHttpStatusCode[EHttpStatusCode["UseProxy"] = 305] = "UseProxy";
520
- EHttpStatusCode[EHttpStatusCode["SwitchProxy"] = 306] = "SwitchProxy";
521
- EHttpStatusCode[EHttpStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
522
- EHttpStatusCode[EHttpStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
523
- EHttpStatusCode[EHttpStatusCode["BadRequest"] = 400] = "BadRequest";
524
- EHttpStatusCode[EHttpStatusCode["Unauthorized"] = 401] = "Unauthorized";
525
- EHttpStatusCode[EHttpStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
526
- EHttpStatusCode[EHttpStatusCode["Forbidden"] = 403] = "Forbidden";
527
- EHttpStatusCode[EHttpStatusCode["NotFound"] = 404] = "NotFound";
528
- EHttpStatusCode[EHttpStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
529
- EHttpStatusCode[EHttpStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
530
- EHttpStatusCode[EHttpStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
531
- EHttpStatusCode[EHttpStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
532
- EHttpStatusCode[EHttpStatusCode["Conflict"] = 409] = "Conflict";
533
- EHttpStatusCode[EHttpStatusCode["Gone"] = 410] = "Gone";
534
- EHttpStatusCode[EHttpStatusCode["LengthRequired"] = 411] = "LengthRequired";
535
- EHttpStatusCode[EHttpStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
536
- EHttpStatusCode[EHttpStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
537
- EHttpStatusCode[EHttpStatusCode["URITooLong"] = 414] = "URITooLong";
538
- EHttpStatusCode[EHttpStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
539
- EHttpStatusCode[EHttpStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
540
- EHttpStatusCode[EHttpStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
541
- EHttpStatusCode[EHttpStatusCode["ImATeapot"] = 418] = "ImATeapot";
542
- EHttpStatusCode[EHttpStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
543
- EHttpStatusCode[EHttpStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
544
- EHttpStatusCode[EHttpStatusCode["Locked"] = 423] = "Locked";
545
- EHttpStatusCode[EHttpStatusCode["FailedDependency"] = 424] = "FailedDependency";
546
- EHttpStatusCode[EHttpStatusCode["TooEarly"] = 425] = "TooEarly";
547
- EHttpStatusCode[EHttpStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
548
- EHttpStatusCode[EHttpStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
549
- EHttpStatusCode[EHttpStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
550
- EHttpStatusCode[EHttpStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
551
- EHttpStatusCode[EHttpStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
552
- EHttpStatusCode[EHttpStatusCode["InternalServerError"] = 500] = "InternalServerError";
553
- EHttpStatusCode[EHttpStatusCode["NotImplemented"] = 501] = "NotImplemented";
554
- EHttpStatusCode[EHttpStatusCode["BadGateway"] = 502] = "BadGateway";
555
- EHttpStatusCode[EHttpStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
556
- EHttpStatusCode[EHttpStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
557
- EHttpStatusCode[EHttpStatusCode["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
558
- EHttpStatusCode[EHttpStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
559
- EHttpStatusCode[EHttpStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
560
- EHttpStatusCode[EHttpStatusCode["LoopDetected"] = 508] = "LoopDetected";
561
- EHttpStatusCode[EHttpStatusCode["NotExtended"] = 510] = "NotExtended";
562
- EHttpStatusCode[EHttpStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
563
- })(exports.EHttpStatusCode || (exports.EHttpStatusCode = {}));
505
+ let EHttpStatusCode = function(EHttpStatusCode$1) {
506
+ EHttpStatusCode$1[EHttpStatusCode$1["Continue"] = 100] = "Continue";
507
+ EHttpStatusCode$1[EHttpStatusCode$1["SwitchingProtocols"] = 101] = "SwitchingProtocols";
508
+ EHttpStatusCode$1[EHttpStatusCode$1["Processing"] = 102] = "Processing";
509
+ EHttpStatusCode$1[EHttpStatusCode$1["EarlyHints"] = 103] = "EarlyHints";
510
+ EHttpStatusCode$1[EHttpStatusCode$1["OK"] = 200] = "OK";
511
+ EHttpStatusCode$1[EHttpStatusCode$1["Created"] = 201] = "Created";
512
+ EHttpStatusCode$1[EHttpStatusCode$1["Accepted"] = 202] = "Accepted";
513
+ EHttpStatusCode$1[EHttpStatusCode$1["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
514
+ EHttpStatusCode$1[EHttpStatusCode$1["NoContent"] = 204] = "NoContent";
515
+ EHttpStatusCode$1[EHttpStatusCode$1["ResetContent"] = 205] = "ResetContent";
516
+ EHttpStatusCode$1[EHttpStatusCode$1["PartialContent"] = 206] = "PartialContent";
517
+ EHttpStatusCode$1[EHttpStatusCode$1["MultiStatus"] = 207] = "MultiStatus";
518
+ EHttpStatusCode$1[EHttpStatusCode$1["AlreadyReported"] = 208] = "AlreadyReported";
519
+ EHttpStatusCode$1[EHttpStatusCode$1["IMUsed"] = 226] = "IMUsed";
520
+ EHttpStatusCode$1[EHttpStatusCode$1["MultipleChoices"] = 300] = "MultipleChoices";
521
+ EHttpStatusCode$1[EHttpStatusCode$1["MovedPermanently"] = 301] = "MovedPermanently";
522
+ EHttpStatusCode$1[EHttpStatusCode$1["Found"] = 302] = "Found";
523
+ EHttpStatusCode$1[EHttpStatusCode$1["SeeOther"] = 303] = "SeeOther";
524
+ EHttpStatusCode$1[EHttpStatusCode$1["NotModified"] = 304] = "NotModified";
525
+ EHttpStatusCode$1[EHttpStatusCode$1["UseProxy"] = 305] = "UseProxy";
526
+ EHttpStatusCode$1[EHttpStatusCode$1["SwitchProxy"] = 306] = "SwitchProxy";
527
+ EHttpStatusCode$1[EHttpStatusCode$1["TemporaryRedirect"] = 307] = "TemporaryRedirect";
528
+ EHttpStatusCode$1[EHttpStatusCode$1["PermanentRedirect"] = 308] = "PermanentRedirect";
529
+ EHttpStatusCode$1[EHttpStatusCode$1["BadRequest"] = 400] = "BadRequest";
530
+ EHttpStatusCode$1[EHttpStatusCode$1["Unauthorized"] = 401] = "Unauthorized";
531
+ EHttpStatusCode$1[EHttpStatusCode$1["PaymentRequired"] = 402] = "PaymentRequired";
532
+ EHttpStatusCode$1[EHttpStatusCode$1["Forbidden"] = 403] = "Forbidden";
533
+ EHttpStatusCode$1[EHttpStatusCode$1["NotFound"] = 404] = "NotFound";
534
+ EHttpStatusCode$1[EHttpStatusCode$1["MethodNotAllowed"] = 405] = "MethodNotAllowed";
535
+ EHttpStatusCode$1[EHttpStatusCode$1["NotAcceptable"] = 406] = "NotAcceptable";
536
+ EHttpStatusCode$1[EHttpStatusCode$1["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
537
+ EHttpStatusCode$1[EHttpStatusCode$1["RequestTimeout"] = 408] = "RequestTimeout";
538
+ EHttpStatusCode$1[EHttpStatusCode$1["Conflict"] = 409] = "Conflict";
539
+ EHttpStatusCode$1[EHttpStatusCode$1["Gone"] = 410] = "Gone";
540
+ EHttpStatusCode$1[EHttpStatusCode$1["LengthRequired"] = 411] = "LengthRequired";
541
+ EHttpStatusCode$1[EHttpStatusCode$1["PreconditionFailed"] = 412] = "PreconditionFailed";
542
+ EHttpStatusCode$1[EHttpStatusCode$1["PayloadTooLarge"] = 413] = "PayloadTooLarge";
543
+ EHttpStatusCode$1[EHttpStatusCode$1["URITooLong"] = 414] = "URITooLong";
544
+ EHttpStatusCode$1[EHttpStatusCode$1["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
545
+ EHttpStatusCode$1[EHttpStatusCode$1["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
546
+ EHttpStatusCode$1[EHttpStatusCode$1["ExpectationFailed"] = 417] = "ExpectationFailed";
547
+ EHttpStatusCode$1[EHttpStatusCode$1["ImATeapot"] = 418] = "ImATeapot";
548
+ EHttpStatusCode$1[EHttpStatusCode$1["MisdirectedRequest"] = 421] = "MisdirectedRequest";
549
+ EHttpStatusCode$1[EHttpStatusCode$1["UnprocessableEntity"] = 422] = "UnprocessableEntity";
550
+ EHttpStatusCode$1[EHttpStatusCode$1["Locked"] = 423] = "Locked";
551
+ EHttpStatusCode$1[EHttpStatusCode$1["FailedDependency"] = 424] = "FailedDependency";
552
+ EHttpStatusCode$1[EHttpStatusCode$1["TooEarly"] = 425] = "TooEarly";
553
+ EHttpStatusCode$1[EHttpStatusCode$1["UpgradeRequired"] = 426] = "UpgradeRequired";
554
+ EHttpStatusCode$1[EHttpStatusCode$1["PreconditionRequired"] = 428] = "PreconditionRequired";
555
+ EHttpStatusCode$1[EHttpStatusCode$1["TooManyRequests"] = 429] = "TooManyRequests";
556
+ EHttpStatusCode$1[EHttpStatusCode$1["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
557
+ EHttpStatusCode$1[EHttpStatusCode$1["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
558
+ EHttpStatusCode$1[EHttpStatusCode$1["InternalServerError"] = 500] = "InternalServerError";
559
+ EHttpStatusCode$1[EHttpStatusCode$1["NotImplemented"] = 501] = "NotImplemented";
560
+ EHttpStatusCode$1[EHttpStatusCode$1["BadGateway"] = 502] = "BadGateway";
561
+ EHttpStatusCode$1[EHttpStatusCode$1["ServiceUnavailable"] = 503] = "ServiceUnavailable";
562
+ EHttpStatusCode$1[EHttpStatusCode$1["GatewayTimeout"] = 504] = "GatewayTimeout";
563
+ EHttpStatusCode$1[EHttpStatusCode$1["HTTPVersionNotSupported"] = 505] = "HTTPVersionNotSupported";
564
+ EHttpStatusCode$1[EHttpStatusCode$1["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
565
+ EHttpStatusCode$1[EHttpStatusCode$1["InsufficientStorage"] = 507] = "InsufficientStorage";
566
+ EHttpStatusCode$1[EHttpStatusCode$1["LoopDetected"] = 508] = "LoopDetected";
567
+ EHttpStatusCode$1[EHttpStatusCode$1["NotExtended"] = 510] = "NotExtended";
568
+ EHttpStatusCode$1[EHttpStatusCode$1["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
569
+ return EHttpStatusCode$1;
570
+ }({});
564
571
 
565
- const preStyles = 'font-family: monospace;' +
566
- 'width: 100%;' +
567
- 'max-width: 900px;' +
568
- 'padding: 10px;' +
569
- 'margin: 20px auto;' +
570
- 'border-radius: 8px;' +
571
- 'background-color: #494949;' +
572
- 'box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);';
573
- class HttpErrorRenderer extends BaseHttpResponseRenderer {
574
- renderHtml(response) {
575
- const data = response.body || {};
576
- response.setContentType('text/html');
577
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
578
- return ('<html style="background-color: #333; color: #bbb;">' +
579
- `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
580
- `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
581
- `<center><h4>${data.message}</h1></center><hr color="#666">` +
582
- `<center style="color: #666;"> Wooks v${"0.5.20"} </center>` +
583
- `${keys.length > 0
584
- ? `<pre style="${preStyles}">${JSON.stringify({
585
- ...data,
586
- statusCode: undefined,
587
- message: undefined,
588
- error: undefined,
589
- }, null, ' ')}</pre>`
590
- : ''}` +
591
- '</body></html>');
592
- }
593
- renderText(response) {
594
- const data = response.body || {};
595
- response.setContentType('text/plain');
596
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
597
- return (`${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` +
598
- `\n\n${keys.length > 0
599
- ? `${JSON.stringify({
600
- ...data,
601
- statusCode: undefined,
602
- message: undefined,
603
- error: undefined,
604
- }, null, ' ')}`
605
- : ''}`);
606
- }
607
- renderJson(response) {
608
- const data = response.body || {};
609
- response.setContentType('application/json');
610
- const keys = Object.keys(data).filter(key => !['statusCode', 'error', 'message'].includes(key));
611
- return (`{"statusCode":${escapeQuotes(data.statusCode)},` +
612
- `"error":"${escapeQuotes(data.error)}",` +
613
- `"message":"${escapeQuotes(data.message)}"` +
614
- `${keys.length > 0
615
- ? `,${keys.map(k => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`).join(',')}`
616
- : ''}}`);
617
- }
618
- render(response) {
619
- const { acceptsJson, acceptsText, acceptsHtml } = useAccept();
620
- response.status = response.body?.statusCode || 500;
621
- if (acceptsJson()) {
622
- return this.renderJson(response);
623
- }
624
- else if (acceptsHtml()) {
625
- return this.renderHtml(response);
626
- }
627
- else if (acceptsText()) {
628
- return this.renderText(response);
629
- }
630
- else {
631
- return this.renderJson(response);
632
- }
633
- }
634
- }
572
+ //#endregion
573
+ //#region packages/event-http/src/errors/error-renderer.ts
574
+ const preStyles = "font-family: monospace;width: 100%;max-width: 900px;padding: 10px;margin: 20px auto;border-radius: 8px;background-color: #494949;box-shadow: 0px 0px 3px 2px rgb(255 255 255 / 20%);";
575
+ var HttpErrorRenderer = class extends BaseHttpResponseRenderer {
576
+ renderHtml(response) {
577
+ const data = response.body || {};
578
+ response.setContentType("text/html");
579
+ const keys = Object.keys(data).filter((key) => ![
580
+ "statusCode",
581
+ "error",
582
+ "message"
583
+ ].includes(key));
584
+ return "<html style=\"background-color: #333; color: #bbb;\">" + `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` + `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` + `<center><h4>${data.message}</h1></center><hr color="#666">` + `<center style="color: #666;"> Wooks v${"0.5.24"} </center>` + `${keys.length > 0 ? `<pre style="${preStyles}">${JSON.stringify({
585
+ ...data,
586
+ statusCode: undefined,
587
+ message: undefined,
588
+ error: undefined
589
+ }, null, " ")}</pre>` : ""}` + "</body></html>";
590
+ }
591
+ renderText(response) {
592
+ const data = response.body || {};
593
+ response.setContentType("text/plain");
594
+ const keys = Object.keys(data).filter((key) => ![
595
+ "statusCode",
596
+ "error",
597
+ "message"
598
+ ].includes(key));
599
+ return `${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` + `\n\n${keys.length > 0 ? `${JSON.stringify({
600
+ ...data,
601
+ statusCode: undefined,
602
+ message: undefined,
603
+ error: undefined
604
+ }, null, " ")}` : ""}`;
605
+ }
606
+ renderJson(response) {
607
+ const data = response.body || {};
608
+ response.setContentType("application/json");
609
+ const keys = Object.keys(data).filter((key) => ![
610
+ "statusCode",
611
+ "error",
612
+ "message"
613
+ ].includes(key));
614
+ return `{"statusCode":${escapeQuotes(data.statusCode)},` + `"error":"${escapeQuotes(data.error)}",` + `"message":"${escapeQuotes(data.message)}"` + `${keys.length > 0 ? `,${keys.map((k) => `"${escapeQuotes(k)}":${JSON.stringify(data[k])}`).join(",")}` : ""}}`;
615
+ }
616
+ render(response) {
617
+ const { acceptsJson, acceptsText, acceptsHtml } = useAccept();
618
+ response.status = response.body?.statusCode || 500;
619
+ if (acceptsJson()) return this.renderJson(response);
620
+ else if (acceptsHtml()) return this.renderHtml(response);
621
+ else if (acceptsText()) return this.renderText(response);
622
+ else return this.renderJson(response);
623
+ }
624
+ };
635
625
  function escapeQuotes(s) {
636
- return (typeof s === 'number' ? s : s || '').toString().replace(/"/g, '\\"');
626
+ return (typeof s === "number" ? s : s || "").toString().replace(/"/gu, "\\\"");
637
627
  }
638
628
 
639
- class HttpError extends Error {
640
- constructor(code = 500, _body = '') {
641
- super(typeof _body === 'string' ? _body : _body.message);
642
- this.code = code;
643
- this._body = _body;
644
- this.name = 'HttpError';
645
- }
646
- get body() {
647
- return typeof this._body === 'string'
648
- ? {
649
- statusCode: this.code,
650
- message: this.message,
651
- error: httpStatusCodes[this.code],
652
- }
653
- : {
654
- ...this._body,
655
- statusCode: this.code,
656
- message: this.message,
657
- error: httpStatusCodes[this.code],
658
- };
659
- }
660
- attachRenderer(renderer) {
661
- this.renderer = renderer;
662
- }
663
- getRenderer() {
664
- return this.renderer;
665
- }
666
- }
629
+ //#endregion
630
+ //#region packages/event-http/src/errors/http-error.ts
631
+ var HttpError = class extends Error {
632
+ name = "HttpError";
633
+ constructor(code = 500, _body = "") {
634
+ super(typeof _body === "string" ? _body : _body.message);
635
+ this.code = code;
636
+ this._body = _body;
637
+ }
638
+ get body() {
639
+ return typeof this._body === "string" ? {
640
+ statusCode: this.code,
641
+ message: this.message,
642
+ error: httpStatusCodes[this.code]
643
+ } : {
644
+ ...this._body,
645
+ statusCode: this.code,
646
+ message: this.message,
647
+ error: httpStatusCodes[this.code]
648
+ };
649
+ }
650
+ renderer;
651
+ attachRenderer(renderer) {
652
+ this.renderer = renderer;
653
+ }
654
+ getRenderer() {
655
+ return this.renderer;
656
+ }
657
+ };
667
658
 
659
+ //#endregion
660
+ //#region packages/event-http/src/response/core.ts
668
661
  const defaultStatus = {
669
- GET: exports.EHttpStatusCode.OK,
670
- POST: exports.EHttpStatusCode.Created,
671
- PUT: exports.EHttpStatusCode.Created,
672
- PATCH: exports.EHttpStatusCode.Accepted,
673
- DELETE: exports.EHttpStatusCode.Accepted,
662
+ GET: EHttpStatusCode.OK,
663
+ POST: EHttpStatusCode.Created,
664
+ PUT: EHttpStatusCode.Created,
665
+ PATCH: EHttpStatusCode.Accepted,
666
+ DELETE: EHttpStatusCode.Accepted
674
667
  };
675
668
  const baseRenderer = new BaseHttpResponseRenderer();
676
- class BaseHttpResponse {
677
- constructor(renderer = baseRenderer) {
678
- this.renderer = renderer;
679
- this._status = 0;
680
- this._headers = {};
681
- }
682
- get status() {
683
- return this._status;
684
- }
685
- set status(value) {
686
- this._status = value;
687
- }
688
- get body() {
689
- return this._body;
690
- }
691
- set body(value) {
692
- this._body = value;
693
- }
694
- setStatus(value) {
695
- this.status = value;
696
- return this;
697
- }
698
- setBody(value) {
699
- this.body = value;
700
- return this;
701
- }
702
- getContentType() {
703
- return this._headers['content-type'];
704
- }
705
- setContentType(value) {
706
- this._headers['content-type'] = value;
707
- return this;
708
- }
709
- enableCors(origin = '*') {
710
- this._headers['Access-Control-Allow-Origin'] = origin;
711
- return this;
712
- }
713
- setCookie(name, value, attrs) {
714
- const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
715
- cookies.push(renderCookie(name, { value, attrs: attrs || {} }));
716
- return this;
717
- }
718
- setCacheControl(data) {
719
- this.setHeader('cache-control', renderCacheControl(data));
720
- }
721
- setCookieRaw(rawValue) {
722
- const cookies = (this._headers['set-cookie'] = (this._headers['set-cookie'] || []));
723
- cookies.push(rawValue);
724
- return this;
725
- }
726
- header(name, value) {
727
- this._headers[name] = value;
728
- return this;
729
- }
730
- setHeader(name, value) {
731
- return this.header(name, value);
732
- }
733
- getHeader(name) {
734
- return this._headers[name];
735
- }
736
- mergeHeaders() {
737
- const { headers } = useSetHeaders();
738
- const { cookies, removeCookie } = useSetCookies();
739
- const newCookies = this._headers['set-cookie'] || [];
740
- for (const cookie of newCookies) {
741
- removeCookie(cookie.slice(0, cookie.indexOf('=')));
742
- }
743
- this._headers = {
744
- ...headers(),
745
- ...this._headers,
746
- };
747
- const setCookie = [...newCookies, ...cookies()];
748
- if (setCookie.length > 0) {
749
- this._headers['set-cookie'] = setCookie;
750
- }
751
- return this;
752
- }
753
- mergeStatus(renderedBody) {
754
- this.status = this.status || useResponse().status();
755
- if (!this.status) {
756
- const { method } = useRequest();
757
- this.status = renderedBody
758
- ? defaultStatus[method] || exports.EHttpStatusCode.OK
759
- : exports.EHttpStatusCode.NoContent;
760
- }
761
- return this;
762
- }
763
- mergeFetchStatus(fetchStatus) {
764
- this.status = this.status || useResponse().status() || fetchStatus;
765
- }
766
- panic(text, logger) {
767
- const error = new Error(text);
768
- logger.error(error);
769
- throw error;
770
- }
771
- async respond() {
772
- const { rawResponse, hasResponded } = useResponse();
773
- const { method, rawRequest } = useRequest();
774
- const logger = eventCore.useEventLogger('http-response') || console;
775
- if (hasResponded()) {
776
- this.panic('The response was already sent.', logger);
777
- }
778
- this.mergeHeaders();
779
- const res = rawResponse();
780
- if (this.body instanceof stream.Readable) {
781
- const stream = this.body;
782
- this.mergeStatus('ok');
783
- res.writeHead(this.status, {
784
- ...this._headers,
785
- });
786
- rawRequest.once('close', () => {
787
- stream.destroy();
788
- });
789
- if (method === 'HEAD') {
790
- stream.destroy();
791
- res.end();
792
- }
793
- else {
794
- return new Promise((resolve, reject) => {
795
- stream.on('error', e => {
796
- stream.destroy();
797
- res.end();
798
- reject(e);
799
- });
800
- stream.on('close', () => {
801
- stream.destroy();
802
- resolve(undefined);
803
- });
804
- stream.pipe(res);
805
- });
806
- }
807
- }
808
- else if (globalThis.Response && this.body instanceof Response) {
809
- this.mergeFetchStatus(this.body.status);
810
- if (method === 'HEAD') {
811
- res.end();
812
- }
813
- else {
814
- const additionalHeaders = {};
815
- if (this.body.headers.get('content-length')) {
816
- additionalHeaders['content-length'] = this.body.headers.get('content-length');
817
- }
818
- if (this.body.headers.get('content-type')) {
819
- additionalHeaders['content-type'] = this.body.headers.get('content-type');
820
- }
821
- res.writeHead(this.status, {
822
- ...additionalHeaders,
823
- ...this._headers,
824
- });
825
- await respondWithFetch(this.body.body, res);
826
- }
827
- }
828
- else {
829
- const renderedBody = this.renderer.render(this);
830
- this.mergeStatus(renderedBody);
831
- res
832
- .writeHead(this.status, {
833
- 'content-length': Buffer.byteLength(renderedBody),
834
- ...this._headers,
835
- })
836
- .end(method === 'HEAD' ? '' : renderedBody);
837
- }
838
- }
839
- }
669
+ var BaseHttpResponse = class {
670
+ constructor(renderer = baseRenderer) {
671
+ this.renderer = renderer;
672
+ }
673
+ _status = 0;
674
+ _body;
675
+ _headers = {};
676
+ get status() {
677
+ return this._status;
678
+ }
679
+ set status(value) {
680
+ this._status = value;
681
+ }
682
+ get body() {
683
+ return this._body;
684
+ }
685
+ set body(value) {
686
+ this._body = value;
687
+ }
688
+ setStatus(value) {
689
+ this.status = value;
690
+ return this;
691
+ }
692
+ setBody(value) {
693
+ this.body = value;
694
+ return this;
695
+ }
696
+ getContentType() {
697
+ return this._headers["content-type"];
698
+ }
699
+ setContentType(value) {
700
+ this._headers["content-type"] = value;
701
+ return this;
702
+ }
703
+ enableCors(origin = "*") {
704
+ this._headers["Access-Control-Allow-Origin"] = origin;
705
+ return this;
706
+ }
707
+ setCookie(name, value, attrs) {
708
+ const cookies = this._headers["set-cookie"] = this._headers["set-cookie"] || [];
709
+ cookies.push(renderCookie(name, {
710
+ value,
711
+ attrs: attrs || {}
712
+ }));
713
+ return this;
714
+ }
715
+ setCacheControl(data) {
716
+ this.setHeader("cache-control", renderCacheControl(data));
717
+ }
718
+ setCookieRaw(rawValue) {
719
+ const cookies = this._headers["set-cookie"] = this._headers["set-cookie"] || [];
720
+ cookies.push(rawValue);
721
+ return this;
722
+ }
723
+ header(name, value) {
724
+ this._headers[name] = value;
725
+ return this;
726
+ }
727
+ setHeader(name, value) {
728
+ return this.header(name, value);
729
+ }
730
+ getHeader(name) {
731
+ return this._headers[name];
732
+ }
733
+ mergeHeaders() {
734
+ const { headers } = useSetHeaders();
735
+ const { cookies, removeCookie } = useSetCookies();
736
+ const newCookies = this._headers["set-cookie"] || [];
737
+ for (const cookie of newCookies) removeCookie(cookie.slice(0, cookie.indexOf("=")));
738
+ this._headers = {
739
+ ...headers(),
740
+ ...this._headers
741
+ };
742
+ const setCookie = [...newCookies, ...cookies()];
743
+ if (setCookie.length > 0) this._headers["set-cookie"] = setCookie;
744
+ return this;
745
+ }
746
+ mergeStatus(renderedBody) {
747
+ this.status = this.status || useResponse().status();
748
+ if (!this.status) {
749
+ const { method } = useRequest();
750
+ this.status = renderedBody ? defaultStatus[method] || EHttpStatusCode.OK : EHttpStatusCode.NoContent;
751
+ }
752
+ return this;
753
+ }
754
+ mergeFetchStatus(fetchStatus) {
755
+ this.status = this.status || useResponse().status() || fetchStatus;
756
+ }
757
+ panic(text, logger) {
758
+ const error = new Error(text);
759
+ logger.error(error);
760
+ throw error;
761
+ }
762
+ async respond() {
763
+ const { rawResponse, hasResponded } = useResponse();
764
+ const { method, rawRequest } = useRequest();
765
+ const logger = (0, __wooksjs_event_core.useEventLogger)("http-response") || console;
766
+ if (hasResponded()) this.panic("The response was already sent.", logger);
767
+ this.mergeHeaders();
768
+ const res = rawResponse();
769
+ if (this.body instanceof stream.Readable) {
770
+ const stream$1 = this.body;
771
+ this.mergeStatus("ok");
772
+ res.writeHead(this.status, { ...this._headers });
773
+ rawRequest.once("close", () => {
774
+ stream$1.destroy();
775
+ });
776
+ if (method === "HEAD") {
777
+ stream$1.destroy();
778
+ res.end();
779
+ } else return new Promise((resolve, reject) => {
780
+ stream$1.on("error", (e) => {
781
+ stream$1.destroy();
782
+ res.end();
783
+ reject(e);
784
+ });
785
+ stream$1.on("close", () => {
786
+ stream$1.destroy();
787
+ resolve(undefined);
788
+ });
789
+ stream$1.pipe(res);
790
+ });
791
+ } else if (globalThis.Response && this.body instanceof Response) {
792
+ this.mergeFetchStatus(this.body.status);
793
+ if (method === "HEAD") res.end();
794
+ else {
795
+ const additionalHeaders = {};
796
+ if (this.body.headers.get("content-length")) additionalHeaders["content-length"] = this.body.headers.get("content-length");
797
+ if (this.body.headers.get("content-type")) additionalHeaders["content-type"] = this.body.headers.get("content-type");
798
+ res.writeHead(this.status, {
799
+ ...additionalHeaders,
800
+ ...this._headers
801
+ });
802
+ await respondWithFetch(this.body.body, res);
803
+ }
804
+ } else {
805
+ const renderedBody = this.renderer.render(this);
806
+ this.mergeStatus(renderedBody);
807
+ res.writeHead(this.status, {
808
+ "content-length": Buffer.byteLength(renderedBody),
809
+ ...this._headers
810
+ }).end(method === "HEAD" ? "" : renderedBody);
811
+ }
812
+ }
813
+ };
840
814
  async function respondWithFetch(fetchBody, res) {
841
- if (fetchBody) {
842
- try {
843
- for await (const chunk of fetchBody) {
844
- res.write(chunk);
845
- }
846
- }
847
- catch (error) {
848
- }
849
- }
850
- res.end();
815
+ if (fetchBody) try {
816
+ for await (const chunk of fetchBody) res.write(chunk);
817
+ } catch (error) {}
818
+ res.end();
851
819
  }
852
820
 
821
+ //#endregion
822
+ //#region packages/event-http/src/response/factory.ts
853
823
  function createWooksResponder(renderer = new BaseHttpResponseRenderer(), errorRenderer = new HttpErrorRenderer()) {
854
- function createResponse(data) {
855
- const { hasResponded } = useResponse();
856
- if (hasResponded()) {
857
- return null;
858
- }
859
- if (data instanceof Error) {
860
- const r = new BaseHttpResponse(errorRenderer);
861
- let httpError;
862
- if (data instanceof HttpError) {
863
- httpError = data;
864
- }
865
- else {
866
- httpError = new HttpError(500, data.message);
867
- }
868
- r.setBody(httpError.body);
869
- return r;
870
- }
871
- else if (data instanceof BaseHttpResponse) {
872
- return data;
873
- }
874
- else {
875
- return new BaseHttpResponse(renderer).setBody(data);
876
- }
877
- }
878
- return {
879
- createResponse,
880
- respond: (data) => createResponse(data)?.respond(),
881
- };
824
+ function createResponse(data) {
825
+ const { hasResponded } = useResponse();
826
+ if (hasResponded()) return null;
827
+ if (data instanceof Error) {
828
+ const r = new BaseHttpResponse(errorRenderer);
829
+ let httpError;
830
+ if (data instanceof HttpError) httpError = data;
831
+ else httpError = new HttpError(500, data.message);
832
+ r.setBody(httpError.body);
833
+ return r;
834
+ } else if (data instanceof BaseHttpResponse) return data;
835
+ else return new BaseHttpResponse(renderer).setBody(data);
836
+ }
837
+ return {
838
+ createResponse,
839
+ respond: (data) => createResponse(data)?.respond()
840
+ };
882
841
  }
883
842
 
884
- class WooksHttp extends wooks.WooksAdapterBase {
885
- constructor(opts, wooks) {
886
- super(wooks, opts?.logger, opts?.router);
887
- this.opts = opts;
888
- this.responder = createWooksResponder();
889
- this.logger = opts?.logger || this.getLogger(`${''}[wooks-http]`);
890
- }
891
- all(path, handler) {
892
- return this.on('*', path, handler);
893
- }
894
- get(path, handler) {
895
- return this.on('GET', path, handler);
896
- }
897
- post(path, handler) {
898
- return this.on('POST', path, handler);
899
- }
900
- put(path, handler) {
901
- return this.on('PUT', path, handler);
902
- }
903
- patch(path, handler) {
904
- return this.on('PATCH', path, handler);
905
- }
906
- delete(path, handler) {
907
- return this.on('DELETE', path, handler);
908
- }
909
- head(path, handler) {
910
- return this.on('HEAD', path, handler);
911
- }
912
- options(path, handler) {
913
- return this.on('OPTIONS', path, handler);
914
- }
915
- async listen(port, hostname, backlog, listeningListener) {
916
- const server = (this.server = http.createServer(this.getServerCb()));
917
- return new Promise((resolve, reject) => {
918
- server.once('listening', resolve);
919
- server.once('error', reject);
920
- let args = [port, hostname, backlog, listeningListener];
921
- const ui = args.indexOf(undefined);
922
- if (ui >= 0) {
923
- args = args.slice(0, ui);
924
- }
925
- server.listen(...args);
926
- });
927
- }
928
- close(server) {
929
- const srv = server || this.server;
930
- return new Promise((resolve, reject) => {
931
- srv?.close(err => {
932
- if (err) {
933
- reject(err);
934
- return;
935
- }
936
- resolve(srv);
937
- });
938
- });
939
- }
940
- getServer() {
941
- return this.server;
942
- }
943
- attachServer(server) {
944
- this.server = server;
945
- }
946
- respond(data) {
947
- void this.responder.respond(data)?.catch(e => {
948
- this.logger.error('Uncaught response exception', e);
949
- });
950
- }
951
- getServerCb() {
952
- return (req, res) => {
953
- const runInContext = createHttpContext({ req, res }, this.mergeEventOptions(this.opts?.eventOptions));
954
- runInContext(async () => {
955
- const { handlers } = this.wooks.lookup(req.method, req.url);
956
- if (handlers || this.opts?.onNotFound) {
957
- try {
958
- return await this.processHandlers(handlers || [this.opts?.onNotFound]);
959
- }
960
- catch (error) {
961
- this.logger.error('Internal error, please report', error);
962
- this.respond(error);
963
- return error;
964
- }
965
- }
966
- else {
967
- this.logger.debug(`404 Not found (${req.method})${req.url}`);
968
- const error = new HttpError(404);
969
- this.respond(error);
970
- return error;
971
- }
972
- });
973
- };
974
- }
975
- async processHandlers(handlers) {
976
- const { store } = useHttpContext();
977
- for (const [i, handler] of handlers.entries()) {
978
- const isLastHandler = handlers.length === i + 1;
979
- try {
980
- const promise = handler();
981
- const result = await promise;
982
- this.respond(result);
983
- return result;
984
- }
985
- catch (error) {
986
- if (error instanceof HttpError) ;
987
- else {
988
- this.logger.error(`Uncaught route handler exception: ${store('event').get('req')?.url || ''}`, error);
989
- }
990
- if (isLastHandler) {
991
- this.respond(error);
992
- return error;
993
- }
994
- }
995
- }
996
- }
997
- }
998
- function createHttpApp(opts, wooks) {
999
- return new WooksHttp(opts, wooks);
843
+ //#endregion
844
+ //#region packages/event-http/src/http-adapter.ts
845
+ var WooksHttp = class extends wooks.WooksAdapterBase {
846
+ logger;
847
+ constructor(opts, wooks$1) {
848
+ super(wooks$1, opts?.logger, opts?.router);
849
+ this.opts = opts;
850
+ this.logger = opts?.logger || this.getLogger(`${"\x1B[96m"}[wooks-http]`);
851
+ }
852
+ all(path, handler) {
853
+ return this.on("*", path, handler);
854
+ }
855
+ get(path, handler) {
856
+ return this.on("GET", path, handler);
857
+ }
858
+ post(path, handler) {
859
+ return this.on("POST", path, handler);
860
+ }
861
+ put(path, handler) {
862
+ return this.on("PUT", path, handler);
863
+ }
864
+ patch(path, handler) {
865
+ return this.on("PATCH", path, handler);
866
+ }
867
+ delete(path, handler) {
868
+ return this.on("DELETE", path, handler);
869
+ }
870
+ head(path, handler) {
871
+ return this.on("HEAD", path, handler);
872
+ }
873
+ options(path, handler) {
874
+ return this.on("OPTIONS", path, handler);
875
+ }
876
+ server;
877
+ async listen(port, hostname, backlog, listeningListener) {
878
+ const server = this.server = http.default.createServer(this.getServerCb());
879
+ return new Promise((resolve, reject) => {
880
+ server.once("listening", resolve);
881
+ server.once("error", reject);
882
+ let args = [
883
+ port,
884
+ hostname,
885
+ backlog,
886
+ listeningListener
887
+ ];
888
+ const ui = args.indexOf(undefined);
889
+ if (ui >= 0) args = args.slice(0, ui);
890
+ server.listen(...args);
891
+ });
892
+ }
893
+ /**
894
+ * Stops the server if it was attached or passed via argument
895
+ * @param server
896
+ */
897
+ close(server) {
898
+ const srv = server || this.server;
899
+ return new Promise((resolve, reject) => {
900
+ srv?.close((err) => {
901
+ if (err) {
902
+ reject(err);
903
+ return;
904
+ }
905
+ resolve(srv);
906
+ });
907
+ });
908
+ }
909
+ /**
910
+ * Returns http(s) server that was attached to Wooks
911
+ *
912
+ * See attachServer method docs
913
+ * @returns Server
914
+ */
915
+ getServer() {
916
+ return this.server;
917
+ }
918
+ /**
919
+ * Attaches http(s) server instance
920
+ * to Wooks.
921
+ *
922
+ * Use it only if you want to `close` method to stop the server.
923
+ * @param server Server
924
+ */
925
+ attachServer(server) {
926
+ this.server = server;
927
+ }
928
+ responder = createWooksResponder();
929
+ respond(data) {
930
+ void this.responder.respond(data)?.catch((e) => {
931
+ this.logger.error("Uncaught response exception", e);
932
+ });
933
+ }
934
+ /**
935
+ * Returns server callback function
936
+ * that can be passed to any node server:
937
+ * ```js
938
+ * import { createHttpApp } from '@wooksjs/event-http'
939
+ * import http from 'http'
940
+ *
941
+ * const app = createHttpApp()
942
+ * const server = http.createServer(app.getServerCb())
943
+ * server.listen(3000)
944
+ * ```
945
+ */
946
+ getServerCb() {
947
+ return (req, res) => {
948
+ const runInContext = createHttpContext({
949
+ req,
950
+ res
951
+ }, this.mergeEventOptions(this.opts?.eventOptions));
952
+ runInContext(async () => {
953
+ const { handlers } = this.wooks.lookup(req.method, req.url);
954
+ if (handlers || this.opts?.onNotFound) try {
955
+ return await this.processHandlers(handlers || [this.opts?.onNotFound]);
956
+ } catch (error) {
957
+ this.logger.error("Internal error, please report", error);
958
+ this.respond(error);
959
+ return error;
960
+ }
961
+ else {
962
+ this.logger.debug(`404 Not found (${req.method})${req.url}`);
963
+ const error = new HttpError(404);
964
+ this.respond(error);
965
+ return error;
966
+ }
967
+ });
968
+ };
969
+ }
970
+ async processHandlers(handlers) {
971
+ const { store } = useHttpContext();
972
+ for (const [i, handler] of handlers.entries()) {
973
+ const isLastHandler = handlers.length === i + 1;
974
+ try {
975
+ const promise = handler();
976
+ const result = await promise;
977
+ this.respond(result);
978
+ return result;
979
+ } catch (error) {
980
+ if (error instanceof HttpError) {} else this.logger.error(`Uncaught route handler exception: ${store("event").get("req")?.url || ""}`, error);
981
+ if (isLastHandler) {
982
+ this.respond(error);
983
+ return error;
984
+ }
985
+ }
986
+ }
987
+ }
988
+ };
989
+ function createHttpApp(opts, wooks$1) {
990
+ return new WooksHttp(opts, wooks$1);
1000
991
  }
1001
992
 
1002
- Object.defineProperty(exports, "useEventLogger", {
993
+ //#endregion
994
+ exports.BaseHttpResponse = BaseHttpResponse
995
+ exports.BaseHttpResponseRenderer = BaseHttpResponseRenderer
996
+ exports.EHttpStatusCode = EHttpStatusCode
997
+ exports.HttpError = HttpError
998
+ exports.HttpErrorRenderer = HttpErrorRenderer
999
+ exports.WooksHttp = WooksHttp
1000
+ exports.WooksURLSearchParams = WooksURLSearchParams
1001
+ exports.createHttpApp = createHttpApp
1002
+ exports.createHttpContext = createHttpContext
1003
+ exports.createWooksResponder = createWooksResponder
1004
+ exports.httpStatusCodes = httpStatusCodes
1005
+ exports.renderCacheControl = renderCacheControl
1006
+ exports.useAccept = useAccept
1007
+ exports.useAuthorization = useAuthorization
1008
+ exports.useCookies = useCookies
1009
+ Object.defineProperty(exports, 'useEventLogger', {
1003
1010
  enumerable: true,
1004
- get: function () { return eventCore.useEventLogger; }
1011
+ get: function () {
1012
+ return __wooksjs_event_core.useEventLogger;
1013
+ }
1005
1014
  });
1006
- Object.defineProperty(exports, "useRouteParams", {
1015
+ exports.useHeaders = useHeaders
1016
+ exports.useHttpContext = useHttpContext
1017
+ exports.useRequest = useRequest
1018
+ exports.useResponse = useResponse
1019
+ Object.defineProperty(exports, 'useRouteParams', {
1007
1020
  enumerable: true,
1008
- get: function () { return eventCore.useRouteParams; }
1021
+ get: function () {
1022
+ return __wooksjs_event_core.useRouteParams;
1023
+ }
1009
1024
  });
1010
- exports.BaseHttpResponse = BaseHttpResponse;
1011
- exports.BaseHttpResponseRenderer = BaseHttpResponseRenderer;
1012
- exports.HttpError = HttpError;
1013
- exports.HttpErrorRenderer = HttpErrorRenderer;
1014
- exports.WooksHttp = WooksHttp;
1015
- exports.WooksURLSearchParams = WooksURLSearchParams;
1016
- exports.createHttpApp = createHttpApp;
1017
- exports.createHttpContext = createHttpContext;
1018
- exports.createWooksResponder = createWooksResponder;
1019
- exports.httpStatusCodes = httpStatusCodes;
1020
- exports.renderCacheControl = renderCacheControl;
1021
- exports.useAccept = useAccept;
1022
- exports.useAuthorization = useAuthorization;
1023
- exports.useCookies = useCookies;
1024
- exports.useHeaders = useHeaders;
1025
- exports.useHttpContext = useHttpContext;
1026
- exports.useRequest = useRequest;
1027
- exports.useResponse = useResponse;
1028
- exports.useSearchParams = useSearchParams;
1029
- exports.useSetCacheControl = useSetCacheControl;
1030
- exports.useSetCookie = useSetCookie;
1031
- exports.useSetCookies = useSetCookies;
1032
- exports.useSetHeader = useSetHeader;
1033
- exports.useSetHeaders = useSetHeaders;
1034
- exports.useStatus = useStatus;
1025
+ exports.useSearchParams = useSearchParams
1026
+ exports.useSetCacheControl = useSetCacheControl
1027
+ exports.useSetCookie = useSetCookie
1028
+ exports.useSetCookies = useSetCookies
1029
+ exports.useSetHeader = useSetHeader
1030
+ exports.useSetHeaders = useSetHeaders
1031
+ exports.useStatus = useStatus