asphodelos 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -233,25 +233,33 @@ import { treaty } from '@elysiajs/eden'
233
233
 
234
234
  import type { app } from '../index'
235
235
 
236
- const origin = import.meta.env.VITE_API_URL!
236
+ function normalizeOrigin(origin: string) {
237
+ if (!origin) return origin
238
+ const url = origin.includes('://')
239
+ ? origin
240
+ : `${['localhost', '127.0.0.1', '0.0.0.0'].some((host) => origin.includes(host)) ? 'http' : 'https'}://${origin}`
241
+ return url.endsWith('/') ? url.slice(0, -1) : url
242
+ }
243
+
244
+ export const clientOrigin = normalizeOrigin(import.meta.env.VITE_API_URL!)
237
245
 
238
- export const client = treaty<typeof app>(origin)
246
+ export const client = treaty<typeof app>(clientOrigin)
239
247
  ```
240
248
 
241
249
  `source: 'process.env'` reads `process.env` instead, for code Node.js or Bun runs:
242
250
 
243
251
  ```ts
244
252
  client: { output: 'src/lib/client.ts', baseUrl: { env: 'API_URL', source: 'process.env' } }
245
- // const origin = process.env.API_URL!
253
+ // export const clientOrigin = normalizeOrigin(process.env.API_URL!)
246
254
  ```
247
255
 
248
- A value a module exports is used as written — `value` is the export followed by what is read
249
- from it, and the module answers for it being there:
256
+ A URL a module exports is read as written — `value` is the export followed by what is read from
257
+ it, a string, and the module answers for it being there:
250
258
 
251
259
  ```ts
252
260
  client: { output: 'src/lib/client.ts', baseUrl: { import: '@/env', value: 'env.API_URL' } }
253
261
  // import { env } from '@/env'
254
- // const origin = env.API_URL
262
+ // export const clientOrigin = normalizeOrigin(env.API_URL)
255
263
  ```
256
264
 
257
265
  `sameOrigin: true` is for an app a host framework such as TanStack Start or Next.js serves beside
@@ -261,9 +269,17 @@ DOM lib.
261
269
 
262
270
  ```ts
263
271
  client: { output: 'src/lib/client.ts', baseUrl: { env: 'API_URL', source: 'process.env' }, sameOrigin: true }
264
- // const origin = typeof window === 'undefined' ? process.env.API_URL! : window.location.origin
272
+ // export const clientOrigin = normalizeOrigin(
273
+ // typeof window === 'undefined' ? process.env.API_URL! : window.location.origin,
274
+ // )
265
275
  ```
266
276
 
277
+ `normalizeOrigin` reads the origin the way treaty does: it adds `http://` for a local host or
278
+ `https://` otherwise when there is no scheme, and drops a trailing `/`. The result is exported as
279
+ `clientOrigin`: the hooks of a path Eden cannot type — a segment with a `.` or a partial parameter,
280
+ such as `/widget.json` — call `fetch` with it, so they send where the client does. A package
281
+ entry that `client.package` names exports `clientOrigin` beside `client`.
282
+
267
283
  The `index.ts` beside the client re-exports it, so it is imported as `./lib` — by `eden`, by the
268
284
  hooks, and by your own code:
269
285
 
package/dist/cli.mjs CHANGED
@@ -4,7 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
4
4
  import { Console, Effect, FileSystem, Option, Path, Ref, Stream } from "effect";
5
5
  import { CliError, Command, Flag } from "effect/cli";
6
6
  // package.json
7
- var version = "0.4.0";
7
+ var version = "0.5.0";
8
8
  var description = "Asphodelos is a code generator from OpenAPI to Elysia";
9
9
  // src/cli/index.ts
10
10
  const COMMAND_NAME = "asphodelos";
@@ -48,7 +48,7 @@ function runJobs(config) {
48
48
  const [{ parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob }] = yield* Effect.promise(() => Promise.all([
49
49
  import("./openapi-4yNuDK_n.mjs").then((n) => n.t),
50
50
  import("./format-DC258z--.mjs").then((n) => n.r),
51
- import("./shared-27xlBR7-.mjs").then((n) => n.s)
51
+ import("./shared-Bb1qvBpw.mjs").then((n) => n.s)
52
52
  ]));
53
53
  const jobs = makeJob(yield* parseOpenAPI(config.input), config);
54
54
  yield* cleanSplitOutputs(jobs);
@@ -86,7 +86,7 @@ function reportJobs(config, previous) {
86
86
  onFailure: (error) => Console.error(`❌ ${error.message}`),
87
87
  onSuccess: (report) => Console.log(report)
88
88
  }));
89
- const { outsideSources } = yield* Effect.promise(() => import("./shared-27xlBR7-.mjs").then((n) => n.s));
89
+ const { outsideSources } = yield* Effect.promise(() => import("./shared-Bb1qvBpw.mjs").then((n) => n.s));
90
90
  const inputDirectory = path.dirname(path.resolve(config.input));
91
91
  return {
92
92
  inputDirectory,
package/dist/index.mjs CHANGED
@@ -171,7 +171,7 @@ const BaseUrlSchema = Schema.Union([Schema.Struct({
171
171
  }),
172
172
  value: Schema.String.check(Schema.isPattern(/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u, { message: "must be an export of the module, with the property read from it: `env.API_URL`" })).annotate({
173
173
  title: "Value",
174
- description: "The expression the client is created with, as it is written: the export of `import` followed by the property read from it. `env.API_URL` imports `env` and reads `env.API_URL`; `apiUrl` imports and uses `apiUrl` itself.",
174
+ description: "The expression the client is created with, as it is written: the export of `import` followed by the property read from it, a URL string. `env.API_URL` imports `env` and reads `env.API_URL`; `apiUrl` imports and uses `apiUrl` itself.",
175
175
  examples: ["env.API_URL", "apiUrl"]
176
176
  })
177
177
  }), Schema.Struct({
@@ -205,7 +205,7 @@ const ClientOutputSchema = Schema.Struct({
205
205
  import: removed("import was removed: a client in another package imports the app by the top-level `package`, the name the app entry is published as. Delete the import and set package."),
206
206
  package: Schema.optionalKey(ImportSchema.annotate({
207
207
  title: "Package name",
208
- description: "The name the generated files in other packages import the client by — the package it is published as, whose entry is the client or its barrel. Files in the client's own package import it relatively or through the alias. Left out, a file outside that package is refused.",
208
+ description: "The name the generated files in other packages import the client by — the package it is published as, whose entry is the client or its barrel, exporting `client` and `clientOrigin`. Files in the client's own package import it relatively or through the alias. Left out, a file outside that package is refused.",
209
209
  examples: ["@packages/client"]
210
210
  })),
211
211
  baseUrl: BaseUrlSchema,
@@ -66,15 +66,44 @@ function emit(code, dir, output) {
66
66
  }
67
67
  // src/core/client/index.ts
68
68
  /**
69
+ * Treaty reads its origin this way before it appends a path: a scheme is added when there is
70
+ * none — `http://` for a local host, `https://` otherwise — and a trailing `/` is dropped. The
71
+ * origin is exported as treaty reads it, so a hook that calls `fetch` with it sends where the
72
+ * client does. A missing origin is passed on as it is, so importing the client still succeeds
73
+ * where the variable is unset and only a request fails, as it did before.
74
+ */
75
+ const NORMALIZE = `function normalizeOrigin(origin: string) {
76
+ if (!origin) return origin
77
+ const url = origin.includes('://')
78
+ ? origin
79
+ : \`\${['localhost', '127.0.0.1', '0.0.0.0'].some((host) => origin.includes(host)) ? 'http' : 'https'}://\${origin}\`
80
+ return url.endsWith('/') ? url.slice(0, -1) : url
81
+ }`;
82
+ /** The names the client file declares itself; an export of the same name is imported under an alias. */
83
+ const DECLARED = /* @__PURE__ */ new Set([
84
+ "treaty",
85
+ "app",
86
+ "client",
87
+ "clientOrigin",
88
+ "normalizeOrigin"
89
+ ]);
90
+ function importCode(baseUrl) {
91
+ const [name = "", ...rest] = baseUrl.value.split(".");
92
+ if (!DECLARED.has(name)) return [[`import { ${name} } from '${baseUrl.import}'`], baseUrl.value];
93
+ const alias = "baseUrl";
94
+ return [[`import { ${name} as ${alias} } from '${baseUrl.import}'`], [alias, ...rest].join(".")];
95
+ }
96
+ /**
69
97
  * The base URL as code: an environment variable, read where it is used and asserted to be set —
70
98
  * with `sameOrigin`, only without a window, so a browser bundle that has no such variable never
71
- * reads it — or a value a module exports, used as written. Never a URL in the file.
99
+ * reads it — or a URL string a module exports, read as written. Never a URL in the file.
72
100
  */
73
101
  function baseUrlCode(baseUrl, sameOrigin) {
74
- const [imports, expression] = "import" in baseUrl ? [[`import { ${String(baseUrl.value.split(".")[0])} } from '${baseUrl.import}'`], baseUrl.value] : [[], `${baseUrl.source}.${baseUrl.env}!`];
102
+ const [imports, expression] = "import" in baseUrl ? importCode(baseUrl) : [[], `${baseUrl.source}.${baseUrl.env}!`];
103
+ const value = sameOrigin ? `typeof window === 'undefined' ? ${expression} : window.location.origin` : expression;
75
104
  return {
76
105
  imports,
77
- origin: sameOrigin ? `const origin = typeof window === 'undefined' ? ${expression} : window.location.origin` : `const origin = ${expression}`
106
+ origin: `${NORMALIZE}\n\nexport const clientOrigin = normalizeOrigin(${value})`
78
107
  };
79
108
  }
80
109
  /**
@@ -85,7 +114,9 @@ function baseUrlCode(baseUrl, sameOrigin) {
85
114
  * browser bundle could pull the server in. `treaty` wants an origin — a relative path is read as
86
115
  * a host — so with `sameOrigin` the browser is given its own, `window.location.origin`, and
87
116
  * `baseUrl` serves the code that runs without a window. Either way the origin is a `const` of
88
- * its own, so what the client is created with is read off one line.
117
+ * its own, `clientOrigin`, read the way treaty reads it, so what the client is created with is
118
+ * read off one declaration. It is exported beside the client: the hooks of a path Eden cannot
119
+ * type call `fetch` with it.
89
120
  */
90
121
  function client(output, options) {
91
122
  return Effect.gen(function* () {
@@ -94,7 +125,7 @@ function client(output, options) {
94
125
  ["import { treaty } from '@elysiajs/eden'", ...imports].join("\n"),
95
126
  `import type { app } from '${options.appImport}'`,
96
127
  origin,
97
- "export const client = treaty<typeof app>(origin)"
128
+ "export const client = treaty<typeof app>(clientOrigin)"
98
129
  ].join("\n\n")}\n`, path.dirname(output), output);
99
130
  if (options.barrel !== void 0) {
100
131
  const line = `export * from './${path.basename(output, ".ts")}'`;
@@ -2766,24 +2797,29 @@ function edenTarget(fullPath, method, operation, client) {
2766
2797
  ...withBody ? { bodyType: `${argsType}[0]` } : {},
2767
2798
  bodyRequired: operation.requestBody !== void 0,
2768
2799
  queryBody: (exprs, options, signal) => `const{data,error}=await ${call(exprs)}(${signal ? `{...${options},fetch:{...${options}${access}fetch,signal}}` : options});if(error)throw error;return data`,
2769
- mutationBody: (exprs, body, options) => `const{data,error}=await ${call(exprs)}(${withBody ? `${body},${options}` : options});if(error)throw error;return data`
2800
+ mutationBody: (exprs, body, options) => `const{data,error}=await ${call(exprs)}(${withBody ? `${body},${options}` : options});if(error)throw error;return data`,
2801
+ usesFetch: false
2770
2802
  };
2771
2803
  }
2804
+ /** The origin the client module exports beside the client, which a `fetch` fallback's URL starts at. */
2805
+ const ORIGIN = "clientOrigin";
2772
2806
  function fetchTarget(fullPath, method, operation) {
2773
2807
  const names = pathParamNames(fullPath);
2808
+ const params = names.map((_, index) => index === 0 ? "params" : `params${index + 1}`);
2774
2809
  const hasQuery = (operation.parameters ?? []).some((p) => "in" in p && p.in === "query");
2775
2810
  const optionsType = hasQuery ? "{ headers?: Record<string, string>; query?: Record<string, unknown> }" : "{ headers?: Record<string, string> }";
2776
2811
  const withBody = isBodyMethod(method);
2777
2812
  const { dataT, importName } = successType(operation);
2778
2813
  const url = (exprs) => {
2779
2814
  const inner = fullPath.replaceAll(/\{([^}]+)\}/gu, (_, n) => {
2780
- return `\${encodeURIComponent(${exprs[names.indexOf(n)] ?? n})}`;
2815
+ const index = names.indexOf(n);
2816
+ return `\${encodeURIComponent(${exprs[index] ?? params[index]})}`;
2781
2817
  });
2782
- return hasQuery ? `\`${inner}\${search.size ? \`?\${search}\` : ''}\`` : `\`${inner}\``;
2818
+ return hasQuery ? `\`\${${ORIGIN}}${inner}\${search.size ? \`?\${search}\` : ''}\`` : `\`\${${ORIGIN}}${inner}\``;
2783
2819
  };
2784
2820
  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))}}` : "";
2785
2821
  return {
2786
- params: names.map((name) => ({
2822
+ params: params.map((name) => ({
2787
2823
  name,
2788
2824
  type: "string"
2789
2825
  })),
@@ -2797,7 +2833,8 @@ function fetchTarget(fullPath, method, operation) {
2797
2833
  bodyRequired: false,
2798
2834
  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())`,
2799
2835
  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())`,
2800
- ...importName ? { fetchType: importName } : {}
2836
+ ...importName ? { fetchType: importName } : {},
2837
+ usesFetch: true
2801
2838
  };
2802
2839
  }
2803
2840
  function queryNames(config, method, pathStr) {
@@ -3093,16 +3130,18 @@ function operationCode(config, pathStr, fullPath, method, operation, client) {
3093
3130
  const names = queryNames(config, method, pathStr);
3094
3131
  return {
3095
3132
  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"),
3096
- fetchType: target.fetchType
3133
+ fetchType: target.fetchType,
3134
+ usesFetch: target.usesFetch
3097
3135
  };
3098
3136
  }
3099
3137
  /**
3100
3138
  * The imports of a hooks file, read off the code it holds: a value and a type import from the
3101
3139
  * library, Vue's helpers when a ref is read, the response components the fetch fallbacks type
3102
- * their data by, and the client. A name is imported only when the file uses it, so a document
3103
- * with no mutation imports nothing a mutation would.
3140
+ * their data by, and the client, with its origin when a fetch fallback builds a URL from it. A
3141
+ * name is imported only when the file uses it, so a document with no mutation imports nothing a
3142
+ * mutation would.
3104
3143
  */
3105
- function headerCode(config, client, importPath, body, fetchTypes, schemasImport) {
3144
+ function headerCode(config, client, importPath, body, fetchTypes, schemasImport, usesFetch) {
3106
3145
  const calls = (name) => new RegExp(`\\b${name}\\s*[<(]`, "u").test(body);
3107
3146
  const names = (name) => new RegExp(`\\b${name}\\b`, "u").test(body);
3108
3147
  const lines = [];
@@ -3141,7 +3180,8 @@ function headerCode(config, client, importPath, body, fetchTypes, schemasImport)
3141
3180
  if (names("MaybeRefOrGetter")) lines.push("import type { MaybeRefOrGetter } from 'vue'");
3142
3181
  }
3143
3182
  if (fetchTypes.length > 0) lines.push("import type { Static } from 'elysia'", `import type { ${fetchTypes.join(", ")} } from '${schemasImport}'`);
3144
- lines.push(`import { ${client} } from '${importPath}'`);
3183
+ const clientImports = usesFetch ? [client, ORIGIN] : [client];
3184
+ lines.push(`import { ${clientImports.join(", ")} } from '${importPath}'`);
3145
3185
  return `${lines.join("\n")}\n\n`;
3146
3186
  }
3147
3187
  function makeQueryHooks(openAPI, output, importPath, config, client, basePath, schemasImport = "./components/schemas") {
@@ -3155,7 +3195,7 @@ function makeQueryHooks(openAPI, output, importPath, config, client, basePath, s
3155
3195
  }) : []);
3156
3196
  if (operations.length === 0) return "No operations found";
3157
3197
  const body = `${[...makePrefixKeyCodes(openAPI, prefix), ...operations.map((op) => op.code)].join("\n\n")}\n`;
3158
- yield* emit(`${headerCode(config, client, importPath, body, [...new Set(filterDefined(operations.map((op) => op.fetchType)))].toSorted(), schemasImport)}${body}`, path.dirname(output), output);
3198
+ yield* emit(`${headerCode(config, client, importPath, body, [...new Set(filterDefined(operations.map((op) => op.fetchType)))].toSorted(), schemasImport, operations.some((op) => op.usesFetch))}${body}`, path.dirname(output), output);
3159
3199
  return `Generated ${config.label} code written to ${output}`;
3160
3200
  });
3161
3201
  }
@@ -1,6 +1,6 @@
1
1
  import { INPUT_EXTENSIONS, parseConfig } from "../index.mjs";
2
2
  import { t as FormatOptions } from "../format-DC258z--.mjs";
3
- import { a as makeJob, c as fileSystemLayer, i as jobTargets, n as isInsideDirectory, o as outsideSources, r as isUserCodeJob, t as cleanSplitOutputs } from "../shared-27xlBR7-.mjs";
3
+ import { a as makeJob, c as fileSystemLayer, i as jobTargets, n as isInsideDirectory, o as outsideSources, r as isUserCodeJob, t as cleanSplitOutputs } from "../shared-Bb1qvBpw.mjs";
4
4
  import { n as parseOpenAPI } from "../openapi-4yNuDK_n.mjs";
5
5
  import { Effect, FileSystem, Result } from "effect";
6
6
  import path from "node:path";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asphodelos",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Asphodelos is a code generator from OpenAPI to Elysia",
5
5
  "keywords": [
6
6
  "elysia",