@loozo/angular-launch 0.0.4 → 0.0.5

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.
@@ -0,0 +1,71 @@
1
+ import { createBuilder, } from "@angular-devkit/architect";
2
+ import { generate } from "../generation/index.js";
3
+ import { message, split } from "./options.js";
4
+ const officialApplicationBuilder = "@angular/build:application";
5
+ // The conditions @angular/build 22.2's bundler uses when none are configured, chosen from the
6
+ // normalized optimization as it chooses them.
7
+ function defaultConditions(optimization = true) {
8
+ let scripts = optimization;
9
+ if (typeof optimization === "object" && optimization !== null && !Array.isArray(optimization)) {
10
+ scripts = optimization.scripts;
11
+ }
12
+ if (scripts) {
13
+ return ["module", "production"];
14
+ }
15
+ return ["module", "development"];
16
+ }
17
+ // Annotated so the emitted declaration doesn't reach into @angular-devkit/core.
18
+ const builder = createBuilder(async (options, context) => {
19
+ let stopped = false;
20
+ let acquisition;
21
+ let generation;
22
+ let cleanup;
23
+ function stop() {
24
+ stopped = true;
25
+ if (!cleanup) {
26
+ const delegateStop = acquisition?.then((run) => run.stop());
27
+ // The builder reports a failed generation itself; stopping only waits for it to settle.
28
+ const drain = generation?.catch(() => undefined);
29
+ cleanup = Promise.all([delegateStop, drain]).then(() => undefined);
30
+ }
31
+ return cleanup;
32
+ }
33
+ context.addTeardown(stop);
34
+ try {
35
+ const { launch, official } = split(options);
36
+ if (official.watch === true) {
37
+ throw new Error("The application builder runs once; it does not support watch: true");
38
+ }
39
+ // The schema's false marks an omitted conditions (scripts/builder-schemas.mjs). Omitting it
40
+ // here would reach Angular as an explicit [] again, so Angular's default list goes instead.
41
+ if (official.conditions === false) {
42
+ official.conditions = defaultConditions(official.optimization);
43
+ }
44
+ generation = generate(context.workspaceRoot, launch, () => stopped);
45
+ try {
46
+ await generation;
47
+ }
48
+ catch (error) {
49
+ // Diagnostics, ownership conflicts and check-mode drift are build failures, not crashes.
50
+ context.logger.error(message(error));
51
+ return { success: false };
52
+ }
53
+ if (stopped) {
54
+ return { success: false };
55
+ }
56
+ acquisition = context.scheduleBuilder(officialApplicationBuilder, official, {
57
+ target: context.target,
58
+ });
59
+ const run = await acquisition;
60
+ if (stopped) {
61
+ await run.stop();
62
+ return { success: false };
63
+ }
64
+ const output = await run.result;
65
+ return output;
66
+ }
67
+ finally {
68
+ await stop();
69
+ }
70
+ });
71
+ export default builder;
@@ -0,0 +1,10 @@
1
+ import { type BuilderContext } from "@angular-devkit/architect";
2
+ import type { GenerationOptions } from "../generation/index.js";
3
+ export type JsonObject = NonNullable<Parameters<BuilderContext["scheduleBuilder"]>[1]>;
4
+ export declare const applicationBuilder = "@loozo/angular-launch:application";
5
+ export declare function message(error: unknown): string;
6
+ export declare function split(options: JsonObject): {
7
+ launch: GenerationOptions;
8
+ official: JsonObject;
9
+ };
10
+ export declare function buildTargetOptions(context: BuilderContext, buildTarget: string): Promise<GenerationOptions>;
@@ -0,0 +1,64 @@
1
+ import { targetFromTargetString } from "@angular-devkit/architect";
2
+ export const applicationBuilder = "@loozo/angular-launch:application";
3
+ function validateLaunchOptions(value) {
4
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
5
+ throw new Error("Launch options must be an object");
6
+ }
7
+ for (const key of ["tsconfig", "outDirectory"]) {
8
+ const option = value[key];
9
+ if (typeof option !== "string" || option.trim() === "") {
10
+ throw new Error(`Launch option ${key} must be a nonempty string`);
11
+ }
12
+ }
13
+ const scanDirectories = value.scanDirectories;
14
+ if (!Array.isArray(scanDirectories) ||
15
+ scanDirectories.length !== 1 ||
16
+ scanDirectories.some((scan) => typeof scan !== "string" || scan.trim() === "")) {
17
+ throw new Error("scanDirectories must contain exactly one nonempty string");
18
+ }
19
+ for (const key of ["tanstackQuery", "check"]) {
20
+ if (Object.hasOwn(value, key) && typeof value[key] !== "boolean") {
21
+ throw new Error(`${key} must be a boolean`);
22
+ }
23
+ }
24
+ }
25
+ export function message(error) {
26
+ if (error instanceof Error) {
27
+ return error.message;
28
+ }
29
+ return String(error);
30
+ }
31
+ // Launch options drive generation; everything else belongs to Angular's application builder.
32
+ export function split(options) {
33
+ validateLaunchOptions(options);
34
+ const { tsconfig, scanDirectories, outDirectory, tanstackQuery, check, ...official } = options;
35
+ const launch = { tsconfig, scanDirectories, outDirectory };
36
+ if (tanstackQuery !== undefined) {
37
+ launch.tanstackQuery = tanstackQuery;
38
+ }
39
+ if (check !== undefined) {
40
+ launch.check = check;
41
+ }
42
+ return { launch, official };
43
+ }
44
+ // Launch options for serve come from its build target, resolved as Angular's dev server resolves it.
45
+ export async function buildTargetOptions(context, buildTarget) {
46
+ const project = context.target?.project;
47
+ if (!project) {
48
+ throw new Error("The serve builder must run as a project target");
49
+ }
50
+ const target = targetFromTargetString(buildTarget, project, "build");
51
+ const [builder, raw] = await Promise.all([
52
+ context.getBuilderNameForTarget(target),
53
+ context.getTargetOptions(target),
54
+ ]);
55
+ if (builder !== applicationBuilder) {
56
+ throw new Error(`buildTarget ${target.project}:${target.target} must use ${applicationBuilder}, not ${builder}`);
57
+ }
58
+ const options = await context.validateOptions(raw, builder);
59
+ const { launch } = split(options);
60
+ if (launch.check === true) {
61
+ throw new Error("Serve writes generated files; its buildTarget must not resolve check: true");
62
+ }
63
+ return launch;
64
+ }
@@ -0,0 +1,8 @@
1
+ import { type Builder } from "@angular-devkit/architect";
2
+ import { type JsonObject } from "./options.js";
3
+ type ServeOptions = JsonObject & {
4
+ buildTarget: string;
5
+ poll?: number | false;
6
+ };
7
+ declare const builder: Builder<ServeOptions>;
8
+ export default builder;
@@ -0,0 +1,248 @@
1
+ import { createBuilder, } from "@angular-devkit/architect";
2
+ import chokidar from "chokidar";
3
+ import { Observable } from "rxjs";
4
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
5
+ import { readFile, realpath } from "node:fs/promises";
6
+ import { launchMarkers } from "@loozo/angular-router/_generation";
7
+ import { createGenerationSession } from "../generation/index.js";
8
+ import { contextFiles } from "../generation/context-file.js";
9
+ import { buildTargetOptions, message } from "./options.js";
10
+ // Polling catches what Angular 22.2's native watcher (@parcel/watcher) misses: edits to files
11
+ // inside a renamed directory, which otherwise leave the dev server serving stale output.
12
+ const defaultPoll = 1000;
13
+ const devServerBuilder = "@angular/build:dev-server";
14
+ // One change can reach the watcher as a burst of events: a save of several files, or a directory
15
+ // rename, whose unlinks chokidar holds back 100 ms to pair them with re-adds. A pass waits for the
16
+ // burst to go quiet, so it runs once and reads the finished change.
17
+ const settleDelay = 150;
18
+ // Generation's own marked outputs in the scan directory; their events need no further pass. The
19
+ // output directory can't overlap the scan directory, so its files never reach the watcher. The
20
+ // router's marker isn't part of its generation seam; if this copy drifts, a write only causes one
21
+ // redundant pass, which writes nothing.
22
+ const generatedMarkers = {
23
+ "route.generated.ts": "// @loozo/angular-router routegen: owned route.generated.ts",
24
+ "rpc.generated.ts": launchMarkers["rpc.generated.ts"],
25
+ };
26
+ function contains(directory, file) {
27
+ const suffix = relative(directory, file);
28
+ return (suffix === "" || (!isAbsolute(suffix) && suffix !== ".." && !suffix.startsWith(`..${sep}`)));
29
+ }
30
+ // Annotated so the emitted declaration doesn't reach into @angular-devkit/core.
31
+ const builder = createBuilder((options, context) => new Observable((subscriber) => {
32
+ let stopped = false;
33
+ let initial = true;
34
+ let dirty = false;
35
+ let watcher;
36
+ let contextWatcher;
37
+ let session;
38
+ let acquisition;
39
+ let forwarding;
40
+ let active;
41
+ let cleanup;
42
+ let cancelReady;
43
+ let settling;
44
+ // Resolved before the watcher starts.
45
+ let scanRoot;
46
+ let watchedContext;
47
+ // The context file can live anywhere in the app's sources, and its path and contents are part
48
+ // of the generated app identity, so a watcher of its own follows wherever the last pass found
49
+ // it. A file inside the scan directory is already watched.
50
+ function followContext() {
51
+ const contextFile = contextFiles.get(session);
52
+ if (stopped || contextFile === undefined || contextFile === watchedContext) {
53
+ return;
54
+ }
55
+ const previous = contextWatcher;
56
+ contextWatcher = undefined;
57
+ watchedContext = contextFile;
58
+ void previous?.close().catch((error) => context.logger.error(String(error)));
59
+ if (contains(scanRoot, contextFile)) {
60
+ return;
61
+ }
62
+ const followed = chokidar.watch(contextFile, {
63
+ ignoreInitial: true,
64
+ followSymlinks: false,
65
+ });
66
+ contextWatcher = followed;
67
+ followed.on("error", (error) => context.logger.error(String(error)));
68
+ followed.on("all", (_event, path) => {
69
+ void changed(path).catch((error) => context.logger.error(String(error)));
70
+ });
71
+ // The pass that found this path read the context before its watch existed, so an edit since
72
+ // went unseen. Once the watch is live, one more pass reads the current text; the watch
73
+ // covers the rest.
74
+ followed.once("ready", () => {
75
+ if (stopped || contextWatcher !== followed) {
76
+ return;
77
+ }
78
+ dirty = true;
79
+ pump();
80
+ });
81
+ }
82
+ async function changed(path) {
83
+ if (stopped) {
84
+ return;
85
+ }
86
+ const marker = generatedMarkers[basename(path)];
87
+ if (marker !== undefined) {
88
+ try {
89
+ const bytes = await readFile(path, "utf8");
90
+ if (bytes.split("\n", 1)[0] === marker) {
91
+ return;
92
+ }
93
+ }
94
+ catch (error) {
95
+ if (error.code !== "ENOENT") {
96
+ throw error;
97
+ }
98
+ }
99
+ }
100
+ if (stopped) {
101
+ return;
102
+ }
103
+ clearTimeout(settling);
104
+ settling = setTimeout(() => {
105
+ settling = undefined;
106
+ dirty = true;
107
+ pump();
108
+ }, settleDelay);
109
+ }
110
+ // A failed or stopped pass leaves the session clean; the next pass starts fresh.
111
+ async function regenerate() {
112
+ try {
113
+ await session.generate(undefined, () => stopped);
114
+ }
115
+ finally {
116
+ followContext();
117
+ }
118
+ }
119
+ function stop() {
120
+ stopped = true;
121
+ dirty = false;
122
+ clearTimeout(settling);
123
+ cancelReady?.();
124
+ forwarding?.unsubscribe();
125
+ if (!cleanup) {
126
+ const close = Promise.all([watcher?.close(), contextWatcher?.close()]);
127
+ const delegateStop = acquisition?.then((run) => run.stop(), () => undefined);
128
+ const drain = active?.catch(() => undefined);
129
+ cleanup = Promise.all([close, delegateStop, drain, session?.dispose()]).then(() => undefined);
130
+ }
131
+ return cleanup;
132
+ }
133
+ context.addTeardown(stop);
134
+ function pump() {
135
+ if (stopped || initial || active || !dirty) {
136
+ return;
137
+ }
138
+ const work = (async () => {
139
+ while (dirty && !stopped) {
140
+ dirty = false;
141
+ try {
142
+ await regenerate();
143
+ }
144
+ catch (error) {
145
+ context.logger.error(message(error));
146
+ }
147
+ }
148
+ })();
149
+ active = work;
150
+ void work.finally(() => {
151
+ if (active === work) {
152
+ active = undefined;
153
+ }
154
+ // An edit between the loop's last check and finalization must not be lost.
155
+ pump();
156
+ });
157
+ }
158
+ async function start() {
159
+ const { poll = defaultPoll, ...devServer } = options;
160
+ if (poll !== false) {
161
+ devServer.poll = poll;
162
+ }
163
+ // Architect already validated the dev-server options against schemas/serve.json, Angular's
164
+ // dev-server schema with this poll. The build target is validated before the watcher and
165
+ // generation too, so invalid options never write.
166
+ const launch = await buildTargetOptions(context, options.buildTarget);
167
+ if (stopped) {
168
+ return;
169
+ }
170
+ const application = await realpath(context.workspaceRoot);
171
+ if (stopped) {
172
+ return;
173
+ }
174
+ scanRoot = resolve(dirname(resolve(application, launch.tsconfig)), launch.scanDirectories[0]);
175
+ session = createGenerationSession(context.workspaceRoot, launch);
176
+ watcher = chokidar.watch([scanRoot], { ignoreInitial: true, followSymlinks: false });
177
+ const ready = new Promise((resolveReady, rejectReady) => {
178
+ cancelReady = () => resolveReady(false);
179
+ watcher.once("ready", () => resolveReady(true));
180
+ watcher.on("error", (error) => {
181
+ if (initial) {
182
+ rejectReady(error);
183
+ }
184
+ else {
185
+ context.logger.error(String(error));
186
+ }
187
+ });
188
+ watcher.on("all", (_event, path) => {
189
+ void changed(path).catch((error) => context.logger.error(String(error)));
190
+ });
191
+ });
192
+ const readyForGeneration = await ready;
193
+ if (stopped || !readyForGeneration) {
194
+ return;
195
+ }
196
+ dirty = false;
197
+ const generation = regenerate();
198
+ active = generation;
199
+ try {
200
+ await generation;
201
+ }
202
+ catch (error) {
203
+ // The dev server never starts on a failed initial generation; report it as a build failure.
204
+ context.logger.error(message(error));
205
+ await stop();
206
+ subscriber.next({ success: false });
207
+ subscriber.complete();
208
+ return;
209
+ }
210
+ finally {
211
+ if (active === generation) {
212
+ active = undefined;
213
+ }
214
+ }
215
+ if (stopped) {
216
+ return;
217
+ }
218
+ initial = false;
219
+ pump();
220
+ if (stopped) {
221
+ return;
222
+ }
223
+ acquisition = context.scheduleBuilder(devServerBuilder, devServer, {
224
+ target: context.target,
225
+ });
226
+ const run = await acquisition;
227
+ if (stopped) {
228
+ await run.stop();
229
+ return;
230
+ }
231
+ forwarding = run.output.subscribe({
232
+ next: (output) => subscriber.next(output),
233
+ error: (error) => {
234
+ void stop().then(() => subscriber.error(error), () => subscriber.error(error));
235
+ },
236
+ complete: () => {
237
+ void stop().then(() => subscriber.complete(), (error) => subscriber.error(error));
238
+ },
239
+ });
240
+ }
241
+ void start().catch((error) => {
242
+ void stop().then(() => subscriber.error(error), () => subscriber.error(error));
243
+ });
244
+ return () => {
245
+ void stop().catch((error) => context.logger.error(String(error)));
246
+ };
247
+ }));
248
+ export default builder;
package/builders.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "$schema": "./node_modules/@angular-devkit/architect/src/builders-schema.json",
3
+ "builders": {
4
+ "application": {
5
+ "implementation": "./builders/application.js",
6
+ "schema": "./schemas/application.json",
7
+ "description": "Generate/check Launch and router files, then run @angular/build:application with the remaining options."
8
+ },
9
+ "serve": {
10
+ "implementation": "./builders/serve.js",
11
+ "schema": "./schemas/serve.json",
12
+ "description": "Watch Launch sources, then run @angular/build:dev-server with the remaining options."
13
+ }
14
+ }
15
+ }
package/client.d.ts CHANGED
@@ -7,8 +7,9 @@ export interface CallOptions {
7
7
  * `DOMException` named `AbortError`.
8
8
  *
9
9
  * @remarks
10
- * An already aborted signal rejects without sending a request. Aborting doesn't
11
- * cancel server work that has already started.
10
+ * An already aborted signal rejects without sending a request. On the server, the
11
+ * call's middleware and handler see their `signal` abort. That's advisory: work that
12
+ * doesn't pass the signal on still finishes.
12
13
  */
13
14
  readonly signal?: AbortSignal;
14
15
  /**
@@ -24,8 +25,9 @@ export interface MutationCallOptions {
24
25
  * `DOMException` named `AbortError`.
25
26
  *
26
27
  * @remarks
27
- * Aborting doesn't cancel server work that has already started, so the write may
28
- * still complete.
28
+ * On the server, the call's middleware and handler see their `signal` abort. That's
29
+ * advisory: work that doesn't pass the signal on still finishes, and the write may
30
+ * already have committed.
29
31
  */
30
32
  readonly signal?: AbortSignal;
31
33
  /** Only `false` is accepted: mutations never use the HTTP transfer cache. */
@@ -53,8 +55,9 @@ export interface ErrorMetadata {
53
55
  * @remarks
54
56
  * - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
55
57
  * {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
56
- * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
57
- * server rendering.
58
+ * - `FORBIDDEN` (403): middleware or a handler threw `forbidden()`, the request wasn't
59
+ * proven to come from the app's own origin, or a mutation was called during server
60
+ * rendering.
58
61
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
59
62
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
60
63
  *
package/client.js CHANGED
@@ -6,8 +6,9 @@ import { isInvalidInputData } from "./input-issues.js";
6
6
  * @remarks
7
7
  * - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
8
8
  * {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
9
- * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
10
- * server rendering.
9
+ * - `FORBIDDEN` (403): middleware or a handler threw `forbidden()`, the request wasn't
10
+ * proven to come from the app's own origin, or a mutation was called during server
11
+ * rendering.
11
12
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
12
13
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
13
14
  *
@@ -0,0 +1,2 @@
1
+ import type { GenerationSession } from "./index.js";
2
+ export declare const contextFiles: WeakMap<GenerationSession, string>;
@@ -0,0 +1,3 @@
1
+ // The context file each session's last pass discovered, for the serve builder's watcher. Internal:
2
+ // the exports map doesn't reach this module, so it isn't public API.
3
+ export const contextFiles = new WeakMap();