@c9up/aurora 0.1.38 → 0.1.40

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.
Files changed (50) hide show
  1. package/dist/AuroraManager.d.ts +6 -0
  2. package/dist/AuroraManager.js +12 -1
  3. package/dist/AuroraProvider.js +5 -2
  4. package/dist/Pages.d.ts +26 -0
  5. package/dist/Pages.js +70 -17
  6. package/dist/browser.js +2 -1
  7. package/dist/component.js +2 -1
  8. package/dist/devPageHooks.d.ts +44 -0
  9. package/dist/devPageHooks.js +62 -0
  10. package/dist/devPageReload.d.ts +75 -0
  11. package/dist/devPageReload.js +136 -0
  12. package/dist/errors.d.ts +51 -0
  13. package/dist/errors.js +26 -0
  14. package/dist/form.d.ts +1 -1
  15. package/dist/html.js +2 -1
  16. package/dist/hydrate.js +4 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.js +1 -0
  19. package/dist/liveRegistry.js +2 -1
  20. package/dist/relay.js +2 -1
  21. package/dist/render.d.ts +17 -1
  22. package/dist/render.js +58 -22
  23. package/dist/server/renderPage.js +2 -1
  24. package/dist/server/serveAssets.d.ts +10 -0
  25. package/dist/server/serveAssets.js +38 -0
  26. package/dist/server.d.ts +4 -1
  27. package/dist/server.js +4 -1
  28. package/dist/services/main.js +2 -1
  29. package/dist/url.js +3 -2
  30. package/package.json +11 -8
  31. package/src/AuroraManager.ts +12 -1
  32. package/src/AuroraProvider.ts +5 -2
  33. package/src/Pages.ts +92 -20
  34. package/src/browser.ts +5 -1
  35. package/src/component.ts +3 -1
  36. package/src/devPageHooks.ts +86 -0
  37. package/src/devPageReload.ts +142 -0
  38. package/src/errors.ts +58 -0
  39. package/src/form.ts +1 -1
  40. package/src/html.ts +4 -1
  41. package/src/hydrate.ts +4 -1
  42. package/src/index.ts +1 -0
  43. package/src/liveRegistry.ts +4 -1
  44. package/src/relay.ts +5 -1
  45. package/src/render.ts +76 -32
  46. package/src/server/renderPage.ts +5 -1
  47. package/src/server/serveAssets.ts +48 -0
  48. package/src/server.ts +8 -1
  49. package/src/services/main.ts +3 -1
  50. package/src/url.ts +6 -2
package/src/render.ts CHANGED
@@ -31,6 +31,42 @@ import {
31
31
 
32
32
  export type Disposer = () => void;
33
33
 
34
+ /**
35
+ * The `onMount` hooks collected while a tree is built, and whether they have
36
+ * already been run.
37
+ *
38
+ * A bare array was not enough. The root flushes it once, after the fragment is
39
+ * in the document; a reactive slot that swapped its content LATER kept
40
+ * appending to that same array, and nothing flushed it again — the component's
41
+ * setup ran, its `onMount` never did, and the hooks piled up for the life of
42
+ * the page. The flag is what lets a later update tell "collect these, the root
43
+ * will run them" from "the root is done, run mine myself".
44
+ */
45
+ interface MountQueue {
46
+ hooks: Array<EffectCallback>;
47
+ flushed: boolean;
48
+ }
49
+
50
+ /**
51
+ * Run hooks, sending any teardown to `cleanups`.
52
+ *
53
+ * Failures are swallowed per hook: one component's bad `onMount` must not stop
54
+ * its siblings from mounting.
55
+ */
56
+ function runMountHooks(
57
+ hooks: Array<EffectCallback>,
58
+ cleanups: Disposer[],
59
+ ): void {
60
+ for (const hook of hooks) {
61
+ try {
62
+ const teardown = hook();
63
+ if (typeof teardown === "function") cleanups.push(teardown);
64
+ } catch {
65
+ /* swallow — one bad onMount should not block sibling components */
66
+ }
67
+ }
68
+ }
69
+
34
70
  /**
35
71
  * Mount a TemplateResult into `container`. Returns a `Disposer` that
36
72
  * stops every reactive effect and removes the mounted nodes. Calling it
@@ -42,22 +78,19 @@ export function render(
42
78
  ): Disposer {
43
79
  const cleanups: Disposer[] = [];
44
80
  const mountedNodes: ChildNode[] = [];
45
- const mountHooks: Array<EffectCallback> = [];
81
+ const queue: MountQueue = { hooks: [], flushed: false };
46
82
 
47
- const fragment = mount(result, cleanups, mountedNodes, mountHooks);
83
+ const fragment = mount(result, cleanups, mountedNodes, queue);
48
84
  container.appendChild(fragment);
49
85
 
50
86
  // `onMount` hooks fire after the fragment is live in the document so
51
87
  // callbacks that measure / focus / observe see a real DOM. A returned
52
88
  // cleanup function joins the unmount queue.
53
- for (const hook of mountHooks) {
54
- try {
55
- const teardown = hook();
56
- if (typeof teardown === "function") cleanups.push(teardown);
57
- } catch {
58
- /* swallow — one bad onMount should not block sibling components */
59
- }
60
- }
89
+ runMountHooks(queue.hooks, cleanups);
90
+ queue.hooks = [];
91
+ // From here on the root never flushes again, so a slot that mounts
92
+ // something later has to run its own hooks.
93
+ queue.flushed = true;
61
94
 
62
95
  let disposed = false;
63
96
  return () => {
@@ -92,7 +125,7 @@ export function mount(
92
125
  result: TemplateResult,
93
126
  cleanups: Disposer[],
94
127
  mounted: ChildNode[],
95
- mountHooks: Array<EffectCallback>,
128
+ queue: MountQueue,
96
129
  ): DocumentFragment {
97
130
  const tpl = getTemplate(result.strings);
98
131
  const fragment = tpl.element.content.cloneNode(true) as DocumentFragment;
@@ -100,7 +133,7 @@ export function mount(
100
133
  // Forward any component()-attached lifecycle from this result.
101
134
  const lifecycle = readComponentLifecycle(result);
102
135
  if (lifecycle) {
103
- for (const hook of lifecycle.mountHooks) mountHooks.push(hook);
136
+ for (const hook of lifecycle.mountHooks) queue.hooks.push(hook);
104
137
  for (const c of lifecycle.cleanups) cleanups.push(c);
105
138
  }
106
139
 
@@ -148,7 +181,7 @@ export function mount(
148
181
  if (slot.kind === "attr" && slot.staticParts !== undefined) {
149
182
  collectMultiAttr(slot, node as Element, result.values[i], multiGroups);
150
183
  } else {
151
- applySlot(slot, node, result.values[i], cleanups, mounted, mountHooks);
184
+ applySlot(slot, node, result.values[i], cleanups, mounted, queue);
152
185
  }
153
186
  }
154
187
 
@@ -185,18 +218,11 @@ function applySlot(
185
218
  value: unknown,
186
219
  cleanups: Disposer[],
187
220
  mounted: ChildNode[],
188
- mountHooks: Array<EffectCallback>,
221
+ queue: MountQueue,
189
222
  ): void {
190
223
  switch (slot.kind) {
191
224
  case "text":
192
- applyTextSlot(
193
- slot,
194
- node as Comment,
195
- value,
196
- cleanups,
197
- mounted,
198
- mountHooks,
199
- );
225
+ applyTextSlot(slot, node as Comment, value, cleanups, mounted, queue);
200
226
  return;
201
227
  case "attr":
202
228
  applyAttrSlot(slot, node as Element, value, cleanups);
@@ -225,7 +251,7 @@ function applyTextSlot(
225
251
  value: unknown,
226
252
  cleanups: Disposer[],
227
253
  mounted: ChildNode[],
228
- mountHooks: Array<EffectCallback>,
254
+ queue: MountQueue,
229
255
  ): void {
230
256
  let currentNodes: ChildNode[] = [];
231
257
  // Per-render disposers for whatever the slot currently shows. A
@@ -246,18 +272,36 @@ function applyTextSlot(
246
272
  disposeLocal();
247
273
  for (const n of currentNodes) n.remove();
248
274
  currentNodes = [];
249
- const nodes = renderValueIntoNodes(
250
- newValue,
251
- localCleanups,
252
- mounted,
253
- mountHooks,
254
- );
275
+ // This render's hooks are collected apart from the shared queue,
276
+ // whichever phase we are in, because their TEARDOWNS belong to this
277
+ // slot: the next swap must dispose what it replaces. Left on the root's
278
+ // list, a component mounted per row kept its subscription until the
279
+ // whole page unmounted.
280
+ //
281
+ // `flushed` is inherited so a deeper slot built during this render
282
+ // still knows whether the root has a flush coming.
283
+ const own: MountQueue = { hooks: [], flushed: queue.flushed };
284
+ const nodes = renderValueIntoNodes(newValue, localCleanups, mounted, own);
255
285
  const parent = anchor.parentNode;
256
286
  if (!parent) return;
257
287
  for (const n of nodes) {
258
288
  parent.insertBefore(n, anchor);
259
289
  currentNodes.push(n);
260
290
  }
291
+ if (queue.flushed) {
292
+ // After insertion, exactly as at the root: an `onMount` that
293
+ // measures, focuses or observes has to see a live node.
294
+ runMountHooks(own.hooks, localCleanups);
295
+ return;
296
+ }
297
+ // Still building the initial tree: the nodes are in a detached
298
+ // fragment, so defer to the root's flush. One wrapper carries them, and
299
+ // it returns nothing — the real teardowns go to `localCleanups`, not to
300
+ // the root.
301
+ const pending = own.hooks;
302
+ queue.hooks.push(() => {
303
+ runMountHooks(pending.splice(0), localCleanups);
304
+ });
261
305
  }
262
306
 
263
307
  if (isSignal(value) || typeof value === "function") {
@@ -282,18 +326,18 @@ function renderValueIntoNodes(
282
326
  value: unknown,
283
327
  cleanups: Disposer[],
284
328
  mounted: ChildNode[],
285
- mountHooks: Array<EffectCallback>,
329
+ queue: MountQueue,
286
330
  ): ChildNode[] {
287
331
  if (value === null || value === undefined || value === false) return [];
288
332
  if (Array.isArray(value)) {
289
333
  const out: ChildNode[] = [];
290
334
  for (const item of value) {
291
- out.push(...renderValueIntoNodes(item, cleanups, mounted, mountHooks));
335
+ out.push(...renderValueIntoNodes(item, cleanups, mounted, queue));
292
336
  }
293
337
  return out;
294
338
  }
295
339
  if (isTemplateResult(value)) {
296
- const frag = mount(value, cleanups, mounted, mountHooks);
340
+ const frag = mount(value, cleanups, mounted, queue);
297
341
  return Array.from(frag.childNodes);
298
342
  }
299
343
  if (value instanceof Node) {
@@ -25,6 +25,7 @@
25
25
 
26
26
  import { AsyncLocalStorage } from "node:async_hooks";
27
27
  import { setCookieStoreReader } from "../browser.js";
28
+ import { AuroraError } from "../errors.js";
28
29
  import type { Pages } from "../Pages.js";
29
30
  import { renderToString } from "../ssr.js";
30
31
  import { setRouteManifestReader } from "../url.js";
@@ -331,7 +332,10 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
331
332
 
332
333
  function normalizeRootTag(tag: string): string {
333
334
  if (/^[a-z][a-z0-9-]*$/i.test(tag)) return tag.toLowerCase();
334
- throw new Error(`[aurora] illegal root tag: ${JSON.stringify(tag)}`);
335
+ throw new AuroraError(
336
+ "E_AURORA_ILLEGAL_ROOT_TAG",
337
+ `[aurora] illegal root tag: ${JSON.stringify(tag)}`,
338
+ );
335
339
  }
336
340
 
337
341
  function rootAttrs(id: string, className: string | undefined): string {
@@ -10,6 +10,7 @@
10
10
  * `AssetsHttpContext` (Ream, AdonisJS, anything duck-typed) works.
11
11
  */
12
12
 
13
+ import { createHash } from "node:crypto";
13
14
  import { readFile, realpath } from "node:fs/promises";
14
15
  import { dirname, extname, join, resolve as resolvePath, sep } from "node:path";
15
16
  import { fileURLToPath } from "node:url";
@@ -28,6 +29,27 @@ export function packageAssetDir(specifier: string): string {
28
29
  return dirname(fileURLToPath(import.meta.resolve(specifier)));
29
30
  }
30
31
 
32
+ /**
33
+ * Does `If-None-Match` cover this entity? (RFC 9110 §13.1.2)
34
+ *
35
+ * A strict `===` answered 200 for three shapes a real client sends: `*`, a
36
+ * comma-separated list of tags, and the weak form `W/"…"` — so a browser
37
+ * holding the exact bytes re-downloaded them anyway, which is most of what the
38
+ * validator exists to prevent. Written here rather than imported because aurora
39
+ * does not depend on ream; the same function lives in `ream/src/http/etag.ts`.
40
+ */
41
+ function matchesIfNoneMatch(header: string | undefined, tag: string): boolean {
42
+ if (header === undefined || header === "" || tag === "") return false;
43
+ // `*` means "any current representation", so a stored copy always matches.
44
+ if (header.trim() === "*") return true;
45
+ const bare = (value: string): string =>
46
+ value.startsWith("W/") ? value.slice(2) : value;
47
+ const current = bare(tag);
48
+ return header
49
+ .split(",")
50
+ .some((candidate) => bare(candidate.trim()) === current);
51
+ }
52
+
31
53
  const CONTENT_TYPES: Record<string, string> = {
32
54
  ".js": "text/javascript; charset=utf-8",
33
55
  ".mjs": "text/javascript; charset=utf-8",
@@ -44,6 +66,12 @@ export interface AssetsRequest {
44
66
  * convention.
45
67
  */
46
68
  param(name: string): unknown;
69
+ /**
70
+ * Read a request header. OPTIONAL, so a host that only implements
71
+ * `param()` keeps working: without it there is no conditional request and
72
+ * every response is a full 200, which is what happened before.
73
+ */
74
+ header?(name: string): string | undefined;
47
75
  }
48
76
  export interface AssetsResponse {
49
77
  status(code: number): AssetsResponse;
@@ -65,6 +93,10 @@ export interface ServeAssetsOptions {
65
93
  * `Cache-Control` value to emit. Defaults to a dev-friendly
66
94
  * 60-second TTL. Production deployments should hash the asset
67
95
  * name and switch to `public, max-age=31536000, immutable`.
96
+ *
97
+ * Note that a TTL alone tells the browser not to ASK for 60 seconds. Pair
98
+ * it with `no-cache` while developing — the ETag below then makes the
99
+ * revalidation nearly free.
68
100
  */
69
101
  cacheControl?: string;
70
102
  }
@@ -144,10 +176,26 @@ export function serveAssets(
144
176
  return;
145
177
  }
146
178
 
179
+ // A validator, so a cached copy can be CHECKED rather than only trusted
180
+ // for a fixed time. Without one an edited module was served stale for
181
+ // the whole TTL with no way for the browser to ask whether it changed —
182
+ // in development that is a source file, and the answer is usually yes.
183
+ //
184
+ // Hashed from the bytes actually being sent rather than from mtime and
185
+ // size: a checkout, a rebuild or a touched file all move the metadata
186
+ // without changing the content, and each would needlessly re-download.
187
+ const etag = `"${createHash("sha1").update(body).digest("base64url")}"`;
147
188
  const type =
148
189
  CONTENT_TYPES[extname(canonicalAbsolute)] ?? "application/octet-stream";
149
190
  ctx.response.header("content-type", type);
150
191
  ctx.response.header("cache-control", cacheControl);
192
+ ctx.response.header("etag", etag);
193
+ if (matchesIfNoneMatch(ctx.request.header?.("if-none-match"), etag)) {
194
+ // 304 carries no body, and must not: the browser reuses the copy it
195
+ // already has.
196
+ ctx.response.status(304).send("");
197
+ return;
198
+ }
151
199
  ctx.response.send(body);
152
200
  };
153
201
  }
package/src/server.ts CHANGED
@@ -12,11 +12,18 @@
12
12
  import "./augmentations.js";
13
13
 
14
14
  export { AuroraManager, type AuroraManagerConfig } from "./AuroraManager.js";
15
+ export { AuroraError, type AuroraErrorCode } from "./errors.js";
15
16
  export {
16
17
  type AuroraRequestRenderer,
17
18
  auroraContext,
18
19
  } from "./middleware.js";
19
- export { type PageFactory, Pages, type PagesConfig } from "./Pages.js";
20
+ export {
21
+ type PageFactory,
22
+ Pages,
23
+ type PagesConfig,
24
+ /** @internal classification seam, asserted by the tests */
25
+ pageImportError,
26
+ } from "./Pages.js";
20
27
  export {
21
28
  type RenderHttpContext,
22
29
  type RenderPageOptions,
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import type { AuroraManager } from "../AuroraManager.js";
14
+ import { AuroraError } from "../errors.js";
14
15
 
15
16
  let instance: AuroraManager | undefined;
16
17
 
@@ -48,7 +49,8 @@ const aurora: AuroraManager = new Proxy({} as AuroraManager, {
48
49
  return undefined;
49
50
  }
50
51
  if (!instance) {
51
- throw new Error(
52
+ throw new AuroraError(
53
+ "E_AURORA_NOT_BOOTED",
52
54
  "[aurora] AuroraManager singleton accessed before AuroraProvider.boot() ran " +
53
55
  "or `setAurora(myManager)` was called. Wire one of them first.",
54
56
  );
package/src/url.ts CHANGED
@@ -17,6 +17,8 @@
17
17
  * side. Node-free — part of aurora's client runtime.
18
18
  */
19
19
 
20
+ import { AuroraError } from "./errors.js";
21
+
20
22
  let manifest: Record<string, string> = {};
21
23
 
22
24
  type RouteManifestReader = () => Record<string, string> | undefined;
@@ -65,7 +67,8 @@ export function urlFor(
65
67
  const pattern = routes[name];
66
68
  if (pattern === undefined) {
67
69
  const known = Object.keys(routes);
68
- throw new Error(
70
+ throw new AuroraError(
71
+ "E_AURORA_UNKNOWN_ROUTE",
69
72
  `[aurora] urlFor: unknown route '${name}'. ${
70
73
  known.length > 0
71
74
  ? `Known: ${known.join(", ")}`
@@ -91,7 +94,8 @@ export function urlFor(
91
94
 
92
95
  const missing = url.match(/:[A-Za-z_][\w]*/g);
93
96
  if (missing && missing.length > 0) {
94
- throw new Error(
97
+ throw new AuroraError(
98
+ "E_AURORA_MISSING_ROUTE_PARAMS",
95
99
  `[aurora] urlFor: route '${name}' is missing params ${missing.join(", ")}`,
96
100
  );
97
101
  }