semola 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +19 -5
  2. package/dist/index-DISN0WKZ.d.mts +78 -0
  3. package/dist/lib/api/index.cjs +1 -537
  4. package/dist/lib/api/index.d.cts +1 -271
  5. package/dist/lib/api/index.d.mts +100 -164
  6. package/dist/lib/api/index.mjs +1 -535
  7. package/dist/lib/cache/index.cjs +1 -99
  8. package/dist/lib/cache/index.d.cts +1 -27
  9. package/dist/lib/cache/index.mjs +1 -98
  10. package/dist/lib/cli/index.cjs +3 -0
  11. package/dist/lib/cli/index.d.cts +1 -0
  12. package/dist/lib/cli/index.d.mts +90 -0
  13. package/dist/lib/cli/index.mjs +3 -0
  14. package/dist/lib/cron/index.cjs +1 -735
  15. package/dist/lib/cron/index.d.cts +1 -146
  16. package/dist/lib/cron/index.d.mts +99 -36
  17. package/dist/lib/cron/index.mjs +1 -726
  18. package/dist/lib/errors/index.cjs +1 -30
  19. package/dist/lib/errors/index.d.cts +1 -13
  20. package/dist/lib/errors/index.mjs +1 -26
  21. package/dist/lib/i18n/index.cjs +1 -42
  22. package/dist/lib/i18n/index.d.cts +1 -28
  23. package/dist/lib/i18n/index.d.mts +2 -2
  24. package/dist/lib/i18n/index.mjs +1 -41
  25. package/dist/lib/logging/index.cjs +1 -388
  26. package/dist/lib/logging/index.d.cts +1 -108
  27. package/dist/lib/logging/index.mjs +1 -374
  28. package/dist/lib/orm/index.cjs +1 -1642
  29. package/dist/lib/orm/index.d.cts +1 -402
  30. package/dist/lib/orm/index.d.mts +27 -25
  31. package/dist/lib/orm/index.mjs +1 -1630
  32. package/dist/lib/policy/index.cjs +1 -285
  33. package/dist/lib/policy/index.d.cts +1 -77
  34. package/dist/lib/policy/index.d.mts +1 -1
  35. package/dist/lib/policy/index.mjs +1 -265
  36. package/dist/lib/prompts/index.cjs +6 -769
  37. package/dist/lib/prompts/index.d.cts +1 -75
  38. package/dist/lib/prompts/index.mjs +6 -762
  39. package/dist/lib/pubsub/index.cjs +1 -141
  40. package/dist/lib/pubsub/index.d.cts +1 -26
  41. package/dist/lib/pubsub/index.mjs +1 -140
  42. package/dist/lib/queue/index.cjs +1 -212
  43. package/dist/lib/queue/index.d.cts +1 -81
  44. package/dist/lib/queue/index.mjs +1 -209
  45. package/dist/lib/workflow/index.cjs +1 -537
  46. package/dist/lib/workflow/index.d.cts +1 -150
  47. package/dist/lib/workflow/index.d.mts +0 -1
  48. package/dist/lib/workflow/index.mjs +1 -527
  49. package/dist/rolldown-runtime-CMqjfN_6.cjs +1 -0
  50. package/package.json +17 -5
  51. package/dist/chunk-CKQMccvm.cjs +0 -28
@@ -1,535 +1 @@
1
- import { mightThrow } from "../errors/index.mjs";
2
- //#region src/lib/api/openapi/index.ts
3
- const toOpenAPISchema = (schema, io = "input") => ({ schema: schema["~standard"].jsonSchema[io]({ target: "draft-2020-12" }) });
4
- const getSchemaDescription = (schema) => {
5
- const metadata = schema["~standard"];
6
- if (!metadata) return "";
7
- if ("description" in metadata && typeof metadata.description === "string") return metadata.description;
8
- return "";
9
- };
10
- const requestFields = [
11
- "body",
12
- "query",
13
- "headers",
14
- "cookies",
15
- "params"
16
- ];
17
- const mergeRequestSchemas = (schemas) => {
18
- const merged = {};
19
- for (const schema of schemas) {
20
- if (!schema) continue;
21
- for (const field of requestFields) if (schema[field]) merged[field] = schema[field];
22
- }
23
- return merged;
24
- };
25
- const mergeResponseSchemas = (schemas) => {
26
- const merged = {};
27
- for (const schema of schemas) {
28
- if (!schema) continue;
29
- for (const status in schema) {
30
- const statusCode = Number(status);
31
- const responseSchema = schema[statusCode];
32
- if (responseSchema) merged[statusCode] = responseSchema;
33
- }
34
- }
35
- return Object.keys(merged).length > 0 ? merged : void 0;
36
- };
37
- const convertSchemaToOpenApi = async (schema, io = "input") => {
38
- const result = toOpenAPISchema(schema, io);
39
- const { schema: jsonSchema } = result;
40
- const schemaId = jsonSchema.id;
41
- if (schemaId && typeof schemaId === "string") {
42
- const schemaWithoutId = { ...jsonSchema };
43
- delete schemaWithoutId.id;
44
- delete schemaWithoutId.$schema;
45
- return {
46
- schema: { $ref: `#/components/schemas/${schemaId}` },
47
- components: { schemas: { [schemaId]: schemaWithoutId } }
48
- };
49
- }
50
- if (jsonSchema.$schema) {
51
- const schemaWithoutMeta = { ...jsonSchema };
52
- delete schemaWithoutMeta.$schema;
53
- return {
54
- schema: schemaWithoutMeta,
55
- components: void 0
56
- };
57
- }
58
- return result;
59
- };
60
- const convertSchemaToInlineOpenApi = async (schema, io = "input") => {
61
- const { schema: jsonSchema } = toOpenAPISchema(schema, io);
62
- const cleanSchema = { ...jsonSchema };
63
- delete cleanSchema.$schema;
64
- delete cleanSchema.id;
65
- return {
66
- schema: cleanSchema,
67
- components: void 0
68
- };
69
- };
70
- const extractParametersFromSchema = async (schema, location) => {
71
- const { schema: jsonSchema, components } = await convertSchemaToInlineOpenApi(schema);
72
- if (jsonSchema.type !== "object") return {
73
- parameters: [],
74
- components
75
- };
76
- if (!jsonSchema.properties) return {
77
- parameters: [],
78
- components
79
- };
80
- const parameters = [];
81
- const requiredFields = jsonSchema.required ?? [];
82
- for (const name in jsonSchema.properties) {
83
- const propertySchema = jsonSchema.properties[name];
84
- const isRequired = requiredFields.includes(name);
85
- parameters.push({
86
- name,
87
- in: location,
88
- required: isRequired,
89
- schema: propertySchema
90
- });
91
- }
92
- return {
93
- parameters,
94
- components
95
- };
96
- };
97
- const normalizePathForOpenAPI = (path) => {
98
- return path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "{$1}");
99
- };
100
- const extractPathParameters = (path) => {
101
- const matches = path.match(/:([a-zA-Z_][a-zA-Z0-9_]*)/g);
102
- if (!matches) return [];
103
- return matches.map((match) => match.slice(1));
104
- };
105
- const paramSources = [
106
- ["query", "query"],
107
- ["headers", "header"],
108
- ["cookies", "cookie"]
109
- ];
110
- const createParameters = async (request, path) => {
111
- const parameters = [];
112
- const allComponents = [];
113
- for (const [field, location] of paramSources) if (request[field]) {
114
- const { parameters: params, components } = await extractParametersFromSchema(request[field], location);
115
- parameters.push(...params);
116
- if (components) allComponents.push(components);
117
- }
118
- const pathParamNames = extractPathParameters(path);
119
- if (pathParamNames.length > 0 && request.params) {
120
- const { schema: jsonSchema, components } = await convertSchemaToInlineOpenApi(request.params);
121
- if (components) allComponents.push(components);
122
- if (jsonSchema.type === "object" && jsonSchema.properties) for (const name of pathParamNames) {
123
- const propertySchema = jsonSchema.properties[name];
124
- if (propertySchema) parameters.push({
125
- name,
126
- in: "path",
127
- required: true,
128
- schema: propertySchema
129
- });
130
- }
131
- }
132
- return {
133
- parameters,
134
- components: allComponents
135
- };
136
- };
137
- const createRequestBody = async (bodySchema) => {
138
- const { schema, components } = await convertSchemaToOpenApi(bodySchema);
139
- return {
140
- components,
141
- requestBody: {
142
- required: true,
143
- content: { "application/json": { schema } }
144
- }
145
- };
146
- };
147
- const createResponses = async (response) => {
148
- const responses = {};
149
- const allComponents = [];
150
- if (!response) return {
151
- responses,
152
- components: allComponents
153
- };
154
- for (const status in response) {
155
- const statusCode = String(status);
156
- const schema = response[Number(status)];
157
- if (!schema) continue;
158
- const description = getSchemaDescription(schema);
159
- const { schema: jsonSchema, components } = await convertSchemaToOpenApi(schema, "output");
160
- if (components) allComponents.push(components);
161
- responses[statusCode] = {
162
- description: description || `Response with status ${statusCode}`,
163
- content: { "application/json": { schema: jsonSchema } }
164
- };
165
- }
166
- return {
167
- responses,
168
- components: allComponents
169
- };
170
- };
171
- const createOperation = async (route, globalMiddlewares, prefix) => {
172
- const allMiddlewares = [...globalMiddlewares ?? [], ...route.middlewares ?? []];
173
- const requestSchemas = [];
174
- const responseSchemas = [];
175
- for (const middleware of allMiddlewares) {
176
- requestSchemas.push(middleware.options.request);
177
- responseSchemas.push(middleware.options.response);
178
- }
179
- requestSchemas.push(route.request);
180
- responseSchemas.push(route.response);
181
- const mergedRequest = mergeRequestSchemas(requestSchemas);
182
- const mergedResponse = mergeResponseSchemas(responseSchemas);
183
- const { parameters, components: parameterComponents } = await createParameters(mergedRequest, prefix ? prefix + route.path : route.path);
184
- const { responses, components: responseComponents } = await createResponses(mergedResponse);
185
- const operation = { responses };
186
- const allComponents = [];
187
- allComponents.push(...responseComponents);
188
- allComponents.push(...parameterComponents);
189
- for (const field of [
190
- "summary",
191
- "description",
192
- "operationId"
193
- ]) if (route[field]) operation[field] = route[field];
194
- if (route.tags && route.tags.length > 0) operation.tags = route.tags;
195
- if (parameters.length > 0) operation.parameters = parameters;
196
- const bodySchema = mergedRequest.body;
197
- if (bodySchema) {
198
- const { requestBody, components: bodyComponents } = await createRequestBody(bodySchema);
199
- operation.requestBody = requestBody;
200
- if (bodyComponents) allComponents.push(bodyComponents);
201
- }
202
- return {
203
- operation,
204
- components: allComponents
205
- };
206
- };
207
- const componentKeys = [
208
- "schemas",
209
- "responses",
210
- "parameters",
211
- "requestBodies"
212
- ];
213
- const mergeComponents = (componentsArray) => {
214
- const merged = {};
215
- for (const components of componentsArray) {
216
- if (!components) continue;
217
- for (const key of componentKeys) if (components[key]) merged[key] = {
218
- ...merged[key],
219
- ...components[key]
220
- };
221
- }
222
- return merged;
223
- };
224
- const generateOpenApiSpec = async (options) => {
225
- const spec = {
226
- openapi: "3.1.0",
227
- info: {
228
- title: options.title,
229
- description: options.description,
230
- version: options.version
231
- },
232
- paths: {}
233
- };
234
- if (options.servers && options.servers.length > 0) spec.servers = options.servers;
235
- if (options.securitySchemes) spec.components = { securitySchemes: options.securitySchemes };
236
- const allRouteComponents = [];
237
- for (const route of options.routes) {
238
- const openApiPath = normalizePathForOpenAPI(options.prefix ? options.prefix + route.path : route.path);
239
- const method = route.method.toLowerCase();
240
- if (!spec.paths[openApiPath]) spec.paths[openApiPath] = {};
241
- const { operation, components } = await createOperation(route, options.globalMiddlewares ?? [], options.prefix);
242
- spec.paths[openApiPath][method] = operation;
243
- allRouteComponents.push(...components);
244
- }
245
- const mergedComponents = mergeComponents(allRouteComponents);
246
- if (!spec.components) spec.components = {};
247
- if (options.securitySchemes) spec.components.securitySchemes = options.securitySchemes;
248
- for (const key of componentKeys) {
249
- const value = mergedComponents[key];
250
- if (value && Object.keys(value).length > 0) spec.components[key] = value;
251
- }
252
- return spec;
253
- };
254
- //#endregion
255
- //#region src/lib/api/errors.ts
256
- var ParseError = class extends Error {
257
- constructor(message) {
258
- super(message);
259
- this.name = "ParseError";
260
- }
261
- };
262
- var ValidationError = class extends Error {
263
- constructor(message) {
264
- super(message);
265
- this.name = "ValidationError";
266
- }
267
- };
268
- //#endregion
269
- //#region src/lib/api/validation/index.ts
270
- const validateSchema = async (schema, data) => {
271
- const result = await schema["~standard"].validate(data);
272
- if (!result.issues) return result.value;
273
- throw new ValidationError(result.issues.map((issue) => {
274
- let path = "unknown";
275
- if (Array.isArray(issue.path)) path = issue.path.map(String).join(".");
276
- return `${path}: ${issue.message ?? "validation failed"}`;
277
- }).join(", "));
278
- };
279
- const validateBody = async (req, bodySchema, bodyCache) => {
280
- if (!bodySchema) return true;
281
- if (!(req.headers.get("content-type") ?? "").includes("application/json")) return;
282
- if (bodyCache?.parsed) return validateSchema(bodySchema, bodyCache.value);
283
- const [parseError, parsedBody] = await mightThrow(req.json());
284
- if (parseError) throw new ParseError("Invalid JSON body");
285
- if (bodyCache) {
286
- bodyCache.parsed = true;
287
- bodyCache.value = parsedBody;
288
- }
289
- return validateSchema(bodySchema, parsedBody);
290
- };
291
- const validateQuery = async (req, querySchema) => {
292
- if (!querySchema) return true;
293
- const qIndex = req.url.indexOf("?");
294
- if (qIndex === -1) return validateSchema(querySchema, {});
295
- const hashIndex = req.url.indexOf("#", qIndex + 1);
296
- const queryString = hashIndex === -1 ? req.url.slice(qIndex + 1) : req.url.slice(qIndex + 1, hashIndex);
297
- const searchParams = new URLSearchParams(queryString);
298
- const queryParams = {};
299
- for (const key of searchParams.keys()) {
300
- const values = searchParams.getAll(key);
301
- const [firstValue] = values;
302
- if (values.length === 1) queryParams[key] = firstValue;
303
- else queryParams[key] = values;
304
- }
305
- return validateSchema(querySchema, queryParams);
306
- };
307
- const validateHeaders = async (req, headersSchema) => {
308
- if (!headersSchema) return true;
309
- const headers = {};
310
- req.headers.forEach((value, key) => {
311
- headers[key] = value;
312
- });
313
- return validateSchema(headersSchema, headers);
314
- };
315
- const validateCookies = async (req, cookiesSchema) => {
316
- if (!cookiesSchema) return true;
317
- const cookieHeader = req.headers.get("cookie") ?? "";
318
- const cookieMap = new Bun.CookieMap(cookieHeader);
319
- return validateSchema(cookiesSchema, Object.fromEntries(cookieMap));
320
- };
321
- const validateParams = async (req, paramsSchema) => {
322
- if (!paramsSchema) return true;
323
- return validateSchema(paramsSchema, req.params);
324
- };
325
- //#endregion
326
- //#region src/lib/api/core/index.ts
327
- const defaultValidated = Object.freeze({
328
- body: void 0,
329
- query: void 0,
330
- headers: void 0,
331
- cookies: void 0,
332
- params: void 0
333
- });
334
- const responseHelpers = {
335
- json: (status, data) => Response.json(data, { status }),
336
- text: (status, text) => new Response(text, { status }),
337
- html: (status, html) => new Response(html, {
338
- status,
339
- headers: { "Content-Type": "text/html" }
340
- }),
341
- redirect: (status, url) => Response.redirect(url, status)
342
- };
343
- const noopGet = () => void 0;
344
- const stripTrailingSlash = (path) => {
345
- if (path !== "/" && path.endsWith("/")) return path.slice(0, -1);
346
- return path;
347
- };
348
- const hasSchemas = (schema) => schema && (schema.body || schema.query || schema.headers || schema.cookies || schema.params);
349
- const needsBodyCache = (schema) => schema?.body !== void 0;
350
- const shouldCreateBodyCache = (hasMiddlewares, allMiddlewares, request) => {
351
- if (needsBodyCache(request)) return true;
352
- if (!hasMiddlewares) return false;
353
- return allMiddlewares.some((mw) => needsBodyCache(mw.options.request));
354
- };
355
- const resolveValidation = (v) => {
356
- if (v === void 0 || v === true) return {
357
- input: true,
358
- output: true
359
- };
360
- if (v === false) return {
361
- input: false,
362
- output: false
363
- };
364
- return {
365
- input: v.input !== false,
366
- output: v.output !== false
367
- };
368
- };
369
- var Api = class {
370
- options;
371
- routes = [];
372
- constructor(options = {}) {
373
- this.options = options;
374
- }
375
- getFullPath(path) {
376
- const normalizedPath = stripTrailingSlash(path) || "/";
377
- if (!this.options.prefix) return normalizedPath;
378
- const normalizedPrefix = stripTrailingSlash(this.options.prefix);
379
- if (normalizedPrefix === "/") return normalizedPath;
380
- if (normalizedPath === "/") return normalizedPrefix;
381
- return normalizedPrefix + normalizedPath;
382
- }
383
- async validateRequestSchema(req, schema, bodyCache) {
384
- if (!schema) return {
385
- success: true,
386
- data: {}
387
- };
388
- const v = {};
389
- if (schema.body) {
390
- const [err, val] = await mightThrow(validateBody(req, schema.body, bodyCache));
391
- if (err) return {
392
- success: false,
393
- error: err
394
- };
395
- v.body = val;
396
- }
397
- if (schema.query) {
398
- const [err, val] = await mightThrow(validateQuery(req, schema.query));
399
- if (err) return {
400
- success: false,
401
- error: err
402
- };
403
- v.query = val;
404
- }
405
- if (schema.headers) {
406
- const [err, val] = await mightThrow(validateHeaders(req, schema.headers));
407
- if (err) return {
408
- success: false,
409
- error: err
410
- };
411
- v.headers = val;
412
- }
413
- if (schema.cookies) {
414
- const [err, val] = await mightThrow(validateCookies(req, schema.cookies));
415
- if (err) return {
416
- success: false,
417
- error: err
418
- };
419
- v.cookies = val;
420
- }
421
- if (schema.params) {
422
- const [err, val] = await mightThrow(validateParams(req, schema.params));
423
- if (err) return {
424
- success: false,
425
- error: err
426
- };
427
- v.params = val;
428
- }
429
- return {
430
- success: true,
431
- data: v
432
- };
433
- }
434
- createContext(req, validated, extensions) {
435
- return {
436
- raw: req,
437
- req: validated,
438
- ...responseHelpers,
439
- get: (key) => extensions[key]
440
- };
441
- }
442
- async validateResponseBody(response, schema) {
443
- if (!schema) return response;
444
- const statusSchema = schema[response.status];
445
- if (!statusSchema) return response;
446
- if (!(response.headers.get("content-type") ?? "").includes("application/json")) return response;
447
- const [parseError, body] = await mightThrow(response.clone().json());
448
- if (parseError) return responseHelpers.json(400, { message: "Invalid response body" });
449
- const [validationError] = await mightThrow(validateSchema(statusSchema, body));
450
- if (validationError) return responseHelpers.json(400, { message: validationError.message });
451
- return response;
452
- }
453
- buildBunRoutes() {
454
- const bunRoutes = {};
455
- const validationConfig = resolveValidation(this.options.validation);
456
- for (const route of this.routes) {
457
- const { path, method, handler, request, response, middlewares } = route;
458
- const fullPath = this.getFullPath(path);
459
- if (!bunRoutes[fullPath]) bunRoutes[fullPath] = {};
460
- const allMiddlewares = [...this.options.middlewares ?? [], ...middlewares ?? []];
461
- const hasMiddlewares = allMiddlewares.length > 0;
462
- const hasRouteSchemas = hasSchemas(request);
463
- const effectiveOutputValidation = validationConfig.output && !!response;
464
- if (!hasMiddlewares && !(validationConfig.input && hasRouteSchemas) && !effectiveOutputValidation) bunRoutes[fullPath][method] = (req) => {
465
- const context = Object.create(responseHelpers);
466
- context.raw = req;
467
- context.req = defaultValidated;
468
- context.get = noopGet;
469
- return handler(context);
470
- };
471
- else bunRoutes[fullPath][method] = async (req) => {
472
- const extensions = {};
473
- const bodyCache = validationConfig.input && shouldCreateBodyCache(hasMiddlewares, allMiddlewares, request) ? {
474
- parsed: false,
475
- value: void 0
476
- } : void 0;
477
- for (const mw of allMiddlewares) {
478
- const { request: reqSchema, handler: mwHandler } = mw.options;
479
- let validated = defaultValidated;
480
- if (validationConfig.input && hasSchemas(reqSchema)) {
481
- const result = await this.validateRequestSchema(req, reqSchema, bodyCache);
482
- if (!result.success) return responseHelpers.json(400, { message: result.error?.message });
483
- validated = result.data;
484
- }
485
- const mwResult = await mwHandler(this.createContext(req, validated, extensions));
486
- if (mwResult instanceof Response) return mwResult;
487
- if (mwResult) Object.assign(extensions, mwResult);
488
- }
489
- let routeValidated = defaultValidated;
490
- if (validationConfig.input && hasRouteSchemas) {
491
- const result = await this.validateRequestSchema(req, request, bodyCache);
492
- if (!result.success) return responseHelpers.json(400, { message: result.error?.message });
493
- routeValidated = result.data;
494
- }
495
- const handlerResponse = await handler(this.createContext(req, routeValidated, extensions));
496
- if (effectiveOutputValidation) return this.validateResponseBody(handlerResponse, response);
497
- return handlerResponse;
498
- };
499
- }
500
- return bunRoutes;
501
- }
502
- defineRoute(config) {
503
- this.routes.push(config);
504
- }
505
- getOpenApiSpec() {
506
- return generateOpenApiSpec({
507
- title: this.options.openapi?.title ?? "API",
508
- description: this.options.openapi?.description,
509
- version: this.options.openapi?.version ?? "1.0.0",
510
- prefix: this.options.prefix,
511
- servers: this.options.openapi?.servers,
512
- securitySchemes: this.options.openapi?.securitySchemes,
513
- routes: this.routes,
514
- globalMiddlewares: this.options.middlewares
515
- });
516
- }
517
- serve(port, callback) {
518
- const bunRoutes = this.buildBunRoutes();
519
- const server = Bun.serve({
520
- port,
521
- routes: bunRoutes,
522
- fetch: () => new Response("Not found", { status: 404 })
523
- });
524
- if (callback) callback(server);
525
- }
526
- };
527
- //#endregion
528
- //#region src/lib/api/middleware/index.ts
529
- var Middleware = class {
530
- constructor(options) {
531
- this.options = options;
532
- }
533
- };
534
- //#endregion
535
- export { Api, Middleware };
1
+ const e={status:404},t=(e,t)=>{let n=e.split(`/`).slice(1),r=[],i=0;for(let e of n){if(e.startsWith(`:`)){r.push({value:``,paramName:e.slice(1)}),i++;continue}r.push({value:e})}return{segments:r,methods:t,paramStarts:Array(i),paramEnds:Array(i)}},n=(e,t)=>{let n=1,r=0;if(t===`/`)return e.segments.length===0;for(let i of e.segments){let a=t.indexOf(`/`,n),o=t.length;if(a!==-1&&(o=a),i.paramName){if(o===n)return!1;e.paramStarts[r]=n,e.paramEnds[r]=o,r++}else{let e=o-n;if(i.value.length!==e||!t.startsWith(i.value,n))return!1}n=a===-1?t.length:a+1}return n===t.length},r=(e,t)=>{let n={},r=0;for(let i of e.segments)i.paramName&&(n[i.paramName]=t.slice(e.paramStarts[r],e.paramEnds[r]),r++);return n},i=e=>{let t=e.indexOf(`://`),n=e.indexOf(`/`,t+3);if(n===-1)return`/`;let r=e.indexOf(`?`,n),i;return i=r===-1?e.slice(n):e.slice(n,r),i.length>1&&i.endsWith(`/`)?i.slice(0,-1):i},a=a=>{let o=Object.create(null),s=[],c=[];for(let[e,n]of Object.entries(a)){let r=n;if(e.includes(`*`)){c.push({pattern:new URLPattern({pathname:e}),methods:r});continue}if(e.includes(`:`)){s.push(t(e,r));continue}o[e]=r}return t=>{let a=i(t.url),l=t.method,u=o[a]?.[l];if(u)return u(t);for(let e of s){if(!n(e,a))continue;let i=e.methods[l];if(i)return t.params=r(e,a),i(t)}for(let e of c){let n=e.pattern.exec({pathname:a});if(!n)continue;let r=e.methods[l];if(r)return t.params=n.pathname.groups,r(t)}return new Response(`Not found`,e)}};var o=class extends Error{constructor(e){super(e),this.name=`ParseError`}},s=class extends Error{constructor(e){super(e),this.name=`ValidationError`}},c=class extends Error{constructor(e){super(e),this.name=`SchemaConfigError`}},l=class extends Error{constructor(e,t){super(`Duplicate route: ${e} ${t}`),this.name=`DuplicateRouteError`}};function u(e){if(e.path?.length){let t=``;for(let n of e.path){let e=typeof n==`object`?n.key:n;if(typeof e==`string`||typeof e==`number`)t?t+=`.${e}`:t+=e;else return null}return t}return null}const d=e=>u(e)??`unknown`,f=e=>e.map(e=>`${d(e)}: ${e.message??`validation failed`}`).join(`, `),p=e=>{if(!e.issues)return e.value;throw new s(f(e.issues))},m=(e,t=!1)=>{let n=e;t&&e.includes(`+`)&&(n=e.replaceAll(`+`,` `));try{return decodeURIComponent(n)}catch{return n}},ee=(e,t,n)=>{let r=e[t];if(r===void 0){e[t]=n;return}if(Array.isArray(r)){r.push(n);return}e[t]=[r,n]},h=(e,t)=>{let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new c(`Async schema validation is not supported`);return p(n)},g=async(e,t,n)=>{if(!t)return!0;if(n?.parsed)return h(t,n.value);let r=e.headers.get(`content-type`)??``,i;if(r.startsWith(`application/json`))try{i=await e.json()}catch{throw new o(`Invalid JSON body`)}else i=await e.text();return n&&(n.parsed=!0,n.value=i),h(t,i)},te=(e,t)=>{if(!t)return!0;let n=e.url.indexOf(`?`);if(n===-1)return h(t,{});let r=e.url.indexOf(`#`,n+1),i=e.url.length;r!==-1&&(i=r);let a={},o=n+1;for(;o<=i;){let t=e.url.indexOf(`&`,o),n=i;if(t!==-1&&t<i&&(n=t),n>o){let t=e.url.indexOf(`=`,o),r=t!==-1&&t<n,i=e.url.slice(o,n),s=``;r&&(i=e.url.slice(o,t),s=e.url.slice(t+1,n)),ee(a,m(i,!0),m(s,!0))}if(t===-1||t>=i)break;o=t+1}return h(t,a)},_=(e,t)=>{if(!t)return!0;let n={};for(let[t,r]of e.headers)n[t]=r;return h(t,n)},v=(e,t)=>{if(!t)return!0;let n=e.headers.get(`cookie`)??``,r={},i=0;for(;i<n.length;){let e=n.indexOf(`;`,i),t=n.length;e!==-1&&(t=e);let a=n.indexOf(`=`,i);if(a!==-1&&a<t){let e=n.slice(i,a).trim();if(e){let i=n.slice(a+1,t).trim();r[e]=m(i)}}if(e===-1)break;i=e+1}return h(t,r)},ne=(e,t)=>!t||h(t,e.params??{}),y=async(e,t)=>{let n=e.schema;if(n)try{if(n.body){let r=await g(e.req,n.body,e.bodyCache);t&&(t.body=r)}if(n.query){let r=te(e.req,n.query);t&&(t.query=r)}if(n.headers){let r=_(e.req,n.headers);t&&(t.headers=r)}if(n.cookies){let r=v(e.req,n.cookies);t&&(t.cookies=r)}if(n.params){let r=ne(e.req,n.params);t&&(t.params=r)}}catch(e){return e}},b=e=>{if(e)return(t,n)=>y({req:t,schema:e,bodyCache:n})},x={"Content-Type":`text/html`},S={status:400},C=(e,t)=>e===200?Response.json(t):Response.json(t,{status:e}),w=(e,t)=>e===200?new Response(t):new Response(t,{status:e}),T=(e,t)=>new Response(t,{status:e,headers:x}),E=(e,t)=>Response.redirect(t,e),D=e=>Response.json({message:e},S),O=e=>{if(e instanceof s||e instanceof o)return D(e.message);throw e},k=e=>(t,n)=>{let r=e[t];if(!r)return C(t,n);try{h(r,n)}catch(e){return O(e)}return C(t,n)},A=Object.freeze({body:void 0,query:void 0,headers:void 0,cookies:void 0,params:void 0}),re={req:A,get:()=>{},json:C,text:w,html:T,redirect:E},j=(e,t,n,r)=>{let i=Object.create(re);return i.raw=e,t&&(i.req=t),n&&(i.get=n),r&&(i.json=r),i},M=e=>e!==`/`&&e.endsWith(`/`)?e.slice(0,-1):e,N=e=>{let t=M(e.path)||`/`;if(!e.prefix)return t;let n=M(e.prefix);return n===`/`?t:t===`/`?n:n+t},P=e=>{let t=0;e.request?.body!==void 0&&t++;for(let n of e.middlewares)if(n.options.request?.body!==void 0&&(t++,t>1))return!0;return!1},F=e=>e===void 0||e===!0?{input:!0,output:!0}:e===!1?{input:!1,output:!1}:{input:e.input!==!1,output:e.output!==!1},I=[],L=(e,t)=>e?.length?t?.length?[...e,...t]:e:t??I,R=(e,t)=>e?t?N({prefix:e,path:t}):e:t;var z=class{options;routes=[];groups=[];parent;constructor(e={}){this.options=e}defineRoute(e){this.routes.push(e),this.onRoutesChanged()}mount(e){e.parent=this,this.groups.push(e),this.onRoutesChanged()}onRoutesChanged(){this.parent?.onRoutesChanged()}collectRoutes(e=this.options.prefix,t=I){let n=L(t,this.options.middlewares),r=this.routes.map(t=>({...t,path:N({prefix:e,path:t.path}),middlewares:L(n,t.middlewares)}));for(let t of this.groups){let i=t.collectRoutes(R(e,t.options.prefix),n);r.push(...i)}return r}};const B=e=>{if(Array.isArray(e))return e.map(B);if(typeof e!=`object`||!e)return e;let t=e;if(typeof t.$ref==`string`&&t.$ref.startsWith(`#/$defs/`))return{$ref:`#/components/schemas/${t.$ref.slice(8)}`};let n={};for(let e in t)n[e]=B(t[e]);return n},V=e=>{let t=e.$defs;if(!t||typeof t!=`object`)return{schema:e,components:void 0};let n=B({...e});delete n.$defs;let r=t,i={};for(let e in r)i[e]=B(r[e]);return{schema:n,components:{schemas:i}}},H=(e,t=`input`)=>{let n=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`});return V(n)},U=e=>{let t=e[`~standard`];return t&&`description`in t&&typeof t.description==`string`?t.description:``},W=e=>{let t=e.meta;if(typeof t!=`function`)return;let n=t();if(typeof n==`object`&&n&&typeof n.id==`string`)return n.id},G=(e,t)=>typeof t.id==`string`?t.id:W(e),K=[`body`,`query`,`headers`,`cookies`,`params`],q=(e,t=`input`)=>{let n=H(e,t),{schema:r,components:i}=n,a=G(e,r);if(a){let e={...r};return delete e.id,delete e.$schema,{schema:{$ref:`#/components/schemas/${a}`},components:{...i,schemas:{...i?.schemas,[a]:e}}}}if(r.$schema){let e={...r};return delete e.$schema,{schema:e,components:i}}return n},J=(e,t=`input`)=>{let{schema:n,components:r}=H(e,t),i={...n};return delete i.$schema,delete i.id,{schema:i,components:r}},Y=(e,t)=>{let{schema:n,components:r}=J(e);if(n.type!==`object`||!n.properties)return{parameters:[],components:r};let i=[],a=n.required??[];for(let e in n.properties){let r=n.properties[e],o=a.includes(e);i.push({name:e,in:t,required:o,schema:r})}return{parameters:i,components:r}},ie=e=>e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,`{$1}`),ae=e=>{let t=e.match(/:([a-zA-Z_][a-zA-Z0-9_]*)/g);return t?t.map(e=>e.slice(1)):[]},oe=[[`query`,`query`],[`headers`,`header`],[`cookies`,`cookie`]],se=(e,t)=>{let n=[],r=[];for(let[t,i]of oe)if(e[t]){let{parameters:a,components:o}=Y(e[t],i);n.push(...a),o&&r.push(o)}let i=ae(t);if(i.length>0&&e.params){let{schema:t,components:a}=J(e.params);if(a&&r.push(a),t.type===`object`&&t.properties)for(let e of i){let r=t.properties[e];r&&n.push({name:e,in:`path`,required:!0,schema:r})}}return{parameters:n,components:r}},ce=e=>{let{schema:t,components:n}=q(e);return{components:n,requestBody:{required:!0,content:{"application/json":{schema:t}}}}},le=e=>{let t={},n=[];if(!e)return{responses:t,components:n};for(let r in e){let i=String(r),a=e[Number(r)];if(!a)continue;let o=U(a),{schema:s,components:c}=q(a,`output`);c&&n.push(c),t[i]={description:o||`Response with status ${i}`,content:{"application/json":{schema:s}}}}return{responses:t,components:n}},ue=(e,t,n)=>{let{request:r,response:i}=de(e,t),a=e.path;n&&(a=n+e.path);let{parameters:o,components:s}=se(r,a),{responses:c,components:l}=le(i),u={responses:c},d=[];d.push(...l),d.push(...s);for(let t of[`summary`,`description`,`operationId`])e[t]&&(u[t]=e[t]);e.tags&&e.tags.length>0&&(u.tags=e.tags),o.length>0&&(u.parameters=o);let f=r.body;if(f){let{requestBody:e,components:t}=ce(f);u.requestBody=e,t&&d.push(t)}return{operation:u,components:d}},de=(e,t)=>{let n={},r={};for(let i of[...t,...e.middlewares??[]])X(n,i.options.request),Z(r,i.options.response);X(n,e.request),Z(r,e.response);let i;return Object.keys(r).length>0&&(i=r),{request:n,response:i}},X=(e,t)=>{if(t)for(let n of K)t[n]&&(e[n]=t[n])},Z=(e,t)=>{if(t)for(let n in t){let r=Number(n),i=t[r];i&&(e[r]=i)}},fe=e=>{let t={openapi:`3.1.0`,info:{title:e.title,description:e.description,version:e.version},paths:{}};e.servers&&e.servers.length>0&&(t.servers=e.servers);let n={};for(let r of e.routes){let i=r.path;e.prefix&&(i=e.prefix+r.path);let a=ie(i),o=r.method.toLowerCase();t.paths[a]??={};let{operation:s,components:c}=ue(r,e.globalMiddlewares??[],e.prefix);t.paths[a][o]=s,c.forEach(e=>{Object.assign(n,e.schemas??{})})}let r=Object.keys(n).length>0;return(e.securitySchemes||r)&&(t.components={},e.securitySchemes&&(t.components.securitySchemes=e.securitySchemes),r&&(t.components.schemas=n)),t},pe=[],Q=e=>e instanceof Response?e:typeof e==`string`?new Response(e):Response.json(e),$=async(e,t)=>{let n=Q(e),r=t?.[n.status];if(!r)return n;let i=e;e instanceof Response&&(i=await n.clone().json());try{h(r,i)}catch(e){return O(e)}return n},me=(e,t)=>{if(e instanceof Response)return $(e,t);let n=Q(e),r=t?.[n.status];if(!r)return n;try{h(r,e)}catch(e){return O(e)}return n},he=(e,t,n,r=!1,i=!1)=>{let a=i?n:void 0,o=r?b(t):void 0,s=e();if(s instanceof Promise)return async t=>{if(o){let e=await o(t);if(e)return O(e)}let n=await e();return $(n,a)};let c=me(s,a);return o?async e=>{let t=await o(e);return t?O(t):c}:c instanceof Promise?async()=>c:()=>c},ge=e=>t=>{let n=e(j(t));return n instanceof Promise?n.then(e=>e instanceof Response?e:Q(e)):n instanceof Response?n:Q(n)},_e=(e,t,n)=>{if(!e.input)return!1;if(t)return!0;for(let e of n)if(e.options.request)return!0;return!1},ve=async(e,t)=>{let n,r,i;t.validateInput&&P({middlewares:t.middlewares,request:t.routeRequest})&&(i={parsed:!1,value:void 0});let a;t.validateOutput&&t.routeResponse&&(a=k(t.routeResponse)),t.middlewares.length>0&&(r=e=>n?.[e]);for(let a of t.middlewares){let{request:o,handler:s}=a.options,c=A;if(t.validateInput&&o){let t={},n=await y({req:e,schema:o,bodyCache:i},t);if(n)return O(n);c=t}let l=await s(j(e,c,r));if(l instanceof Response)return l;l&&(n||={},Object.assign(n,l))}let o=A;if(t.validateInput&&t.routeRequest){let n={},r=await y({req:e,schema:t.routeRequest,bodyCache:i},n);if(r)return O(r);o=n}let s=j(e,o,r,a);return t.handler(s)},ye=(e,t)=>{let n=e.middlewares??pe,r=e.handler,i=n.length>0,a=_e(t,e.request,n),o=t.output&&!!e.response;if(!i&&typeof r==`function`&&r.length===0)return he(r,e.request,e.response,a,o);if(!i&&typeof r==`function`&&r.length===1&&!a&&!o)return ge(r);let s={middlewares:n,routeRequest:e.request,routeResponse:e.response,validateInput:a,validateOutput:o,handler:r};return e=>ve(e,s)},be=(e,t)=>{let n={};for(let r of e){let e=n[r.path];if(e||(e={},n[r.path]=e),e[r.method])throw new l(r.method,r.path);e[r.method]=ye(r,t)}return n};var xe=class extends z{options;compiled;needsRecompile=!0;constructor(e={}){super(e),this.options=e}onRoutesChanged(){this.needsRecompile=!0,super.onRoutesChanged()}fetch=e=>this.ensureCompiled().fetch(e);getRouteHandlers(){return this.ensureCompiled().routes}getOpenApiSpec(){return fe({title:this.options.openapi?.title??`API`,description:this.options.openapi?.description,version:this.options.openapi?.version??`1.0.0`,servers:this.options.openapi?.servers,securitySchemes:this.options.openapi?.securitySchemes,routes:this.collectRoutes()})}serve(e,t){let n=Bun.serve({port:e,routes:this.getRouteHandlers(),fetch:()=>new Response(`Not found`,{status:404})});t&&t(n)}ensureCompiled(){if(!this.needsRecompile&&this.compiled)return this.compiled;let e=be(this.collectRoutes(),F(this.options.validation));return this.compiled={routes:e,fetch:a(e)},this.needsRecompile=!1,this.compiled}},Se=class{options;constructor(e){this.options=e}};export{xe as Api,z as Group,Se as Middleware};
@@ -1,99 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_lib_errors_index = require("../errors/index.cjs");
3
- //#region src/lib/cache/errors.ts
4
- var CacheError = class extends Error {
5
- constructor(message) {
6
- super(message);
7
- this.name = "CacheError";
8
- }
9
- };
10
- var InvalidTTLError = class extends Error {
11
- constructor(message) {
12
- super(message);
13
- this.name = "InvalidTTLError";
14
- }
15
- };
16
- var NotFoundError = class extends Error {
17
- constructor(message) {
18
- super(message);
19
- this.name = "NotFoundError";
20
- }
21
- };
22
- var SerializationError = class extends Error {
23
- constructor(message) {
24
- super(message);
25
- this.name = "SerializationError";
26
- }
27
- };
28
- var DeserializationError = class extends Error {
29
- constructor(message) {
30
- super(message);
31
- this.name = "DeserializationError";
32
- }
33
- };
34
- //#endregion
35
- //#region src/lib/cache/index.ts
36
- var Cache = class {
37
- options;
38
- serialize;
39
- deserialize;
40
- constructor(options) {
41
- this.options = options;
42
- this.serialize = options.serializer ?? JSON.stringify;
43
- this.deserialize = options.deserializer ?? ((raw) => JSON.parse(raw));
44
- }
45
- async get(key) {
46
- if (!this.isEnabled) throw new NotFoundError(`Key ${key} not found`);
47
- const resolvedKey = this.resolveKey(key);
48
- const [error, value] = await require_lib_errors_index.mightThrow(this.options.redis.get(resolvedKey));
49
- if (error) throw new CacheError(`Unable to get value for key ${key}`);
50
- if (value === null || value === void 0) throw new NotFoundError(`Key ${key} not found`);
51
- const [deserializeErr, deserialized] = require_lib_errors_index.mightThrowSync(() => this.deserialize(value));
52
- if (deserializeErr) throw new DeserializationError(`Unable to deserialize value for key ${key}`);
53
- return deserialized;
54
- }
55
- async set(key, value) {
56
- if (!this.isEnabled) return value;
57
- const [serializeErr, serialized] = require_lib_errors_index.mightThrowSync(() => this.serialize(value));
58
- if (serializeErr) throw new SerializationError(`Unable to serialize value for key ${key}`);
59
- if (serialized === null || serialized === void 0) throw new SerializationError(`Unable to serialize value for key ${key}`);
60
- const [ttlErr, ttl] = require_lib_errors_index.mightThrowSync(() => this.resolveTTL(key, value));
61
- if (ttlErr) throw new InvalidTTLError(`Unable to resolve ttl for key ${key}`);
62
- if (!this.isTTLValid(ttl)) throw new InvalidTTLError(`Unable to save records with ttl equal to ${ttl}`);
63
- const resolvedKey = this.resolveKey(key);
64
- const [setError] = await require_lib_errors_index.mightThrow(this.getSetPromise(resolvedKey, serialized, ttl));
65
- if (setError) throw new CacheError(`Unable to set value for key ${key}`);
66
- return value;
67
- }
68
- async delete(key) {
69
- if (!this.isEnabled) return 0;
70
- const resolvedKey = this.resolveKey(key);
71
- const [error, data] = await require_lib_errors_index.mightThrow(this.options.redis.del(resolvedKey));
72
- if (error) throw new CacheError(`Unable to delete key ${key}`);
73
- return data;
74
- }
75
- get isEnabled() {
76
- return this.options.enabled !== false;
77
- }
78
- resolveKey(key) {
79
- if (this.options.prefix) return `${this.options.prefix}:${key}`;
80
- return key;
81
- }
82
- resolveTTL(key, value) {
83
- if (typeof this.options.ttl === "function") return this.options.ttl(key, value);
84
- return this.options.ttl;
85
- }
86
- getSetPromise(key, value, ttl) {
87
- if (ttl === void 0 || ttl === null) return this.options.redis.set(key, value);
88
- return this.options.redis.set(key, value, "PX", ttl);
89
- }
90
- isTTLValid(ttl) {
91
- if (ttl === void 0 || ttl === null) return true;
92
- if (!Number.isFinite(ttl)) return false;
93
- if (!Number.isInteger(ttl)) return false;
94
- if (ttl < 0) return false;
95
- return true;
96
- }
97
- };
98
- //#endregion
99
- exports.Cache = Cache;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../errors/index.cjs");var t=class extends Error{constructor(e){super(e),this.name=`CacheError`}},n=class extends Error{constructor(e){super(e),this.name=`InvalidTTLError`}},r=class extends Error{constructor(e){super(e),this.name=`NotFoundError`}},i=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},a=class extends Error{constructor(e){super(e),this.name=`DeserializationError`}},o=class{options;serialize;deserialize;constructor(e){this.options=e,this.serialize=e.serializer??JSON.stringify,this.deserialize=e.deserializer??(e=>JSON.parse(e))}async get(n){if(!this.isEnabled)throw new r(`Key ${n} not found`);let i=this.resolveKey(n),[o,s]=await e.mightThrow(this.options.redis.get(i));if(o)throw new t(`Unable to get value for key ${n}`);if(s==null)throw new r(`Key ${n} not found`);let[c,l]=e.mightThrowSync(()=>this.deserialize(s));if(c)throw new a(`Unable to deserialize value for key ${n}`);return l}async set(r,a){if(!this.isEnabled)return a;let[o,s]=e.mightThrowSync(()=>this.serialize(a));if(o||s==null)throw new i(`Unable to serialize value for key ${r}`);let[c,l]=e.mightThrowSync(()=>this.resolveTTL(r,a));if(c)throw new n(`Unable to resolve ttl for key ${r}`);if(!this.isTTLValid(l))throw new n(`Unable to save records with ttl equal to ${l}`);let u=this.resolveKey(r),[d]=await e.mightThrow(this.getSetPromise(u,s,l));if(d)throw new t(`Unable to set value for key ${r}`);return a}async delete(n){if(!this.isEnabled)return 0;let r=this.resolveKey(n),[i,a]=await e.mightThrow(this.options.redis.del(r));if(i)throw new t(`Unable to delete key ${n}`);return a}get isEnabled(){return this.options.enabled!==!1}resolveKey(e){return this.options.prefix?`${this.options.prefix}:${e}`:e}resolveTTL(e,t){return typeof this.options.ttl==`function`?this.options.ttl(e,t):this.options.ttl}getSetPromise(e,t,n){return n==null?this.options.redis.set(e,t):this.options.redis.set(e,t,`PX`,n)}isTTLValid(e){return e==null||!(!Number.isFinite(e)||!Number.isInteger(e)||e<0)}};exports.Cache=o;
@@ -1,27 +1 @@
1
- //#region src/lib/cache/types.d.ts
2
- type CacheOptions<T> = {
3
- redis: Bun.RedisClient;
4
- ttl?: number | ((key: string, value: T) => number);
5
- enabled?: boolean;
6
- prefix?: string;
7
- serializer?: (value: T) => string;
8
- deserializer?: (raw: string) => T;
9
- };
10
- //#endregion
11
- //#region src/lib/cache/index.d.ts
12
- declare class Cache<T> {
13
- private options;
14
- private serialize;
15
- private deserialize;
16
- constructor(options: CacheOptions<T>);
17
- get(key: string): Promise<T>;
18
- set(key: string, value: T): Promise<T>;
19
- delete(key: string): Promise<number>;
20
- private get isEnabled();
21
- private resolveKey;
22
- private resolveTTL;
23
- private getSetPromise;
24
- private isTTLValid;
25
- }
26
- //#endregion
27
- export { Cache };
1
+ export type * from './index.d.mts'