asphodelos 0.0.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +209 -127
- package/dist/cli.mjs +184 -119
- package/dist/index.d.mts +323 -561
- package/dist/index.mjs +392 -66
- package/dist/openapi-C8b6Ibiu.mjs +26 -0
- package/dist/{core-DS3sAabb.mjs → shared-Becl66EY.mjs} +1041 -743
- package/dist/vite-plugin/index.mjs +37 -18
- package/package.json +11 -16
- package/dist/openapi-B4aAnx4P.mjs +0 -40
- package/dist/shared-CrbXsFUJ.mjs +0 -221
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-wcPFST8Q.mjs";
|
|
2
|
+
import { COMPONENT_KINDS, HOOK_KINDS } from "./index.mjs";
|
|
2
3
|
import { n as fmt } from "./format-B0W7HIAg.mjs";
|
|
3
|
-
import { r as pathEntries } from "./openapi-B4aAnx4P.mjs";
|
|
4
4
|
import { Data, Effect, FileSystem } from "effect";
|
|
5
|
-
import path from "node:path";
|
|
5
|
+
import path, { posix } from "node:path";
|
|
6
6
|
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
|
|
7
|
+
import SwaggerParser from "@apidevtools/swagger-parser";
|
|
7
8
|
import { Node, Project } from "ts-morph";
|
|
8
9
|
//#region src/fsp/index.ts
|
|
9
10
|
/**
|
|
@@ -65,6 +66,47 @@ function emit(code, dir, output) {
|
|
|
65
66
|
});
|
|
66
67
|
}
|
|
67
68
|
//#endregion
|
|
69
|
+
//#region src/core/client/index.ts
|
|
70
|
+
/**
|
|
71
|
+
* The base URL as code: an environment variable, read where it is used and asserted to be set —
|
|
72
|
+
* with `sameOrigin`, only without a window, so a browser bundle that has no such variable never
|
|
73
|
+
* reads it — or a value a module exports, used as written. Never a URL in the file.
|
|
74
|
+
*/
|
|
75
|
+
function baseUrlCode(baseUrl, sameOrigin) {
|
|
76
|
+
const [imports, expression] = "import" in baseUrl ? [[`import { ${String(baseUrl.value.split(".")[0])} } from '${baseUrl.import}'`], baseUrl.value] : [[], `${baseUrl.source}.${baseUrl.env}!`];
|
|
77
|
+
return {
|
|
78
|
+
imports,
|
|
79
|
+
origin: sameOrigin ? `const origin = typeof window === 'undefined' ? ${expression} : window.location.origin` : `const origin = ${expression}`
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Generates the Eden Treaty client of the generated app.
|
|
84
|
+
*
|
|
85
|
+
* The client is typed by `typeof app`, through a type-only import of the app entry: the type is
|
|
86
|
+
* worked out from the app as it stands, user code included, and the import is erased before a
|
|
87
|
+
* browser bundle could pull the server in. `treaty` wants an origin — a relative path is read as
|
|
88
|
+
* a host — so with `sameOrigin` the browser is given its own, `window.location.origin`, and
|
|
89
|
+
* `baseUrl` serves the code that runs without a window. Either way the origin is a `const` of
|
|
90
|
+
* its own, so what the client is created with is read off one line.
|
|
91
|
+
*/
|
|
92
|
+
function client(output, options) {
|
|
93
|
+
return Effect.gen(function* () {
|
|
94
|
+
const { imports, origin } = baseUrlCode(options.baseUrl, options.sameOrigin);
|
|
95
|
+
yield* emit(`${[
|
|
96
|
+
["import { treaty } from '@elysiajs/eden'", ...imports].join("\n"),
|
|
97
|
+
`import type { app } from '${options.appImport}'`,
|
|
98
|
+
origin,
|
|
99
|
+
"export const client = treaty<typeof app>(origin)"
|
|
100
|
+
].join("\n\n")}\n`, path.dirname(output), output);
|
|
101
|
+
if (options.barrel !== void 0) {
|
|
102
|
+
const line = `export * from './${path.basename(output, ".ts")}'`;
|
|
103
|
+
const existing = (yield* readFile(options.barrel)) ?? "";
|
|
104
|
+
if (!existing.split("\n").map((text) => text.trim().replace(/;$/u, "")).some((text) => text.replaceAll("\"", "'") === line)) yield* emit(`${existing.trimEnd()}\n${line}\n`, path.dirname(options.barrel), options.barrel);
|
|
105
|
+
}
|
|
106
|
+
return `Generated client written to ${output}`;
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
//#endregion
|
|
68
110
|
//#region src/guard/index.ts
|
|
69
111
|
function isReference(v) {
|
|
70
112
|
return typeof v === "object" && v !== null && "$ref" in v && typeof v.$ref === "string" && !!v.$ref;
|
|
@@ -231,6 +273,17 @@ function safeStatusKey(status) {
|
|
|
231
273
|
function resourcePrefix(pathStr) {
|
|
232
274
|
return pathStr.replace(/^\//u, "").split("/")[0] ?? "";
|
|
233
275
|
}
|
|
276
|
+
/**
|
|
277
|
+
* The identifier an operation goes by: its method followed by the words of its path, each
|
|
278
|
+
* capitalized. `('get', '/users/{id}')` is `getUsersId`; `('', '/users')` is `Users`, for a name
|
|
279
|
+
* that leaves the method out. Every character that is not a letter or digit breaks a word, and a
|
|
280
|
+
* trailing slash becomes `Index` so `/users/` and `/users` stay apart; the root path is `Index`.
|
|
281
|
+
*/
|
|
282
|
+
function methodPath(method, pathStr) {
|
|
283
|
+
const hasTrailingSlash = pathStr !== "/" && pathStr.endsWith("/");
|
|
284
|
+
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
|
+
return words ? `${method}${words}${hasTrailingSlash ? "Index" : ""}` : `${method}Index`;
|
|
286
|
+
}
|
|
234
287
|
//#endregion
|
|
235
288
|
//#region src/helper/schema.ts
|
|
236
289
|
function pickVendorExtensions(source) {
|
|
@@ -385,7 +438,7 @@ function sccSchemas(schemas) {
|
|
|
385
438
|
const lowlink = /* @__PURE__ */ new Map();
|
|
386
439
|
const onStack = /* @__PURE__ */ new Set();
|
|
387
440
|
const stack = [];
|
|
388
|
-
const
|
|
441
|
+
const groups = [];
|
|
389
442
|
const counter = { value: 0 };
|
|
390
443
|
const strongconnect = (v) => {
|
|
391
444
|
index.set(v, counter.value);
|
|
@@ -407,11 +460,11 @@ function sccSchemas(schemas) {
|
|
|
407
460
|
if (def) group.push(def);
|
|
408
461
|
if (w === v) break;
|
|
409
462
|
}
|
|
410
|
-
|
|
463
|
+
groups.push(group);
|
|
411
464
|
}
|
|
412
465
|
};
|
|
413
466
|
for (const { name } of schemas) if (!index.has(name)) strongconnect(name);
|
|
414
|
-
return
|
|
467
|
+
return groups;
|
|
415
468
|
}
|
|
416
469
|
const REF_SUFFIX = {
|
|
417
470
|
schemas: "Schema",
|
|
@@ -445,7 +498,7 @@ function stringifyRefs(value) {
|
|
|
445
498
|
const ident = refIdent(value.$ref);
|
|
446
499
|
if (ident) return ident;
|
|
447
500
|
}
|
|
448
|
-
return `{${Object.entries(value).
|
|
501
|
+
return `{${Object.entries(value).flatMap(([k, v]) => v === void 0 ? [] : [`${JSON.stringify(k)}:${stringifyRefs(v)}`]).join(",")}}`;
|
|
449
502
|
}
|
|
450
503
|
return JSON.stringify(value);
|
|
451
504
|
}
|
|
@@ -880,10 +933,11 @@ function _enum(schema) {
|
|
|
880
933
|
if (opts && typeof v !== "object") return `t.Literal(${JSON.stringify(v)},${opts})`;
|
|
881
934
|
return literalSchema(v);
|
|
882
935
|
}
|
|
883
|
-
if (values.every(isUnionEnumValue)) {
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
936
|
+
if (values.every(isUnionEnumValue)) return `t.UnionEnum(${JSON.stringify(values)},${options([
|
|
937
|
+
...filterDefined([enumErrorCallback(schema)]),
|
|
938
|
+
...commonOpts(schema),
|
|
939
|
+
...schema.default === void 0 ? [["default", raw("undefined")]] : []
|
|
940
|
+
])})`;
|
|
887
941
|
return opts ? `t.Union([${values.map(literalSchema).join(",")}],${opts})` : `t.Union([${values.map(literalSchema).join(",")}])`;
|
|
888
942
|
}
|
|
889
943
|
//#endregion
|
|
@@ -894,11 +948,16 @@ function autoMaximum(format, maximum, exclusiveMaximum) {
|
|
|
894
948
|
if (format === "int32") return 2147483647;
|
|
895
949
|
return Number.MAX_SAFE_INTEGER;
|
|
896
950
|
}
|
|
951
|
+
function autoMinimum(format, minimum, exclusiveMinimum) {
|
|
952
|
+
if (minimum !== void 0) return minimum;
|
|
953
|
+
if (exclusiveMinimum !== void 0) return void 0;
|
|
954
|
+
if (format === "int32") return -2147483648;
|
|
955
|
+
}
|
|
897
956
|
function integer(schema) {
|
|
898
957
|
const bounds = normalizeBounds(schema);
|
|
899
958
|
const opts = options([
|
|
900
959
|
["format", schema.format],
|
|
901
|
-
["minimum", bounds.minimum],
|
|
960
|
+
["minimum", autoMinimum(schema.format, bounds.minimum, bounds.exclusiveMinimum)],
|
|
902
961
|
["maximum", autoMaximum(schema.format, bounds.maximum, bounds.exclusiveMaximum)],
|
|
903
962
|
["exclusiveMinimum", bounds.exclusiveMinimum],
|
|
904
963
|
["exclusiveMaximum", bounds.exclusiveMaximum],
|
|
@@ -910,9 +969,22 @@ function integer(schema) {
|
|
|
910
969
|
}
|
|
911
970
|
//#endregion
|
|
912
971
|
//#region src/generator/typebox/t/intersect.ts
|
|
972
|
+
/**
|
|
973
|
+
* Whether an `allOf` member is a bare scalar or a bag of constraints, with nothing of its own to
|
|
974
|
+
* intersect: no reference, no properties, no items and no composition.
|
|
975
|
+
*/
|
|
976
|
+
function isScalarMember(schema) {
|
|
977
|
+
return schema.$ref === void 0 && schema.properties === void 0 && schema.items === void 0 && schema.allOf === void 0 && schema.anyOf === void 0 && schema.oneOf === void 0 && schema.not === void 0 && !Array.isArray(schema.type) && schema.type !== "object" && schema.type !== "array";
|
|
978
|
+
}
|
|
913
979
|
function intersect(schemas, parent) {
|
|
914
980
|
if (schemas.length === 0) return "t.Unknown()";
|
|
915
981
|
if (schemas.length === 1 && schemas[0]) return typebox(schemas[0]);
|
|
982
|
+
if (schemas.every(isScalarMember) && schemas.some((s) => typeof s.type === "string")) {
|
|
983
|
+
const { allOf: _allOf, ...annotations } = parent ?? {};
|
|
984
|
+
const merged = {};
|
|
985
|
+
for (const part of [...schemas, annotations]) Object.assign(merged, part);
|
|
986
|
+
return typebox(merged);
|
|
987
|
+
}
|
|
916
988
|
const opts = parent ? options([...filterDefined([errorCallback(parent, "composition")]), ...commonOpts(parent)]) : "";
|
|
917
989
|
return opts ? `t.Intersect([${schemas.map((s) => typebox(s)).join(",")}],${opts})` : `t.Intersect([${schemas.map((s) => typebox(s)).join(",")}])`;
|
|
918
990
|
}
|
|
@@ -1004,6 +1076,40 @@ function ref(schema) {
|
|
|
1004
1076
|
}
|
|
1005
1077
|
//#endregion
|
|
1006
1078
|
//#region src/generator/typebox/t/string.ts
|
|
1079
|
+
/**
|
|
1080
|
+
* The string formats Elysia registers with TypeBox (`elysia/type-system/format`).
|
|
1081
|
+
*
|
|
1082
|
+
* TypeBox rejects every value of a format it does not know, so a `format` outside this set is left
|
|
1083
|
+
* off the schema rather than turned into a validator that fails on its own input. `password` is
|
|
1084
|
+
* OpenAPI's hint to hide the text in a UI and says nothing about the value, so it is dropped in
|
|
1085
|
+
* silence; any other unknown format is reported, since the document meant something by it.
|
|
1086
|
+
*/
|
|
1087
|
+
const ELYSIA_STRING_FORMATS = new Set([
|
|
1088
|
+
"date",
|
|
1089
|
+
"time",
|
|
1090
|
+
"date-time",
|
|
1091
|
+
"iso-time",
|
|
1092
|
+
"iso-date-time",
|
|
1093
|
+
"duration",
|
|
1094
|
+
"uri",
|
|
1095
|
+
"uri-reference",
|
|
1096
|
+
"uri-template",
|
|
1097
|
+
"url",
|
|
1098
|
+
"email",
|
|
1099
|
+
"hostname",
|
|
1100
|
+
"ipv4",
|
|
1101
|
+
"ipv6",
|
|
1102
|
+
"regex",
|
|
1103
|
+
"uuid",
|
|
1104
|
+
"json-pointer",
|
|
1105
|
+
"json-pointer-uri-fragment",
|
|
1106
|
+
"relative-json-pointer",
|
|
1107
|
+
"byte"
|
|
1108
|
+
]);
|
|
1109
|
+
function validatedFormat(format) {
|
|
1110
|
+
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`);
|
|
1112
|
+
}
|
|
1007
1113
|
function string(schema, ctx = {}) {
|
|
1008
1114
|
if (schema.format === "date" || schema.format === "date-time") return `t.Date(${options([...commonOpts(schema)])})`;
|
|
1009
1115
|
if (schema.format === "binary") {
|
|
@@ -1020,7 +1126,7 @@ function string(schema, ctx = {}) {
|
|
|
1020
1126
|
])})`;
|
|
1021
1127
|
}
|
|
1022
1128
|
return stringTransformWrap(`t.String(${options([
|
|
1023
|
-
["format", schema.format],
|
|
1129
|
+
["format", validatedFormat(schema.format)],
|
|
1024
1130
|
["pattern", stringPatternFrom(schema)],
|
|
1025
1131
|
["minLength", schema.minLength],
|
|
1026
1132
|
["maxLength", schema.maxLength],
|
|
@@ -1593,13 +1699,32 @@ function resolvePathItem(pathItem, api) {
|
|
|
1593
1699
|
const m = /^#\/components\/pathItems\/(.+)$/u.exec(pathItem.$ref);
|
|
1594
1700
|
return (m?.[1] ? api.components?.pathItems?.[decodeURIComponent(m[1])] : void 0) ?? pathItem;
|
|
1595
1701
|
}
|
|
1702
|
+
/**
|
|
1703
|
+
* The operation with the parameters its path item declares for every operation under it.
|
|
1704
|
+
*
|
|
1705
|
+
* A parameter the operation declares itself, by name and location, replaces the path item's; the
|
|
1706
|
+
* rest are inherited, ahead of the operation's own.
|
|
1707
|
+
*/
|
|
1708
|
+
function withPathItemParameters(operation, inherited, components) {
|
|
1709
|
+
if (inherited.length === 0) return operation;
|
|
1710
|
+
const own = operation.parameters ?? [];
|
|
1711
|
+
const declared = new Set(own.map((p) => resolveParameter$1(p, components)).filter((p) => p !== void 0).map((p) => `${p.in}:${p.name}`));
|
|
1712
|
+
const added = inherited.filter((p) => {
|
|
1713
|
+
const parameter = resolveParameter$1(p, components);
|
|
1714
|
+
return parameter !== void 0 && !declared.has(`${parameter.in}:${parameter.name}`);
|
|
1715
|
+
});
|
|
1716
|
+
return {
|
|
1717
|
+
...operation,
|
|
1718
|
+
parameters: [...added, ...own]
|
|
1719
|
+
};
|
|
1720
|
+
}
|
|
1596
1721
|
function walk(path, resource, pathItem, api, canonical) {
|
|
1597
1722
|
const resolved = resolvePathItem(pathItem, api);
|
|
1598
1723
|
const { path: normalizedPath, renames } = normalizePath(path, canonical);
|
|
1599
1724
|
return HTTP_METHODS.flatMap((method) => {
|
|
1600
1725
|
const operation = resolved[method];
|
|
1601
1726
|
if (!operation) return [];
|
|
1602
|
-
return [[resource, makeRoute(method, normalizedPath, renameOperationParams(resolveOperation(operation, api.components), renames))]];
|
|
1727
|
+
return [[resource, makeRoute(method, normalizedPath, renameOperationParams(resolveOperation(withPathItemParameters(operation, resolved.parameters ?? [], api.components), api.components), renames))]];
|
|
1603
1728
|
});
|
|
1604
1729
|
}
|
|
1605
1730
|
function operationsByResource(api) {
|
|
@@ -1610,7 +1735,7 @@ function operationsByResource(api) {
|
|
|
1610
1735
|
bucket.push(item);
|
|
1611
1736
|
grouped.set(resource, bucket);
|
|
1612
1737
|
};
|
|
1613
|
-
for (const [path, pathItem] of
|
|
1738
|
+
for (const [path, pathItem] of Object.entries(api.paths)) {
|
|
1614
1739
|
if (!pathItem) continue;
|
|
1615
1740
|
for (const [resource, route] of walk(path, resourceName(path), pathItem, api, canonical)) collect(resource, route);
|
|
1616
1741
|
}
|
|
@@ -1666,12 +1791,12 @@ function fileNameOf(group) {
|
|
|
1666
1791
|
return uncapitalize(group.map((g) => g.name).toSorted()[0] ?? "schema");
|
|
1667
1792
|
}
|
|
1668
1793
|
function splitSchemaFiles(section, readonly, exportTypes) {
|
|
1669
|
-
const
|
|
1794
|
+
const groups = sccSchemas(Object.entries(section).map(([name, schema]) => ({
|
|
1670
1795
|
name,
|
|
1671
1796
|
schema
|
|
1672
1797
|
})));
|
|
1673
|
-
const nameToFile = new Map(
|
|
1674
|
-
return
|
|
1798
|
+
const nameToFile = new Map(groups.flatMap((g) => g.map((s) => [s.name, fileNameOf(g)])));
|
|
1799
|
+
return groups.map((group) => {
|
|
1675
1800
|
const fileName = fileNameOf(group);
|
|
1676
1801
|
const body = schemasCode(Object.fromEntries(group.map((g) => [g.name, g.schema])), readonly, exportTypes);
|
|
1677
1802
|
if (body === "") return {
|
|
@@ -1918,32 +2043,21 @@ function mediaTypes(section, output, split, exportTypes, components, readonly) {
|
|
|
1918
2043
|
}
|
|
1919
2044
|
//#endregion
|
|
1920
2045
|
//#region src/core/eden/index.ts
|
|
1921
|
-
function
|
|
1922
|
-
const blocks = [];
|
|
1923
|
-
if (operation.summary) blocks.push([operation.summary]);
|
|
1924
|
-
if (operation.description) blocks.push(operation.description.split("\n"));
|
|
1925
|
-
blocks.push([`${method.toUpperCase()} ${pathStr}`]);
|
|
1926
|
-
const tagLines = [];
|
|
1927
|
-
if (operation.deprecated) tagLines.push("@deprecated");
|
|
1928
|
-
if (tagLines.length > 0) blocks.push(tagLines);
|
|
1929
|
-
return `/**\n${blocks.map((lines) => lines.map((l) => l === "" ? " *" : ` * ${l}`).join("\n")).join("\n *\n")}\n */`;
|
|
1930
|
-
}
|
|
1931
|
-
function makeOperation$1(pathStr, method, operation, client, docs) {
|
|
2046
|
+
function makeOperation(pathStr, method, operation, client) {
|
|
1932
2047
|
const funcName = toSafeIdentifier(resolveOperationId(operation, method, pathStr));
|
|
1933
2048
|
const { callExpr, methodHostTypeExpr, paramArgs } = edenChain(pathStr, client, method);
|
|
1934
|
-
|
|
1935
|
-
return docs ? `${makeJsDocs(method, pathStr, operation)}\n${fn}` : fn;
|
|
2049
|
+
return `export async function ${funcName}(${[...paramArgs.map((p) => `${p.name}: ${p.typeExpr}`), `...args: Parameters<${methodHostTypeExpr}>`].join(", ")}) {\n return ${callExpr}(...args)\n}`;
|
|
1936
2050
|
}
|
|
1937
|
-
function eden(openAPI, output, importPath, client, basePath
|
|
2051
|
+
function eden(openAPI, output, importPath, client, basePath) {
|
|
1938
2052
|
return Effect.gen(function* () {
|
|
1939
2053
|
const prefix = basePath && basePath !== "/" ? basePath : "";
|
|
1940
2054
|
const operations = [];
|
|
1941
|
-
for (const [pathStr, pathItem] of
|
|
2055
|
+
for (const [pathStr, pathItem] of Object.entries(openAPI.paths)) {
|
|
1942
2056
|
if (!pathItem) continue;
|
|
1943
2057
|
for (const method of HTTP_METHODS) {
|
|
1944
2058
|
const operation = pathItem[method];
|
|
1945
2059
|
if (!operation) continue;
|
|
1946
|
-
operations.push(makeOperation
|
|
2060
|
+
operations.push(makeOperation(`${prefix}${pathStr}`, method, operation, client));
|
|
1947
2061
|
}
|
|
1948
2062
|
}
|
|
1949
2063
|
if (operations.length === 0) return "No operations found";
|
|
@@ -2201,17 +2315,20 @@ function elysia(api, options = {}) {
|
|
|
2201
2315
|
const modulesDir = path.join(baseDir, "modules");
|
|
2202
2316
|
const schemasImportFromModule = (() => {
|
|
2203
2317
|
const fromFile = path.join(modulesDir, "_", "index.ts");
|
|
2204
|
-
if (options.componentsOutput)
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2318
|
+
if (options.componentsOutput) {
|
|
2319
|
+
if (options.componentsImport) return options.componentsImport;
|
|
2320
|
+
return makeModuleSpec(fromFile, {
|
|
2321
|
+
output: path.resolve(process.cwd(), options.componentsOutput),
|
|
2322
|
+
split: false
|
|
2323
|
+
});
|
|
2324
|
+
}
|
|
2208
2325
|
const cfg = options.components?.schemas;
|
|
2209
2326
|
if (cfg?.import) return cfg.import;
|
|
2210
2327
|
if (cfg?.output) return makeModuleSpec(fromFile, {
|
|
2211
2328
|
output: path.resolve(process.cwd(), cfg.output),
|
|
2212
2329
|
split: cfg.split
|
|
2213
2330
|
});
|
|
2214
|
-
return options.pathAlias ? `${options.pathAlias}/schemas` : "../../components/schemas";
|
|
2331
|
+
return options.pathAlias ? `${options.pathAlias}/components/schemas` : "../../components/schemas";
|
|
2215
2332
|
})();
|
|
2216
2333
|
function writeResource(resource) {
|
|
2217
2334
|
return Effect.gen(function* () {
|
|
@@ -2243,171 +2360,24 @@ function elysia(api, options = {}) {
|
|
|
2243
2360
|
}
|
|
2244
2361
|
//#endregion
|
|
2245
2362
|
//#region src/helper/query.ts
|
|
2246
|
-
function optionsObjectType(config, optionsType) {
|
|
2247
|
-
return config.unwrapOptionsAccessor ? `ReturnType<${optionsType}>` : optionsType;
|
|
2248
|
-
}
|
|
2249
2363
|
const QUERY_OMIT_KEYS = `'queryKey' | 'queryFn'`;
|
|
2250
2364
|
const INFINITE_OMIT_KEYS = `'queryKey' | 'queryFn' | 'initialPageParam' | 'getNextPageParam'`;
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
}
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
return
|
|
2261
|
-
}
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
function makeGetHookBody(config, dataT, keyCall, queryFnBlock) {
|
|
2267
|
-
const inner = `${config.thunkOptionsCall ? "...queryOptions?.()" : "...queryOptions"},queryKey:${keyCall},${queryFnBlock}`;
|
|
2268
|
-
if (config.useQueryGenerics) return `${config.queryFn}<${dataT},TError,TData>({${inner}})`;
|
|
2269
|
-
if (config.useThunk) return `${config.queryFn}(()=>({${inner}}))`;
|
|
2270
|
-
return `${config.queryFn}({${inner}})`;
|
|
2271
|
-
}
|
|
2272
|
-
function makeMutationFactoryCode(name, keySig, keyCall, dataT, errorT, variablesType, mutationFnBlock) {
|
|
2273
|
-
return `export function ${name}<TError = ${errorT}>(${keySig}){return mutationOptions<${dataT},TError,${variablesType}>({mutationKey:${keyCall},${mutationFnBlock}})}`;
|
|
2274
|
-
}
|
|
2275
|
-
function makeMutationHookBody(config, dataT, variablesType, factoryCall) {
|
|
2276
|
-
const inner = `${config.thunkOptionsCall ? "...mutationOptions?.()" : "...mutationOptions"},...${factoryCall}`;
|
|
2277
|
-
if (config.useQueryGenerics) return `${config.mutationFn}<${dataT},TError,${variablesType}>({${inner}})`;
|
|
2278
|
-
if (config.useThunk) return `${config.mutationFn}(()=>({${inner}}))`;
|
|
2279
|
-
return `${config.mutationFn}({${inner}})`;
|
|
2280
|
-
}
|
|
2281
|
-
function makeTanstackInfiniteParts(config, args) {
|
|
2282
|
-
const { funcName, hookName, suspenseHookName, keyPrefix, pathStr } = args;
|
|
2283
|
-
const { paramSig, paramPass, optionsType, dataT, errorT, callExpr } = args;
|
|
2284
|
-
const infiniteKeyName = `${funcName}InfiniteQueryKey`;
|
|
2285
|
-
const infiniteKeyCode = `export function ${infiniteKeyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){const{headers:_h,fetch:_f,throwHttpError:_t,...keyArgs}=options??{};return[${[
|
|
2286
|
-
`'${keyPrefix}'`,
|
|
2287
|
-
`'${pathStr}'`,
|
|
2288
|
-
`'infinite'`,
|
|
2289
|
-
...paramPass,
|
|
2290
|
-
"keyArgs"
|
|
2291
|
-
].join(", ")}]as const}`;
|
|
2292
|
-
const infiniteKeyCall = `${infiniteKeyName}(${[...paramPass, "options"].join(", ")})`;
|
|
2293
|
-
const infiniteHookName = `${hookName}Infinite`;
|
|
2294
|
-
const suspenseInfiniteHookName = `${suspenseHookName}Infinite`;
|
|
2295
|
-
const queryKeyType = `ReturnType<typeof ${infiniteKeyName}>`;
|
|
2296
|
-
const paginationParam = `pagination: { initialPageParam: TPageParam; getNextPageParam: (lastPage: ${dataT}, allPages: ${dataT}[], lastPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | undefined | null; buildInit: (pageParam: unknown) => ${optionsType} }`;
|
|
2297
|
-
const infiniteSig = [
|
|
2298
|
-
...paramSig,
|
|
2299
|
-
`options: ${optionsType} | undefined`,
|
|
2300
|
-
paginationParam
|
|
2301
|
-
].join(", ");
|
|
2302
|
-
const infiniteQueryFnBody = `queryFn:async({pageParam,signal})=>{const overlay=pagination.buildInit(pageParam);const{data,error}=await ${callExpr}({...options,...overlay,query:{...options?.query,...overlay?.query},headers:{...options?.headers,...overlay?.headers},fetch:{...options?.fetch,...overlay?.fetch,signal}});if(error)throw error;return data},`;
|
|
2303
|
-
const infiniteOptionsCode = `export function ${`${funcName}InfiniteQueryOptions`}<TPageParam>(${infiniteSig}){return infiniteQueryOptions<${dataT},${errorT},InfiniteData<${dataT},TPageParam>,${queryKeyType},TPageParam>({queryKey:${infiniteKeyCall},${infiniteQueryFnBody}initialPageParam:pagination.initialPageParam,getNextPageParam:pagination.getNextPageParam})}`;
|
|
2304
|
-
const infiniteGenerics = `<TPageParam = unknown, TData = InfiniteData<${dataT}, TPageParam>, TError = ${errorT}>`;
|
|
2305
|
-
const hookQueryFnBody = `queryFn:async({pageParam,signal}:QueryFunctionContext<${queryKeyType},TPageParam>)=>{const overlay=pagination.buildInit(pageParam);const{data,error}=await ${callExpr}({...options,...overlay,query:{...options?.query,...overlay?.query},headers:{...options?.headers,...overlay?.headers},fetch:{...options?.fetch,...overlay?.fetch,signal}});if(error)throw error;return data},`;
|
|
2306
|
-
const inner = `${config.thunkOptionsCall ? "...queryOptions?.()" : "...queryOptions"},queryKey:${infiniteKeyCall},${hookQueryFnBody}initialPageParam:pagination.initialPageParam,getNextPageParam:pagination.getNextPageParam`;
|
|
2307
|
-
const hookBody = (queryFn) => config.useThunk ? `${queryFn}(()=>({${inner}}))` : `${queryFn}({${inner}})`;
|
|
2308
|
-
const hookSig = (libOptionsType) => {
|
|
2309
|
-
const fullType = omitInjectedKeys(config, `${libOptionsType}<${dataT}, TError, TData, ${queryKeyType}, TPageParam>`, INFINITE_OMIT_KEYS);
|
|
2310
|
-
return [infiniteSig, config.thunkOptionsCall ? `queryOptions?: () => ${fullType}` : `queryOptions?: ${fullType}`].join(", ");
|
|
2365
|
+
const MUTATION_OMIT_KEYS = `'mutationFn'`;
|
|
2366
|
+
const VUE_QUERY_MEMBER = `{ queryKey: unknown }`;
|
|
2367
|
+
const VUE_MUTATION_MEMBER = `{ mutationFn?: unknown }`;
|
|
2368
|
+
/** The caller's options slot: the library type, unwrapped for Solid, narrowed for Vue, minus the keys the hook supplies. */
|
|
2369
|
+
function slotType(config, optionsType, keys, vueMember) {
|
|
2370
|
+
return `Omit<${config.isVueQuery ? `Extract<${optionsType}, ${vueMember ?? VUE_QUERY_MEMBER}>` : config.unwrapOptionsAccessor ? `ReturnType<${optionsType}>` : optionsType}, ${keys}>`;
|
|
2371
|
+
}
|
|
2372
|
+
function tailOf(config, kind) {
|
|
2373
|
+
const tail = config.hookTail;
|
|
2374
|
+
return tail ? {
|
|
2375
|
+
sig: `, ${tail.name}?: ${tail[kind]}`,
|
|
2376
|
+
arg: `, ${tail.name}`
|
|
2377
|
+
} : {
|
|
2378
|
+
sig: "",
|
|
2379
|
+
arg: ""
|
|
2311
2380
|
};
|
|
2312
|
-
const infiniteCode = `export function ${infiniteHookName}${infiniteGenerics}(${hookSig(config.infiniteOptionsType)}){return ${hookBody(config.infiniteQueryFn)}}`;
|
|
2313
|
-
if (!config.suspenseInfiniteQueryFn) return [
|
|
2314
|
-
infiniteKeyCode,
|
|
2315
|
-
infiniteOptionsCode,
|
|
2316
|
-
infiniteCode
|
|
2317
|
-
];
|
|
2318
|
-
return [
|
|
2319
|
-
infiniteKeyCode,
|
|
2320
|
-
infiniteOptionsCode,
|
|
2321
|
-
infiniteCode,
|
|
2322
|
-
`export function ${suspenseInfiniteHookName}${infiniteGenerics}(${hookSig(config.suspenseInfiniteOptionsType)}){return ${hookBody(config.suspenseInfiniteQueryFn)}}`
|
|
2323
|
-
];
|
|
2324
|
-
}
|
|
2325
|
-
function makeInfiniteParts(config, args) {
|
|
2326
|
-
if (config.hasInfiniteQueryOptionsHelper) return makeTanstackInfiniteParts(config, args);
|
|
2327
|
-
const { funcName, hookName, keyPrefix, pathStr } = args;
|
|
2328
|
-
const { paramSig, paramPass, optionsType, dataT, errorT, callExpr } = args;
|
|
2329
|
-
const infiniteKeyName = `${funcName}InfiniteQueryKey`;
|
|
2330
|
-
const infiniteKeyCode = `export function ${infiniteKeyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){const{headers:_h,fetch:_f,throwHttpError:_t,...keyArgs}=options??{};return[${[
|
|
2331
|
-
`'${keyPrefix}'`,
|
|
2332
|
-
`'${pathStr}'`,
|
|
2333
|
-
`'infinite'`,
|
|
2334
|
-
...paramPass,
|
|
2335
|
-
"keyArgs"
|
|
2336
|
-
].join(", ")}]as const}`;
|
|
2337
|
-
const infiniteKeyCall = `${infiniteKeyName}(${[...paramPass, "options"].join(", ")})`;
|
|
2338
|
-
const infiniteHookName = `${hookName}Infinite`;
|
|
2339
|
-
const infiniteGenerics = `<TPageParam = unknown, TData = InfiniteData<${dataT}, TPageParam>, TError = ${errorT}>`;
|
|
2340
|
-
const infiniteQueryFnBlock = `queryFn:async({pageParam,signal}:QueryFunctionContext)=>{const overlay=pagination.buildInit(pageParam);const{data,error}=await ${callExpr}({...options,...overlay,query:{...options?.query,...overlay?.query},headers:{...options?.headers,...overlay?.headers},fetch:{...options?.fetch,...overlay?.fetch,signal}});if(error)throw error;return data},`;
|
|
2341
|
-
const fullOptionsType = `${config.infiniteOptionsType}<${dataT}, TError, TData, ReturnType<typeof ${infiniteKeyName}>, TPageParam>`;
|
|
2342
|
-
const infiniteHookSig = [
|
|
2343
|
-
...paramSig,
|
|
2344
|
-
`options: ${optionsType} | undefined`,
|
|
2345
|
-
`pagination: { buildInit: (pageParam: unknown) => ${optionsType} }`,
|
|
2346
|
-
`queryOptions: ${omitInjectedKeys(config, fullOptionsType, QUERY_OMIT_KEYS)}`
|
|
2347
|
-
].join(", ");
|
|
2348
|
-
const inner = `...queryOptions,queryKey:${infiniteKeyCall},${infiniteQueryFnBlock}`;
|
|
2349
|
-
return [infiniteKeyCode, `export function ${infiniteHookName}${infiniteGenerics}(${infiniteHookSig}){return ${config.infiniteQueryFn}({${inner}})}`];
|
|
2350
|
-
}
|
|
2351
|
-
function makeSwrOperation(config, args) {
|
|
2352
|
-
const { hookName, immutableHookName, keyName, keyPrefix, pathStr, method } = args;
|
|
2353
|
-
const { paramSig, paramPass } = args;
|
|
2354
|
-
const { argsType, optionsType, dataT, errorT, callExpr } = args;
|
|
2355
|
-
const { isQuery, isBodyMethod, isPaginated, hasKeyArgs, optMark } = args;
|
|
2356
|
-
if (isQuery) {
|
|
2357
|
-
const keySig = (hasKeyArgs ? [...paramSig, `options?: ${optionsType}`] : paramSig).join(", ");
|
|
2358
|
-
const keyTuple = [
|
|
2359
|
-
`'${keyPrefix}'`,
|
|
2360
|
-
`'${pathStr}'`,
|
|
2361
|
-
...paramPass,
|
|
2362
|
-
...hasKeyArgs ? ["keyArgs"] : []
|
|
2363
|
-
].join(", ");
|
|
2364
|
-
const keyCode = hasKeyArgs ? `export function ${keyName}(${keySig}){const{headers:_h,fetch:_f,throwHttpError:_t,...keyArgs}=options??{};return[${keyTuple}]as const}` : `export function ${keyName}(${keySig}){return[${keyTuple}]as const}`;
|
|
2365
|
-
const keyCall = `${keyName}(${[...paramPass, ...hasKeyArgs ? ["options"] : []].join(", ")})`;
|
|
2366
|
-
const generics = `<TError = ${errorT}>`;
|
|
2367
|
-
const hookSig = [
|
|
2368
|
-
...paramSig,
|
|
2369
|
-
`options${optMark}: ${optionsType}`,
|
|
2370
|
-
`config?: SWRConfiguration<${dataT}, TError>`
|
|
2371
|
-
].join(", ");
|
|
2372
|
-
const swrHook = (name, swrFn) => `export function ${name}${generics}(${hookSig}){return ${swrFn}<${dataT},TError>(${keyCall},async()=>{const{data,error}=await ${callExpr}(options);if(error)throw error;return data},config)}`;
|
|
2373
|
-
const hookCode = config.immutableQueryFn ? `${swrHook(hookName, config.queryFn)}\n\n${swrHook(immutableHookName, config.immutableQueryFn)}` : swrHook(hookName, config.queryFn);
|
|
2374
|
-
if (isPaginated) {
|
|
2375
|
-
const infiniteHookName = `${hookName}Infinite`;
|
|
2376
|
-
const infiniteHookSig = [
|
|
2377
|
-
...paramSig,
|
|
2378
|
-
`buildInit: (pageIndex: number, previousPage: ${dataT} | null) => ${optionsType} | null`,
|
|
2379
|
-
`config?: SWRInfiniteConfiguration<${dataT}, TError>`
|
|
2380
|
-
].join(", ");
|
|
2381
|
-
const infiniteKeyTuple = [
|
|
2382
|
-
`'${keyPrefix}'`,
|
|
2383
|
-
`'${pathStr}'`,
|
|
2384
|
-
`'infinite'`,
|
|
2385
|
-
"pageIndex",
|
|
2386
|
-
...paramPass,
|
|
2387
|
-
"keyArgs"
|
|
2388
|
-
].join(", ");
|
|
2389
|
-
const fetcherDestructure = [
|
|
2390
|
-
"_resource",
|
|
2391
|
-
"_opId",
|
|
2392
|
-
"_infinite",
|
|
2393
|
-
"_pageIndex",
|
|
2394
|
-
...paramPass.map((_, i) => `_key${i}`),
|
|
2395
|
-
"keyArgs"
|
|
2396
|
-
].join(", ");
|
|
2397
|
-
return `${keyCode}\n\n${hookCode}\n\n${`export function ${infiniteHookName}${generics}(${infiniteHookSig}){${`const getKey=(pageIndex:number,previousPage:${dataT}|null)=>{const options=buildInit(pageIndex,previousPage);if(options===null)return null;const{headers:_h,fetch:_f,throwHttpError:_t,...keyArgs}=options??{};return[${infiniteKeyTuple}]as const}`};return useSWRInfinite<${dataT},TError,typeof getKey>(getKey,async([${fetcherDestructure}])=>{const{data,error}=await ${callExpr}(keyArgs);if(error)throw error;return data},config)}`}`;
|
|
2398
|
-
}
|
|
2399
|
-
return `${keyCode}\n\n${hookCode}`;
|
|
2400
|
-
}
|
|
2401
|
-
const keyCode = `export function ${keyName}(${paramSig.join(", ")}){return ${`[${[
|
|
2402
|
-
`'${keyPrefix}'`,
|
|
2403
|
-
`'${pathStr}'`,
|
|
2404
|
-
`'${method.toUpperCase()}'`,
|
|
2405
|
-
...paramPass
|
|
2406
|
-
].join(", ")}] as const`}}`;
|
|
2407
|
-
const keyCall = `${keyName}(${paramPass.join(", ")})`;
|
|
2408
|
-
const variablesType = isBodyMethod ? `{ body: ${argsType}[0]; options${optMark}: ${argsType}[1] }` : `{ options${optMark}: ${argsType}[0] }`;
|
|
2409
|
-
const triggerCallExpr = isBodyMethod ? `${callExpr}(arg.body, arg.options)` : `${callExpr}(arg.options)`;
|
|
2410
|
-
return `${keyCode}\n\n${`export function ${hookName}${`<TError = ${errorT}>`}(${[...paramSig, `config?: SWRMutationConfiguration<${dataT}, TError, ReturnType<typeof ${keyName}>, ${variablesType}>`].join(", ")}){return useSWRMutation<${dataT},TError,ReturnType<typeof ${keyName}>,${variablesType}>(${keyCall},${`async(_key:ReturnType<typeof ${keyName}>,{arg}:{arg:${variablesType}})=>{const{data,error}=await ${triggerCallExpr};if(error)throw error;return data}`},config)}`}`;
|
|
2411
2381
|
}
|
|
2412
2382
|
function needsFetchHook(pathStr) {
|
|
2413
2383
|
return pathStr.split("/").filter(Boolean).some((seg) => seg.includes(".") || seg.includes("{") && !/^\{[^}]+\}$/u.test(seg));
|
|
@@ -2426,281 +2396,456 @@ function successType(operation) {
|
|
|
2426
2396
|
if (info.void) return { dataT: "void" };
|
|
2427
2397
|
return { dataT: "unknown" };
|
|
2428
2398
|
}
|
|
2429
|
-
function
|
|
2430
|
-
return
|
|
2399
|
+
function isBodyMethod(method) {
|
|
2400
|
+
return method === "post" || method === "put" || method === "patch" || method === "delete";
|
|
2431
2401
|
}
|
|
2432
|
-
function
|
|
2433
|
-
const
|
|
2434
|
-
const Op = capitalize(funcName);
|
|
2435
|
-
const hookName = `${config.hookPrefix}${Op}`;
|
|
2436
|
-
const suspenseHookName = `${config.hookPrefix}Suspense${Op}`;
|
|
2437
|
-
const immutableHookName = `${config.hookPrefix}Immutable${Op}`;
|
|
2438
|
-
const keyPrefix = resourcePrefix(pathStr);
|
|
2439
|
-
const isQuery = method === "get" || method === "head";
|
|
2440
|
-
const params = pathParamNames(pathStr);
|
|
2441
|
-
const paramSig = params.map((p) => `${p}: string`);
|
|
2442
|
-
const paramPass = [...params];
|
|
2443
|
-
const hasQuery = (operation.parameters ?? []).some((p) => "in" in p && p.in === "query");
|
|
2444
|
-
const optionsType = hasQuery ? "{ headers?: Record<string, string>; query?: Record<string, unknown> }" : "{ headers?: Record<string, string> }";
|
|
2445
|
-
const { dataT } = successType(operation);
|
|
2446
|
-
const errorT = "unknown";
|
|
2447
|
-
const urlInner = pathStr.replaceAll(/\{([^}]+)\}/gu, (_, n) => `\${encodeURIComponent(${n})}`);
|
|
2448
|
-
const urlExpr = hasQuery ? `\`${urlInner}\${search.size ? \`?\${search}\` : ''}\`` : `\`${urlInner}\``;
|
|
2449
|
-
const searchCode = (opt) => hasQuery ? `const search=new URLSearchParams();for(const[k,v]of Object.entries(${opt}?.query??{})){if(v===undefined)continue;if(Array.isArray(v)){for(const x of v){search.append(k,String(x))}}else{search.set(k,String(v))}}` : "";
|
|
2450
|
-
const getBody = (returnAnnotation, opt, signal) => `${searchCode(opt)}const res=await fetch(${urlExpr},{headers:${opt}?.headers${signal ? ",signal" : ""}});if(!res.ok)throw await res.json();return JSON.parse(await res.text())`;
|
|
2451
|
-
const keyArgsDecl = hasQuery ? "const{headers:_h,...keyArgs}=options??{};" : "";
|
|
2452
|
-
const keyTuple = [
|
|
2453
|
-
`'${keyPrefix}'`,
|
|
2454
|
-
`'${pathStr}'`,
|
|
2455
|
-
...paramPass,
|
|
2456
|
-
...hasQuery ? ["keyArgs"] : []
|
|
2457
|
-
].join(", ");
|
|
2458
|
-
if (config.isSWR && isQuery) {
|
|
2459
|
-
const keyName = `${funcName}QueryKey`;
|
|
2460
|
-
const keyCode = `export function ${keyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){${keyArgsDecl}return[${keyTuple}]as const}`;
|
|
2461
|
-
const keyCall = `${keyName}(${[...paramPass, "options"].join(", ")})`;
|
|
2462
|
-
const fetcher = `async():Promise<${dataT}>=>{${getBody(dataT, "options", false)}}`;
|
|
2463
|
-
const hookSig = [
|
|
2464
|
-
...paramSig,
|
|
2465
|
-
`options?: ${optionsType}`,
|
|
2466
|
-
`config?: SWRConfiguration<${dataT}, TError>`
|
|
2467
|
-
].join(", ");
|
|
2468
|
-
const swrHook = (name, swrFn) => `export function ${name}<TError=${errorT}>(${hookSig}){return ${swrFn}<${dataT},TError>(${keyCall},${fetcher},config)}`;
|
|
2469
|
-
return `${keyCode}\n\n${config.immutableQueryFn ? `${swrHook(hookName, config.queryFn)}\n\n${swrHook(immutableHookName, config.immutableQueryFn)}` : swrHook(hookName, config.queryFn)}`;
|
|
2470
|
-
}
|
|
2471
|
-
const mutationBody = (opt, body) => `${searchCode(opt)}const res=await fetch(${urlExpr},{method:'${method.toUpperCase()}',headers:{'content-type':'application/json',...${opt}?.headers},body:${body}===undefined?undefined:JSON.stringify(${body})});if(!res.ok)throw await res.json();return JSON.parse(await res.text())`;
|
|
2472
|
-
const variablesType = `{ body?: unknown; options?: ${optionsType} }`;
|
|
2473
|
-
if (config.isSWR) {
|
|
2474
|
-
const keyName = `${funcName}MutationKey`;
|
|
2475
|
-
const keyExpr = `[${[
|
|
2476
|
-
`'${keyPrefix}'`,
|
|
2477
|
-
`'${pathStr}'`,
|
|
2478
|
-
`'${method.toUpperCase()}'`,
|
|
2479
|
-
...paramPass
|
|
2480
|
-
].join(", ")}] as const`;
|
|
2481
|
-
const keyCode = `export function ${keyName}(${paramSig.join(", ")}){return ${keyExpr}}`;
|
|
2482
|
-
const keyCall = `${keyName}(${paramPass.join(", ")})`;
|
|
2483
|
-
const triggerCb = `async(_key:ReturnType<typeof ${keyName}>,{arg}:{arg:${variablesType}}):Promise<${dataT}>=>{${mutationBody("arg.options", "arg.body")}}`;
|
|
2484
|
-
return `${keyCode}\n\n${`export function ${hookName}<TError=${errorT}>(${[...paramSig, `config?: SWRMutationConfiguration<${dataT}, TError, ReturnType<typeof ${keyName}>, ${variablesType}>`].join(", ")}){return useSWRMutation<${dataT},TError,ReturnType<typeof ${keyName}>,${variablesType}>(${keyCall},${triggerCb},config)}`}`;
|
|
2485
|
-
}
|
|
2486
|
-
if (isQuery) {
|
|
2487
|
-
const keyName = `${funcName}QueryKey`;
|
|
2488
|
-
const keyCode = `export function ${keyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){${keyArgsDecl}return[${keyTuple}]as const}`;
|
|
2489
|
-
const keyCall = `${keyName}(${[...paramPass, "options"].join(", ")})`;
|
|
2490
|
-
const queryFnBlock = `queryFn:async(${config.queryFnContext ? "{signal}:QueryFunctionContext" : "{signal}"}):Promise<${dataT}>=>{${getBody(dataT, "options", true)}},`;
|
|
2491
|
-
const queryOptionsCode = `export function ${`${funcName}QueryOptions`}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){return queryOptions({queryKey:${keyCall},queryFn:async({signal}):Promise<${dataT}>=>{${getBody(dataT, "options", true)}}})}`;
|
|
2492
|
-
const generics = `<TData = ${dataT}, TError = ${errorT}>`;
|
|
2493
|
-
const queryOptionsParam = makeGetQueryOptionsParam(config, dataT, keyName);
|
|
2494
|
-
const parts = [
|
|
2495
|
-
keyCode,
|
|
2496
|
-
queryOptionsCode,
|
|
2497
|
-
`export function ${hookName}${generics}(${[
|
|
2498
|
-
...paramSig,
|
|
2499
|
-
`options?: ${optionsType}`,
|
|
2500
|
-
queryOptionsParam
|
|
2501
|
-
].join(", ")}){return ${makeGetHookBody(config, dataT, keyCall, queryFnBlock)}}`
|
|
2502
|
-
];
|
|
2503
|
-
if (config.suspenseQueryFn) {
|
|
2504
|
-
const suspenseHookCode = `export function ${suspenseHookName}${generics}(${[
|
|
2505
|
-
...paramSig,
|
|
2506
|
-
`options?: ${optionsType}`,
|
|
2507
|
-
`queryOptions?: ${omitInjectedKeys(config, `${config.suspenseQueryOptionsType}<${dataT}, TError, TData>`, QUERY_OMIT_KEYS)}`
|
|
2508
|
-
].join(", ")}){return ${config.suspenseQueryFn}<${dataT},TError,TData>({...queryOptions,queryKey:${keyCall},${queryFnBlock}})}`;
|
|
2509
|
-
parts.push(suspenseHookCode);
|
|
2510
|
-
}
|
|
2511
|
-
return parts.join("\n\n");
|
|
2512
|
-
}
|
|
2513
|
-
const keyName = `${funcName}MutationKey`;
|
|
2514
|
-
const keyExpr = `[${[
|
|
2515
|
-
`'${keyPrefix}'`,
|
|
2516
|
-
`'${pathStr}'`,
|
|
2517
|
-
`'${method.toUpperCase()}'`,
|
|
2518
|
-
...paramPass
|
|
2519
|
-
].join(", ")}] as const`;
|
|
2520
|
-
const keyCode = `export function ${keyName}(${paramSig.join(", ")}){return ${keyExpr}}`;
|
|
2521
|
-
const keyCall = `${keyName}(${paramPass.join(", ")})`;
|
|
2522
|
-
const mutationFnBlock = `mutationFn:async({body,options}):Promise<${dataT}>=>{${mutationBody("options", "body")}},`;
|
|
2523
|
-
const mutationOptionsName = `${funcName}MutationOptions`;
|
|
2524
|
-
const factoryCode = makeMutationFactoryCode(mutationOptionsName, paramSig.join(", "), keyCall, dataT, errorT, variablesType, mutationFnBlock);
|
|
2525
|
-
const factoryCall = `${mutationOptionsName}<TError>(${paramPass.join(", ")})`;
|
|
2526
|
-
const mutationOptionsParam = makeMutationOptionsParam(config, dataT, "TError", variablesType);
|
|
2527
|
-
return `${keyCode}\n\n${factoryCode}\n\n${`export function ${hookName}<TError=${errorT}>(${[...paramSig, mutationOptionsParam].join(", ")}){return ${makeMutationHookBody(config, dataT, variablesType, factoryCall)}}`}`;
|
|
2528
|
-
}
|
|
2529
|
-
function makeOperation(pathStr, method, operation, client, config) {
|
|
2530
|
-
if (needsFetchHook(pathStr)) return makeFetchOperation(pathStr, method, operation, config);
|
|
2531
|
-
const funcName = toSafeIdentifier(resolveOperationId(operation, method, pathStr));
|
|
2532
|
-
const Op = capitalize(funcName);
|
|
2533
|
-
const hookName = `${config.hookPrefix}${Op}`;
|
|
2534
|
-
const suspenseHookName = `${config.hookPrefix}Suspense${Op}`;
|
|
2535
|
-
const immutableHookName = `${config.hookPrefix}Immutable${Op}`;
|
|
2536
|
-
const isQuery = method === "get" || method === "head";
|
|
2537
|
-
const keyName = `${funcName}${isQuery ? "QueryKey" : "MutationKey"}`;
|
|
2538
|
-
const keyPrefix = resourcePrefix(pathStr);
|
|
2539
|
-
const { callExpr, methodHostTypeExpr, paramArgs } = edenChain(pathStr, client, method);
|
|
2540
|
-
const paramSig = paramArgs.map((p) => `${p.name}: ${p.typeExpr}`);
|
|
2541
|
-
const paramPass = paramArgs.map((p) => p.name);
|
|
2402
|
+
function edenTarget(fullPath, method, operation, client) {
|
|
2403
|
+
const { callExpr, methodHostTypeExpr, paramArgs } = edenChain(fullPath, client, method);
|
|
2542
2404
|
const argsType = `Parameters<${methodHostTypeExpr}>`;
|
|
2543
|
-
const
|
|
2405
|
+
const withBody = isBodyMethod(method);
|
|
2406
|
+
const optionsType = withBody ? `${argsType}[1]` : `${argsType}[0]`;
|
|
2544
2407
|
const response = `Awaited<ReturnType<${methodHostTypeExpr}>>`;
|
|
2545
|
-
const dataT = `Extract<${response}, { error: null }>['data']`;
|
|
2546
|
-
const errorT = `Exclude<${response}['error'], null>`;
|
|
2547
|
-
const isBodyMethod = method === "post" || method === "put" || method === "patch" || method === "delete";
|
|
2548
|
-
const isPaginated = operation["x-pagination"] === true;
|
|
2549
|
-
const hasKeyArgs = (operation.parameters ?? []).some((p) => "in" in p ? p.in === "query" : true);
|
|
2550
2408
|
const requiredOptions = (operation.parameters ?? []).some((p) => "in" in p && (p.in === "query" || p.in === "header") && p.required === true);
|
|
2551
|
-
const
|
|
2552
|
-
const
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2409
|
+
const call = (exprs) => paramArgs.reduce((acc, param, index) => acc.replace(`(${param.name})`, `(${exprs[index] ?? param.name})`), callExpr);
|
|
2410
|
+
const access = requiredOptions ? "." : "?.";
|
|
2411
|
+
return {
|
|
2412
|
+
params: paramArgs.map((p) => ({
|
|
2413
|
+
name: p.name,
|
|
2414
|
+
type: p.typeExpr
|
|
2415
|
+
})),
|
|
2416
|
+
optionsType,
|
|
2417
|
+
requiredOptions,
|
|
2418
|
+
hasKeyArgs: (operation.parameters ?? []).some((p) => "in" in p ? p.in === "query" : true),
|
|
2419
|
+
keyDrops: [
|
|
2420
|
+
"headers",
|
|
2421
|
+
"fetch",
|
|
2422
|
+
"throwHttpError"
|
|
2423
|
+
],
|
|
2424
|
+
dataT: `Extract<${response}, { error: null }>['data']`,
|
|
2425
|
+
errorT: `Exclude<${response}['error'], null>`,
|
|
2426
|
+
...withBody ? { bodyType: `${argsType}[0]` } : {},
|
|
2427
|
+
bodyRequired: operation.requestBody !== void 0,
|
|
2428
|
+
queryBody: (exprs, options, signal) => `const{data,error}=await ${call(exprs)}(${signal ? `{...${options},fetch:{...${options}${access}fetch,signal}}` : options});if(error)throw error;return data`,
|
|
2429
|
+
mutationBody: (exprs, body, options) => `const{data,error}=await ${call(exprs)}(${withBody ? `${body},${options}` : options});if(error)throw error;return data`
|
|
2430
|
+
};
|
|
2431
|
+
}
|
|
2432
|
+
function fetchTarget(fullPath, method, operation) {
|
|
2433
|
+
const names = pathParamNames(fullPath);
|
|
2434
|
+
const hasQuery = (operation.parameters ?? []).some((p) => "in" in p && p.in === "query");
|
|
2435
|
+
const optionsType = hasQuery ? "{ headers?: Record<string, string>; query?: Record<string, unknown> }" : "{ headers?: Record<string, string> }";
|
|
2436
|
+
const withBody = isBodyMethod(method);
|
|
2437
|
+
const { dataT, importName } = successType(operation);
|
|
2438
|
+
const url = (exprs) => {
|
|
2439
|
+
const inner = fullPath.replaceAll(/\{([^}]+)\}/gu, (_, n) => {
|
|
2440
|
+
return `\${encodeURIComponent(${exprs[names.indexOf(n)] ?? n})}`;
|
|
2441
|
+
});
|
|
2442
|
+
return hasQuery ? `\`${inner}\${search.size ? \`?\${search}\` : ''}\`` : `\`${inner}\``;
|
|
2443
|
+
};
|
|
2444
|
+
const search = (options) => hasQuery ? `const search=new URLSearchParams();for(const[k,v]of Object.entries(${options}?.query??{})){if(v===undefined)continue;if(Array.isArray(v)){for(const x of v){search.append(k,String(x))}}else{search.set(k,String(v))}}` : "";
|
|
2445
|
+
return {
|
|
2446
|
+
params: names.map((name) => ({
|
|
2447
|
+
name,
|
|
2448
|
+
type: "string"
|
|
2449
|
+
})),
|
|
2563
2450
|
optionsType,
|
|
2451
|
+
requiredOptions: false,
|
|
2452
|
+
hasKeyArgs: hasQuery,
|
|
2453
|
+
keyDrops: ["headers"],
|
|
2564
2454
|
dataT,
|
|
2565
|
-
errorT,
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2455
|
+
errorT: "unknown",
|
|
2456
|
+
...withBody ? { bodyType: "unknown" } : {},
|
|
2457
|
+
bodyRequired: false,
|
|
2458
|
+
queryBody: (exprs, options, signal) => `${search(options)}const res=await fetch(${url(exprs)},{headers:${options}?.headers${signal ? ",signal" : ""}});if(!res.ok)throw await res.json();return JSON.parse(await res.text())`,
|
|
2459
|
+
mutationBody: (exprs, body, options) => `${search(options)}const res=await fetch(${url(exprs)},{method:'${method.toUpperCase()}',headers:{'content-type':'application/json',...${options}?.headers},body:${body}===undefined?undefined:JSON.stringify(${body})});if(!res.ok)throw await res.json();return JSON.parse(await res.text())`,
|
|
2460
|
+
...importName ? { fetchType: importName } : {}
|
|
2461
|
+
};
|
|
2462
|
+
}
|
|
2463
|
+
function queryNames(config, method, pathStr) {
|
|
2464
|
+
const name = capitalize(methodPath(method === "get" ? "" : method, pathStr));
|
|
2465
|
+
const full = capitalize(methodPath(method, pathStr));
|
|
2466
|
+
if (config.isSWR) return {
|
|
2467
|
+
hook: `${config.hookPrefix}${full}`,
|
|
2468
|
+
suspense: "",
|
|
2469
|
+
immutable: `${config.hookPrefix}Immutable${full}`,
|
|
2470
|
+
infinite: `${config.hookPrefix}Infinite${full}`,
|
|
2471
|
+
suspenseInfinite: "",
|
|
2472
|
+
key: `get${full}Key`,
|
|
2473
|
+
options: "",
|
|
2474
|
+
infiniteKey: `get${full}InfiniteKey`,
|
|
2475
|
+
infiniteOptions: ""
|
|
2476
|
+
};
|
|
2477
|
+
return {
|
|
2478
|
+
hook: `${config.hookPrefix}${name}`,
|
|
2479
|
+
suspense: `${config.hookPrefix}Suspense${name}`,
|
|
2480
|
+
immutable: "",
|
|
2481
|
+
infinite: `${config.hookPrefix}Infinite${name}`,
|
|
2482
|
+
suspenseInfinite: `${config.hookPrefix}SuspenseInfinite${name}`,
|
|
2483
|
+
key: `get${name}QueryKey`,
|
|
2484
|
+
options: `get${name}QueryOptions`,
|
|
2485
|
+
infiniteKey: `get${name}InfiniteQueryKey`,
|
|
2486
|
+
infiniteOptions: `get${name}InfiniteQueryOptions`
|
|
2487
|
+
};
|
|
2488
|
+
}
|
|
2489
|
+
const PLAIN = {
|
|
2490
|
+
paramSig: (t) => t.params.map((p) => `${p.name}: ${p.type}`),
|
|
2491
|
+
paramRead: (t) => t.params.map((p) => p.name),
|
|
2492
|
+
paramPass: (t) => t.params.map((p) => p.name)
|
|
2493
|
+
};
|
|
2494
|
+
const THUNK = {
|
|
2495
|
+
paramSig: (t) => t.params.map((p) => `${p.name}: () => ${p.type}`),
|
|
2496
|
+
paramRead: (t) => t.params.map((p) => `${p.name}()`),
|
|
2497
|
+
paramPass: (t) => t.params.map((p) => `${p.name}()`)
|
|
2498
|
+
};
|
|
2499
|
+
const REF = {
|
|
2500
|
+
paramSig: (t) => t.params.map((p) => `${p.name}: MaybeRefOrGetter<${p.type}>`),
|
|
2501
|
+
paramRead: (t) => t.params.map((p) => `toValue(${p.name})`),
|
|
2502
|
+
paramPass: (t) => t.params.map((p) => p.name)
|
|
2503
|
+
};
|
|
2504
|
+
/** How the key getters and factories of a library spell the path parameters. */
|
|
2505
|
+
function baseSpelling(config) {
|
|
2506
|
+
return config.isVueQuery ? REF : PLAIN;
|
|
2507
|
+
}
|
|
2508
|
+
/** How the hooks of a library spell the path parameters. */
|
|
2509
|
+
function hookSpelling(config) {
|
|
2510
|
+
if (config.useThunk) return THUNK;
|
|
2511
|
+
return baseSpelling(config);
|
|
2512
|
+
}
|
|
2513
|
+
/**
|
|
2514
|
+
* The cache key getter of a query: `['<prefix>', '<path>', ...params, keyArgs?]`, where `keyArgs`
|
|
2515
|
+
* is the options without the members that never identify a resource (headers, fetch). The
|
|
2516
|
+
* structured key lets a caller invalidate by prefix, by endpoint or by one request. An infinite
|
|
2517
|
+
* query puts `'infinite'` after the path, so its prefix matches infinite lists only.
|
|
2518
|
+
*
|
|
2519
|
+
* @see https://tanstack.com/query/latest/docs/framework/react/guides/query-keys
|
|
2520
|
+
*/
|
|
2521
|
+
function keyGetterCode(name, target, spelling, prefix, fullPath, marker) {
|
|
2522
|
+
const sig = [...spelling.paramSig(target), ...target.hasKeyArgs ? [`options${target.requiredOptions ? "" : "?"}: ${target.optionsType}`] : []];
|
|
2523
|
+
const drops = target.keyDrops.map((key, index) => `${key}:_${String.fromCodePoint(97 + index)}`);
|
|
2524
|
+
const keyArgs = target.hasKeyArgs ? `const{${drops.join(",")},...keyArgs}=options??{};` : "";
|
|
2525
|
+
const tuple = [
|
|
2526
|
+
`'${prefix}'`,
|
|
2527
|
+
`'${fullPath}'`,
|
|
2528
|
+
...marker ? [`'${marker}'`] : [],
|
|
2529
|
+
...spelling.paramRead(target),
|
|
2530
|
+
...target.hasKeyArgs ? ["keyArgs"] : []
|
|
2531
|
+
].join(", ");
|
|
2532
|
+
return `export function ${name}(${sig.join(", ")}){${keyArgs}return[${tuple}]as const}`;
|
|
2533
|
+
}
|
|
2534
|
+
function keyCall(name, target, spelling, optionsExpr) {
|
|
2535
|
+
return `${name}(${[...spelling.paramPass(target), ...target.hasKeyArgs ? [optionsExpr] : []].join(", ")})`;
|
|
2536
|
+
}
|
|
2537
|
+
function vueKey(target, call) {
|
|
2538
|
+
return target.params.length > 0 ? `computed(()=>${call})` : call;
|
|
2539
|
+
}
|
|
2540
|
+
/**
|
|
2541
|
+
* The hook's `options` parameter: the caller's slot beside the request options, optional unless
|
|
2542
|
+
* the request options are required. Thunk libraries take the whole object as `() => {...}`.
|
|
2543
|
+
*/
|
|
2544
|
+
function hookOptions(config, target, slotName, slot, withClientOptions = true) {
|
|
2545
|
+
const required = target.requiredOptions && withClientOptions;
|
|
2546
|
+
const type = `{ ${[`${slotName}?: ${slot}`, ...withClientOptions ? [`options${target.requiredOptions ? "" : "?"}: ${target.optionsType}`] : []].join("; ")} }`;
|
|
2547
|
+
return {
|
|
2548
|
+
sig: `options${required ? "" : "?"}: ${config.useThunk ? `() => ${type}` : type}`,
|
|
2549
|
+
read: config.useThunk ? required ? "options()" : "options?.()??{}" : required ? "options" : "options??{}"
|
|
2550
|
+
};
|
|
2551
|
+
}
|
|
2552
|
+
/**
|
|
2553
|
+
* A GET: key getter, `queryOptions` factory, hook and suspense hook.
|
|
2554
|
+
*
|
|
2555
|
+
* The request is written once, in the factory, and the hooks spread it with the caller's
|
|
2556
|
+
* options: `{ ...getXQueryOptions<TData, TError>(params, clientOptions), ...query }`. The factory
|
|
2557
|
+
* carries the hooks' `<TData, TError>` so that spread type-checks — `queryOptions()` bakes both
|
|
2558
|
+
* into its result. Vue is the exception: its `MaybeRef` option types do not take the branded
|
|
2559
|
+
* factory, so its factory is a plain object and its hooks write the key and the request inline.
|
|
2560
|
+
*/
|
|
2561
|
+
function queryCode(config, names, target, prefix, fullPath) {
|
|
2562
|
+
const base = baseSpelling(config);
|
|
2563
|
+
const hooks = hookSpelling(config);
|
|
2564
|
+
const keyCode = keyGetterCode(names.key, target, base, prefix, fullPath);
|
|
2565
|
+
const keyType = `ReturnType<typeof ${names.key}>`;
|
|
2566
|
+
const reads = base.paramRead(target);
|
|
2567
|
+
const factorySig = [...base.paramSig(target), `options${target.requiredOptions ? "" : "?"}: ${target.optionsType}`].join(", ");
|
|
2568
|
+
const generics = `<TData = ${target.dataT}, TError = ${target.errorT}>`;
|
|
2569
|
+
const tail = tailOf(config, "query");
|
|
2570
|
+
if (config.isVueQuery) {
|
|
2571
|
+
const factory = `export function ${names.options}(${factorySig}){return{queryKey:${vueKey(target, keyCall(names.key, target, base, "options"))},queryFn:async({signal}:QueryFunctionContext)=>{${target.queryBody(reads, "options", true)}}}}`;
|
|
2572
|
+
const options = hookOptions(config, target, "query", slotType(config, `${config.queryOptionsType}<${target.dataT}, TError, TData, ${target.dataT}, ${keyType}>`, QUERY_OMIT_KEYS));
|
|
2573
|
+
return [
|
|
2574
|
+
keyCode,
|
|
2575
|
+
factory,
|
|
2576
|
+
`export function ${names.hook}${generics}(${[...base.paramSig(target), options.sig].join(", ")}${tail.sig}){const{query:queryOptions,options:clientOptions}=${options.read};return ${config.queryFn}({...queryOptions,queryKey:${vueKey(target, keyCall(names.key, target, base, "clientOptions"))},queryFn:async({signal})=>{${target.queryBody(reads, "clientOptions", true)}}}${tail.arg})}`
|
|
2577
|
+
];
|
|
2578
|
+
}
|
|
2579
|
+
const factory = `export function ${names.options}${generics}(${factorySig}){return queryOptions<${target.dataT},TError,TData,${keyType}>({queryKey:${keyCall(names.key, target, base, "options")},queryFn:async({signal})=>{${target.queryBody(reads, "options", true)}}})}`;
|
|
2580
|
+
const factoryCall = `${names.options}<TData,TError>(${[...hooks.paramPass(target), "clientOptions"].join(", ")})`;
|
|
2581
|
+
const hookOf = (hookName, queryFn, optionsType) => {
|
|
2582
|
+
const options = hookOptions(config, target, "query", slotType(config, `${optionsType}<${target.dataT}, TError, TData, ${keyType}>`, QUERY_OMIT_KEYS));
|
|
2583
|
+
const sig = [...hooks.paramSig(target), options.sig].join(", ");
|
|
2584
|
+
if (config.useThunk) return `export function ${hookName}${generics}(${sig}${tail.sig}){return ${queryFn}(()=>{const{query,options:clientOptions}=${options.read};return{...${factoryCall},...query}}${tail.arg})}`;
|
|
2585
|
+
return `export function ${hookName}${generics}(${sig}${tail.sig}){const{query:queryOptions,options:clientOptions}=${options.read};return ${queryFn}({...${factoryCall},...queryOptions}${tail.arg})}`;
|
|
2586
|
+
};
|
|
2587
|
+
const parts = [
|
|
2588
|
+
keyCode,
|
|
2589
|
+
factory,
|
|
2590
|
+
hookOf(names.hook, config.queryFn, config.queryOptionsType ?? "")
|
|
2591
|
+
];
|
|
2592
|
+
if (config.suspenseQueryFn && config.suspenseQueryOptionsType) parts.push(hookOf(names.suspense, config.suspenseQueryFn, config.suspenseQueryOptionsType));
|
|
2593
|
+
return parts;
|
|
2594
|
+
}
|
|
2595
|
+
/**
|
|
2596
|
+
* A paginated GET (`x-pagination: true`): infinite key getter, `infiniteQueryOptions` factory,
|
|
2597
|
+
* infinite hook and suspense infinite hook.
|
|
2598
|
+
*
|
|
2599
|
+
* `pagination` carries the three page-param concerns TanStack v5 requires that the flag cannot
|
|
2600
|
+
* supply: where paging starts, how to read the next page param from a page, and how a page param
|
|
2601
|
+
* maps onto the request options (`getRequestArgs`). The factory carries the hooks' generics and
|
|
2602
|
+
* the hooks spread it. Vue Query's helper types `initialPageParam` as `MaybeRefDeep<TPageParam>`,
|
|
2603
|
+
* which a generic parameter never satisfies, so Vue gets a plain factory and inline hooks, with the
|
|
2604
|
+
* page-param functions traveling in the caller's `query` slot.
|
|
2605
|
+
*/
|
|
2606
|
+
function infiniteCode(config, names, target, prefix, fullPath) {
|
|
2607
|
+
const base = baseSpelling(config);
|
|
2608
|
+
const hooks = hookSpelling(config);
|
|
2609
|
+
const keyCode = keyGetterCode(names.infiniteKey, target, base, prefix, fullPath, "infinite");
|
|
2610
|
+
const keyType = `ReturnType<typeof ${names.infiniteKey}>`;
|
|
2611
|
+
const reads = base.paramRead(target);
|
|
2612
|
+
const optionsSig = `options${target.requiredOptions ? "" : "?"}: ${target.optionsType}`;
|
|
2613
|
+
const tail = tailOf(config, "infinite");
|
|
2614
|
+
const requestArgs = `getRequestArgs: (options: ${target.optionsType}, pageParam: unknown) => ${target.optionsType}`;
|
|
2615
|
+
const generics = `<TPageParam = unknown, TData = InfiniteData<${target.dataT}, TPageParam>, TError = ${target.errorT}>`;
|
|
2616
|
+
const pageBody = (options) => `const page=pagination.getRequestArgs(${options},pageParam);${target.queryBody(reads, "page", true)}`;
|
|
2617
|
+
if (config.isVueQuery) {
|
|
2618
|
+
const factorySig = [
|
|
2619
|
+
...base.paramSig(target),
|
|
2620
|
+
`pagination: { ${requestArgs} }`,
|
|
2621
|
+
optionsSig
|
|
2622
|
+
];
|
|
2623
|
+
const factory = `export function ${names.infiniteOptions}<TPageParam = unknown>(${factorySig.join(", ")}){return{queryKey:${vueKey(target, keyCall(names.infiniteKey, target, base, "options"))},queryFn:async({pageParam,signal}:QueryFunctionContext<${keyType},TPageParam>)=>{${pageBody("options")}}}}`;
|
|
2624
|
+
const slot = slotType(config, `${config.infiniteOptionsType}<${target.dataT}, TError, TData, ${keyType}, TPageParam>`, QUERY_OMIT_KEYS);
|
|
2625
|
+
const sig = [
|
|
2626
|
+
...base.paramSig(target),
|
|
2627
|
+
`pagination: { ${requestArgs} }`,
|
|
2628
|
+
`options: { query: ${slot}; ${optionsSig} }`
|
|
2580
2629
|
].join(", ");
|
|
2581
|
-
|
|
2582
|
-
const keyCall = `${keyName}(${[...paramPass, ...hasKeyArgs ? ["options"] : []].join(", ")})`;
|
|
2583
|
-
const queryOptionsCode = `export function ${`${funcName}QueryOptions`}(${[...paramSig, `options${optMark}: ${optionsType}`].join(", ")}){return queryOptions({queryKey:${keyCall},queryFn:async({signal})=>{const{data,error}=await ${callExpr}({...options,fetch:{...${optFetch},signal}});if(error)throw error;return data}})}`;
|
|
2584
|
-
const queryFnBlock = `queryFn:async(${config.queryFnContext ? "{signal}:QueryFunctionContext" : "{signal}"})=>{const{data,error}=await ${callExpr}({...options,fetch:{...${optFetch},signal}});if(error)throw error;return data},`;
|
|
2585
|
-
const generics = `<TData = ${dataT}, TError = ${errorT}>`;
|
|
2586
|
-
const queryOptionsParam = makeGetQueryOptionsParam(config, dataT, keyName);
|
|
2587
|
-
const parts = [
|
|
2630
|
+
return [
|
|
2588
2631
|
keyCode,
|
|
2589
|
-
|
|
2590
|
-
`export function ${
|
|
2591
|
-
...paramSig,
|
|
2592
|
-
`options${optMark}: ${optionsType}`,
|
|
2593
|
-
queryOptionsParam
|
|
2594
|
-
].join(", ")}){return ${makeGetHookBody(config, dataT, keyCall, queryFnBlock)}}`
|
|
2632
|
+
factory,
|
|
2633
|
+
`export function ${names.infinite}${generics}(${sig}${tail.sig}){const{query:queryOptions,options:clientOptions}=options;return ${config.infiniteQueryFn}({...queryOptions,queryKey:${vueKey(target, keyCall(names.infiniteKey, target, base, "clientOptions"))},queryFn:async({pageParam,signal}:QueryFunctionContext<${keyType},TPageParam>)=>{${pageBody("clientOptions")}}}${tail.arg})}`
|
|
2595
2634
|
];
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
}));
|
|
2617
|
-
return
|
|
2618
|
-
}
|
|
2619
|
-
const
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
const
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
}
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
const
|
|
2642
|
-
const
|
|
2643
|
-
const
|
|
2644
|
-
const
|
|
2645
|
-
const
|
|
2646
|
-
|
|
2647
|
-
}
|
|
2648
|
-
|
|
2635
|
+
}
|
|
2636
|
+
const pagination = `pagination: { initialPageParam: TPageParam; getNextPageParam: (lastPage: ${target.dataT}, allPages: ${target.dataT}[], lastPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | undefined | null; ${requestArgs} }`;
|
|
2637
|
+
const factorySig = [
|
|
2638
|
+
...base.paramSig(target),
|
|
2639
|
+
pagination,
|
|
2640
|
+
optionsSig
|
|
2641
|
+
].join(", ");
|
|
2642
|
+
const factory = `export function ${names.infiniteOptions}${generics}(${factorySig}){return infiniteQueryOptions<${target.dataT},TError,TData,${keyType},TPageParam>({queryKey:${keyCall(names.infiniteKey, target, base, "options")},queryFn:async({pageParam,signal}:QueryFunctionContext<${keyType},TPageParam>)=>{${pageBody("options")}},initialPageParam:pagination.initialPageParam,getNextPageParam:pagination.getNextPageParam})}`;
|
|
2643
|
+
const factoryCall = `${names.infiniteOptions}<TPageParam,TData,TError>(${[
|
|
2644
|
+
...hooks.paramPass(target),
|
|
2645
|
+
"pagination",
|
|
2646
|
+
"clientOptions"
|
|
2647
|
+
].join(", ")})`;
|
|
2648
|
+
const hookOf = (hookName, queryFn, optionsType) => {
|
|
2649
|
+
const options = hookOptions(config, target, "query", slotType(config, `${optionsType}<${target.dataT}, TError, TData, ${keyType}, TPageParam>`, INFINITE_OMIT_KEYS));
|
|
2650
|
+
const sig = [
|
|
2651
|
+
...hooks.paramSig(target),
|
|
2652
|
+
pagination,
|
|
2653
|
+
options.sig
|
|
2654
|
+
].join(", ");
|
|
2655
|
+
if (config.useThunk) return `export function ${hookName}${generics}(${sig}${tail.sig}){return ${queryFn}(()=>{const{query,options:clientOptions}=${options.read};return{...${factoryCall},...query}}${tail.arg})}`;
|
|
2656
|
+
return `export function ${hookName}${generics}(${sig}${tail.sig}){const{query:queryOptions,options:clientOptions}=${options.read};return ${queryFn}({...${factoryCall},...queryOptions}${tail.arg})}`;
|
|
2657
|
+
};
|
|
2658
|
+
const parts = [
|
|
2659
|
+
keyCode,
|
|
2660
|
+
factory,
|
|
2661
|
+
hookOf(names.infinite, config.infiniteQueryFn, config.infiniteOptionsType ?? "")
|
|
2662
|
+
];
|
|
2663
|
+
if (config.suspenseInfiniteQueryFn && config.suspenseInfiniteOptionsType) parts.push(hookOf(names.suspenseInfinite, config.suspenseInfiniteQueryFn, config.suspenseInfiniteOptionsType));
|
|
2664
|
+
return parts;
|
|
2665
|
+
}
|
|
2666
|
+
/** The variables a mutation takes: the body, when the method carries one, beside the request options. */
|
|
2667
|
+
function variablesType(target) {
|
|
2668
|
+
const options = `options${target.requiredOptions ? "" : "?"}: ${target.optionsType}`;
|
|
2669
|
+
return target.bodyType ? `{ body${target.bodyRequired ? "" : "?"}: ${target.bodyType}; ${options} }` : `{ ${options} }`;
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* A mutation: key getter, `mutationOptions` factory and hook.
|
|
2673
|
+
*
|
|
2674
|
+
* The variables are `{ body, options }` for a method that carries a body and `{ options }` for the
|
|
2675
|
+
* rest, so the request is spelled out at the call to `mutate`. The hook spreads the caller's
|
|
2676
|
+
* options first and the factory after it, so the operation contract wins — `Omit` only rejects a
|
|
2677
|
+
* fresh object literal — and then restores the caller's `mutationKey`.
|
|
2678
|
+
*/
|
|
2679
|
+
function mutationCode(config, method, pathStr, target, prefix, fullPath) {
|
|
2680
|
+
const base = baseSpelling(config);
|
|
2681
|
+
const hooks = hookSpelling(config);
|
|
2682
|
+
const name = capitalize(methodPath(method, pathStr));
|
|
2683
|
+
const hookName = `${config.hookPrefix}${name}`;
|
|
2684
|
+
const keyName = `get${name}MutationKey`;
|
|
2685
|
+
const factoryName = `get${name}MutationOptions`;
|
|
2686
|
+
const keyCode = `export function ${keyName}(){return['${prefix}', '${fullPath}', '${method.toUpperCase()}']as const}`;
|
|
2687
|
+
const variables = variablesType(target);
|
|
2688
|
+
const destructure = target.bodyType ? "{body,options}" : "{options}";
|
|
2689
|
+
const bodyExpr = target.bodyType ? "body" : "undefined";
|
|
2690
|
+
const generics = `<TError = ${target.errorT}, TOnMutateResult = unknown>`;
|
|
2691
|
+
const factory = `export function ${factoryName}${generics}(${base.paramSig(target).join(", ")}){return mutationOptions<${target.dataT},TError,${variables},TOnMutateResult>({mutationKey:${keyName}(),mutationFn:async(${destructure})=>{${target.mutationBody(base.paramRead(target), bodyExpr, "options")}}})}`;
|
|
2692
|
+
const factoryCall = `${factoryName}<TError,TOnMutateResult>(${hooks.paramPass(target).join(", ")})`;
|
|
2693
|
+
const options = hookOptions(config, target, "mutation", slotType(config, `${config.mutationOptionsType}<${target.dataT}, TError, ${variables}, TOnMutateResult>`, MUTATION_OMIT_KEYS, VUE_MUTATION_MEMBER), false);
|
|
2694
|
+
const tail = tailOf(config, "mutation");
|
|
2695
|
+
const sig = [...hooks.paramSig(target), options.sig].join(", ");
|
|
2696
|
+
const merge = `{...mutation,...mutationDefaults,mutationKey:mutation?.mutationKey??mutationDefaults.mutationKey}`;
|
|
2697
|
+
if (config.useThunk) return [
|
|
2698
|
+
keyCode,
|
|
2699
|
+
factory,
|
|
2700
|
+
`export function ${hookName}${generics}(${sig}${tail.sig}){return ${config.mutationFn}(()=>{const{mutation}=${options.read};const mutationDefaults=${factoryCall};return ${merge}}${tail.arg})}`
|
|
2701
|
+
];
|
|
2702
|
+
return [
|
|
2703
|
+
keyCode,
|
|
2704
|
+
factory,
|
|
2705
|
+
`export function ${hookName}${generics}(${sig}${tail.sig}){const{mutation}=${options.read};const mutationDefaults=${factoryCall};return ${config.mutationFn}(${merge}${tail.arg})}`
|
|
2706
|
+
];
|
|
2707
|
+
}
|
|
2708
|
+
/**
|
|
2709
|
+
* SWR: `useSWR` and `useSWRImmutable` hooks for a GET, and `useSWRInfinite` for a paginated one.
|
|
2710
|
+
* A hook takes `{ swr, options }`: `swr` is the SWR configuration plus `swrKey`, which replaces
|
|
2711
|
+
* the generated key, and `enabled`, which turns the key into `null` — how SWR is told not to
|
|
2712
|
+
* fetch. The hook answers with the key it used beside SWR's own result.
|
|
2713
|
+
*/
|
|
2714
|
+
function swrQueryCode(config, names, target, prefix, fullPath, paginated) {
|
|
2715
|
+
const keyCode = keyGetterCode(names.key, target, PLAIN, prefix, fullPath);
|
|
2716
|
+
const params = PLAIN.paramSig(target);
|
|
2717
|
+
const reads = PLAIN.paramRead(target);
|
|
2718
|
+
const mark = target.requiredOptions ? "" : "?";
|
|
2719
|
+
const swrOptions = `SWRConfiguration<${target.dataT}, TError> & { swrKey?: Key; enabled?: boolean }`;
|
|
2720
|
+
const sig = [...params, `options${mark}: { swr?: ${swrOptions}; options${mark}: ${target.optionsType} }`];
|
|
2721
|
+
const read = mark === "" ? "options" : "options??{}";
|
|
2722
|
+
const hookOf = (hookName, swrFn) => `export function ${hookName}<TError = ${target.errorT}>(${sig.join(", ")}){const{swr:swrOptions,options:clientOptions}=${read};const{swrKey:customKey,enabled,...restSwrOptions}=swrOptions??{};const swrKey=enabled!==false?(customKey===undefined?${keyCall(names.key, target, PLAIN, "clientOptions")}:customKey):null;return{swrKey,...${swrFn}<${target.dataT},TError>(swrKey,async()=>{${target.queryBody(reads, "clientOptions", false)}},restSwrOptions)}}`;
|
|
2723
|
+
const parts = [keyCode, hookOf(names.hook, config.queryFn)];
|
|
2724
|
+
if (config.immutableQueryFn) parts.push(hookOf(names.immutable, config.immutableQueryFn));
|
|
2725
|
+
if (!paginated) return parts;
|
|
2726
|
+
const infiniteKeyCode = keyGetterCode(names.infiniteKey, target, PLAIN, prefix, fullPath, "infinite");
|
|
2727
|
+
const loaderKey = `readonly [...ReturnType<typeof ${names.infiniteKey}>, number]`;
|
|
2728
|
+
const infiniteSwr = `SWRInfiniteConfiguration<${target.dataT}, TError> & { swrKey?: (index: number, previousPageData: ${target.dataT} | null) => ${loaderKey} | null; enabled?: boolean }`;
|
|
2729
|
+
const infiniteSig = [...params, `options: { swr?: ${infiniteSwr}; options${mark}: ${target.optionsType}; pagination: { getRequestArgs: (options: ${target.optionsType}, index: number) => ${target.optionsType} } }`];
|
|
2730
|
+
const leading = 3 + target.params.length + (target.hasKeyArgs ? 1 : 0);
|
|
2731
|
+
const infinite = `export function ${names.infinite}<TError = ${target.errorT}>(${infiniteSig.join(", ")}){const{swr:swrOptions,options:clientOptions,pagination}=options;const{swrKey:customKeyLoader,enabled,...restSwrOptions}=swrOptions??{};const keyLoader=enabled!==false?(customKeyLoader??((index:number)=>[...${keyCall(names.infiniteKey, target, PLAIN, "clientOptions")},index]as const)):()=>null;return useSWRInfinite(keyLoader,async([${",".repeat(leading)}index]:${loaderKey})=>{const page=pagination.getRequestArgs(clientOptions,index);${target.queryBody(reads, "page", false)}},restSwrOptions)}`;
|
|
2732
|
+
parts.push(infiniteKeyCode, infinite);
|
|
2733
|
+
return parts;
|
|
2734
|
+
}
|
|
2735
|
+
/** SWR: a `useSWRMutation` hook, taking `{ mutation }` with `swrKey` replacing the generated key. */
|
|
2736
|
+
function swrMutationCode(config, method, pathStr, target, prefix, fullPath) {
|
|
2737
|
+
const name = capitalize(methodPath(method, pathStr));
|
|
2738
|
+
const hookName = `${config.hookPrefix}${name}`;
|
|
2739
|
+
const keyName = `get${name}Key`;
|
|
2740
|
+
const keyCode = `export function ${keyName}(){return['${prefix}', '${fullPath}', '${method.toUpperCase()}']as const}`;
|
|
2741
|
+
const variables = variablesType(target);
|
|
2742
|
+
const mutationOptions = `SWRMutationConfiguration<${target.dataT}, TError, Key, ${variables}> & { swrKey?: Key; throwOnError?: boolean }`;
|
|
2743
|
+
const sig = [...PLAIN.paramSig(target), `options?: { mutation?: ${mutationOptions} }`];
|
|
2744
|
+
const bodyExpr = target.bodyType ? "arg.body" : "undefined";
|
|
2745
|
+
return [keyCode, `export function ${hookName}<TError = ${target.errorT}>(${sig.join(", ")}){const{mutation:mutationOptions}=options??{};const{swrKey:customKey,...restMutationOptions}=mutationOptions??{};const swrKey=customKey??${keyName}();return{swrKey,...useSWRMutation<${target.dataT},TError,Key,${variables}>(swrKey,async(_key:Key,{arg}:{arg:${variables}})=>{${target.mutationBody(PLAIN.paramRead(target), bodyExpr, "arg.options")}},restMutationOptions)}}`];
|
|
2746
|
+
}
|
|
2747
|
+
/** Every hook and helper of one operation, in the order they are written. */
|
|
2748
|
+
function operationCode(config, pathStr, fullPath, method, operation, client) {
|
|
2749
|
+
const target = needsFetchHook(fullPath) ? fetchTarget(fullPath, method, operation) : edenTarget(fullPath, method, operation, client);
|
|
2750
|
+
const prefix = resourcePrefix(fullPath);
|
|
2751
|
+
const isQuery = method === "get" || method === "head";
|
|
2752
|
+
const paginated = isQuery && operation["x-pagination"] === true;
|
|
2753
|
+
const names = queryNames(config, method, pathStr);
|
|
2754
|
+
return {
|
|
2755
|
+
code: (config.isSWR ? isQuery ? swrQueryCode(config, names, target, prefix, fullPath, paginated) : swrMutationCode(config, method, pathStr, target, prefix, fullPath) : isQuery ? [...queryCode(config, names, target, prefix, fullPath), ...paginated ? infiniteCode(config, names, target, prefix, fullPath) : []] : mutationCode(config, method, pathStr, target, prefix, fullPath)).join("\n\n"),
|
|
2756
|
+
fetchType: target.fetchType
|
|
2757
|
+
};
|
|
2758
|
+
}
|
|
2759
|
+
/**
|
|
2760
|
+
* The imports of a hooks file, read off the code it holds: a value and a type import from the
|
|
2761
|
+
* library, Vue's helpers when a ref is read, the response components the fetch fallbacks type
|
|
2762
|
+
* their data by, and the client. A name is imported only when the file uses it, so a document
|
|
2763
|
+
* with no mutation imports nothing a mutation would.
|
|
2764
|
+
*/
|
|
2765
|
+
function headerCode(config, client, importPath, body, fetchTypes, schemasImport) {
|
|
2766
|
+
const calls = (name) => new RegExp(`\\b${name}\\s*[<(]`, "u").test(body);
|
|
2767
|
+
const names = (name) => new RegExp(`\\b${name}\\b`, "u").test(body);
|
|
2768
|
+
const lines = [];
|
|
2769
|
+
if (config.isSWR) {
|
|
2770
|
+
if (calls("useSWR")) lines.push("import useSWR from 'swr'");
|
|
2771
|
+
if (calls("useSWRImmutable")) lines.push("import useSWRImmutable from 'swr/immutable'");
|
|
2772
|
+
const swrTypes = ["Key", "SWRConfiguration"].filter(names);
|
|
2773
|
+
if (swrTypes.length > 0) lines.push(`import type { ${swrTypes.join(", ")} } from 'swr'`);
|
|
2774
|
+
if (calls("useSWRInfinite")) lines.push("import useSWRInfinite from 'swr/infinite'", "import type { SWRInfiniteConfiguration } from 'swr/infinite'");
|
|
2775
|
+
if (calls("useSWRMutation")) lines.push("import useSWRMutation from 'swr/mutation'", "import type { SWRMutationConfiguration } from 'swr/mutation'");
|
|
2776
|
+
} else {
|
|
2777
|
+
const values = [...new Set(filterDefined([
|
|
2778
|
+
config.queryFn,
|
|
2779
|
+
config.suspenseQueryFn,
|
|
2780
|
+
config.infiniteQueryFn,
|
|
2781
|
+
config.suspenseInfiniteQueryFn,
|
|
2782
|
+
config.mutationFn,
|
|
2783
|
+
"queryOptions",
|
|
2784
|
+
"infiniteQueryOptions",
|
|
2785
|
+
"mutationOptions"
|
|
2786
|
+
]))].filter(calls);
|
|
2787
|
+
const types = [...new Set(filterDefined([
|
|
2788
|
+
config.queryOptionsType,
|
|
2789
|
+
"QueryFunctionContext",
|
|
2790
|
+
config.suspenseQueryOptionsType,
|
|
2791
|
+
config.infiniteOptionsType,
|
|
2792
|
+
config.suspenseInfiniteOptionsType,
|
|
2793
|
+
"InfiniteData",
|
|
2794
|
+
config.mutationOptionsType,
|
|
2795
|
+
...config.hookTail?.imports ?? []
|
|
2796
|
+
]))].filter(names);
|
|
2797
|
+
if (values.length > 0) lines.push(`import { ${values.join(", ")} } from '${config.packageName}'`);
|
|
2798
|
+
if (types.length > 0) lines.push(`import type { ${types.join(", ")} } from '${config.packageName}'`);
|
|
2799
|
+
const vue = ["computed", "toValue"].filter(calls);
|
|
2800
|
+
if (vue.length > 0) lines.push(`import { ${vue.join(", ")} } from 'vue'`);
|
|
2801
|
+
if (names("MaybeRefOrGetter")) lines.push("import type { MaybeRefOrGetter } from 'vue'");
|
|
2802
|
+
}
|
|
2803
|
+
if (fetchTypes.length > 0) lines.push(`import type { ${fetchTypes.join(", ")} } from '${schemasImport}'`);
|
|
2804
|
+
lines.push(`import { ${client} } from '${importPath}'`);
|
|
2805
|
+
return `${lines.join("\n")}\n\n`;
|
|
2806
|
+
}
|
|
2807
|
+
function makeQueryHooks(openAPI, output, importPath, config, client, basePath, schemasImport = "./components/schemas") {
|
|
2649
2808
|
return Effect.gen(function* () {
|
|
2650
2809
|
const prefix = basePath && basePath !== "/" ? basePath : "";
|
|
2651
|
-
const
|
|
2652
|
-
|
|
2653
|
-
if (!
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
const keyPrefix = resourcePrefix(`${prefix}${pathStr}`);
|
|
2661
|
-
const isQuery = method === "get" || method === "head";
|
|
2662
|
-
ops.push({
|
|
2663
|
-
funcName,
|
|
2664
|
-
code,
|
|
2665
|
-
prefix: keyPrefix,
|
|
2666
|
-
deps: {
|
|
2667
|
-
isQuery,
|
|
2668
|
-
isInfinite: isQuery && operation["x-pagination"] === true,
|
|
2669
|
-
isMutation: !isQuery
|
|
2670
|
-
},
|
|
2671
|
-
fetchType: fetchTypeImport(`${prefix}${pathStr}`, operation)
|
|
2672
|
-
});
|
|
2673
|
-
}
|
|
2674
|
-
}
|
|
2675
|
-
if (ops.length === 0) return "No operations found";
|
|
2676
|
-
if (split) {
|
|
2677
|
-
const prefixKeys = makePrefixKeyCodes(openAPI, prefix);
|
|
2678
|
-
const keysCode = prefixKeys.length > 0 ? `${prefixKeys.join("\n\n")}\n` : "";
|
|
2679
|
-
if (keysCode && ops.some((op) => op.funcName === "keys")) return yield* new GenerateError({ message: "Operation file name 'keys.ts' collides with the aggregated cache-key file. Rename the operation (operationId) that resolves to 'keys'." });
|
|
2680
|
-
for (const op of ops) {
|
|
2681
|
-
const header = makeHeader(config, client, importPath, op.deps);
|
|
2682
|
-
const typeImport = op.fetchType ? `import type { ${op.fetchType} } from '../components/schemas'\n` : "";
|
|
2683
|
-
const file = path.join(output, `${op.funcName}.ts`);
|
|
2684
|
-
yield* emit(`${typeImport}${header}${op.code}\n`, output, file);
|
|
2685
|
-
}
|
|
2686
|
-
if (keysCode) yield* emit(keysCode, output, path.join(output, "keys.ts"));
|
|
2687
|
-
yield* emit(`${[...keysCode ? [`export * from './keys'`] : [], ...ops.map((op) => `export * from './${op.funcName}'`)].join("\n")}\n`, output, path.join(output, "index.ts"));
|
|
2688
|
-
return `Generated split ${config.label} code → ${output}/`;
|
|
2689
|
-
}
|
|
2690
|
-
yield* emit(`${makeHeader(config, client, importPath, ops.reduce((acc, op) => ({
|
|
2691
|
-
isQuery: acc.isQuery || op.deps.isQuery,
|
|
2692
|
-
isInfinite: acc.isInfinite || op.deps.isInfinite,
|
|
2693
|
-
isMutation: acc.isMutation || op.deps.isMutation
|
|
2694
|
-
}), {
|
|
2695
|
-
isQuery: false,
|
|
2696
|
-
isInfinite: false,
|
|
2697
|
-
isMutation: false
|
|
2698
|
-
}))}${`${[...makePrefixKeyCodes(openAPI, prefix), ...ops.map((op) => op.code)].join("\n\n")}\n`}`, path.dirname(output), output);
|
|
2810
|
+
const operations = Object.entries(openAPI.paths).flatMap(([pathStr, pathItem]) => pathItem ? HTTP_METHODS.flatMap((method) => {
|
|
2811
|
+
const rawOperation = pathItem[method];
|
|
2812
|
+
if (!rawOperation) return [];
|
|
2813
|
+
const operation = resolveOperation(rawOperation, openAPI.components);
|
|
2814
|
+
return [operationCode(config, pathStr, `${prefix}${pathStr}`, method, operation, client)];
|
|
2815
|
+
}) : []);
|
|
2816
|
+
if (operations.length === 0) return "No operations found";
|
|
2817
|
+
const body = `${[...makePrefixKeyCodes(openAPI, prefix), ...operations.map((op) => op.code)].join("\n\n")}\n`;
|
|
2818
|
+
yield* emit(`${headerCode(config, client, importPath, body, [...new Set(filterDefined(operations.map((op) => op.fetchType)))].toSorted(), schemasImport)}${body}`, path.dirname(output), output);
|
|
2699
2819
|
return `Generated ${config.label} code written to ${output}`;
|
|
2700
2820
|
});
|
|
2701
2821
|
}
|
|
2702
2822
|
//#endregion
|
|
2703
2823
|
//#region src/core/hooks/index.ts
|
|
2824
|
+
const QUERY_CLIENT_TAIL = {
|
|
2825
|
+
name: "queryClient",
|
|
2826
|
+
query: "QueryClient",
|
|
2827
|
+
infinite: "QueryClient",
|
|
2828
|
+
mutation: "QueryClient",
|
|
2829
|
+
imports: ["QueryClient"]
|
|
2830
|
+
};
|
|
2831
|
+
const QUERY_CLIENT_ACCESSOR_TAIL = {
|
|
2832
|
+
name: "queryClient",
|
|
2833
|
+
query: "() => QueryClient",
|
|
2834
|
+
infinite: "() => QueryClient",
|
|
2835
|
+
mutation: "() => QueryClient",
|
|
2836
|
+
imports: ["QueryClient"]
|
|
2837
|
+
};
|
|
2838
|
+
const INJECT_OPTIONS_TAIL = {
|
|
2839
|
+
name: "injectOptions",
|
|
2840
|
+
query: "InjectQueryOptions",
|
|
2841
|
+
infinite: "InjectInfiniteQueryOptions",
|
|
2842
|
+
mutation: "InjectMutationOptions",
|
|
2843
|
+
imports: [
|
|
2844
|
+
"InjectQueryOptions",
|
|
2845
|
+
"InjectInfiniteQueryOptions",
|
|
2846
|
+
"InjectMutationOptions"
|
|
2847
|
+
]
|
|
2848
|
+
};
|
|
2704
2849
|
const TANSTACK = {
|
|
2705
2850
|
label: "tanstack-query",
|
|
2706
2851
|
packageName: "@tanstack/react-query",
|
|
@@ -2708,15 +2853,14 @@ const TANSTACK = {
|
|
|
2708
2853
|
queryFn: "useQuery",
|
|
2709
2854
|
mutationFn: "useMutation",
|
|
2710
2855
|
infiniteQueryFn: "useInfiniteQuery",
|
|
2711
|
-
useQueryGenerics: true,
|
|
2712
|
-
hasInfiniteQueryOptionsHelper: true,
|
|
2713
2856
|
suspenseQueryFn: "useSuspenseQuery",
|
|
2714
2857
|
suspenseInfiniteQueryFn: "useSuspenseInfiniteQuery",
|
|
2715
2858
|
queryOptionsType: "UseQueryOptions",
|
|
2716
2859
|
suspenseQueryOptionsType: "UseSuspenseQueryOptions",
|
|
2717
2860
|
mutationOptionsType: "UseMutationOptions",
|
|
2718
2861
|
infiniteOptionsType: "UseInfiniteQueryOptions",
|
|
2719
|
-
suspenseInfiniteOptionsType: "UseSuspenseInfiniteQueryOptions"
|
|
2862
|
+
suspenseInfiniteOptionsType: "UseSuspenseInfiniteQueryOptions",
|
|
2863
|
+
hookTail: QUERY_CLIENT_TAIL
|
|
2720
2864
|
};
|
|
2721
2865
|
const HOOK_CONFIGS = {
|
|
2722
2866
|
swr: {
|
|
@@ -2742,11 +2886,11 @@ const HOOK_CONFIGS = {
|
|
|
2742
2886
|
queryFn: "useQuery",
|
|
2743
2887
|
mutationFn: "useMutation",
|
|
2744
2888
|
infiniteQueryFn: "useInfiniteQuery",
|
|
2745
|
-
|
|
2746
|
-
maybeRefOptions: true,
|
|
2889
|
+
isVueQuery: true,
|
|
2747
2890
|
queryOptionsType: "UseQueryOptions",
|
|
2748
2891
|
mutationOptionsType: "UseMutationOptions",
|
|
2749
|
-
infiniteOptionsType: "UseInfiniteQueryOptions"
|
|
2892
|
+
infiniteOptionsType: "UseInfiniteQueryOptions",
|
|
2893
|
+
hookTail: QUERY_CLIENT_TAIL
|
|
2750
2894
|
},
|
|
2751
2895
|
"solid-query": {
|
|
2752
2896
|
label: "solid-query",
|
|
@@ -2755,14 +2899,12 @@ const HOOK_CONFIGS = {
|
|
|
2755
2899
|
queryFn: "createQuery",
|
|
2756
2900
|
mutationFn: "createMutation",
|
|
2757
2901
|
infiniteQueryFn: "createInfiniteQuery",
|
|
2758
|
-
queryFnContext: true,
|
|
2759
2902
|
useThunk: true,
|
|
2760
|
-
thunkOptionsCall: true,
|
|
2761
2903
|
unwrapOptionsAccessor: true,
|
|
2762
|
-
hasInfiniteQueryOptionsHelper: true,
|
|
2763
2904
|
queryOptionsType: "UndefinedInitialDataOptions",
|
|
2764
2905
|
mutationOptionsType: "CreateMutationOptions",
|
|
2765
|
-
infiniteOptionsType: "UndefinedInitialDataInfiniteOptions"
|
|
2906
|
+
infiniteOptionsType: "UndefinedInitialDataInfiniteOptions",
|
|
2907
|
+
hookTail: QUERY_CLIENT_ACCESSOR_TAIL
|
|
2766
2908
|
},
|
|
2767
2909
|
"svelte-query": {
|
|
2768
2910
|
label: "svelte-query",
|
|
@@ -2771,12 +2913,11 @@ const HOOK_CONFIGS = {
|
|
|
2771
2913
|
queryFn: "createQuery",
|
|
2772
2914
|
mutationFn: "createMutation",
|
|
2773
2915
|
infiniteQueryFn: "createInfiniteQuery",
|
|
2774
|
-
queryFnContext: true,
|
|
2775
2916
|
useThunk: true,
|
|
2776
|
-
hasInfiniteQueryOptionsHelper: true,
|
|
2777
2917
|
queryOptionsType: "CreateQueryOptions",
|
|
2778
2918
|
mutationOptionsType: "CreateMutationOptions",
|
|
2779
|
-
infiniteOptionsType: "CreateInfiniteQueryOptions"
|
|
2919
|
+
infiniteOptionsType: "CreateInfiniteQueryOptions",
|
|
2920
|
+
hookTail: QUERY_CLIENT_ACCESSOR_TAIL
|
|
2780
2921
|
},
|
|
2781
2922
|
"angular-query": {
|
|
2782
2923
|
label: "angular-query",
|
|
@@ -2785,16 +2926,27 @@ const HOOK_CONFIGS = {
|
|
|
2785
2926
|
queryFn: "injectQuery",
|
|
2786
2927
|
mutationFn: "injectMutation",
|
|
2787
2928
|
infiniteQueryFn: "injectInfiniteQuery",
|
|
2788
|
-
queryFnContext: true,
|
|
2789
2929
|
useThunk: true,
|
|
2790
|
-
hasInfiniteQueryOptionsHelper: true,
|
|
2791
2930
|
queryOptionsType: "CreateQueryOptions",
|
|
2792
2931
|
mutationOptionsType: "CreateMutationOptions",
|
|
2793
|
-
infiniteOptionsType: "CreateInfiniteQueryOptions"
|
|
2932
|
+
infiniteOptionsType: "CreateInfiniteQueryOptions",
|
|
2933
|
+
hookTail: INJECT_OPTIONS_TAIL
|
|
2794
2934
|
}
|
|
2795
2935
|
};
|
|
2936
|
+
/**
|
|
2937
|
+
* Generates the hooks of one client library into `output`.
|
|
2938
|
+
*
|
|
2939
|
+
* `schemas` is where `components.schemas` is written: a hook for a path Eden cannot type (a
|
|
2940
|
+
* segment with a `.` or a partial parameter) falls back to `fetch` and types its data by the
|
|
2941
|
+
* component the response names, so it has to import that component from wherever the schemas
|
|
2942
|
+
* generator put it — by the specifier the config names, or relative to `output`.
|
|
2943
|
+
*/
|
|
2796
2944
|
function hooks(openAPI, output, importPath, library, options) {
|
|
2797
|
-
|
|
2945
|
+
const schemasImport = options.schemas?.import ?? (options.schemas ? makeModuleSpec(path.resolve(process.cwd(), output), {
|
|
2946
|
+
output: path.resolve(process.cwd(), options.schemas.output),
|
|
2947
|
+
split: options.schemas.split
|
|
2948
|
+
}) : void 0);
|
|
2949
|
+
return makeQueryHooks(openAPI, output, importPath, HOOK_CONFIGS[library], options.client, options.basePath, schemasImport);
|
|
2798
2950
|
}
|
|
2799
2951
|
//#endregion
|
|
2800
2952
|
//#region src/helper/faker.ts
|
|
@@ -3286,9 +3438,9 @@ function credentialExpr(scheme) {
|
|
|
3286
3438
|
if (scheme.type === "http" || scheme.type === "oauth2" || scheme.type === "openIdConnect") return "c.headers.authorization";
|
|
3287
3439
|
if (scheme.type !== "apiKey") return void 0;
|
|
3288
3440
|
const name = scheme.name ?? "X-API-Key";
|
|
3289
|
-
if (scheme.in === "query") return `c.query[${quoteSingle
|
|
3290
|
-
if (scheme.in === "cookie") return `c.cookie[${quoteSingle
|
|
3291
|
-
return `c.headers[${quoteSingle
|
|
3441
|
+
if (scheme.in === "query") return `c.query[${quoteSingle(name)}]`;
|
|
3442
|
+
if (scheme.in === "cookie") return `c.cookie[${quoteSingle(name)}]?.value`;
|
|
3443
|
+
return `c.headers[${quoteSingle(name.toLowerCase())}]`;
|
|
3292
3444
|
}
|
|
3293
3445
|
/**
|
|
3294
3446
|
* The guard a secured operation answers 401 with, or `''` when there is nothing to guard.
|
|
@@ -3314,9 +3466,9 @@ function authGuard(operation, spec, responses) {
|
|
|
3314
3466
|
* The guard a path parameter answers 404 with, or `''` when there is nothing to guard.
|
|
3315
3467
|
*
|
|
3316
3468
|
* Emitted only when the operation declares a 404, for the same reason as the 401: a status the
|
|
3317
|
-
* document never mentioned is one the client was never told to expect. The sentinel value
|
|
3318
|
-
*
|
|
3319
|
-
*
|
|
3469
|
+
* document never mentioned is one the client was never told to expect. The sentinel is a value
|
|
3470
|
+
* the schema accepts that no real record is likely to carry, so a client can ask for "not there"
|
|
3471
|
+
* on purpose.
|
|
3320
3472
|
*/
|
|
3321
3473
|
function notFoundGuard(operation, components, responses) {
|
|
3322
3474
|
if (!("404" in responses)) return "";
|
|
@@ -3326,8 +3478,8 @@ function notFoundGuard(operation, components, responses) {
|
|
|
3326
3478
|
if (!schema) return [];
|
|
3327
3479
|
const sentinel = nonExistentPathValue(schema);
|
|
3328
3480
|
if (!sentinel) return [];
|
|
3329
|
-
const value = sentinel.kind === "literal" ? quoteSingle
|
|
3330
|
-
return [`if (prefer.key === undefined && c.params[${quoteSingle
|
|
3481
|
+
const value = sentinel.kind === "literal" ? quoteSingle(sentinel.value) : `String(${sentinel.code})`;
|
|
3482
|
+
return [`if (prefer.key === undefined && c.params[${quoteSingle(parameter.name)}] === ${value}) return c.status(404)`];
|
|
3331
3483
|
});
|
|
3332
3484
|
return guards.length === 0 ? "" : `${guards.join("\n ")}\n `;
|
|
3333
3485
|
}
|
|
@@ -3338,7 +3490,7 @@ function notFoundGuard(operation, components, responses) {
|
|
|
3338
3490
|
*/
|
|
3339
3491
|
function returnStatement(status, body) {
|
|
3340
3492
|
if (body.kind === "empty") return `return c.status(${status})`;
|
|
3341
|
-
const header = body.kind === "json" && body.mediaType !== "application/json" ? `c.set.headers['content-type'] = ${quoteSingle
|
|
3493
|
+
const header = body.kind === "json" && body.mediaType !== "application/json" ? `c.set.headers['content-type'] = ${quoteSingle(body.mediaType)}\n ` : "";
|
|
3342
3494
|
if (status === "200") return `${header}return ${body.kind === "json" ? `(${body.expr})` : body.expr}`;
|
|
3343
3495
|
return `${header}return c.status(${status}, ${body.expr})`;
|
|
3344
3496
|
}
|
|
@@ -3404,11 +3556,11 @@ function preferProblem(detail: string) {
|
|
|
3404
3556
|
function indent(statement) {
|
|
3405
3557
|
return statement.replaceAll("\n ", "\n ");
|
|
3406
3558
|
}
|
|
3407
|
-
function quoteSingle
|
|
3559
|
+
function quoteSingle(s) {
|
|
3408
3560
|
return `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t")}'`;
|
|
3409
3561
|
}
|
|
3410
3562
|
function routePath(path) {
|
|
3411
|
-
return quoteSingle
|
|
3563
|
+
return quoteSingle(path.replaceAll(/\{([^}]+)\}/gu, ":$1"));
|
|
3412
3564
|
}
|
|
3413
3565
|
/**
|
|
3414
3566
|
* The middleware every response passes through when `delay` is configured.
|
|
@@ -3427,7 +3579,7 @@ function delayMiddleware(delay) {
|
|
|
3427
3579
|
* test) starts no server.
|
|
3428
3580
|
*
|
|
3429
3581
|
* A secured operation that declares a 401 checks for the credential first, and a path parameter
|
|
3430
|
-
* with a
|
|
3582
|
+
* with a recognizable "missing" value answers 404 — so a client can drive the unhappy paths the
|
|
3431
3583
|
* document promises, not just the happy one.
|
|
3432
3584
|
*/
|
|
3433
3585
|
function makeMock(spec, options = {}) {
|
|
@@ -3438,7 +3590,7 @@ function makeMock(spec, options = {}) {
|
|
|
3438
3590
|
...useExamples === "all" ? { useExamples: true } : {}
|
|
3439
3591
|
};
|
|
3440
3592
|
const components = spec.components;
|
|
3441
|
-
const routes =
|
|
3593
|
+
const routes = Object.entries(spec.paths).flatMap(([path, pathItem]) => {
|
|
3442
3594
|
if (!pathItem) return [];
|
|
3443
3595
|
return HTTP_METHODS.flatMap((method) => {
|
|
3444
3596
|
const operation = pathItem[method];
|
|
@@ -3462,8 +3614,8 @@ function makeMock(spec, options = {}) {
|
|
|
3462
3614
|
const render = (r, example) => {
|
|
3463
3615
|
return indent(returnStatement(/^\d{3}$/u.test(r.key) ? r.key : `prefer.status ?? ${/^[1-5]XX$/u.test(r.key) ? `${r.key.slice(0, 1)}00` : "200"}`, responseBody(r.response, example, fakerOptions)));
|
|
3464
3616
|
};
|
|
3465
|
-
const branches = [responses.flatMap((r) => r.named.filter(([, value]) => value !== r.example).map(([name, value]) => `if (prefer.key === ${quoteSingle
|
|
3466
|
-
const prefer = `const prefer = resolvePrefer(c.headers.prefer, c.query, ${JSON.stringify(preferTable)}, ${quoteSingle
|
|
3617
|
+
const branches = [responses.flatMap((r) => r.named.filter(([, value]) => value !== r.example).map(([name, value]) => `if (prefer.key === ${quoteSingle(r.key)} && prefer.example === ${quoteSingle(name)}) {\n ${render(r, value)}\n }\n `)), responses.filter((r) => !(r.key === success.key && /^\d{3}$/u.test(r.key))).map((r) => `if (prefer.key === ${quoteSingle(r.key)}) {\n ${render(r, r.example)}\n }\n `)].flat();
|
|
3618
|
+
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("")}`;
|
|
3467
3619
|
const successBody = responseBody(success.response, defaultExample(success.response, components, useExamples !== false), fakerOptions);
|
|
3468
3620
|
const auth = authGuard(resolved, spec, resolved.responses);
|
|
3469
3621
|
const notFound = notFoundGuard(resolved, components, resolved.responses);
|
|
@@ -3485,7 +3637,7 @@ function makeMock(spec, options = {}) {
|
|
|
3485
3637
|
});
|
|
3486
3638
|
});
|
|
3487
3639
|
const mockFunctions = makeMockFunctions(spec, new Set(routes.flatMap((r) => r.refs)), fakerOptions);
|
|
3488
|
-
const ctorArgs = prefix ? `{ prefix: ${quoteSingle
|
|
3640
|
+
const ctorArgs = prefix ? `{ prefix: ${quoteSingle(prefix)} }` : "";
|
|
3489
3641
|
const routeChain = routes.map((r) => ` ${r.code}`).join("\n");
|
|
3490
3642
|
const listenBlock = `
|
|
3491
3643
|
|
|
@@ -3507,230 +3659,6 @@ function mock(openAPI, output, options = {}) {
|
|
|
3507
3659
|
});
|
|
3508
3660
|
}
|
|
3509
3661
|
//#endregion
|
|
3510
|
-
//#region src/generator/test/test-generator.ts
|
|
3511
|
-
function extractSecurity(opSecurity, globalSecurity, securitySchemes) {
|
|
3512
|
-
return (opSecurity ?? globalSecurity ?? []).flatMap((secDef) => Object.keys(secDef).flatMap((schemeName) => {
|
|
3513
|
-
const scheme = securitySchemes?.[schemeName];
|
|
3514
|
-
if (!scheme || typeof scheme.type !== "string") return [];
|
|
3515
|
-
if (scheme.type === "http" && scheme.scheme === "bearer") return [{
|
|
3516
|
-
type: "bearer",
|
|
3517
|
-
name: "Authorization"
|
|
3518
|
-
}];
|
|
3519
|
-
if (scheme.type === "http" && scheme.scheme === "basic") return [{
|
|
3520
|
-
type: "basic",
|
|
3521
|
-
name: "Authorization"
|
|
3522
|
-
}];
|
|
3523
|
-
if (scheme.type === "apiKey") {
|
|
3524
|
-
const inLocation = scheme.in === "header" || scheme.in === "query" || scheme.in === "cookie" ? scheme.in : "header";
|
|
3525
|
-
return [{
|
|
3526
|
-
type: "apiKey",
|
|
3527
|
-
name: scheme.name || "X-API-Key",
|
|
3528
|
-
in: inLocation
|
|
3529
|
-
}];
|
|
3530
|
-
}
|
|
3531
|
-
if (scheme.type === "oauth2") return [{
|
|
3532
|
-
type: "oauth2",
|
|
3533
|
-
name: "Authorization"
|
|
3534
|
-
}];
|
|
3535
|
-
return [];
|
|
3536
|
-
}));
|
|
3537
|
-
}
|
|
3538
|
-
function extractTestCases(spec) {
|
|
3539
|
-
const components = spec.components;
|
|
3540
|
-
return pathEntries(spec).flatMap(([path, pathItem]) => {
|
|
3541
|
-
if (!pathItem) return [];
|
|
3542
|
-
return HTTP_METHODS.flatMap((method) => {
|
|
3543
|
-
const operation = pathItem[method];
|
|
3544
|
-
if (!operation) return [];
|
|
3545
|
-
const resolved = resolveOperation(operation, components);
|
|
3546
|
-
const resolvedParams = resolved.parameters.map((param) => {
|
|
3547
|
-
const schema = param.schema ?? { type: "string" };
|
|
3548
|
-
return {
|
|
3549
|
-
param,
|
|
3550
|
-
schema,
|
|
3551
|
-
fakerCode: schemaToFaker(schema, param.name)
|
|
3552
|
-
};
|
|
3553
|
-
});
|
|
3554
|
-
const pathParams = resolvedParams.filter((p) => p.param.in === "path").map((p) => ({
|
|
3555
|
-
name: p.param.name,
|
|
3556
|
-
fakerCode: p.fakerCode,
|
|
3557
|
-
schema: p.schema
|
|
3558
|
-
}));
|
|
3559
|
-
const queryParams = resolvedParams.filter((p) => p.param.in === "query").map((p) => ({
|
|
3560
|
-
name: p.param.name,
|
|
3561
|
-
fakerCode: p.fakerCode,
|
|
3562
|
-
required: p.param.required ?? false
|
|
3563
|
-
}));
|
|
3564
|
-
const headerParams = resolvedParams.filter((p) => p.param.in === "header").map((p) => ({
|
|
3565
|
-
name: p.param.name,
|
|
3566
|
-
fakerCode: p.fakerCode,
|
|
3567
|
-
required: p.param.required ?? false
|
|
3568
|
-
}));
|
|
3569
|
-
const requestBodyDef = resolved.requestBody;
|
|
3570
|
-
const jsonMedia = requestBodyDef && "content" in requestBodyDef ? requestBodyDef.content?.["application/json"] : void 0;
|
|
3571
|
-
const jsonBodySchema = jsonMedia && isMediaWithSchema(jsonMedia) ? jsonMedia.schema : void 0;
|
|
3572
|
-
const requestBody = jsonBodySchema ? { fakerCode: schemaToFaker(jsonBodySchema) } : void 0;
|
|
3573
|
-
const bodyRefs = jsonBodySchema ? collectSchemaRefs(jsonBodySchema, components?.schemas) : [];
|
|
3574
|
-
const paramRefs = resolvedParams.flatMap((p) => collectSchemaRefs(p.schema, components?.schemas));
|
|
3575
|
-
const usedSchemaRefs = [...new Set([...bodyRefs, ...paramRefs])];
|
|
3576
|
-
const responseKeys = Object.keys(operation.responses ?? {});
|
|
3577
|
-
const successStatus = responseKeys.filter((s) => s.startsWith("2")).map((s) => Number.parseInt(s, 10)).toSorted((a, b) => a - b)[0] ?? 200;
|
|
3578
|
-
const errorStatuses = responseKeys.filter((s) => (s.startsWith("4") || s.startsWith("5")) && s !== "default").map((s) => Number.parseInt(s, 10)).toSorted((a, b) => a - b);
|
|
3579
|
-
const security = extractSecurity(operation.security, spec.security, components?.securitySchemes);
|
|
3580
|
-
return [{
|
|
3581
|
-
operationId: resolveOperationId(operation, method, path),
|
|
3582
|
-
method: method.toUpperCase(),
|
|
3583
|
-
path,
|
|
3584
|
-
summary: operation.summary || "",
|
|
3585
|
-
tag: operation.tags?.[0],
|
|
3586
|
-
pathParams,
|
|
3587
|
-
queryParams,
|
|
3588
|
-
headerParams,
|
|
3589
|
-
requestBody,
|
|
3590
|
-
successStatus,
|
|
3591
|
-
errorStatuses,
|
|
3592
|
-
security,
|
|
3593
|
-
usedSchemaRefs
|
|
3594
|
-
}];
|
|
3595
|
-
});
|
|
3596
|
-
});
|
|
3597
|
-
}
|
|
3598
|
-
function quoteSingle(s) {
|
|
3599
|
-
return `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t")}'`;
|
|
3600
|
-
}
|
|
3601
|
-
function escapeTemplateLiteral(s) {
|
|
3602
|
-
return s.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${");
|
|
3603
|
-
}
|
|
3604
|
-
function resolveNonExistent(schema, schemas) {
|
|
3605
|
-
return nonExistentPathValue(schema.$ref && schemas ? schemas[schema.$ref.replace("#/components/schemas/", "")] ?? schema : schema);
|
|
3606
|
-
}
|
|
3607
|
-
function makeAuthHeader(sec) {
|
|
3608
|
-
switch (sec.type) {
|
|
3609
|
-
case "bearer":
|
|
3610
|
-
case "oauth2": return "'Authorization':`Bearer ${faker.string.alphanumeric(32)}`";
|
|
3611
|
-
case "basic": return "'Authorization':`Basic ${btoa(`${faker.internet.username()}:${faker.internet.password()}`)}`";
|
|
3612
|
-
case "apiKey":
|
|
3613
|
-
if (sec.in === "header") return `${quoteSingle(sec.name)}:faker.string.alphanumeric(32)`;
|
|
3614
|
-
if (sec.in === "cookie") return `'Cookie':\`${escapeTemplateLiteral(sec.name)}=\${faker.string.alphanumeric(32)}\``;
|
|
3615
|
-
return "";
|
|
3616
|
-
default: return "";
|
|
3617
|
-
}
|
|
3618
|
-
}
|
|
3619
|
-
function makeTestCase(tc, prefix = "", schemas) {
|
|
3620
|
-
const fullPath = `${prefix && prefix !== "/" ? prefix : ""}${tc.path}`;
|
|
3621
|
-
const escapedFullPath = escapeTemplateLiteral(fullPath);
|
|
3622
|
-
const testPath = tc.pathParams.reduce((path, param) => path.replace(`{${param.name}}`, `\${${toSafeIdentifier(param.name)}}`), escapedFullPath);
|
|
3623
|
-
const pathSetup = tc.pathParams.map((param) => `const ${toSafeIdentifier(param.name)}=${param.fakerCode}`);
|
|
3624
|
-
const querySetup = tc.queryParams.map((param) => `const ${toSafeIdentifier(param.name)}=${param.fakerCode}`);
|
|
3625
|
-
const queryParts = tc.queryParams.map((param) => `${escapeTemplateLiteral(param.name)}=\${encodeURIComponent(String(${toSafeIdentifier(param.name)}))}`);
|
|
3626
|
-
const queryString = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
|
|
3627
|
-
const authQueryParts = tc.security.filter((sec) => sec.type === "apiKey" && sec.in === "query").map((sec) => `${escapeTemplateLiteral(sec.name)}=\${faker.string.alphanumeric(32)}`);
|
|
3628
|
-
const authQueryString = authQueryParts.length > 0 ? queryString ? `&${authQueryParts.join("&")}` : `?${authQueryParts.join("&")}` : "";
|
|
3629
|
-
const requiredHeaderParams = tc.headerParams.filter((p) => p.required);
|
|
3630
|
-
const headerSetup = requiredHeaderParams.map((param) => `const ${toSafeIdentifier(param.name)}=${param.fakerCode}`);
|
|
3631
|
-
const headerEntries = requiredHeaderParams.map((param) => `${quoteSingle(param.name)}:String(${toSafeIdentifier(param.name)})`);
|
|
3632
|
-
const authHeaders = tc.security.map(makeAuthHeader).filter(Boolean);
|
|
3633
|
-
const { bodySetup, bodyOption, contentTypeHeader } = tc.requestBody ? {
|
|
3634
|
-
bodySetup: `const body=${tc.requestBody.fakerCode}`,
|
|
3635
|
-
bodyOption: ",body:JSON.stringify(body)",
|
|
3636
|
-
contentTypeHeader: "'Content-Type':'application/json'"
|
|
3637
|
-
} : {
|
|
3638
|
-
bodySetup: "",
|
|
3639
|
-
bodyOption: "",
|
|
3640
|
-
contentTypeHeader: ""
|
|
3641
|
-
};
|
|
3642
|
-
const headers = [...headerEntries, ...contentTypeHeader ? [contentTypeHeader] : []];
|
|
3643
|
-
const allHeaders = [...headers, ...authHeaders];
|
|
3644
|
-
const headersOption = allHeaders.length > 0 ? `,headers:{${allHeaders.join(",")}}` : "";
|
|
3645
|
-
const headersWithoutAuth = headers.length > 0 ? `,headers:{${headers.join(",")}}` : "";
|
|
3646
|
-
const summaryPart = tc.summary ? ` - ${tc.summary}` : "";
|
|
3647
|
-
const setupCode = [
|
|
3648
|
-
...pathSetup,
|
|
3649
|
-
...querySetup,
|
|
3650
|
-
...headerSetup,
|
|
3651
|
-
bodySetup
|
|
3652
|
-
].filter(Boolean).join("\n");
|
|
3653
|
-
const describeTitle = quoteSingle(`${tc.method} ${fullPath}`);
|
|
3654
|
-
const methodLiteral = quoteSingle(tc.method);
|
|
3655
|
-
return `${`describe(${describeTitle},()=>{it(${quoteSingle(`should return ${tc.successStatus}${summaryPart}`)},async()=>{${setupCode}\nconst res=await app.handle(new Request(\`http://localhost${testPath}${queryString}${authQueryString}\`,{method:${methodLiteral}${headersOption}${bodyOption}}))\nexpect(res.status).toBe(${tc.successStatus})})`}${tc.security.length > 0 ? `\nit('should return 401 without auth',async()=>{${setupCode}\nconst res=await app.handle(new Request(\`http://localhost${testPath}${queryString}\`,{method:${methodLiteral}${headersWithoutAuth}${bodyOption}}))\nexpect(res.status).toBe(401)})` : ""}${tc.pathParams.length > 0 && tc.errorStatuses.includes(404) ? (() => {
|
|
3656
|
-
const probes = tc.pathParams.map((param) => ({
|
|
3657
|
-
param,
|
|
3658
|
-
probe: resolveNonExistent(param.schema, schemas)
|
|
3659
|
-
}));
|
|
3660
|
-
if (probes.some(({ probe }) => probe === void 0)) return "";
|
|
3661
|
-
const probeSetup = probes.flatMap(({ param, probe }) => probe?.kind === "expr" ? [`const ${toSafeIdentifier(param.name)}=${probe.code}`] : []);
|
|
3662
|
-
const notFoundPath = probes.reduce((path, { param, probe }) => {
|
|
3663
|
-
const value = probe?.kind === "expr" ? `\${${toSafeIdentifier(param.name)}}` : probe?.value ?? "";
|
|
3664
|
-
return path.replace(`{${param.name}}`, value);
|
|
3665
|
-
}, escapedFullPath);
|
|
3666
|
-
return `\nit('should return 404 for non-existent resource',async()=>{${[
|
|
3667
|
-
...probeSetup,
|
|
3668
|
-
...querySetup,
|
|
3669
|
-
...headerSetup,
|
|
3670
|
-
bodySetup
|
|
3671
|
-
].filter(Boolean).join("\n")}\nconst res=await app.handle(new Request(\`http://localhost${notFoundPath}${queryString}\`,{method:${methodLiteral}${headersOption}${bodyOption}}))\nexpect(res.status).toBe(404)})`;
|
|
3672
|
-
})() : ""}})\n`;
|
|
3673
|
-
}
|
|
3674
|
-
function makeTagDescribes(testCases, spec, prefix) {
|
|
3675
|
-
return [...testCases.reduce((acc, tc) => {
|
|
3676
|
-
const tag = tc.tag || "default";
|
|
3677
|
-
return acc.set(tag, [...acc.get(tag) ?? [], tc]);
|
|
3678
|
-
}, /* @__PURE__ */ new Map()).entries()].map(([tag, cases]) => {
|
|
3679
|
-
const tagDescription = (spec.tags?.find((t) => t.name === tag))?.description || tag;
|
|
3680
|
-
const testCasesCode = cases.map((tc) => makeTestCase(tc, prefix, spec.components?.schemas)).join("");
|
|
3681
|
-
return `describe(${quoteSingle(tagDescription)},()=>{${testCasesCode}})\n`;
|
|
3682
|
-
}).join("");
|
|
3683
|
-
}
|
|
3684
|
-
function makeAppTestFile(spec, appImport, prefix, resourceFilter) {
|
|
3685
|
-
const testCases = resourceFilter ? extractTestCases(spec).filter((tc) => resourceFilter.has(resourceName(tc.path))) : extractTestCases(spec);
|
|
3686
|
-
const apiTitle = spec.info?.title || "API";
|
|
3687
|
-
const mockFunctions = makeMockFunctions(spec, new Set(testCases.flatMap((tc) => tc.usedSchemaRefs)));
|
|
3688
|
-
const tagDescribes = makeTagDescribes(testCases, spec, prefix);
|
|
3689
|
-
const body = `${mockFunctions ? `${mockFunctions}\n\n` : ""}describe(${quoteSingle(apiTitle)},()=>{${tagDescribes}})\n`;
|
|
3690
|
-
return `${`import{describe,it,expect}from'bun:test'${body.includes("faker.") ? `\nimport{faker}from'@faker-js/faker'` : ""}\nimport{app}from'${appImport}'\n`}\n${body}`;
|
|
3691
|
-
}
|
|
3692
|
-
function makeTestFile(spec, appImport = "..", prefix) {
|
|
3693
|
-
return makeAppTestFile(spec, appImport, prefix);
|
|
3694
|
-
}
|
|
3695
|
-
function makeColocatedTestEntries(spec, appImport = "../../index", prefix) {
|
|
3696
|
-
const resources = [...operationsByResource(spec).keys()];
|
|
3697
|
-
const resourcesWithCases = new Set(extractTestCases(spec).map((tc) => resourceName(tc.path)));
|
|
3698
|
-
return resources.filter((name) => resourcesWithCases.has(name)).map((name) => ({
|
|
3699
|
-
name,
|
|
3700
|
-
code: makeAppTestFile(spec, appImport, prefix, new Set([name]))
|
|
3701
|
-
}));
|
|
3702
|
-
}
|
|
3703
|
-
//#endregion
|
|
3704
|
-
//#region src/core/test/index.ts
|
|
3705
|
-
/** Writes `code`, keeping whatever the user already wrote in `output`. */
|
|
3706
|
-
function writeMerged(code, output) {
|
|
3707
|
-
return Effect.gen(function* () {
|
|
3708
|
-
const existing = yield* readFile(output);
|
|
3709
|
-
yield* emit(existing === null ? code : mergeSource(existing, code), path.dirname(output), output);
|
|
3710
|
-
});
|
|
3711
|
-
}
|
|
3712
|
-
function test(openAPI, output, options = {}) {
|
|
3713
|
-
return Effect.gen(function* () {
|
|
3714
|
-
const { appOutput = "src/index.ts", split = false, pathAlias, prefix } = options;
|
|
3715
|
-
const appOutputAbs = path.resolve(process.cwd(), appOutput);
|
|
3716
|
-
const appBase = path.basename(appOutput).replace(/\.ts$/u, "");
|
|
3717
|
-
const appImportFor = (fromFileAbs) => {
|
|
3718
|
-
if (pathAlias) return `${pathAlias.replace(/\/$/u, "")}/${appBase}`;
|
|
3719
|
-
const rel = path.relative(path.dirname(fromFileAbs), appOutputAbs).replaceAll("\\", "/").replace(/\.ts$/u, "");
|
|
3720
|
-
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
3721
|
-
};
|
|
3722
|
-
if (split) {
|
|
3723
|
-
const modulesDir = path.join(path.dirname(appOutputAbs), "modules");
|
|
3724
|
-
const entries = makeColocatedTestEntries(openAPI, appImportFor(path.join(modulesDir, "resource", "index.test.ts")), prefix);
|
|
3725
|
-
yield* Effect.all(entries.map((entry) => writeMerged(entry.code, path.join(modulesDir, entry.name, "index.test.ts"))), { concurrency: "unbounded" });
|
|
3726
|
-
return `Generated ${entries.length} co-located test file(s) under ${path.posix.dirname(appOutput)}/modules/`;
|
|
3727
|
-
}
|
|
3728
|
-
if (output === void 0) return yield* new GenerateError({ message: "test.output is required when split is false" });
|
|
3729
|
-
yield* writeMerged(makeTestFile(openAPI, appImportFor(path.resolve(process.cwd(), output)), prefix), output);
|
|
3730
|
-
return `Generated test file written to ${output}`;
|
|
3731
|
-
});
|
|
3732
|
-
}
|
|
3733
|
-
//#endregion
|
|
3734
3662
|
//#region src/core/type/index.ts
|
|
3735
3663
|
function primitiveTypeToTs(t) {
|
|
3736
3664
|
if (t === "string") return "string";
|
|
@@ -3895,7 +3823,7 @@ function nestRoute(keys, method, opTs) {
|
|
|
3895
3823
|
function makeRoutes(openAPI, prefix) {
|
|
3896
3824
|
const out = [];
|
|
3897
3825
|
const prefixKeys = prefix && prefix !== "/" ? pathToKeys(prefix) : [];
|
|
3898
|
-
for (const [pathStr, pathItem] of
|
|
3826
|
+
for (const [pathStr, pathItem] of Object.entries(openAPI.paths)) {
|
|
3899
3827
|
if (!pathItem) continue;
|
|
3900
3828
|
const keys = [...prefixKeys, ...pathToKeys(pathStr)];
|
|
3901
3829
|
for (const method of HTTP_METHODS) {
|
|
@@ -3939,7 +3867,7 @@ function collectRefs(openAPI) {
|
|
|
3939
3867
|
}
|
|
3940
3868
|
if (resp.content) walkContentMap(resp.content);
|
|
3941
3869
|
};
|
|
3942
|
-
for (const [, pathItem] of
|
|
3870
|
+
for (const [, pathItem] of Object.entries(openAPI.paths)) {
|
|
3943
3871
|
if (!pathItem) continue;
|
|
3944
3872
|
for (const method of HTTP_METHODS) {
|
|
3945
3873
|
const op = pathItem[method];
|
|
@@ -3989,30 +3917,400 @@ function types(openAPI, output, prefix) {
|
|
|
3989
3917
|
});
|
|
3990
3918
|
}
|
|
3991
3919
|
//#endregion
|
|
3992
|
-
//#region src/
|
|
3993
|
-
var
|
|
3994
|
-
|
|
3995
|
-
|
|
3996
|
-
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
headers: () => headers,
|
|
4001
|
-
hooks: () => hooks,
|
|
4002
|
-
links: () => links,
|
|
4003
|
-
makeAppType: () => makeAppType,
|
|
4004
|
-
makeJsDocs: () => makeJsDocs,
|
|
4005
|
-
mediaTypes: () => mediaTypes,
|
|
4006
|
-
mock: () => mock,
|
|
4007
|
-
parameters: () => parameters,
|
|
4008
|
-
pathItems: () => pathItems,
|
|
4009
|
-
requestBodies: () => requestBodies,
|
|
4010
|
-
responses: () => responses,
|
|
4011
|
-
schemaToTs: () => schemaToTs,
|
|
4012
|
-
schemas: () => schemas,
|
|
4013
|
-
securitySchemes: () => securitySchemes,
|
|
4014
|
-
test: () => test,
|
|
4015
|
-
types: () => types
|
|
3920
|
+
//#region src/shared/index.ts
|
|
3921
|
+
var shared_exports = /* @__PURE__ */ __exportAll({
|
|
3922
|
+
cleanSplitOutputs: () => cleanSplitOutputs,
|
|
3923
|
+
isInsideDirectory: () => isInsideDirectory,
|
|
3924
|
+
isUserCodeJob: () => isUserCodeJob,
|
|
3925
|
+
jobTargets: () => jobTargets,
|
|
3926
|
+
makeJob: () => makeJob,
|
|
3927
|
+
outsideSources: () => outsideSources
|
|
4016
3928
|
});
|
|
3929
|
+
/**
|
|
3930
|
+
* The specifier `from` imports the generated file `target` by.
|
|
3931
|
+
*
|
|
3932
|
+
* Through the alias when the config names one and `target` sits under the app entry's directory —
|
|
3933
|
+
* `@/` stands for that directory, so `src/client.ts` is `@/client` from anywhere — and relative to
|
|
3934
|
+
* `from` otherwise. The extension goes. A barrel is imported by its directory; any other file
|
|
3935
|
+
* keeps its `index`, so an entry is named rather than left to directory resolution.
|
|
3936
|
+
*/
|
|
3937
|
+
function importSpecifier(from, target, alias, kind = "file") {
|
|
3938
|
+
const module = posix.normalize(target).replace(kind === "barrel" ? /(?:\/index)?\.ts$/u : /\.ts$/u, "");
|
|
3939
|
+
if (alias !== void 0) {
|
|
3940
|
+
const inside = posix.relative(alias.directory, module);
|
|
3941
|
+
if (inside !== "" && !inside.startsWith("..")) return `${alias.prefix}/${inside}`;
|
|
3942
|
+
}
|
|
3943
|
+
const relative = posix.relative(posix.dirname(posix.normalize(from)), module);
|
|
3944
|
+
return relative.startsWith(".") ? relative : `./${relative}`;
|
|
3945
|
+
}
|
|
3946
|
+
/**
|
|
3947
|
+
* The directory of the nearest `package.json` at or above `dir`, or `undefined` when there is
|
|
3948
|
+
* none: the package a file belongs to, read from where it sits and nothing else.
|
|
3949
|
+
*/
|
|
3950
|
+
function packageRoot(dir) {
|
|
3951
|
+
return Effect.gen(function* () {
|
|
3952
|
+
if (yield* (yield* FileSystem.FileSystem).exists(path.join(dir, "package.json")).pipe(Effect.orElseSucceed(() => false))) return dir;
|
|
3953
|
+
const parent = path.dirname(dir);
|
|
3954
|
+
return parent === dir ? void 0 : yield* packageRoot(parent);
|
|
3955
|
+
});
|
|
3956
|
+
}
|
|
3957
|
+
/**
|
|
3958
|
+
* The specifier `from` imports the generated file `target` by, package boundaries respected.
|
|
3959
|
+
*
|
|
3960
|
+
* Inside one package it is `local` — relative, or through the alias. Across packages it is the
|
|
3961
|
+
* name the target's package is imported by, `named`; a crossing with no name is refused with
|
|
3962
|
+
* `missing`, rather than written as a relative path into another package.
|
|
3963
|
+
*/
|
|
3964
|
+
function packageImport(from, target, local, named, missing) {
|
|
3965
|
+
return Effect.gen(function* () {
|
|
3966
|
+
const [fromRoot, targetRoot] = yield* Effect.all([packageRoot(path.dirname(path.resolve(process.cwd(), from))), packageRoot(path.dirname(path.resolve(process.cwd(), target)))]);
|
|
3967
|
+
if (fromRoot === targetRoot) return local;
|
|
3968
|
+
if (named !== void 0) return named;
|
|
3969
|
+
return yield* new GenerateError({ message: missing });
|
|
3970
|
+
});
|
|
3971
|
+
}
|
|
3972
|
+
/** Runs `make` on what `input` works out against the filesystem. */
|
|
3973
|
+
function resolved(input, make) {
|
|
3974
|
+
return Effect.gen(function* () {
|
|
3975
|
+
return yield* make(yield* input);
|
|
3976
|
+
});
|
|
3977
|
+
}
|
|
3978
|
+
/** The `client` job's run: the client, importing the app entry from where `appImport` answers. */
|
|
3979
|
+
function clientRun(output, appImport, options) {
|
|
3980
|
+
return Effect.gen(function* () {
|
|
3981
|
+
const specifier = yield* appImport;
|
|
3982
|
+
return yield* client(output, {
|
|
3983
|
+
...options,
|
|
3984
|
+
appImport: specifier
|
|
3985
|
+
});
|
|
3986
|
+
});
|
|
3987
|
+
}
|
|
3988
|
+
/** The `eden` job's run: the wrappers, importing the client from where `importPath` answers. */
|
|
3989
|
+
function edenRun(openAPI, output, importPath, edenConfig, prefix) {
|
|
3990
|
+
return Effect.gen(function* () {
|
|
3991
|
+
return yield* eden(openAPI, output, yield* importPath, "client", prefix);
|
|
3992
|
+
});
|
|
3993
|
+
}
|
|
3994
|
+
/**
|
|
3995
|
+
* A hooks job's run: one library's hooks, importing the client from where `importPath` answers
|
|
3996
|
+
* and the schemas from where `view` says.
|
|
3997
|
+
*/
|
|
3998
|
+
function hooksRun(openAPI, output, importPath, library, view, componentsOutput, options) {
|
|
3999
|
+
return Effect.gen(function* () {
|
|
4000
|
+
const [specifier, seen] = yield* Effect.all([importPath, view]);
|
|
4001
|
+
const schemasTarget = componentsOutput === void 0 ? seen.targets.schemas : {
|
|
4002
|
+
output: componentsOutput,
|
|
4003
|
+
import: seen.componentsImport
|
|
4004
|
+
};
|
|
4005
|
+
return yield* hooks(openAPI, output, specifier, library, {
|
|
4006
|
+
...options,
|
|
4007
|
+
schemas: schemasTarget
|
|
4008
|
+
});
|
|
4009
|
+
});
|
|
4010
|
+
}
|
|
4011
|
+
/**
|
|
4012
|
+
* How the file at `from` imports the component kind `target`: by the package name across a
|
|
4013
|
+
* package boundary; through the alias under the app entry's directory; and relatively otherwise — which the generators work out themselves, so it is left unsaid here. A
|
|
4014
|
+
* kind in another package that names no package is imported relatively as well: which kinds a
|
|
4015
|
+
* file imports depends on the document, so a name cannot be demanded ahead of it.
|
|
4016
|
+
*/
|
|
4017
|
+
function settleTarget(from, target, pathAlias) {
|
|
4018
|
+
return Effect.gen(function* () {
|
|
4019
|
+
const [fromRoot, targetRoot] = yield* Effect.all([packageRoot(path.dirname(path.resolve(process.cwd(), from))), packageRoot(path.dirname(path.resolve(process.cwd(), target.output)))]);
|
|
4020
|
+
if (fromRoot !== targetRoot) return target.package === void 0 ? target : {
|
|
4021
|
+
...target,
|
|
4022
|
+
import: target.package
|
|
4023
|
+
};
|
|
4024
|
+
if (pathAlias === void 0) return target;
|
|
4025
|
+
const specifier = importSpecifier(from, target.output, pathAlias, "barrel");
|
|
4026
|
+
return specifier.startsWith(".") ? target : {
|
|
4027
|
+
...target,
|
|
4028
|
+
import: specifier
|
|
4029
|
+
};
|
|
4030
|
+
});
|
|
4031
|
+
}
|
|
4032
|
+
/** What the file at `from` sees of every component kind, and of the single components file. */
|
|
4033
|
+
function viewFrom(from, options) {
|
|
4034
|
+
return Effect.gen(function* () {
|
|
4035
|
+
const settled = yield* Effect.all(COMPONENT_KINDS.map((kind) => settleTarget(from, options.targetOf(kind), options.pathAlias).pipe(Effect.map((target) => [kind, target]))), { concurrency: "unbounded" });
|
|
4036
|
+
const single = options.single === void 0 ? void 0 : yield* settleTarget(from, options.single, options.pathAlias);
|
|
4037
|
+
return {
|
|
4038
|
+
targets: Object.fromEntries(settled),
|
|
4039
|
+
componentsImport: single?.import
|
|
4040
|
+
};
|
|
4041
|
+
});
|
|
4042
|
+
}
|
|
4043
|
+
function makeJob(openAPI, config) {
|
|
4044
|
+
const { client: clientConfig, eden: edenConfig } = config;
|
|
4045
|
+
const appOutput = config.output ?? "src/index.ts";
|
|
4046
|
+
const baseDir = posix.normalize(posix.dirname(appOutput));
|
|
4047
|
+
const pathAlias = config.pathAlias === void 0 ? void 0 : {
|
|
4048
|
+
prefix: config.pathAlias.replace(/\/+$/u, ""),
|
|
4049
|
+
directory: baseDir
|
|
4050
|
+
};
|
|
4051
|
+
const clientBarrel = (() => {
|
|
4052
|
+
if (clientConfig === void 0 || posix.basename(clientConfig.output) === "index.ts") return;
|
|
4053
|
+
const barrel = posix.join(posix.dirname(clientConfig.output), "index.ts");
|
|
4054
|
+
return [
|
|
4055
|
+
appOutput,
|
|
4056
|
+
config.components?.output,
|
|
4057
|
+
...COMPONENT_KINDS.map((kind) => config.components?.[kind]?.output),
|
|
4058
|
+
edenConfig?.output,
|
|
4059
|
+
config.types?.output,
|
|
4060
|
+
config.mock?.output,
|
|
4061
|
+
...HOOK_KINDS.map((kind) => config[kind]?.output)
|
|
4062
|
+
].some((file) => file !== void 0 && posix.normalize(file) === barrel) ? void 0 : barrel;
|
|
4063
|
+
})();
|
|
4064
|
+
const clientImport = (field, output) => {
|
|
4065
|
+
if (clientConfig === void 0) return Effect.fail(new GenerateError({ message: `${field} needs the top-level client it imports` }));
|
|
4066
|
+
const isBeside = posix.dirname(posix.normalize(output)) === posix.dirname(clientConfig.output);
|
|
4067
|
+
return packageImport(output, clientConfig.output, isBeside || clientBarrel === void 0 ? importSpecifier(output, clientConfig.output, pathAlias) : importSpecifier(output, clientBarrel, pathAlias, "barrel"), clientConfig.package, `${field}.output is in another package than the client: name the package the client is published as, client.package, for the file to import it by.`);
|
|
4068
|
+
};
|
|
4069
|
+
const { output: componentsOutput, package: componentsPackage, ...componentTargets } = config.components ?? {};
|
|
4070
|
+
const targetOf = (kind) => componentTargets[kind] ?? { output: `${baseDir}/components/${kind}.ts` };
|
|
4071
|
+
const view = (from) => viewFrom(from, {
|
|
4072
|
+
targetOf,
|
|
4073
|
+
single: componentsOutput === void 0 ? void 0 : {
|
|
4074
|
+
output: componentsOutput,
|
|
4075
|
+
package: componentsPackage
|
|
4076
|
+
},
|
|
4077
|
+
pathAlias
|
|
4078
|
+
});
|
|
4079
|
+
const componentJobs = componentsOutput ? [{
|
|
4080
|
+
name: "components",
|
|
4081
|
+
output: componentsOutput,
|
|
4082
|
+
split: false,
|
|
4083
|
+
run: (output) => components(openAPI.components, output, config.readonly)
|
|
4084
|
+
}] : perTypeComponentJobs(openAPI, componentTargets, baseDir, config.readonly, view);
|
|
4085
|
+
return [
|
|
4086
|
+
{
|
|
4087
|
+
name: "elysia",
|
|
4088
|
+
output: appOutput,
|
|
4089
|
+
split: false,
|
|
4090
|
+
run: (output) => resolved(view(`${baseDir}/modules/_/index.ts`), (seen) => elysia(openAPI, {
|
|
4091
|
+
output,
|
|
4092
|
+
prefix: config.prefix,
|
|
4093
|
+
port: config.port,
|
|
4094
|
+
integration: config.integration === true,
|
|
4095
|
+
readonly: config.readonly === true,
|
|
4096
|
+
pathAlias: pathAlias?.prefix,
|
|
4097
|
+
components: seen.targets,
|
|
4098
|
+
componentsOutput,
|
|
4099
|
+
componentsImport: seen.componentsImport
|
|
4100
|
+
}))
|
|
4101
|
+
},
|
|
4102
|
+
...componentJobs,
|
|
4103
|
+
clientConfig ? {
|
|
4104
|
+
name: "client",
|
|
4105
|
+
output: clientConfig.output,
|
|
4106
|
+
split: false,
|
|
4107
|
+
run: (output) => clientRun(output, packageImport(output, appOutput, importSpecifier(output, appOutput, pathAlias), config.package, "client.output is in another package than the app entry: name the package the app is published as, the top-level package, for the client to import it by."), {
|
|
4108
|
+
baseUrl: clientConfig.baseUrl,
|
|
4109
|
+
sameOrigin: clientConfig.sameOrigin === true,
|
|
4110
|
+
barrel: clientBarrel
|
|
4111
|
+
})
|
|
4112
|
+
} : void 0,
|
|
4113
|
+
edenConfig ? {
|
|
4114
|
+
name: "eden",
|
|
4115
|
+
output: edenConfig.output,
|
|
4116
|
+
split: false,
|
|
4117
|
+
run: (output) => edenRun(openAPI, output, clientImport("eden", output), edenConfig, config.prefix)
|
|
4118
|
+
} : void 0,
|
|
4119
|
+
config.types ? {
|
|
4120
|
+
name: "types",
|
|
4121
|
+
output: config.types.output,
|
|
4122
|
+
split: false,
|
|
4123
|
+
run: (output) => types(openAPI, output, config.prefix)
|
|
4124
|
+
} : void 0,
|
|
4125
|
+
config.mock ? {
|
|
4126
|
+
name: "mock",
|
|
4127
|
+
output: config.mock.output,
|
|
4128
|
+
split: false,
|
|
4129
|
+
run: (output) => mock(openAPI, output, {
|
|
4130
|
+
...config.mock,
|
|
4131
|
+
prefix: config.prefix,
|
|
4132
|
+
port: config.port
|
|
4133
|
+
})
|
|
4134
|
+
} : void 0,
|
|
4135
|
+
...HOOK_KINDS.map((library) => {
|
|
4136
|
+
const cfg = config[library];
|
|
4137
|
+
return cfg ? {
|
|
4138
|
+
name: library,
|
|
4139
|
+
output: cfg.output,
|
|
4140
|
+
split: false,
|
|
4141
|
+
run: (output) => hooksRun(openAPI, output, clientImport(library, output), library, view(output), componentsOutput, {
|
|
4142
|
+
client: "client",
|
|
4143
|
+
basePath: config.prefix
|
|
4144
|
+
})
|
|
4145
|
+
} : void 0;
|
|
4146
|
+
})
|
|
4147
|
+
].filter((job) => job !== void 0);
|
|
4148
|
+
}
|
|
4149
|
+
function perTypeComponentJobs(openAPI, componentTargets, baseDir, readonly, view) {
|
|
4150
|
+
const target = (kind) => ({
|
|
4151
|
+
name: kind,
|
|
4152
|
+
output: componentTargets[kind]?.output ?? `${baseDir}/components/${kind}.ts`,
|
|
4153
|
+
split: componentTargets[kind]?.split ?? false
|
|
4154
|
+
});
|
|
4155
|
+
const seenFrom = (kind) => {
|
|
4156
|
+
const { output, split } = target(kind);
|
|
4157
|
+
return view(split ? `${output}/index.ts` : output);
|
|
4158
|
+
};
|
|
4159
|
+
return [
|
|
4160
|
+
openAPI.components?.schemas ? {
|
|
4161
|
+
...target("schemas"),
|
|
4162
|
+
run: (output) => resolved(seenFrom("schemas"), ({ targets }) => schemas(openAPI.components?.schemas, output, componentTargets.schemas?.split ?? false, componentTargets.schemas?.exportTypes ?? false, targets, readonly))
|
|
4163
|
+
} : void 0,
|
|
4164
|
+
openAPI.components?.responses ? {
|
|
4165
|
+
...target("responses"),
|
|
4166
|
+
run: (output) => resolved(seenFrom("responses"), ({ targets }) => responses(openAPI.components?.responses, output, componentTargets.responses?.split ?? false, componentTargets.responses?.exportTypes ?? false, targets, readonly))
|
|
4167
|
+
} : void 0,
|
|
4168
|
+
openAPI.components?.parameters ? {
|
|
4169
|
+
...target("parameters"),
|
|
4170
|
+
run: (output) => resolved(seenFrom("parameters"), ({ targets }) => parameters(openAPI.components?.parameters, output, componentTargets.parameters?.split ?? false, componentTargets.parameters?.exportTypes ?? false, targets, readonly))
|
|
4171
|
+
} : void 0,
|
|
4172
|
+
openAPI.components?.examples ? {
|
|
4173
|
+
...target("examples"),
|
|
4174
|
+
run: (output) => resolved(seenFrom("examples"), ({ targets }) => examples(openAPI.components?.examples, output, componentTargets.examples?.split ?? false, targets))
|
|
4175
|
+
} : void 0,
|
|
4176
|
+
openAPI.components?.requestBodies ? {
|
|
4177
|
+
...target("requestBodies"),
|
|
4178
|
+
run: (output) => resolved(seenFrom("requestBodies"), ({ targets }) => requestBodies(openAPI.components?.requestBodies, output, componentTargets.requestBodies?.split ?? false, componentTargets.requestBodies?.exportTypes ?? false, targets, readonly))
|
|
4179
|
+
} : void 0,
|
|
4180
|
+
openAPI.components?.headers ? {
|
|
4181
|
+
...target("headers"),
|
|
4182
|
+
run: (output) => resolved(seenFrom("headers"), ({ targets }) => headers(openAPI.components?.headers, output, componentTargets.headers?.split ?? false, componentTargets.headers?.exportTypes ?? false, targets, readonly))
|
|
4183
|
+
} : void 0,
|
|
4184
|
+
openAPI.components?.securitySchemes ? {
|
|
4185
|
+
...target("securitySchemes"),
|
|
4186
|
+
run: (output) => resolved(seenFrom("securitySchemes"), ({ targets }) => securitySchemes(openAPI.components?.securitySchemes, output, componentTargets.securitySchemes?.split ?? false, targets))
|
|
4187
|
+
} : void 0,
|
|
4188
|
+
openAPI.components?.links ? {
|
|
4189
|
+
...target("links"),
|
|
4190
|
+
run: (output) => resolved(seenFrom("links"), ({ targets }) => links(openAPI.components?.links, output, componentTargets.links?.split ?? false, targets))
|
|
4191
|
+
} : void 0,
|
|
4192
|
+
openAPI.components?.callbacks ? {
|
|
4193
|
+
...target("callbacks"),
|
|
4194
|
+
run: (output) => resolved(seenFrom("callbacks"), ({ targets }) => callbacks(openAPI.components?.callbacks, output, componentTargets.callbacks?.split ?? false, targets))
|
|
4195
|
+
} : void 0,
|
|
4196
|
+
openAPI.components?.pathItems ? {
|
|
4197
|
+
...target("pathItems"),
|
|
4198
|
+
run: (output) => resolved(seenFrom("pathItems"), ({ targets }) => pathItems(openAPI.components?.pathItems, output, componentTargets.pathItems?.split ?? false, targets))
|
|
4199
|
+
} : void 0,
|
|
4200
|
+
openAPI.components?.mediaTypes ? {
|
|
4201
|
+
...target("mediaTypes"),
|
|
4202
|
+
run: (output) => resolved(seenFrom("mediaTypes"), ({ targets }) => mediaTypes(openAPI.components?.mediaTypes, output, componentTargets.mediaTypes?.split ?? false, componentTargets.mediaTypes?.exportTypes ?? false, targets, readonly))
|
|
4203
|
+
} : void 0
|
|
4204
|
+
];
|
|
4205
|
+
}
|
|
4206
|
+
/**
|
|
4207
|
+
* Whether a job merges into what is already at its output rather than overwrite it.
|
|
4208
|
+
*
|
|
4209
|
+
* `elysia` reads the app entry and the modules back and keeps whatever the user wrote there
|
|
4210
|
+
* (`mergeSource`), so what it writes holds the user's code as much as the generator's. Nothing
|
|
4211
|
+
* that deletes — the split clean below, the Vite plugin's stale-output cleanup — may touch it.
|
|
4212
|
+
*/
|
|
4213
|
+
function isUserCodeJob(job) {
|
|
4214
|
+
return job.name === "elysia";
|
|
4215
|
+
}
|
|
4216
|
+
/**
|
|
4217
|
+
* Every absolute path a job writes under.
|
|
4218
|
+
*
|
|
4219
|
+
* The output itself, and for `elysia` the `modules/` directory it fills beside the app entry —
|
|
4220
|
+
* one file per resource, which a caller that watches for changed output has to see as well.
|
|
4221
|
+
*/
|
|
4222
|
+
function jobTargets(job) {
|
|
4223
|
+
const output = path.resolve(process.cwd(), job.output);
|
|
4224
|
+
return job.name === "elysia" ? [output, path.join(path.dirname(output), "modules")] : [output];
|
|
4225
|
+
}
|
|
4226
|
+
/**
|
|
4227
|
+
* Whether `filePath` sits under `directory`, at any depth.
|
|
4228
|
+
*
|
|
4229
|
+
* Asked of the path segments rather than the string: `/app/spec-old/a.yaml` starts with
|
|
4230
|
+
* `/app/spec` and is not inside it.
|
|
4231
|
+
*/
|
|
4232
|
+
function isInsideDirectory(directory, filePath) {
|
|
4233
|
+
const relative = path.relative(directory, filePath);
|
|
4234
|
+
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
4235
|
+
}
|
|
4236
|
+
function cleanSplitDirectory(directory, keep) {
|
|
4237
|
+
return Effect.gen(function* () {
|
|
4238
|
+
const stale = (yield* readdir(directory)).filter((name) => name.endsWith(".ts")).map((name) => path.join(directory, name)).filter((file) => !keep.has(file));
|
|
4239
|
+
yield* Effect.all(stale.map(unlink), { concurrency: "unbounded" });
|
|
4240
|
+
return stale;
|
|
4241
|
+
});
|
|
4242
|
+
}
|
|
4243
|
+
/**
|
|
4244
|
+
* Empties every split output directory before the generators refill them, answering with what
|
|
4245
|
+
* was removed.
|
|
4246
|
+
*
|
|
4247
|
+
* A split generator writes one file per entry plus a barrel beside them, and knows only what it
|
|
4248
|
+
* writes — so an entry that leaves the document leaves its file behind, orphaned and still
|
|
4249
|
+
* importing names the document no longer defines. A split directory is therefore the generator's,
|
|
4250
|
+
* not a place to keep anything by hand.
|
|
4251
|
+
*
|
|
4252
|
+
* Only the direct `.ts` children are removed, never a subdirectory, and never a file another job
|
|
4253
|
+
* writes on its own: a single-file output that lives inside a split directory is left where it is
|
|
4254
|
+
* rather than deleted and rewritten. A split job that merges into the user's code is never
|
|
4255
|
+
* cleaned at all.
|
|
4256
|
+
*
|
|
4257
|
+
* This runs before any job writes, never per job as it goes: two jobs can be aimed at one
|
|
4258
|
+
* directory, and a clean that lands after a sibling has filled it would take the fresh files with
|
|
4259
|
+
* it.
|
|
4260
|
+
*/
|
|
4261
|
+
function cleanSplitOutputs(jobs) {
|
|
4262
|
+
return Effect.gen(function* () {
|
|
4263
|
+
const keep = new Set(jobs.filter((job) => !job.split).map((job) => path.resolve(process.cwd(), job.output)));
|
|
4264
|
+
const directories = new Set(jobs.filter((job) => job.split && !isUserCodeJob(job)).map((job) => path.resolve(process.cwd(), job.output)));
|
|
4265
|
+
return (yield* Effect.all([...directories].map((directory) => cleanSplitDirectory(directory, keep)), { concurrency: "unbounded" })).flat();
|
|
4266
|
+
});
|
|
4267
|
+
}
|
|
4268
|
+
const TYPESPEC_IMPORT = /^\s*import\s+"(?<specifier>\.{1,2}\/[^"]*)"/gmu;
|
|
4269
|
+
/**
|
|
4270
|
+
* The `.tsp` files reachable from `file` through relative imports, `file` included.
|
|
4271
|
+
*
|
|
4272
|
+
* Read off the source text rather than asked of the compiler: a compile is the expensive part of
|
|
4273
|
+
* a pass, and the only thing wanted here is which files an edit could come from. An import of a
|
|
4274
|
+
* directory is its `main.tsp`, as it is to the compiler. A file that cannot be read is still
|
|
4275
|
+
* named — it is where the fix will be written.
|
|
4276
|
+
*/
|
|
4277
|
+
function typeSpecSources(file, seen) {
|
|
4278
|
+
return Effect.gen(function* () {
|
|
4279
|
+
if (seen.has(file)) return seen;
|
|
4280
|
+
const fs = yield* FileSystem.FileSystem;
|
|
4281
|
+
if ((yield* fs.stat(file).pipe(Effect.orElseSucceed(() => null)))?.type === "Directory") return yield* typeSpecSources(path.join(file, "main.tsp"), seen);
|
|
4282
|
+
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));
|
|
4284
|
+
});
|
|
4285
|
+
}
|
|
4286
|
+
/**
|
|
4287
|
+
* The files the document at `input` reads from that sit outside its own directory.
|
|
4288
|
+
*
|
|
4289
|
+
* For a watcher, and only for a watcher. A `$ref` or a TypeSpec `import` can reach a file
|
|
4290
|
+
* anywhere on disk, so watching the directory `input` sits in misses some of the edits that
|
|
4291
|
+
* change the output; these are the files it misses.
|
|
4292
|
+
*
|
|
4293
|
+
* Nothing here feeds generation. `parseOpenAPI` still reads the document with `bundle`, which is
|
|
4294
|
+
* what folds a split document into one; this asks `resolve`, which stops after reading the files
|
|
4295
|
+
* `bundle` would go on to fold. The two read the same files, so the list is the one `bundle`
|
|
4296
|
+
* works from, without paying for a document nobody uses — and an edit to one of them reruns the
|
|
4297
|
+
* pass, where `bundle` picks the new contents up.
|
|
4298
|
+
*
|
|
4299
|
+
* Nothing under `node_modules` is named: a library the document imports is not something the
|
|
4300
|
+
* user edits. Fails when the document cannot be read, so the caller can keep the list it already
|
|
4301
|
+
* has rather than trust a partial one.
|
|
4302
|
+
*/
|
|
4303
|
+
function outsideSources(input) {
|
|
4304
|
+
return Effect.gen(function* () {
|
|
4305
|
+
const files = input.endsWith(".tsp") ? [...yield* typeSpecSources(path.resolve(input), /* @__PURE__ */ new Set())] : yield* Effect.tryPromise({
|
|
4306
|
+
try: async () => {
|
|
4307
|
+
return (await SwaggerParser.resolve(input)).paths("file");
|
|
4308
|
+
},
|
|
4309
|
+
catch: (error) => new GenerateError({ message: error instanceof Error ? error.message : String(error) })
|
|
4310
|
+
});
|
|
4311
|
+
const inputDirectory = path.dirname(path.resolve(input));
|
|
4312
|
+
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
|
+
});
|
|
4314
|
+
}
|
|
4017
4315
|
//#endregion
|
|
4018
|
-
export {
|
|
4316
|
+
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 };
|