@verajs/autoloader 0.2.0 → 0.2.2

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
@@ -1,6 +1,6 @@
1
1
  # @verajs/autoloader
2
2
 
3
- Lazy component loading by tag name — <!--size:autoloader.gzip-->1.64 KB<!--/size:autoloader.gzip-->
3
+ Lazy component loading by tag name — <!--size:autoloader.gzip-->1.87 KB<!--/size:autoloader.gzip-->
4
4
  gzipped, no dependencies, no build step required.
5
5
 
6
6
  When an undefined custom element appears inside a component marked `autoloader`, its module is
@@ -83,7 +83,7 @@ there.
83
83
  Scanning is per-component on purpose: the insert scans the element's own tree, not the shadow roots
84
84
  of its descendants, so each component that hosts lazily-loaded children carries the attribute.
85
85
 
86
- It is `autoload-dir`, never HTML's global `dir` — `dir="rtl"` on any internationalised page would
86
+ It is `autoload-dir`, never HTML's global `dir` — `dir="rtl"` on any internationalized page would
87
87
  otherwise have silently redirected component loading.
88
88
 
89
89
  **All three are watched, not just read once.** Marking a component `autoloader` after it already has
@@ -190,7 +190,14 @@ most.
190
190
 
191
191
  `autoload.retry(element)` forgets that an element's tag failed and tries it again. A failed load is
192
192
  otherwise permanent for the page, which is right for a component that does not exist and wrong for
193
- one lost to a dropped connection. `vera:autoload-error` hands you the element:
193
+ one lost to a dropped connection. A retry asks the server again: an engine keeps a failed module import
194
+ by its URL (Chromium does), so the component's module is imported with `vera-retry=<n>` added to its
195
+ URL. A module of its own that failed to load stays failed in such an engine until the page reloads,
196
+ and a module that loaded but did not define its tag, or defined it and then threw, is not run again.
197
+ On a page whose import map pins anything with `integrity`, every retry imports as it is: a pin is
198
+ keyed by URL, so the same file under a new query would load unchecked. There, in an engine that keeps
199
+ a failed import (Chromium), a module that failed stays failed until the page reloads. A retry while that tag is still loading does
200
+ nothing: the load in flight answers it. `vera:autoload-error` hands you the element:
194
201
 
195
202
  ```js
196
203
  addEventListener('vera:autoload-error', ({ detail }) => {
@@ -291,3 +298,8 @@ The name itself is markup input and is allowlisted to `[a-z][a-z0-9-]*` before a
291
298
  a name outside the grammar is declined, never fetched. `directiveLoader(...).url(name)` returns
292
299
  the URL it would fetch, for `<link rel="modulepreload">` warming and for answering "why is it
293
300
  fetching that". One attempt per name per page load; the engine memoizes the refusals.
301
+
302
+ **A failed import is reported once, by the engine** — one line naming the directive and the URL, with the error
303
+ beside it. The loader itself prints nothing: its load function rejects with an `Error` whose message is the URL
304
+ it tried and whose `cause` is the import's own error (`error.cause`). So a page that calls the loader directly,
305
+ without the engine, reads both from its own `catch`.
@@ -1,3 +1,12 @@
1
+ /**
2
+ * What `autoloader(import.meta.url, dir, options)` accepts beyond its two required arguments.
3
+ *
4
+ * Every field has a default, and the reason they exist is that a tag name does not determine a URL:
5
+ * the default `dir/tag.extension` suits most projects, `extension` covers a dev server that serves
6
+ * `.ts`, and `resolve` replaces the path building entirely for anything else. Containment against
7
+ * `rootDir`'s directory is enforced whichever you use — a tag name reaches the network, so it is
8
+ * treated as untrusted input rather than as a path fragment.
9
+ */
1
10
  type AutoloaderOptions = {
2
11
  /**
3
12
  * File extension appended to the tag name when building a component's URL.
@@ -51,6 +60,14 @@ type DirectiveLoaderOptions = {
51
60
  /** Replaces path building entirely; containment against rootDir's directory still applies. */
52
61
  resolve?: (name: string, dir: string) => string;
53
62
  };
63
+ /**
64
+ * What `directiveLoader(...)` returns: the loader function itself, carrying the descriptor members
65
+ * `wire` reads — the dual shape described in `CLAUDE.md`, so one value is both callable and
66
+ * wireable.
67
+ *
68
+ * `fn` is `never` because the descriptor's callable half IS the function; the field exists only so
69
+ * the object satisfies the descriptor shape, and nothing should ever read it.
70
+ */
54
71
  type DirectiveLoaderInstance = ((name: string, element: Element) => boolean | Promise<unknown>) & {
55
72
  /** The URL this loader would fetch for a name — for modulepreload warming and for asking
56
73
  * "why is it fetching that". Throws where `load` would decline. */
@@ -1 +1 @@
1
- {"version":3,"file":"vera-autoloader.d.ts","sources":["../../src/autoloader.ts","../../src/loader.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BG;AACH;cAKE,UAAA,sDAAA,iBAAA,KAA4F,kBAAA;;ACE9F;AAC+C;AAC/C;AAEA;AAKE;AAAc;;AAEZ;AACE;;AACA;AACA;AAEI;;AAGN;;;AAGM;AAEI;;;AAIZ;AACA;AACA;AACA;;AAGA;AAEA;;;;;AAKG;AACH;;;cAGG,eAAA,sDAAA,sBAAA,KAAA,uBAAA;;;;","names":[]}
1
+ {"version":3,"file":"vera-autoloader.d.ts","sources":["../../src/autoloader.ts","../../src/loader.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;AACA;AAEA;;;;;AAKG;AACH;AACE;AACA;;AACiD;AACjD;;AAEF;AAEA;;;;;AAKG;AACH;;AAEI;AACE;AACA;AAA8F;cAC/F,UAAA,sDAAA,iBAAA,KAAA,kBAAA;;ACML;AACA;AACA;AAEA;AACA;AACA;AACE;AACA;AACA;AACF;AAEA;AAC+C;AAC/C;AAEA;;AAME;AACA;AACA;;AAGA;AAEA;;;;;AAKG;AACH;;AAEI;;AAEF;;AAEA;;;;;;;;","names":[]}
@@ -1,3 +1,180 @@
1
+ /**
2
+ * **Where every diagnostic code is explained.** The URL is permanent: a released bundle is immutable, so every version
3
+ * published points here for ever — the domain cannot lapse and `/e/` cannot be reorganized without breaking links in
4
+ * code nobody can edit; the docs site redirects instead. `scripts/sync-diagnostics.mjs` imports this constant, so the
5
+ * pages and the bundles can never disagree about where they are.
6
+ */
7
+ const DOCS = 'https://verajs.dev/e/';
8
+ /**
9
+ * **One shape for every diagnostic the framework prints** — the short line production keeps, the whole sentence
10
+ * development adds — so a package converting its messages writes a table and a call, never its own format.
11
+ *
12
+ * production `[vera] hydration: element: found <i> — https://verajs.dev/e/hydration-fallback`
13
+ * development `[vera] hydration: element: found <i> — fell back to a client render: … (hydration-fallback)`
14
+ *
15
+ * `subject` is the free information — what the code already has at hand, naming the problem area — the same in both
16
+ * builds. `prose` is development only: the package's table entry (`Prose`), called behind `true ` at the call site so
17
+ * the table goes unreferenced in production and rollup drops it whole. Production prints the code inside the link, so
18
+ * the reader is one click from the explanation, which `scripts/sync-diagnostics.mjs` publishes from the same tables.
19
+ *
20
+ * **Every production message is coded** (Brian, 2026-11-11; this supersedes "convert where smaller", 2026-10-02):
21
+ * consistency over a few bytes, so no package keeps a hand-written production line beside its table.
22
+ */
23
+ /*
24
+ * The parameter names are deliberately unlike anything a caller holds: terser will not inline a function whose
25
+ * parameter shadows a name at the call site (measured 2026-10-02 — directives passes its own `code`, and a parameter
26
+ * called `code` left `((e,t,n)=>`…`)(0,t,n)` in its bundle, +8 B; renamed, the call folds to the bare template).
27
+ */
28
+ /**
29
+ * **A misused API, named by its function** — the thrown-error twin of `diagnostic()`: `untrack: expected a function …
30
+ * (untrack-not-function)`, function-first because a stack already names the source and the sweep reads that shape. The
31
+ * prose comes from a package's table, behind `true `, so a development-only guard costs production nothing.
32
+ */
33
+ const misuse = (forName, withCode, andProse) => true && andProse
34
+ ? `${forName}: ${andProse[0]}${andProse[1] ? ` ${andProse[1]}` : ''} (${withCode})`
35
+ : `${forName}: ${DOCS}${withCode}`;
36
+ const diagnostic = (inArea, bySubject, withCode, andProse) =>
37
+ /** `true ` HERE as well as at the call: production folds this to the one-line form, branch and all. */
38
+ true && andProse
39
+ ? `[vera] ${inArea}: ${bySubject} — ${andProse[0]}${andProse[1] ? ` ${andProse[1]}` : ''} (${withCode})`
40
+ : `[vera] ${inArea}: ${bySubject} — ${DOCS}${withCode}`;
41
+
42
+ /**
43
+ * core's `html`/`svg`/`mathml` and the renderer's `tag` — a tagged template called as a function. The FACT is shared;
44
+ * the EXAMPLE is each emitter's: `html` writes markup, `tag` an element name — so the emitter passes it.
45
+ */
46
+ /**
47
+ * An option a module or loader does not have — autoloader(), directiveLoader(), router(), and the directives packs
48
+ * remote(), sensors(), motion(). One fact and one fix; the module is the line's SUBJECT and the list is its own.
49
+ */
50
+ const unknownOption = (key, list) => [
51
+ `\`${key}\` is not an option, so it was ignored.`,
52
+ `The options are ${list}.`,
53
+ ];
54
+
55
+ /**
56
+ * **What a thrown value says, whatever was thrown — and it never throws itself.** A caught value comes from author
57
+ * code (a `resolve` option, a motion tick or vocabulary function), and JavaScript can throw anything: `null`, an object
58
+ * with no prototype (`String()` finds no `toString`), one whose `toString` or `message` getter throws, a Proxy whose
59
+ * traps throw. Formatting it naively replaced the real failure with an unrelated TypeError from inside the framework.
60
+ * Anything unreadable becomes a fixed phrase; `Object.prototype.toString` is no fallback, since it reads
61
+ * `Symbol.toStringTag` through a Proxy's trap too.
62
+ *
63
+ * **A deliberate duplicate of `thrownMessage` in `packages/ssr/src/vera/escaping.ts` — fix both copies.** `@verajs/ssr`
64
+ * is compiled per file with no bundling, so it cannot import this private, unpublished package at run time;
65
+ * `tests/thrown-message-copies.test.mjs` runs one table of thrown values against both, so they cannot drift.
66
+ */
67
+ const thrownMessage = (error) => {
68
+ try {
69
+ if (error instanceof Error)
70
+ return String(error.message);
71
+ const message = error?.message;
72
+ return typeof message === 'string' ? message : String(error);
73
+ }
74
+ catch {
75
+ return '[unprintable value thrown]';
76
+ }
77
+ };
78
+
79
+ const PROSE = {
80
+ 'loader-root-required': () => ['rootDir is required — the directory every path resolves against.', 'Pass import.meta.url.'],
81
+ 'loader-root-not-absolute': (rootDir) => [
82
+ `rootDir must be an absolute URL, and "${rootDir}" is not.`,
83
+ 'Pass import.meta.url — a relative path has nothing to resolve against.',
84
+ ],
85
+ /**
86
+ * Three reasons, one fact — a URL this loader will not fetch (and no request is made). The refused URL is the line's
87
+ * SUBJECT, so production — which prints no prose — still says which.
88
+ */
89
+ 'loader-url-refused': (why) => [`refused — ${why}.`, 'Nothing was requested. Point the directory, or `resolve`, at a path inside rootDir.'],
90
+ /** What it threw is the SUBJECT (printed in every build); this explains it. */
91
+ 'loader-resolve-threw': () => [
92
+ 'the `resolve` option threw.',
93
+ 'The element was left unloaded; `resolve(name, dir)` must return a path and never throw.',
94
+ ],
95
+ 'loader-import-failed': (what, src) => [`failed to load ${what} from ${src}.`, 'The error is printed beside this line; the import itself failed.'],
96
+ 'autoloader-not-defined': (tag) => [
97
+ `the module loaded but nothing defined <${tag}>.`,
98
+ 'Check the tag name in that file matches the one in the markup, and that its `customElements.define` actually runs.',
99
+ ],
100
+ 'directive-loader-name': (name) => [`"${name}" is not a directive name this will resolve.`, 'A directive name is lowercase letters, digits and dashes, starting with a letter.'],
101
+ };
102
+
103
+ /**
104
+ * **The checks both loaders make on their entry, in one home** (`autoloader` and `directiveLoader` each held a copy):
105
+ * the root is required and absolute, an unknown option warns, and the extension is normalized. Answers the directory
106
+ * every URL must stay inside, and the extension.
107
+ *
108
+ * A configuration error fails at the misconfiguration, not once per element per render.
109
+ *
110
+ * A **relative** `rootDir` throws either way; development says why. The platform's own message (`Failed to construct
111
+ * 'URL': Invalid base URL`) names neither the argument nor the fix. The value has to be absolute because every URL
112
+ * resolves against it, which is why `import.meta.url` is the documented answer.
113
+ *
114
+ * An option a loader does not have does nothing, and did so in silence: `extensions` or `resolver` reads exactly like
115
+ * the real thing at a glance, and the symptom is the *default* behavior, which looks like the option was never needed
116
+ * rather than never seen.
117
+ *
118
+ * Both of those are `true `-only, so a production bundle carries neither the checks nor their text.
119
+ *
120
+ * @param owner The loader's name, the area every line it prints is filed under
121
+ * @param known The option names that loader reads
122
+ * @return `[base, extension]`: `base` is `new URL('.', rootDir)`, which always ends in `/`, so a prefix test against it
123
+ * cannot be satisfied by a sibling directory whose name merely starts the same way. Every resolved URL must stay inside
124
+ * it: the per-element directory override is free text, and CODE-PRINCIPLES #8 requires bounding anything that turns
125
+ * markup into a module URL. The extension may be given as `ts` or `.ts`.
126
+ */
127
+ const entry = (owner, rootDir, options, known) => {
128
+ if (!rootDir)
129
+ throw new Error(misuse(owner, 'loader-root-required', true && PROSE['loader-root-required']()));
130
+ if (true ) {
131
+ try {
132
+ new URL('.', rootDir);
133
+ }
134
+ catch {
135
+ throw new Error(misuse(owner, 'loader-root-not-absolute', true && PROSE['loader-root-not-absolute'](rootDir)));
136
+ }
137
+ if (options)
138
+ for (const key of Object.keys(options))
139
+ if (!known.includes(key))
140
+ console.warn(diagnostic(owner, 'options', 'unknown-option', true && unknownOption(key, known.join(', '))));
141
+ }
142
+ return [new URL('.', rootDir).href, `.${(options?.extension ?? '.js').replace(/^\./, '')}`];
143
+ };
144
+
145
+ /**
146
+ * `src` with `vera-retry=<n>` added to its query (a hash kept where it was): a URL the engine has not seen, for a retry
147
+ * of an import it rejected (see `retries`). A server ignores a query it does not read, so it is the same file. Only a
148
+ * URL a server answers (`http:`, `https:`, `file:`): a query would change a `data:` URL's content, and a `blob:` that
149
+ * failed cannot come back, so those are imported as they are.
150
+ */
151
+ const retried = (src, tries, document) => {
152
+ const url = new URL(src);
153
+ const served = url.protocol === 'http:' || url.protocol === 'https:' || url.protocol === 'file:';
154
+ if (!served || /*@__NOINLINE__*/ pins(document))
155
+ return src;
156
+ url.searchParams.set('vera-retry', String(tries));
157
+ return url.href;
158
+ };
159
+ /**
160
+ * **Whether an import map on the page pins anything with `integrity`**: a hash is keyed by URL, so the same file under
161
+ * `vera-retry=<n>` loads unchecked (measured on Chromium, Firefox and WebKit), and a file that failed its check would
162
+ * load on the retry. On such a page every retry imports as it is. Not a match against `src`: a hash is keyed by the URL
163
+ * the map RESOLVES to, after its `imports` and `scopes` remap `src`, so a match on `src` misses a remapped pin.
164
+ */
165
+ const pins = (document) => {
166
+ for (const script of document.querySelectorAll('script[type="importmap"]')) {
167
+ try {
168
+ const integrity = JSON.parse(script.textContent ?? '').integrity;
169
+ if (typeof integrity === 'object' && integrity !== null && Object.keys(integrity).length > 0)
170
+ return true;
171
+ }
172
+ catch {
173
+ /** Not JSON: the engine refused that map as well, so it pins nothing. */
174
+ }
175
+ }
176
+ return false;
177
+ };
1
178
  /**
2
179
  * Inits an autoloader with the provided root directory, component directory and autoloader options.
3
180
  *
@@ -27,23 +204,7 @@
27
204
  * once. Carries `url(tag)` and `retry(element)`.
28
205
  */
29
206
  const autoloader = (rootDir, componentsDir, options) => {
30
- /** A configuration error fails at the misconfiguration, not once per element per render. */
31
- if (!rootDir)
32
- throw new Error('autoloader: rootDir is required (usually import.meta.url)');
33
- /**
34
- * An option this autoloader does not have does nothing, and did so in silence — `extensions` or
35
- * `resolver` reads exactly like the real thing at a glance, and the symptom is the *default*
36
- * behaviour, which looks like the option was never needed rather than never seen.
37
- *
38
- * `true `-only, so a production bundle carries neither the list nor the text.
39
- */
40
- if (true && options)
41
- for (const key of Object.keys(options))
42
- if (key !== 'extension' && key !== 'resolve')
43
- console.warn(`[vera] autoloader: \`${key}\` is not an option, so it was ignored. ` +
44
- `The options are extension and resolve.`);
45
- /** Normalized so callers may pass either `ts` or `.ts` */
46
- const extension = `.${(options?.extension ?? '.js').replace(/^\./, '')}`;
207
+ const [base, extension] = entry('autoloader', rootDir, options, ['extension', 'resolve']);
47
208
  /**
48
209
  * `dir/tag.ext` is one layout, and a component library is as likely to use `tag/tag.js`,
49
210
  * `tag/index.js`, or a flat manifest. `resolve` replaces the URL-building step entirely while
@@ -52,31 +213,6 @@ const autoloader = (rootDir, componentsDir, options) => {
52
213
  * shape to avoid; the path around it is the same problem one level out.
53
214
  */
54
215
  const resolve = options?.resolve;
55
- /**
56
- * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`
57
- * (the HTML parser won't produce one), but the `data-autoload-dir` override is free text — and
58
- * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An
59
- * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is
60
- * refused.
61
- */
62
- /**
63
- * A **relative** `rootDir` throws either way; development says why.
64
- *
65
- * The platform's own message — `Failed to construct 'URL': Invalid base URL` — names neither the
66
- * argument nor the fix. The value has to be absolute because every component URL resolves against
67
- * it, which is why `import.meta.url` is the documented answer. Behind `true `, so the build
68
- * folds it away and a production bundle carries neither the check nor the text.
69
- */
70
- if (true ) {
71
- try {
72
- new URL('.', rootDir);
73
- }
74
- catch {
75
- throw new Error(`autoloader: rootDir must be an absolute URL, and "${rootDir}" is not. ` +
76
- `Pass import.meta.url — a relative path has nothing to resolve against.`);
77
- }
78
- }
79
- const base = new URL('.', rootDir).href;
80
216
  /** One attempt per URL per page load, so a 404 costs one request and one console line. */
81
217
  const attempted = new Set();
82
218
  /**
@@ -91,6 +227,16 @@ const autoloader = (rootDir, componentsDir, options) => {
91
227
  const requested = new Set();
92
228
  /** The URL last tried for a tag, so `retry` knows which memo to clear. Dropped once it loads. */
93
229
  const failed = new Map();
230
+ /**
231
+ * **How many times `retry` has asked again for a tag whose import REJECTED** (2026-11-21): an engine keeps a failed
232
+ * module import, keyed by its URL — Chromium 159 and Firefox and WebKit before 159 and 27 answer the same URL from that
233
+ * record without asking the server (`tests/browser/autoloader.test.js` measures it) — so a retry imports the URL with
234
+ * `vera-retry=<n>` added, which the engine has not seen. A fragment would not do: Chromium keeps the failure under
235
+ * `#…` too. Only for a rejected import: a module that loaded and did not define its tag is retried from its own URL,
236
+ * since running it again could not define the tag and would run its code twice. Dropped once the tag loads. (One map
237
+ * of `{ src, tries }` for both was measured at +8 B gz, for one delete fewer in three places.)
238
+ */
239
+ const retries = new Map();
94
240
  /**
95
241
  * Roots under observation, so attaching is idempotent and cheap to re-attempt.
96
242
  *
@@ -100,6 +246,25 @@ const autoloader = (rootDir, componentsDir, options) => {
100
246
  * bookkeeping rather than the observer contract.)
101
247
  */
102
248
  const watched = new WeakSet();
249
+ /**
250
+ * The URLs this loader refused, by the refusal it threw — read back in `load` to report each once. The refusal still
251
+ * carries `href` for a caller of `url()`; `load` reads this map instead, because whatever reaches its `catch` may be
252
+ * the caller's own throw, and reading a property off `null` (or a Proxy that throws) crashed the error path, where
253
+ * `WeakMap#get` answers `undefined` for anything.
254
+ */
255
+ const refused = new WeakMap();
256
+ /**
257
+ * One refusal of a URL, recorded as it is made. The refused URL rides on the error, so discovery can dedupe on it
258
+ * exactly as it dedupes a fetch. Keying the refusal on the *tag* instead would be wrong: `data-autoload-dir` is
259
+ * watched precisely so it can be pointed somewhere else after a first attempt failed, and a tag marked spent never
260
+ * looks again.
261
+ */
262
+ const refuse = (tag, href, why) => {
263
+ const refusal = new Error(diagnostic('autoloader', `<${tag}> ${href}`, 'loader-url-refused', true && PROSE['loader-url-refused'](why)));
264
+ refusal.href = href;
265
+ refused.set(refusal, href);
266
+ return refusal;
267
+ };
103
268
  /**
104
269
  * Creates the expected element url location to be appended to the root dir.
105
270
  *
@@ -149,11 +314,7 @@ const autoloader = (rootDir, componentsDir, options) => {
149
314
  */
150
315
  if (!resolve && /[?#]/.test(dir)) {
151
316
  const url = new URL(href);
152
- const refusal = new Error(`[vera] autoloader: refused ${href} for <${tag}> — data-autoload-dir "${dir}" contains ? or #, ` +
153
- `which ends the path, so <${tag}> lands in the query or fragment and ` +
154
- `${url.origin}${url.pathname} would be fetched instead. Use \`resolve\` to add a query.`);
155
- refusal.href = href;
156
- throw refusal;
317
+ throw refuse(tag, href, `data-autoload-dir "${dir}" contains ? or #, which ends the path, so <${tag}> lands in the query or fragment and ${url.origin}${url.pathname} would be fetched instead; use \`resolve\` to add a query`);
157
318
  }
158
319
  /**
159
320
  * **An encoded separator is refused the way a real one is caught.**
@@ -170,11 +331,8 @@ const autoloader = (rootDir, componentsDir, options) => {
170
331
  * default path only, since `resolve` owns its own URL building and a `%2F` in a query it adds
171
332
  * is legitimately its business.
172
333
  */
173
- if (!resolve && /%2f|%5c/i.test(dir)) {
174
- const refusal = new Error(`[vera] autoloader: refused ${href} for <${tag}> — encoded path separator in "${dir}"`);
175
- refusal.href = href;
176
- throw refusal;
177
- }
334
+ if (!resolve && /%2f|%5c/i.test(dir))
335
+ throw refuse(tag, href, `an encoded path separator in "${dir}"`);
178
336
  /**
179
337
  * **Containment belongs here, not only at the fetch.**
180
338
  *
@@ -188,20 +346,11 @@ const autoloader = (rootDir, componentsDir, options) => {
188
346
  * would refuse handed the caller the fetch this module declines to make. One check, at the one
189
347
  * place URLs are built, also covers a custom `resolve` returning something unbounded.
190
348
  *
191
- * `base` is `new URL('.', rootDir)`, which always ends in `/`, so the prefix test cannot be
192
- * satisfied by a sibling directory whose name merely starts the same way.
349
+ * Tag names cannot carry `/` (the HTML parser won't produce one), but `data-autoload-dir` is free text: an
350
+ * absolute, protocol-relative or upward-traversing value resolves outside `base` (see `entry`) and is refused.
193
351
  */
194
- if (!href.startsWith(base)) {
195
- /**
196
- * The refused URL rides on the error, so discovery can dedupe on it exactly as it dedupes a
197
- * fetch. Keying the refusal on the *tag* instead would be wrong: `data-autoload-dir` is watched
198
- * precisely so it can be pointed somewhere else after a first attempt failed, and a tag
199
- * marked spent never looks again.
200
- */
201
- const refusal = new Error(`[vera] autoloader: refused ${href} for <${tag}> — resolves outside ${base}`);
202
- refusal.href = href;
203
- throw refusal;
204
- }
352
+ if (!href.startsWith(base))
353
+ throw refuse(tag, href, `it resolves outside ${base}`);
205
354
  return href;
206
355
  };
207
356
  /**
@@ -222,12 +371,16 @@ const autoloader = (rootDir, componentsDir, options) => {
222
371
  * Deduped on the refused URL, so it is reported once rather than on every scan — and so
223
372
  * pointing `data-autoload-dir` at a valid directory afterwards is a different URL and tries.
224
373
  */
225
- const href = error.href;
226
- if (href !== undefined) {
227
- if (attempted.has(href))
228
- return;
229
- attempted.add(href);
374
+ const href = refused.get(error);
375
+ if (href === undefined) {
376
+ /** Not a refusal of ours: the caller's `resolve` threw, and it can throw any value at all. */
377
+ console.error(diagnostic('autoloader', `<${tag}>: ${thrownMessage(error)}`, 'loader-resolve-threw', true && PROSE['loader-resolve-threw']()));
378
+ return;
230
379
  }
380
+ if (attempted.has(href))
381
+ return;
382
+ attempted.add(href);
383
+ /** Routing: a refusal of ours, already carrying its code (`loader-url-refused`). */
231
384
  console.error(error.message);
232
385
  return;
233
386
  }
@@ -236,8 +389,11 @@ const autoloader = (rootDir, componentsDir, options) => {
236
389
  attempted.add(src);
237
390
  requested.add(tag);
238
391
  failed.set(tag, src);
392
+ const tries = retries.get(tag);
393
+ let imported = false;
239
394
  try {
240
- await import(/* @vite-ignore */ src);
395
+ await import(/* @vite-ignore */ tries === undefined ? src : /*@__NOINLINE__*/ retried(src, tries, element.ownerDocument));
396
+ imported = true;
241
397
  /**
242
398
  * **A module can import cleanly and still not define the tag**, and that used to be silent
243
399
  * forever: `whenDefined` never settles, so the `catch` below never runs, no event is
@@ -257,15 +413,23 @@ const autoloader = (rootDir, componentsDir, options) => {
257
413
  await Promise.resolve();
258
414
  await Promise.resolve();
259
415
  if (!customElements.get(tag)) {
260
- throw new Error(`imported ${src} but nothing defined <${tag}>. Check the tag name in that file matches ` +
261
- `the one in the markup, and that its \`customElements.define\` actually runs.`);
416
+ throw new Error(diagnostic('autoloader', `<${tag}> from ${src}`, 'autoloader-not-defined', true && PROSE['autoloader-not-defined'](tag)));
262
417
  }
263
418
  await customElements.whenDefined(tag);
264
419
  failed.delete(tag);
420
+ retries.delete(tag);
265
421
  watch(element);
266
422
  }
267
423
  catch (error) {
268
424
  requested.delete(tag);
425
+ /**
426
+ * A rejected import is retried from a fresh URL; one that loaded, or that defined its tag before its code threw,
427
+ * keeps its own, so its code never runs twice (see `retries`).
428
+ */
429
+ if (!imported && !customElements.get(tag))
430
+ retries.set(tag, retries.get(tag) ?? 0);
431
+ else
432
+ retries.delete(tag);
269
433
  /**
270
434
  * Reported as a DOM event as well as a console line, because a component that never arrives
271
435
  * is something an app may want to render around — a placeholder, a retry button, a report to
@@ -278,7 +442,7 @@ const autoloader = (rootDir, componentsDir, options) => {
278
442
  composed: true,
279
443
  detail: { tag, src, error, element },
280
444
  }));
281
- console.error(`[vera] autoloader: failed to load <${tag}> from ${src}:`, error);
445
+ console.error('%s', diagnostic('autoloader', `<${tag}>`, 'loader-import-failed', true && PROSE['loader-import-failed'](`<${tag}>`, src)), error);
282
446
  }
283
447
  };
284
448
  /** Loads one candidate, unless it has opted out. */
@@ -301,14 +465,12 @@ const autoloader = (rootDir, componentsDir, options) => {
301
465
  * One observer for every watched root. A node added anywhere inside one is examined itself and
302
466
  * then scanned, because a subtree may arrive whole — `innerHTML` on a container delivers one
303
467
  * added node holding any number of undefined elements.
304
- */
305
- /**
306
- * Created on first use, not at construction.
307
468
  *
308
- * `new MutationObserver(...)` in the constructor made `autoloader` throw in Node —
309
- * `MutationObserver is not defined` — so an app entry that wires the autoloader could not be
310
- * imported server-side at all. `@verajs/router` attaches its window listeners lazily for exactly
311
- * this reason and says so; the observed-discovery rewrite reintroduced the problem here.
469
+ * Created on first use, not at construction. `new MutationObserver(...)` in the constructor made
470
+ * `autoloader` throw in Node — `MutationObserver is not defined` — so an app entry that wires the
471
+ * autoloader could not be imported server-side at all. `@verajs/router` attaches its window
472
+ * listeners lazily for exactly this reason and says so; the observed-discovery rewrite
473
+ * reintroduced the problem here.
312
474
  */
313
475
  let observer;
314
476
  const observing = () => (observer ??= new MutationObserver((records) => {
@@ -347,7 +509,8 @@ const autoloader = (rootDir, componentsDir, options) => {
347
509
  * to be cheap when there is nothing to do: an attribute read, then a `WeakSet` check. The scan
348
510
  * happens once, when the observation starts — everything after that arrives as a mutation.
349
511
  *
350
- * @param element The element to watch for undefined custom elements within
512
+ * @param target The element or shadow root to watch for undefined custom elements within, or the document for
513
+ * every marked host on the page
351
514
  */
352
515
  const watch = (target = document) => {
353
516
  /**
@@ -360,7 +523,7 @@ const autoloader = (rootDir, componentsDir, options) => {
360
523
  * shape of a function that already exists it costs almost nothing, can be called again whenever
361
524
  * new markup lands, and leaves `autoloader` free of side effects.
362
525
  *
363
- * A document is recognised by `nodeType`, not by having a `body`. `document.body` is null until
526
+ * A document is recognized by `nodeType`, not by having a `body`. `document.body` is null until
364
527
  * the parser reaches it, so an `autoload()` from a classic or `async` module script in `<head>`
365
528
  * fell straight through this branch and the document was treated as a root to watch — observing
366
529
  * `document` itself, `subtree: true`. That is precisely the shape this module exists to avoid
@@ -403,13 +566,34 @@ const autoloader = (rootDir, componentsDir, options) => {
403
566
  */
404
567
  const retry = (element) => {
405
568
  const tag = element.localName;
406
- requested.delete(tag);
569
+ /** Defined after all (a module that defined its tag, then threw): the element has upgraded, so watch it instead. */
570
+ if (customElements.get(tag)) {
571
+ failed.delete(tag);
572
+ retries.delete(tag);
573
+ watch(element);
574
+ return;
575
+ }
576
+ /**
577
+ * Still loading (a retry button pressed twice): the import in flight answers for both presses. Clearing its guards
578
+ * here would import a second fresh URL, run the module twice and throw at its second `define`.
579
+ */
580
+ if (requested.has(tag))
581
+ return;
407
582
  const src = failed.get(tag);
408
583
  if (src)
409
584
  attempted.delete(src);
410
585
  failed.delete(tag);
586
+ const tries = retries.get(tag);
587
+ if (tries !== undefined)
588
+ retries.set(tag, tries + 1);
411
589
  load(element, tag);
412
590
  };
591
+ /**
592
+ * `name` goes through `defineProperty` because a function's own `name` is non-writable, so
593
+ * `Object.assign` throws in strict mode — and the descriptor's `name` is what the duplicate-
594
+ * priority warning quotes, so leaving it as `"watch"` would name the wrong thing.
595
+ */
596
+ Object.defineProperty(watch, 'name', { value: '@verajs/autoloader', configurable: true });
413
597
  /**
414
598
  * The instance is also its own `wire` descriptor, so configuring the autoloader and installing it
415
599
  * are one call:
@@ -424,12 +608,6 @@ const autoloader = (rootDir, componentsDir, options) => {
424
608
  *
425
609
  * Priority 75 runs it *after* the renderer at 50, because it scans what the render just produced.
426
610
  */
427
- /**
428
- * `name` goes through `defineProperty` because a function's own `name` is non-writable, so
429
- * `Object.assign` throws in strict mode — and the descriptor's `name` is what the duplicate-
430
- * priority warning quotes, so leaving it as `"watch"` would name the wrong thing.
431
- */
432
- Object.defineProperty(watch, 'name', { value: '@verajs/autoloader', configurable: true });
433
611
  return Object.assign(watch, {
434
612
  url,
435
613
  retry,
@@ -441,28 +619,18 @@ const autoloader = (rootDir, componentsDir, options) => {
441
619
  });
442
620
  };
443
621
 
622
+ /** The refusals this loader throws itself — already coded, so `load` forwards them as they are (routing). */
623
+ const ours = new WeakSet();
624
+ const refuse = (message) => {
625
+ const error = new Error(message);
626
+ ours.add(error);
627
+ return error;
628
+ };
444
629
  /** The name grammar. An attribute tail that is not a plausible directive name is declined —
445
630
  * which also means it never becomes a URL. */
446
631
  const SAFE_NAME = /^[a-z][a-z0-9-]*$/;
447
632
  const directiveLoader = (rootDir, directivesDir, options) => {
448
- if (!rootDir)
449
- throw new Error('directiveLoader: rootDir is required (usually import.meta.url)');
450
- if (true ) {
451
- try {
452
- new URL('.', rootDir);
453
- }
454
- catch {
455
- throw new Error(`directiveLoader: rootDir must be an absolute URL, and "${rootDir}" is not. ` +
456
- `Pass import.meta.url — a relative path has nothing to resolve against.`);
457
- }
458
- if (options)
459
- for (const key of Object.keys(options))
460
- if (key !== 'extension' && key !== 'alias' && key !== 'resolve')
461
- console.warn(`[vera] directiveLoader: \`${key}\` is not an option, so it was ignored. ` +
462
- `The options are extension, alias and resolve.`);
463
- }
464
- const base = new URL('.', rootDir).href;
465
- const extension = `.${(options?.extension ?? '.js').replace(/^\./, '')}`;
633
+ const [base, extension] = entry('directiveLoader', rootDir, options, ['extension', 'alias', 'resolve']);
466
634
  const alias = options?.alias;
467
635
  const resolve = options?.resolve;
468
636
  const dir = (directivesDir ?? '.').replace(/\/+$/, '') || '.';
@@ -476,7 +644,7 @@ const directiveLoader = (rootDir, directivesDir, options) => {
476
644
  */
477
645
  const url = (name) => {
478
646
  if (!SAFE_NAME.test(name)) {
479
- throw new Error(`directiveLoader: "${name}" is not a directive name this will resolve.`);
647
+ throw refuse(misuse('directiveLoader', 'directive-loader-name', true && PROSE['directive-loader-name'](name)));
480
648
  }
481
649
  const target = alias?.[name] ?? (resolve ? resolve(name, dir) : `${dir}/${name}${extension}`);
482
650
  const href = new URL(target, rootDir).href;
@@ -488,7 +656,7 @@ const directiveLoader = (rootDir, directivesDir, options) => {
488
656
  * execution and the entry's directory is the stated bound.
489
657
  */
490
658
  if (!href.startsWith(base)) {
491
- throw new Error(`directiveLoader: refused ${href} for "${name}" — resolves outside ${base}`);
659
+ throw refuse(diagnostic('directiveLoader', `"${name}" ${href}`, 'loader-url-refused', true && PROSE['loader-url-refused'](`it resolves outside ${base}`)));
492
660
  }
493
661
  return href;
494
662
  };
@@ -503,18 +671,28 @@ const directiveLoader = (rootDir, directivesDir, options) => {
503
671
  src = url(name);
504
672
  }
505
673
  catch (error) {
506
- console.error(`[vera] ${error.message}`);
674
+ /**
675
+ * Ours (already coded) is forwarded as it is — routing; anything else is the caller's `resolve` throwing, which
676
+ * can throw any value at all, so it is formatted by what never throws.
677
+ */
678
+ if (ours.has(error))
679
+ console.error(error.message);
680
+ else
681
+ console.error(diagnostic('directiveLoader', `"${name}": ${thrownMessage(error)}`, 'loader-resolve-threw', true && PROSE['loader-resolve-threw']()));
507
682
  return false;
508
683
  }
509
684
  /**
510
685
  * The import IS the claim. Success means "the module ran" — whether it registered the name
511
686
  * is the ASKER's check, because only the asker owns the registry; a module that loads and
512
- * registers nothing earns `loader-loaded-nothing` there, with this URL in the story via the
513
- * console line below.
687
+ * registers nothing earns `loader-loaded-nothing` there.
688
+ *
689
+ * A failure is the ASKER's to report too, and this prints nothing (2026-10-09): one failed import used to say two
690
+ * lines — this one with the URL and the error, the engine's with the directive and its elements. The engine now
691
+ * says one, asking `url` for the address and forwarding the import's error; a direct caller reads the address in
692
+ * the rejection's message and the import's own error as its `cause` — the standard shape.
514
693
  */
515
694
  const request = import(/* @vite-ignore */ src).catch((error) => {
516
- console.error(`[vera] directiveLoader: failed to load "${name}" from ${src}:`, error);
517
- throw error;
695
+ throw new Error(src, { cause: error });
518
696
  });
519
697
  claimed.set(name, request);
520
698
  return request;