asphodelos 0.2.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.
@@ -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) {
@@ -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).map(([k, v]) => `${JSON.stringify(k)}:${stringifyRefs(v)}`).join(",")}}`;
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
- const list = JSON.stringify(values);
885
- return opts ? `t.UnionEnum(${list},${opts})` : `t.UnionEnum(${list})`;
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 pathEntries(api)) {
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
  }
@@ -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 makeJsDocs(method, pathStr, operation) {
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
- const fn = `export async function ${funcName}(${[...paramArgs.map((p) => `${p.name}: ${p.typeExpr}`), `...args: Parameters<${methodHostTypeExpr}>`].join(", ")}) {\n return ${callExpr}(...args)\n}`;
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, docs = false) {
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 pathEntries(openAPI)) {
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$1(`${prefix}${pathStr}`, method, operation, client, docs));
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) return makeModuleSpec(fromFile, {
2205
- output: path.resolve(process.cwd(), options.componentsOutput),
2206
- split: false
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,172 +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
- const MUTATION_OMIT_KEYS = `'mutationKey' | 'mutationFn'`;
2252
- function omitInjectedKeys(config, optionsType, keys, marker = "{ queryKey: unknown }") {
2253
- return `Omit<${config.maybeRefOptions ? `Extract<${optionsType}, ${marker}>` : optionsObjectType(config, optionsType)}, ${keys}>`;
2254
- }
2255
- function makeGetQueryOptionsParam(config, dataT, keyName) {
2256
- const optType = config.queryOptionsType;
2257
- const omit = (optionsType) => omitInjectedKeys(config, optionsType, QUERY_OMIT_KEYS);
2258
- if (config.useQueryGenerics) return `queryOptions?: ${omit(`${optType}<${dataT}, TError, TData>`)}`;
2259
- if (config.maybeRefOptions) return `queryOptions?: ${omit(`${optType}<${dataT}, TError, TData, ${dataT}, ReturnType<typeof ${keyName}>>`)}`;
2260
- if (config.thunkOptionsCall) return `queryOptions?: () => ${omit(`${optType}<${dataT}, TError, TData, ReturnType<typeof ${keyName}>>`)}`;
2261
- return `queryOptions?: ${omit(`${optType}<${dataT}, TError, TData>`)}`;
2262
- }
2263
- function makeMutationOptionsParam(config, dataT, errorT, variablesType) {
2264
- const optType = omitInjectedKeys(config, `${config.mutationOptionsType}<${dataT}, ${errorT}, ${variablesType}>`, MUTATION_OMIT_KEYS, "{ mutationKey?: unknown }");
2265
- return config.thunkOptionsCall ? `mutationOptions?: () => ${optType}` : `mutationOptions?: ${optType}`;
2266
- }
2267
- function makeGetHookBody(config, dataT, keyCall, queryFnBlock) {
2268
- const inner = `${config.thunkOptionsCall ? "...queryOptions?.()" : "...queryOptions"},queryKey:${keyCall},${queryFnBlock}`;
2269
- if (config.useQueryGenerics) return `${config.queryFn}<${dataT},TError,TData>({${inner}})`;
2270
- if (config.useThunk) return `${config.queryFn}(()=>({${inner}}))`;
2271
- return `${config.queryFn}({${inner}})`;
2272
- }
2273
- function makeMutationFactoryCode(name, keySig, keyCall, dataT, errorT, variablesType, mutationFnBlock) {
2274
- return `export function ${name}<TError = ${errorT}>(${keySig}){return mutationOptions<${dataT},TError,${variablesType}>({mutationKey:${keyCall},${mutationFnBlock}})}`;
2275
- }
2276
- function makeMutationHookBody(config, dataT, variablesType, factoryCall) {
2277
- const inner = `${config.thunkOptionsCall ? "...mutationOptions?.()" : "...mutationOptions"},...${factoryCall}`;
2278
- if (config.useQueryGenerics) return `${config.mutationFn}<${dataT},TError,${variablesType}>({${inner}})`;
2279
- if (config.useThunk) return `${config.mutationFn}(()=>({${inner}}))`;
2280
- return `${config.mutationFn}({${inner}})`;
2281
- }
2282
- function makeTanstackInfiniteParts(config, args) {
2283
- const { funcName, hookName, suspenseHookName, keyPrefix, pathStr } = args;
2284
- const { paramSig, paramPass, optionsType, dataT, errorT, callExpr } = args;
2285
- const infiniteKeyName = `${funcName}InfiniteQueryKey`;
2286
- const infiniteKeyCode = `export function ${infiniteKeyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){const{headers:_h,fetch:_f,throwHttpError:_t,...keyArgs}=options??{};return[${[
2287
- `'${keyPrefix}'`,
2288
- `'${pathStr}'`,
2289
- `'infinite'`,
2290
- ...paramPass,
2291
- "keyArgs"
2292
- ].join(", ")}]as const}`;
2293
- const infiniteKeyCall = `${infiniteKeyName}(${[...paramPass, "options"].join(", ")})`;
2294
- const infiniteHookName = `${hookName}Infinite`;
2295
- const suspenseInfiniteHookName = `${suspenseHookName}Infinite`;
2296
- const queryKeyType = `ReturnType<typeof ${infiniteKeyName}>`;
2297
- const paginationParam = `pagination: { initialPageParam: TPageParam; getNextPageParam: (lastPage: ${dataT}, allPages: ${dataT}[], lastPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | undefined | null; buildInit: (pageParam: unknown) => ${optionsType} }`;
2298
- const infiniteSig = [
2299
- ...paramSig,
2300
- `options: ${optionsType} | undefined`,
2301
- paginationParam
2302
- ].join(", ");
2303
- 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},`;
2304
- 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})}`;
2305
- const infiniteGenerics = `<TPageParam = unknown, TData = InfiniteData<${dataT}, TPageParam>, TError = ${errorT}>`;
2306
- 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},`;
2307
- const inner = `${config.thunkOptionsCall ? "...queryOptions?.()" : "...queryOptions"},queryKey:${infiniteKeyCall},${hookQueryFnBody}initialPageParam:pagination.initialPageParam,getNextPageParam:pagination.getNextPageParam`;
2308
- const hookBody = (queryFn) => config.useThunk ? `${queryFn}(()=>({${inner}}))` : `${queryFn}({${inner}})`;
2309
- const hookSig = (libOptionsType) => {
2310
- const fullType = omitInjectedKeys(config, `${libOptionsType}<${dataT}, TError, TData, ${queryKeyType}, TPageParam>`, INFINITE_OMIT_KEYS);
2311
- 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: ""
2312
2380
  };
2313
- const infiniteCode = `export function ${infiniteHookName}${infiniteGenerics}(${hookSig(config.infiniteOptionsType)}){return ${hookBody(config.infiniteQueryFn)}}`;
2314
- if (!config.suspenseInfiniteQueryFn) return [
2315
- infiniteKeyCode,
2316
- infiniteOptionsCode,
2317
- infiniteCode
2318
- ];
2319
- return [
2320
- infiniteKeyCode,
2321
- infiniteOptionsCode,
2322
- infiniteCode,
2323
- `export function ${suspenseInfiniteHookName}${infiniteGenerics}(${hookSig(config.suspenseInfiniteOptionsType)}){return ${hookBody(config.suspenseInfiniteQueryFn)}}`
2324
- ];
2325
- }
2326
- function makeInfiniteParts(config, args) {
2327
- if (config.hasInfiniteQueryOptionsHelper) return makeTanstackInfiniteParts(config, args);
2328
- const { funcName, hookName, keyPrefix, pathStr } = args;
2329
- const { paramSig, paramPass, optionsType, dataT, errorT, callExpr } = args;
2330
- const infiniteKeyName = `${funcName}InfiniteQueryKey`;
2331
- const infiniteKeyCode = `export function ${infiniteKeyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){const{headers:_h,fetch:_f,throwHttpError:_t,...keyArgs}=options??{};return[${[
2332
- `'${keyPrefix}'`,
2333
- `'${pathStr}'`,
2334
- `'infinite'`,
2335
- ...paramPass,
2336
- "keyArgs"
2337
- ].join(", ")}]as const}`;
2338
- const infiniteKeyCall = `${infiniteKeyName}(${[...paramPass, "options"].join(", ")})`;
2339
- const infiniteHookName = `${hookName}Infinite`;
2340
- const infiniteGenerics = `<TPageParam = unknown, TData = InfiniteData<${dataT}, TPageParam>, TError = ${errorT}>`;
2341
- 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},`;
2342
- const fullOptionsType = `${config.infiniteOptionsType}<${dataT}, TError, TData, ReturnType<typeof ${infiniteKeyName}>, TPageParam>`;
2343
- const infiniteHookSig = [
2344
- ...paramSig,
2345
- `options: ${optionsType} | undefined`,
2346
- `pagination: { buildInit: (pageParam: unknown) => ${optionsType} }`,
2347
- `queryOptions: ${omitInjectedKeys(config, fullOptionsType, QUERY_OMIT_KEYS)}`
2348
- ].join(", ");
2349
- const inner = `...queryOptions,queryKey:${infiniteKeyCall},${infiniteQueryFnBlock}`;
2350
- return [infiniteKeyCode, `export function ${infiniteHookName}${infiniteGenerics}(${infiniteHookSig}){return ${config.infiniteQueryFn}({${inner}})}`];
2351
- }
2352
- function makeSwrOperation(config, args) {
2353
- const { hookName, immutableHookName, keyName, keyPrefix, pathStr, method } = args;
2354
- const { paramSig, paramPass } = args;
2355
- const { argsType, optionsType, dataT, errorT, callExpr } = args;
2356
- const { isQuery, isBodyMethod, isPaginated, hasKeyArgs, optMark } = args;
2357
- if (isQuery) {
2358
- const keySig = (hasKeyArgs ? [...paramSig, `options?: ${optionsType}`] : paramSig).join(", ");
2359
- const keyTuple = [
2360
- `'${keyPrefix}'`,
2361
- `'${pathStr}'`,
2362
- ...paramPass,
2363
- ...hasKeyArgs ? ["keyArgs"] : []
2364
- ].join(", ");
2365
- 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}`;
2366
- const keyCall = `${keyName}(${[...paramPass, ...hasKeyArgs ? ["options"] : []].join(", ")})`;
2367
- const generics = `<TError = ${errorT}>`;
2368
- const hookSig = [
2369
- ...paramSig,
2370
- `options${optMark}: ${optionsType}`,
2371
- `config?: SWRConfiguration<${dataT}, TError>`
2372
- ].join(", ");
2373
- 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)}`;
2374
- const hookCode = config.immutableQueryFn ? `${swrHook(hookName, config.queryFn)}\n\n${swrHook(immutableHookName, config.immutableQueryFn)}` : swrHook(hookName, config.queryFn);
2375
- if (isPaginated) {
2376
- const infiniteHookName = `${hookName}Infinite`;
2377
- const infiniteHookSig = [
2378
- ...paramSig,
2379
- `buildInit: (pageIndex: number, previousPage: ${dataT} | null) => ${optionsType} | null`,
2380
- `config?: SWRInfiniteConfiguration<${dataT}, TError>`
2381
- ].join(", ");
2382
- const infiniteKeyTuple = [
2383
- `'${keyPrefix}'`,
2384
- `'${pathStr}'`,
2385
- `'infinite'`,
2386
- "pageIndex",
2387
- ...paramPass,
2388
- "keyArgs"
2389
- ].join(", ");
2390
- const fetcherDestructure = [
2391
- "_resource",
2392
- "_opId",
2393
- "_infinite",
2394
- "_pageIndex",
2395
- ...paramPass.map((_, i) => `_key${i}`),
2396
- "keyArgs"
2397
- ].join(", ");
2398
- 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)}`}`;
2399
- }
2400
- return `${keyCode}\n\n${hookCode}`;
2401
- }
2402
- const keyCode = `export function ${keyName}(${paramSig.join(", ")}){return ${`[${[
2403
- `'${keyPrefix}'`,
2404
- `'${pathStr}'`,
2405
- `'${method.toUpperCase()}'`,
2406
- ...paramPass
2407
- ].join(", ")}] as const`}}`;
2408
- const keyCall = `${keyName}(${paramPass.join(", ")})`;
2409
- const variablesType = isBodyMethod ? `{ body: ${argsType}[0]; options${optMark}: ${argsType}[1] }` : `{ options${optMark}: ${argsType}[0] }`;
2410
- const triggerCallExpr = isBodyMethod ? `${callExpr}(arg.body, arg.options)` : `${callExpr}(arg.options)`;
2411
- 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)}`}`;
2412
2381
  }
2413
2382
  function needsFetchHook(pathStr) {
2414
2383
  return pathStr.split("/").filter(Boolean).some((seg) => seg.includes(".") || seg.includes("{") && !/^\{[^}]+\}$/u.test(seg));
@@ -2427,281 +2396,456 @@ function successType(operation) {
2427
2396
  if (info.void) return { dataT: "void" };
2428
2397
  return { dataT: "unknown" };
2429
2398
  }
2430
- function fetchTypeImport(pathStr, operation) {
2431
- return needsFetchHook(pathStr) ? successType(operation).importName : void 0;
2399
+ function isBodyMethod(method) {
2400
+ return method === "post" || method === "put" || method === "patch" || method === "delete";
2432
2401
  }
2433
- function makeFetchOperation(pathStr, method, operation, config) {
2434
- const funcName = toSafeIdentifier(resolveOperationId(operation, method, pathStr));
2435
- const Op = capitalize(funcName);
2436
- const hookName = `${config.hookPrefix}${Op}`;
2437
- const suspenseHookName = `${config.hookPrefix}Suspense${Op}`;
2438
- const immutableHookName = `${config.hookPrefix}Immutable${Op}`;
2439
- const keyPrefix = resourcePrefix(pathStr);
2440
- const isQuery = method === "get" || method === "head";
2441
- const params = pathParamNames(pathStr);
2442
- const paramSig = params.map((p) => `${p}: string`);
2443
- const paramPass = [...params];
2444
- const hasQuery = (operation.parameters ?? []).some((p) => "in" in p && p.in === "query");
2445
- const optionsType = hasQuery ? "{ headers?: Record<string, string>; query?: Record<string, unknown> }" : "{ headers?: Record<string, string> }";
2446
- const { dataT } = successType(operation);
2447
- const errorT = "unknown";
2448
- const urlInner = pathStr.replaceAll(/\{([^}]+)\}/gu, (_, n) => `\${encodeURIComponent(${n})}`);
2449
- const urlExpr = hasQuery ? `\`${urlInner}\${search.size ? \`?\${search}\` : ''}\`` : `\`${urlInner}\``;
2450
- 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))}}` : "";
2451
- 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())`;
2452
- const keyArgsDecl = hasQuery ? "const{headers:_h,...keyArgs}=options??{};" : "";
2453
- const keyTuple = [
2454
- `'${keyPrefix}'`,
2455
- `'${pathStr}'`,
2456
- ...paramPass,
2457
- ...hasQuery ? ["keyArgs"] : []
2458
- ].join(", ");
2459
- if (config.isSWR && isQuery) {
2460
- const keyName = `${funcName}QueryKey`;
2461
- const keyCode = `export function ${keyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){${keyArgsDecl}return[${keyTuple}]as const}`;
2462
- const keyCall = `${keyName}(${[...paramPass, "options"].join(", ")})`;
2463
- const fetcher = `async():Promise<${dataT}>=>{${getBody(dataT, "options", false)}}`;
2464
- const hookSig = [
2465
- ...paramSig,
2466
- `options?: ${optionsType}`,
2467
- `config?: SWRConfiguration<${dataT}, TError>`
2468
- ].join(", ");
2469
- const swrHook = (name, swrFn) => `export function ${name}<TError=${errorT}>(${hookSig}){return ${swrFn}<${dataT},TError>(${keyCall},${fetcher},config)}`;
2470
- return `${keyCode}\n\n${config.immutableQueryFn ? `${swrHook(hookName, config.queryFn)}\n\n${swrHook(immutableHookName, config.immutableQueryFn)}` : swrHook(hookName, config.queryFn)}`;
2471
- }
2472
- 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())`;
2473
- const variablesType = `{ body?: unknown; options?: ${optionsType} }`;
2474
- if (config.isSWR) {
2475
- const keyName = `${funcName}MutationKey`;
2476
- const keyExpr = `[${[
2477
- `'${keyPrefix}'`,
2478
- `'${pathStr}'`,
2479
- `'${method.toUpperCase()}'`,
2480
- ...paramPass
2481
- ].join(", ")}] as const`;
2482
- const keyCode = `export function ${keyName}(${paramSig.join(", ")}){return ${keyExpr}}`;
2483
- const keyCall = `${keyName}(${paramPass.join(", ")})`;
2484
- const triggerCb = `async(_key:ReturnType<typeof ${keyName}>,{arg}:{arg:${variablesType}}):Promise<${dataT}>=>{${mutationBody("arg.options", "arg.body")}}`;
2485
- 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)}`}`;
2486
- }
2487
- if (isQuery) {
2488
- const keyName = `${funcName}QueryKey`;
2489
- const keyCode = `export function ${keyName}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){${keyArgsDecl}return[${keyTuple}]as const}`;
2490
- const keyCall = `${keyName}(${[...paramPass, "options"].join(", ")})`;
2491
- const queryFnBlock = `queryFn:async(${config.queryFnContext ? "{signal}:QueryFunctionContext" : "{signal}"}):Promise<${dataT}>=>{${getBody(dataT, "options", true)}},`;
2492
- const queryOptionsCode = `export function ${`${funcName}QueryOptions`}(${[...paramSig, `options?: ${optionsType}`].join(", ")}){return queryOptions({queryKey:${keyCall},queryFn:async({signal}):Promise<${dataT}>=>{${getBody(dataT, "options", true)}}})}`;
2493
- const generics = `<TData = ${dataT}, TError = ${errorT}>`;
2494
- const queryOptionsParam = makeGetQueryOptionsParam(config, dataT, keyName);
2495
- const parts = [
2496
- keyCode,
2497
- queryOptionsCode,
2498
- `export function ${hookName}${generics}(${[
2499
- ...paramSig,
2500
- `options?: ${optionsType}`,
2501
- queryOptionsParam
2502
- ].join(", ")}){return ${makeGetHookBody(config, dataT, keyCall, queryFnBlock)}}`
2503
- ];
2504
- if (config.suspenseQueryFn) {
2505
- const suspenseHookCode = `export function ${suspenseHookName}${generics}(${[
2506
- ...paramSig,
2507
- `options?: ${optionsType}`,
2508
- `queryOptions?: ${omitInjectedKeys(config, `${config.suspenseQueryOptionsType}<${dataT}, TError, TData>`, QUERY_OMIT_KEYS)}`
2509
- ].join(", ")}){return ${config.suspenseQueryFn}<${dataT},TError,TData>({...queryOptions,queryKey:${keyCall},${queryFnBlock}})}`;
2510
- parts.push(suspenseHookCode);
2511
- }
2512
- return parts.join("\n\n");
2513
- }
2514
- const keyName = `${funcName}MutationKey`;
2515
- const keyExpr = `[${[
2516
- `'${keyPrefix}'`,
2517
- `'${pathStr}'`,
2518
- `'${method.toUpperCase()}'`,
2519
- ...paramPass
2520
- ].join(", ")}] as const`;
2521
- const keyCode = `export function ${keyName}(${paramSig.join(", ")}){return ${keyExpr}}`;
2522
- const keyCall = `${keyName}(${paramPass.join(", ")})`;
2523
- const mutationFnBlock = `mutationFn:async({body,options}):Promise<${dataT}>=>{${mutationBody("options", "body")}},`;
2524
- const mutationOptionsName = `${funcName}MutationOptions`;
2525
- const factoryCode = makeMutationFactoryCode(mutationOptionsName, paramSig.join(", "), keyCall, dataT, errorT, variablesType, mutationFnBlock);
2526
- const factoryCall = `${mutationOptionsName}<TError>(${paramPass.join(", ")})`;
2527
- const mutationOptionsParam = makeMutationOptionsParam(config, dataT, "TError", variablesType);
2528
- return `${keyCode}\n\n${factoryCode}\n\n${`export function ${hookName}<TError=${errorT}>(${[...paramSig, mutationOptionsParam].join(", ")}){return ${makeMutationHookBody(config, dataT, variablesType, factoryCall)}}`}`;
2529
- }
2530
- function makeOperation(pathStr, method, operation, client, config) {
2531
- if (needsFetchHook(pathStr)) return makeFetchOperation(pathStr, method, operation, config);
2532
- const funcName = toSafeIdentifier(resolveOperationId(operation, method, pathStr));
2533
- const Op = capitalize(funcName);
2534
- const hookName = `${config.hookPrefix}${Op}`;
2535
- const suspenseHookName = `${config.hookPrefix}Suspense${Op}`;
2536
- const immutableHookName = `${config.hookPrefix}Immutable${Op}`;
2537
- const isQuery = method === "get" || method === "head";
2538
- const keyName = `${funcName}${isQuery ? "QueryKey" : "MutationKey"}`;
2539
- const keyPrefix = resourcePrefix(pathStr);
2540
- const { callExpr, methodHostTypeExpr, paramArgs } = edenChain(pathStr, client, method);
2541
- const paramSig = paramArgs.map((p) => `${p.name}: ${p.typeExpr}`);
2542
- const paramPass = paramArgs.map((p) => p.name);
2402
+ function edenTarget(fullPath, method, operation, client) {
2403
+ const { callExpr, methodHostTypeExpr, paramArgs } = edenChain(fullPath, client, method);
2543
2404
  const argsType = `Parameters<${methodHostTypeExpr}>`;
2544
- const optionsType = `${argsType}[0]`;
2405
+ const withBody = isBodyMethod(method);
2406
+ const optionsType = withBody ? `${argsType}[1]` : `${argsType}[0]`;
2545
2407
  const response = `Awaited<ReturnType<${methodHostTypeExpr}>>`;
2546
- const dataT = `Extract<${response}, { error: null }>['data']`;
2547
- const errorT = `Exclude<${response}['error'], null>`;
2548
- const isBodyMethod = method === "post" || method === "put" || method === "patch" || method === "delete";
2549
- const isPaginated = operation["x-pagination"] === true;
2550
- const hasKeyArgs = (operation.parameters ?? []).some((p) => "in" in p ? p.in === "query" : true);
2551
2408
  const requiredOptions = (operation.parameters ?? []).some((p) => "in" in p && (p.in === "query" || p.in === "header") && p.required === true);
2552
- const optMark = requiredOptions ? "" : "?";
2553
- const optFetch = requiredOptions ? "options.fetch" : "options?.fetch";
2554
- if (config.isSWR) return makeSwrOperation(config, {
2555
- hookName,
2556
- immutableHookName,
2557
- keyName,
2558
- keyPrefix,
2559
- pathStr,
2560
- method,
2561
- paramSig,
2562
- paramPass,
2563
- argsType,
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
+ })),
2564
2450
  optionsType,
2451
+ requiredOptions: false,
2452
+ hasKeyArgs: hasQuery,
2453
+ keyDrops: ["headers"],
2565
2454
  dataT,
2566
- errorT,
2567
- callExpr,
2568
- isQuery,
2569
- isBodyMethod,
2570
- isPaginated,
2571
- hasKeyArgs,
2572
- optMark
2573
- });
2574
- if (isQuery) {
2575
- const keySig = (hasKeyArgs ? [...paramSig, `options?: ${optionsType}`] : paramSig).join(", ");
2576
- const keyTuple = [
2577
- `'${keyPrefix}'`,
2578
- `'${pathStr}'`,
2579
- ...paramPass,
2580
- ...hasKeyArgs ? ["keyArgs"] : []
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} }`
2581
2629
  ].join(", ");
2582
- 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}`;
2583
- const keyCall = `${keyName}(${[...paramPass, ...hasKeyArgs ? ["options"] : []].join(", ")})`;
2584
- 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}})}`;
2585
- const queryFnBlock = `queryFn:async(${config.queryFnContext ? "{signal}:QueryFunctionContext" : "{signal}"})=>{const{data,error}=await ${callExpr}({...options,fetch:{...${optFetch},signal}});if(error)throw error;return data},`;
2586
- const generics = `<TData = ${dataT}, TError = ${errorT}>`;
2587
- const queryOptionsParam = makeGetQueryOptionsParam(config, dataT, keyName);
2588
- const parts = [
2630
+ return [
2589
2631
  keyCode,
2590
- queryOptionsCode,
2591
- `export function ${hookName}${generics}(${[
2592
- ...paramSig,
2593
- `options${optMark}: ${optionsType}`,
2594
- queryOptionsParam
2595
- ].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})}`
2596
2634
  ];
2597
- if (config.suspenseQueryFn) {
2598
- const suspenseHookCode = `export function ${suspenseHookName}${generics}(${[
2599
- ...paramSig,
2600
- `options${optMark}: ${optionsType}`,
2601
- `queryOptions?: ${omitInjectedKeys(config, `${config.suspenseQueryOptionsType}<${dataT}, TError, TData>`, QUERY_OMIT_KEYS)}`
2602
- ].join(", ")}){return ${config.suspenseQueryFn}<${dataT},TError,TData>({...queryOptions,queryKey:${keyCall},${queryFnBlock}})}`;
2603
- parts.push(suspenseHookCode);
2604
- }
2605
- if (isPaginated) parts.push(...makeInfiniteParts(config, {
2606
- funcName,
2607
- hookName,
2608
- suspenseHookName,
2609
- keyPrefix,
2610
- pathStr,
2611
- paramSig,
2612
- paramPass,
2613
- optionsType,
2614
- dataT,
2615
- errorT,
2616
- callExpr
2617
- }));
2618
- return parts.join("\n\n");
2619
- }
2620
- const keySig = paramSig.join(", ");
2621
- const keyCode = `export function ${keyName}(${keySig}){return ${`[${[
2622
- `'${keyPrefix}'`,
2623
- `'${pathStr}'`,
2624
- `'${method.toUpperCase()}'`,
2625
- ...paramPass
2626
- ].join(", ")}] as const`}}`;
2627
- const keyCall = `${keyName}(${paramPass.join(", ")})`;
2628
- const variablesType = isBodyMethod ? `{ body: ${argsType}[0]; options${optMark}: ${argsType}[1] }` : `{ options${optMark}: ${argsType}[0] }`;
2629
- const mutationFnBlock = isBodyMethod ? `mutationFn:async({body,options})=>{const{data,error}=await ${callExpr}(body,options);if(error)throw error;return data},` : `mutationFn:async({options})=>{const{data,error}=await ${callExpr}(options);if(error)throw error;return data},`;
2630
- const mutationOptionsName = `${funcName}MutationOptions`;
2631
- const factoryCode = makeMutationFactoryCode(mutationOptionsName, keySig, keyCall, dataT, errorT, variablesType, mutationFnBlock);
2632
- const factoryCall = `${mutationOptionsName}<TError>(${paramPass.join(", ")})`;
2633
- const mutationGenerics = `<TError = ${errorT}>`;
2634
- const mutationOptionsParam = makeMutationOptionsParam(config, dataT, "TError", variablesType);
2635
- return `${keyCode}\n\n${factoryCode}\n\n${`export function ${hookName}${mutationGenerics}(${[...paramSig, mutationOptionsParam].join(", ")}){return ${makeMutationHookBody(config, dataT, variablesType, factoryCall)}}`}`;
2636
- }
2637
- function makeSwrHeader(config, client, importPath, deps) {
2638
- return `${deps.isQuery ? `import useSWR from 'swr'\nimport type { SWRConfiguration } from 'swr'\n` : ""}${deps.isQuery && config.immutableQueryFn ? `import ${config.immutableQueryFn} from 'swr/immutable'\n` : ""}${deps.isInfinite ? `import useSWRInfinite from 'swr/infinite'\nimport type { SWRInfiniteConfiguration } from 'swr/infinite'\n` : ""}${deps.isMutation ? `import useSWRMutation from 'swr/mutation'\nimport type { SWRMutationConfiguration } from 'swr/mutation'\n` : ""}import { ${client} } from '${importPath}'\n\n`;
2639
- }
2640
- function makeHeader(config, client, importPath, deps) {
2641
- if (config.isSWR) return makeSwrHeader(config, client, importPath, deps);
2642
- const pkg = config.packageName;
2643
- const suspenseValue = config.suspenseQueryFn ? `, ${config.suspenseQueryFn}` : "";
2644
- const suspenseType = config.suspenseQueryOptionsType ? `, ${config.suspenseQueryOptionsType}` : "";
2645
- const suspenseInfiniteValue = config.suspenseInfiniteQueryFn ? `, ${config.suspenseInfiniteQueryFn}` : "";
2646
- const suspenseInfiniteType = config.suspenseInfiniteOptionsType ? `, ${config.suspenseInfiniteOptionsType}` : "";
2647
- return `${deps.isQuery ? `import { ${config.queryFn}${suspenseValue}, queryOptions } from '${pkg}'\n` : ""}${deps.isQuery ? `import type { ${config.queryOptionsType}${suspenseType} } from '${pkg}'\n` : ""}${deps.isInfinite ? config.hasInfiniteQueryOptionsHelper ? `import { ${config.infiniteQueryFn}${suspenseInfiniteValue}, infiniteQueryOptions } from '${pkg}'\n` : `import { ${config.infiniteQueryFn}${suspenseInfiniteValue} } from '${pkg}'\n` : ""}${deps.isInfinite ? `import type { ${config.infiniteOptionsType}, InfiniteData${suspenseInfiniteType} } from '${pkg}'\n` : ""}${deps.isMutation ? `import { ${config.mutationFn}, mutationOptions } from '${pkg}'\n` : ""}${deps.isMutation ? `import type { ${config.mutationOptionsType} } from '${pkg}'\n` : ""}${config.queryFnContext && deps.isQuery || deps.isInfinite ? `import type { QueryFunctionContext } from '${pkg}'\n` : ""}import { ${client} } from '${importPath}'\n\n`;
2648
- }
2649
- function makeQueryHooks(openAPI, output, importPath, config, client, basePath, split = false) {
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") {
2650
2808
  return Effect.gen(function* () {
2651
2809
  const prefix = basePath && basePath !== "/" ? basePath : "";
2652
- const ops = [];
2653
- for (const [pathStr, pathItem] of pathEntries(openAPI)) {
2654
- if (!pathItem) continue;
2655
- for (const method of HTTP_METHODS) {
2656
- const rawOperation = pathItem[method];
2657
- if (!rawOperation) continue;
2658
- const operation = resolveOperation(rawOperation, openAPI.components);
2659
- const funcName = toSafeIdentifier(resolveOperationId(operation, method, `${prefix}${pathStr}`));
2660
- const code = makeOperation(`${prefix}${pathStr}`, method, operation, client, config);
2661
- const keyPrefix = resourcePrefix(`${prefix}${pathStr}`);
2662
- const isQuery = method === "get" || method === "head";
2663
- ops.push({
2664
- funcName,
2665
- code,
2666
- prefix: keyPrefix,
2667
- deps: {
2668
- isQuery,
2669
- isInfinite: isQuery && operation["x-pagination"] === true,
2670
- isMutation: !isQuery
2671
- },
2672
- fetchType: fetchTypeImport(`${prefix}${pathStr}`, operation)
2673
- });
2674
- }
2675
- }
2676
- if (ops.length === 0) return "No operations found";
2677
- if (split) {
2678
- const prefixKeys = makePrefixKeyCodes(openAPI, prefix);
2679
- const keysCode = prefixKeys.length > 0 ? `${prefixKeys.join("\n\n")}\n` : "";
2680
- 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'." });
2681
- for (const op of ops) {
2682
- const header = makeHeader(config, client, importPath, op.deps);
2683
- const typeImport = op.fetchType ? `import type { ${op.fetchType} } from '../components/schemas'\n` : "";
2684
- const file = path.join(output, `${op.funcName}.ts`);
2685
- yield* emit(`${typeImport}${header}${op.code}\n`, output, file);
2686
- }
2687
- if (keysCode) yield* emit(keysCode, output, path.join(output, "keys.ts"));
2688
- yield* emit(`${[...keysCode ? [`export * from './keys'`] : [], ...ops.map((op) => `export * from './${op.funcName}'`)].join("\n")}\n`, output, path.join(output, "index.ts"));
2689
- return `Generated split ${config.label} code → ${output}/`;
2690
- }
2691
- yield* emit(`${makeHeader(config, client, importPath, ops.reduce((acc, op) => ({
2692
- isQuery: acc.isQuery || op.deps.isQuery,
2693
- isInfinite: acc.isInfinite || op.deps.isInfinite,
2694
- isMutation: acc.isMutation || op.deps.isMutation
2695
- }), {
2696
- isQuery: false,
2697
- isInfinite: false,
2698
- isMutation: false
2699
- }))}${`${[...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);
2700
2819
  return `Generated ${config.label} code written to ${output}`;
2701
2820
  });
2702
2821
  }
2703
2822
  //#endregion
2704
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
+ };
2705
2849
  const TANSTACK = {
2706
2850
  label: "tanstack-query",
2707
2851
  packageName: "@tanstack/react-query",
@@ -2709,15 +2853,14 @@ const TANSTACK = {
2709
2853
  queryFn: "useQuery",
2710
2854
  mutationFn: "useMutation",
2711
2855
  infiniteQueryFn: "useInfiniteQuery",
2712
- useQueryGenerics: true,
2713
- hasInfiniteQueryOptionsHelper: true,
2714
2856
  suspenseQueryFn: "useSuspenseQuery",
2715
2857
  suspenseInfiniteQueryFn: "useSuspenseInfiniteQuery",
2716
2858
  queryOptionsType: "UseQueryOptions",
2717
2859
  suspenseQueryOptionsType: "UseSuspenseQueryOptions",
2718
2860
  mutationOptionsType: "UseMutationOptions",
2719
2861
  infiniteOptionsType: "UseInfiniteQueryOptions",
2720
- suspenseInfiniteOptionsType: "UseSuspenseInfiniteQueryOptions"
2862
+ suspenseInfiniteOptionsType: "UseSuspenseInfiniteQueryOptions",
2863
+ hookTail: QUERY_CLIENT_TAIL
2721
2864
  };
2722
2865
  const HOOK_CONFIGS = {
2723
2866
  swr: {
@@ -2743,11 +2886,11 @@ const HOOK_CONFIGS = {
2743
2886
  queryFn: "useQuery",
2744
2887
  mutationFn: "useMutation",
2745
2888
  infiniteQueryFn: "useInfiniteQuery",
2746
- queryFnContext: true,
2747
- maybeRefOptions: true,
2889
+ isVueQuery: true,
2748
2890
  queryOptionsType: "UseQueryOptions",
2749
2891
  mutationOptionsType: "UseMutationOptions",
2750
- infiniteOptionsType: "UseInfiniteQueryOptions"
2892
+ infiniteOptionsType: "UseInfiniteQueryOptions",
2893
+ hookTail: QUERY_CLIENT_TAIL
2751
2894
  },
2752
2895
  "solid-query": {
2753
2896
  label: "solid-query",
@@ -2756,14 +2899,12 @@ const HOOK_CONFIGS = {
2756
2899
  queryFn: "createQuery",
2757
2900
  mutationFn: "createMutation",
2758
2901
  infiniteQueryFn: "createInfiniteQuery",
2759
- queryFnContext: true,
2760
2902
  useThunk: true,
2761
- thunkOptionsCall: true,
2762
2903
  unwrapOptionsAccessor: true,
2763
- hasInfiniteQueryOptionsHelper: true,
2764
2904
  queryOptionsType: "UndefinedInitialDataOptions",
2765
2905
  mutationOptionsType: "CreateMutationOptions",
2766
- infiniteOptionsType: "UndefinedInitialDataInfiniteOptions"
2906
+ infiniteOptionsType: "UndefinedInitialDataInfiniteOptions",
2907
+ hookTail: QUERY_CLIENT_ACCESSOR_TAIL
2767
2908
  },
2768
2909
  "svelte-query": {
2769
2910
  label: "svelte-query",
@@ -2772,12 +2913,11 @@ const HOOK_CONFIGS = {
2772
2913
  queryFn: "createQuery",
2773
2914
  mutationFn: "createMutation",
2774
2915
  infiniteQueryFn: "createInfiniteQuery",
2775
- queryFnContext: true,
2776
2916
  useThunk: true,
2777
- hasInfiniteQueryOptionsHelper: true,
2778
2917
  queryOptionsType: "CreateQueryOptions",
2779
2918
  mutationOptionsType: "CreateMutationOptions",
2780
- infiniteOptionsType: "CreateInfiniteQueryOptions"
2919
+ infiniteOptionsType: "CreateInfiniteQueryOptions",
2920
+ hookTail: QUERY_CLIENT_ACCESSOR_TAIL
2781
2921
  },
2782
2922
  "angular-query": {
2783
2923
  label: "angular-query",
@@ -2786,16 +2926,27 @@ const HOOK_CONFIGS = {
2786
2926
  queryFn: "injectQuery",
2787
2927
  mutationFn: "injectMutation",
2788
2928
  infiniteQueryFn: "injectInfiniteQuery",
2789
- queryFnContext: true,
2790
2929
  useThunk: true,
2791
- hasInfiniteQueryOptionsHelper: true,
2792
2930
  queryOptionsType: "CreateQueryOptions",
2793
2931
  mutationOptionsType: "CreateMutationOptions",
2794
- infiniteOptionsType: "CreateInfiniteQueryOptions"
2932
+ infiniteOptionsType: "CreateInfiniteQueryOptions",
2933
+ hookTail: INJECT_OPTIONS_TAIL
2795
2934
  }
2796
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
+ */
2797
2944
  function hooks(openAPI, output, importPath, library, options) {
2798
- return makeQueryHooks(openAPI, output, importPath, HOOK_CONFIGS[library], options.client, options.basePath, options.split);
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);
2799
2950
  }
2800
2951
  //#endregion
2801
2952
  //#region src/helper/faker.ts
@@ -3287,9 +3438,9 @@ function credentialExpr(scheme) {
3287
3438
  if (scheme.type === "http" || scheme.type === "oauth2" || scheme.type === "openIdConnect") return "c.headers.authorization";
3288
3439
  if (scheme.type !== "apiKey") return void 0;
3289
3440
  const name = scheme.name ?? "X-API-Key";
3290
- if (scheme.in === "query") return `c.query[${quoteSingle$1(name)}]`;
3291
- if (scheme.in === "cookie") return `c.cookie[${quoteSingle$1(name)}]?.value`;
3292
- return `c.headers[${quoteSingle$1(name.toLowerCase())}]`;
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())}]`;
3293
3444
  }
3294
3445
  /**
3295
3446
  * The guard a secured operation answers 401 with, or `''` when there is nothing to guard.
@@ -3315,9 +3466,9 @@ function authGuard(operation, spec, responses) {
3315
3466
  * The guard a path parameter answers 404 with, or `''` when there is nothing to guard.
3316
3467
  *
3317
3468
  * Emitted only when the operation declares a 404, for the same reason as the 401: a status the
3318
- * document never mentioned is one the client was never told to expect. The sentinel value is
3319
- * shared with the test generator, so a generated 404 test and the mock agree on which value
3320
- * means "not there".
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.
3321
3472
  */
3322
3473
  function notFoundGuard(operation, components, responses) {
3323
3474
  if (!("404" in responses)) return "";
@@ -3327,8 +3478,8 @@ function notFoundGuard(operation, components, responses) {
3327
3478
  if (!schema) return [];
3328
3479
  const sentinel = nonExistentPathValue(schema);
3329
3480
  if (!sentinel) return [];
3330
- const value = sentinel.kind === "literal" ? quoteSingle$1(sentinel.value) : `String(${sentinel.code})`;
3331
- return [`if (prefer.key === undefined && c.params[${quoteSingle$1(parameter.name)}] === ${value}) return c.status(404)`];
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)`];
3332
3483
  });
3333
3484
  return guards.length === 0 ? "" : `${guards.join("\n ")}\n `;
3334
3485
  }
@@ -3339,7 +3490,7 @@ function notFoundGuard(operation, components, responses) {
3339
3490
  */
3340
3491
  function returnStatement(status, body) {
3341
3492
  if (body.kind === "empty") return `return c.status(${status})`;
3342
- const header = body.kind === "json" && body.mediaType !== "application/json" ? `c.set.headers['content-type'] = ${quoteSingle$1(body.mediaType)}\n ` : "";
3493
+ const header = body.kind === "json" && body.mediaType !== "application/json" ? `c.set.headers['content-type'] = ${quoteSingle(body.mediaType)}\n ` : "";
3343
3494
  if (status === "200") return `${header}return ${body.kind === "json" ? `(${body.expr})` : body.expr}`;
3344
3495
  return `${header}return c.status(${status}, ${body.expr})`;
3345
3496
  }
@@ -3405,11 +3556,11 @@ function preferProblem(detail: string) {
3405
3556
  function indent(statement) {
3406
3557
  return statement.replaceAll("\n ", "\n ");
3407
3558
  }
3408
- function quoteSingle$1(s) {
3559
+ function quoteSingle(s) {
3409
3560
  return `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t")}'`;
3410
3561
  }
3411
3562
  function routePath(path) {
3412
- return quoteSingle$1(path.replaceAll(/\{([^}]+)\}/gu, ":$1"));
3563
+ return quoteSingle(path.replaceAll(/\{([^}]+)\}/gu, ":$1"));
3413
3564
  }
3414
3565
  /**
3415
3566
  * The middleware every response passes through when `delay` is configured.
@@ -3439,7 +3590,7 @@ function makeMock(spec, options = {}) {
3439
3590
  ...useExamples === "all" ? { useExamples: true } : {}
3440
3591
  };
3441
3592
  const components = spec.components;
3442
- const routes = pathEntries(spec).flatMap(([path, pathItem]) => {
3593
+ const routes = Object.entries(spec.paths).flatMap(([path, pathItem]) => {
3443
3594
  if (!pathItem) return [];
3444
3595
  return HTTP_METHODS.flatMap((method) => {
3445
3596
  const operation = pathItem[method];
@@ -3463,8 +3614,8 @@ function makeMock(spec, options = {}) {
3463
3614
  const render = (r, example) => {
3464
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)));
3465
3616
  };
3466
- const branches = [responses.flatMap((r) => r.named.filter(([, value]) => value !== r.example).map(([name, value]) => `if (prefer.key === ${quoteSingle$1(r.key)} && prefer.example === ${quoteSingle$1(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$1(r.key)}) {\n ${render(r, r.example)}\n }\n `)].flat();
3467
- const prefer = `const prefer = resolvePrefer(c.headers.prefer, c.query, ${JSON.stringify(preferTable)}, ${quoteSingle$1(success.key)})\n if (prefer.problem) return prefer.problem\n ${branches.join("")}`;
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("")}`;
3468
3619
  const successBody = responseBody(success.response, defaultExample(success.response, components, useExamples !== false), fakerOptions);
3469
3620
  const auth = authGuard(resolved, spec, resolved.responses);
3470
3621
  const notFound = notFoundGuard(resolved, components, resolved.responses);
@@ -3486,7 +3637,7 @@ function makeMock(spec, options = {}) {
3486
3637
  });
3487
3638
  });
3488
3639
  const mockFunctions = makeMockFunctions(spec, new Set(routes.flatMap((r) => r.refs)), fakerOptions);
3489
- const ctorArgs = prefix ? `{ prefix: ${quoteSingle$1(prefix)} }` : "";
3640
+ const ctorArgs = prefix ? `{ prefix: ${quoteSingle(prefix)} }` : "";
3490
3641
  const routeChain = routes.map((r) => ` ${r.code}`).join("\n");
3491
3642
  const listenBlock = `
3492
3643
 
@@ -3508,230 +3659,6 @@ function mock(openAPI, output, options = {}) {
3508
3659
  });
3509
3660
  }
3510
3661
  //#endregion
3511
- //#region src/generator/test/test-generator.ts
3512
- function extractSecurity(opSecurity, globalSecurity, securitySchemes) {
3513
- return (opSecurity ?? globalSecurity ?? []).flatMap((secDef) => Object.keys(secDef).flatMap((schemeName) => {
3514
- const scheme = securitySchemes?.[schemeName];
3515
- if (!scheme || typeof scheme.type !== "string") return [];
3516
- if (scheme.type === "http" && scheme.scheme === "bearer") return [{
3517
- type: "bearer",
3518
- name: "Authorization"
3519
- }];
3520
- if (scheme.type === "http" && scheme.scheme === "basic") return [{
3521
- type: "basic",
3522
- name: "Authorization"
3523
- }];
3524
- if (scheme.type === "apiKey") {
3525
- const inLocation = scheme.in === "header" || scheme.in === "query" || scheme.in === "cookie" ? scheme.in : "header";
3526
- return [{
3527
- type: "apiKey",
3528
- name: scheme.name || "X-API-Key",
3529
- in: inLocation
3530
- }];
3531
- }
3532
- if (scheme.type === "oauth2") return [{
3533
- type: "oauth2",
3534
- name: "Authorization"
3535
- }];
3536
- return [];
3537
- }));
3538
- }
3539
- function extractTestCases(spec) {
3540
- const components = spec.components;
3541
- return pathEntries(spec).flatMap(([path, pathItem]) => {
3542
- if (!pathItem) return [];
3543
- return HTTP_METHODS.flatMap((method) => {
3544
- const operation = pathItem[method];
3545
- if (!operation) return [];
3546
- const resolved = resolveOperation(operation, components);
3547
- const resolvedParams = resolved.parameters.map((param) => {
3548
- const schema = param.schema ?? { type: "string" };
3549
- return {
3550
- param,
3551
- schema,
3552
- fakerCode: schemaToFaker(schema, param.name)
3553
- };
3554
- });
3555
- const pathParams = resolvedParams.filter((p) => p.param.in === "path").map((p) => ({
3556
- name: p.param.name,
3557
- fakerCode: p.fakerCode,
3558
- schema: p.schema
3559
- }));
3560
- const queryParams = resolvedParams.filter((p) => p.param.in === "query").map((p) => ({
3561
- name: p.param.name,
3562
- fakerCode: p.fakerCode,
3563
- required: p.param.required ?? false
3564
- }));
3565
- const headerParams = resolvedParams.filter((p) => p.param.in === "header").map((p) => ({
3566
- name: p.param.name,
3567
- fakerCode: p.fakerCode,
3568
- required: p.param.required ?? false
3569
- }));
3570
- const requestBodyDef = resolved.requestBody;
3571
- const jsonMedia = requestBodyDef && "content" in requestBodyDef ? requestBodyDef.content?.["application/json"] : void 0;
3572
- const jsonBodySchema = jsonMedia && isMediaWithSchema(jsonMedia) ? jsonMedia.schema : void 0;
3573
- const requestBody = jsonBodySchema ? { fakerCode: schemaToFaker(jsonBodySchema) } : void 0;
3574
- const bodyRefs = jsonBodySchema ? collectSchemaRefs(jsonBodySchema, components?.schemas) : [];
3575
- const paramRefs = resolvedParams.flatMap((p) => collectSchemaRefs(p.schema, components?.schemas));
3576
- const usedSchemaRefs = [...new Set([...bodyRefs, ...paramRefs])];
3577
- const responseKeys = Object.keys(operation.responses ?? {});
3578
- const successStatus = responseKeys.filter((s) => s.startsWith("2")).map((s) => Number.parseInt(s, 10)).toSorted((a, b) => a - b)[0] ?? 200;
3579
- const errorStatuses = responseKeys.filter((s) => (s.startsWith("4") || s.startsWith("5")) && s !== "default").map((s) => Number.parseInt(s, 10)).toSorted((a, b) => a - b);
3580
- const security = extractSecurity(operation.security, spec.security, components?.securitySchemes);
3581
- return [{
3582
- operationId: resolveOperationId(operation, method, path),
3583
- method: method.toUpperCase(),
3584
- path,
3585
- summary: operation.summary || "",
3586
- tag: operation.tags?.[0],
3587
- pathParams,
3588
- queryParams,
3589
- headerParams,
3590
- requestBody,
3591
- successStatus,
3592
- errorStatuses,
3593
- security,
3594
- usedSchemaRefs
3595
- }];
3596
- });
3597
- });
3598
- }
3599
- function quoteSingle(s) {
3600
- return `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t")}'`;
3601
- }
3602
- function escapeTemplateLiteral(s) {
3603
- return s.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${");
3604
- }
3605
- function resolveNonExistent(schema, schemas) {
3606
- return nonExistentPathValue(schema.$ref && schemas ? schemas[schema.$ref.replace("#/components/schemas/", "")] ?? schema : schema);
3607
- }
3608
- function makeAuthHeader(sec) {
3609
- switch (sec.type) {
3610
- case "bearer":
3611
- case "oauth2": return "'Authorization':`Bearer ${faker.string.alphanumeric(32)}`";
3612
- case "basic": return "'Authorization':`Basic ${btoa(`${faker.internet.username()}:${faker.internet.password()}`)}`";
3613
- case "apiKey":
3614
- if (sec.in === "header") return `${quoteSingle(sec.name)}:faker.string.alphanumeric(32)`;
3615
- if (sec.in === "cookie") return `'Cookie':\`${escapeTemplateLiteral(sec.name)}=\${faker.string.alphanumeric(32)}\``;
3616
- return "";
3617
- default: return "";
3618
- }
3619
- }
3620
- function makeTestCase(tc, prefix = "", schemas) {
3621
- const fullPath = `${prefix && prefix !== "/" ? prefix : ""}${tc.path}`;
3622
- const escapedFullPath = escapeTemplateLiteral(fullPath);
3623
- const testPath = tc.pathParams.reduce((path, param) => path.replace(`{${param.name}}`, `\${${toSafeIdentifier(param.name)}}`), escapedFullPath);
3624
- const pathSetup = tc.pathParams.map((param) => `const ${toSafeIdentifier(param.name)}=${param.fakerCode}`);
3625
- const querySetup = tc.queryParams.map((param) => `const ${toSafeIdentifier(param.name)}=${param.fakerCode}`);
3626
- const queryParts = tc.queryParams.map((param) => `${escapeTemplateLiteral(param.name)}=\${encodeURIComponent(String(${toSafeIdentifier(param.name)}))}`);
3627
- const queryString = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
3628
- const authQueryParts = tc.security.filter((sec) => sec.type === "apiKey" && sec.in === "query").map((sec) => `${escapeTemplateLiteral(sec.name)}=\${faker.string.alphanumeric(32)}`);
3629
- const authQueryString = authQueryParts.length > 0 ? queryString ? `&${authQueryParts.join("&")}` : `?${authQueryParts.join("&")}` : "";
3630
- const requiredHeaderParams = tc.headerParams.filter((p) => p.required);
3631
- const headerSetup = requiredHeaderParams.map((param) => `const ${toSafeIdentifier(param.name)}=${param.fakerCode}`);
3632
- const headerEntries = requiredHeaderParams.map((param) => `${quoteSingle(param.name)}:String(${toSafeIdentifier(param.name)})`);
3633
- const authHeaders = tc.security.map(makeAuthHeader).filter(Boolean);
3634
- const { bodySetup, bodyOption, contentTypeHeader } = tc.requestBody ? {
3635
- bodySetup: `const body=${tc.requestBody.fakerCode}`,
3636
- bodyOption: ",body:JSON.stringify(body)",
3637
- contentTypeHeader: "'Content-Type':'application/json'"
3638
- } : {
3639
- bodySetup: "",
3640
- bodyOption: "",
3641
- contentTypeHeader: ""
3642
- };
3643
- const headers = [...headerEntries, ...contentTypeHeader ? [contentTypeHeader] : []];
3644
- const allHeaders = [...headers, ...authHeaders];
3645
- const headersOption = allHeaders.length > 0 ? `,headers:{${allHeaders.join(",")}}` : "";
3646
- const headersWithoutAuth = headers.length > 0 ? `,headers:{${headers.join(",")}}` : "";
3647
- const summaryPart = tc.summary ? ` - ${tc.summary}` : "";
3648
- const setupCode = [
3649
- ...pathSetup,
3650
- ...querySetup,
3651
- ...headerSetup,
3652
- bodySetup
3653
- ].filter(Boolean).join("\n");
3654
- const describeTitle = quoteSingle(`${tc.method} ${fullPath}`);
3655
- const methodLiteral = quoteSingle(tc.method);
3656
- 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) ? (() => {
3657
- const probes = tc.pathParams.map((param) => ({
3658
- param,
3659
- probe: resolveNonExistent(param.schema, schemas)
3660
- }));
3661
- if (probes.some(({ probe }) => probe === void 0)) return "";
3662
- const probeSetup = probes.flatMap(({ param, probe }) => probe?.kind === "expr" ? [`const ${toSafeIdentifier(param.name)}=${probe.code}`] : []);
3663
- const notFoundPath = probes.reduce((path, { param, probe }) => {
3664
- const value = probe?.kind === "expr" ? `\${${toSafeIdentifier(param.name)}}` : probe?.value ?? "";
3665
- return path.replace(`{${param.name}}`, value);
3666
- }, escapedFullPath);
3667
- return `\nit('should return 404 for non-existent resource',async()=>{${[
3668
- ...probeSetup,
3669
- ...querySetup,
3670
- ...headerSetup,
3671
- bodySetup
3672
- ].filter(Boolean).join("\n")}\nconst res=await app.handle(new Request(\`http://localhost${notFoundPath}${queryString}\`,{method:${methodLiteral}${headersOption}${bodyOption}}))\nexpect(res.status).toBe(404)})`;
3673
- })() : ""}})\n`;
3674
- }
3675
- function makeTagDescribes(testCases, spec, prefix) {
3676
- return [...testCases.reduce((acc, tc) => {
3677
- const tag = tc.tag || "default";
3678
- return acc.set(tag, [...acc.get(tag) ?? [], tc]);
3679
- }, /* @__PURE__ */ new Map()).entries()].map(([tag, cases]) => {
3680
- const tagDescription = (spec.tags?.find((t) => t.name === tag))?.description || tag;
3681
- const testCasesCode = cases.map((tc) => makeTestCase(tc, prefix, spec.components?.schemas)).join("");
3682
- return `describe(${quoteSingle(tagDescription)},()=>{${testCasesCode}})\n`;
3683
- }).join("");
3684
- }
3685
- function makeAppTestFile(spec, appImport, prefix, resourceFilter) {
3686
- const testCases = resourceFilter ? extractTestCases(spec).filter((tc) => resourceFilter.has(resourceName(tc.path))) : extractTestCases(spec);
3687
- const apiTitle = spec.info?.title || "API";
3688
- const mockFunctions = makeMockFunctions(spec, new Set(testCases.flatMap((tc) => tc.usedSchemaRefs)));
3689
- const tagDescribes = makeTagDescribes(testCases, spec, prefix);
3690
- const body = `${mockFunctions ? `${mockFunctions}\n\n` : ""}describe(${quoteSingle(apiTitle)},()=>{${tagDescribes}})\n`;
3691
- return `${`import{describe,it,expect}from'bun:test'${body.includes("faker.") ? `\nimport{faker}from'@faker-js/faker'` : ""}\nimport{app}from'${appImport}'\n`}\n${body}`;
3692
- }
3693
- function makeTestFile(spec, appImport = "..", prefix) {
3694
- return makeAppTestFile(spec, appImport, prefix);
3695
- }
3696
- function makeColocatedTestEntries(spec, appImport = "../../index", prefix) {
3697
- const resources = [...operationsByResource(spec).keys()];
3698
- const resourcesWithCases = new Set(extractTestCases(spec).map((tc) => resourceName(tc.path)));
3699
- return resources.filter((name) => resourcesWithCases.has(name)).map((name) => ({
3700
- name,
3701
- code: makeAppTestFile(spec, appImport, prefix, new Set([name]))
3702
- }));
3703
- }
3704
- //#endregion
3705
- //#region src/core/test/index.ts
3706
- /** Writes `code`, keeping whatever the user already wrote in `output`. */
3707
- function writeMerged(code, output) {
3708
- return Effect.gen(function* () {
3709
- const existing = yield* readFile(output);
3710
- yield* emit(existing === null ? code : mergeSource(existing, code), path.dirname(output), output);
3711
- });
3712
- }
3713
- function test(openAPI, output, options = {}) {
3714
- return Effect.gen(function* () {
3715
- const { appOutput = "src/index.ts", split = false, pathAlias, prefix } = options;
3716
- const appOutputAbs = path.resolve(process.cwd(), appOutput);
3717
- const appBase = path.basename(appOutput).replace(/\.ts$/u, "");
3718
- const appImportFor = (fromFileAbs) => {
3719
- if (pathAlias) return `${pathAlias.replace(/\/$/u, "")}/${appBase}`;
3720
- const rel = path.relative(path.dirname(fromFileAbs), appOutputAbs).replaceAll("\\", "/").replace(/\.ts$/u, "");
3721
- return rel.startsWith(".") ? rel : `./${rel}`;
3722
- };
3723
- if (split) {
3724
- const modulesDir = path.join(path.dirname(appOutputAbs), "modules");
3725
- const entries = makeColocatedTestEntries(openAPI, appImportFor(path.join(modulesDir, "resource", "index.test.ts")), prefix);
3726
- yield* Effect.all(entries.map((entry) => writeMerged(entry.code, path.join(modulesDir, entry.name, "index.test.ts"))), { concurrency: "unbounded" });
3727
- return `Generated ${entries.length} co-located test file(s) under ${path.posix.dirname(appOutput)}/modules/`;
3728
- }
3729
- if (output === void 0) return yield* new GenerateError({ message: "test.output is required when split is false" });
3730
- yield* writeMerged(makeTestFile(openAPI, appImportFor(path.resolve(process.cwd(), output)), prefix), output);
3731
- return `Generated test file written to ${output}`;
3732
- });
3733
- }
3734
- //#endregion
3735
3662
  //#region src/core/type/index.ts
3736
3663
  function primitiveTypeToTs(t) {
3737
3664
  if (t === "string") return "string";
@@ -3896,7 +3823,7 @@ function nestRoute(keys, method, opTs) {
3896
3823
  function makeRoutes(openAPI, prefix) {
3897
3824
  const out = [];
3898
3825
  const prefixKeys = prefix && prefix !== "/" ? pathToKeys(prefix) : [];
3899
- for (const [pathStr, pathItem] of pathEntries(openAPI)) {
3826
+ for (const [pathStr, pathItem] of Object.entries(openAPI.paths)) {
3900
3827
  if (!pathItem) continue;
3901
3828
  const keys = [...prefixKeys, ...pathToKeys(pathStr)];
3902
3829
  for (const method of HTTP_METHODS) {
@@ -3940,7 +3867,7 @@ function collectRefs(openAPI) {
3940
3867
  }
3941
3868
  if (resp.content) walkContentMap(resp.content);
3942
3869
  };
3943
- for (const [, pathItem] of pathEntries(openAPI)) {
3870
+ for (const [, pathItem] of Object.entries(openAPI.paths)) {
3944
3871
  if (!pathItem) continue;
3945
3872
  for (const method of HTTP_METHODS) {
3946
3873
  const op = pathItem[method];
@@ -3990,30 +3917,400 @@ function types(openAPI, output, prefix) {
3990
3917
  });
3991
3918
  }
3992
3919
  //#endregion
3993
- //#region src/core/index.ts
3994
- var core_exports = /* @__PURE__ */ __exportAll({
3995
- HOOK_CONFIGS: () => HOOK_CONFIGS,
3996
- callbacks: () => callbacks,
3997
- components: () => components,
3998
- eden: () => eden,
3999
- elysia: () => elysia,
4000
- examples: () => examples,
4001
- headers: () => headers,
4002
- hooks: () => hooks,
4003
- links: () => links,
4004
- makeAppType: () => makeAppType,
4005
- makeJsDocs: () => makeJsDocs,
4006
- mediaTypes: () => mediaTypes,
4007
- mock: () => mock,
4008
- parameters: () => parameters,
4009
- pathItems: () => pathItems,
4010
- requestBodies: () => requestBodies,
4011
- responses: () => responses,
4012
- schemaToTs: () => schemaToTs,
4013
- schemas: () => schemas,
4014
- securitySchemes: () => securitySchemes,
4015
- test: () => test,
4016
- 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
4017
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
+ }
4018
4315
  //#endregion
4019
- export { unlink as S, responses as _, hooks as a, fileSystemLayer as b, mediaTypes as c, links as d, securitySchemes as f, parameters as g, examples as h, mock as i, pathItems as l, requestBodies as m, types as n, elysia as o, headers as p, test as r, eden as s, core_exports as t, callbacks as u, schemas as v, readdir as x, components as y };
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 };