@h3ravel/http 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 h3ravel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,371 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ ApiResource: () => ApiResource,
25
+ HttpServiceProvider: () => HttpServiceProvider,
26
+ JsonResource: () => JsonResource,
27
+ LogRequests: () => LogRequests,
28
+ Middleware: () => Middleware,
29
+ Request: () => Request,
30
+ Response: () => Response
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/Middleware.ts
35
+ var Middleware = class {
36
+ static {
37
+ __name(this, "Middleware");
38
+ }
39
+ };
40
+
41
+ // src/Request.ts
42
+ var import_h3 = require("h3");
43
+ var import_support = require("@h3ravel/support");
44
+ var Request = class {
45
+ static {
46
+ __name(this, "Request");
47
+ }
48
+ event;
49
+ constructor(event) {
50
+ this.event = event;
51
+ }
52
+ /**
53
+ * Get all input data (query + body).
54
+ */
55
+ async all() {
56
+ let data = {
57
+ ...(0, import_h3.getRouterParams)(this.event),
58
+ ...(0, import_h3.getQuery)(this.event)
59
+ };
60
+ if (this.event.req.method === "POST") {
61
+ data = Object.assign({}, data, Object.fromEntries((await this.event.req.formData()).entries()));
62
+ } else if (this.event.req.method === "PUT") {
63
+ data = Object.fromEntries(Object.entries(await (0, import_h3.readBody)(this.event)));
64
+ }
65
+ return data;
66
+ }
67
+ /**
68
+ * Get a single input field from query or body.
69
+ */
70
+ async input(key, defaultValue) {
71
+ const data = await this.all();
72
+ return data[key] ?? defaultValue;
73
+ }
74
+ /**
75
+ * Get route parameters.
76
+ */
77
+ params() {
78
+ return (0, import_h3.getRouterParams)(this.event);
79
+ }
80
+ /**
81
+ * Get query parameters.
82
+ */
83
+ query() {
84
+ return (0, import_h3.getQuery)(this.event);
85
+ }
86
+ getEvent(key) {
87
+ return (0, import_support.safeDot)(this.event, key);
88
+ }
89
+ };
90
+
91
+ // src/Response.ts
92
+ var import_support2 = require("@h3ravel/support");
93
+ var import_h32 = require("h3");
94
+ var Response = class {
95
+ static {
96
+ __name(this, "Response");
97
+ }
98
+ event;
99
+ statusCode = 200;
100
+ headers = {};
101
+ constructor(event) {
102
+ this.event = event;
103
+ }
104
+ /**
105
+ * Set HTTP status code.
106
+ */
107
+ setStatusCode(code) {
108
+ this.statusCode = code;
109
+ this.event.res.status = code;
110
+ return this;
111
+ }
112
+ /**
113
+ * Set a header.
114
+ */
115
+ setHeader(name, value) {
116
+ this.headers[name] = value;
117
+ return this;
118
+ }
119
+ html(content) {
120
+ this.applyHeaders();
121
+ return (0, import_h32.html)(this.event, content);
122
+ }
123
+ /**
124
+ * Send a JSON response.
125
+ */
126
+ json(data) {
127
+ this.setHeader("content-type", "application/json; charset=utf-8");
128
+ this.applyHeaders();
129
+ return data;
130
+ }
131
+ /**
132
+ * Send plain text.
133
+ */
134
+ text(data) {
135
+ this.setHeader("content-type", "text/plain; charset=utf-8");
136
+ this.applyHeaders();
137
+ return data;
138
+ }
139
+ /**
140
+ * Redirect to another URL.
141
+ */
142
+ redirect(url, status = 302) {
143
+ this.setStatusCode(status);
144
+ return (0, import_h32.redirect)(this.event, url, this.statusCode);
145
+ }
146
+ /**
147
+ * Apply headers before sending response.
148
+ */
149
+ applyHeaders() {
150
+ Object.entries(this.headers).forEach(([key, value]) => {
151
+ this.event.res.headers.set(key, value);
152
+ });
153
+ }
154
+ getEvent(key) {
155
+ return (0, import_support2.safeDot)(this.event, key);
156
+ }
157
+ };
158
+
159
+ // src/Middleware/LogRequests.ts
160
+ var LogRequests = class extends Middleware {
161
+ static {
162
+ __name(this, "LogRequests");
163
+ }
164
+ async handle({ request }, next) {
165
+ const url = request.getEvent("url");
166
+ console.log(`[${request.getEvent("method")}] ${url.pathname + url.search}`);
167
+ return next();
168
+ }
169
+ };
170
+
171
+ // src/Providers/HttpServiceProvider.ts
172
+ var import_h33 = require("h3");
173
+ var import_core = require("@h3ravel/core");
174
+ var HttpServiceProvider = class extends import_core.ServiceProvider {
175
+ static {
176
+ __name(this, "HttpServiceProvider");
177
+ }
178
+ register() {
179
+ this.app.singleton("http.app", () => {
180
+ return new import_h33.H3();
181
+ });
182
+ this.app.singleton("http.serve", () => import_h33.serve);
183
+ }
184
+ };
185
+
186
+ // src/Resources/JsonResource.ts
187
+ var JsonResource = class {
188
+ static {
189
+ __name(this, "JsonResource");
190
+ }
191
+ event;
192
+ /**
193
+ * The request instance
194
+ */
195
+ request;
196
+ /**
197
+ * The response instance
198
+ */
199
+ response;
200
+ /**
201
+ * The data to send to the client
202
+ */
203
+ resource;
204
+ /**
205
+ * The final response data object
206
+ */
207
+ body = {
208
+ data: {}
209
+ };
210
+ /**
211
+ * Flag to track if response should be sent automatically
212
+ */
213
+ shouldSend = false;
214
+ /**
215
+ * Flag to track if response has been sent
216
+ */
217
+ responseSent = false;
218
+ /**
219
+ * @param req The request instance
220
+ * @param res The response instance
221
+ * @param rsc The data to send to the client
222
+ */
223
+ constructor(event, rsc) {
224
+ this.event = event;
225
+ this.request = event.req;
226
+ this.response = event.res;
227
+ this.resource = rsc;
228
+ for (const key of Object.keys(rsc)) {
229
+ if (!(key in this)) {
230
+ Object.defineProperty(this, key, {
231
+ enumerable: true,
232
+ configurable: true,
233
+ get: /* @__PURE__ */ __name(() => this.resource[key], "get"),
234
+ set: /* @__PURE__ */ __name((value) => {
235
+ this.resource[key] = value;
236
+ }, "set")
237
+ });
238
+ }
239
+ }
240
+ }
241
+ /**
242
+ * Return the data in the expected format
243
+ *
244
+ * @returns
245
+ */
246
+ data() {
247
+ return this.resource;
248
+ }
249
+ /**
250
+ * Build the response object
251
+ * @returns this
252
+ */
253
+ json() {
254
+ this.shouldSend = true;
255
+ this.response.status = 200;
256
+ const resource = this.data();
257
+ let data = Array.isArray(resource) ? [
258
+ ...resource
259
+ ] : {
260
+ ...resource
261
+ };
262
+ if (typeof data.data !== "undefined") {
263
+ data = data.data;
264
+ }
265
+ if (!Array.isArray(resource)) {
266
+ delete data.pagination;
267
+ }
268
+ this.body = {
269
+ data
270
+ };
271
+ if (!Array.isArray(resource) && resource.pagination) {
272
+ const meta = this.body.meta ?? {};
273
+ meta.pagination = resource.pagination;
274
+ this.body.meta = meta;
275
+ }
276
+ if (this.resource.pagination && !this.body.meta?.pagination) {
277
+ const meta = this.body.meta ?? {};
278
+ meta.pagination = this.resource.pagination;
279
+ this.body.meta = meta;
280
+ }
281
+ return this;
282
+ }
283
+ /**
284
+ * Add context data to the response object
285
+ * @param data Context data
286
+ * @returns this
287
+ */
288
+ additional(data) {
289
+ this.shouldSend = true;
290
+ delete data.data;
291
+ delete data.pagination;
292
+ this.body = {
293
+ ...this.body,
294
+ ...data
295
+ };
296
+ return this;
297
+ }
298
+ /**
299
+ * Send the output to the client
300
+ * @returns this
301
+ */
302
+ send() {
303
+ this.shouldSend = false;
304
+ if (!this.responseSent) {
305
+ this.#send();
306
+ }
307
+ return this;
308
+ }
309
+ /**
310
+ * Set the status code for this response
311
+ * @param code Status code
312
+ * @returns this
313
+ */
314
+ status(code) {
315
+ this.response.status = code;
316
+ return this;
317
+ }
318
+ /**
319
+ * Private method to send the response
320
+ */
321
+ #send() {
322
+ if (!this.responseSent) {
323
+ this.event.context.this.response.json(this.body);
324
+ this.responseSent = true;
325
+ }
326
+ }
327
+ /**
328
+ * Check if send should be triggered automatically
329
+ */
330
+ checkSend() {
331
+ if (this.shouldSend && !this.responseSent) {
332
+ this.#send();
333
+ }
334
+ }
335
+ };
336
+
337
+ // src/Resources/ApiResource.ts
338
+ function ApiResource(instance) {
339
+ return new Proxy(instance, {
340
+ get(target, prop, receiver) {
341
+ const value = Reflect.get(target, prop, receiver);
342
+ if (typeof value === "function") {
343
+ if (prop === "json" || prop === "additional") {
344
+ return (...args) => {
345
+ const result = value.apply(target, args);
346
+ setImmediate(() => target["checkSend"]());
347
+ return result;
348
+ };
349
+ } else if (prop === "send") {
350
+ return (...args) => {
351
+ target["shouldSend"] = false;
352
+ return value.apply(target, args);
353
+ };
354
+ }
355
+ }
356
+ return value;
357
+ }
358
+ });
359
+ }
360
+ __name(ApiResource, "ApiResource");
361
+ // Annotate the CommonJS export names for ESM import in node:
362
+ 0 && (module.exports = {
363
+ ApiResource,
364
+ HttpServiceProvider,
365
+ JsonResource,
366
+ LogRequests,
367
+ Middleware,
368
+ Request,
369
+ Response
370
+ });
371
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/Middleware.ts","../src/Request.ts","../src/Response.ts","../src/Middleware/LogRequests.ts","../src/Providers/HttpServiceProvider.ts","../src/Resources/JsonResource.ts","../src/Resources/ApiResource.ts"],"sourcesContent":["/**\n * @file Automatically generated by barrelsby.\n */\n\nexport * from './Middleware';\nexport * from './Request';\nexport * from './Response';\nexport * from './Contracts/ControllerContracts';\nexport * from './Contracts/HttpContract';\nexport * from './Middleware/LogRequests';\nexport * from './Providers/HttpServiceProvider';\nexport * from './Resources/ApiResource';\nexport * from './Resources/JsonResource';\n","import { HttpContext } from './Contracts/HttpContract';\n\nexport abstract class Middleware {\n abstract handle (context: HttpContext, next: () => Promise<unknown>): Promise<unknown>\n}\n","import { getQuery, getRouterParams, readBody, type H3Event } from 'h3'\nimport { DotNestedKeys, DotNestedValue, safeDot } from '@h3ravel/support'\n\nexport class Request {\n private readonly event: H3Event\n\n constructor(event: H3Event) {\n this.event = event\n }\n\n /**\n * Get all input data (query + body).\n */\n async all<T = Record<string, unknown>> (): Promise<T> {\n let data = {\n ...getRouterParams(this.event),\n ...getQuery(this.event),\n } as T\n\n if (this.event.req.method === 'POST') {\n data = Object.assign({}, data, Object.fromEntries((await this.event.req.formData()).entries()))\n } else if (this.event.req.method === 'PUT') {\n data = <never>Object.fromEntries(Object.entries(<never>await readBody(this.event)))\n }\n\n return data\n }\n\n /**\n * Get a single input field from query or body.\n */\n async input<T = unknown> (key: string, defaultValue?: T): Promise<T> {\n const data = await this.all<Record<string, T>>()\n return (data[key] ?? defaultValue) as T\n }\n\n /**\n * Get route parameters.\n */\n params<T = Record<string, string>> (): T {\n return getRouterParams(this.event) as T\n }\n\n /**\n * Get query parameters.\n */\n query<T = Record<string, string>> (): T {\n return getQuery(this.event) as T\n }\n\n /**\n * Get the base event\n */\n getEvent (): H3Event\n getEvent<K extends DotNestedKeys<H3Event>> (key: K): DotNestedValue<H3Event, K>\n getEvent<K extends DotNestedKeys<H3Event>> (key?: K): any {\n return safeDot(this.event, key)\n }\n}\n","import { DotNestedKeys, DotNestedValue, safeDot } from '@h3ravel/support'\nimport { html, redirect, } from 'h3'\n\nimport type { H3Event } from 'h3'\n\nexport class Response {\n private readonly event: H3Event\n private statusCode: number = 200\n private headers: Record<string, string> = {}\n\n constructor(event: H3Event) {\n this.event = event\n }\n\n /**\n * Set HTTP status code.\n */\n setStatusCode (code: number): this {\n this.statusCode = code\n this.event.res.status = code\n return this\n }\n\n /**\n * Set a header.\n */\n setHeader (name: string, value: string): this {\n this.headers[name] = value\n return this\n }\n\n html (content: string): string {\n this.applyHeaders()\n return html(this.event, content)\n }\n\n /**\n * Send a JSON response.\n */\n json<T = unknown> (data: T): T {\n this.setHeader(\"content-type\", \"application/json; charset=utf-8\")\n this.applyHeaders()\n return data\n }\n\n /**\n * Send plain text.\n */\n text (data: string): string {\n this.setHeader(\"content-type\", \"text/plain; charset=utf-8\")\n this.applyHeaders()\n return data;\n }\n\n /**\n * Redirect to another URL.\n */\n redirect (url: string, status = 302): string {\n this.setStatusCode(status)\n return redirect(this.event, url, this.statusCode)\n }\n\n /**\n * Apply headers before sending response.\n */\n private applyHeaders (): void {\n Object.entries(this.headers).forEach(([key, value]) => {\n this.event.res.headers.set(key, value)\n })\n }\n\n /**\n * Get the base event\n */\n getEvent (): H3Event\n getEvent<K extends DotNestedKeys<H3Event>> (key: K): DotNestedValue<H3Event, K>\n getEvent<K extends DotNestedKeys<H3Event>> (key?: K): any {\n return safeDot(this.event, key)\n }\n}\n","import { HttpContext, Middleware } from '@h3ravel/http'\n\nexport class LogRequests extends Middleware {\n async handle ({ request }: HttpContext, next: () => Promise<unknown>): Promise<unknown> {\n const url = request.getEvent('url')\n console.log(`[${request.getEvent('method')}] ${url.pathname + url.search}`)\n return next()\n }\n}\n","import { H3, serve } from 'h3'\n\nimport { ServiceProvider } from '@h3ravel/core'\n\n/**\n * Sets up HTTP kernel and request lifecycle.\n * \n * Register Request, Response, and Middleware classes.\n * Configure global middleware stack.\n * Boot HTTP kernel.\n * \n * Auto-Registered\n */\nexport class HttpServiceProvider extends ServiceProvider {\n register () {\n this.app.singleton('http.app', () => {\n return new H3()\n })\n\n this.app.singleton('http.serve', () => serve)\n }\n}\n","import { EventHandlerRequest, H3Event } from \"h3\";\n\nexport interface Resource {\n [key: string]: any;\n pagination?: {\n from?: number | undefined;\n to?: number | undefined;\n perPage?: number | undefined;\n total?: number | undefined;\n } | undefined;\n}\n\ntype BodyResource = Resource & {\n data: Omit<Resource, 'pagination'>,\n meta?: {\n pagination?: Resource['pagination']\n } | undefined;\n}\n\n/**\n * Class to render API resource\n */\nexport class JsonResource<R extends Resource = any> {\n /**\n * The request instance\n */\n request: H3Event<EventHandlerRequest>['req'];\n /**\n * The response instance\n */\n response: H3Event['res'];\n /**\n * The data to send to the client\n */\n resource: R;\n /**\n * The final response data object\n */\n body: BodyResource = {\n data: {},\n };\n /**\n * Flag to track if response should be sent automatically\n */\n private shouldSend: boolean = false;\n /**\n * Flag to track if response has been sent\n */\n\n private responseSent: boolean = false;\n\n /**\n * Declare that this includes R's properties\n */\n [key: string]: any;\n\n /**\n * @param req The request instance\n * @param res The response instance\n * @param rsc The data to send to the client\n */\n constructor(private event: H3Event, rsc: R) {\n this.request = event.req;\n this.response = event.res;\n this.resource = rsc;\n\n // Copy all properties from rsc to this, avoiding conflicts\n for (const key of Object.keys(rsc)) {\n if (!(key in this)) {\n Object.defineProperty(this, key, {\n enumerable: true,\n configurable: true,\n get: () => this.resource[key],\n set: (value) => {\n (<any>this.resource)[key] = value;\n },\n });\n }\n }\n }\n\n /**\n * Return the data in the expected format\n * \n * @returns \n */\n data (): Resource {\n return this.resource\n }\n\n /**\n * Build the response object\n * @returns this\n */\n json () {\n // Indicate response should be sent automatically\n this.shouldSend = true;\n\n // Set default status code\n this.response.status = 200;\n\n // Prepare body\n const resource = this.data()\n let data: Resource = Array.isArray(resource) ? [...resource] : { ...resource };\n\n if (typeof data.data !== 'undefined') {\n data = data.data\n }\n\n if (!Array.isArray(resource)) {\n delete data.pagination;\n }\n\n this.body = {\n data,\n };\n\n // Set the pagination from the data() resource, if available\n if (!Array.isArray(resource) && resource.pagination) {\n const meta: BodyResource['meta'] = this.body.meta ?? {}\n meta.pagination = resource.pagination;\n this.body.meta = meta;\n }\n\n // If pagination is not available on the resource, then check and set it\n // if it's available on the base resource.\n if (this.resource.pagination && !this.body.meta?.pagination) {\n const meta: BodyResource['meta'] = this.body.meta ?? {}\n meta.pagination = this.resource.pagination;\n this.body.meta = meta;\n }\n\n return this;\n }\n\n /**\n * Add context data to the response object\n * @param data Context data\n * @returns this\n */\n additional<X extends { [key: string]: any }> (data: X) {\n\n // Allow automatic send after additional\n this.shouldSend = true;\n\n // Merge data with body\n delete data.data;\n delete data.pagination;\n\n this.body = {\n ...this.body,\n ...data,\n };\n\n return this;\n }\n\n /**\n * Send the output to the client\n * @returns this\n */\n send () {\n this.shouldSend = false; // Prevent automatic send\n if (!this.responseSent) {\n this.#send();\n }\n return this;\n }\n\n /**\n * Set the status code for this response\n * @param code Status code\n * @returns this\n */\n status (code: number) {\n this.response.status = code;\n return this;\n }\n\n /**\n * Private method to send the response\n */\n #send () {\n if (!this.responseSent) {\n this.event.context.\n this.response.json(this.body);\n\n // Mark response as sent\n this.responseSent = true;\n }\n }\n\n /**\n * Check if send should be triggered automatically\n */\n private checkSend () {\n if (this.shouldSend && !this.responseSent) {\n this.#send();\n }\n }\n}\n","import { JsonResource, Resource } from \"./JsonResource\";\n\nimport { H3Event } from \"h3\";\n\nexport function ApiResource (\n instance: JsonResource\n) {\n return new Proxy(instance, {\n get (target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (typeof value === 'function') {\n // Intercept json, additional, and send methods\n if (prop === 'json' || prop === 'additional') {\n return (...args: any[]) => {\n const result = value.apply(target, args);\n // Schedule checkSend after json or additional\n setImmediate(() => target['checkSend']());\n return result;\n };\n } else if (prop === 'send') {\n return (...args: any[]) => {\n // Prevent checkSend from firing\n target['shouldSend'] = false;\n\n return value.apply(target, args);\n };\n }\n }\n return value;\n },\n });\n}\n\nexport default function BaseResource<R extends Resource> (\n evt: H3Event,\n rsc: R\n) {\n return ApiResource(new JsonResource<R>(evt, rsc))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;ACEO,IAAeA,aAAf,MAAeA;EAAtB,OAAsBA;;;AAEtB;;;ACJA,gBAAkE;AAClE,qBAAuD;AAEhD,IAAMC,UAAN,MAAMA;EAHb,OAGaA;;;EACQC;EAEjB,YAAYA,OAAgB;AACxB,SAAKA,QAAQA;EACjB;;;;EAKA,MAAMC,MAAgD;AAClD,QAAIC,OAAO;MACP,OAAGC,2BAAgB,KAAKH,KAAK;MAC7B,OAAGI,oBAAS,KAAKJ,KAAK;IAC1B;AAEA,QAAI,KAAKA,MAAMK,IAAIC,WAAW,QAAQ;AAClCJ,aAAOK,OAAOC,OAAO,CAAC,GAAGN,MAAMK,OAAOE,aAAa,MAAM,KAAKT,MAAMK,IAAIK,SAAQ,GAAIC,QAAO,CAAA,CAAA;IAC/F,WAAW,KAAKX,MAAMK,IAAIC,WAAW,OAAO;AACxCJ,aAAcK,OAAOE,YAAYF,OAAOI,QAAe,UAAMC,oBAAS,KAAKZ,KAAK,CAAA,CAAA;IACpF;AAEA,WAAOE;EACX;;;;EAKA,MAAMW,MAAoBC,KAAaC,cAA8B;AACjE,UAAMb,OAAO,MAAM,KAAKD,IAA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AAI,KAAK1B,cAAc,CAAC,KAAKC,cAAc;AACvC,WAAK,MAAK;IACd;EACJ;AACJ;;;ACpMO,SAAS0B,YACZC,UAAsB;AAEtB,SAAO,IAAIC,MAAMD,UAAU;IACvBE,IAAKC,QAAQC,MAAMC,UAAQ;AACvB,YAAMC,QAAQC,QAAQL,IAAIC,QAAQC,MAAMC,QAAAA;AACxC,UAAI,OAAOC,UAAU,YAAY;AAE7B,YAAIF,SAAS,UAAUA,SAAS,cAAc;AAC1C,iBAAO,IAAII,SAAAA;AACP,kBAAMC,SAASH,MAAMI,MAAMP,QAAQK,IAAAA;AAEnCG,yBAAa,MAAMR,OAAO,WAAA,EAAY,CAAA;AACtC,mBAAOM;UACX;QACJ,WAAWL,SAAS,QAAQ;AACxB,iBAAO,IAAII,SAAAA;AAEPL,mBAAO,YAAA,IAAgB;AAEvB,mBAAOG,MAAMI,MAAMP,QAAQK,IAAAA;UAC/B;QACJ;MACJ;AACA,aAAOF;IACX;EACJ,CAAA;AACJ;AA3BgBP;","names":["Middleware","Request","event","all","data","getRouterParams","getQuery","req","method","Object","assign","fromEntries","formData","entries","readBody","input","key","defaultValue","params","query","getEvent","safeDot","import_support","import_h3","Response","event","statusCode","headers","setStatusCode","code","res","status","setHeader","name","value","html","content","applyHeaders","json","data","text","redirect","url","Object","entries","forEach","key","set","getEvent","safeDot","LogRequests","Middleware","handle","request","next","url","getEvent","console","log","pathname","search","import_h3","HttpServiceProvider","ServiceProvider","register","app","singleton","H3","serve","JsonResource","request","response","resource","body","data","shouldSend","responseSent","event","rsc","req","res","key","Object","keys","defineProperty","enumerable","configurable","get","set","value","json","status","Array","isArray","pagination","meta","additional","send","code","context","this","checkSend","ApiResource","instance","Proxy","get","target","prop","receiver","value","Reflect","args","result","apply","setImmediate"]}
@@ -0,0 +1,199 @@
1
+ import { H3Event, EventHandlerRequest } from 'h3';
2
+ import { DotNestedKeys, DotNestedValue } from '@h3ravel/support';
3
+ import { ServiceProvider } from '@h3ravel/core';
4
+
5
+ declare class Request {
6
+ private readonly event;
7
+ constructor(event: H3Event);
8
+ /**
9
+ * Get all input data (query + body).
10
+ */
11
+ all<T = Record<string, unknown>>(): Promise<T>;
12
+ /**
13
+ * Get a single input field from query or body.
14
+ */
15
+ input<T = unknown>(key: string, defaultValue?: T): Promise<T>;
16
+ /**
17
+ * Get route parameters.
18
+ */
19
+ params<T = Record<string, string>>(): T;
20
+ /**
21
+ * Get query parameters.
22
+ */
23
+ query<T = Record<string, string>>(): T;
24
+ /**
25
+ * Get the base event
26
+ */
27
+ getEvent(): H3Event;
28
+ getEvent<K extends DotNestedKeys<H3Event>>(key: K): DotNestedValue<H3Event, K>;
29
+ }
30
+
31
+ declare class Response {
32
+ private readonly event;
33
+ private statusCode;
34
+ private headers;
35
+ constructor(event: H3Event);
36
+ /**
37
+ * Set HTTP status code.
38
+ */
39
+ setStatusCode(code: number): this;
40
+ /**
41
+ * Set a header.
42
+ */
43
+ setHeader(name: string, value: string): this;
44
+ html(content: string): string;
45
+ /**
46
+ * Send a JSON response.
47
+ */
48
+ json<T = unknown>(data: T): T;
49
+ /**
50
+ * Send plain text.
51
+ */
52
+ text(data: string): string;
53
+ /**
54
+ * Redirect to another URL.
55
+ */
56
+ redirect(url: string, status?: number): string;
57
+ /**
58
+ * Apply headers before sending response.
59
+ */
60
+ private applyHeaders;
61
+ /**
62
+ * Get the base event
63
+ */
64
+ getEvent(): H3Event;
65
+ getEvent<K extends DotNestedKeys<H3Event>>(key: K): DotNestedValue<H3Event, K>;
66
+ }
67
+
68
+ interface HttpContext {
69
+ request: Request;
70
+ response: Response;
71
+ }
72
+
73
+ declare abstract class Middleware {
74
+ abstract handle(context: HttpContext, next: () => Promise<unknown>): Promise<unknown>;
75
+ }
76
+
77
+ /**
78
+ * Defines the contract for all controllers.
79
+ * Any controller implementing this must define these methods.
80
+ */
81
+ interface IController {
82
+ show(ctx: HttpContext): any;
83
+ index(ctx: HttpContext): any;
84
+ store(ctx: HttpContext): any;
85
+ update(ctx: HttpContext): any;
86
+ destroy(ctx: HttpContext): any;
87
+ }
88
+
89
+ declare class LogRequests extends Middleware {
90
+ handle({ request }: HttpContext, next: () => Promise<unknown>): Promise<unknown>;
91
+ }
92
+
93
+ /**
94
+ * Sets up HTTP kernel and request lifecycle.
95
+ *
96
+ * Register Request, Response, and Middleware classes.
97
+ * Configure global middleware stack.
98
+ * Boot HTTP kernel.
99
+ *
100
+ * Auto-Registered
101
+ */
102
+ declare class HttpServiceProvider extends ServiceProvider {
103
+ register(): void;
104
+ }
105
+
106
+ interface Resource {
107
+ [key: string]: any;
108
+ pagination?: {
109
+ from?: number | undefined;
110
+ to?: number | undefined;
111
+ perPage?: number | undefined;
112
+ total?: number | undefined;
113
+ } | undefined;
114
+ }
115
+ type BodyResource = Resource & {
116
+ data: Omit<Resource, 'pagination'>;
117
+ meta?: {
118
+ pagination?: Resource['pagination'];
119
+ } | undefined;
120
+ };
121
+ /**
122
+ * Class to render API resource
123
+ */
124
+ declare class JsonResource<R extends Resource = any> {
125
+ #private;
126
+ private event;
127
+ /**
128
+ * The request instance
129
+ */
130
+ request: H3Event<EventHandlerRequest>['req'];
131
+ /**
132
+ * The response instance
133
+ */
134
+ response: H3Event['res'];
135
+ /**
136
+ * The data to send to the client
137
+ */
138
+ resource: R;
139
+ /**
140
+ * The final response data object
141
+ */
142
+ body: BodyResource;
143
+ /**
144
+ * Flag to track if response should be sent automatically
145
+ */
146
+ private shouldSend;
147
+ /**
148
+ * Flag to track if response has been sent
149
+ */
150
+ private responseSent;
151
+ /**
152
+ * Declare that this includes R's properties
153
+ */
154
+ [key: string]: any;
155
+ /**
156
+ * @param req The request instance
157
+ * @param res The response instance
158
+ * @param rsc The data to send to the client
159
+ */
160
+ constructor(event: H3Event, rsc: R);
161
+ /**
162
+ * Return the data in the expected format
163
+ *
164
+ * @returns
165
+ */
166
+ data(): Resource;
167
+ /**
168
+ * Build the response object
169
+ * @returns this
170
+ */
171
+ json(): this;
172
+ /**
173
+ * Add context data to the response object
174
+ * @param data Context data
175
+ * @returns this
176
+ */
177
+ additional<X extends {
178
+ [key: string]: any;
179
+ }>(data: X): this;
180
+ /**
181
+ * Send the output to the client
182
+ * @returns this
183
+ */
184
+ send(): this;
185
+ /**
186
+ * Set the status code for this response
187
+ * @param code Status code
188
+ * @returns this
189
+ */
190
+ status(code: number): this;
191
+ /**
192
+ * Check if send should be triggered automatically
193
+ */
194
+ private checkSend;
195
+ }
196
+
197
+ declare function ApiResource(instance: JsonResource): JsonResource<any>;
198
+
199
+ export { ApiResource, type HttpContext, HttpServiceProvider, type IController, JsonResource, LogRequests, Middleware, Request, type Resource, Response };