asphodelos 0.0.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3
3
  import * as NodeServices from "@effect/platform-node/NodeServices";
4
- import { Console, Effect, FileSystem, Option, Schema, Stream } from "effect";
5
- import path, { resolve } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { Argument, CliError, Command, Flag } from "effect/unstable/cli";
4
+ import { Console, Effect, FileSystem, Option, Path, Ref, Stream } from "effect";
5
+ import { CliError, Command, Flag } from "effect/cli";
6
+ //#region package.json
7
+ var version = "0.3.0";
8
+ var description = "Asphodelos is a code generator from OpenAPI to Elysia";
9
+ //#endregion
8
10
  //#region src/cli/index.ts
9
11
  const COMMAND_NAME = "asphodelos";
10
12
  /** Config file `asphodelos` picks up from the working directory when `--config` is omitted. */
@@ -15,137 +17,211 @@ const INPUT_EXTENSIONS = [
15
17
  ".json",
16
18
  ".tsp"
17
19
  ];
18
- const DocumentPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals(INPUT_EXTENSIONS)])), { message: "an OpenAPI (.yaml, .json) or TypeSpec (.tsp) document" }));
19
- const TypeScriptPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.TemplateLiteral([Schema.String, ".ts"])), { message: "a TypeScript file path ending in .ts" }));
20
20
  /**
21
21
  * The command line itself: what `asphodelos` accepts, what each piece means, and the schema every
22
22
  * value is decoded through before {@link generate} ever sees it.
23
23
  */
24
24
  const commandLine = {
25
- input: Argument.file("input", { mustExist: true }).pipe(Argument.withSchema(DocumentPathSchema), Argument.withDescription("OpenAPI (.yaml, .json) or TypeSpec (.tsp) document to generate from"), Argument.withMetavar("input.{yaml,json,tsp}"), Argument.optional),
26
- output: Flag.string("output").pipe(Flag.withAlias("o"), Flag.withSchema(TypeScriptPathSchema), Flag.withDescription("TypeScript file the generated app is written to"), Flag.withMetavar("output.ts"), Flag.optional),
27
- config: Flag.file("config", { mustExist: true }).pipe(Flag.withAlias("c"), Flag.withDescription(`Config file to run (default: ./${DEFAULT_CONFIG_FILE})`), Flag.withMetavar("file"), Flag.optional),
28
- watch: Flag.boolean("watch").pipe(Flag.withAlias("w"), Flag.withDescription("Rerun the config on every change to its documents or itself"), Flag.withDefault(false))
25
+ config: Flag.File("config", { mustExist: true }).pipe(Flag.withAlias("c"), Flag.withDescription(`Config file to run (default: ./${DEFAULT_CONFIG_FILE})`), Flag.withMetavar("file"), Flag.optional),
26
+ watch: Flag.Boolean("watch").pipe(Flag.withAlias("w"), Flag.withDescription("Rerun the config on every change to its documents or itself"), Flag.withDefault(false))
29
27
  };
30
28
  /**
31
- * One pass over a config file: read it, parse the document it names, and run every generator it
32
- * opts into.
33
- *
34
- * `reload` is for the passes after the first, where the config file may have been edited since it
35
- * was imported.
29
+ * Reads a config file.
36
30
  *
37
- * The generator pipeline pulls in the OpenAPI parser, the TypeSpec compiler and ts-morph.
38
- * `--help`, `--version`, `--completions` and every rejected command line must not pay for that,
39
- * so it is loaded here rather than at module scope. After the first pass the loader answers from
40
- * cache, so a watch tick pays nothing.
31
+ * The config module is loaded here rather than at module scope, with the rest of the pipeline:
32
+ * `--help`, `--version`, `--completions` and every rejected command line must not pay for the
33
+ * OpenAPI parser, the TypeSpec compiler and ts-morph. After the first pass the loader answers
34
+ * from cache, so a watch tick pays nothing.
41
35
  */
42
- function runConfigPass(configPath, reload) {
36
+ function loadConfig(configPath, reload) {
43
37
  return Effect.gen(function* () {
44
- const [{ readConfig }, { parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob }] = yield* Effect.promise(() => Promise.all([
45
- import("./index.mjs"),
46
- import("./openapi-B4aAnx4P.mjs").then((n) => n.t),
38
+ const { readConfig } = yield* Effect.promise(() => import("./index.mjs"));
39
+ return yield* readConfig(configPath, reload);
40
+ });
41
+ }
42
+ /** Parses the document a config names and runs every generator the config opts into. */
43
+ function runJobs(config) {
44
+ return Effect.gen(function* () {
45
+ const [{ parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob }] = yield* Effect.promise(() => Promise.all([
46
+ import("./openapi-C8b6Ibiu.mjs").then((n) => n.t),
47
47
  import("./format-B0W7HIAg.mjs").then((n) => n.r),
48
- import("./shared-CrbXsFUJ.mjs").then((n) => n.a)
48
+ import("./shared-Becl66EY.mjs").then((n) => n.s)
49
49
  ]));
50
- const config = yield* readConfig(configPath, reload);
51
50
  const jobs = makeJob(yield* parseOpenAPI(config.input), config);
52
51
  yield* cleanSplitOutputs(jobs);
52
+ return (yield* Effect.forEach(jobs, (job) => job.run(job.output), { concurrency: "unbounded" }).pipe(Effect.provideService(FormatOptions, config.format ?? {}))).filter((message) => message !== "").join("\n");
53
+ });
54
+ }
55
+ /** One pass over a config file: read it, then {@link runJobs}. */
56
+ function runConfigPass(configPath, reload) {
57
+ return Effect.gen(function* () {
58
+ const config = yield* loadConfig(configPath, reload);
53
59
  return {
54
60
  config,
55
- report: (yield* Effect.all(jobs.map((job) => job.run(job.output)), { concurrency: "unbounded" }).pipe(Effect.provideService(FormatOptions, config.format ?? {}))).filter((message) => message !== "").join("\n")
61
+ report: yield* runJobs(config)
56
62
  };
57
63
  });
58
64
  }
65
+ function isSameTarget(left, right) {
66
+ return left?.inputDirectory === right?.inputDirectory && left?.outside.join("\n") === right?.outside.join("\n");
67
+ }
59
68
  /**
60
- * A pass whose failure is printed rather than raised, so the watch loop survives it, and which
61
- * answers with the input directory the config now names.
69
+ * Generates from a config that was read, and answers what to watch for its documents.
62
70
  *
63
- * `undefined` means the pass did not get far enough to say — the config is missing, will not
64
- * import, or does not validate. The loop keeps watching the config either way.
71
+ * The directory comes from the config alone, so a pass that fails here — a document that does
72
+ * not parse, say — still names it. Otherwise the very edit that fixes the document would never
73
+ * be seen.
74
+ *
75
+ * The files outside the directory come from the document, and a broken document cannot list
76
+ * them. `previous` is what stands in then: the fix may well belong in one of the files the last
77
+ * readable version pointed at.
65
78
  */
66
- function reportConfigPass(configPath, reload) {
79
+ function reportJobs(config, previous) {
67
80
  return Effect.gen(function* () {
68
- const result = yield* Effect.result(runConfigPass(configPath, reload));
69
- if (result._tag === "Failure") {
70
- yield* Console.error(`❌ ${result.failure.message}`);
71
- return;
72
- }
73
- yield* Console.log(result.success.report);
74
- return path.dirname(resolve(process.cwd(), result.success.config.input));
81
+ const path = yield* Path.Path;
82
+ yield* runJobs(config).pipe(Effect.matchEffect({
83
+ onFailure: (error) => Console.error(`❌ ${error.message}`),
84
+ onSuccess: (report) => Console.log(report)
85
+ }));
86
+ const { outsideSources } = yield* Effect.promise(() => import("./shared-Becl66EY.mjs").then((n) => n.s));
87
+ const inputDirectory = path.dirname(path.resolve(config.input));
88
+ return {
89
+ inputDirectory,
90
+ outside: yield* outsideSources(config.input).pipe(Effect.orElseSucceed(() => previous?.inputDirectory === inputDirectory ? previous.outside : []))
91
+ };
75
92
  });
76
93
  }
77
94
  /**
78
- * Waits for the first change worth regenerating for.
95
+ * Runs one pass and answers what to watch for the documents.
79
96
  *
80
- * `runHead` is what ends the wait: it takes the first change that survives the filter and the
81
- * debounce, then tears the stream down, so the next round can watch wherever the reloaded config
82
- * points. Changes are debounced because one save is several filesystem events — an editor writes,
83
- * renames and touches — and a round per event would race itself.
97
+ * Two separate things happen to the document here. `runJobs` generates from it, reading it the
98
+ * way every other mode does. `outsideSources` then only asks which files it was read from, so
99
+ * that an edit to any of them brings the session back to this function; what it answers never
100
+ * reaches a generator.
84
101
  *
85
- * `WatchEvent.path` is relative to the directory it came from, which is why each stream is
86
- * filtered after being resolved back to an absolute path.
102
+ * The answer is `undefined` only when the config itself could not be read.
87
103
  */
88
- function awaitChange(configPath, inputDirectory) {
104
+ function reportConfigPass(configPath, reload, previous) {
105
+ return loadConfig(configPath, reload).pipe(Effect.matchEffect({
106
+ onFailure: (error) => Console.error(`❌ ${error.message}`).pipe(Effect.as(void 0)),
107
+ onSuccess: (config) => reportJobs(config, previous)
108
+ }));
109
+ }
110
+ /**
111
+ * `directory`, or the closest directory above it that exists.
112
+ *
113
+ * A directory that is not there cannot be watched, but the one it will appear in can.
114
+ */
115
+ function nearestExisting(directory) {
89
116
  return Effect.gen(function* () {
90
117
  const fs = yield* FileSystem.FileSystem;
91
- const stream = [path.dirname(configPath), ...inputDirectory === void 0 ? [] : [inputDirectory]].filter((directory, index, all) => all.indexOf(directory) === index).map((directory) => Stream.map(fs.watch(directory), (event) => path.resolve(directory, event.path))).reduce((merged, next) => Stream.merge(merged, next));
92
- yield* Stream.runHead(Stream.debounce(Stream.filter(stream, (changed) => changed === configPath || INPUT_EXTENSIONS.some((extension) => changed.endsWith(extension))), "200 millis"));
118
+ const path = yield* Path.Path;
119
+ const exists = yield* fs.exists(directory).pipe(Effect.orElseSucceed(() => false));
120
+ const parent = path.dirname(directory);
121
+ return exists || parent === directory ? directory : yield* nearestExisting(parent);
93
122
  });
94
123
  }
95
124
  /**
96
- * Regenerates on every change to the input documents or the config, until interrupted.
125
+ * One pass inside a round; answers whether the round's watchers are still the right ones.
126
+ */
127
+ function watchPass(configPath, target, watched, nextTarget) {
128
+ return Effect.gen(function* () {
129
+ const next = (yield* reportConfigPass(configPath, true, target)) ?? target;
130
+ yield* Ref.set(nextTarget, next);
131
+ if (!isSameTarget(next, target)) return false;
132
+ return next === void 0 || (yield* nearestExisting(next.inputDirectory)) === watched;
133
+ });
134
+ }
135
+ /**
136
+ * The edits to the files a document reads from outside its own directory.
97
137
  *
98
- * Two things can invalidate the output, so both are watched: the config file, and the directory
99
- * the document it names lives in — a TypeSpec entry imports its siblings and a `$ref` can point
100
- * at one, so the file named by `input` is rarely the only one that matters. The config file is
101
- * watched through its directory rather than directly, so an editor that saves by renaming does
102
- * not take the watcher down with it.
138
+ * Each one is watched through the directory it sits in, which is how an editor's
139
+ * write-then-rename save is still seen. A directory that is not there is skipped rather than
140
+ * failed on: the pass that follows reports the missing file in its own words.
141
+ */
142
+ function outsideEvents(outside) {
143
+ return Effect.gen(function* () {
144
+ const fs = yield* FileSystem.FileSystem;
145
+ const path = yield* Path.Path;
146
+ const directories = [...new Set(outside.map((file) => path.dirname(file)))];
147
+ const present = yield* Effect.forEach(directories, (directory) => fs.exists(directory).pipe(Effect.orElseSucceed(() => false)), { concurrency: "unbounded" });
148
+ return directories.filter((_, index) => present[index]).map((directory) => fs.watch(directory).pipe(Stream.filter((event) => outside.includes(path.join(directory, event.path)))));
149
+ });
150
+ }
151
+ /**
152
+ * Watches until what has to be watched changes, and answers the next target.
103
153
  *
104
- * Recursive rather than a loop because the directory to watch comes from the config, and the
105
- * config is re-read every round: an edit that repoints `input` elsewhere has to move the watcher
106
- * with it, which means new streams rather than new values.
154
+ * `watched` is where the watcher for the input directory actually sits. It is that directory
155
+ * while it exists; once it is removed — or before it is created — it is the closest directory
156
+ * above, and the only event that matters there is the missing path coming into being. A watcher
157
+ * left on a removed directory reports nothing, even after the directory is back, so the round
158
+ * ends whenever `watched` stops being the right place.
159
+ *
160
+ * Changes are debounced because one save is several filesystem events — an editor writes,
161
+ * renames and touches — and a round per event would race itself.
162
+ */
163
+ function watchRound(configPath, target, watched) {
164
+ return Effect.gen(function* () {
165
+ const fs = yield* FileSystem.FileSystem;
166
+ const path = yield* Path.Path;
167
+ const configFile = path.basename(configPath);
168
+ const nextTarget = yield* Ref.make(target);
169
+ const configEvents = fs.watch(path.dirname(configPath)).pipe(Stream.filter((event) => event.path === configFile));
170
+ const inputEvents = target === void 0 || watched === void 0 ? [] : [watched === target.inputDirectory ? fs.watch(target.inputDirectory, { recursive: true }).pipe(Stream.filter((event) => INPUT_EXTENSIONS.some((extension) => event.path.endsWith(extension)))) : fs.watch(watched).pipe(Stream.filter((event) => event.path === path.relative(watched, target.inputDirectory).split(path.sep)[0]))];
171
+ yield* Stream.mergeAll([
172
+ configEvents,
173
+ ...inputEvents,
174
+ ...yield* outsideEvents(target?.outside ?? [])
175
+ ], { concurrency: "unbounded" }).pipe(Stream.debounce("200 millis"), Stream.runForEachWhile(() => watchPass(configPath, target, watched, nextTarget)));
176
+ return yield* Ref.get(nextTarget);
177
+ });
178
+ }
179
+ /**
180
+ * Announces what a round watches, runs it, and leaves the next target in `current`.
107
181
  */
108
- function watchConfig(configPath, inputDirectory) {
182
+ function watchCycle(configPath, current) {
109
183
  return Effect.gen(function* () {
110
- yield* Console.log(inputDirectory === void 0 ? `\n👀 Watching ${configPath} — Ctrl-C to stop` : `\n👀 Watching ${inputDirectory} and ${configPath} — Ctrl-C to stop`);
111
- yield* awaitChange(configPath, inputDirectory);
112
- return yield* watchConfig(configPath, yield* reportConfigPass(configPath, true));
184
+ const target = yield* Ref.get(current);
185
+ const watched = target === void 0 ? void 0 : yield* nearestExisting(target.inputDirectory);
186
+ const documents = [target?.inputDirectory, ...target?.outside ?? []].filter((entry) => entry !== void 0).join(", ");
187
+ yield* Console.log(target === void 0 ? `\n👀 Watching ${configPath} — Ctrl-C to stop` : watched === target.inputDirectory ? `\n👀 Watching ${documents} and ${configPath} — Ctrl-C to stop` : `\n👀 Watching ${configPath}, waiting for ${target.inputDirectory} — Ctrl-C to stop`);
188
+ yield* Ref.set(current, yield* watchRound(configPath, target, watched));
113
189
  });
114
190
  }
115
191
  /**
116
- * Everything the command does once the command line has parsed.
192
+ * Regenerates on every change to the input documents or the config, until interrupted.
117
193
  *
118
- * It resolves to one of two modes and nothing else: an `<input>` with an `-o` writes a single app
119
- * from a single document, and anything else runs a config file — which is what opts in the
120
- * components, eden, types, test, mock and client-hook generators. `--config` and `<input>` are
121
- * mutually exclusive, and each of `<input>` / `--output` is meaningless without the other.
194
+ * Two things can invalidate the output, so both are watched: the config file, and the documents
195
+ * it names — the whole directory the entry document sits in, since a TypeSpec entry imports its
196
+ * siblings and a `$ref` can point at one, plus every file referenced from outside it. The config
197
+ * is re-read every round, so an edit that points `input` somewhere else moves the watcher with it.
198
+ */
199
+ function watchConfig(configPath, target) {
200
+ return Effect.gen(function* () {
201
+ const current = yield* Ref.make(target);
202
+ return yield* Effect.forever(watchCycle(configPath, current));
203
+ });
204
+ }
205
+ /**
206
+ * Everything the command does once the command line has parsed.
122
207
  *
123
- * Everything past the guard clauses fails with something carrying a `message`, so the single
124
- * `mapError` at the end is where all of it turns into rendered CLI output.
208
+ * The command runs a config file — the one `--config` names, or `asphodelos.config.ts` in the
209
+ * working directory — once, or under `--watch` on every change. Everything past the first line
210
+ * fails with something carrying a `message`, so the single `mapError` at the end is where all of
211
+ * it turns into rendered CLI output.
125
212
  */
126
213
  function generate(args) {
127
214
  return Effect.gen(function* () {
128
- const input = Option.getOrUndefined(args.input);
129
- const output = Option.getOrUndefined(args.output);
130
215
  const configPath = Option.getOrUndefined(args.config);
131
- const reject = (message) => new CliError.ShowHelp({
216
+ const resolvedConfig = configPath ?? DEFAULT_CONFIG_FILE;
217
+ if (args.watch) return yield* watchConfig(resolvedConfig, yield* reportConfigPass(resolvedConfig, false, void 0));
218
+ const first = yield* runConfigPass(resolvedConfig, false).pipe(Effect.catchTag("ConfigError", (error) => Effect.fail(configPath === void 0 && error.notFound === true ? new CliError.ShowHelp({
132
219
  commandPath: [COMMAND_NAME],
133
220
  errors: [new CliError.UserError({
134
- cause: new Error(message),
135
- userMessage: message
221
+ cause: error,
222
+ userMessage: error.message
136
223
  })]
137
- });
138
- if (configPath !== void 0 && (input !== void 0 || output !== void 0)) return yield* reject("--config cannot be combined with <input> or --output. A config file already names its own input and outputs.");
139
- if (input !== void 0 && output === void 0) return yield* reject("<input> requires -o <output.ts>.");
140
- if (output !== void 0 && input === void 0) return yield* reject("-o <output.ts> requires an <input> document.");
141
- if (args.watch && (input !== void 0 || output !== void 0)) return yield* reject("--watch runs a config file, so it cannot be combined with <input> or --output.");
142
- if (input !== void 0 && output !== void 0) {
143
- const [{ parseOpenAPI }, { elysia }] = yield* Effect.promise(() => Promise.all([import("./openapi-B4aAnx4P.mjs").then((n) => n.t), import("./core-DS3sAabb.mjs").then((n) => n.t)]));
144
- return yield* Console.log(yield* elysia(yield* parseOpenAPI(input), { output }));
145
- }
146
- const resolvedConfig = configPath ?? DEFAULT_CONFIG_FILE;
147
- if (args.watch) return yield* watchConfig(resolve(process.cwd(), resolvedConfig), yield* reportConfigPass(resolvedConfig, false));
148
- const first = yield* runConfigPass(resolvedConfig, false).pipe(Effect.mapError((error) => configPath === void 0 && error._tag === "ConfigError" && error.notFound === true ? reject(error.message) : error));
224
+ }) : error)));
149
225
  yield* Console.log(first.report);
150
226
  }).pipe(Effect.mapError((error) => CliError.isCliError(error) ? error : new CliError.UserError({
151
227
  cause: error,
@@ -154,46 +230,35 @@ function generate(args) {
154
230
  }
155
231
  /**
156
232
  * The `asphodelos` command: parsing, validation, `--help`, `--version` and shell completions are
157
- * owned by `effect/unstable/cli`, {@link generate} is the rest.
233
+ * owned by `effect/cli`, {@link generate} is the rest.
158
234
  */
159
- const cli = Command.make(COMMAND_NAME, commandLine, generate).pipe(Command.withDescription("Generate Elysia code from OpenAPI or TypeSpec"), Command.withExamples([
160
- {
161
- command: "asphodelos openapi.yaml -o src/index.ts",
162
- description: "Generate a single app from one document"
163
- },
164
- {
165
- command: "asphodelos",
166
- description: `Run every generator declared in ./${DEFAULT_CONFIG_FILE}`
167
- },
168
- {
169
- command: "asphodelos --config config/api.config.ts",
170
- description: "Run a config file from another location"
171
- },
172
- {
173
- command: "asphodelos --watch",
174
- description: "Rerun on every change to the input documents or the config"
175
- }
176
- ]));
235
+ function makeCli() {
236
+ return Command.make(COMMAND_NAME, commandLine, generate).pipe(Command.withDescription(description), Command.withExamples([
237
+ {
238
+ command: "asphodelos",
239
+ description: `Run every generator declared in ./${DEFAULT_CONFIG_FILE}`
240
+ },
241
+ {
242
+ command: "asphodelos --config config/api.config.ts",
243
+ description: "Run a config file from another location"
244
+ },
245
+ {
246
+ command: "asphodelos --watch",
247
+ description: "Rerun on every change to the input documents or the config"
248
+ }
249
+ ]));
250
+ }
177
251
  /**
178
- * Runs `asphodelos` against an argument list.
252
+ * Runs `asphodelos` against the arguments of the process.
179
253
  *
180
- * `entryUrl` is the `import.meta.url` of the executable, and `--version` is read from the
181
- * `package.json` next to it rather than baked in, so the two can never disagree.
254
+ * `--version` is read from the package manifest rather than baked in, so the two can never
255
+ * disagree.
182
256
  */
183
- function asphodelos(argv, entryUrl) {
184
- return Effect.gen(function* () {
185
- const manifestPath = fileURLToPath(new URL("../package.json", entryUrl));
186
- const source = yield* (yield* FileSystem.FileSystem).readFileString(manifestPath);
187
- const manifest = yield* Effect.try({
188
- try: () => JSON.parse(source),
189
- catch: (cause) => new Error(`${manifestPath} is not valid JSON`, { cause })
190
- });
191
- const { version } = yield* Schema.decodeUnknownEffect(Schema.Struct({ version: Schema.String }))(manifest);
192
- return yield* Command.runWith(cli, { version })(argv);
193
- });
257
+ function asphodelos() {
258
+ return Command.run(makeCli(), { version });
194
259
  }
195
260
  //#endregion
196
261
  //#region src/index.ts
197
- NodeRuntime.runMain(asphodelos(process.argv.slice(2), import.meta.url).pipe(Effect.provide(NodeServices.layer)));
262
+ NodeRuntime.runMain(asphodelos().pipe(Effect.provide(NodeServices.layer)));
198
263
  //#endregion
199
264
  export {};