asphodelos 0.3.0 → 0.3.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.
- package/README.md +55 -3
- package/dist/cli.d.mts +1 -1
- package/dist/cli.mjs +23 -15
- package/dist/{format-B0W7HIAg.mjs → format-DC258z--.mjs} +2 -3
- package/dist/index.d.mts +169 -171
- package/dist/index.mjs +27 -14
- package/dist/{openapi-C8b6Ibiu.mjs → openapi-4yNuDK_n.mjs} +15 -7
- package/dist/{rolldown-runtime-wcPFST8Q.mjs → rolldown-runtime-D8jQpDG7.mjs} +1 -2
- package/dist/{shared-Becl66EY.mjs → shared-nkpRcjdg.mjs} +795 -440
- package/dist/vite-plugin/index.d.mts +1 -4
- package/dist/vite-plugin/index.mjs +6 -13
- package/package.json +17 -17
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.mjs";
|
|
2
2
|
import { COMPONENT_KINDS, HOOK_KINDS } from "./index.mjs";
|
|
3
|
-
import { n as fmt } from "./format-
|
|
3
|
+
import { n as fmt } from "./format-DC258z--.mjs";
|
|
4
4
|
import { Data, Effect, FileSystem } from "effect";
|
|
5
5
|
import path, { posix } from "node:path";
|
|
6
6
|
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
|
|
7
7
|
import SwaggerParser from "@apidevtools/swagger-parser";
|
|
8
|
-
import {
|
|
9
|
-
|
|
8
|
+
import { parseSync } from "oxc-parser";
|
|
9
|
+
// src/fsp/index.ts
|
|
10
10
|
/**
|
|
11
11
|
* Node's `FileSystem` implementation.
|
|
12
12
|
*
|
|
@@ -16,8 +16,8 @@ import { Node, Project } from "ts-morph";
|
|
|
16
16
|
*/
|
|
17
17
|
const fileSystemLayer = NodeFileSystem.layer;
|
|
18
18
|
/** Whether a platform failure is "the path is not there", the one case worth absorbing. */
|
|
19
|
-
function isNotFound(
|
|
20
|
-
return
|
|
19
|
+
function isNotFound(error) {
|
|
20
|
+
return error.reason._tag === "NotFound";
|
|
21
21
|
}
|
|
22
22
|
/** Removes a file. A path that is already gone is not an error. */
|
|
23
23
|
function unlink(path) {
|
|
@@ -49,15 +49,14 @@ function readFile(path) {
|
|
|
49
49
|
* That skip is contract, not optimization: the Vite plugin watches its own output, so rewriting
|
|
50
50
|
* an unchanged file would feed a change event straight back into the generator.
|
|
51
51
|
*/
|
|
52
|
-
function writeFile(path,
|
|
52
|
+
function writeFile(path, content) {
|
|
53
53
|
return Effect.gen(function* () {
|
|
54
54
|
const fs = yield* FileSystem.FileSystem;
|
|
55
|
-
if ((yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => null))) ===
|
|
56
|
-
yield* fs.writeFileString(path,
|
|
55
|
+
if ((yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => null))) === content) return;
|
|
56
|
+
yield* fs.writeFileString(path, content);
|
|
57
57
|
});
|
|
58
58
|
}
|
|
59
|
-
|
|
60
|
-
//#region src/emit/index.ts
|
|
59
|
+
// src/emit/index.ts
|
|
61
60
|
/** Formats generated source and writes it to `output`, creating `dir` on the way. */
|
|
62
61
|
function emit(code, dir, output) {
|
|
63
62
|
return Effect.gen(function* () {
|
|
@@ -65,8 +64,7 @@ function emit(code, dir, output) {
|
|
|
65
64
|
yield* writeFile(output, formatted);
|
|
66
65
|
});
|
|
67
66
|
}
|
|
68
|
-
|
|
69
|
-
//#region src/core/client/index.ts
|
|
67
|
+
// src/core/client/index.ts
|
|
70
68
|
/**
|
|
71
69
|
* The base URL as code: an environment variable, read where it is used and asserted to be set —
|
|
72
70
|
* with `sameOrigin`, only without a window, so a browser bundle that has no such variable never
|
|
@@ -106,8 +104,7 @@ function client(output, options) {
|
|
|
106
104
|
return `Generated client written to ${output}`;
|
|
107
105
|
});
|
|
108
106
|
}
|
|
109
|
-
|
|
110
|
-
//#region src/guard/index.ts
|
|
107
|
+
// src/guard/index.ts
|
|
111
108
|
function isReference(v) {
|
|
112
109
|
return typeof v === "object" && v !== null && "$ref" in v && typeof v.$ref === "string" && !!v.$ref;
|
|
113
110
|
}
|
|
@@ -121,7 +118,7 @@ function isMediaWithSchema(v) {
|
|
|
121
118
|
return typeof v === "object" && v !== null && !Array.isArray(v) && "schema" in v;
|
|
122
119
|
}
|
|
123
120
|
function isSecurityArray(v) {
|
|
124
|
-
return Array.isArray(v) && v.every((
|
|
121
|
+
return Array.isArray(v) && v.every((item) => typeof item === "object" && item !== null);
|
|
125
122
|
}
|
|
126
123
|
function isSchemaArray(v) {
|
|
127
124
|
return Array.isArray(v);
|
|
@@ -129,8 +126,7 @@ function isSchemaArray(v) {
|
|
|
129
126
|
function isTypeArray(v) {
|
|
130
127
|
return Array.isArray(v);
|
|
131
128
|
}
|
|
132
|
-
|
|
133
|
-
//#region src/openapi/vendor-ext.ts
|
|
129
|
+
// src/openapi/vendor-ext.ts
|
|
134
130
|
const VENDOR_EXT_KEYS = [
|
|
135
131
|
"x-error-message",
|
|
136
132
|
"x-required-message",
|
|
@@ -173,8 +169,7 @@ const VENDOR_EXT_KEYS = [
|
|
|
173
169
|
"x-implication-message",
|
|
174
170
|
"x-brand"
|
|
175
171
|
];
|
|
176
|
-
|
|
177
|
-
//#region src/utils/index.ts
|
|
172
|
+
// src/utils/index.ts
|
|
178
173
|
function capitalize(s) {
|
|
179
174
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
180
175
|
}
|
|
@@ -193,10 +188,10 @@ function pascalCase(s) {
|
|
|
193
188
|
const result = parts.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
194
189
|
return /^[0-9]/u.test(result) ? `_${result}` : result;
|
|
195
190
|
}
|
|
196
|
-
function filterDefined(
|
|
197
|
-
return
|
|
191
|
+
function filterDefined(items) {
|
|
192
|
+
return items.filter((item) => item !== null && item !== void 0);
|
|
198
193
|
}
|
|
199
|
-
const JS_RESERVED = new Set([
|
|
194
|
+
const JS_RESERVED = /* @__PURE__ */ new Set([
|
|
200
195
|
"break",
|
|
201
196
|
"case",
|
|
202
197
|
"catch",
|
|
@@ -284,8 +279,7 @@ function methodPath(method, pathStr) {
|
|
|
284
279
|
const words = pathStr.replaceAll(/[^A-Za-z0-9]/gu, " ").trim().split(/\s+/u).filter((word) => word !== "").map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join("");
|
|
285
280
|
return words ? `${method}${words}${hasTrailingSlash ? "Index" : ""}` : `${method}Index`;
|
|
286
281
|
}
|
|
287
|
-
|
|
288
|
-
//#region src/helper/schema.ts
|
|
282
|
+
// src/helper/schema.ts
|
|
289
283
|
function pickVendorExtensions(source) {
|
|
290
284
|
if (!source) return {};
|
|
291
285
|
const picked = {};
|
|
@@ -301,6 +295,7 @@ function jsonSchema(content) {
|
|
|
301
295
|
const BODY_MEDIA_PRIORITY = [
|
|
302
296
|
"application/json",
|
|
303
297
|
"multipart/form-data",
|
|
298
|
+
"application/x-www-form-urlencoded",
|
|
304
299
|
"application/octet-stream"
|
|
305
300
|
];
|
|
306
301
|
function pickBodyMedia(content) {
|
|
@@ -313,19 +308,74 @@ function pickBodyMedia(content) {
|
|
|
313
308
|
};
|
|
314
309
|
}
|
|
315
310
|
}
|
|
311
|
+
/**
|
|
312
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
313
|
+
*
|
|
314
|
+
* @internal
|
|
315
|
+
*/
|
|
316
316
|
function refSchemaName(s) {
|
|
317
317
|
if (!s?.$ref) return null;
|
|
318
318
|
const m = /^#\/components\/schemas\/([^/]+)$/u.exec(s.$ref);
|
|
319
319
|
return m?.[1] ? decodeURIComponent(m[1]) : null;
|
|
320
320
|
}
|
|
321
|
-
|
|
321
|
+
/**
|
|
322
|
+
* The schema and media type of the request body, and how the body is read. A body that is a
|
|
323
|
+
* component is referenced by name — except a form body, whose fields arrive as text: the
|
|
324
|
+
* component is written for typed values, so the form takes a copy of its schema inlined and read
|
|
325
|
+
* from text, and the component stays as it is for the JSON bodies that share it.
|
|
326
|
+
*/
|
|
327
|
+
/** A component schema is an object, which its users read as a whole rather than from text. */
|
|
328
|
+
function isObjectLike(schema) {
|
|
329
|
+
return schema.type === "object" || schema.properties !== void 0 || schema.additionalProperties !== void 0;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* A schema that arrives as text, with every `$ref` to a component that is not an object replaced
|
|
333
|
+
* by a copy of the component: the component is written for a typed value, and the copy is read
|
|
334
|
+
* from text where it is used. Arrays, combinators and chains of references are followed; an object
|
|
335
|
+
* component stays a reference.
|
|
336
|
+
*
|
|
337
|
+
* @internal
|
|
338
|
+
*/
|
|
339
|
+
function inlineScalarRefs(schema, components, depth = 0) {
|
|
340
|
+
if (depth > 16) return schema;
|
|
341
|
+
const name = refSchemaName(schema);
|
|
342
|
+
const target = name ? components?.schemas?.[name] : void 0;
|
|
343
|
+
if (target && !isObjectLike(target)) {
|
|
344
|
+
const { $ref: _ref, ...site } = schema;
|
|
345
|
+
return inlineScalarRefs({
|
|
346
|
+
...target,
|
|
347
|
+
...site
|
|
348
|
+
}, components, depth + 1);
|
|
349
|
+
}
|
|
350
|
+
if (target) return schema;
|
|
351
|
+
const items = schema.items;
|
|
352
|
+
return {
|
|
353
|
+
...schema,
|
|
354
|
+
...items && !isSchemaArray(items) ? { items: inlineScalarRefs(items, components, depth + 1) } : {},
|
|
355
|
+
...schema.oneOf ? { oneOf: schema.oneOf.map((s) => inlineScalarRefs(s, components, depth + 1)) } : {},
|
|
356
|
+
...schema.anyOf ? { anyOf: schema.anyOf.map((s) => inlineScalarRefs(s, components, depth + 1)) } : {},
|
|
357
|
+
...schema.allOf ? { allOf: schema.allOf.map((s) => inlineScalarRefs(s, components, depth + 1)) } : {}
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
/** Each property of an object read from text, its scalar references inlined. */
|
|
361
|
+
function inlinePropertyRefs(schema, components) {
|
|
362
|
+
if (!components || !schema.properties) return schema;
|
|
363
|
+
return {
|
|
364
|
+
...schema,
|
|
365
|
+
properties: Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => [key, inlineScalarRefs(value, components)]))
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function bodyInfo(operation, components) {
|
|
322
369
|
const body = operation.requestBody;
|
|
323
370
|
if (!body || isReference(body)) return {};
|
|
324
371
|
const picked = pickBodyMedia(body.content);
|
|
325
372
|
if (!picked) return {};
|
|
326
|
-
const { mediaType
|
|
327
|
-
const ref = refSchemaName(schema);
|
|
328
|
-
|
|
373
|
+
const { mediaType } = picked;
|
|
374
|
+
const ref = refSchemaName(picked.schema);
|
|
375
|
+
const isForm = mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded";
|
|
376
|
+
const component = ref && isForm ? components?.schemas?.[ref] : void 0;
|
|
377
|
+
if (ref && !component) return { ref };
|
|
378
|
+
const schema = isForm ? inlinePropertyRefs(component ?? picked.schema, components) : picked.schema;
|
|
329
379
|
const media = body.content?.[mediaType];
|
|
330
380
|
const mediaExt = media && !isReference(media) ? pickVendorExtensions(media) : {};
|
|
331
381
|
const bodyExt = pickVendorExtensions(body);
|
|
@@ -339,53 +389,77 @@ function bodyInfo(operation) {
|
|
|
339
389
|
if (mediaType === "application/json") return { inline };
|
|
340
390
|
return {
|
|
341
391
|
inline,
|
|
342
|
-
|
|
392
|
+
context: { mediaType }
|
|
343
393
|
};
|
|
344
394
|
}
|
|
345
|
-
function responseInfo(
|
|
346
|
-
const schema = jsonSchema(
|
|
395
|
+
function responseInfo(response) {
|
|
396
|
+
const schema = jsonSchema(response.content);
|
|
347
397
|
if (!schema) return { void: true };
|
|
348
398
|
const ref = refSchemaName(schema);
|
|
349
399
|
return ref ? { ref } : { inline: schema };
|
|
350
400
|
}
|
|
351
|
-
function makeParamsSchema(params, where) {
|
|
401
|
+
function makeParamsSchema(params, where, components) {
|
|
352
402
|
const filtered = params.filter((p) => !isReference(p) && p.in === where);
|
|
353
403
|
if (filtered.length === 0) return void 0;
|
|
354
|
-
const withSchema = filtered.
|
|
355
|
-
if (
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
404
|
+
const withSchema = filtered.flatMap((p) => {
|
|
405
|
+
if (p.schema) return [{
|
|
406
|
+
p,
|
|
407
|
+
schema: inlineScalarRefs(p.schema, components),
|
|
408
|
+
json: false
|
|
409
|
+
}];
|
|
410
|
+
const content = contentSchema(p);
|
|
411
|
+
if (!content) return [];
|
|
412
|
+
const json = content.mediaType === "application/json";
|
|
413
|
+
return [{
|
|
414
|
+
p,
|
|
415
|
+
schema: json ? content.schema : inlineScalarRefs(content.schema, components),
|
|
416
|
+
json
|
|
417
|
+
}];
|
|
360
418
|
});
|
|
361
419
|
if (withSchema.length === 0) return void 0;
|
|
362
|
-
const
|
|
363
|
-
const
|
|
420
|
+
const keyOf = (p) => where === "header" ? p.name.toLowerCase() : p.name;
|
|
421
|
+
const properties = Object.fromEntries(withSchema.map(({ p, schema }) => [keyOf(p), schema]));
|
|
422
|
+
const required = withSchema.filter(({ p }) => p.required).map(({ p }) => keyOf(p));
|
|
423
|
+
const jsonProperties = withSchema.filter(({ json }) => json).map(({ p }) => keyOf(p));
|
|
424
|
+
const delimitedProperties = Object.fromEntries(withSchema.flatMap(({ p, schema }) => {
|
|
425
|
+
if (!(schema.type === "array" || schema.items !== void 0) || p.style !== "pipeDelimited" && p.style !== "spaceDelimited") return [];
|
|
426
|
+
return [[keyOf(p), p.style === "pipeDelimited" ? "|" : " "]];
|
|
427
|
+
}));
|
|
364
428
|
const hoisted = {};
|
|
365
|
-
for (const p of withSchema) {
|
|
429
|
+
for (const { p, schema: paramSchema } of withSchema) {
|
|
366
430
|
const fromParam = pickVendorExtensions(p);
|
|
367
|
-
const fromSchema = pickVendorExtensions(
|
|
431
|
+
const fromSchema = pickVendorExtensions(paramSchema);
|
|
368
432
|
for (const key of VENDOR_EXT_KEYS) {
|
|
369
433
|
if (hoisted[key] !== void 0) continue;
|
|
370
434
|
const value = fromParam[key] ?? fromSchema[key];
|
|
371
435
|
if (value !== void 0) hoisted[key] = value;
|
|
372
436
|
}
|
|
373
437
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
438
|
+
return {
|
|
439
|
+
schema: {
|
|
440
|
+
type: "object",
|
|
441
|
+
properties,
|
|
442
|
+
...required.length > 0 ? { required } : {},
|
|
443
|
+
...hoisted
|
|
444
|
+
},
|
|
445
|
+
context: {
|
|
446
|
+
parameterLocation: where,
|
|
447
|
+
...where === "cookie" ? { elysiaKind: "cookie" } : {},
|
|
448
|
+
...jsonProperties.length > 0 ? { jsonProperties } : {},
|
|
449
|
+
...Object.keys(delimitedProperties).length > 0 ? { delimitedProperties } : {}
|
|
450
|
+
}
|
|
383
451
|
};
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
452
|
+
}
|
|
453
|
+
/** The one document a parameter declares under `content`, with its media type. */
|
|
454
|
+
function contentSchema(p) {
|
|
455
|
+
for (const [mediaType, media] of Object.entries(p.content ?? {})) if (isMediaWithSchema(media)) return {
|
|
456
|
+
mediaType,
|
|
457
|
+
schema: media.schema
|
|
387
458
|
};
|
|
388
|
-
|
|
459
|
+
}
|
|
460
|
+
/** The schema a parameter declares, directly or as the one document under `content`. */
|
|
461
|
+
function parameterSchema(p) {
|
|
462
|
+
return p.schema ?? contentSchema(p)?.schema;
|
|
389
463
|
}
|
|
390
464
|
function collectSchemaRefs$1(schema, acc = /* @__PURE__ */ new Set()) {
|
|
391
465
|
if (schema.properties) for (const v of Object.values(schema.properties)) collectSchemaRefs$1(v, acc);
|
|
@@ -395,7 +469,7 @@ function collectSchemaRefs$1(schema, acc = /* @__PURE__ */ new Set()) {
|
|
|
395
469
|
else collectSchemaRefs$1(items, acc);
|
|
396
470
|
}
|
|
397
471
|
if (schema.prefixItems) for (const i of schema.prefixItems) collectSchemaRefs$1(i, acc);
|
|
398
|
-
if (
|
|
472
|
+
if (typeof schema.additionalProperties === "object") collectSchemaRefs$1(schema.additionalProperties, acc);
|
|
399
473
|
if (schema.$ref) {
|
|
400
474
|
const m = /^#\/components\/schemas\/([^/]+)$/u.exec(schema.$ref);
|
|
401
475
|
if (m?.[1]) acc.add(decodeURIComponent(m[1]));
|
|
@@ -410,6 +484,11 @@ function collectSchemaRefs$1(schema, acc = /* @__PURE__ */ new Set()) {
|
|
|
410
484
|
if (schema.contains) collectSchemaRefs$1(schema.contains, acc);
|
|
411
485
|
return acc;
|
|
412
486
|
}
|
|
487
|
+
/**
|
|
488
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
489
|
+
*
|
|
490
|
+
* @internal
|
|
491
|
+
*/
|
|
413
492
|
function topoSortSchemas(schemas) {
|
|
414
493
|
const byName = new Map(schemas.map((s) => [s.name, s]));
|
|
415
494
|
const visited = /* @__PURE__ */ new Set();
|
|
@@ -446,19 +525,16 @@ function sccSchemas(schemas) {
|
|
|
446
525
|
counter.value += 1;
|
|
447
526
|
stack.push(v);
|
|
448
527
|
onStack.add(v);
|
|
449
|
-
for (const
|
|
450
|
-
strongconnect(
|
|
451
|
-
lowlink.set(v, Math.min(lowlink.get(v) ?? 0, lowlink.get(
|
|
452
|
-
} else if (onStack.has(
|
|
528
|
+
for (const next of refsOf(v)) if (!index.has(next)) {
|
|
529
|
+
strongconnect(next);
|
|
530
|
+
lowlink.set(v, Math.min(lowlink.get(v) ?? 0, lowlink.get(next) ?? 0));
|
|
531
|
+
} else if (onStack.has(next)) lowlink.set(v, Math.min(lowlink.get(v) ?? 0, index.get(next) ?? 0));
|
|
453
532
|
if ((lowlink.get(v) ?? 0) === (index.get(v) ?? 0)) {
|
|
454
533
|
const group = [];
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
onStack.delete(w);
|
|
459
|
-
const def = byName.get(w);
|
|
534
|
+
for (let member = stack.pop(); member !== void 0; member = member === v ? void 0 : stack.pop()) {
|
|
535
|
+
onStack.delete(member);
|
|
536
|
+
const def = byName.get(member);
|
|
460
537
|
if (def) group.push(def);
|
|
461
|
-
if (w === v) break;
|
|
462
538
|
}
|
|
463
539
|
groups.push(group);
|
|
464
540
|
}
|
|
@@ -487,6 +563,48 @@ function refIdent(ref) {
|
|
|
487
563
|
if (!suffix) return void 0;
|
|
488
564
|
return `${pascalCase(decodeURIComponent(m[2]))}${suffix}`;
|
|
489
565
|
}
|
|
566
|
+
/** `refIdent`, or nothing for a `$ref` whose name is not valid percent-encoding. */
|
|
567
|
+
function decodedRefIdent(ref) {
|
|
568
|
+
try {
|
|
569
|
+
return refIdent(ref);
|
|
570
|
+
} catch {
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function stringifiedRefEntries(value) {
|
|
575
|
+
if (Array.isArray(value)) return value.flatMap(stringifiedRefEntries);
|
|
576
|
+
if (typeof value !== "object" || value === null) return [];
|
|
577
|
+
if (isReference(value) && value.$ref) {
|
|
578
|
+
const kind = REF_PATTERN.exec(value.$ref)?.[1];
|
|
579
|
+
const ident = decodedRefIdent(value.$ref);
|
|
580
|
+
if (kind && ident) return [[ident, kind]];
|
|
581
|
+
}
|
|
582
|
+
return Object.values(value).flatMap(stringifiedRefEntries);
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* The identifier `stringifyRefs(value)` renders each `$ref` as, keyed to the kind of component the
|
|
586
|
+
* `$ref` names. The identifier's suffix cannot tell: `#/components/schemas/ErrorResponse` renders
|
|
587
|
+
* as `ErrorResponseSchema`, as `#/components/responses/Error` does.
|
|
588
|
+
*/
|
|
589
|
+
function stringifiedRefKinds(value) {
|
|
590
|
+
return new Map(stringifiedRefEntries(value));
|
|
591
|
+
}
|
|
592
|
+
function schemaRefNames(schema) {
|
|
593
|
+
if (schema === void 0) return [];
|
|
594
|
+
try {
|
|
595
|
+
return [...collectSchemaRefs$1(schema)];
|
|
596
|
+
} catch {
|
|
597
|
+
return [];
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* The identifier `typebox` renders each `$ref` in `schemas` as, keyed to `schemas`: the only kind a
|
|
602
|
+
* schema refers to. A schema whose `$ref`s cannot be decoded contributes nothing, and its
|
|
603
|
+
* identifiers are classified by their suffix.
|
|
604
|
+
*/
|
|
605
|
+
function schemaRefKinds(schemas) {
|
|
606
|
+
return new Map(schemas.flatMap(schemaRefNames).map((name) => [`${pascalCase(name)}Schema`, "schemas"]));
|
|
607
|
+
}
|
|
490
608
|
function stringifyRefs(value) {
|
|
491
609
|
if (value === null) return "null";
|
|
492
610
|
if (value === void 0) return "undefined";
|
|
@@ -507,9 +625,9 @@ function moduleInlineSchemas(inline) {
|
|
|
507
625
|
}
|
|
508
626
|
function moduleComponentRefs(routes, inline, componentNames, componentSchemas = {}) {
|
|
509
627
|
const direct = /* @__PURE__ */ new Set();
|
|
510
|
-
for (const
|
|
511
|
-
if (
|
|
512
|
-
for (const
|
|
628
|
+
for (const route of routes) {
|
|
629
|
+
if (route.bodyRef && componentNames.has(route.bodyRef)) direct.add(route.bodyRef);
|
|
630
|
+
for (const response of route.responses) if (response.schema.kind === "ref" && componentNames.has(response.schema.name)) direct.add(response.schema.name);
|
|
513
631
|
}
|
|
514
632
|
for (const { schema } of inline) for (const n of collectSchemaRefs$1(schema)) if (componentNames.has(n)) direct.add(n);
|
|
515
633
|
const closure = new Set(direct);
|
|
@@ -526,8 +644,7 @@ function moduleComponentRefs(routes, inline, componentNames, componentSchemas =
|
|
|
526
644
|
}
|
|
527
645
|
return closure;
|
|
528
646
|
}
|
|
529
|
-
|
|
530
|
-
//#region src/helper/typebox.ts
|
|
647
|
+
// src/helper/typebox.ts
|
|
531
648
|
const RAW = Symbol.for("asphodelos.options.raw");
|
|
532
649
|
function raw(expr) {
|
|
533
650
|
return {
|
|
@@ -727,8 +844,8 @@ function errorCallback(schema, kind) {
|
|
|
727
844
|
message: b.message,
|
|
728
845
|
types: [b.type]
|
|
729
846
|
}];
|
|
730
|
-
}, []).map((
|
|
731
|
-
return `if(${[...
|
|
847
|
+
}, []).map((group) => {
|
|
848
|
+
return `if(${[...group.types].toSorted((a, b) => a - b).map((tag) => `type===${tag}`).join("||")})return ${JSON.stringify(group.message)}`;
|
|
732
849
|
}).join(";")};return ${fallbackExpr}}`)];
|
|
733
850
|
}
|
|
734
851
|
function enumErrorCallback(schema) {
|
|
@@ -779,11 +896,11 @@ function dependentRequiredSection(schema) {
|
|
|
779
896
|
const message = schema["x-dependentRequired-message"];
|
|
780
897
|
const map = schema.dependentRequired;
|
|
781
898
|
if (message === void 0 || !map || Object.keys(map).length === 0) return null;
|
|
782
|
-
const emptyEntries = Object.entries(map).filter(([, requiredKeys]) =>
|
|
783
|
-
if (emptyEntries.length > 0) console.warn(`[asphodelos] x-dependentRequired-message: dependentRequired entries with empty arrays are silently skipped — ${emptyEntries.map((
|
|
899
|
+
const emptyEntries = Object.entries(map).filter(([, requiredKeys]) => requiredKeys.length === 0).map(([trigger]) => trigger);
|
|
900
|
+
if (emptyEntries.length > 0) console.warn(`[asphodelos] x-dependentRequired-message: dependentRequired entries with empty arrays are silently skipped — ${emptyEntries.map((trigger) => `\`${trigger}\``).join(", ")} produce no runtime check. Add at least one required key or remove the entry.`);
|
|
784
901
|
const check = Object.entries(map).map(([trigger, requiredKeys]) => {
|
|
785
902
|
const triggerJson = JSON.stringify(trigger);
|
|
786
|
-
const missing =
|
|
903
|
+
const missing = requiredKeys.map((k) => `!(${JSON.stringify(k)} in v)`).join("||");
|
|
787
904
|
return missing ? `if(${triggerJson} in v&&(${missing}))throw new Error(${JSON.stringify(message)})` : null;
|
|
788
905
|
}).filter((s) => s !== null).join(";");
|
|
789
906
|
return check ? {
|
|
@@ -797,10 +914,10 @@ function dependentSchemasSection(schema, renderSubSchema) {
|
|
|
797
914
|
if (message === void 0 || !map || Object.keys(map).length === 0) return null;
|
|
798
915
|
if (renderSubSchema) {
|
|
799
916
|
for (const [trigger, sub] of Object.entries(map)) {
|
|
800
|
-
if (sub
|
|
917
|
+
if (sub.additionalProperties === false) {
|
|
801
918
|
if (!Object.keys(sub.properties ?? {}).includes(trigger)) console.warn(`[asphodelos] x-dependentSchemas-message: sub-schema for \`${trigger}\` has \`additionalProperties: false\` but does not list \`${trigger}\` in its properties. Per JSON Schema spec the dependent schema applies to the whole instance, so the trigger key itself is rejected as unexpected — every payload (including conforming ones) will fail. Add \`${trigger}\` to the sub-schema's properties, drop \`additionalProperties: false\`, or restructure the dependency.`);
|
|
802
919
|
}
|
|
803
|
-
const subType = sub
|
|
920
|
+
const subType = sub.type;
|
|
804
921
|
if (subType !== void 0 && subType !== "object") console.warn(`[asphodelos] x-dependentSchemas-message: sub-schema for \`${trigger}\` has \`type: ${typeof subType === "string" ? subType : JSON.stringify(subType)}\` — non-object sub-schemas can't match the parent object at runtime so every payload will fail. dependentSchemas applies to the whole instance; the sub-schema must be \`type: 'object'\` (or omit \`type\`).`);
|
|
805
922
|
}
|
|
806
923
|
const subsLit = Object.entries(map).map(([trigger, sub]) => `${JSON.stringify(trigger)}:${renderSubSchema(sub)}`).join(",");
|
|
@@ -813,7 +930,7 @@ function dependentSchemasSection(schema, renderSubSchema) {
|
|
|
813
930
|
console.warn("[asphodelos] x-dependentSchemas-message: deep enforcement requires a renderSubSchema callback. Falling back to shallow `required[]`-only check; nested constraints in dependent sub-schemas (pattern, enum, …) will not be enforced at runtime.");
|
|
814
931
|
const check = Object.entries(map).map(([trigger, sub]) => {
|
|
815
932
|
const triggerJson = JSON.stringify(trigger);
|
|
816
|
-
const missing = (Array.isArray(sub
|
|
933
|
+
const missing = (Array.isArray(sub.required) ? sub.required : []).map((k) => `!(${JSON.stringify(k)} in v)`).join("||");
|
|
817
934
|
return missing ? `if(${triggerJson} in v&&(${missing}))throw new Error(${JSON.stringify(message)})` : null;
|
|
818
935
|
}).filter((s) => s !== null).join(";");
|
|
819
936
|
return check ? {
|
|
@@ -846,8 +963,17 @@ function stringTransformWrap(expr, schema) {
|
|
|
846
963
|
if (steps.length === 0) return expr;
|
|
847
964
|
return `t.Transform(${expr}).Decode((v)=>{${steps.map((s) => `v=${s}`).join(";")};return v}).Encode((v)=>v)`;
|
|
848
965
|
}
|
|
849
|
-
|
|
850
|
-
|
|
966
|
+
/**
|
|
967
|
+
* Adds `null` to a nullable schema. Where the value arrives as text and is not a string, the word
|
|
968
|
+
* `null` is read as the value: a query, a header or a form field has no other way to spell it. A
|
|
969
|
+
* nullable string keeps the word as text, which is what it is there.
|
|
970
|
+
*/
|
|
971
|
+
function wrap(expr, schema, context = {}) {
|
|
972
|
+
if (!(schema.nullable === true || Array.isArray(schema.type) && schema.type.includes("null"))) return expr;
|
|
973
|
+
const union = `t.Union([${expr},t.Null()])`;
|
|
974
|
+
const primary = Array.isArray(schema.type) ? schema.type.find((kind) => kind !== "null") : schema.type;
|
|
975
|
+
if (!(context.text === true && (primary === "integer" || primary === "number" || primary === "boolean"))) return union;
|
|
976
|
+
return `t.Transform(t.Union([t.Literal("null"),${union}])).Decode((v)=>(v==="null"?null:v)).Encode((v)=>v)`;
|
|
851
977
|
}
|
|
852
978
|
function readonly(expr, enabled) {
|
|
853
979
|
return enabled ? `t.Readonly(${expr})` : expr;
|
|
@@ -861,22 +987,43 @@ function brand(expr, schema) {
|
|
|
861
987
|
number: "number",
|
|
862
988
|
boolean: "boolean"
|
|
863
989
|
};
|
|
864
|
-
const primary = typeof schema.type === "string" ? schema.type : Array.isArray(schema.type) ? schema.type.find((
|
|
990
|
+
const primary = typeof schema.type === "string" ? schema.type : Array.isArray(schema.type) ? schema.type.find((kind) => kind !== "null") : void 0;
|
|
865
991
|
const base = primary ? TS_BASE_TYPE[primary] : void 0;
|
|
866
992
|
if (!base) return expr;
|
|
867
993
|
return `t.Unsafe<${base} & { readonly __brand: '${name}' }>(${expr})`;
|
|
868
994
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
return items.format === "binary" && ctx.mediaType === "multipart/form-data";
|
|
995
|
+
// src/generator/typebox/t/array.ts
|
|
996
|
+
function isMultipartBinaryArray(items, context) {
|
|
997
|
+
return items.format === "binary" && context.mediaType === "multipart/form-data";
|
|
873
998
|
}
|
|
874
|
-
|
|
875
|
-
|
|
999
|
+
/**
|
|
1000
|
+
* How an array is read where it arrives as text. A parameter declared with `content` is one JSON
|
|
1001
|
+
* document. A form field repeats its name for each element and is a bare value when sent once,
|
|
1002
|
+
* which `t.Array` would refuse, and a header or a cookie holds one value, comma-separated;
|
|
1003
|
+
* `t.ArrayQuery` reads all of those the way Elysia reads a query array. A query array is read by
|
|
1004
|
+
* Elysia itself, and a JSON body carries the array.
|
|
1005
|
+
*/
|
|
1006
|
+
/**
|
|
1007
|
+
* A `pipeDelimited` or `spaceDelimited` array: one value whose elements are joined with the
|
|
1008
|
+
* separator, which Elysia does not split. The text — or each repetition of it, for a client that
|
|
1009
|
+
* repeats the name — is split, and the elements decoded against the array schema, read from text.
|
|
1010
|
+
*/
|
|
1011
|
+
function delimited(arrayExpr, separator) {
|
|
1012
|
+
const sep = JSON.stringify(separator);
|
|
1013
|
+
return `t.Transform(t.Union([t.String(),t.Array(t.String())])).Decode((v)=>Value.Decode(${arrayExpr},(Array.isArray(v)?v:[v]).flatMap((s)=>s.split(${sep})))).Encode((v)=>v.join(${sep}))`;
|
|
1014
|
+
}
|
|
1015
|
+
function arrayFactory(context) {
|
|
1016
|
+
if (context.elysiaKind === "json-string") return "t.ArrayString";
|
|
1017
|
+
if (readsTextItself(context)) return "t.ArrayQuery";
|
|
1018
|
+
if (context.parameterLocation === "header" || context.parameterLocation === "cookie") return "t.ArrayQuery";
|
|
1019
|
+
return "t.Array";
|
|
1020
|
+
}
|
|
1021
|
+
function array(schema, context = {}) {
|
|
1022
|
+
const childCtx = context.mediaType ? { mediaType: context.mediaType } : {};
|
|
876
1023
|
if (schema.prefixItems) return `t.Tuple([${schema.prefixItems.map((s) => typebox(s, childCtx)).join(",")}])`;
|
|
877
1024
|
const items = schema.items;
|
|
878
1025
|
if (items && isSchemaArray(items)) return `t.Tuple([${items.map((s) => typebox(s, childCtx)).join(",")}])`;
|
|
879
|
-
if (items && !isSchemaArray(items) && isMultipartBinaryArray(items,
|
|
1026
|
+
if (items && !isSchemaArray(items) && isMultipartBinaryArray(items, context)) {
|
|
880
1027
|
const filesOpts = options([
|
|
881
1028
|
["type", items.contentMediaType],
|
|
882
1029
|
["minItems", schema.minItems],
|
|
@@ -888,7 +1035,11 @@ function array(schema, ctx = {}) {
|
|
|
888
1035
|
]);
|
|
889
1036
|
return filesOpts ? `t.Files(${filesOpts})` : "t.Files()";
|
|
890
1037
|
}
|
|
891
|
-
const
|
|
1038
|
+
const itemCtx = context.delimiter ? {
|
|
1039
|
+
text: true,
|
|
1040
|
+
readsText: true
|
|
1041
|
+
} : childCtx;
|
|
1042
|
+
const itemExpr = items ? typebox(items, itemCtx) : "t.Unknown()";
|
|
892
1043
|
const containsExpr = schema.contains ? raw(typebox(schema.contains, childCtx)) : void 0;
|
|
893
1044
|
const opts = options([
|
|
894
1045
|
["minItems", schema.minItems],
|
|
@@ -900,20 +1051,20 @@ function array(schema, ctx = {}) {
|
|
|
900
1051
|
...filterDefined([errorCallback(schema, "array")]),
|
|
901
1052
|
...commonOpts(schema)
|
|
902
1053
|
]);
|
|
903
|
-
return opts ? `t.Array(${itemExpr},${opts})` : `t.Array(${itemExpr})
|
|
1054
|
+
if (context.delimiter) return delimited(opts ? `t.Array(${itemExpr},${opts})` : `t.Array(${itemExpr})`, context.delimiter);
|
|
1055
|
+
const factory = arrayFactory(context);
|
|
1056
|
+
return opts ? `${factory}(${itemExpr},${opts})` : `${factory}(${itemExpr})`;
|
|
904
1057
|
}
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
function boolean(schema) {
|
|
1058
|
+
// src/generator/typebox/t/boolean.ts
|
|
1059
|
+
function boolean(schema, context = {}) {
|
|
908
1060
|
const opts = options([
|
|
909
1061
|
["format", schema.format],
|
|
910
1062
|
...filterDefined([errorCallback(schema, "boolean")]),
|
|
911
1063
|
...commonOpts(schema)
|
|
912
1064
|
]);
|
|
913
|
-
return `${schema.format === "boolean-string" ? "t.BooleanString" : "t.Boolean"}(${opts})`;
|
|
1065
|
+
return `${schema.format === "boolean-string" || readsTextItself(context) ? "t.BooleanString" : "t.Boolean"}(${opts})`;
|
|
914
1066
|
}
|
|
915
|
-
|
|
916
|
-
//#region src/generator/typebox/t/enum.ts
|
|
1067
|
+
// src/generator/typebox/t/enum.ts
|
|
917
1068
|
function isUnionEnumValue(v) {
|
|
918
1069
|
return typeof v === "string" || typeof v === "number";
|
|
919
1070
|
}
|
|
@@ -940,8 +1091,7 @@ function _enum(schema) {
|
|
|
940
1091
|
])})`;
|
|
941
1092
|
return opts ? `t.Union([${values.map(literalSchema).join(",")}],${opts})` : `t.Union([${values.map(literalSchema).join(",")}])`;
|
|
942
1093
|
}
|
|
943
|
-
|
|
944
|
-
//#region src/generator/typebox/t/integer.ts
|
|
1094
|
+
// src/generator/typebox/t/integer.ts
|
|
945
1095
|
function autoMaximum(format, maximum, exclusiveMaximum) {
|
|
946
1096
|
if (maximum !== void 0) return maximum;
|
|
947
1097
|
if (exclusiveMaximum !== void 0) return void 0;
|
|
@@ -967,8 +1117,7 @@ function integer(schema) {
|
|
|
967
1117
|
]);
|
|
968
1118
|
return `${schema.format === "numeric" ? "t.Numeric" : "t.Integer"}(${opts})`;
|
|
969
1119
|
}
|
|
970
|
-
|
|
971
|
-
//#region src/generator/typebox/t/intersect.ts
|
|
1120
|
+
// src/generator/typebox/t/intersect.ts
|
|
972
1121
|
/**
|
|
973
1122
|
* Whether an `allOf` member is a bare scalar or a bag of constraints, with nothing of its own to
|
|
974
1123
|
* intersect: no reference, no properties, no items and no composition.
|
|
@@ -988,21 +1137,18 @@ function intersect(schemas, parent) {
|
|
|
988
1137
|
const opts = parent ? options([...filterDefined([errorCallback(parent, "composition")]), ...commonOpts(parent)]) : "";
|
|
989
1138
|
return opts ? `t.Intersect([${schemas.map((s) => typebox(s)).join(",")}],${opts})` : `t.Intersect([${schemas.map((s) => typebox(s)).join(",")}])`;
|
|
990
1139
|
}
|
|
991
|
-
|
|
992
|
-
//#region src/generator/typebox/t/not.ts
|
|
1140
|
+
// src/generator/typebox/t/not.ts
|
|
993
1141
|
function notType(inner, parent) {
|
|
994
1142
|
const innerExpr = typebox(inner);
|
|
995
1143
|
const opts = options([...filterDefined([errorCallback(parent, "composition")]), ...commonOpts(parent)]);
|
|
996
1144
|
return opts ? `t.Not(${innerExpr},${opts})` : `t.Not(${innerExpr})`;
|
|
997
1145
|
}
|
|
998
|
-
|
|
999
|
-
//#region src/generator/typebox/t/null.ts
|
|
1146
|
+
// src/generator/typebox/t/null.ts
|
|
1000
1147
|
function nullType() {
|
|
1001
1148
|
return "t.Null()";
|
|
1002
1149
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
function number(schema) {
|
|
1150
|
+
// src/generator/typebox/t/number.ts
|
|
1151
|
+
function number(schema, context = {}) {
|
|
1006
1152
|
const bounds = normalizeBounds(schema);
|
|
1007
1153
|
const opts = options([
|
|
1008
1154
|
["format", schema.format],
|
|
@@ -1014,36 +1160,57 @@ function number(schema) {
|
|
|
1014
1160
|
...filterDefined([errorCallback(schema, "number")]),
|
|
1015
1161
|
...commonOpts(schema)
|
|
1016
1162
|
]);
|
|
1017
|
-
return `${schema.format === "numeric" ? "t.Numeric" : "t.Number"}(${opts})`;
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
if (
|
|
1023
|
-
if (
|
|
1024
|
-
if (ctx.mediaType === "multipart/form-data") return "Form";
|
|
1163
|
+
return `${schema.format === "numeric" || readsTextItself(context) ? "t.Numeric" : "t.Number"}(${opts})`;
|
|
1164
|
+
}
|
|
1165
|
+
// src/generator/typebox/t/object.ts
|
|
1166
|
+
function pickObjectFactory(context) {
|
|
1167
|
+
if (context.elysiaKind === "object-string" || context.elysiaKind === "json-string") return "ObjectString";
|
|
1168
|
+
if (context.elysiaKind === "cookie") return "Cookie";
|
|
1169
|
+
if (context.mediaType === "multipart/form-data") return "Form";
|
|
1025
1170
|
return "Object";
|
|
1026
1171
|
}
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1172
|
+
/**
|
|
1173
|
+
* The context of a property. The properties of a parameter container and of a form body arrive as
|
|
1174
|
+
* text, so each is marked `text` and keeps the location it is read from; an object nested in one
|
|
1175
|
+
* of those is a single JSON document, whose own properties carry their types and are left alone.
|
|
1176
|
+
*/
|
|
1177
|
+
function childCtxFor(parentCtx, propSchema, key) {
|
|
1178
|
+
const media = parentCtx.mediaType ? { mediaType: parentCtx.mediaType } : {};
|
|
1179
|
+
if (parentCtx.text === true) return media;
|
|
1180
|
+
const location = parentCtx.parameterLocation;
|
|
1181
|
+
if (location === void 0 && !isFormMedia(parentCtx)) return media;
|
|
1182
|
+
const text = {
|
|
1183
|
+
...media,
|
|
1184
|
+
text: true,
|
|
1185
|
+
...location === void 0 ? {} : { parameterLocation: location }
|
|
1186
|
+
};
|
|
1187
|
+
if (key !== void 0 && parentCtx.jsonProperties?.includes(key)) return {
|
|
1188
|
+
...text,
|
|
1189
|
+
elysiaKind: "json-string"
|
|
1190
|
+
};
|
|
1191
|
+
const delimiter = key === void 0 ? void 0 : parentCtx.delimitedProperties?.[key];
|
|
1192
|
+
if (delimiter !== void 0) return {
|
|
1193
|
+
...text,
|
|
1194
|
+
delimiter
|
|
1195
|
+
};
|
|
1196
|
+
if (location === "query" && propSchema.type === "object") return {
|
|
1197
|
+
...text,
|
|
1031
1198
|
elysiaKind: "object-string"
|
|
1032
1199
|
};
|
|
1033
|
-
return
|
|
1200
|
+
return text;
|
|
1034
1201
|
}
|
|
1035
|
-
function object(schema,
|
|
1202
|
+
function object(schema, context = {}) {
|
|
1036
1203
|
const properties = schema.properties ?? {};
|
|
1037
1204
|
const required = new Set(schema.required);
|
|
1038
1205
|
const propEntries = Object.entries(properties).map(([key, propSchema]) => {
|
|
1039
|
-
const inner = typebox(propSchema, childCtxFor(
|
|
1206
|
+
const inner = typebox(propSchema, childCtxFor(context, propSchema, key));
|
|
1040
1207
|
const isRequired = required.has(key);
|
|
1041
1208
|
const wrapped = propSchema.readOnly === true ? isRequired ? `t.Readonly(${inner})` : `t.ReadonlyOptional(${inner})` : isRequired ? inner : `t.Optional(${inner})`;
|
|
1042
1209
|
return `${JSON.stringify(key)}:${wrapped}`;
|
|
1043
1210
|
});
|
|
1044
1211
|
const additional = schema.additionalProperties;
|
|
1045
|
-
if (Object.keys(properties).length === 0 &&
|
|
1046
|
-
const additionalCtx = childCtxFor(
|
|
1212
|
+
if (Object.keys(properties).length === 0 && typeof additional === "object") {
|
|
1213
|
+
const additionalCtx = childCtxFor(context, additional);
|
|
1047
1214
|
const valueExpr = typebox(additional, additionalCtx);
|
|
1048
1215
|
const opts = options([
|
|
1049
1216
|
["minProperties", schema.minProperties],
|
|
@@ -1053,29 +1220,28 @@ function object(schema, ctx = {}) {
|
|
|
1053
1220
|
]);
|
|
1054
1221
|
return transformWrap(opts ? `t.Record(t.String(),${valueExpr},${opts})` : `t.Record(t.String(),${valueExpr})`, schema, (s) => typebox(s, additionalCtx));
|
|
1055
1222
|
}
|
|
1223
|
+
const additionalOption = additional === false ? false : typeof additional === "object" ? raw(typebox(additional, childCtxFor(context, additional))) : void 0;
|
|
1056
1224
|
const opts = options([
|
|
1057
1225
|
["minProperties", schema.minProperties],
|
|
1058
1226
|
["maxProperties", schema.maxProperties],
|
|
1059
|
-
["additionalProperties",
|
|
1227
|
+
["additionalProperties", additionalOption],
|
|
1060
1228
|
...filterDefined([errorCallback(schema, "object")]),
|
|
1061
1229
|
...commonOpts(schema)
|
|
1062
1230
|
]);
|
|
1063
1231
|
const body = `{${propEntries.join(",")}}`;
|
|
1064
|
-
const factory = pickObjectFactory(
|
|
1232
|
+
const factory = pickObjectFactory(context);
|
|
1065
1233
|
const objectExpr = opts ? `t.${factory}(${body},${opts})` : `t.${factory}(${body})`;
|
|
1066
|
-
const subCtx =
|
|
1234
|
+
const subCtx = context.mediaType ? { mediaType: context.mediaType } : {};
|
|
1067
1235
|
return transformWrap(objectExpr, schema, (s) => typebox(s, subCtx));
|
|
1068
1236
|
}
|
|
1069
|
-
|
|
1070
|
-
//#region src/generator/typebox/t/ref.ts
|
|
1237
|
+
// src/generator/typebox/t/ref.ts
|
|
1071
1238
|
function ref(schema) {
|
|
1072
1239
|
if (!schema.$ref) return "t.Unknown()";
|
|
1073
1240
|
const m = /^#\/components\/schemas\/([^/]+)$/u.exec(schema.$ref);
|
|
1074
1241
|
if (m?.[1]) return `${pascalCase(decodeURIComponent(m[1]))}Schema`;
|
|
1075
1242
|
return "t.Unknown()";
|
|
1076
1243
|
}
|
|
1077
|
-
|
|
1078
|
-
//#region src/generator/typebox/t/string.ts
|
|
1244
|
+
// src/generator/typebox/t/string.ts
|
|
1079
1245
|
/**
|
|
1080
1246
|
* The string formats Elysia registers with TypeBox (`elysia/type-system/format`).
|
|
1081
1247
|
*
|
|
@@ -1084,7 +1250,7 @@ function ref(schema) {
|
|
|
1084
1250
|
* OpenAPI's hint to hide the text in a UI and says nothing about the value, so it is dropped in
|
|
1085
1251
|
* silence; any other unknown format is reported, since the document meant something by it.
|
|
1086
1252
|
*/
|
|
1087
|
-
const ELYSIA_STRING_FORMATS = new Set([
|
|
1253
|
+
const ELYSIA_STRING_FORMATS = /* @__PURE__ */ new Set([
|
|
1088
1254
|
"date",
|
|
1089
1255
|
"time",
|
|
1090
1256
|
"date-time",
|
|
@@ -1106,14 +1272,78 @@ const ELYSIA_STRING_FORMATS = new Set([
|
|
|
1106
1272
|
"relative-json-pointer",
|
|
1107
1273
|
"byte"
|
|
1108
1274
|
]);
|
|
1275
|
+
const UUID_HEX = "[0-9a-fA-F]";
|
|
1276
|
+
function uuidOfVersion(version) {
|
|
1277
|
+
return `^${UUID_HEX}{8}-${UUID_HEX}{4}-${version}${UUID_HEX}{3}-[89abAB]${UUID_HEX}{3}-${UUID_HEX}{12}$`;
|
|
1278
|
+
}
|
|
1279
|
+
const OCTET = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])";
|
|
1280
|
+
const H16 = "[0-9a-fA-F]{1,4}";
|
|
1281
|
+
/** Every spelling of an IPv6 address, `::` compression included (RFC 4291 §2.2). */
|
|
1282
|
+
const IPV6 = `(?:${[
|
|
1283
|
+
`(?:${H16}:){7}${H16}`,
|
|
1284
|
+
`(?:${H16}:){1,7}:`,
|
|
1285
|
+
`(?:${H16}:){1,6}:${H16}`,
|
|
1286
|
+
`(?:${H16}:){1,5}(?::${H16}){1,2}`,
|
|
1287
|
+
`(?:${H16}:){1,4}(?::${H16}){1,3}`,
|
|
1288
|
+
`(?:${H16}:){1,3}(?::${H16}){1,4}`,
|
|
1289
|
+
`(?:${H16}:){1,2}(?::${H16}){1,5}`,
|
|
1290
|
+
`${H16}:(?::${H16}){1,6}`,
|
|
1291
|
+
`:(?:(?::${H16}){1,7}|:)`
|
|
1292
|
+
].join("|")})`;
|
|
1293
|
+
/**
|
|
1294
|
+
* The string formats Elysia does not register but a regular expression decides, as the same
|
|
1295
|
+
* patterns Zod checks them with (hono-takibi generates those). They are emitted as `pattern`, so
|
|
1296
|
+
* the value is validated rather than passed through. A format that needs a checksum or a list —
|
|
1297
|
+
* `creditCard`, `iban`, `currencyCode` — or the Unicode property escapes TypeBox does not compile
|
|
1298
|
+
* (`emoji`) has none, and is still left off with a warning.
|
|
1299
|
+
*/
|
|
1300
|
+
const FORMAT_PATTERNS = {
|
|
1301
|
+
...Object.fromEntries([
|
|
1302
|
+
"1",
|
|
1303
|
+
"2",
|
|
1304
|
+
"3",
|
|
1305
|
+
"4",
|
|
1306
|
+
"5",
|
|
1307
|
+
"6",
|
|
1308
|
+
"7",
|
|
1309
|
+
"8"
|
|
1310
|
+
].map((v) => [`uuidv${v}`, uuidOfVersion(v)])),
|
|
1311
|
+
guid: `^${UUID_HEX}{8}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{4}-${UUID_HEX}{12}$`,
|
|
1312
|
+
hex: "^[0-9a-fA-F]*$",
|
|
1313
|
+
base64: "^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$",
|
|
1314
|
+
base64url: "^[A-Za-z0-9_-]*$",
|
|
1315
|
+
nanoid: "^[a-zA-Z0-9_-]{21}$",
|
|
1316
|
+
cuid2: "^[0-9a-z]+$",
|
|
1317
|
+
ulid: "^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$",
|
|
1318
|
+
ksuid: "^[A-Za-z0-9]{27}$",
|
|
1319
|
+
xid: "^[0-9a-vA-V]{20}$",
|
|
1320
|
+
cidrv4: `^(?:${OCTET}\\.){3}${OCTET}\\/(?:[0-9]|[1-2][0-9]|3[0-2])$`,
|
|
1321
|
+
cidrv6: `^${IPV6}\\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$`,
|
|
1322
|
+
mac: "^(?:[0-9A-F]{2}:){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$",
|
|
1323
|
+
e164: "^\\+[0-9]{6,14}[0-9]$",
|
|
1324
|
+
httpUrl: "^https?:\\/\\/(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z]{2,}(?::[0-9]{1,5})?(?:[/?#][^\\s]*)?$"
|
|
1325
|
+
};
|
|
1326
|
+
/**
|
|
1327
|
+
* Both patterns at once: the format's, checked from the start of the value, and the document's,
|
|
1328
|
+
* which JSON Schema matches anywhere in it.
|
|
1329
|
+
*/
|
|
1330
|
+
function bothPatterns(formatPattern, pattern) {
|
|
1331
|
+
return `^(?=(?:${formatPattern}))[\\s\\S]*?(?:${pattern})`;
|
|
1332
|
+
}
|
|
1109
1333
|
function validatedFormat(format) {
|
|
1110
1334
|
if (format === void 0 || ELYSIA_STRING_FORMATS.has(format)) return format;
|
|
1111
|
-
if (format !== "password") console.warn(`[asphodelos] format '${format}' is not one Elysia validates; the string is emitted without it`);
|
|
1335
|
+
if (format !== "password" && FORMAT_PATTERNS[format] === void 0) console.warn(`[asphodelos] format '${format}' is not one Elysia validates; the string is emitted without it`);
|
|
1112
1336
|
}
|
|
1113
|
-
function
|
|
1337
|
+
function patternOf(schema) {
|
|
1338
|
+
const pattern = stringPatternFrom(schema);
|
|
1339
|
+
const formatPattern = schema.format === void 0 ? void 0 : FORMAT_PATTERNS[schema.format];
|
|
1340
|
+
if (formatPattern === void 0) return pattern;
|
|
1341
|
+
return pattern === void 0 ? formatPattern : bothPatterns(formatPattern, pattern);
|
|
1342
|
+
}
|
|
1343
|
+
function string(schema, context = {}) {
|
|
1114
1344
|
if (schema.format === "date" || schema.format === "date-time") return `t.Date(${options([...commonOpts(schema)])})`;
|
|
1115
1345
|
if (schema.format === "binary") {
|
|
1116
|
-
if (
|
|
1346
|
+
if (context.mediaType === "application/octet-stream") return `t.Uint8Array(${options([
|
|
1117
1347
|
["minByteLength", schema.minLength],
|
|
1118
1348
|
["maxByteLength", schema.maxLength],
|
|
1119
1349
|
...commonOpts(schema)
|
|
@@ -1127,59 +1357,90 @@ function string(schema, ctx = {}) {
|
|
|
1127
1357
|
}
|
|
1128
1358
|
return stringTransformWrap(`t.String(${options([
|
|
1129
1359
|
["format", validatedFormat(schema.format)],
|
|
1130
|
-
["pattern",
|
|
1360
|
+
["pattern", patternOf(schema)],
|
|
1131
1361
|
["minLength", schema.minLength],
|
|
1132
1362
|
["maxLength", schema.maxLength],
|
|
1133
1363
|
...filterDefined([errorCallback(schema, "string")]),
|
|
1134
1364
|
...commonOpts(schema)
|
|
1135
1365
|
])})`, schema);
|
|
1136
1366
|
}
|
|
1137
|
-
|
|
1138
|
-
//#region src/generator/typebox/t/union.ts
|
|
1367
|
+
// src/generator/typebox/t/union.ts
|
|
1139
1368
|
function union(schemas, parent) {
|
|
1140
1369
|
if (schemas.length === 0) return "t.Never()";
|
|
1141
1370
|
if (schemas.length === 1 && schemas[0]) return typebox(schemas[0]);
|
|
1142
1371
|
const opts = parent ? options([...filterDefined([errorCallback(parent, "composition")]), ...commonOpts(parent)]) : "";
|
|
1143
1372
|
return opts ? `t.Union([${schemas.map((s) => typebox(s)).join(",")}],${opts})` : `t.Union([${schemas.map((s) => typebox(s)).join(",")}])`;
|
|
1144
1373
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
function
|
|
1374
|
+
// src/generator/typebox/index.ts
|
|
1375
|
+
/** Whether the value this schema describes reaches Elysia as text. */
|
|
1376
|
+
function isTextInput(context) {
|
|
1377
|
+
return context.text === true;
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Whether the schema describes a form body, whose every field reaches Elysia as text. A number or
|
|
1381
|
+
* a boolean there is read through `t.Numeric` / `t.BooleanString`, the way Elysia itself reads a
|
|
1382
|
+
* query or a header; a JSON body carries its own types and keeps the plain factories.
|
|
1383
|
+
*/
|
|
1384
|
+
function isFormMedia(context) {
|
|
1385
|
+
return context.mediaType === "multipart/form-data" || context.mediaType === "application/x-www-form-urlencoded";
|
|
1386
|
+
}
|
|
1387
|
+
/** Whether a number or a boolean has to be read from text by the schema itself. */
|
|
1388
|
+
function readsTextItself(context) {
|
|
1389
|
+
return isFormMedia(context) || context.readsText === true;
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* A literal of a number or a boolean, where the value arrives as text: the text of each member is
|
|
1393
|
+
* accepted beside the member itself and read into it, so `?level=2` reaches the handler as `2`
|
|
1394
|
+
* and is typed `1 | 2 | 3`. A string member needs no reading, and a value that is not text, a JSON
|
|
1395
|
+
* body, is left as it is.
|
|
1396
|
+
*/
|
|
1397
|
+
function readLiteralsFromText(expr, values, context) {
|
|
1398
|
+
if (!isTextInput(context) || values.length === 0) return expr;
|
|
1399
|
+
if (!values.every((v) => typeof v === "number" || typeof v === "boolean")) return expr;
|
|
1400
|
+
const spelled = values.map((v) => `t.Literal(${JSON.stringify(String(v))})`);
|
|
1401
|
+
return `t.Transform(t.Union([${spelled.length === 1 ? spelled[0] : `t.Union([${spelled.join(",")}])`},${expr}])).Decode((v):${values.map(String).join("|")}=>(typeof v==='string'?JSON.parse(v):v)).Encode((v)=>v)`;
|
|
1402
|
+
}
|
|
1403
|
+
function typebox(schema, context = {}) {
|
|
1148
1404
|
const enabled = schema["x-readonly"] === true;
|
|
1149
1405
|
const rawTransform = schema["x-transform"];
|
|
1150
|
-
if (typeof rawTransform === "string" && rawTransform.length > 0) return readonly(wrap(brand(rawTransform, schema), schema), enabled);
|
|
1406
|
+
if (typeof rawTransform === "string" && rawTransform.length > 0) return readonly(wrap(brand(rawTransform, schema), schema, context), enabled);
|
|
1151
1407
|
if (schema.$ref) return ref(schema);
|
|
1152
|
-
if (schema.allOf) return readonly(wrap(intersect(schema.allOf, schema), schema), enabled);
|
|
1153
|
-
if (schema.oneOf) return readonly(wrap(union(schema.oneOf, schema), schema), enabled);
|
|
1154
|
-
if (schema.anyOf) return readonly(wrap(union(schema.anyOf, schema), schema), enabled);
|
|
1155
|
-
if (schema.not) return readonly(wrap(notType(schema.not, schema), schema), enabled);
|
|
1156
|
-
if (schema.enum) return readonly(wrap(brand(_enum(schema), schema), schema), enabled);
|
|
1408
|
+
if (schema.allOf) return readonly(wrap(intersect(schema.allOf, schema), schema, context), enabled);
|
|
1409
|
+
if (schema.oneOf) return readonly(wrap(union(schema.oneOf, schema), schema, context), enabled);
|
|
1410
|
+
if (schema.anyOf) return readonly(wrap(union(schema.anyOf, schema), schema, context), enabled);
|
|
1411
|
+
if (schema.not) return readonly(wrap(notType(schema.not, schema), schema, context), enabled);
|
|
1412
|
+
if (schema.enum) return readonly(wrap(brand(readLiteralsFromText(_enum(schema), schema.enum, context), schema), schema, context), enabled);
|
|
1157
1413
|
if (schema.const !== void 0) {
|
|
1158
1414
|
const opts = options([...filterDefined([errorCallback(schema, "composition")]), ...commonOpts(schema)]);
|
|
1159
1415
|
const optsPart = opts ? `,${opts}` : "";
|
|
1160
|
-
return readonly(wrap(brand(schema.const === null ? `t.Null(${opts})` : typeof schema.const === "object" ? literalSchema(schema.const) : `t.Literal(${JSON.stringify(schema.const)}${optsPart})`, schema), schema), enabled);
|
|
1416
|
+
return readonly(wrap(brand(readLiteralsFromText(schema.const === null ? `t.Null(${opts})` : typeof schema.const === "object" ? literalSchema(schema.const) : `t.Literal(${JSON.stringify(schema.const)}${optsPart})`, [schema.const], context), schema), schema, context), enabled);
|
|
1161
1417
|
}
|
|
1418
|
+
const listed = isTypeArray(schema.type) ? schema.type.filter((kind) => kind !== "null") : [];
|
|
1419
|
+
if (listed.length > 1) return readonly(wrap(`t.Union([${listed.map((kind) => typebox({
|
|
1420
|
+
...schema,
|
|
1421
|
+
type: kind,
|
|
1422
|
+
nullable: void 0
|
|
1423
|
+
}, context)).join(",")}])`, schema, context), enabled);
|
|
1162
1424
|
const primaryType = () => {
|
|
1163
1425
|
if (typeof schema.type === "string") return schema.type;
|
|
1164
|
-
if (isTypeArray(schema.type)) return schema.type.find((
|
|
1165
|
-
if (schema.properties
|
|
1426
|
+
if (isTypeArray(schema.type)) return schema.type.find((kind) => kind !== "null");
|
|
1427
|
+
if (schema.properties !== void 0 || schema.additionalProperties !== void 0) return "object";
|
|
1166
1428
|
if (schema.items ?? schema.prefixItems) return "array";
|
|
1167
1429
|
};
|
|
1168
1430
|
switch (primaryType()) {
|
|
1169
|
-
case "string": return readonly(wrap(brand(string(schema,
|
|
1170
|
-
case "integer": return readonly(wrap(brand(integer(schema), schema), schema), enabled);
|
|
1171
|
-
case "number": return readonly(wrap(brand(number(schema), schema), schema), enabled);
|
|
1172
|
-
case "boolean": return readonly(wrap(brand(boolean(schema), schema), schema), enabled);
|
|
1173
|
-
case "array": return readonly(wrap(array(schema,
|
|
1174
|
-
case "object": return readonly(wrap(object(schema,
|
|
1431
|
+
case "string": return readonly(wrap(brand(string(schema, context), schema), schema, context), enabled);
|
|
1432
|
+
case "integer": return readonly(wrap(brand(integer(schema), schema), schema, context), enabled);
|
|
1433
|
+
case "number": return readonly(wrap(brand(number(schema, context), schema), schema, context), enabled);
|
|
1434
|
+
case "boolean": return readonly(wrap(brand(boolean(schema, context), schema), schema, context), enabled);
|
|
1435
|
+
case "array": return readonly(wrap(array(schema, context), schema, context), enabled);
|
|
1436
|
+
case "object": return readonly(wrap(object(schema, context), schema, context), enabled);
|
|
1175
1437
|
case "null": return nullType();
|
|
1176
1438
|
case "date":
|
|
1177
1439
|
case void 0: return "t.Unknown()";
|
|
1178
1440
|
default: return "t.Unknown()";
|
|
1179
1441
|
}
|
|
1180
1442
|
}
|
|
1181
|
-
|
|
1182
|
-
//#region src/generator/components/schemas.ts
|
|
1443
|
+
// src/generator/components/schemas.ts
|
|
1183
1444
|
function sub(code, from, to) {
|
|
1184
1445
|
return code.replaceAll(new RegExp(`\\b${from}\\b`, "gu"), to);
|
|
1185
1446
|
}
|
|
@@ -1216,18 +1477,18 @@ function schemasCode(schemas, readonlyMode, exportTypes, exported = true) {
|
|
|
1216
1477
|
}))).map((group) => emitGroup(group, readonlyMode, exportTypes, exported, names)).filter((s) => s.length > 0).join("\n\n");
|
|
1217
1478
|
}
|
|
1218
1479
|
function refsWithin(schema, memberNames) {
|
|
1219
|
-
return new Set([...collectSchemaRefs$1(schema)].filter((
|
|
1480
|
+
return new Set([...collectSchemaRefs$1(schema)].filter((ref) => memberNames.has(ref)));
|
|
1220
1481
|
}
|
|
1221
1482
|
function findStar(group, exportedName) {
|
|
1222
|
-
if (group.some((
|
|
1223
|
-
const memberNames = new Set(group.map((
|
|
1224
|
-
const refs = new Map(group.map((
|
|
1483
|
+
if (group.some((member) => exportedName(member.name) !== pascalCase(member.name))) return null;
|
|
1484
|
+
const memberNames = new Set(group.map((member) => member.name));
|
|
1485
|
+
const refs = new Map(group.map((member) => [member.name, refsWithin(member.schema, memberNames)]));
|
|
1225
1486
|
const candidates = group.filter((hub) => {
|
|
1226
|
-
const spokes = group.filter((
|
|
1487
|
+
const spokes = group.filter((member) => member.name !== hub.name);
|
|
1227
1488
|
const hubRefs = refs.get(hub.name) ?? /* @__PURE__ */ new Set();
|
|
1228
1489
|
return spokes.every((s) => {
|
|
1229
|
-
const
|
|
1230
|
-
return
|
|
1490
|
+
const spokeRefs = refs.get(s.name) ?? /* @__PURE__ */ new Set();
|
|
1491
|
+
return spokeRefs.size === 1 && spokeRefs.has(hub.name);
|
|
1231
1492
|
}) && spokes.every((s) => hubRefs.has(s.name));
|
|
1232
1493
|
});
|
|
1233
1494
|
if (candidates.length === 0) return null;
|
|
@@ -1240,7 +1501,7 @@ function findStar(group, exportedName) {
|
|
|
1240
1501
|
});
|
|
1241
1502
|
return {
|
|
1242
1503
|
hub,
|
|
1243
|
-
spokes: group.filter((
|
|
1504
|
+
spokes: group.filter((member) => member.name !== hub.name)
|
|
1244
1505
|
};
|
|
1245
1506
|
}
|
|
1246
1507
|
function emitStar(star, exportKw, readonlyMode, exportTypes) {
|
|
@@ -1249,8 +1510,8 @@ function emitStar(star, exportKw, readonlyMode, exportTypes) {
|
|
|
1249
1510
|
const hubExpr = `t.Recursive((Self)=>${sub(spokes.reduce((acc, s) => sub(acc, `${pascalCase(s.name)}Schema`, `(${sub(typebox(s.schema), hubRef, "Self")})`), typebox(hub.schema)), hubRef, "Self")})`;
|
|
1250
1511
|
const decl = (name, expr) => {
|
|
1251
1512
|
const ident = `${pascalCase(name)}Schema`;
|
|
1252
|
-
const
|
|
1253
|
-
return exportTypes ? `${
|
|
1513
|
+
const declaration = `${exportKw}const ${ident}=${readonly(expr, readonlyMode)}`;
|
|
1514
|
+
return exportTypes ? `${declaration}\n\nexport type ${pascalCase(name)}=Static<typeof ${ident}>` : declaration;
|
|
1254
1515
|
};
|
|
1255
1516
|
return [decl(hub.name, hubExpr), ...spokes.map((s) => decl(s.name, typebox(s.schema)))].join("\n\n");
|
|
1256
1517
|
}
|
|
@@ -1269,7 +1530,7 @@ function emitGroup(group, readonlyMode, exportTypes, exported, names) {
|
|
|
1269
1530
|
}
|
|
1270
1531
|
const star = findStar(group, exportedName);
|
|
1271
1532
|
if (star) return emitStar(star, exportKw, readonlyMode, exportTypes);
|
|
1272
|
-
const memberNames = new Set(group.map((
|
|
1533
|
+
const memberNames = new Set(group.map((member) => member.name));
|
|
1273
1534
|
const moduleEntries = group.map(({ name, schema }) => {
|
|
1274
1535
|
const inner = typebox(schema);
|
|
1275
1536
|
return `${name}:${[...memberNames].reduce((acc, m) => {
|
|
@@ -1280,12 +1541,12 @@ function emitGroup(group, readonlyMode, exportTypes, exported, names) {
|
|
|
1280
1541
|
const moduleId = head ? `${pascalCase(head.name)}Module` : "Module";
|
|
1281
1542
|
return `const ${moduleId}=t.Module({${moduleEntries}})\n\n${group.map(({ name }) => {
|
|
1282
1543
|
const ident = `${exportedName(name)}Schema`;
|
|
1283
|
-
const
|
|
1544
|
+
const expr = `${moduleId}.Import('${name}')`;
|
|
1545
|
+
const decl = `${exportKw}const ${ident}=${readonly(expr, readonlyMode)}`;
|
|
1284
1546
|
return exportTypes ? `${decl}\n\nexport type ${exportedName(name)}=Static<typeof ${ident}>` : decl;
|
|
1285
1547
|
}).join("\n\n")}`;
|
|
1286
1548
|
}
|
|
1287
|
-
|
|
1288
|
-
//#region src/generator/components/typeboxKinds.ts
|
|
1549
|
+
// src/generator/components/typeboxKinds.ts
|
|
1289
1550
|
function makeCode(suffix, extract) {
|
|
1290
1551
|
return (section, readonlyMode, exportTypes, exported = true) => {
|
|
1291
1552
|
if (!section) return "";
|
|
@@ -1300,10 +1561,14 @@ function makeCode(suffix, extract) {
|
|
|
1300
1561
|
}).join("\n\n");
|
|
1301
1562
|
};
|
|
1302
1563
|
}
|
|
1303
|
-
const responsesCode = makeCode("ResponseSchema", (s) => Object.entries(s).map(([name,
|
|
1304
|
-
const schema = jsonSchema(
|
|
1564
|
+
const responsesCode = makeCode("ResponseSchema", (s) => Object.entries(s).map(([name, response]) => {
|
|
1565
|
+
const schema = jsonSchema(response.content);
|
|
1305
1566
|
return [name, schema ? typebox(schema) : "t.Void()"];
|
|
1306
1567
|
}));
|
|
1568
|
+
/** What `responsesCode` renders a `$ref` as: the schemas of the JSON content. */
|
|
1569
|
+
function responsesRefKinds(section) {
|
|
1570
|
+
return schemaRefKinds(Object.values(section ?? {}).map((response) => jsonSchema(response.content)));
|
|
1571
|
+
}
|
|
1307
1572
|
const parametersCode = makeCode("ParamsSchema", (s) => Object.entries(s).map(([name, p]) => {
|
|
1308
1573
|
if (!p.schema) {
|
|
1309
1574
|
if (p.content) console.warn(`asphodelos: Component parameter '${name}' uses 'content' field (OpenAPI 3.1 alternative to 'schema'). This is not yet supported; emitting t.Unknown() placeholder.`);
|
|
@@ -1311,22 +1576,45 @@ const parametersCode = makeCode("ParamsSchema", (s) => Object.entries(s).map(([n
|
|
|
1311
1576
|
}
|
|
1312
1577
|
return [name, typebox(p.schema)];
|
|
1313
1578
|
}));
|
|
1579
|
+
/** What `parametersCode` renders a `$ref` as: the schemas of the parameters. */
|
|
1580
|
+
function parametersRefKinds(section) {
|
|
1581
|
+
return schemaRefKinds(Object.values(section ?? {}).map((p) => p.schema));
|
|
1582
|
+
}
|
|
1314
1583
|
const requestBodiesCode = makeCode("RequestBodySchema", (s) => Object.entries(s).map(([name, body]) => {
|
|
1315
1584
|
const schema = jsonSchema(body.content);
|
|
1316
1585
|
return [name, schema ? typebox(schema) : "t.Unknown()"];
|
|
1317
1586
|
}));
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1587
|
+
/** What `requestBodiesCode` renders a `$ref` as: the schemas of the JSON content. */
|
|
1588
|
+
function requestBodiesRefKinds(section) {
|
|
1589
|
+
return schemaRefKinds(Object.values(section ?? {}).map((body) => jsonSchema(body.content)));
|
|
1590
|
+
}
|
|
1591
|
+
const headersCode = makeCode("HeaderSchema", (s) => Object.entries(s).map(([name, header]) => {
|
|
1592
|
+
if (isReference(header) && header.$ref) return [name, refIdent(header.$ref) ?? "t.Unknown()"];
|
|
1593
|
+
const schema = "schema" in header ? header.schema : void 0;
|
|
1321
1594
|
return [name, schema ? typebox(schema) : "t.Unknown()"];
|
|
1322
1595
|
}));
|
|
1596
|
+
/**
|
|
1597
|
+
* What `headersCode` renders a `$ref` as: a header that is a `$ref`, or the schema of one that is
|
|
1598
|
+
* not.
|
|
1599
|
+
*/
|
|
1600
|
+
function headersRefKinds(section) {
|
|
1601
|
+
const entries = Object.values(section ?? {});
|
|
1602
|
+
return new Map([...schemaRefKinds(entries.map((header) => isReference(header) && header.$ref ? void 0 : "schema" in header ? header.schema : void 0)), ...stringifiedRefKinds(entries.filter((header) => isReference(header) && header.$ref !== void 0))]);
|
|
1603
|
+
}
|
|
1323
1604
|
const mediaTypesCode = makeCode("MediaTypeSchema", (s) => Object.entries(s).map(([name, mt]) => {
|
|
1324
1605
|
if (isReference(mt) && mt.$ref) return [name, refIdent(mt.$ref) ?? "t.Unknown()"];
|
|
1325
1606
|
const schema = !isReference(mt) && "schema" in mt ? mt.schema : void 0;
|
|
1326
1607
|
return [name, schema ? typebox(schema) : "t.Unknown()"];
|
|
1327
1608
|
}));
|
|
1328
|
-
|
|
1329
|
-
|
|
1609
|
+
/**
|
|
1610
|
+
* What `mediaTypesCode` renders a `$ref` as: a media type that is a `$ref`, or the schema of one
|
|
1611
|
+
* that is not.
|
|
1612
|
+
*/
|
|
1613
|
+
function mediaTypesRefKinds(section) {
|
|
1614
|
+
const entries = Object.values(section ?? {});
|
|
1615
|
+
return new Map([...schemaRefKinds(entries.map((mt) => !isReference(mt) && "schema" in mt ? mt.schema : void 0)), ...stringifiedRefKinds(entries.filter((mt) => isReference(mt) && mt.$ref !== void 0))]);
|
|
1616
|
+
}
|
|
1617
|
+
// src/generator/components/metadataKinds.ts
|
|
1330
1618
|
function makeMetadataCode(suffix) {
|
|
1331
1619
|
return (section, exported = true) => {
|
|
1332
1620
|
if (!section) return "";
|
|
@@ -1345,8 +1633,7 @@ const securitySchemesCode = makeMetadataCode("SecurityScheme");
|
|
|
1345
1633
|
const linksCode = makeMetadataCode("Link");
|
|
1346
1634
|
const callbacksCode = makeMetadataCode("Callback");
|
|
1347
1635
|
const pathItemsCode = makeMetadataCode("PathItem");
|
|
1348
|
-
|
|
1349
|
-
//#region src/helper/code.ts
|
|
1636
|
+
// src/helper/code.ts
|
|
1350
1637
|
function makeModuleSpec(fromFile, target) {
|
|
1351
1638
|
const stripped = path.relative(path.dirname(fromFile), target.output).replaceAll("\\", "/").replace(/\.ts$/u, "").replace(/(^|\/)index$/u, "");
|
|
1352
1639
|
return stripped === "" ? "." : stripped.startsWith(".") ? stripped : `./${stripped}`;
|
|
@@ -1381,7 +1668,12 @@ const EXPORT_TYPE_PATTERN = new RegExp(`export\\s+type\\s+(${JS_IDENT})\\s*=`, "
|
|
|
1381
1668
|
function classifyRef(name) {
|
|
1382
1669
|
return COMPONENT_SUFFIXES.reduce((best, entry) => name.endsWith(entry[1]) && (!best || entry[1].length > best[1].length) ? entry : best, void 0)?.[0];
|
|
1383
1670
|
}
|
|
1384
|
-
|
|
1671
|
+
/**
|
|
1672
|
+
* `code` with the imports it needs prepended: Elysia's `t` and types, TypeBox's `Value`, and each
|
|
1673
|
+
* component it references. A component comes from the kind `refKinds` gives it (the kind of the
|
|
1674
|
+
* `$ref` it was rendered from), and is classified by its suffix otherwise.
|
|
1675
|
+
*/
|
|
1676
|
+
function makeImports(code, fromFile, components, split = false, refKinds = /* @__PURE__ */ new Map(), excludeKinds = /* @__PURE__ */ new Set()) {
|
|
1385
1677
|
const fallbackPrefix = split ? ".." : ".";
|
|
1386
1678
|
const resolvePath = (k) => {
|
|
1387
1679
|
const target = components?.[k];
|
|
@@ -1393,7 +1685,7 @@ function makeImports(code, fromFile, components, split = false, excludeKinds = /
|
|
|
1393
1685
|
for (const match of code.matchAll(SCAN)) {
|
|
1394
1686
|
const name = match[1];
|
|
1395
1687
|
if (!name || definedConsts.has(name) || definedTypes.has(name)) continue;
|
|
1396
|
-
const kind = classifyRef(name);
|
|
1688
|
+
const kind = refKinds.get(name) ?? classifyRef(name);
|
|
1397
1689
|
if (!kind || excludeKinds.has(kind)) continue;
|
|
1398
1690
|
const bucket = grouped.get(kind) ?? /* @__PURE__ */ new Set();
|
|
1399
1691
|
bucket.add(name);
|
|
@@ -1409,7 +1701,7 @@ function makeImports(code, fromFile, components, split = false, excludeKinds = /
|
|
|
1409
1701
|
].filter(Boolean);
|
|
1410
1702
|
const headerLines = [
|
|
1411
1703
|
elysiaParts.length > 0 ? `import {${elysiaParts.join(",")}} from 'elysia'` : "",
|
|
1412
|
-
/\bValue\.Check\b/u.test(code) ? `import {Value} from '@sinclair/typebox/value'` : "",
|
|
1704
|
+
/\bValue\.(?:Check|Decode)\b/u.test(code) ? `import {Value} from '@sinclair/typebox/value'` : "",
|
|
1413
1705
|
...COMPONENT_SUFFIXES.flatMap(([kind]) => {
|
|
1414
1706
|
const names = grouped.get(kind);
|
|
1415
1707
|
if (!names) return [];
|
|
@@ -1419,8 +1711,7 @@ function makeImports(code, fromFile, components, split = false, excludeKinds = /
|
|
|
1419
1711
|
if (headerLines.length === 0) return code;
|
|
1420
1712
|
return `${headerLines.join("\n")}\n\n${code}`;
|
|
1421
1713
|
}
|
|
1422
|
-
|
|
1423
|
-
//#region src/helper/eden.ts
|
|
1714
|
+
// src/helper/eden.ts
|
|
1424
1715
|
function isIdentifierSegment(seg) {
|
|
1425
1716
|
return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(seg);
|
|
1426
1717
|
}
|
|
@@ -1433,16 +1724,16 @@ function accessSegment(seg) {
|
|
|
1433
1724
|
function edenChain(pathStr, client, method) {
|
|
1434
1725
|
const { callChain, typeChain, typeIsValue, typeChainHasBracket, paramArgs } = pathStr.split("/").filter(Boolean).reduce((acc, seg) => {
|
|
1435
1726
|
if (/^\{([^}]+)\}$/u.exec(seg)) {
|
|
1436
|
-
const
|
|
1727
|
+
const fnType = acc.typeIsValue ? `typeof ${acc.typeChain}` : acc.typeChain;
|
|
1437
1728
|
const name = acc.paramArgs.length === 0 ? "params" : `params${acc.paramArgs.length + 1}`;
|
|
1438
1729
|
return {
|
|
1439
1730
|
callChain: `${acc.callChain}(${name})`,
|
|
1440
|
-
typeChain: `ReturnType<${
|
|
1731
|
+
typeChain: `ReturnType<${fnType}>`,
|
|
1441
1732
|
typeIsValue: false,
|
|
1442
1733
|
typeChainHasBracket: acc.typeChainHasBracket,
|
|
1443
1734
|
paramArgs: [...acc.paramArgs, {
|
|
1444
1735
|
name,
|
|
1445
|
-
typeExpr: `Parameters<${
|
|
1736
|
+
typeExpr: `Parameters<${fnType}>[0]`
|
|
1446
1737
|
}]
|
|
1447
1738
|
};
|
|
1448
1739
|
}
|
|
@@ -1469,8 +1760,7 @@ function edenChain(pathStr, client, method) {
|
|
|
1469
1760
|
paramArgs
|
|
1470
1761
|
};
|
|
1471
1762
|
}
|
|
1472
|
-
|
|
1473
|
-
//#region src/helper/path-params.ts
|
|
1763
|
+
// src/helper/path-params.ts
|
|
1474
1764
|
function isIdentifier(name) {
|
|
1475
1765
|
return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(name);
|
|
1476
1766
|
}
|
|
@@ -1537,8 +1827,7 @@ function renameOperationParams(operation, renames) {
|
|
|
1537
1827
|
parameters
|
|
1538
1828
|
};
|
|
1539
1829
|
}
|
|
1540
|
-
|
|
1541
|
-
//#region src/helper/openapi.ts
|
|
1830
|
+
// src/helper/openapi.ts
|
|
1542
1831
|
/**
|
|
1543
1832
|
* Generates prefix-only query-key getters (`get<Prefix>Key() => ['<prefix>']`)
|
|
1544
1833
|
* for each unique first path segment, mirroring hono-takibi. Used for
|
|
@@ -1560,12 +1849,22 @@ function tagName(tag) {
|
|
|
1560
1849
|
if (!cleaned) return "default";
|
|
1561
1850
|
return cleaned.split(/\s+/u).map((p, i) => i === 0 ? p.toLowerCase() : p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join("");
|
|
1562
1851
|
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
1854
|
+
*
|
|
1855
|
+
* @internal
|
|
1856
|
+
*/
|
|
1563
1857
|
function resourceName(pathStr) {
|
|
1564
1858
|
const first = pathStr.split("/").find((s) => s.length > 0 && !s.startsWith("{"));
|
|
1565
1859
|
return first ? tagName(first) : "root";
|
|
1566
1860
|
}
|
|
1861
|
+
/**
|
|
1862
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
1863
|
+
*
|
|
1864
|
+
* @internal
|
|
1865
|
+
*/
|
|
1567
1866
|
function makeOperationId(method, path) {
|
|
1568
|
-
const camel = path.replaceAll(/\{([^}]+)\}/gu, "By-$1").split("/").filter(Boolean).map((p, i) => i === 0 ? p : p.charAt(0).toUpperCase() + p.slice(1)).join("").replaceAll(/-([a-z])/giu, (_,
|
|
1867
|
+
const camel = path.replaceAll(/\{([^}]+)\}/gu, "By-$1").split("/").filter(Boolean).map((p, i) => i === 0 ? p : p.charAt(0).toUpperCase() + p.slice(1)).join("").replaceAll(/-([a-z])/giu, (_, letter) => letter.toUpperCase());
|
|
1569
1868
|
return camel ? `${method}${camel.charAt(0).toUpperCase()}${camel.slice(1)}` : method;
|
|
1570
1869
|
}
|
|
1571
1870
|
function resolveOperationId(operation, method, path) {
|
|
@@ -1585,16 +1884,16 @@ function resolveRequestBody(b, components) {
|
|
|
1585
1884
|
if (isReference(b) && b.$ref) return lookup$1(b.$ref, "requestBodies", components?.requestBodies);
|
|
1586
1885
|
return b;
|
|
1587
1886
|
}
|
|
1588
|
-
function resolveResponse(
|
|
1589
|
-
if (isReference(
|
|
1590
|
-
return
|
|
1887
|
+
function resolveResponse(response, components) {
|
|
1888
|
+
if (isReference(response) && response.$ref) return lookup$1(response.$ref, "responses", components?.responses) ?? {};
|
|
1889
|
+
return response;
|
|
1591
1890
|
}
|
|
1592
1891
|
function resolveOperation(operation, components) {
|
|
1593
1892
|
return {
|
|
1594
1893
|
...operation,
|
|
1595
1894
|
parameters: (operation.parameters ?? []).map((p) => resolveParameter$1(p, components)).filter((p) => p !== void 0),
|
|
1596
1895
|
requestBody: resolveRequestBody(operation.requestBody, components),
|
|
1597
|
-
responses: Object.fromEntries(Object.entries(operation.responses ?? {}).map(([status,
|
|
1896
|
+
responses: Object.fromEntries(Object.entries(operation.responses ?? {}).map(([status, response]) => [status, resolveResponse(response, components)]))
|
|
1598
1897
|
};
|
|
1599
1898
|
}
|
|
1600
1899
|
const HTTP_METHODS = [
|
|
@@ -1606,17 +1905,22 @@ const HTTP_METHODS = [
|
|
|
1606
1905
|
"head",
|
|
1607
1906
|
"patch"
|
|
1608
1907
|
];
|
|
1609
|
-
|
|
1908
|
+
/**
|
|
1909
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
1910
|
+
*
|
|
1911
|
+
* @internal
|
|
1912
|
+
*/
|
|
1913
|
+
function makeRoute(method, path, operation, components) {
|
|
1610
1914
|
const operationId = resolveOperationId(operation, method, path);
|
|
1611
1915
|
const tags = operation.tags ?? [];
|
|
1612
|
-
const params = makeParamsSchema(operation.parameters ?? [], "path");
|
|
1613
|
-
const query = makeParamsSchema(operation.parameters ?? [], "query");
|
|
1614
|
-
const headers = makeParamsSchema(operation.parameters ?? [], "header");
|
|
1615
|
-
const cookie = makeParamsSchema(operation.parameters ?? [], "cookie");
|
|
1616
|
-
const body = bodyInfo(operation);
|
|
1916
|
+
const params = makeParamsSchema(operation.parameters ?? [], "path", components);
|
|
1917
|
+
const query = makeParamsSchema(operation.parameters ?? [], "query", components);
|
|
1918
|
+
const headers = makeParamsSchema(operation.parameters ?? [], "header", components);
|
|
1919
|
+
const cookie = makeParamsSchema(operation.parameters ?? [], "cookie", components);
|
|
1920
|
+
const body = bodyInfo(operation, components);
|
|
1617
1921
|
const synth = (kind) => `${toSafeIdentifier(operationId)}${kind}`;
|
|
1618
|
-
const responsesAndInline = Object.entries(operation.responses ?? {}).map(([status,
|
|
1619
|
-
const info = responseInfo(
|
|
1922
|
+
const responsesAndInline = Object.entries(operation.responses ?? {}).map(([status, response]) => {
|
|
1923
|
+
const info = responseInfo(response);
|
|
1620
1924
|
if (info.ref) return { entry: {
|
|
1621
1925
|
status,
|
|
1622
1926
|
schema: {
|
|
@@ -1649,27 +1953,27 @@ function makeRoute(method, path, operation) {
|
|
|
1649
1953
|
...params ? [{
|
|
1650
1954
|
name: synth("Params"),
|
|
1651
1955
|
schema: params.schema,
|
|
1652
|
-
|
|
1956
|
+
context: params.context
|
|
1653
1957
|
}] : [],
|
|
1654
1958
|
...query ? [{
|
|
1655
1959
|
name: synth("Query"),
|
|
1656
1960
|
schema: query.schema,
|
|
1657
|
-
|
|
1961
|
+
context: query.context
|
|
1658
1962
|
}] : [],
|
|
1659
1963
|
...headers ? [{
|
|
1660
1964
|
name: synth("Headers"),
|
|
1661
1965
|
schema: headers.schema,
|
|
1662
|
-
|
|
1966
|
+
context: headers.context
|
|
1663
1967
|
}] : [],
|
|
1664
1968
|
...cookie ? [{
|
|
1665
1969
|
name: synth("Cookie"),
|
|
1666
1970
|
schema: cookie.schema,
|
|
1667
|
-
|
|
1971
|
+
context: cookie.context
|
|
1668
1972
|
}] : [],
|
|
1669
1973
|
...body.inline ? [{
|
|
1670
1974
|
name: synth("Body"),
|
|
1671
1975
|
schema: body.inline,
|
|
1672
|
-
|
|
1976
|
+
context: body.context
|
|
1673
1977
|
}] : [],
|
|
1674
1978
|
...responsesAndInline.flatMap((item) => "inline" in item && item.inline ? [item.inline] : [])
|
|
1675
1979
|
];
|
|
@@ -1724,18 +2028,19 @@ function walk(path, resource, pathItem, api, canonical) {
|
|
|
1724
2028
|
return HTTP_METHODS.flatMap((method) => {
|
|
1725
2029
|
const operation = resolved[method];
|
|
1726
2030
|
if (!operation) return [];
|
|
1727
|
-
|
|
2031
|
+
const resolvedOperation = renameOperationParams(resolveOperation(withPathItemParameters(operation, resolved.parameters ?? [], api.components), api.components), renames);
|
|
2032
|
+
return [[resource, makeRoute(method, normalizedPath, resolvedOperation, api.components)]];
|
|
1728
2033
|
});
|
|
1729
2034
|
}
|
|
1730
2035
|
function operationsByResource(api) {
|
|
1731
|
-
const canonical = canonicalParamNames([...Object.keys(api.paths), ...Object.keys(api.webhooks ?? {}).map((event) => `/webhooks/${event}`)]);
|
|
2036
|
+
const canonical = canonicalParamNames([...Object.keys(api.paths ?? {}), ...Object.keys(api.webhooks ?? {}).map((event) => `/webhooks/${event}`)]);
|
|
1732
2037
|
const grouped = /* @__PURE__ */ new Map();
|
|
1733
2038
|
const collect = (resource, item) => {
|
|
1734
2039
|
const bucket = grouped.get(resource) ?? [];
|
|
1735
2040
|
bucket.push(item);
|
|
1736
2041
|
grouped.set(resource, bucket);
|
|
1737
2042
|
};
|
|
1738
|
-
for (const [path, pathItem] of Object.entries(api.paths)) {
|
|
2043
|
+
for (const [path, pathItem] of Object.entries(api.paths ?? {})) {
|
|
1739
2044
|
if (!pathItem) continue;
|
|
1740
2045
|
for (const [resource, route] of walk(path, resourceName(path), pathItem, api, canonical)) collect(resource, route);
|
|
1741
2046
|
}
|
|
@@ -1745,8 +2050,7 @@ function operationsByResource(api) {
|
|
|
1745
2050
|
}
|
|
1746
2051
|
return grouped;
|
|
1747
2052
|
}
|
|
1748
|
-
|
|
1749
|
-
//#region src/core/components/output.ts
|
|
2053
|
+
// src/core/components/output.ts
|
|
1750
2054
|
/**
|
|
1751
2055
|
* Emits every component kind into a single file (`components.output` mode).
|
|
1752
2056
|
* Cross-component references resolve within the same file — `makeImports`
|
|
@@ -1775,8 +2079,7 @@ function components(section, output, readonly) {
|
|
|
1775
2079
|
return `Generated components code written to ${output}`;
|
|
1776
2080
|
});
|
|
1777
2081
|
}
|
|
1778
|
-
|
|
1779
|
-
//#region src/error/index.ts
|
|
2082
|
+
// src/error/index.ts
|
|
1780
2083
|
/**
|
|
1781
2084
|
* A generator refused the work it was given — an empty section, an output path that does not fit
|
|
1782
2085
|
* the mode, a document that says nothing to write.
|
|
@@ -1785,25 +2088,25 @@ function components(section, output, readonly) {
|
|
|
1785
2088
|
* source): this one is always the caller's input, and the CLI renders its message as-is.
|
|
1786
2089
|
*/
|
|
1787
2090
|
var GenerateError = class extends Data.TaggedError("GenerateError") {};
|
|
1788
|
-
|
|
1789
|
-
//#region src/core/components/schemas.ts
|
|
2091
|
+
// src/core/components/schemas.ts
|
|
1790
2092
|
function fileNameOf(group) {
|
|
1791
|
-
return uncapitalize(group.map((
|
|
2093
|
+
return uncapitalize(group.map((member) => member.name).toSorted()[0] ?? "schema");
|
|
1792
2094
|
}
|
|
1793
2095
|
function splitSchemaFiles(section, readonly, exportTypes) {
|
|
1794
2096
|
const groups = sccSchemas(Object.entries(section).map(([name, schema]) => ({
|
|
1795
2097
|
name,
|
|
1796
2098
|
schema
|
|
1797
2099
|
})));
|
|
1798
|
-
const nameToFile = new Map(groups.flatMap((
|
|
2100
|
+
const nameToFile = new Map(groups.flatMap((group) => group.map((s) => [s.name, fileNameOf(group)])));
|
|
1799
2101
|
return groups.map((group) => {
|
|
1800
2102
|
const fileName = fileNameOf(group);
|
|
1801
|
-
const body = schemasCode(Object.fromEntries(group.map((
|
|
2103
|
+
const body = schemasCode(Object.fromEntries(group.map((member) => [member.name, member.schema])), readonly, exportTypes);
|
|
1802
2104
|
if (body === "") return {
|
|
1803
2105
|
fileName,
|
|
1804
|
-
code: ""
|
|
2106
|
+
code: "",
|
|
2107
|
+
refKinds: /* @__PURE__ */ new Map()
|
|
1805
2108
|
};
|
|
1806
|
-
const memberNames = new Set(group.map((
|
|
2109
|
+
const memberNames = new Set(group.map((member) => member.name));
|
|
1807
2110
|
const bySibling = /* @__PURE__ */ new Map();
|
|
1808
2111
|
for (const { schema } of group) for (const refName of collectSchemaRefs$1(schema)) {
|
|
1809
2112
|
const sibling = nameToFile.get(refName);
|
|
@@ -1815,7 +2118,8 @@ function splitSchemaFiles(section, readonly, exportTypes) {
|
|
|
1815
2118
|
const siblingImports = [...bySibling.entries()].toSorted(([a], [b]) => a.localeCompare(b)).map(([sibling, idents]) => `import {${[...idents].toSorted().join(",")}} from './${sibling}'`).join("\n");
|
|
1816
2119
|
return {
|
|
1817
2120
|
fileName,
|
|
1818
|
-
code: siblingImports ? `${siblingImports}\n\n${body}` : body
|
|
2121
|
+
code: siblingImports ? `${siblingImports}\n\n${body}` : body,
|
|
2122
|
+
refKinds: schemaRefKinds(group.map((member) => member.schema))
|
|
1819
2123
|
};
|
|
1820
2124
|
});
|
|
1821
2125
|
}
|
|
@@ -1825,24 +2129,23 @@ function schemas(section, output, split, exportTypes, components, readonly) {
|
|
|
1825
2129
|
if (Object.keys(section).length === 0) return "No schemas found";
|
|
1826
2130
|
const abs = path.resolve(process.cwd(), output);
|
|
1827
2131
|
if (split) {
|
|
1828
|
-
const exclude = new Set(["schemas"]);
|
|
2132
|
+
const exclude = /* @__PURE__ */ new Set(["schemas"]);
|
|
1829
2133
|
const outDir = path.join(path.dirname(abs), path.basename(abs, ".ts"));
|
|
1830
2134
|
const files = splitSchemaFiles(section, readonly, exportTypes);
|
|
1831
|
-
const barrelLines = files.map((
|
|
1832
|
-
yield* Effect.all([...files.map((
|
|
1833
|
-
const filePath = path.join(outDir, `${
|
|
1834
|
-
return emit(
|
|
2135
|
+
const barrelLines = files.map((file) => `export * from './${file.fileName}'`).toSorted();
|
|
2136
|
+
yield* Effect.all([...files.map((file) => {
|
|
2137
|
+
const filePath = path.join(outDir, `${file.fileName}.ts`);
|
|
2138
|
+
return emit(file.code === "" ? "" : makeImports(file.code, filePath, components, true, file.refKinds, exclude), path.dirname(filePath), filePath);
|
|
1835
2139
|
}), emit(`${barrelLines.join("\n")}\n`, outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1836
2140
|
return `Generated schemas code written to ${outDir}/*.ts (index.ts included)`;
|
|
1837
2141
|
}
|
|
1838
2142
|
const code = schemasCode(section, readonly, exportTypes);
|
|
1839
2143
|
if (code === "") return "No schemas found";
|
|
1840
|
-
yield* emit(makeImports(code, abs, components, false), path.dirname(abs), abs);
|
|
2144
|
+
yield* emit(makeImports(code, abs, components, false, schemaRefKinds(Object.values(section))), path.dirname(abs), abs);
|
|
1841
2145
|
return `Generated schemas code written to ${output}`;
|
|
1842
2146
|
});
|
|
1843
2147
|
}
|
|
1844
|
-
|
|
1845
|
-
//#region src/core/components/responses.ts
|
|
2148
|
+
// src/core/components/responses.ts
|
|
1846
2149
|
function responses(section, output, split, exportTypes, components, readonly) {
|
|
1847
2150
|
return Effect.gen(function* () {
|
|
1848
2151
|
if (!section) return yield* new GenerateError({ message: "No responses found" });
|
|
@@ -1853,16 +2156,15 @@ function responses(section, output, split, exportTypes, components, readonly) {
|
|
|
1853
2156
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1854
2157
|
const code = responsesCode({ [name]: value }, readonly, exportTypes);
|
|
1855
2158
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1856
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2159
|
+
return emit(makeImports(code, filePath, components, split, responsesRefKinds({ [name]: value })), path.dirname(filePath), filePath);
|
|
1857
2160
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1858
2161
|
return `Generated responses code written to ${outDir}/*.ts (index.ts included)`;
|
|
1859
2162
|
}
|
|
1860
|
-
yield* emit(makeImports(responsesCode(section, readonly, exportTypes), output, components, split), path.dirname(output), output);
|
|
2163
|
+
yield* emit(makeImports(responsesCode(section, readonly, exportTypes), output, components, split, responsesRefKinds(section)), path.dirname(output), output);
|
|
1861
2164
|
return `Generated responses code written to ${output}`;
|
|
1862
2165
|
});
|
|
1863
2166
|
}
|
|
1864
|
-
|
|
1865
|
-
//#region src/core/components/parameters.ts
|
|
2167
|
+
// src/core/components/parameters.ts
|
|
1866
2168
|
function parameters(section, output, split, exportTypes, components, readonly) {
|
|
1867
2169
|
return Effect.gen(function* () {
|
|
1868
2170
|
if (!section) return yield* new GenerateError({ message: "No parameters found" });
|
|
@@ -1873,16 +2175,15 @@ function parameters(section, output, split, exportTypes, components, readonly) {
|
|
|
1873
2175
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1874
2176
|
const code = parametersCode({ [name]: value }, readonly, exportTypes);
|
|
1875
2177
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1876
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2178
|
+
return emit(makeImports(code, filePath, components, split, parametersRefKinds({ [name]: value })), path.dirname(filePath), filePath);
|
|
1877
2179
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1878
2180
|
return `Generated parameters code written to ${outDir}/*.ts (index.ts included)`;
|
|
1879
2181
|
}
|
|
1880
|
-
yield* emit(makeImports(parametersCode(section, readonly, exportTypes), output, components, split), path.dirname(output), output);
|
|
2182
|
+
yield* emit(makeImports(parametersCode(section, readonly, exportTypes), output, components, split, parametersRefKinds(section)), path.dirname(output), output);
|
|
1881
2183
|
return `Generated parameters code written to ${output}`;
|
|
1882
2184
|
});
|
|
1883
2185
|
}
|
|
1884
|
-
|
|
1885
|
-
//#region src/core/components/examples.ts
|
|
2186
|
+
// src/core/components/examples.ts
|
|
1886
2187
|
function examples(section, output, split, components) {
|
|
1887
2188
|
return Effect.gen(function* () {
|
|
1888
2189
|
if (!section) return yield* new GenerateError({ message: "No examples found" });
|
|
@@ -1893,16 +2194,15 @@ function examples(section, output, split, components) {
|
|
|
1893
2194
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1894
2195
|
const code = examplesCode({ [name]: value });
|
|
1895
2196
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1896
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2197
|
+
return emit(makeImports(code, filePath, components, split, stringifiedRefKinds(value)), path.dirname(filePath), filePath);
|
|
1897
2198
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1898
2199
|
return `Generated examples code written to ${outDir}/*.ts (index.ts included)`;
|
|
1899
2200
|
}
|
|
1900
|
-
yield* emit(makeImports(examplesCode(section), output, components, split), path.dirname(output), output);
|
|
2201
|
+
yield* emit(makeImports(examplesCode(section), output, components, split, stringifiedRefKinds(section)), path.dirname(output), output);
|
|
1901
2202
|
return `Generated examples code written to ${output}`;
|
|
1902
2203
|
});
|
|
1903
2204
|
}
|
|
1904
|
-
|
|
1905
|
-
//#region src/core/components/requestBodies.ts
|
|
2205
|
+
// src/core/components/requestBodies.ts
|
|
1906
2206
|
function requestBodies(section, output, split, exportTypes, components, readonly) {
|
|
1907
2207
|
return Effect.gen(function* () {
|
|
1908
2208
|
if (!section) return yield* new GenerateError({ message: "No requestBodies found" });
|
|
@@ -1913,16 +2213,15 @@ function requestBodies(section, output, split, exportTypes, components, readonly
|
|
|
1913
2213
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1914
2214
|
const code = requestBodiesCode({ [name]: value }, readonly, exportTypes);
|
|
1915
2215
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1916
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2216
|
+
return emit(makeImports(code, filePath, components, split, requestBodiesRefKinds({ [name]: value })), path.dirname(filePath), filePath);
|
|
1917
2217
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1918
2218
|
return `Generated requestBodies code written to ${outDir}/*.ts (index.ts included)`;
|
|
1919
2219
|
}
|
|
1920
|
-
yield* emit(makeImports(requestBodiesCode(section, readonly, exportTypes), output, components, split), path.dirname(output), output);
|
|
2220
|
+
yield* emit(makeImports(requestBodiesCode(section, readonly, exportTypes), output, components, split, requestBodiesRefKinds(section)), path.dirname(output), output);
|
|
1921
2221
|
return `Generated requestBodies code written to ${output}`;
|
|
1922
2222
|
});
|
|
1923
2223
|
}
|
|
1924
|
-
|
|
1925
|
-
//#region src/core/components/headers.ts
|
|
2224
|
+
// src/core/components/headers.ts
|
|
1926
2225
|
function headers(section, output, split, exportTypes, components, readonly) {
|
|
1927
2226
|
return Effect.gen(function* () {
|
|
1928
2227
|
if (!section) return yield* new GenerateError({ message: "No headers found" });
|
|
@@ -1933,16 +2232,15 @@ function headers(section, output, split, exportTypes, components, readonly) {
|
|
|
1933
2232
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1934
2233
|
const code = headersCode({ [name]: value }, readonly, exportTypes);
|
|
1935
2234
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1936
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2235
|
+
return emit(makeImports(code, filePath, components, split, headersRefKinds({ [name]: value })), path.dirname(filePath), filePath);
|
|
1937
2236
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1938
2237
|
return `Generated headers code written to ${outDir}/*.ts (index.ts included)`;
|
|
1939
2238
|
}
|
|
1940
|
-
yield* emit(makeImports(headersCode(section, readonly, exportTypes), output, components, split), path.dirname(output), output);
|
|
2239
|
+
yield* emit(makeImports(headersCode(section, readonly, exportTypes), output, components, split, headersRefKinds(section)), path.dirname(output), output);
|
|
1941
2240
|
return `Generated headers code written to ${output}`;
|
|
1942
2241
|
});
|
|
1943
2242
|
}
|
|
1944
|
-
|
|
1945
|
-
//#region src/core/components/securitySchemes.ts
|
|
2243
|
+
// src/core/components/securitySchemes.ts
|
|
1946
2244
|
function securitySchemes(section, output, split, components) {
|
|
1947
2245
|
return Effect.gen(function* () {
|
|
1948
2246
|
if (!section) return yield* new GenerateError({ message: "No securitySchemes found" });
|
|
@@ -1953,16 +2251,15 @@ function securitySchemes(section, output, split, components) {
|
|
|
1953
2251
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1954
2252
|
const code = securitySchemesCode({ [name]: value });
|
|
1955
2253
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1956
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2254
|
+
return emit(makeImports(code, filePath, components, split, stringifiedRefKinds(value)), path.dirname(filePath), filePath);
|
|
1957
2255
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1958
2256
|
return `Generated securitySchemes code written to ${outDir}/*.ts (index.ts included)`;
|
|
1959
2257
|
}
|
|
1960
|
-
yield* emit(makeImports(securitySchemesCode(section), output, components, split), path.dirname(output), output);
|
|
2258
|
+
yield* emit(makeImports(securitySchemesCode(section), output, components, split, stringifiedRefKinds(section)), path.dirname(output), output);
|
|
1961
2259
|
return `Generated securitySchemes code written to ${output}`;
|
|
1962
2260
|
});
|
|
1963
2261
|
}
|
|
1964
|
-
|
|
1965
|
-
//#region src/core/components/links.ts
|
|
2262
|
+
// src/core/components/links.ts
|
|
1966
2263
|
function links(section, output, split, components) {
|
|
1967
2264
|
return Effect.gen(function* () {
|
|
1968
2265
|
if (!section) return yield* new GenerateError({ message: "No links found" });
|
|
@@ -1973,16 +2270,15 @@ function links(section, output, split, components) {
|
|
|
1973
2270
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1974
2271
|
const code = linksCode({ [name]: value });
|
|
1975
2272
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1976
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2273
|
+
return emit(makeImports(code, filePath, components, split, stringifiedRefKinds(value)), path.dirname(filePath), filePath);
|
|
1977
2274
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1978
2275
|
return `Generated links code written to ${outDir}/*.ts (index.ts included)`;
|
|
1979
2276
|
}
|
|
1980
|
-
yield* emit(makeImports(linksCode(section), output, components, split), path.dirname(output), output);
|
|
2277
|
+
yield* emit(makeImports(linksCode(section), output, components, split, stringifiedRefKinds(section)), path.dirname(output), output);
|
|
1981
2278
|
return `Generated links code written to ${output}`;
|
|
1982
2279
|
});
|
|
1983
2280
|
}
|
|
1984
|
-
|
|
1985
|
-
//#region src/core/components/callbacks.ts
|
|
2281
|
+
// src/core/components/callbacks.ts
|
|
1986
2282
|
function callbacks(section, output, split, components) {
|
|
1987
2283
|
return Effect.gen(function* () {
|
|
1988
2284
|
if (!section) return yield* new GenerateError({ message: "No callbacks found" });
|
|
@@ -1993,16 +2289,15 @@ function callbacks(section, output, split, components) {
|
|
|
1993
2289
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
1994
2290
|
const code = callbacksCode({ [name]: value });
|
|
1995
2291
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
1996
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2292
|
+
return emit(makeImports(code, filePath, components, split, stringifiedRefKinds(value)), path.dirname(filePath), filePath);
|
|
1997
2293
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
1998
2294
|
return `Generated callbacks code written to ${outDir}/*.ts (index.ts included)`;
|
|
1999
2295
|
}
|
|
2000
|
-
yield* emit(makeImports(callbacksCode(section), output, components, split), path.dirname(output), output);
|
|
2296
|
+
yield* emit(makeImports(callbacksCode(section), output, components, split, stringifiedRefKinds(section)), path.dirname(output), output);
|
|
2001
2297
|
return `Generated callbacks code written to ${output}`;
|
|
2002
2298
|
});
|
|
2003
2299
|
}
|
|
2004
|
-
|
|
2005
|
-
//#region src/core/components/pathItems.ts
|
|
2300
|
+
// src/core/components/pathItems.ts
|
|
2006
2301
|
function pathItems(section, output, split, components) {
|
|
2007
2302
|
return Effect.gen(function* () {
|
|
2008
2303
|
if (!section) return yield* new GenerateError({ message: "No pathItems found" });
|
|
@@ -2013,16 +2308,15 @@ function pathItems(section, output, split, components) {
|
|
|
2013
2308
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
2014
2309
|
const code = pathItemsCode({ [name]: value });
|
|
2015
2310
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
2016
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2311
|
+
return emit(makeImports(code, filePath, components, split, stringifiedRefKinds(value)), path.dirname(filePath), filePath);
|
|
2017
2312
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
2018
2313
|
return `Generated pathItems code written to ${outDir}/*.ts (index.ts included)`;
|
|
2019
2314
|
}
|
|
2020
|
-
yield* emit(makeImports(pathItemsCode(section), output, components, split), path.dirname(output), output);
|
|
2315
|
+
yield* emit(makeImports(pathItemsCode(section), output, components, split, stringifiedRefKinds(section)), path.dirname(output), output);
|
|
2021
2316
|
return `Generated pathItems code written to ${output}`;
|
|
2022
2317
|
});
|
|
2023
2318
|
}
|
|
2024
|
-
|
|
2025
|
-
//#region src/core/components/mediaTypes.ts
|
|
2319
|
+
// src/core/components/mediaTypes.ts
|
|
2026
2320
|
function mediaTypes(section, output, split, exportTypes, components, readonly) {
|
|
2027
2321
|
return Effect.gen(function* () {
|
|
2028
2322
|
if (!section) return yield* new GenerateError({ message: "No mediaTypes found" });
|
|
@@ -2033,16 +2327,15 @@ function mediaTypes(section, output, split, exportTypes, components, readonly) {
|
|
|
2033
2327
|
yield* Effect.all([...entries.map(([name, value]) => {
|
|
2034
2328
|
const code = mediaTypesCode({ [name]: value }, readonly, exportTypes);
|
|
2035
2329
|
const filePath = path.join(outDir, `${uncapitalize(name)}.ts`);
|
|
2036
|
-
return emit(makeImports(code, filePath, components, split), path.dirname(filePath), filePath);
|
|
2330
|
+
return emit(makeImports(code, filePath, components, split, mediaTypesRefKinds({ [name]: value })), path.dirname(filePath), filePath);
|
|
2037
2331
|
}), emit(makeBarrel(section), outDir, path.join(outDir, "index.ts"))], { concurrency: "unbounded" });
|
|
2038
2332
|
return `Generated mediaTypes code written to ${outDir}/*.ts (index.ts included)`;
|
|
2039
2333
|
}
|
|
2040
|
-
yield* emit(makeImports(mediaTypesCode(section, readonly, exportTypes), output, components, split), path.dirname(output), output);
|
|
2334
|
+
yield* emit(makeImports(mediaTypesCode(section, readonly, exportTypes), output, components, split, mediaTypesRefKinds(section)), path.dirname(output), output);
|
|
2041
2335
|
return `Generated mediaTypes code written to ${output}`;
|
|
2042
2336
|
});
|
|
2043
2337
|
}
|
|
2044
|
-
|
|
2045
|
-
//#region src/core/eden/index.ts
|
|
2338
|
+
// src/core/eden/index.ts
|
|
2046
2339
|
function makeOperation(pathStr, method, operation, client) {
|
|
2047
2340
|
const funcName = toSafeIdentifier(resolveOperationId(operation, method, pathStr));
|
|
2048
2341
|
const { callExpr, methodHostTypeExpr, paramArgs } = edenChain(pathStr, client, method);
|
|
@@ -2052,7 +2345,7 @@ function eden(openAPI, output, importPath, client, basePath) {
|
|
|
2052
2345
|
return Effect.gen(function* () {
|
|
2053
2346
|
const prefix = basePath && basePath !== "/" ? basePath : "";
|
|
2054
2347
|
const operations = [];
|
|
2055
|
-
for (const [pathStr, pathItem] of Object.entries(openAPI.paths)) {
|
|
2348
|
+
for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
|
|
2056
2349
|
if (!pathItem) continue;
|
|
2057
2350
|
for (const method of HTTP_METHODS) {
|
|
2058
2351
|
const operation = pathItem[method];
|
|
@@ -2065,8 +2358,7 @@ function eden(openAPI, output, importPath, client, basePath) {
|
|
|
2065
2358
|
return `Generated eden code written to ${output}`;
|
|
2066
2359
|
});
|
|
2067
2360
|
}
|
|
2068
|
-
|
|
2069
|
-
//#region src/generator/app/index.ts
|
|
2361
|
+
// src/generator/app/index.ts
|
|
2070
2362
|
function exportName(name) {
|
|
2071
2363
|
return toSafeIdentifier(name);
|
|
2072
2364
|
}
|
|
@@ -2089,8 +2381,7 @@ if (import.meta.main) {
|
|
|
2089
2381
|
}`}
|
|
2090
2382
|
`;
|
|
2091
2383
|
}
|
|
2092
|
-
|
|
2093
|
-
//#region src/generator/controller/index.ts
|
|
2384
|
+
// src/generator/controller/index.ts
|
|
2094
2385
|
function schemaIdent(name) {
|
|
2095
2386
|
return `${pascalCase(name)}Schema`;
|
|
2096
2387
|
}
|
|
@@ -2118,7 +2409,7 @@ function controllerFile(tag, routes, componentImports = [], componentNames = /*
|
|
|
2118
2409
|
route.bodyRef ? "body" : null
|
|
2119
2410
|
]);
|
|
2120
2411
|
const handler = `${argKeys.length > 0 ? `({${argKeys.join(",")}})` : "()"}=>{}`;
|
|
2121
|
-
const responseEntries = route.responses.map((
|
|
2412
|
+
const responseEntries = route.responses.map((response) => `${safeStatusKey(response.status)}:${renderResponseValue(response.schema)}`).join(",");
|
|
2122
2413
|
const detail = join([
|
|
2123
2414
|
`tags:${JSON.stringify(route.tags)}`,
|
|
2124
2415
|
route.summary ? `summary:${JSON.stringify(route.summary)}` : null,
|
|
@@ -2148,153 +2439,200 @@ ${componentImport}import {${className}} from './model'
|
|
|
2148
2439
|
export const ${toSafeIdentifier(tag)}=new Elysia()${componentRegister}${chain}
|
|
2149
2440
|
`;
|
|
2150
2441
|
}
|
|
2151
|
-
|
|
2152
|
-
//#region src/generator/model/index.ts
|
|
2442
|
+
// src/generator/model/index.ts
|
|
2153
2443
|
function modelFile(tag, schemas, componentNames = /* @__PURE__ */ new Set(), schemasImportPath = "../../components", readonlyMode) {
|
|
2154
2444
|
const className = `${pascalCase(tag)}Model`;
|
|
2155
2445
|
const referenced = /* @__PURE__ */ new Set();
|
|
2156
|
-
for (const { schema } of schemas) for (const
|
|
2446
|
+
for (const { schema } of schemas) for (const ref of collectSchemaRefs$1(schema)) if (componentNames.has(ref)) referenced.add(ref);
|
|
2157
2447
|
const importedIdents = [...referenced].toSorted().map((n) => `${pascalCase(n)}Schema`);
|
|
2158
2448
|
const componentImport = importedIdents.length > 0 ? `import {${importedIdents.join(",")}} from '${schemasImportPath}'\n` : "";
|
|
2159
|
-
const entries = schemas.map(({ name, schema,
|
|
2449
|
+
const entries = schemas.map(({ name, schema, context }) => `${name}:${readonly(typebox(schema, context), readonlyMode)}`).join(",");
|
|
2160
2450
|
if (entries === "") return `${componentImport}
|
|
2161
2451
|
export const ${className}={} as const
|
|
2162
2452
|
|
|
2163
2453
|
export type ${className}=typeof ${className}
|
|
2164
2454
|
`;
|
|
2165
2455
|
return `import {t,type UnwrapSchema} from 'elysia'
|
|
2166
|
-
${componentImport}
|
|
2456
|
+
${/\bValue\.Decode\(/u.test(entries) ? `import {Value} from '@sinclair/typebox/value'\n` : ""}${componentImport}
|
|
2167
2457
|
export const ${className}={${entries}} as const
|
|
2168
2458
|
|
|
2169
2459
|
export type ${className}={[k in keyof typeof ${className}]:UnwrapSchema<(typeof ${className})[k]>}
|
|
2170
2460
|
`;
|
|
2171
2461
|
}
|
|
2172
|
-
|
|
2173
|
-
//#region src/generator/service/index.ts
|
|
2462
|
+
// src/generator/service/index.ts
|
|
2174
2463
|
function serviceFile(tag) {
|
|
2175
2464
|
return `export abstract class ${pascalCase(tag)}{}
|
|
2176
2465
|
`;
|
|
2177
2466
|
}
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
const first = stmt.getDeclarations()[0];
|
|
2191
|
-
return first ? `var:${first.getName()}` : null;
|
|
2192
|
-
}
|
|
2193
|
-
if (Node.isTypeAliasDeclaration(stmt)) {
|
|
2194
|
-
const name = stmt.getName();
|
|
2195
|
-
return name ? `type:${name}` : null;
|
|
2196
|
-
}
|
|
2197
|
-
if (Node.isInterfaceDeclaration(stmt)) {
|
|
2198
|
-
const name = stmt.getName();
|
|
2199
|
-
return name ? `interface:${name}` : null;
|
|
2200
|
-
}
|
|
2201
|
-
if (Node.isIfStatement(stmt)) return `if:${stmt.getExpression().getText().trim()}`;
|
|
2202
|
-
if (Node.isExpressionStatement(stmt)) {
|
|
2203
|
-
const expr = stmt.getExpression();
|
|
2204
|
-
if (Node.isCallExpression(expr)) {
|
|
2205
|
-
const callee = expr.getExpression();
|
|
2206
|
-
if (Node.isIdentifier(callee) && callee.getText() === "describe") {
|
|
2207
|
-
const first = expr.getArguments()[0];
|
|
2208
|
-
if (first && Node.isStringLiteral(first)) return `describe:${first.getLiteralText()}`;
|
|
2209
|
-
}
|
|
2210
|
-
const argSig = expr.getArguments().map((a) => a.getText().trim().replace(/;$/u, "")).join(",");
|
|
2211
|
-
return `expr:${callee.getText().trim()}(${argSig})`;
|
|
2212
|
-
}
|
|
2213
|
-
}
|
|
2214
|
-
return null;
|
|
2467
|
+
// src/merge/syntax.ts
|
|
2468
|
+
function parseSource(code) {
|
|
2469
|
+
const { program, comments, errors } = parseSync("module.ts", code, {
|
|
2470
|
+
lang: "ts",
|
|
2471
|
+
sourceType: "module"
|
|
2472
|
+
});
|
|
2473
|
+
return {
|
|
2474
|
+
code,
|
|
2475
|
+
program,
|
|
2476
|
+
comments,
|
|
2477
|
+
errors: errors.map((error) => error.message)
|
|
2478
|
+
};
|
|
2215
2479
|
}
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
function stmtText(s) {
|
|
2219
|
-
if (Node.isJSDocable(s)) {
|
|
2220
|
-
const docs = s.getJsDocs().map((d) => d.getText()).join("\n");
|
|
2221
|
-
if (docs.length > 0) return `${docs}\n${s.getText()}`;
|
|
2222
|
-
}
|
|
2223
|
-
return s.getText();
|
|
2480
|
+
function textOf(code, node) {
|
|
2481
|
+
return code.slice(node.start, node.end);
|
|
2224
2482
|
}
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
if (
|
|
2231
|
-
|
|
2232
|
-
return
|
|
2483
|
+
/**
|
|
2484
|
+
* A top-level statement with its `export` taken off: `export const x = …` is the variable
|
|
2485
|
+
* declaration, `export default class X {}` the class. Any other statement is itself.
|
|
2486
|
+
*/
|
|
2487
|
+
function declarationOf(statement) {
|
|
2488
|
+
if (statement.type === "ExportNamedDeclaration" && statement.declaration !== null) return statement.declaration;
|
|
2489
|
+
if (statement.type === "ExportDefaultDeclaration" && (statement.declaration.type === "FunctionDeclaration" || statement.declaration.type === "ClassDeclaration")) return statement.declaration;
|
|
2490
|
+
return statement;
|
|
2233
2491
|
}
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2492
|
+
/**
|
|
2493
|
+
* The text of the statement at `index`, with the comments written above it.
|
|
2494
|
+
*
|
|
2495
|
+
* A comment belongs to the statement below it when it sits on a line of its own between the end
|
|
2496
|
+
* of the previous top-level node and the statement; a comment that trails the previous node on
|
|
2497
|
+
* its own line stays with that node and is not repeated here.
|
|
2498
|
+
*/
|
|
2499
|
+
function statementText(source, index) {
|
|
2500
|
+
const { code, comments, program } = source;
|
|
2501
|
+
const statement = program.body[index];
|
|
2502
|
+
if (!statement) return "";
|
|
2503
|
+
const previousEnd = index === 0 ? 0 : program.body[index - 1]?.end ?? 0;
|
|
2504
|
+
const leading = comments.find((comment) => comment.start >= previousEnd && comment.end <= statement.start && (previousEnd === 0 || code.slice(previousEnd, comment.start).includes("\n")));
|
|
2505
|
+
return code.slice(leading ? leading.start : statement.start, statement.end);
|
|
2506
|
+
}
|
|
2507
|
+
// src/merge/statement-key.ts
|
|
2508
|
+
/**
|
|
2509
|
+
* The key a top-level statement is merged by, or `null` for one that is never matched across the
|
|
2510
|
+
* two files and is kept from wherever it came.
|
|
2511
|
+
*
|
|
2512
|
+
* The prefix encodes the merge semantics: a `class:`, `fn:`, `var:`, `type:`, `interface:`, `if:`
|
|
2513
|
+
* or `describe:` statement in both files is taken from the existing file, so the user's edits
|
|
2514
|
+
* win; an `expr:` statement — a bare call such as `console.log(…)` — is emitted on the first run
|
|
2515
|
+
* and then belongs to the user, so one the user deleted stays deleted.
|
|
2516
|
+
*/
|
|
2517
|
+
function statementKey(code, statement) {
|
|
2518
|
+
const node = declarationOf(statement);
|
|
2519
|
+
if (node.type === "ClassDeclaration") return node.id ? `class:${node.id.name}` : null;
|
|
2520
|
+
if (node.type === "FunctionDeclaration") return node.id ? `fn:${node.id.name}` : null;
|
|
2521
|
+
if (node.type === "VariableDeclaration") {
|
|
2522
|
+
const first = node.declarations[0];
|
|
2523
|
+
if (!first) return null;
|
|
2524
|
+
return `var:${first.id.type === "Identifier" ? first.id.name : textOf(code, first.id)}`;
|
|
2525
|
+
}
|
|
2526
|
+
if (node.type === "TSTypeAliasDeclaration") return `type:${node.id.name}`;
|
|
2527
|
+
if (node.type === "TSInterfaceDeclaration") return `interface:${node.id.name}`;
|
|
2528
|
+
if (node.type === "IfStatement") return `if:${textOf(code, node.test).trim()}`;
|
|
2529
|
+
if (node.type !== "ExpressionStatement") return null;
|
|
2530
|
+
const expression = node.expression;
|
|
2531
|
+
if (expression.type !== "CallExpression") return null;
|
|
2532
|
+
const { callee } = expression;
|
|
2533
|
+
const [first] = expression.arguments;
|
|
2534
|
+
if (callee.type === "Identifier" && callee.name === "describe" && first?.type === "Literal" && typeof first.value === "string") return `describe:${first.value}`;
|
|
2535
|
+
const argSig = expression.arguments.map((argument) => textOf(code, argument).trim().replace(/;$/u, "")).join(",");
|
|
2536
|
+
return `expr:${textOf(code, callee).trim()}(${argSig})`;
|
|
2537
|
+
}
|
|
2538
|
+
// src/merge/index.ts
|
|
2539
|
+
function isImport(statement) {
|
|
2540
|
+
return statement.type === "ImportDeclaration";
|
|
2541
|
+
}
|
|
2542
|
+
/** The names an import binds as the generated file would claim them: `a` in `{ a as b }`. */
|
|
2543
|
+
function importedNames(source, declaration) {
|
|
2544
|
+
return declaration.specifiers.map((specifier) => specifier.type === "ImportSpecifier" ? textOf(source.code, specifier.imported) : specifier.local.name);
|
|
2545
|
+
}
|
|
2546
|
+
/**
|
|
2547
|
+
* The import block of the merged file: every import of the generated file, then every import only
|
|
2548
|
+
* the existing file has, in that order. The existing file's import wins for a module both import,
|
|
2549
|
+
* and an existing import whose names the generated file now takes from another module is pruned
|
|
2550
|
+
* of those names, or dropped when nothing is left.
|
|
2551
|
+
*/
|
|
2552
|
+
function mergeImports(existing, generated) {
|
|
2553
|
+
const generatedImports = generated.program.body.filter(isImport);
|
|
2554
|
+
const claimedByGenerated = new Set(generatedImports.flatMap((declaration) => importedNames(generated, declaration)));
|
|
2240
2555
|
const importBySpec = /* @__PURE__ */ new Map();
|
|
2241
|
-
for (const
|
|
2242
|
-
for (const
|
|
2243
|
-
const spec =
|
|
2556
|
+
for (const declaration of generatedImports) importBySpec.set(declaration.source.value, textOf(generated.code, declaration));
|
|
2557
|
+
for (const declaration of existing.program.body.filter(isImport)) {
|
|
2558
|
+
const spec = declaration.source.value;
|
|
2559
|
+
const text = textOf(existing.code, declaration);
|
|
2244
2560
|
if (importBySpec.has(spec)) {
|
|
2245
|
-
importBySpec.set(spec,
|
|
2561
|
+
importBySpec.set(spec, text);
|
|
2246
2562
|
continue;
|
|
2247
2563
|
}
|
|
2248
|
-
const
|
|
2249
|
-
const
|
|
2250
|
-
const
|
|
2251
|
-
const
|
|
2252
|
-
const
|
|
2253
|
-
const
|
|
2564
|
+
const specifiers = declaration.specifiers;
|
|
2565
|
+
const named = specifiers.filter((specifier) => specifier.type === "ImportSpecifier");
|
|
2566
|
+
const def = specifiers.find((specifier) => specifier.type === "ImportDefaultSpecifier");
|
|
2567
|
+
const ns = specifiers.find((specifier) => specifier.type === "ImportNamespaceSpecifier");
|
|
2568
|
+
const survivingNamed = named.filter((specifier) => !claimedByGenerated.has(textOf(existing.code, specifier.imported)));
|
|
2569
|
+
const defClaimed = def ? claimedByGenerated.has(def.local.name) : false;
|
|
2570
|
+
const nsClaimed = ns ? claimedByGenerated.has(ns.local.name) : false;
|
|
2254
2571
|
if (survivingNamed.length === named.length && !defClaimed && !nsClaimed) {
|
|
2255
|
-
importBySpec.set(spec,
|
|
2572
|
+
importBySpec.set(spec, text);
|
|
2256
2573
|
continue;
|
|
2257
2574
|
}
|
|
2258
2575
|
const clauseParts = [
|
|
2259
|
-
def && !defClaimed ? def.
|
|
2260
|
-
ns && !nsClaimed ? `* as ${ns.
|
|
2261
|
-
survivingNamed.length > 0 ? `{${survivingNamed.map((
|
|
2576
|
+
def && !defClaimed ? def.local.name : "",
|
|
2577
|
+
ns && !nsClaimed ? `* as ${ns.local.name}` : "",
|
|
2578
|
+
survivingNamed.length > 0 ? `{${survivingNamed.map((specifier) => textOf(existing.code, specifier)).join(",")}}` : ""
|
|
2262
2579
|
].filter(Boolean);
|
|
2263
2580
|
if (clauseParts.length === 0) continue;
|
|
2264
2581
|
importBySpec.set(spec, `import ${clauseParts.join(",")} from '${spec}'`);
|
|
2265
2582
|
}
|
|
2266
|
-
|
|
2267
|
-
|
|
2583
|
+
return [...importBySpec.values()];
|
|
2584
|
+
}
|
|
2585
|
+
/** Every top-level statement that is not an import, with its key and its text. */
|
|
2586
|
+
function keyedStatements(source) {
|
|
2587
|
+
return source.program.body.flatMap((statement, index) => isImport(statement) ? [] : [{
|
|
2588
|
+
key: statementKey(source.code, statement),
|
|
2589
|
+
text: statementText(source, index)
|
|
2590
|
+
}]);
|
|
2591
|
+
}
|
|
2592
|
+
/**
|
|
2593
|
+
* Merges the code the generator produced into what is already on disk, so that regenerating never
|
|
2594
|
+
* discards the user's work.
|
|
2595
|
+
*
|
|
2596
|
+
* Imports are merged into one block (see `mergeImports`). Every other top-level statement is matched by its
|
|
2597
|
+
* `statementKey`: a statement in both files is taken from the existing one, a generated statement
|
|
2598
|
+
* the existing file lacks is added in the generator's order, and an existing statement the
|
|
2599
|
+
* generator no longer emits is kept after them. The exception is an `expr:` statement, a bare call
|
|
2600
|
+
* such as the startup `console.log`: it is emitted only when the existing file holds no statement
|
|
2601
|
+
* at all, so that deleting it is an edit that lasts.
|
|
2602
|
+
*
|
|
2603
|
+
* Text is sliced from the source rather than printed from the tree, so the user's comments and
|
|
2604
|
+
* formatting come through unchanged. An existing file that does not parse is returned exactly as
|
|
2605
|
+
* it is: its tree is empty, and a merge against it would write the generated code over the edit
|
|
2606
|
+
* that broke it.
|
|
2607
|
+
*/
|
|
2608
|
+
function mergeSource(existing, generated) {
|
|
2609
|
+
const existingSource = parseSource(existing);
|
|
2610
|
+
if (existingSource.errors.length > 0) return existing;
|
|
2611
|
+
const generatedSource = parseSource(generated);
|
|
2612
|
+
const existingStmts = keyedStatements(existingSource);
|
|
2613
|
+
const generatedStmts = keyedStatements(generatedSource);
|
|
2268
2614
|
const existingByKey = /* @__PURE__ */ new Map();
|
|
2269
|
-
for (const
|
|
2270
|
-
const k = statementKey(s);
|
|
2271
|
-
if (k) existingByKey.set(k, s);
|
|
2272
|
-
}
|
|
2615
|
+
for (const { key, text } of existingStmts) if (key !== null) existingByKey.set(key, text);
|
|
2273
2616
|
const usedExistingKeys = /* @__PURE__ */ new Set();
|
|
2274
2617
|
const isFirstEmit = existingStmts.length === 0;
|
|
2275
|
-
const fromGenerated = generatedStmts.flatMap((
|
|
2276
|
-
const
|
|
2277
|
-
if (
|
|
2278
|
-
usedExistingKeys.add(
|
|
2279
|
-
|
|
2280
|
-
return [existingStmt ? stmtText(existingStmt) : stmtText(s)];
|
|
2618
|
+
const fromGenerated = generatedStmts.flatMap(({ key, text }) => {
|
|
2619
|
+
const existingText = key === null ? void 0 : existingByKey.get(key);
|
|
2620
|
+
if (key !== null && existingText !== void 0) {
|
|
2621
|
+
usedExistingKeys.add(key);
|
|
2622
|
+
return [existingText];
|
|
2281
2623
|
}
|
|
2282
|
-
if (!isFirstEmit &&
|
|
2283
|
-
return [
|
|
2624
|
+
if (!isFirstEmit && key?.startsWith("expr:")) return [];
|
|
2625
|
+
return [text];
|
|
2284
2626
|
});
|
|
2285
|
-
const fromExistingOnly = existingStmts.filter((
|
|
2286
|
-
const k = statementKey(s);
|
|
2287
|
-
return k ? !usedExistingKeys.has(k) : true;
|
|
2288
|
-
}).map(stmtText);
|
|
2627
|
+
const fromExistingOnly = existingStmts.filter(({ key }) => key === null || !usedExistingKeys.has(key)).map(({ text }) => text);
|
|
2289
2628
|
return [
|
|
2290
|
-
|
|
2629
|
+
mergeImports(existingSource, generatedSource).join("\n"),
|
|
2291
2630
|
"",
|
|
2292
2631
|
[...fromGenerated, ...fromExistingOnly].join("\n\n"),
|
|
2293
2632
|
""
|
|
2294
2633
|
].join("\n");
|
|
2295
2634
|
}
|
|
2296
|
-
|
|
2297
|
-
//#region src/core/elysia/index.ts
|
|
2635
|
+
// src/core/elysia/index.ts
|
|
2298
2636
|
/** Keeps whatever the user already wrote in `output` when regenerating over it. */
|
|
2299
2637
|
function merged(code, output) {
|
|
2300
2638
|
return Effect.gen(function* () {
|
|
@@ -2358,8 +2696,7 @@ function elysia(api, options = {}) {
|
|
|
2358
2696
|
return `Generated ${resources.length} module(s) (${resources.join(", ")}) → ${path.posix.dirname(appOutput)}/`;
|
|
2359
2697
|
});
|
|
2360
2698
|
}
|
|
2361
|
-
|
|
2362
|
-
//#region src/helper/query.ts
|
|
2699
|
+
// src/helper/query.ts
|
|
2363
2700
|
const QUERY_OMIT_KEYS = `'queryKey' | 'queryFn'`;
|
|
2364
2701
|
const INFINITE_OMIT_KEYS = `'queryKey' | 'queryFn' | 'initialPageParam' | 'getNextPageParam'`;
|
|
2365
2702
|
const MUTATION_OMIT_KEYS = `'mutationFn'`;
|
|
@@ -2487,19 +2824,19 @@ function queryNames(config, method, pathStr) {
|
|
|
2487
2824
|
};
|
|
2488
2825
|
}
|
|
2489
2826
|
const PLAIN = {
|
|
2490
|
-
paramSig: (
|
|
2491
|
-
paramRead: (
|
|
2492
|
-
paramPass: (
|
|
2827
|
+
paramSig: (target) => target.params.map((p) => `${p.name}: ${p.type}`),
|
|
2828
|
+
paramRead: (target) => target.params.map((p) => p.name),
|
|
2829
|
+
paramPass: (target) => target.params.map((p) => p.name)
|
|
2493
2830
|
};
|
|
2494
2831
|
const THUNK = {
|
|
2495
|
-
paramSig: (
|
|
2496
|
-
paramRead: (
|
|
2497
|
-
paramPass: (
|
|
2832
|
+
paramSig: (target) => target.params.map((p) => `${p.name}: () => ${p.type}`),
|
|
2833
|
+
paramRead: (target) => target.params.map((p) => `${p.name}()`),
|
|
2834
|
+
paramPass: (target) => target.params.map((p) => `${p.name}()`)
|
|
2498
2835
|
};
|
|
2499
2836
|
const REF = {
|
|
2500
|
-
paramSig: (
|
|
2501
|
-
paramRead: (
|
|
2502
|
-
paramPass: (
|
|
2837
|
+
paramSig: (target) => target.params.map((p) => `${p.name}: MaybeRefOrGetter<${p.type}>`),
|
|
2838
|
+
paramRead: (target) => target.params.map((p) => `toValue(${p.name})`),
|
|
2839
|
+
paramPass: (target) => target.params.map((p) => p.name)
|
|
2503
2840
|
};
|
|
2504
2841
|
/** How the key getters and factories of a library spell the path parameters. */
|
|
2505
2842
|
function baseSpelling(config) {
|
|
@@ -2807,7 +3144,7 @@ function headerCode(config, client, importPath, body, fetchTypes, schemasImport)
|
|
|
2807
3144
|
function makeQueryHooks(openAPI, output, importPath, config, client, basePath, schemasImport = "./components/schemas") {
|
|
2808
3145
|
return Effect.gen(function* () {
|
|
2809
3146
|
const prefix = basePath && basePath !== "/" ? basePath : "";
|
|
2810
|
-
const operations = Object.entries(openAPI.paths).flatMap(([pathStr, pathItem]) => pathItem ? HTTP_METHODS.flatMap((method) => {
|
|
3147
|
+
const operations = Object.entries(openAPI.paths ?? {}).flatMap(([pathStr, pathItem]) => pathItem ? HTTP_METHODS.flatMap((method) => {
|
|
2811
3148
|
const rawOperation = pathItem[method];
|
|
2812
3149
|
if (!rawOperation) return [];
|
|
2813
3150
|
const operation = resolveOperation(rawOperation, openAPI.components);
|
|
@@ -2819,8 +3156,7 @@ function makeQueryHooks(openAPI, output, importPath, config, client, basePath, s
|
|
|
2819
3156
|
return `Generated ${config.label} code written to ${output}`;
|
|
2820
3157
|
});
|
|
2821
3158
|
}
|
|
2822
|
-
|
|
2823
|
-
//#region src/core/hooks/index.ts
|
|
3159
|
+
// src/core/hooks/index.ts
|
|
2824
3160
|
const QUERY_CLIENT_TAIL = {
|
|
2825
3161
|
name: "queryClient",
|
|
2826
3162
|
query: "QueryClient",
|
|
@@ -2862,6 +3198,11 @@ const TANSTACK = {
|
|
|
2862
3198
|
suspenseInfiniteOptionsType: "UseSuspenseInfiniteQueryOptions",
|
|
2863
3199
|
hookTail: QUERY_CLIENT_TAIL
|
|
2864
3200
|
};
|
|
3201
|
+
/**
|
|
3202
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
3203
|
+
*
|
|
3204
|
+
* @internal
|
|
3205
|
+
*/
|
|
2865
3206
|
const HOOK_CONFIGS = {
|
|
2866
3207
|
swr: {
|
|
2867
3208
|
label: "swr",
|
|
@@ -2948,8 +3289,7 @@ function hooks(openAPI, output, importPath, library, options) {
|
|
|
2948
3289
|
}) : void 0);
|
|
2949
3290
|
return makeQueryHooks(openAPI, output, importPath, HOOK_CONFIGS[library], options.client, options.basePath, schemasImport);
|
|
2950
3291
|
}
|
|
2951
|
-
|
|
2952
|
-
//#region src/helper/faker.ts
|
|
3292
|
+
// src/helper/faker.ts
|
|
2953
3293
|
function hasNumericConstraint(schema) {
|
|
2954
3294
|
return schema.minimum !== void 0 || schema.maximum !== void 0 || schema.exclusiveMinimum !== void 0 || schema.exclusiveMaximum !== void 0 || schema.multipleOf !== void 0;
|
|
2955
3295
|
}
|
|
@@ -2992,7 +3332,7 @@ function arrayLengthExpr(schema, options = {}) {
|
|
|
2992
3332
|
const NON_EXISTENT_CEIL = 2147483647;
|
|
2993
3333
|
function primaryType$2(schema) {
|
|
2994
3334
|
const type = schema.type;
|
|
2995
|
-
if (Array.isArray(type)) return type.find((
|
|
3335
|
+
if (Array.isArray(type)) return type.find((kind) => kind !== "null") ?? type[0];
|
|
2996
3336
|
return type;
|
|
2997
3337
|
}
|
|
2998
3338
|
function nonExistentNumber(schema, isInt) {
|
|
@@ -3042,11 +3382,15 @@ function nonExistentPathValue(schema) {
|
|
|
3042
3382
|
value: nonExistentStringLiteral(schema)
|
|
3043
3383
|
};
|
|
3044
3384
|
}
|
|
3045
|
-
|
|
3046
|
-
//#region src/generator/faker/index.ts
|
|
3385
|
+
// src/generator/faker/index.ts
|
|
3047
3386
|
function safeObjectKey(key) {
|
|
3048
3387
|
return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key) ? key : JSON.stringify(key);
|
|
3049
3388
|
}
|
|
3389
|
+
/**
|
|
3390
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
3391
|
+
*
|
|
3392
|
+
* @internal
|
|
3393
|
+
*/
|
|
3050
3394
|
function mockName(schemaName) {
|
|
3051
3395
|
return `mock${schemaName.replaceAll(".", "").replaceAll(/[^A-Za-z0-9_$]/gu, "_")}`;
|
|
3052
3396
|
}
|
|
@@ -3141,10 +3485,10 @@ function isHintCompatible(type, expr) {
|
|
|
3141
3485
|
return false;
|
|
3142
3486
|
}
|
|
3143
3487
|
function propertyNameHint(propertyName) {
|
|
3144
|
-
return lookup(PROPERTY_NAME_TO_FAKER, propertyName) ?? lookup(PROPERTY_NAME_TO_FAKER, propertyName.replaceAll(/[_-]+([a-zA-Z0-9])/gu, (_,
|
|
3488
|
+
return lookup(PROPERTY_NAME_TO_FAKER, propertyName) ?? lookup(PROPERTY_NAME_TO_FAKER, propertyName.replaceAll(/[_-]+([a-zA-Z0-9])/gu, (_, letter) => letter.toUpperCase()));
|
|
3145
3489
|
}
|
|
3146
3490
|
function primaryType$1(type) {
|
|
3147
|
-
if (isTypeArray(type)) return type.find((
|
|
3491
|
+
if (isTypeArray(type)) return type.find((kind) => kind !== "null") ?? type[0];
|
|
3148
3492
|
return type;
|
|
3149
3493
|
}
|
|
3150
3494
|
function isNullType(type) {
|
|
@@ -3206,7 +3550,7 @@ function schemaToFaker(schema, propertyName, options = {}) {
|
|
|
3206
3550
|
}).join(", ");
|
|
3207
3551
|
};
|
|
3208
3552
|
if (type === "object" && schema.properties) return `{ ${renderProps(schema.properties, schema.required)} }`;
|
|
3209
|
-
if (type === "object" && !schema.properties && schema.additionalProperties) {
|
|
3553
|
+
if (type === "object" && !schema.properties && schema.additionalProperties !== void 0 && schema.additionalProperties !== false) {
|
|
3210
3554
|
if (typeof schema.additionalProperties === "boolean" || schema.propertyNames !== void 0 || schema.patternProperties !== void 0) return "{}";
|
|
3211
3555
|
const value = schemaToFaker(schema.additionalProperties, void 0, options);
|
|
3212
3556
|
const max = schema.maxProperties ?? Math.max(schema.minProperties ?? 1, 3);
|
|
@@ -3295,7 +3639,7 @@ function topologicalOrder(usedSchemaNames, schemas) {
|
|
|
3295
3639
|
if (visited.has(name) || !usedSchemaNames.has(name) || visiting.has(name)) return [];
|
|
3296
3640
|
const nextVisiting = new Set(visiting).add(name);
|
|
3297
3641
|
const schema = schemas[name];
|
|
3298
|
-
const depOrder = schema ? collectSchemaRefs(schema, schemas, new Set([name])).flatMap((dep) => {
|
|
3642
|
+
const depOrder = schema ? collectSchemaRefs(schema, schemas, /* @__PURE__ */ new Set([name])).flatMap((dep) => {
|
|
3299
3643
|
const subOrder = visit(dep, visited, nextVisiting);
|
|
3300
3644
|
for (const n of subOrder) visited.add(n);
|
|
3301
3645
|
return subOrder;
|
|
@@ -3317,8 +3661,7 @@ function makeMockFunctions(spec, usedSchemaNames, options = {}) {
|
|
|
3317
3661
|
return `function ${mockName(name)}()${returnType} {\n return ${value}\n}`;
|
|
3318
3662
|
}).join("\n\n");
|
|
3319
3663
|
}
|
|
3320
|
-
|
|
3321
|
-
//#region src/generator/mock/index.ts
|
|
3664
|
+
// src/generator/mock/index.ts
|
|
3322
3665
|
const SEED_REF_DATE = "2025-01-01T00:00:00.000Z";
|
|
3323
3666
|
function normalizeKey(key) {
|
|
3324
3667
|
return /^[1-5]xx$/iu.test(key) ? key.toUpperCase() : key;
|
|
@@ -3590,7 +3933,7 @@ function makeMock(spec, options = {}) {
|
|
|
3590
3933
|
...useExamples === "all" ? { useExamples: true } : {}
|
|
3591
3934
|
};
|
|
3592
3935
|
const components = spec.components;
|
|
3593
|
-
const routes = Object.entries(spec.paths).flatMap(([path, pathItem]) => {
|
|
3936
|
+
const routes = Object.entries(spec.paths ?? {}).flatMap(([path, pathItem]) => {
|
|
3594
3937
|
if (!pathItem) return [];
|
|
3595
3938
|
return HTTP_METHODS.flatMap((method) => {
|
|
3596
3939
|
const operation = pathItem[method];
|
|
@@ -3610,11 +3953,11 @@ function makeMock(spec, options = {}) {
|
|
|
3610
3953
|
};
|
|
3611
3954
|
});
|
|
3612
3955
|
const refs = responses.flatMap(({ jsonSchema }) => jsonSchema && isMediaWithSchema(jsonSchema) ? collectSchemaRefs(jsonSchema.schema, components?.schemas) : []);
|
|
3613
|
-
const preferTable = Object.fromEntries(responses.map((
|
|
3614
|
-
const render = (
|
|
3615
|
-
return indent(returnStatement(/^\d{3}$/u.test(
|
|
3956
|
+
const preferTable = Object.fromEntries(responses.map((entry) => [entry.key, entry.named.map(([name]) => name)]));
|
|
3957
|
+
const render = (entry, example) => {
|
|
3958
|
+
return indent(returnStatement(/^\d{3}$/u.test(entry.key) ? entry.key : `prefer.status ?? ${/^[1-5]XX$/u.test(entry.key) ? `${entry.key.slice(0, 1)}00` : "200"}`, responseBody(entry.response, example, fakerOptions)));
|
|
3616
3959
|
};
|
|
3617
|
-
const branches = [responses.flatMap((
|
|
3960
|
+
const branches = [responses.flatMap((entry) => entry.named.filter(([, value]) => value !== entry.example).map(([name, value]) => `if (prefer.key === ${quoteSingle(entry.key)} && prefer.example === ${quoteSingle(name)}) {\n ${render(entry, value)}\n }\n `)), responses.filter((entry) => !(entry.key === success.key && /^\d{3}$/u.test(entry.key))).map((entry) => `if (prefer.key === ${quoteSingle(entry.key)}) {\n ${render(entry, entry.example)}\n }\n `)].flat();
|
|
3618
3961
|
const prefer = `const prefer = resolvePrefer(c.headers.prefer, c.query, ${JSON.stringify(preferTable)}, ${quoteSingle(success.key)})\n if (prefer.problem) return prefer.problem\n ${branches.join("")}`;
|
|
3619
3962
|
const successBody = responseBody(success.response, defaultExample(success.response, components, useExamples !== false), fakerOptions);
|
|
3620
3963
|
const auth = authGuard(resolved, spec, resolved.responses);
|
|
@@ -3636,9 +3979,9 @@ function makeMock(spec, options = {}) {
|
|
|
3636
3979
|
}];
|
|
3637
3980
|
});
|
|
3638
3981
|
});
|
|
3639
|
-
const mockFunctions = makeMockFunctions(spec, new Set(routes.flatMap((
|
|
3982
|
+
const mockFunctions = makeMockFunctions(spec, new Set(routes.flatMap((route) => route.refs)), fakerOptions);
|
|
3640
3983
|
const ctorArgs = prefix ? `{ prefix: ${quoteSingle(prefix)} }` : "";
|
|
3641
|
-
const routeChain = routes.map((
|
|
3984
|
+
const routeChain = routes.map((route) => ` ${route.code}`).join("\n");
|
|
3642
3985
|
const listenBlock = `
|
|
3643
3986
|
|
|
3644
3987
|
if (import.meta.main) {
|
|
@@ -3650,21 +3993,19 @@ if (import.meta.main) {
|
|
|
3650
3993
|
const fakerModule = locale === void 0 ? "@faker-js/faker" : `@faker-js/faker/locale/${locale}`;
|
|
3651
3994
|
return `import { Elysia } from 'elysia'${body.includes("faker.") ? `\nimport { faker } from '${fakerModule}'` : ""}\n\n${body}\n`;
|
|
3652
3995
|
}
|
|
3653
|
-
|
|
3654
|
-
//#region src/core/mock/index.ts
|
|
3996
|
+
// src/core/mock/index.ts
|
|
3655
3997
|
function mock(openAPI, output, options = {}) {
|
|
3656
3998
|
return Effect.gen(function* () {
|
|
3657
3999
|
yield* emit(makeMock(openAPI, options), path.dirname(output), output);
|
|
3658
4000
|
return `Generated mock server written to ${output}`;
|
|
3659
4001
|
});
|
|
3660
4002
|
}
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
|
|
3664
|
-
if (
|
|
3665
|
-
if (
|
|
3666
|
-
if (
|
|
3667
|
-
if (t === "null") return "null";
|
|
4003
|
+
// src/core/type/index.ts
|
|
4004
|
+
function primitiveTypeToTs(type) {
|
|
4005
|
+
if (type === "string") return "string";
|
|
4006
|
+
if (type === "number" || type === "integer") return "number";
|
|
4007
|
+
if (type === "boolean") return "boolean";
|
|
4008
|
+
if (type === "null") return "null";
|
|
3668
4009
|
return "unknown";
|
|
3669
4010
|
}
|
|
3670
4011
|
function tsName(name) {
|
|
@@ -3679,13 +4020,18 @@ function literalToTs(v) {
|
|
|
3679
4020
|
}
|
|
3680
4021
|
function isNullable(s) {
|
|
3681
4022
|
if (s.nullable === true) return true;
|
|
3682
|
-
if (Array.isArray(s.type)) return s.type.some((
|
|
4023
|
+
if (Array.isArray(s.type)) return s.type.some((kind) => kind === "null");
|
|
3683
4024
|
return false;
|
|
3684
4025
|
}
|
|
3685
4026
|
function primaryType(s) {
|
|
3686
4027
|
if (typeof s.type === "string") return s.type;
|
|
3687
|
-
if (Array.isArray(s.type)) return s.type.find((
|
|
4028
|
+
if (Array.isArray(s.type)) return s.type.find((kind) => kind !== "null");
|
|
3688
4029
|
}
|
|
4030
|
+
/**
|
|
4031
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
4032
|
+
*
|
|
4033
|
+
* @internal
|
|
4034
|
+
*/
|
|
3689
4035
|
function schemaToTs(schema) {
|
|
3690
4036
|
if (!schema) return "unknown";
|
|
3691
4037
|
if (schema.$ref) {
|
|
@@ -3718,7 +4064,7 @@ function schemaToTs(schema) {
|
|
|
3718
4064
|
});
|
|
3719
4065
|
const additional = schema.additionalProperties;
|
|
3720
4066
|
const propsTs = entries.length === 0 ? "" : `{ ${entries.join("; ")} }`;
|
|
3721
|
-
if (
|
|
4067
|
+
if (typeof additional === "object") {
|
|
3722
4068
|
const recordTs = `Record<string, ${schemaToTs(additional)}>`;
|
|
3723
4069
|
return wrap(propsTs === "" ? recordTs : `${propsTs} & ${recordTs}`);
|
|
3724
4070
|
}
|
|
@@ -3794,7 +4140,8 @@ function paramsTs(params, where, components) {
|
|
|
3794
4140
|
if (resolved.length === 0) return "{}";
|
|
3795
4141
|
return `{ ${resolved.map((p) => {
|
|
3796
4142
|
const opt = p.required ? "" : "?";
|
|
3797
|
-
|
|
4143
|
+
const name = where === "header" ? p.name.toLowerCase() : p.name;
|
|
4144
|
+
return `${JSON.stringify(name)}${opt}: ${schemaToTs(parameterSchema(p))}`;
|
|
3798
4145
|
}).join("; ")} }`;
|
|
3799
4146
|
}
|
|
3800
4147
|
const VALIDATION_ERROR_TS = `{ type: "validation"; on: string; summary?: string; message?: string; found?: unknown; property?: string; expected?: string }`;
|
|
@@ -3823,7 +4170,7 @@ function nestRoute(keys, method, opTs) {
|
|
|
3823
4170
|
function makeRoutes(openAPI, prefix) {
|
|
3824
4171
|
const out = [];
|
|
3825
4172
|
const prefixKeys = prefix && prefix !== "/" ? pathToKeys(prefix) : [];
|
|
3826
|
-
for (const [pathStr, pathItem] of Object.entries(openAPI.paths)) {
|
|
4173
|
+
for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
|
|
3827
4174
|
if (!pathItem) continue;
|
|
3828
4175
|
const keys = [...prefixKeys, ...pathToKeys(pathStr)];
|
|
3829
4176
|
for (const method of HTTP_METHODS) {
|
|
@@ -3867,18 +4214,23 @@ function collectRefs(openAPI) {
|
|
|
3867
4214
|
}
|
|
3868
4215
|
if (resp.content) walkContentMap(resp.content);
|
|
3869
4216
|
};
|
|
3870
|
-
|
|
4217
|
+
const walkParameter = (p) => {
|
|
4218
|
+
if (isStringRef(p) && p.$ref) {
|
|
4219
|
+
const name = p.$ref.split("/").pop();
|
|
4220
|
+
const resolved = name ? components?.parameters?.[decodeURIComponent(name)] : void 0;
|
|
4221
|
+
if (resolved) enqueue(resolved.schema);
|
|
4222
|
+
return;
|
|
4223
|
+
}
|
|
4224
|
+
if ("schema" in p) enqueue(parameterSchema(p));
|
|
4225
|
+
};
|
|
4226
|
+
for (const [, pathItem] of Object.entries(openAPI.paths ?? {})) {
|
|
3871
4227
|
if (!pathItem) continue;
|
|
3872
4228
|
for (const method of HTTP_METHODS) {
|
|
3873
4229
|
const op = pathItem[method];
|
|
3874
4230
|
if (!op) continue;
|
|
3875
4231
|
walkRequestBody(op.requestBody);
|
|
3876
|
-
for (const p of op.parameters ?? [])
|
|
3877
|
-
|
|
3878
|
-
const resolved = pname ? components?.parameters?.[decodeURIComponent(pname)] : void 0;
|
|
3879
|
-
if (resolved) enqueue(resolved.schema);
|
|
3880
|
-
} else if ("schema" in p) enqueue(p.schema);
|
|
3881
|
-
for (const resp of Object.values(op.responses ?? {})) if (resp) walkResponse(resp);
|
|
4232
|
+
for (const p of op.parameters ?? []) walkParameter(p);
|
|
4233
|
+
for (const resp of Object.values(op.responses ?? {})) walkResponse(resp);
|
|
3882
4234
|
}
|
|
3883
4235
|
}
|
|
3884
4236
|
while (queue.length > 0) {
|
|
@@ -3888,6 +4240,11 @@ function collectRefs(openAPI) {
|
|
|
3888
4240
|
}
|
|
3889
4241
|
return [...seen];
|
|
3890
4242
|
}
|
|
4243
|
+
/**
|
|
4244
|
+
* Exported for its unit tests; nothing outside this module imports it.
|
|
4245
|
+
*
|
|
4246
|
+
* @internal
|
|
4247
|
+
*/
|
|
3891
4248
|
function makeAppType(openAPI, prefix) {
|
|
3892
4249
|
const refAliases = collectRefs(openAPI).map((name) => {
|
|
3893
4250
|
const schema = openAPI.components?.schemas?.[name];
|
|
@@ -3916,8 +4273,7 @@ function types(openAPI, output, prefix) {
|
|
|
3916
4273
|
return `Generated app type written to ${output}`;
|
|
3917
4274
|
});
|
|
3918
4275
|
}
|
|
3919
|
-
|
|
3920
|
-
//#region src/shared/index.ts
|
|
4276
|
+
// src/shared/index.ts
|
|
3921
4277
|
var shared_exports = /* @__PURE__ */ __exportAll({
|
|
3922
4278
|
cleanSplitOutputs: () => cleanSplitOutputs,
|
|
3923
4279
|
isInsideDirectory: () => isInsideDirectory,
|
|
@@ -4280,7 +4636,7 @@ function typeSpecSources(file, seen) {
|
|
|
4280
4636
|
const fs = yield* FileSystem.FileSystem;
|
|
4281
4637
|
if ((yield* fs.stat(file).pipe(Effect.orElseSucceed(() => null)))?.type === "Directory") return yield* typeSpecSources(path.join(file, "main.tsp"), seen);
|
|
4282
4638
|
const imports = [...(file.endsWith(".tsp") ? yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => "")) : "").matchAll(TYPESPEC_IMPORT)].map((match) => match.groups?.specifier).filter((specifier) => specifier !== void 0).map((specifier) => path.resolve(path.dirname(file), specifier));
|
|
4283
|
-
return yield* Effect.reduce(imports, () => new Set([...seen, file]), (found, imported) => typeSpecSources(imported, found));
|
|
4639
|
+
return yield* Effect.reduce(imports, () => /* @__PURE__ */ new Set([...seen, file]), (found, imported) => typeSpecSources(imported, found));
|
|
4284
4640
|
});
|
|
4285
4641
|
}
|
|
4286
4642
|
/**
|
|
@@ -4312,5 +4668,4 @@ function outsideSources(input) {
|
|
|
4312
4668
|
return [...new Set(files.map((file) => path.resolve(file)))].filter((file) => file !== path.resolve(input) && !isInsideDirectory(inputDirectory, file) && !file.split(path.sep).includes("node_modules")).toSorted();
|
|
4313
4669
|
});
|
|
4314
4670
|
}
|
|
4315
|
-
//#endregion
|
|
4316
4671
|
export { makeJob as a, fileSystemLayer as c, jobTargets as i, isInsideDirectory as n, outsideSources as o, isUserCodeJob as r, shared_exports as s, cleanSplitOutputs as t };
|