@wooksjs/http-body 0.6.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,4 @@
1
- # Wooks Body
2
-
3
- **!!! This is work-in-progress library, breaking changes are expected !!!**
1
+ # @wooksjs/http-body
4
2
 
5
3
  <p align="center">
6
4
  <img src="../../wooks-logo.png" width="450px"><br>
@@ -9,60 +7,18 @@
9
7
  </a>
10
8
  </p>
11
9
 
12
- Wooks Body is composable body parser for [@wooksjs/event-http](https://github.com/wooksjs/wooksjs/tree/main/packages/event-http).
13
-
14
- Supported content types:
15
-
16
- - ✅ application/json
17
- - ✅ text/\*
18
- - ✅ multipart/form-data
19
- - ✅ application/x-www-form-urlencoded
20
-
21
- Body parser does not parse every request's body. The parsing happens only when you call `parseBody` function.
10
+ Composable body parser for [@wooksjs/event-http](https://github.com/wooksjs/wooksjs/tree/main/packages/event-http). Supports JSON, text, multipart/form-data, and URL-encoded content types. Parsing is lazy — the body is only read when you call `parseBody()`.
22
11
 
23
12
  ## Installation
24
13
 
25
- `npm install @wooksjs/http-body`
26
-
27
- ## Usage
28
-
29
- ```ts
30
- import { useBody } from '@wooksjs/http-body'
31
- app.post('test', async () => {
32
- const { parseBody } = useBody()
33
- const data = await parseBody()
34
- })
14
+ ```sh
15
+ npm install @wooksjs/http-body
35
16
  ```
36
17
 
37
- ### Additional hooks
38
-
39
- ```ts
40
- import { useBody } from '@wooksjs/http-body'
41
- app.post('test', async () => {
42
- const {
43
- isJson, // checks if content-type is "application/json" : () => boolean;
44
- isHtml, // checks if content-type is "text/html" : () => boolean;
45
- isXml, // checks if content-type is "application/xml" : () => boolean;
46
- isText, // checks if content-type is "text/plain" : () => boolean;
47
- isBinary, // checks if content-type is binary : () => boolean;
48
- isFormData, // checks if content-type is "multipart/form-data" : () => boolean;
49
- isUrlencoded, // checks if content-type is "application/x-www-form-urlencoded" : () => boolean;
50
- isCompressed, // checks content-encoding : () => boolean | undefined;
51
- contentEncodings, // returns an array of encodings : () => string[];
52
- parseBody, // parses body according to content-type : <T = unknown>() => Promise<T>;
53
- rawBody, // returns raw body Buffer : () => Promise<Buffer>;
54
- } = useBody()
55
-
56
- // the handler got the control, but the body isn't loaded yet
57
- //...
58
-
59
- console.log(await parseBody())
18
+ ## Documentation
60
19
 
61
- // after `await parseBody()` the body was loaded and parsed
62
- // ...
63
- })
64
- ```
20
+ For full documentation, visit [wooks.moost.org/webapp/body](https://wooks.moost.org/webapp/body).
65
21
 
66
- ## Documentation
22
+ ## License
67
23
 
68
- To check out docs, visit [wooks.moost.org](https://wooks.moost.org/).
24
+ MIT
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  }) : target, mod));
22
22
 
23
23
  //#endregion
24
+ const __wooksjs_event_core = __toESM(require("@wooksjs/event-core"));
24
25
  const __wooksjs_event_http = __toESM(require("@wooksjs/event-http"));
25
26
 
26
27
  //#region packages/http-body/src/utils/safe-json.ts
@@ -42,124 +43,118 @@ function assertKey(k) {
42
43
 
43
44
  //#endregion
44
45
  //#region packages/http-body/src/body.ts
46
+ const CONTENT_TYPE_MAP = {
47
+ json: "application/json",
48
+ html: "text/html",
49
+ xml: "text/xml",
50
+ text: "text/plain",
51
+ binary: "application/octet-stream",
52
+ "form-data": "multipart/form-data",
53
+ urlencoded: "application/x-www-form-urlencoded"
54
+ };
55
+ const contentIsSlot = (0, __wooksjs_event_core.cachedBy)((type, ctx) => {
56
+ const contentType = (0, __wooksjs_event_http.useHeaders)(ctx)["content-type"] || "";
57
+ const mime = CONTENT_TYPE_MAP[type] || type;
58
+ return contentType.includes(mime);
59
+ });
60
+ const parsedBodySlot = (0, __wooksjs_event_core.cached)(async (ctx) => {
61
+ const { rawBody } = (0, __wooksjs_event_http.useRequest)(ctx);
62
+ const contentType = (0, __wooksjs_event_http.useHeaders)(ctx)["content-type"] || "";
63
+ const contentIs = (type) => contentType.includes(type);
64
+ const body = await rawBody();
65
+ const sBody = body.toString();
66
+ if (contentIs("application/json")) return jsonParser(sBody);
67
+ else if (contentIs("multipart/form-data")) return formDataParser(sBody, contentType);
68
+ else if (contentIs("application/x-www-form-urlencoded")) return urlEncodedParser(sBody);
69
+ else return sBody;
70
+ });
71
+ function jsonParser(v) {
72
+ try {
73
+ return safeJsonParse(v);
74
+ } catch (error) {
75
+ throw new __wooksjs_event_http.HttpError(400, error.message);
76
+ }
77
+ }
78
+ function formDataParser(v, contentType) {
79
+ const MAX_PARTS = 255;
80
+ const MAX_KEY_LENGTH = 100;
81
+ const MAX_VALUE_LENGTH = 100 * 1024;
82
+ const boundary = `--${(/boundary=([^;]+)(?:;|$)/u.exec(contentType || "") || [, ""])[1]}`;
83
+ if (!boundary) throw new __wooksjs_event_http.HttpError(__wooksjs_event_http.EHttpStatusCode.BadRequest, "form-data boundary not recognized");
84
+ const parts = v.trim().split(boundary);
85
+ const result = Object.create(null);
86
+ let key = "";
87
+ let partContentType = "text/plain";
88
+ let partCount = 0;
89
+ for (const part of parts) {
90
+ parsePart();
91
+ key = "";
92
+ partContentType = "text/plain";
93
+ if (!part.trim() || part.trim() === "--") continue;
94
+ partCount++;
95
+ if (partCount > MAX_PARTS) throw new __wooksjs_event_http.HttpError(413, "Too many form fields");
96
+ let valueMode = false;
97
+ const lines = part.trim().split(/\n/u).map((l) => l.trim());
98
+ for (const line of lines) {
99
+ if (valueMode) {
100
+ if (line.length + String(result[key] ?? "").length > MAX_VALUE_LENGTH) throw new __wooksjs_event_http.HttpError(413, `Field "${key}" is too large`);
101
+ result[key] = (result[key] ? `${result[key]}\n` : "") + line;
102
+ continue;
103
+ }
104
+ if (!line) {
105
+ valueMode = !!key;
106
+ continue;
107
+ }
108
+ if (line.toLowerCase().startsWith("content-disposition: form-data;")) {
109
+ key = (/name=([^;]+)/.exec(line) || [])[1].replace(/^["']|["']$/g, "") ?? "";
110
+ if (!key) throw new __wooksjs_event_http.HttpError(400, `Could not read multipart name: ${line}`);
111
+ if (key.length > MAX_KEY_LENGTH) throw new __wooksjs_event_http.HttpError(413, "Field name too long");
112
+ if ([
113
+ "__proto__",
114
+ "constructor",
115
+ "prototype"
116
+ ].includes(key)) throw new __wooksjs_event_http.HttpError(400, `Illegal key name "${key}"`);
117
+ continue;
118
+ }
119
+ if (line.toLowerCase().startsWith("content-type:")) {
120
+ partContentType = (/content-type:\s?([^;]+)/i.exec(line) || [])[1] ?? "";
121
+ continue;
122
+ }
123
+ }
124
+ }
125
+ parsePart();
126
+ return result;
127
+ function parsePart() {
128
+ if (key && partContentType.includes("application/json") && typeof result[key] === "string") result[key] = safeJsonParse(result[key]);
129
+ }
130
+ }
131
+ function urlEncodedParser(v) {
132
+ return new __wooksjs_event_http.WooksURLSearchParams(v.trim()).toJson();
133
+ }
45
134
  /**
46
135
  * Composable that provides request body parsing utilities for various content types.
47
136
  *
48
137
  * @example
49
138
  * ```ts
50
139
  * app.post('/api/data', async () => {
51
- * const { parseBody, isJson } = useBody()
52
- * if (isJson()) {
140
+ * const { contentIs, parseBody } = useBody()
141
+ * if (contentIs('json')) {
53
142
  * const data = await parseBody<{ name: string }>()
54
143
  * return { received: data.name }
55
144
  * }
56
145
  * })
57
146
  * ```
58
147
  *
59
- * @returns Object with content-type checkers (`isJson`, `isHtml`, `isXml`, `isText`, `isBinary`, `isFormData`, `isUrlencoded`), a `parseBody` function, and `rawBody` accessor.
148
+ * @returns Object with `contentIs(type)` checker, `parseBody` function, and `rawBody` accessor.
60
149
  */
61
- function useBody() {
62
- const { store } = (0, __wooksjs_event_http.useHttpContext)();
63
- const { init } = store("request");
64
- const { rawBody } = (0, __wooksjs_event_http.useRequest)();
65
- const { "content-type": contentType } = (0, __wooksjs_event_http.useHeaders)();
66
- function contentIs(type) {
67
- return (contentType || "").includes(type);
68
- }
69
- const isJson = () => init("isJson", () => contentIs("application/json"));
70
- const isHtml = () => init("isHtml", () => contentIs("text/html"));
71
- const isXml = () => init("isXml", () => contentIs("text/xml"));
72
- const isText = () => init("isText", () => contentIs("text/plain"));
73
- const isBinary = () => init("isBinary", () => contentIs("application/octet-stream"));
74
- const isFormData = () => init("isFormData", () => contentIs("multipart/form-data"));
75
- const isUrlencoded = () => init("isUrlencoded", () => contentIs("application/x-www-form-urlencoded"));
76
- const parseBody = () => init("parsed", async () => {
77
- const body = await rawBody();
78
- const sBody = body.toString();
79
- if (isJson()) return jsonParser(sBody);
80
- else if (isFormData()) return formDataParser(sBody);
81
- else if (isUrlencoded()) return urlEncodedParser(sBody);
82
- else if (isBinary()) return textParser(sBody);
83
- else return textParser(sBody);
84
- });
85
- function jsonParser(v) {
86
- try {
87
- return safeJsonParse(v);
88
- } catch (error) {
89
- throw new __wooksjs_event_http.HttpError(400, error.message);
90
- }
91
- }
92
- function textParser(v) {
93
- return v;
94
- }
95
- function formDataParser(v) {
96
- const MAX_PARTS = 255;
97
- const MAX_KEY_LENGTH = 100;
98
- const MAX_VALUE_LENGTH = 100 * 1024;
99
- const boundary = `--${(/boundary=([^;]+)(?:;|$)/u.exec(contentType || "") || [, ""])[1]}`;
100
- if (!boundary) throw new __wooksjs_event_http.HttpError(__wooksjs_event_http.EHttpStatusCode.BadRequest, "form-data boundary not recognized");
101
- const parts = v.trim().split(boundary);
102
- const result = Object.create(null);
103
- let key = "";
104
- let partContentType = "text/plain";
105
- let partCount = 0;
106
- for (const part of parts) {
107
- parsePart();
108
- key = "";
109
- partContentType = "text/plain";
110
- if (!part.trim() || part.trim() === "--") continue;
111
- partCount++;
112
- if (partCount > MAX_PARTS) throw new __wooksjs_event_http.HttpError(413, "Too many form fields");
113
- let valueMode = false;
114
- const lines = part.trim().split(/\n/u).map((l) => l.trim());
115
- for (const line of lines) {
116
- if (valueMode) {
117
- if (line.length + String(result[key] ?? "").length > MAX_VALUE_LENGTH) throw new __wooksjs_event_http.HttpError(413, `Field "${key}" is too large`);
118
- result[key] = (result[key] ? `${result[key]}\n` : "") + line;
119
- continue;
120
- }
121
- if (!line) {
122
- valueMode = !!key;
123
- continue;
124
- }
125
- if (line.toLowerCase().startsWith("content-disposition: form-data;")) {
126
- key = (/name=([^;]+)/.exec(line) || [])[1].replace(/^["']|["']$/g, "") ?? "";
127
- if (!key) throw new __wooksjs_event_http.HttpError(400, `Could not read multipart name: ${line}`);
128
- if (key.length > MAX_KEY_LENGTH) throw new __wooksjs_event_http.HttpError(413, "Field name too long");
129
- if ([
130
- "__proto__",
131
- "constructor",
132
- "prototype"
133
- ].includes(key)) throw new __wooksjs_event_http.HttpError(400, `Illegal key name "${key}"`);
134
- continue;
135
- }
136
- if (line.toLowerCase().startsWith("content-type:")) {
137
- partContentType = (/content-type:\s?([^;]+)/i.exec(line) || [])[1] ?? "";
138
- continue;
139
- }
140
- }
141
- }
142
- parsePart();
143
- return result;
144
- function parsePart() {
145
- if (key && partContentType.includes("application/json") && typeof result[key] === "string") result[key] = safeJsonParse(result[key]);
146
- }
147
- }
148
- function urlEncodedParser(v) {
149
- return new __wooksjs_event_http.WooksURLSearchParams(v.trim()).toJson();
150
- }
150
+ const useBody = (0, __wooksjs_event_core.defineWook)((ctx) => {
151
+ const { rawBody } = (0, __wooksjs_event_http.useRequest)(ctx);
151
152
  return {
152
- isJson,
153
- isHtml,
154
- isXml,
155
- isText,
156
- isBinary,
157
- isFormData,
158
- isUrlencoded,
159
- parseBody,
153
+ contentIs: (type) => contentIsSlot(type, ctx),
154
+ parseBody: () => ctx.get(parsedBodySlot),
160
155
  rawBody
161
156
  };
162
- }
157
+ });
163
158
 
164
159
  //#endregion
165
160
  exports.useBody = useBody;
package/dist/index.d.ts CHANGED
@@ -1,29 +1,28 @@
1
+ import { EventContext } from '@wooksjs/event-core';
2
+
3
+ /** Short names for common Content-Type values. */
4
+ type KnownContentType = 'json' | 'html' | 'xml' | 'text' | 'binary' | 'form-data' | 'urlencoded';
1
5
  /**
2
6
  * Composable that provides request body parsing utilities for various content types.
3
7
  *
4
8
  * @example
5
9
  * ```ts
6
10
  * app.post('/api/data', async () => {
7
- * const { parseBody, isJson } = useBody()
8
- * if (isJson()) {
11
+ * const { contentIs, parseBody } = useBody()
12
+ * if (contentIs('json')) {
9
13
  * const data = await parseBody<{ name: string }>()
10
14
  * return { received: data.name }
11
15
  * }
12
16
  * })
13
17
  * ```
14
18
  *
15
- * @returns Object with content-type checkers (`isJson`, `isHtml`, `isXml`, `isText`, `isBinary`, `isFormData`, `isUrlencoded`), a `parseBody` function, and `rawBody` accessor.
19
+ * @returns Object with `contentIs(type)` checker, `parseBody` function, and `rawBody` accessor.
16
20
  */
17
- declare function useBody(): {
18
- isJson: () => boolean;
19
- isHtml: () => boolean;
20
- isXml: () => boolean;
21
- isText: () => boolean;
22
- isBinary: () => boolean;
23
- isFormData: () => boolean;
24
- isUrlencoded: () => boolean;
21
+ declare const useBody: (ctx?: EventContext) => {
22
+ contentIs: (type: KnownContentType | (string & {})) => boolean;
25
23
  parseBody: <T>() => Promise<T>;
26
24
  rawBody: () => Promise<Buffer<ArrayBufferLike>>;
27
25
  };
28
26
 
29
27
  export { useBody };
28
+ export type { KnownContentType };
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { EHttpStatusCode, HttpError, WooksURLSearchParams, useHeaders, useHttpContext, useRequest } from "@wooksjs/event-http";
1
+ import { cached, cachedBy, defineWook } from "@wooksjs/event-core";
2
+ import { EHttpStatusCode, HttpError, WooksURLSearchParams, useHeaders, useRequest } from "@wooksjs/event-http";
2
3
 
3
4
  //#region packages/http-body/src/utils/safe-json.ts
4
5
  const ILLEGAL_KEYS = [
@@ -19,124 +20,118 @@ function assertKey(k) {
19
20
 
20
21
  //#endregion
21
22
  //#region packages/http-body/src/body.ts
23
+ const CONTENT_TYPE_MAP = {
24
+ json: "application/json",
25
+ html: "text/html",
26
+ xml: "text/xml",
27
+ text: "text/plain",
28
+ binary: "application/octet-stream",
29
+ "form-data": "multipart/form-data",
30
+ urlencoded: "application/x-www-form-urlencoded"
31
+ };
32
+ const contentIsSlot = cachedBy((type, ctx) => {
33
+ const contentType = useHeaders(ctx)["content-type"] || "";
34
+ const mime = CONTENT_TYPE_MAP[type] || type;
35
+ return contentType.includes(mime);
36
+ });
37
+ const parsedBodySlot = cached(async (ctx) => {
38
+ const { rawBody } = useRequest(ctx);
39
+ const contentType = useHeaders(ctx)["content-type"] || "";
40
+ const contentIs = (type) => contentType.includes(type);
41
+ const body = await rawBody();
42
+ const sBody = body.toString();
43
+ if (contentIs("application/json")) return jsonParser(sBody);
44
+ else if (contentIs("multipart/form-data")) return formDataParser(sBody, contentType);
45
+ else if (contentIs("application/x-www-form-urlencoded")) return urlEncodedParser(sBody);
46
+ else return sBody;
47
+ });
48
+ function jsonParser(v) {
49
+ try {
50
+ return safeJsonParse(v);
51
+ } catch (error) {
52
+ throw new HttpError(400, error.message);
53
+ }
54
+ }
55
+ function formDataParser(v, contentType) {
56
+ const MAX_PARTS = 255;
57
+ const MAX_KEY_LENGTH = 100;
58
+ const MAX_VALUE_LENGTH = 100 * 1024;
59
+ const boundary = `--${(/boundary=([^;]+)(?:;|$)/u.exec(contentType || "") || [, ""])[1]}`;
60
+ if (!boundary) throw new HttpError(EHttpStatusCode.BadRequest, "form-data boundary not recognized");
61
+ const parts = v.trim().split(boundary);
62
+ const result = Object.create(null);
63
+ let key = "";
64
+ let partContentType = "text/plain";
65
+ let partCount = 0;
66
+ for (const part of parts) {
67
+ parsePart();
68
+ key = "";
69
+ partContentType = "text/plain";
70
+ if (!part.trim() || part.trim() === "--") continue;
71
+ partCount++;
72
+ if (partCount > MAX_PARTS) throw new HttpError(413, "Too many form fields");
73
+ let valueMode = false;
74
+ const lines = part.trim().split(/\n/u).map((l) => l.trim());
75
+ for (const line of lines) {
76
+ if (valueMode) {
77
+ if (line.length + String(result[key] ?? "").length > MAX_VALUE_LENGTH) throw new HttpError(413, `Field "${key}" is too large`);
78
+ result[key] = (result[key] ? `${result[key]}\n` : "") + line;
79
+ continue;
80
+ }
81
+ if (!line) {
82
+ valueMode = !!key;
83
+ continue;
84
+ }
85
+ if (line.toLowerCase().startsWith("content-disposition: form-data;")) {
86
+ key = (/name=([^;]+)/.exec(line) || [])[1].replace(/^["']|["']$/g, "") ?? "";
87
+ if (!key) throw new HttpError(400, `Could not read multipart name: ${line}`);
88
+ if (key.length > MAX_KEY_LENGTH) throw new HttpError(413, "Field name too long");
89
+ if ([
90
+ "__proto__",
91
+ "constructor",
92
+ "prototype"
93
+ ].includes(key)) throw new HttpError(400, `Illegal key name "${key}"`);
94
+ continue;
95
+ }
96
+ if (line.toLowerCase().startsWith("content-type:")) {
97
+ partContentType = (/content-type:\s?([^;]+)/i.exec(line) || [])[1] ?? "";
98
+ continue;
99
+ }
100
+ }
101
+ }
102
+ parsePart();
103
+ return result;
104
+ function parsePart() {
105
+ if (key && partContentType.includes("application/json") && typeof result[key] === "string") result[key] = safeJsonParse(result[key]);
106
+ }
107
+ }
108
+ function urlEncodedParser(v) {
109
+ return new WooksURLSearchParams(v.trim()).toJson();
110
+ }
22
111
  /**
23
112
  * Composable that provides request body parsing utilities for various content types.
24
113
  *
25
114
  * @example
26
115
  * ```ts
27
116
  * app.post('/api/data', async () => {
28
- * const { parseBody, isJson } = useBody()
29
- * if (isJson()) {
117
+ * const { contentIs, parseBody } = useBody()
118
+ * if (contentIs('json')) {
30
119
  * const data = await parseBody<{ name: string }>()
31
120
  * return { received: data.name }
32
121
  * }
33
122
  * })
34
123
  * ```
35
124
  *
36
- * @returns Object with content-type checkers (`isJson`, `isHtml`, `isXml`, `isText`, `isBinary`, `isFormData`, `isUrlencoded`), a `parseBody` function, and `rawBody` accessor.
125
+ * @returns Object with `contentIs(type)` checker, `parseBody` function, and `rawBody` accessor.
37
126
  */
38
- function useBody() {
39
- const { store } = useHttpContext();
40
- const { init } = store("request");
41
- const { rawBody } = useRequest();
42
- const { "content-type": contentType } = useHeaders();
43
- function contentIs(type) {
44
- return (contentType || "").includes(type);
45
- }
46
- const isJson = () => init("isJson", () => contentIs("application/json"));
47
- const isHtml = () => init("isHtml", () => contentIs("text/html"));
48
- const isXml = () => init("isXml", () => contentIs("text/xml"));
49
- const isText = () => init("isText", () => contentIs("text/plain"));
50
- const isBinary = () => init("isBinary", () => contentIs("application/octet-stream"));
51
- const isFormData = () => init("isFormData", () => contentIs("multipart/form-data"));
52
- const isUrlencoded = () => init("isUrlencoded", () => contentIs("application/x-www-form-urlencoded"));
53
- const parseBody = () => init("parsed", async () => {
54
- const body = await rawBody();
55
- const sBody = body.toString();
56
- if (isJson()) return jsonParser(sBody);
57
- else if (isFormData()) return formDataParser(sBody);
58
- else if (isUrlencoded()) return urlEncodedParser(sBody);
59
- else if (isBinary()) return textParser(sBody);
60
- else return textParser(sBody);
61
- });
62
- function jsonParser(v) {
63
- try {
64
- return safeJsonParse(v);
65
- } catch (error) {
66
- throw new HttpError(400, error.message);
67
- }
68
- }
69
- function textParser(v) {
70
- return v;
71
- }
72
- function formDataParser(v) {
73
- const MAX_PARTS = 255;
74
- const MAX_KEY_LENGTH = 100;
75
- const MAX_VALUE_LENGTH = 100 * 1024;
76
- const boundary = `--${(/boundary=([^;]+)(?:;|$)/u.exec(contentType || "") || [, ""])[1]}`;
77
- if (!boundary) throw new HttpError(EHttpStatusCode.BadRequest, "form-data boundary not recognized");
78
- const parts = v.trim().split(boundary);
79
- const result = Object.create(null);
80
- let key = "";
81
- let partContentType = "text/plain";
82
- let partCount = 0;
83
- for (const part of parts) {
84
- parsePart();
85
- key = "";
86
- partContentType = "text/plain";
87
- if (!part.trim() || part.trim() === "--") continue;
88
- partCount++;
89
- if (partCount > MAX_PARTS) throw new HttpError(413, "Too many form fields");
90
- let valueMode = false;
91
- const lines = part.trim().split(/\n/u).map((l) => l.trim());
92
- for (const line of lines) {
93
- if (valueMode) {
94
- if (line.length + String(result[key] ?? "").length > MAX_VALUE_LENGTH) throw new HttpError(413, `Field "${key}" is too large`);
95
- result[key] = (result[key] ? `${result[key]}\n` : "") + line;
96
- continue;
97
- }
98
- if (!line) {
99
- valueMode = !!key;
100
- continue;
101
- }
102
- if (line.toLowerCase().startsWith("content-disposition: form-data;")) {
103
- key = (/name=([^;]+)/.exec(line) || [])[1].replace(/^["']|["']$/g, "") ?? "";
104
- if (!key) throw new HttpError(400, `Could not read multipart name: ${line}`);
105
- if (key.length > MAX_KEY_LENGTH) throw new HttpError(413, "Field name too long");
106
- if ([
107
- "__proto__",
108
- "constructor",
109
- "prototype"
110
- ].includes(key)) throw new HttpError(400, `Illegal key name "${key}"`);
111
- continue;
112
- }
113
- if (line.toLowerCase().startsWith("content-type:")) {
114
- partContentType = (/content-type:\s?([^;]+)/i.exec(line) || [])[1] ?? "";
115
- continue;
116
- }
117
- }
118
- }
119
- parsePart();
120
- return result;
121
- function parsePart() {
122
- if (key && partContentType.includes("application/json") && typeof result[key] === "string") result[key] = safeJsonParse(result[key]);
123
- }
124
- }
125
- function urlEncodedParser(v) {
126
- return new WooksURLSearchParams(v.trim()).toJson();
127
- }
127
+ const useBody = defineWook((ctx) => {
128
+ const { rawBody } = useRequest(ctx);
128
129
  return {
129
- isJson,
130
- isHtml,
131
- isXml,
132
- isText,
133
- isBinary,
134
- isFormData,
135
- isUrlencoded,
136
- parseBody,
130
+ contentIs: (type) => contentIsSlot(type, ctx),
131
+ parseBody: () => ctx.get(parsedBodySlot),
137
132
  rawBody
138
133
  };
139
- }
134
+ });
140
135
 
141
136
  //#endregion
142
137
  export { useBody };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooksjs/http-body",
3
- "version": "0.6.5",
3
+ "version": "0.7.0",
4
4
  "description": "@wooksjs/http-body",
5
5
  "keywords": [
6
6
  "api",
@@ -42,10 +42,12 @@
42
42
  "devDependencies": {
43
43
  "typescript": "^5.9.3",
44
44
  "vitest": "^3.2.4",
45
- "@wooksjs/event-http": "^0.6.5"
45
+ "@wooksjs/event-core": "^0.7.0",
46
+ "@wooksjs/event-http": "^0.7.0"
46
47
  },
47
48
  "peerDependencies": {
48
- "@wooksjs/event-http": "^0.6.5"
49
+ "@wooksjs/event-core": "^0.7.0",
50
+ "@wooksjs/event-http": "^0.7.0"
49
51
  },
50
52
  "scripts": {
51
53
  "build": "rolldown -c ../../rolldown.config.mjs"