@webjsdev/core 0.7.50 → 0.7.51

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 (57) hide show
  1. package/dist/webjs-core-browser.js +5 -5
  2. package/dist/webjs-core-browser.js.map +3 -3
  3. package/dist/webjs-core-testing.js +20 -20
  4. package/dist/webjs-core-testing.js.map +3 -3
  5. package/dist/webjs-core.js +7 -7
  6. package/dist/webjs-core.js.map +3 -3
  7. package/index-browser.js +1 -1
  8. package/index.d.ts +1 -1
  9. package/index.js +1 -1
  10. package/package.json +1 -1
  11. package/src/component/lifecycle.js +1481 -0
  12. package/src/component/reactive.js +171 -0
  13. package/src/component/server-element.js +248 -0
  14. package/src/component.js +2 -1896
  15. package/src/render-client/parts.js +2007 -0
  16. package/src/render-client/reconciler.js +388 -0
  17. package/src/render-client/template-compiler.js +525 -0
  18. package/src/render-client.js +1 -2938
  19. package/src/render-server/attrs.js +160 -0
  20. package/src/render-server/dsd.js +445 -0
  21. package/src/render-server/html-scan.js +402 -0
  22. package/src/render-server/slots.js +213 -0
  23. package/src/render-server/stream.js +163 -0
  24. package/src/render-server/template-renderer.js +923 -0
  25. package/src/render-server/text.js +163 -0
  26. package/src/render-server.js +6 -2405
  27. package/src/router-client/anchors.js +44 -0
  28. package/src/router-client/boundaries.js +221 -0
  29. package/src/router-client/constants.js +187 -0
  30. package/src/router-client/diagnostics.js +377 -0
  31. package/src/router-client/dom-differ.js +709 -0
  32. package/src/router-client/dom-parse.js +150 -0
  33. package/src/router-client/events.js +139 -0
  34. package/src/router-client/fetch-apply.js +387 -0
  35. package/src/router-client/form-encoder.js +135 -0
  36. package/src/router-client/frames.js +329 -0
  37. package/src/router-client/head-merge.js +344 -0
  38. package/src/router-client/nav-error.js +105 -0
  39. package/src/router-client/navigator.js +781 -0
  40. package/src/router-client/prefetch.js +824 -0
  41. package/src/router-client/scroll.js +259 -0
  42. package/src/router-client/snapshot-cache.js +97 -0
  43. package/src/router-client/state.js +92 -0
  44. package/src/router-client/stream.js +206 -0
  45. package/src/router-client/swap.js +451 -0
  46. package/src/router-client/upgrade.js +261 -0
  47. package/src/router-client/view-transition.js +223 -0
  48. package/src/router-client.d.ts +10 -1
  49. package/src/router-client.js +75 -5345
  50. package/src/slot/assignment.js +304 -0
  51. package/src/slot/interception.js +558 -0
  52. package/src/slot/polyfills.js +365 -0
  53. package/src/slot/project.js +432 -0
  54. package/src/slot/sensors.js +303 -0
  55. package/src/slot/state.js +245 -0
  56. package/src/slot/symbols.js +85 -0
  57. package/src/slot.js +7 -2199
@@ -1,2405 +1,6 @@
1
- import { html, isTemplate } from './html.js';
2
- import { BINDING_PREFIXES } from './binding-prefixes.js';
3
- import { escapeText, escapeAttr } from './escape.js';
4
- import {
5
- assertNotFunctionActionAttr, assertNotFunctionReflectedActionProp,
6
- assertIdentifiableAction, bindFormActionStartTag, isBoundFormAction, resolveFormActionId,
7
- assertConvergentBoundForm, assertSubmitterHasNoName, assertSubmitterHasNoValue,
8
- assertSubmitterHasNoFormAttribute,
9
- assertSingleSubmitterAction, bindSubmitterStartTag, parseStartTagAttrs,
10
- isSubmitterReflectedProp, FORM_ACTION_FIELD,
11
- } from './form-action.js';
12
- import { lookup, lookupModuleUrl, allTags } from './registry.js';
13
- import { stylesToString, isCSS } from './css.js';
14
- import { isRepeat } from './repeat.js';
15
- import { isSuspense } from './suspense.js';
16
- import { unsafeHTML, isUnsafeHTML, isLive, isKeyed, isGuard, isTemplateContent, isRef, isCache, isUntil, isAsyncAppend, isAsyncReplace, isWatch } from './directives.js';
17
- import { stringify, parse } from './serialize.js';
18
- import { cspNonce } from './csp-nonce.js';
19
- import { readAttributeValue, resolveAttributeProperty } from './attribute-reader.js';
20
- import NAMED_ENTITIES, { LEGACY_NAMES } from './html-entities.js';
21
-
22
- /**
23
- * Render a TemplateResult (or any renderable value) to an HTML string.
24
- *
25
- * Async by design: template holes may be Promises, components' `render()`
26
- * methods may be async, and data-fetching inside nested components is
27
- * awaited before the final string is emitted.
28
- *
29
- * If `opts.suspenseCtx` is provided, Suspense boundaries encountered during
30
- * the render will push `{ id, promise }` into `opts.suspenseCtx.pending`
31
- * and their fallback HTML is emitted immediately. The caller is responsible
32
- * for streaming each resolved promise afterwards. Without a suspenseCtx,
33
- * Suspense still works but we fall back to emitting only the fallback
34
- * (the promise is dropped: appropriate for static pre-render).
35
- *
36
- * @typedef {{ pending: {id: string, promise: Promise<unknown>}[], nextId: number }} SuspenseCtx
37
- *
38
- * A boundary's enclosing form scope used to be recorded here and threaded back
39
- * in (#1207), because the page pipeline in `@webjsdev/server` drains
40
- * `ctx.pending` and re-renders each resolved child through a FRESH scan with no
41
- * view of the shell it belongs to, so a `<button formaction=${fn}>` inside a
42
- * bound form's Suspense boundary read as form-less and was refused. Gone with
43
- * #1307: a bound submitter carries its own `formmethod` and enctype, so no
44
- * renderer needs to know what encloses it and there is nothing left to thread.
45
- *
46
- * @param {unknown} value
47
- * @param {{ ssr?: boolean, suspenseCtx?: SuspenseCtx, dev?: boolean }} [opts]
48
- * @returns {Promise<string>}
49
- */
50
- export async function renderToString(value, opts = { ssr: true }) {
51
- const ctx = opts && opts.suspenseCtx;
52
- // The server `dev` flag drives prod-silence of SSR error states (#483).
53
- // `opts.dev` wins; else inherit a `dev` already stamped on the ctx (so a
54
- // streamed sub-context inherits it); back-fill the ctx so downstream renders
55
- // sharing it see the same flag. Undefined stays undefined (NODE_ENV fallback).
56
- const dev = opts && opts.dev !== undefined ? opts.dev : ctx && ctx.dev;
57
- if (ctx && ctx.dev === undefined && dev !== undefined) ctx.dev = dev;
58
- const html = await render(value, ctx);
59
- return opts && opts.ssr === false ? html : await injectDSD(html, ctx, [], dev);
60
- }
61
-
62
- /**
63
- * @param {unknown} value
64
- * @param {SuspenseCtx} [ctx]
65
- * @returns {Promise<string>}
66
- */
67
- async function render(value, ctx) {
68
- if (value == null || value === false || value === true) return '';
69
- if (value && typeof /** @type any */ (value).then === 'function') {
70
- value = await value;
71
- return render(value, ctx);
72
- }
73
- // unsafeHTML: inject raw HTML string without escaping.
74
- if (isUnsafeHTML(value)) {
75
- return String(/** @type any */ (value).value ?? '');
76
- }
77
- // live() on the server just unwraps and renders the inner value.
78
- if (isLive(value)) {
79
- return render(/** @type any */ (value).value, ctx);
80
- }
81
- // watch() on the server reads the signal once and inlines the
82
- // result. Subscription is a client-only concern; the SSR HTML
83
- // freezes a snapshot of the current value.
84
- if (isWatch(value)) {
85
- return render(/** @type any */ (value).signal.get(), ctx);
86
- }
87
- // keyed() on the server: render the wrapped template; key is client-only.
88
- if (isKeyed(value)) {
89
- return render(/** @type any */ (value).value, ctx);
90
- }
91
- // guard() on the server: always invoke the value function (no cache on SSR).
92
- if (isGuard(value)) {
93
- return render(/** @type any */ (value).fn(), ctx);
94
- }
95
- // templateContent() on the server: emit the template's innerHTML verbatim.
96
- if (isTemplateContent(value)) {
97
- const tpl = /** @type any */ (value).template;
98
- return String(tpl?.innerHTML ?? '');
99
- }
100
- // ref() on the server: no-op (no DOM yet). Returns empty string.
101
- if (isRef(value)) {
102
- return '';
103
- }
104
- // cache() on the server: pass-through to the inner value.
105
- if (isCache(value)) {
106
- return render(/** @type any */ (value).value, ctx);
107
- }
108
- // until() on the server: render the first synchronous candidate, or
109
- // await the first Promise to settle when all candidates are Promises.
110
- // Rejections are swallowed (treated as "no value"); if every candidate
111
- // rejects, render empty rather than crash the SSR pipeline.
112
- if (isUntil(value)) {
113
- const args = /** @type any */ (value).args;
114
- for (const a of args) {
115
- if (!a || typeof (/** @type any */ (a).then) !== 'function') {
116
- return render(a, ctx);
117
- }
118
- }
119
- if (args.length > 0) {
120
- try {
121
- const winner = await Promise.race(args.map((p) => Promise.resolve(p).catch(() => undefined)));
122
- return render(winner, ctx);
123
- } catch {
124
- return '';
125
- }
126
- }
127
- return '';
128
- }
129
- // asyncAppend / asyncReplace on the server: render empty. Full
130
- // streaming is a follow-up; pages should use Suspense for streaming.
131
- if (isAsyncAppend(value) || isAsyncReplace(value)) {
132
- return '';
133
- }
134
- if (Array.isArray(value)) {
135
- const parts = await Promise.all(value.map((v) => render(v, ctx)));
136
- return parts.join('');
137
- }
138
- if (isRepeat(value)) {
139
- const r = /** @type any */ (value);
140
- const parts = await Promise.all(r.items.map((it, i) => render(r.templateFn(it, i), ctx)));
141
- return parts.join('');
142
- }
143
- if (isSuspense(value)) {
144
- const s = /** @type any */ (value);
145
- const fallback = await render(s.fallback, ctx);
146
- if (ctx) {
147
- const id = `s${ctx.nextId++}`;
148
- ctx.pending.push({ id, promise: Promise.resolve(s.children) });
149
- return `<webjs-boundary id="${id}">${fallback}</webjs-boundary>`;
150
- }
151
- return fallback;
152
- }
153
- if (isTemplate(value)) return renderTemplate(/** @type any */ (value), ctx);
154
- return escapeText(String(value));
155
- }
156
-
157
- /**
158
- * @param {import('./html.js').TemplateResult} tr
159
- * @param {SuspenseCtx} [ctx]
160
- * @returns {Promise<string>}
161
- */
162
- async function renderTemplate(tr, ctx) {
163
- const { strings, values } = tr;
164
- let out = '';
165
- let state = 'text';
166
- let attrName = '';
167
- let attrStart = 0;
168
- let attrQuote = '';
169
- let commentDashes = 0;
170
- let currentTag = ''; // lowercased tag name currently being parsed
171
- let rawTail = ''; // rolling lowercased tail, tracks </script>/</style>
172
- let tagStart = -1; // index in `out` of the `<` opening the current tag
173
- /** @type {string | null} */
174
- let pendingActionId = null; // identity of a bound form action, until the tag closes
175
- /** @type {string | null} */
176
- let pendingSubmitterTag = null; // tag of a bound submitter, until it closes
177
- // Shapes on the CURRENT start tag that a bound form may not carry (#1155).
178
- // Collected as the tag is scanned and judged at its `>`, because the action
179
- // hole may come after them.
180
- let pendingActionCount = 0;
181
- /** @type {string[]} */
182
- let pendingPropAttrs = [];
183
- /** @type {string[]} */
184
- let pendingSubmitterProps = [];
185
- let isCloseTag = false;
186
-
187
- // A bound `action=${fn}` is committed at its hole, but the edits it implies
188
- // (forcing `method` / `enctype`, and the hidden identity field) are only
189
- // possible once the whole start tag is known: an attribute the author wrote
190
- // AFTER the action hole still counts, and the hidden field belongs INSIDE
191
- // the form, after the `>`. So the hole records the identity and this runs at
192
- // the `>`, rewriting the start tag that was just emitted.
193
- const closeBoundFormTag = () => {
194
- // Reset per tag whether or not this one was bound, so a later form is never
195
- // judged on an earlier tag's shapes.
196
- const propAttrs = pendingPropAttrs;
197
- const submitterProps = pendingSubmitterProps;
198
- const duplicateAction = pendingActionCount > 1;
199
- const submitterTag = pendingSubmitterTag;
200
- pendingPropAttrs = [];
201
- pendingSubmitterProps = [];
202
- pendingActionCount = 0;
203
- pendingSubmitterTag = null;
204
- if (pendingActionId != null) {
205
- assertConvergentBoundForm({ duplicateAction, propAttrs });
206
- const bound = bindFormActionStartTag(out.slice(tagStart), pendingActionId);
207
- out = out.slice(0, tagStart) + bound.tag + bound.hidden;
208
- pendingActionId = null;
209
- }
210
- if (submitterTag != null) {
211
- // #1307: a bound submitter carries its WHOLE submission, so `formmethod`
212
- // and the enctype are injected onto the button here rather than inherited
213
- // from a form this scan may not even be able to see. That is what removed
214
- // the enclosing-form question, and with it the four-state scope tracking
215
- // that could never answer it for a button inside a component.
216
- out = out.slice(0, tagStart)
217
- + bindSubmitterStartTag(out.slice(tagStart), submitterTag, { duplicateAction, propAttrs: submitterProps });
218
- }
219
- };
220
- // #1155: a `.method` / `.enctype` / `.encoding` prop on a form is dropped
221
- // here but applied for real in the browser, where all three are reflected IDL
222
- // attributes, so a bound form carrying one submits differently with JS than
223
- // without it. Recorded and refused at the `>`, once the tag's action hole is
224
- // known.
225
- const notePropAttr = (name, tag) => {
226
- const t = String(tag).toLowerCase();
227
- if (t === 'button' || t === 'input') {
228
- // #1207: the submitter twin. `name` / `value` / `formAction` / `formMethod`
229
- // / `formEnctype` all reflect on a submitter, so a `.prop` spelling is
230
- // dropped here and written to the attribute in the browser.
231
- if (isSubmitterReflectedProp(name)) pendingSubmitterProps.push(String(name));
232
- return;
233
- }
234
- if (t !== 'form') return;
235
- let n = String(name).toLowerCase();
236
- if (n === 'encoding') n = 'enctype';
237
- if (n === 'method' || n === 'enctype') pendingPropAttrs.push(String(name));
238
- };
239
- const noteActionHole = (name, tag) => {
240
- const t = String(tag).toLowerCase();
241
- const n = String(name).toLowerCase();
242
- if ((t === 'form' && n === 'action') ||
243
- ((t === 'button' || t === 'input') && n === 'formaction')) {
244
- pendingActionCount += 1;
245
- }
246
- };
247
-
248
- // Every `>` in a tag state funnels through here, so the bound-form bookkeeping
249
- // stays in one place rather than at five call sites.
250
- //
251
- // `allowRawtext` is NOT a preference. Only two of those five call sites ever
252
- // entered rawtext: the `tag-name` and `in-tag` exits. The three attribute
253
- // exits (`attr-name`, `after-eq`, `attr-unquoted`) always forced `text`, so
254
- // `<script defer>` and `<style media=print>`, whose start tags end on a bare
255
- // or unquoted attribute, escaped their bodies. Switching them to rawtext here
256
- // would silently turn `<script defer>${userInput}</script>` from escaped into
257
- // raw script, which is an XSS mitigation this change has no business
258
- // touching. Whether that escaping is the RIGHT behaviour is a separate
259
- // question from #1207; this preserves it exactly.
260
- const handleTagEnd = (allowRawtext) => {
261
- closeBoundFormTag();
262
- isCloseTag = false;
263
- state = allowRawtext && isRawtextTag(currentTag) ? 'rawtext' : 'text';
264
- if (state === 'rawtext') rawTail = '';
265
- };
266
-
267
- for (let i = 0; i < strings.length; i++) {
268
- const s = strings[i];
269
- for (let j = 0; j < s.length; j++) {
270
- const c = s[j];
271
- switch (state) {
272
- case 'text':
273
- out += c;
274
- if (c === '<') { state = 'tag-open'; tagStart = out.length - 1; isCloseTag = false; }
275
- break;
276
- case 'tag-open':
277
- out += c;
278
- if (c === '!') state = 'bang-1';
279
- else if (c === '/') { state = 'tag-name'; currentTag = ''; isCloseTag = true; }
280
- else if (/[a-zA-Z]/.test(c)) { state = 'tag-name'; currentTag = c.toLowerCase(); }
281
- else state = 'text';
282
- break;
283
- case 'bang-1':
284
- out += c;
285
- state = c === '-' ? 'bang-dash' : 'tag-name';
286
- break;
287
- case 'bang-dash':
288
- out += c;
289
- if (c === '-') { state = 'comment'; commentDashes = 0; }
290
- else state = 'tag-name';
291
- break;
292
- case 'comment':
293
- out += c;
294
- if (c === '-') commentDashes += 1;
295
- else if (c === '>' && commentDashes >= 2) { state = 'text'; commentDashes = 0; }
296
- else commentDashes = 0;
297
- break;
298
- case 'tag-name':
299
- out += c;
300
- if (c === '>') {
301
- handleTagEnd(true);
302
- } else if (/\s/.test(c)) state = 'in-tag';
303
- else currentTag += c.toLowerCase();
304
- break;
305
- case 'in-tag':
306
- out += c;
307
- if (c === '>') {
308
- handleTagEnd(true);
309
- } else if (!/\s/.test(c) && c !== '/') {
310
- state = 'attr-name';
311
- attrName = c;
312
- attrStart = out.length - 1;
313
- }
314
- break;
315
- case 'rawtext':
316
- out += c;
317
- rawTail = (rawTail + c.toLowerCase()).slice(-9);
318
- if (rawTail.endsWith('</script>') || rawTail.endsWith('</style>')) {
319
- state = 'text';
320
- rawTail = '';
321
- currentTag = '';
322
- }
323
- break;
324
- case 'attr-name':
325
- if (c === '=') { state = 'after-eq'; out += c; }
326
- else if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; out += c; }
327
- else if (c === '>') { state = 'text'; attrName = ''; out += c; handleTagEnd(false); }
328
- else { attrName += c; out += c; }
329
- break;
330
- case 'after-eq':
331
- if (c === '"' || c === "'") { state = 'attr-quoted'; attrQuote = c; out += c; }
332
- else if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; out += c; }
333
- else if (c === '>') { state = 'text'; attrName = ''; out += c; handleTagEnd(false); }
334
- else { state = 'attr-unquoted'; out += c; }
335
- break;
336
- case 'attr-unquoted':
337
- if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; out += c; }
338
- else if (c === '>') { state = 'text'; attrName = ''; out += c; handleTagEnd(false); }
339
- else out += c;
340
- break;
341
- case 'attr-quoted':
342
- out += c;
343
- if (c === attrQuote) { state = 'in-tag'; attrName = ''; }
344
- break;
345
- }
346
- }
347
-
348
- if (i < values.length) {
349
- let val = values[i];
350
- // Resolve promises anywhere in the value graph.
351
- if (val && typeof /** @type any */ (val).then === 'function') {
352
- val = await val;
353
- }
354
- if (state === 'comment') {
355
- // Holes inside <!-- comments --> are emitted raw (no escaping; comments
356
- // are inert and not rendered by browsers).
357
- out += String(val ?? '');
358
- commentDashes = 0;
359
- } else if (state === 'rawtext') {
360
- // Inside <script> / <style>: emit the value as-is (no HTML escaping).
361
- // Author is responsible for not closing the tag with user-controlled
362
- // data: the usual caveat for CSS/JS interpolation.
363
- out += String(val ?? '');
364
- rawTail = '';
365
- } else if (state === 'text') {
366
- out += await render(val, ctx);
367
- } else if (state === 'after-eq') {
368
- const prefix = attrName[0];
369
- const name = attrName.slice(1);
370
- const kind = BINDING_PREFIXES[prefix];
371
- if (kind === 'event') {
372
- // Event listener. Client-only behaviour, drop at SSR.
373
- out = out.slice(0, attrStart);
374
- state = 'in-tag';
375
- attrName = '';
376
- } else if (kind === 'prop') {
377
- // Property binding. Only meaningful on custom elements (which
378
- // have a hyphen in the tag name and a WebComponent subclass
379
- // that knows how to apply + strip data-webjs-prop-* on
380
- // hydration). For native elements (`<input .value=${v}>`)
381
- // the attribute would be dead weight (nothing consumes it),
382
- // so we drop it the same way the old behaviour did. The
383
- // client renderer still applies the property when the
384
- // template runs in the browser, which is the only place a
385
- // page-level `.prop` on a native element could have set the
386
- // property to begin with.
387
- out = out.slice(0, attrStart);
388
- // `<webjs-suspense .fallback=${html`...`}>` (#471). This element is
389
- // defined only in the browser, so the injectDSD walk skips it
390
- // (`lookup(tag)` finds no class) and no server-side instance runs
391
- // consumePropAttrs. A normal data-webjs-prop-* binding would then
392
- // land at connectedCallback, too late for the streaming placeholder.
393
- // So render the fallback to HTML now and carry it as
394
- // data-webjs-fallback, which the injectDSD streaming pre-pass reads
395
- // as the boundary placeholder. (The value itself would serialize
396
- // fine: a TemplateResult is a plain {strings, values} object.)
397
- if (currentTag === 'webjs-suspense' && name === 'fallback') {
398
- const fbHtml = await render(val, ctx);
399
- out += `data-webjs-fallback="${escapeAttr(fbHtml)}"`;
400
- state = 'in-tag';
401
- attrName = '';
402
- continue;
403
- }
404
- if (!currentTag.includes('-')) {
405
- // A native element's `.prop` is dropped at SSR, so this path never
406
- // leaked here. It still refuses a function where the property is a
407
- // REFLECTED IDL attribute (`.action` on a form, `.formAction` on a
408
- // button or input), so the rule does not depend on which renderer
409
- // sees it first: the client sets that property for real and the
410
- // reflection writes the source into the DOM. A page that renders
411
- // clean on the server and throws on hydration is a worse failure
412
- // than one that refuses at the earliest point. Elsewhere the
413
- // property is a plain expando that reflects nothing, so refusing
414
- // it would be a false positive.
415
- assertNotFunctionReflectedActionProp(val, name, currentTag);
416
- notePropAttr(name, currentTag);
417
- state = 'in-tag';
418
- attrName = '';
419
- continue;
420
- }
421
- // `undefined` has no meaningful HTML representation. Drop
422
- // silently so the consumer falls back to its constructor
423
- // default. `null` is preserved because it's a real value
424
- // distinct from "not set".
425
- if (val === undefined) {
426
- state = 'in-tag';
427
- attrName = '';
428
- continue;
429
- }
430
- try {
431
- const encoded = await stringify(val);
432
- out += `data-webjs-prop-${kebabCase(name)}="${escapeAttr(encoded)}"`;
433
- } catch (e) {
434
- // Unserializable value (function, class instance with
435
- // private state, DOM node, etc.). Drop with a warning so
436
- // SSR does not crash. Same constraint as Next.js RSC.
437
- console.warn(
438
- `[webjs] property binding .${name} has an unserializable `
439
- + `value during SSR. Dropping. The browser will see the `
440
- + `property as undefined. Detail: ${e && e.message}`
441
- );
442
- }
443
- state = 'in-tag';
444
- attrName = '';
445
- } else if (kind === 'bool') {
446
- // Never leaked (a boolean binding stringifies nothing), but
447
- // `?action=${fn}` is meaningless in every case and refusing it keeps
448
- // the rule true for every sigil rather than only the quoted ones.
449
- assertNotFunctionActionAttr(val, name, currentTag);
450
- out = out.slice(0, attrStart);
451
- if (val) out += `${name}=""`;
452
- state = 'in-tag';
453
- attrName = '';
454
- } else if (isBoundFormAction(val, attrName, currentTag)) {
455
- noteActionHole(attrName, currentTag);
456
- if (currentTag === 'form') {
457
- // #1155: the form-level binding. Drop the `action=` attribute
458
- // entirely so the form posts to the page's own url (an omitted
459
- // attribute, not `action=""`, which the spec calls a conformance
460
- // error), and remember the identity so the `>` can force the
461
- // submission attributes and emit the hidden field.
462
- pendingActionId = assertIdentifiableAction(await resolveFormActionId(val), currentTag);
463
- // Trailing whitespace goes with the attribute: every injected
464
- // attribute carries its own leading space, so keeping the old one
465
- // would double it in the emitted tag.
466
- out = out.slice(0, attrStart).replace(/\s+$/, '');
467
- } else {
468
- // #1207: the submitter binding. The identity replaces the
469
- // `formaction=` hole IN PLACE with the button's own name/value
470
- // pair, the one channel a browser submits for the pressed button
471
- // alone. No `formaction` url is emitted, so the submission targets
472
- // whatever the FORM targets, and a form-level identity is simply
473
- // overridden by this later entry.
474
- //
475
- // Refused here rather than at the `>` only where the answer cannot
476
- // change later: an attribute written BEFORE the hole is already in
477
- // `out`. Everything else waits for the close,
478
- // where `assertSubmitterStartTag` sees the whole tag.
479
- // A second binding hole on this same tag, refused here so the
480
- // author gets the duplicate message rather than a confusing
481
- // complaint about the `name` the FIRST hole just injected.
482
- assertSingleSubmitterAction(pendingSubmitterTag != null, currentTag);
483
- const attrs = parseStartTagAttrs(out.slice(tagStart));
484
- if (attrs.has('name')) assertSubmitterHasNoName(attrs.get('name') || '', currentTag, false);
485
- if (attrs.has('value')) assertSubmitterHasNoValue(currentTag);
486
- if (attrs.has('form')) assertSubmitterHasNoFormAttribute(currentTag);
487
- const subId = assertIdentifiableAction(await resolveFormActionId(val), currentTag);
488
- pendingSubmitterTag = currentTag;
489
- out = out.slice(0, attrStart) + `name="${FORM_ACTION_FIELD}" value="${escapeAttr(subId)}"`;
490
- }
491
- state = 'in-tag';
492
- attrName = '';
493
- } else {
494
- // A second `action` hole that resolved to a plain url still COUNTS,
495
- // so the duplicate refusal fires whatever the values happen to be.
496
- noteActionHole(attrName, currentTag);
497
- // #1154: never stringify a function into action=/formaction= (it
498
- // would serialize a server action's source into the served HTML).
499
- assertNotFunctionActionAttr(val, attrName, currentTag);
500
- out += `"${escapeAttr(String(val ?? ''))}"`;
501
- state = 'in-tag';
502
- attrName = '';
503
- }
504
- } else if (state === 'attr-quoted' || state === 'attr-unquoted') {
505
- // Same guard for a hole inside a quoted/unquoted value, the
506
- // `action="${fn}"` and mixed `action="/x/${fn}"` shapes (#1154).
507
- assertNotFunctionActionAttr(val, attrName, currentTag);
508
- out += escapeAttr(String(val ?? ''));
509
- }
510
- }
511
- }
512
- return out;
513
- }
514
-
515
- // Browser-only names whose absence during SSR produces a recognisable error.
516
- // Mirrors the `no-browser-globals-in-render` webjs check rule, which catches
517
- // these at edit time; this turns the runtime SSR crash into the same guidance.
518
- const SSR_BROWSER_GLOBALS = new Set([
519
- 'document', 'window', 'localStorage', 'sessionStorage', 'navigator',
520
- 'matchMedia', 'requestAnimationFrame', 'getComputedStyle',
521
- 'IntersectionObserver', 'MutationObserver', 'ResizeObserver',
522
- ]);
523
- // Attribute methods (get/set/has/remove/toggleAttribute), the event methods
524
- // (add/removeEventListener, dispatchEvent), and attachInternals are backed by
525
- // the server-side element shim and work at SSR, so they are NOT listed here.
526
- // What remains is the genuinely browser-only HTMLElement surface that still
527
- // has no server stand-in and throws at SSR.
528
- const SSR_HTMLELEMENT_METHODS = new Set([
529
- 'attachShadow', 'querySelector', 'querySelectorAll',
530
- 'getBoundingClientRect', 'focus', 'blur', 'scrollIntoView',
531
- ]);
532
-
533
- /**
534
- * If `e` is the recognisable failure of touching a browser-only API during
535
- * SSR (a `ReferenceError` for a browser global, or a `TypeError` calling an
536
- * HTMLElement method that does not exist on the bare server-side instance),
537
- * return an actionable, member-naming hint; otherwise null.
538
- * @param {unknown} e
539
- * @returns {string | null}
540
- */
541
- function browserMemberHint(e) {
542
- const msg = e && typeof (/** @type any */ (e).message) === 'string' ? /** @type any */ (e).message : '';
543
- // Match on a word boundary, NOT end-of-string: V8 (Node) ends the message at
544
- // "is not defined" / "is not a function", but JSC (Bun) appends a detail
545
- // clause (e.g. ". (In '({}).querySelector(\"p\")', '...' is undefined)"), so an
546
- // anchored `$` would miss the Bun message and drop the actionable hint.
547
- let m = /^(\w+) is not defined\b/.exec(msg);
548
- if (e instanceof ReferenceError && m && SSR_BROWSER_GLOBALS.has(m[1])) {
549
- return `\`${m[1]}\` is a browser-only global and is undefined during SSR.`;
550
- }
551
- m = /\.(\w+) is not a function\b/.exec(msg);
552
- if (e instanceof TypeError && m && SSR_HTMLELEMENT_METHODS.has(m[1])) {
553
- return `\`${m[1]}\` is an HTMLElement method that does not exist on the server-side component instance during SSR.`;
554
- }
555
- return null;
556
- }
557
-
558
- /** True in a production build (no dev error surfacing). */
559
- function isProd() {
560
- return typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production';
561
- }
562
-
563
- /**
564
- * Default component-scoped error state for an async/sync render that threw
565
- * during SSR, used when the component does not define renderError() (#469).
566
- * Dev surfaces the tag + message loudly so the failure is obvious; prod
567
- * renders an empty (silent, isolated) element so no internal detail leaks.
568
- *
569
- * The prod-silence signal is the SERVER's `dev` flag, threaded through the SSR
570
- * render context (#483). WebJs keys prod on the CLI `dev` flag, not `NODE_ENV`,
571
- * and `webjs start` does not export `NODE_ENV=production`, so a bare prod launch
572
- * would otherwise leak the message. When `dev` is undefined (a context-free
573
- * `renderToString` with no server signal, e.g. a bare unit test) it falls back
574
- * to `isProd()` / `NODE_ENV`, preserving the prior behaviour for that path.
575
- *
576
- * @param {string} tag
577
- * @param {Error} err
578
- * @param {boolean} [dev] server dev flag; undefined falls back to NODE_ENV
579
- * @returns {unknown} a TemplateResult (dev) or '' (prod)
580
- */
581
- function defaultSSRErrorTemplate(tag, err, dev) {
582
- const surface = dev === undefined ? !isProd() : !!dev;
583
- if (!surface) return '';
584
- const msg = err && err.message ? err.message : String(err);
585
- return html`<div data-webjs-error="${tag}" style="border:1px solid #f5c2c7;background:#f8d7da;color:#842029;padding:8px 12px;border-radius:6px;font:13px/1.4 system-ui,sans-serif">
586
- <strong>&lt;${tag}&gt; failed to render</strong>
587
- <div style="margin-top:4px;white-space:pre-wrap">${msg}</div>
588
- </div>`;
589
- }
590
-
591
- /**
592
- * Index just past the end of the comment starting at `start`, or -1 if it is
593
- * unterminated. Shared so every scanner that has to decide where a comment
594
- * stops agrees, including on the spec short forms.
595
- *
596
- * @param {string} html
597
- * @param {number} start index of the `<` of `<!--`
598
- * @returns {number}
599
- */
600
- function endOfComment(html, start) {
601
- let p = start + 4;
602
- // `<!-->` and `<!--->` are comments whose data is empty (spec short forms).
603
- if (html[p] === '>') return p + 1;
604
- if (html.startsWith('->', p)) return p + 2;
605
- while (p < html.length) {
606
- // `--!>` is the spec's "abrupt closing" form and closes just like `-->`.
607
- if (html.startsWith('-->', p)) return p + 3;
608
- if (html.startsWith('--!>', p)) return p + 4;
609
- p += 1;
610
- }
611
- return -1;
612
- }
613
-
614
- /**
615
- * Index of the `</script` that really closes a `<script>` whose content starts
616
- * at `from`, or -1 when unterminated (#1134).
617
- *
618
- * Script data is not plain raw text: once the content contains `<!--` followed
619
- * by `<script`, the tokenizer is in the script-data-double-escaped state, where
620
- * a `</script>` is TEXT (it only steps back to the escaped state) and the
621
- * element ends at the NEXT `</script>`. The legacy comment-wrapped inline
622
- * script that document.writes a script tag is the pattern that produces this.
623
- * Stopping at the first `</script>` there re-opened the original #1128 bug in
624
- * the one element the scanner most explicitly claims to handle.
625
- *
626
- * @param {string} html
627
- * @param {number} from index just past the opening tag's `>`
628
- * @returns {number}
629
- */
630
- function endOfScriptContent(html, from) {
631
- const re = /<!--|-->|<\/script(?=[\s/>])|<script(?=[\s/>])/gi;
632
- re.lastIndex = from;
633
- let escaped = false;
634
- let dbl = false;
635
- let m;
636
- while ((m = re.exec(html)) !== null) {
637
- const t = m[0];
638
- if (t === '<!--') {
639
- // The token's own trailing `--` puts the tokenizer in a dash-dash state
640
- // REGARDLESS of what state it was in (`<!` are inert bytes in escaped and
641
- // double-escaped states too), and every dash-dash state exits straight
642
- // back to plain script data on `>`. So `<!-->`, `<!--->`, and any dash
643
- // run followed by `>` clear BOTH flags: entering fresh it cancels the
644
- // escape before it starts, and inside an escaped or double-escaped body
645
- // it is the exit a browser honours, after which the element ends at the
646
- // next `</script>`.
647
- let q = m.index + 4;
648
- while (html[q] === '-') q += 1;
649
- if (html[q] === '>') { escaped = false; dbl = false; re.lastIndex = q + 1; }
650
- else if (!escaped) escaped = true;
651
- }
652
- else if (t === '-->') { escaped = false; dbl = false; }
653
- else if (t[1] === '/') {
654
- if (dbl) dbl = false;
655
- else return m.index;
656
- } else if (escaped) dbl = true;
657
- }
658
- return -1;
659
- }
660
-
661
- /**
662
- * Byte ranges of `html` where a tag-shaped match is NOT an element (#1128).
663
- *
664
- * The element scanners below match tags with a flat regex over already-
665
- * assembled markup, which has no notion of an HTML context. So a registered tag
666
- * name written inside a comment used to be constructed and rendered as a real
667
- * element, and the replacement consumed the rest of the comment INCLUDING its
668
- * closing `-->`, leaving an unterminated comment that swallowed every following
669
- * byte. Whether it happened depended on whether the name in the comment was a
670
- * registered component, which is what made it look random.
671
- *
672
- * This is a single left-to-right pass rather than a search for `<!--`, because
673
- * the naive version introduces failures worse than the bug: an `<!--` inside an
674
- * attribute value (`title="use <!-- here"`) or inside RCDATA would open a region
675
- * that never closes, and every component after it would silently stop rendering.
676
- * Deciding that requires knowing the context, which means tokenizing, so the
677
- * pass tracks the same states the HTML parser does for these purposes:
678
- *
679
- * - **Comments**, including the spec's short forms. `<!-->` and `<!--->` close
680
- * immediately, `--!>` closes as well as `-->`, and an unterminated comment
681
- * runs to EOF, exactly as a browser would treat the same bytes.
682
- * - **Markup declarations and bogus comments** (`<!doctype …>`, `<![CDATA[…]]>`),
683
- * which end at the next `>`.
684
- * - **Tags**, consumed with their quoted attribute values, so `<` and `<!--`
685
- * inside an attribute are inert rather than context-changing.
686
- * - **Text-only elements**, whose content the HTML tokenizer never reads as
687
- * markup: raw text (`script`, `style`, `iframe`, `xmp`, `noembed`,
688
- * `noframes`, `plaintext`) and RCDATA (`textarea`, `title`). Their content is
689
- * returned as a skip range too, because a component tag inside a `<style>`
690
- * comment or an `<iframe>` fallback hit the identical markup-destroying path,
691
- * so excluding them would leave half the bug live.
692
- *
693
- * Two deliberate exclusions. `<template>` content IS parsed and legitimately
694
- * carries components (Declarative Shadow DOM and the streamed swap templates
695
- * both depend on that). `<noscript>` content is parsed as markup when
696
- * scripting is disabled, which for a progressive-enhancement framework is the
697
- * case that matters, so components inside it must keep rendering.
698
- *
699
- * @param {string} html
700
- * @returns {[number, number][]} ascending, non-overlapping `[start, end)` pairs
701
- */
702
- function inertRanges(html) {
703
- /** @type {[number, number][]} */
704
- const ranges = [];
705
- const n = html.length;
706
- let i = 0;
707
- while (i < n) {
708
- const lt = html.indexOf('<', i);
709
- if (lt === -1) break;
710
- if (html.startsWith('<!--', lt)) {
711
- const end = endOfComment(html, lt);
712
- const stop = end === -1 ? n : end;
713
- ranges.push([lt, stop]);
714
- i = stop;
715
- continue;
716
- }
717
- if (html.startsWith('<!', lt) || html.startsWith('<?', lt)) {
718
- // Doctype / bogus comment / processing instruction: ends at the next `>`.
719
- const close = html.indexOf('>', lt);
720
- const end = close === -1 ? n : close + 1;
721
- ranges.push([lt, end]);
722
- i = end;
723
- continue;
724
- }
725
- const name = /^<\/?([a-zA-Z][^\s/>]*)/.exec(html.slice(lt, lt + 64));
726
- if (!name) {
727
- // `</` followed by anything that is not an ASCII letter is the third
728
- // bogus-comment form (`</1`, `</<`, `</ `), which the spec also runs to
729
- // the next `>`. Without this branch the bytes after it are scanned as
730
- // markup and a tag inside gets instantiated, which is the original bug.
731
- if (html.startsWith('</', lt)) {
732
- const close = html.indexOf('>', lt);
733
- const end = close === -1 ? n : close + 1;
734
- ranges.push([lt, end]);
735
- i = end;
736
- continue;
737
- }
738
- i = lt + 1;
739
- continue;
740
- }
741
- // Consume the tag, honouring quoted attribute values so a `<` or `<!--`
742
- // inside one cannot be mistaken for markup.
743
- //
744
- // A quote only OPENS a value when it directly follows `=`. That condition
745
- // is load-bearing rather than pedantic: `escapeAttr` does not escape `'`,
746
- // so an interpolated apostrophe in a single-quoted attribute emits three
747
- // unbalanced quotes (`title='don't'`). Treating every quote as a delimiter
748
- // left the scanner stuck inside a value to EOF, which returned a truncated
749
- // range list and silently re-enabled this whole bug for the rest of the
750
- // page. A browser recovers at the `>`, and so does this: after the value
751
- // closes, the stray `'` is just an attribute-name character.
752
- let p = lt + 1;
753
- let quote = '';
754
- // `expectValue` is set by `=` and cleared by the first non-whitespace
755
- // character after it. Only THAT character can open a quoted value, which is
756
- // what the spec does: before-attribute-value reconsumes anything else in
757
- // attribute-value-unquoted state. Keying off "the previous character was
758
- // `=`" instead re-opens the hole on `<a title==">`, where the `"` is an
759
- // ordinary value character; an odd quote count then ran the scan to EOF and
760
- // returned one giant inert range, silently disabling this whole fix for the
761
- // rest of the page.
762
- let expectValue = false;
763
- // Unquoted values need their own state for two reasons the spec spells out
764
- // and a simpler scan gets wrong: `>` ends the tag from here (so `attr=>` is
765
- // a missing value, not a value of `>`), and `/` is an ordinary value
766
- // character, so an unquoted URL ending in `/` is NOT a self-closing solidus.
767
- let inUnquoted = false;
768
- let selfClosing = false;
769
- while (p < n) {
770
- const c = html[p];
771
- const isSpace = c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f';
772
- if (quote) {
773
- if (c === quote) quote = '';
774
- } else if (c === '>') {
775
- // Checked before the value branches: a `>` arriving where a value was
776
- // expected terminates the tag (`<a href=>`). Consuming it as a value
777
- // character ran the scan on to the NEXT `>`, which swallowed the real
778
- // tag end and re-armed the original bug for what followed.
779
- selfClosing = !inUnquoted && html[p - 1] === '/';
780
- p += 1;
781
- break;
782
- } else if (expectValue) {
783
- // The first non-whitespace character after `=` decides the value form.
784
- if (!isSpace) {
785
- if (c === '"' || c === "'") quote = c;
786
- else inUnquoted = true;
787
- expectValue = false;
788
- }
789
- } else if (inUnquoted) {
790
- if (isSpace) inUnquoted = false;
791
- } else if (c === '=') {
792
- expectValue = true;
793
- }
794
- p += 1;
795
- }
796
- // The tag's interior is not markup either. A component tag written inside
797
- // an attribute value (`title="renders a <my-card> element"`) was otherwise
798
- // instantiated in place, destroying the rest of the document exactly like
799
- // the comment case. Start at lt+1 so the tag's OWN opening `<` still
800
- // matches; only what is nested inside it is inert.
801
- if (p > lt + 1) ranges.push([lt + 1, p]);
802
- i = p;
803
- const tag = name[1].toLowerCase();
804
- const isClose = html[lt + 1] === '/';
805
- // A self-closing start tag has no content to skip. In HTML the `/` is
806
- // ignored, but in SVG and MathML foreign content it genuinely closes the
807
- // element, and `<svg><title/></svg>` otherwise finds no `</title`, runs the
808
- // range to EOF, and makes every component in the rest of the document
809
- // inert. Honouring `/>` costs only the malformed-HTML case (`<style/>`,
810
- // already broken authoring) and fails in the direction where components
811
- // keep rendering rather than silently vanishing.
812
- if (!isClose && !selfClosing && isTextOnlyTag(tag)) {
813
- // Everything up to the matching close tag is text, not markup.
814
- let contentEnd;
815
- if (tag === 'plaintext') {
816
- // `<plaintext>` has no end tag at all: the rest of the document is text.
817
- contentEnd = n;
818
- } else if (tag === 'script') {
819
- // Script data has the double-escaped state (#1134), so its real end is
820
- // not necessarily the first `</script`.
821
- const end = endOfScriptContent(html, p);
822
- contentEnd = end === -1 ? n : end;
823
- } else {
824
- const close = new RegExp(`</${tag}(?=[\\s/>])`, 'i').exec(html.slice(p));
825
- contentEnd = close ? p + close.index : n;
826
- }
827
- if (contentEnd > p) ranges.push([p, contentEnd]);
828
- i = contentEnd;
829
- }
830
- }
831
- return ranges;
832
- }
833
-
834
- /**
835
- * Random-access membership test over ascending, non-overlapping ranges, for
836
- * callers whose queries are NOT monotonic (findClosingTagInString resets its
837
- * regex cursors backward while pairing opens with closes). O(ranges) per call;
838
- * monotonic callers use `inertAt` below instead.
839
- *
840
- * @param {[number, number][]} ranges
841
- * @param {number} index
842
- * @returns {boolean}
843
- */
844
- function inRanges(ranges, index) {
845
- for (const [start, end] of ranges) {
846
- if (start > index) return false;
847
- if (index < end) return true;
848
- }
849
- return false;
850
- }
851
-
852
- /**
853
- * A left-to-right membership test over ascending, non-overlapping ranges.
854
- *
855
- * Returns a function that answers "is this index inert?" and REMEMBERS how far
856
- * it has walked, so a caller scanning matches in increasing order pays O(ranges)
857
- * across the whole scan instead of O(ranges) per match. Restarting each time is
858
- * an O(tags x components) term, which is measurable on a large page: holding a
859
- * document at 40k tags and raising the component count adds hundreds of
860
- * milliseconds that the cursor removes.
861
- *
862
- * The cursor only ever moves forward, so callers MUST query in non-decreasing
863
- * index order. All three call sites do (`matchAll`, and the two loops that
864
- * consume their input left to right). A caller that needs random access should
865
- * scan `ranges` directly rather than reusing this.
866
- *
867
- * @param {[number, number][]} ranges
868
- * @returns {(index: number) => boolean}
869
- */
870
- function inertAt(ranges) {
871
- let cursor = 0;
872
- return (index) => {
873
- while (cursor < ranges.length && ranges[cursor][1] <= index) cursor += 1;
874
- if (cursor >= ranges.length) return false;
875
- return index >= ranges[cursor][0];
876
- };
877
- }
878
-
879
- /**
880
- * Scan an HTML string for registered custom elements and inject
881
- * Declarative Shadow DOM (`<template shadowrootmode="open">`).
882
- * Awaits each component's render() so async components are fully resolved.
883
- *
884
- * @param {string} html
885
- * @param {SuspenseCtx} [ctx]
886
- * @param {any[]} [ancestors]
887
- * @param {boolean} [dev] server dev flag, threaded to the per-component error
888
- * template for prod-silence (#483); undefined falls back to NODE_ENV
889
- * @returns {Promise<string>}
890
- */
891
- async function injectDSD(html, ctx, ancestors = [], dev) {
892
- // Resolve <webjs-suspense> boundaries first (#471): in a streaming context
893
- // each becomes a fallback placeholder now, with its children pushed for
894
- // out-of-order streaming; without a streaming context the children render
895
- // inline (blocking). Run before the custom-element walk so a streamed
896
- // boundary's children leave the main flow and are not double-processed.
897
- html = await processSuspenseElements(html, ctx, ancestors, dev);
898
- const tags = allTags();
899
- if (!tags.length) return html;
900
- // Sort longest tag name first so the regex alternation tries the most
901
- // specific match before its prefixes. Combined with the (?=[\s>/])
902
- // lookahead this prevents `my-card` from spuriously matching the prefix
903
- // of `<my-card-2>` (or `slot-ssr-1` matching `<slot-ssr-14>`, etc).
904
- // Attribute section is "anything that isn't `>`, with quoted values as a
905
- // single unit" so slashes in URL-valued attrs (e.g. then="/dashboard") don't
906
- // prevent the match. Non-greedy so self-closing `/>` still captures into the
907
- // third group.
908
- const sortedTags = [...tags].sort((a, b) => b.length - a.length);
909
- const pattern = new RegExp(
910
- `<(${sortedTags.map(escapeRegex).join('|')})(?=[\\s>/])((?:"[^"]*"|'[^']*'|[^>])*?)(/?)>`,
911
- 'g'
912
- );
913
- /** @type {{start:number, end:number, text:string}[]} */
914
- const edits = [];
915
- // A tag name inside a comment, a script, a style, RCDATA, or another tag's
916
- // attribute value is text, not an element (#1128).
917
- const inert = inertRanges(html);
918
- const isInert = inertAt(inert);
919
- for (const m of html.matchAll(pattern)) {
920
- const [match, tag, attrs, selfClose] = m;
921
- const Cls = lookup(tag);
922
- if (!Cls) continue;
923
- if (isInert(m.index)) continue;
924
- // Track which custom elements actually appeared: used by SSR to emit
925
- // `<link rel="modulepreload">` hints for their module URLs.
926
- if (ctx && ctx.usedComponents) ctx.usedComponents.add(tag);
927
- let opening = selfClose ? `<${tag}${attrs}>` : match;
928
- // Hoisted so the per-component error boundary (#469) can ask the failed
929
- // instance for its renderError() output.
930
- let instance = null;
931
- try {
932
- const isShadow = /** @type any */ (Cls).shadow === true;
933
- instance = new /** @type any */ (Cls)();
934
- // Thread the ancestor chain (the enclosing custom-element instances)
935
- // so the server element shim's closest() can resolve a parent at SSR.
936
- // Set before performServerUpdate so a willUpdate() that reads a parent
937
- // via closest() sees the chain. Each child recursion below extends it.
938
- instance.__ssrTag = tag;
939
- instance.__ssrAncestors = ancestors;
940
- const attrMap = parseAttrs(attrs);
941
- // Decode `data-webjs-prop-*` attributes first (rich-typed values
942
- // emitted for `.prop=${val}` bindings in the parent template),
943
- // then coerce the ordinary string attributes by `static
944
- // properties` type. Property bindings take priority on a name
945
- // collision because they preserve the original JS reference.
946
- const propValues = consumePropAttrs(attrMap);
947
- // Names already present in the source opening tag (including the
948
- // data-webjs-prop-* bindings, which were stripped from attrMap above
949
- // but remain in the emitted `attrs` string). Reflected/added
950
- // attributes are appended only when their name is NOT already here, so
951
- // existing output stays byte-identical when nothing reflects.
952
- const presentAttrNames = new Set(Object.keys(parseAttrs(attrs)).map((n) => n.toLowerCase()));
953
- // Seed the server attribute shim so `this.getAttribute(...)` /
954
- // `this.hasAttribute(...)` in willUpdate / render read the source
955
- // attributes (a lit muscle-memory pattern) instead of reading empty.
956
- seedServerAttrs(instance, attrMap);
957
- applyAttrsToInstance(instance, attrMap, Cls);
958
- for (const [k, v] of Object.entries(propValues)) instance[k] = v;
959
- // Extract the authored inner HTML BEFORE the render (the injectDSD
960
- // reorder): the source scan needs no render output, and hoisting it lets
961
- // the light-DOM branch below project the authored children into the
962
- // rendered slots. The shadow branch is a read-only peek (its authored
963
- // children stay in place for native projection, and its edit keeps the
964
- // old end).
965
- let authoredInner = '';
966
- let closeEnd = m.index + match.length;
967
- if (!selfClose) {
968
- const innerStart = m.index + match.length;
969
- const closeIdx = findClosingTagInString(html, innerStart, tag, inert);
970
- if (closeIdx !== -1) {
971
- authoredInner = html.slice(innerStart, closeIdx);
972
- const closeRe = new RegExp(`</${escapeRegex(tag)}\\s*>`, 'i');
973
- const tail = html.slice(closeIdx);
974
- const closeMatch = closeRe.exec(tail);
975
- const closeLen = closeMatch ? closeMatch[0].length : `</${tag}>`.length;
976
- closeEnd = closeIdx + closeLen;
977
- } else {
978
- // Unclosed in source. Take rest of html as authored content
979
- // and synthesize a closing tag on output.
980
- authoredInner = html.slice(innerStart);
981
- closeEnd = html.length;
982
- }
983
- }
984
- const partitioned = partitionAuthoredBySlot(authoredInner);
985
- // Run the pre-render lifecycle (willUpdate, controllers' hostUpdate,
986
- // then reflect reflect:true props) so derived state computed there is
987
- // correct in the SSR'd HTML, matching how lit runs the update cycle at
988
- // SSR. WebComponent instances expose performServerUpdate; bare
989
- // Base-extending kit components (no lifecycle) do not, so it is guarded.
990
- if (typeof instance.performServerUpdate === 'function') instance.performServerUpdate();
991
- let tpl = instance.render ? instance.render() : '';
992
- if (tpl && typeof tpl.then === 'function') tpl = await tpl;
993
- // Surface attributes the component set up to and including render()
994
- // that were not already in the source tag: reflected reflect:true
995
- // props, an explicit this.setAttribute in the constructor / willUpdate,
996
- // or a host-attribute mutation inside render() itself (a light-DOM
997
- // compound-component pattern, e.g. this.dataset.state / this.className /
998
- // this.hidden on the host). Reading after render() captures all three.
999
- // Appending keeps the original tag byte-identical when nothing changed.
1000
- opening = appendReflectedAttrs(opening, instance, presentAttrNames);
1001
- // Mark LIGHT-DOM component hosts so the framework default
1002
- // `@layer webjs-host { :where([data-wj-host]) { display: block } }`
1003
- // (injected once in the document head) applies at first paint. A custom
1004
- // element is `display:inline` by default, which collapses a component used
1005
- // as a block container (a board / card) until an author style intervenes.
1006
- // The low-priority `@layer` keeps it overridable by any author style,
1007
- // INCLUDING Tailwind's layered utilities (`class="flex"` wins). Emitted
1008
- // uniformly regardless of elision, so the elision on-vs-off differential is
1009
- // preserved.
1010
- //
1011
- // Shadow hosts are NOT marked: a document-level rule targeting the host
1012
- // beats the shadow tree's own `:host { display: … }` (the encapsulation-
1013
- // context criterion outranks both layer and specificity for normal
1014
- // declarations), so marking them would silently override the shadow
1015
- // author's `:host` display. Shadow components set their own host display
1016
- // via `:host` in `static styles` (the idiomatic mechanism), which the
1017
- // framework must not clobber.
1018
- if (!isShadow) opening = withHostMarker(opening);
1019
- // Render the template to HTML. injectDSD recurses on the result so
1020
- // nested custom elements (e.g. <theme-toggle> inside <blog-shell>)
1021
- // get their own DSD pass.
1022
- // This is a SEPARATE render pass over one component's own template,
1023
- // driven by walking the already-emitted HTML, so it has no idea whether
1024
- // the host tag sits inside a `<form>`. It does not need to: a bound
1025
- // submitter carries its whole submission (#1307), so nothing here asks
1026
- // about an enclosing form.
1027
- const rawInner = await render(tpl, ctx);
1028
-
1029
- if (isShadow) {
1030
- // Shadow DOM: native <slot> stays as-is in the DSD template. The
1031
- // browser handles projection from the host's light-DOM children
1032
- // into the shadow tree natively. No framework substitution here.
1033
- const innerProcessed = await injectDSD(rawInner, ctx, [...ancestors, instance], dev);
1034
- const rawStyles = /** @type any */ (Cls).styles;
1035
- const styleList = Array.isArray(rawStyles) ? rawStyles : rawStyles && isCSS(rawStyles) ? [rawStyles] : [];
1036
- const styleStr = stylesToString(styleList);
1037
- edits.push({
1038
- start: m.index,
1039
- end: m.index + match.length,
1040
- text: `${opening}<template shadowrootmode="open">${styleStr}${innerProcessed}</template>`,
1041
- });
1042
- } else {
1043
- // Light DOM. When the component has a non-empty rendered template,
1044
- // run the slot pipeline so behaviour matches shadow DOM: authored
1045
- // children are visible only where projected through <slot>; any
1046
- // child without a matching slot is dropped.
1047
- //
1048
- // When rendered template is empty (Base-extending decorator
1049
- // components that have no render() method, or render() that
1050
- // returns an empty template), the host acts as a transparent
1051
- // wrapper: authored children stay in place adjacent to the
1052
- // (empty) hydration marker. This preserves the kit's
1053
- // decorator-pattern components (those extending Base from the
1054
- // ui package's lib/utils.ts) without forcing a render() rewrite.
1055
- const renderedIsEmpty = rawInner.trim() === '';
1056
- if (renderedIsEmpty) {
1057
- edits.push({
1058
- start: m.index,
1059
- end: m.index + match.length,
1060
- text: `${opening}<!--webjs-hydrate-->`,
1061
- });
1062
- continue;
1063
- }
1064
- //
1065
- // The authored inner HTML + slot partition were extracted BEFORE
1066
- // the render (the #1015 reorder, see above), so here:
1067
- // 1. Substitute each <slot> in the rendered output with a
1068
- // framework-marked <slot data-webjs-light data-projection
1069
- // ="actual|fallback"> element carrying projection or
1070
- // fallback content per first-wins rule.
1071
- // 2. Recursively run injectDSD on the substituted output so
1072
- // nested custom elements (inside projected children) get
1073
- // their own DSD pass.
1074
- const innerWithSlots = substituteSlotsInRender(rawInner, partitioned, tag);
1075
- const innerProcessed = await injectDSD(innerWithSlots, ctx, [...ancestors, instance], dev);
1076
- edits.push({
1077
- start: m.index,
1078
- end: closeEnd,
1079
- text: `${opening}<!--webjs-hydrate-->${innerProcessed}</${tag}>`,
1080
- });
1081
- }
1082
- } catch (e) {
1083
- const hint = browserMemberHint(e);
1084
- if (hint) {
1085
- console.error(
1086
- `[webjs] SSR failed for <${tag}>: ${hint} It was touched in the component's constructor or render(), which run during SSR. Move browser-only work to connectedCallback() or a lifecycle hook (firstUpdated/updated), which SSR never calls; seed first-paint defaults in the constructor only from server-known inputs (attributes / props).`,
1087
- e,
1088
- );
1089
- } else {
1090
- console.error(`[webjs] SSR failed for <${tag}>:`, e);
1091
- }
1092
- // Per-component error isolation (#469). A render that throws (most
1093
- // commonly a rejected `await getData()` in an async render, but any
1094
- // render throw) is caught HERE, per component: the loop continues so
1095
- // siblings render normally, and this element renders a component-scoped
1096
- // error state instead of bubbling to the route error.js or leaving its
1097
- // raw, unprocessed children in the output. renderError() customizes the
1098
- // error UI; the default surfaces the message in dev and renders an empty
1099
- // (silent, isolated) element in prod so no internal detail leaks.
1100
- const err = e instanceof Error ? e : new Error(String(e));
1101
- let errorInner = '';
1102
- try {
1103
- let errTpl;
1104
- if (instance && typeof instance.renderError === 'function') {
1105
- errTpl = instance.renderError(err);
1106
- }
1107
- if (errTpl === undefined) errTpl = defaultSSRErrorTemplate(tag, err, dev);
1108
- errorInner = await render(errTpl, ctx);
1109
- if (errorInner.trim()) {
1110
- errorInner = await injectDSD(errorInner, ctx, instance ? [...ancestors, instance] : ancestors, dev);
1111
- }
1112
- } catch (renderErrorThrew) {
1113
- console.error(`[webjs] renderError() for <${tag}> also threw:`, renderErrorThrew);
1114
- errorInner = '';
1115
- }
1116
- // Replace the element (opening tag through its matching close) with the
1117
- // error state plus a hydration marker, so the client error boundary
1118
- // (component.js renderError) can take over on hydration.
1119
- let closeEnd = m.index + match.length;
1120
- if (!selfClose) {
1121
- const innerStart = m.index + match.length;
1122
- const closeIdx = findClosingTagInString(html, innerStart, tag, inert);
1123
- if (closeIdx !== -1) {
1124
- const closeRe = new RegExp(`</${escapeRegex(tag)}\\s*>`, 'i');
1125
- const cm = closeRe.exec(html.slice(closeIdx));
1126
- closeEnd = closeIdx + (cm ? cm[0].length : `</${tag}>`.length);
1127
- } else {
1128
- closeEnd = html.length;
1129
- }
1130
- }
1131
- // A shadow component renders into a shadow root on the client, so its
1132
- // SSR error state must ride a DSD template too (matching the success
1133
- // path), not land in light DOM. Otherwise the client renders the error
1134
- // into the shadow root while the light error box lingers underneath.
1135
- const isShadowErr = /** @type any */ (Cls).shadow === true;
1136
- // Mark the LIGHT host here too, so a component whose SSR render() throws
1137
- // paints its error state as display:block (not the inline default),
1138
- // matching the success path. When an `async render()` rejects, it throws
1139
- // before the success-path withHostMarker (above) ran, so `opening` is still
1140
- // unmarked; when a later template render throws, the success marker already
1141
- // ran and this call is a no-op (withHostMarker is idempotent). Shadow hosts
1142
- // stay unmarked (their :host must win).
1143
- if (!isShadowErr) opening = withHostMarker(opening);
1144
- let text;
1145
- if (isShadowErr) {
1146
- const rawStyles = /** @type any */ (Cls).styles;
1147
- const styleList = Array.isArray(rawStyles) ? rawStyles : rawStyles && isCSS(rawStyles) ? [rawStyles] : [];
1148
- const styleStr = stylesToString(styleList);
1149
- text = `${opening}<template shadowrootmode="open">${styleStr}${errorInner}</template>`;
1150
- } else {
1151
- text = `${opening}<!--webjs-hydrate-->${errorInner}</${tag}>`;
1152
- }
1153
- edits.push({ start: m.index, end: closeEnd, text });
1154
- }
1155
- }
1156
- if (!edits.length) return html;
1157
-
1158
- // Drop edits whose range lives inside an earlier edit's range. This
1159
- // happens when an outer custom element with <slot> in its render takes
1160
- // an edit that spans its opening + closing tags (covering inner custom
1161
- // elements among authored children); the inner matches were enumerated
1162
- // independently against the original html, but those inner elements
1163
- // are processed by the recursive injectDSD call on innerWithSlots.
1164
- // Keeping both edits would double-process them and corrupt the output.
1165
- // A consequence: a nested instance's render() runs once per chain depth
1166
- // (the discarded top-level pass sees an empty ancestor chain, so its
1167
- // closest() reads null; the kept recursive pass has the real chain). The
1168
- // kept pass is the only output, and closest() is a read, so render() must
1169
- // stay pure at SSR (the standard SSR contract), not branch on side effects.
1170
- edits.sort((a, b) => a.start - b.start);
1171
- /** @type {{start:number, end:number, text:string}[]} */
1172
- const filtered = [];
1173
- let consumedTo = -1;
1174
- for (const e of edits) {
1175
- if (e.start >= consumedTo) {
1176
- filtered.push(e);
1177
- consumedTo = e.end;
1178
- }
1179
- }
1180
- // Apply edits from last to first so indices stay stable.
1181
- let out = html;
1182
- for (let i = filtered.length - 1; i >= 0; i--) {
1183
- const { start, end, text } = filtered[i];
1184
- out = out.slice(0, start) + text + out.slice(end);
1185
- }
1186
- return out;
1187
- }
1188
-
1189
- // ---------------------------------------------------------------------------
1190
- // Slot SSR helpers
1191
- // ---------------------------------------------------------------------------
1192
-
1193
- const VOID_ELEMENTS = new Set([
1194
- 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
1195
- 'link', 'meta', 'param', 'source', 'track', 'wbr',
1196
- ]);
1197
-
1198
- /** @param {string} tag @returns {boolean} */
1199
- function isVoidElement(tag) {
1200
- return VOID_ELEMENTS.has(tag.toLowerCase());
1201
- }
1202
-
1203
- /**
1204
- * Resolve `<webjs-suspense>` boundaries in an HTML string (#471). For each
1205
- * top-level boundary (nested ones are handled by the recursive injectDSD that
1206
- * processes a boundary's streamed children):
1207
- *
1208
- * - Streaming (a SuspenseCtx is present): emit the boundary as
1209
- * `<webjs-suspense id="sN">FALLBACK</webjs-suspense>` and push the raw inner
1210
- * children to `ctx.pending` (wrapped in `unsafeHTML` so the streaming pass
1211
- * renders them as HTML, not escaped text, then runs injectDSD over them).
1212
- * `streamSuspenseBoundaries` later streams the resolved children as a
1213
- * `<template data-webjs-resolve="sN">` plus the swap script. Multiple
1214
- * boundaries resolve via `Promise.all`, so their data fetches run
1215
- * concurrently. The placeholder is the boundary's `.fallback`
1216
- * (carried as `data-webjs-fallback`); a boundary without one shows empty.
1217
- * - Blocking (no ctx): render the children inline now and drop the fallback,
1218
- * so a non-streaming `renderToString` returns the real content. The
1219
- * `<webjs-suspense>` wrapper stays as an inert inline element.
1220
- *
1221
- * @param {string} html
1222
- * @param {SuspenseCtx} [ctx]
1223
- * @param {any[]} [ancestors]
1224
- * @param {boolean} [dev] server dev flag for prod-silence of a throwing
1225
- * component in an inline (ctx-absent) boundary (#483)
1226
- * @returns {Promise<string>}
1227
- */
1228
- async function processSuspenseElements(html, ctx, ancestors = [], dev) {
1229
- if (html.indexOf('<webjs-suspense') === -1) return html;
1230
- const OPEN = /<webjs-suspense((?:"[^"]*"|'[^']*'|[^>])*?)>/i;
1231
- // A commented-out boundary is text, not an element (#1128). This scanner is
1232
- // the reason the comment fix cannot live in injectDSD alone: it runs FIRST
1233
- // and hands the boundary's children to a fresh injectDSD as a standalone
1234
- // string, which has no idea those bytes came from inside a comment. Under
1235
- // streaming it is worse than a stray render, because the children's data
1236
- // fetches run and the swap script targets an id that only exists inside a
1237
- // comment, so it can never resolve. Ranges are computed against the FULL
1238
- // input once, and `consumed` maps the shrinking `rest` back onto it.
1239
- const inert = inertRanges(html);
1240
- const isInert = inertAt(inert);
1241
- let consumed = 0;
1242
- let result = '';
1243
- let rest = html;
1244
- // Bounded loop: each iteration consumes at least the opening tag.
1245
- for (let guard = 0; guard < 10000; guard++) {
1246
- const m = OPEN.exec(rest);
1247
- if (!m) {
1248
- result += rest;
1249
- break;
1250
- }
1251
- if (isInert(consumed + m.index)) {
1252
- // Emit through the end of this match and keep scanning after it.
1253
- const skipTo = m.index + m[0].length;
1254
- result += rest.slice(0, skipTo);
1255
- rest = rest.slice(skipTo);
1256
- consumed += skipTo;
1257
- continue;
1258
- }
1259
- const openStart = m.index;
1260
- const openEnd = m.index + m[0].length;
1261
- result += rest.slice(0, openStart);
1262
- const attrs = m[1] || '';
1263
- const fbMatch = /data-webjs-fallback="([^"]*)"/i.exec(attrs);
1264
- const fallbackHtml = fbMatch ? decodeAttrEntities(fbMatch[1]) : '';
1265
-
1266
- // Pass the FULL-input ranges shifted into `rest` coordinates rather than
1267
- // letting the helper re-tokenize the suffix. `rest` can begin mid-comment
1268
- // or mid-raw-text after the skip path above, and a tokenizer restarted
1269
- // there is in the wrong state: a text-only opener named later in that same
1270
- // comment would read as a real element and mark everything to EOF inert,
1271
- // so the boundary's real close tag was skipped and the trailing markup
1272
- // folded into the boundary. The shifted view keeps the full-string truth,
1273
- // including a first range that starts before `rest` does.
1274
- const shifted = [];
1275
- for (const [s, e] of inert) {
1276
- if (e <= consumed) continue;
1277
- shifted.push([Math.max(0, s - consumed), e - consumed]);
1278
- }
1279
- const closeIdx = findClosingTagInString(rest, openEnd, 'webjs-suspense', shifted);
1280
- let inner;
1281
- let afterClose;
1282
- if (closeIdx === -1) {
1283
- inner = rest.slice(openEnd);
1284
- afterClose = '';
1285
- } else {
1286
- inner = rest.slice(openEnd, closeIdx);
1287
- const cm = /<\/webjs-suspense\s*>/i.exec(rest.slice(closeIdx));
1288
- afterClose = rest.slice(closeIdx + (cm ? cm[0].length : '</webjs-suspense>'.length));
1289
- }
1290
-
1291
- if (ctx) {
1292
- const id = `s${ctx.nextId++}`;
1293
- // Raw children stream in later. unsafeHTML so the streaming pass emits
1294
- // the markup verbatim (then injectDSD runs over it, resolving the async
1295
- // components and any nested boundaries).
1296
- ctx.pending.push({ id, promise: Promise.resolve(unsafeHTML(inner)) });
1297
- result += `<webjs-suspense id="${id}">${fallbackHtml}</webjs-suspense>`;
1298
- } else {
1299
- const innerProcessed = await injectDSD(inner, ctx, ancestors, dev);
1300
- result += `<webjs-suspense>${innerProcessed}</webjs-suspense>`;
1301
- }
1302
- consumed += rest.length - afterClose.length;
1303
- rest = afterClose;
1304
- }
1305
- return result;
1306
- }
1307
-
1308
- /**
1309
- * Find the position of the matching closing tag for `tagName` starting from
1310
- * `fromIndex` in `html`. Handles nested same-tag elements via depth tracking.
1311
- * Returns the index of the `<` of `</tagName>`, or -1 if unclosed.
1312
- *
1313
- * @param {string} html
1314
- * @param {number} fromIndex
1315
- * @param {string} tagName
1316
- * @returns {number}
1317
- */
1318
- function findClosingTagInString(html, fromIndex, tagName, inert) {
1319
- const esc = escapeRegex(tagName);
1320
- // Match same-name opening tags. Followed by a name-boundary character
1321
- // so we don't accept <table> as opening <tab>.
1322
- const openRe = new RegExp(`<${esc}(?:[\\s>/])`, 'gi');
1323
- const closeRe = new RegExp(`</${esc}\\s*>`, 'gi');
1324
- // A tag inside a comment, raw text, RCDATA, or an attribute value is text
1325
- // and must count for NEITHER side of the depth ledger (#1133). Counting a
1326
- // commented `<my-card>` as a nested open meant depth never returned to zero,
1327
- // and matching a commented `</my-card>` as the close truncated the authored
1328
- // children at the comment, so the projected content ended with an
1329
- // unterminated `<!--` that a browser read as commenting out the real close
1330
- // tags. Callers that already computed the ranges for this exact string pass
1331
- // them; a caller that did not gets them computed here.
1332
- const ranges = inert === undefined ? inertRanges(html) : inert;
1333
- const next = (re) => {
1334
- let m;
1335
- while ((m = re.exec(html)) !== null) {
1336
- if (ranges.length === 0 || !inRanges(ranges, m.index)) return m;
1337
- }
1338
- return null;
1339
- };
1340
- openRe.lastIndex = fromIndex;
1341
- closeRe.lastIndex = fromIndex;
1342
- let depth = 1;
1343
- while (depth > 0) {
1344
- const o = next(openRe);
1345
- const c = next(closeRe);
1346
- if (!c) return -1;
1347
- if (o && o.index < c.index) {
1348
- depth++;
1349
- closeRe.lastIndex = o.index + 1;
1350
- } else {
1351
- depth--;
1352
- if (depth === 0) return c.index;
1353
- openRe.lastIndex = c.index + 1;
1354
- }
1355
- }
1356
- return -1;
1357
- }
1358
-
1359
- /**
1360
- * Extract the `slot` attribute value from an attribute string. Returns
1361
- * null when the attribute is absent.
1362
- *
1363
- * @param {string} attrsRaw
1364
- * @returns {string | null}
1365
- */
1366
- function extractSlotAttr(attrsRaw) {
1367
- const m = /\bslot\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(attrsRaw);
1368
- if (!m) return null;
1369
- const value = m[1] ?? m[2] ?? m[3] ?? '';
1370
- // Per shadow DOM spec, slot="" (empty) and missing slot attribute both
1371
- // route to the default slot. `default` is the framework's reserved alias
1372
- // for it (#1015: the client record normalizes it identically, so both
1373
- // sides agree end to end).
1374
- return value === '' || value === 'default' ? null : value;
1375
- }
1376
-
1377
- /**
1378
- * Partition authored inner HTML by each top-level child's `slot=""`
1379
- * attribute. Text nodes, comment nodes, and elements without `slot=""`
1380
- * all route to the default-slot key (null).
1381
- *
1382
- * Returns a Map keyed by slot name (null for default) whose values are
1383
- * the concatenated HTML strings for that slot in source order.
1384
- *
1385
- * @param {string} html
1386
- * @returns {Map<string|null, string>}
1387
- */
1388
- function partitionAuthoredBySlot(html) {
1389
- /** @type {Map<string|null, string>} */
1390
- const groups = new Map();
1391
- let defaultBuf = '';
1392
- let cursor = 0;
1393
- while (cursor < html.length) {
1394
- const lt = html.indexOf('<', cursor);
1395
- if (lt === -1) {
1396
- defaultBuf += html.slice(cursor);
1397
- break;
1398
- }
1399
- if (lt > cursor) defaultBuf += html.slice(cursor, lt);
1400
- const rest = html.slice(lt);
1401
- if (rest.startsWith('<!--')) {
1402
- // Find the comment's end the same way inertRanges does, rather than with
1403
- // a bare `indexOf('-->')`. The two helpers both decide where a comment
1404
- // stops, so a bare search makes them DISAGREE on the spec short forms
1405
- // (`--!>`, `<!-->`, `<!--->`): this one would run past the real end and
1406
- // swallow the slotted children that follow, silently routing a
1407
- // `slot="head"` child into the default slot.
1408
- const commentEnd = endOfComment(html, lt);
1409
- if (commentEnd === -1) {
1410
- defaultBuf += rest;
1411
- cursor = html.length;
1412
- break;
1413
- }
1414
- defaultBuf += html.slice(lt, commentEnd);
1415
- cursor = commentEnd;
1416
- continue;
1417
- }
1418
- if (rest.startsWith('<!') || rest.startsWith('</')) {
1419
- const end = html.indexOf('>', lt);
1420
- if (end === -1) {
1421
- defaultBuf += rest;
1422
- cursor = html.length;
1423
- break;
1424
- }
1425
- defaultBuf += html.slice(lt, end + 1);
1426
- cursor = end + 1;
1427
- continue;
1428
- }
1429
- const tagMatch = /^<([a-zA-Z][\w-]*)((?:"[^"]*"|'[^']*'|[^>])*?)(\/?)>/.exec(rest);
1430
- if (!tagMatch) {
1431
- defaultBuf += '<';
1432
- cursor = lt + 1;
1433
- continue;
1434
- }
1435
- const [tagFull, tagName, attrsRaw, selfCloseSlash] = tagMatch;
1436
- const lower = tagName.toLowerCase();
1437
- const isSelfClose = !!selfCloseSlash || isVoidElement(lower);
1438
- const slotAttr = extractSlotAttr(attrsRaw);
1439
- let elemEnd;
1440
- if (isSelfClose) {
1441
- elemEnd = lt + tagFull.length;
1442
- } else {
1443
- const innerStart = lt + tagFull.length;
1444
- const closeIdx = findClosingTagInString(html, innerStart, lower);
1445
- if (closeIdx === -1) {
1446
- // Unclosed element. Take to end of html.
1447
- const elementHTML = html.slice(lt);
1448
- if (slotAttr !== null) appendStringToMap(groups, slotAttr, elementHTML);
1449
- else defaultBuf += elementHTML;
1450
- cursor = html.length;
1451
- continue;
1452
- }
1453
- const closeRe = new RegExp(`</${escapeRegex(lower)}\\s*>`, 'i');
1454
- const tail = html.slice(closeIdx);
1455
- const closeMatch = closeRe.exec(tail);
1456
- const closeLen = closeMatch ? closeMatch[0].length : `</${lower}>`.length;
1457
- elemEnd = closeIdx + closeLen;
1458
- }
1459
- const elementHTML = html.slice(lt, elemEnd);
1460
- if (slotAttr !== null) appendStringToMap(groups, slotAttr, elementHTML);
1461
- else defaultBuf += elementHTML;
1462
- cursor = elemEnd;
1463
- }
1464
- if (defaultBuf.length > 0) groups.set(null, defaultBuf);
1465
- return groups;
1466
- }
1467
-
1468
- /** Append a string to a Map<K, string>, concatenating if the key exists. */
1469
- function appendStringToMap(map, key, value) {
1470
- const existing = map.get(key);
1471
- if (existing !== undefined) map.set(key, existing + value);
1472
- else map.set(key, value);
1473
- }
1474
-
1475
- /**
1476
- * Substitute every `<slot>` tag in `rendered` with a framework-marked
1477
- * `<slot data-webjs-light data-projection="actual|fallback">` element
1478
- * carrying either the projected children for that slot (from
1479
- * `partitioned`) or the slot's authored fallback content. Multiple
1480
- * slots with the same name follow the first-wins rule per spec; later
1481
- * same-named slots fall back regardless of available projection.
1482
- *
1483
- * The `ownerTag` (the tag of the component whose template rendered these
1484
- * slots) is emitted as `data-wj-slot-owner` so the client resolves template
1485
- * ownership on hydration the same way the client renderer stamps SLOT_OWNER,
1486
- * which is what makes a FORWARDED slot (rendered by this component but nested
1487
- * inside a child) route to this component and not the child (#1023).
1488
- *
1489
- * @param {string} rendered
1490
- * @param {Map<string|null, string>} partitioned
1491
- * @param {string} ownerTag
1492
- * @returns {string}
1493
- */
1494
- function substituteSlotsInRender(rendered, partitioned, ownerTag) {
1495
- const ownerAttr = ownerTag ? ` data-wj-slot-owner="${escapeAttr(ownerTag)}"` : '';
1496
- /** @type {Set<string|null>} */
1497
- const consumedNames = new Set();
1498
- let result = '';
1499
- let cursor = 0;
1500
- const slotRe = /<slot((?:"[^"]*"|'[^']*'|[^>])*?)(\/?)>/gi;
1501
- // A `<slot>` written inside a comment is documentation, not a slot (#1128).
1502
- // Substituting one is worse here than in the element walk: a commented slot
1503
- // has no `</slot>`, so the fallback scan below swallows the rest of the
1504
- // template, the component's REAL slot is never substituted, and the authored
1505
- // children are dropped from the page entirely.
1506
- const inert = inertRanges(rendered);
1507
- const isInert = inertAt(inert);
1508
- let m;
1509
- while ((m = slotRe.exec(rendered)) !== null) {
1510
- if (isInert(m.index)) continue;
1511
- result += rendered.slice(cursor, m.index);
1512
- const [fullOpen, attrsRaw, selfCloseSlash] = m;
1513
- const isSelfClose = !!selfCloseSlash;
1514
- const nameMatch = /\bname\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(attrsRaw);
1515
- const name = nameMatch ? (nameMatch[1] ?? nameMatch[2] ?? nameMatch[3]) : null;
1516
- // Strip the `name` attribute from the carried-through attribute
1517
- // string so we can re-add it (with escaping) on the framework slot.
1518
- const otherAttrs = attrsRaw.replace(/\bname\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i, '').trim();
1519
- let fallback = '';
1520
- let totalEnd;
1521
- if (isSelfClose) {
1522
- totalEnd = m.index + fullOpen.length;
1523
- } else {
1524
- const innerStart = m.index + fullOpen.length;
1525
- const closeIdx = findClosingTagInString(rendered, innerStart, 'slot', inert);
1526
- if (closeIdx === -1) {
1527
- fallback = rendered.slice(innerStart);
1528
- totalEnd = rendered.length;
1529
- } else {
1530
- fallback = rendered.slice(innerStart, closeIdx);
1531
- const closeRe = /<\/slot\s*>/i;
1532
- const tail = rendered.slice(closeIdx);
1533
- const closeMatch = closeRe.exec(tail);
1534
- const closeLen = closeMatch ? closeMatch[0].length : '</slot>'.length;
1535
- totalEnd = closeIdx + closeLen;
1536
- }
1537
- }
1538
- // `default` and `''` are the reserved aliases for the default slot
1539
- // (#1015), matching the client's keyOfName exactly: the LOOKUP key
1540
- // normalizes, while the emitted name attribute stays as authored so the
1541
- // output bytes are unchanged for every other app.
1542
- const slotKey = name === 'default' || name === '' ? null : name;
1543
- const projected = partitioned.get(slotKey);
1544
- const nameAttr = name !== null ? ` name="${escapeAttr(name)}"` : '';
1545
- const extraAttrs = otherAttrs ? ` ${otherAttrs}` : '';
1546
- if (projected !== undefined && !consumedNames.has(slotKey)) {
1547
- consumedNames.add(slotKey);
1548
- result += `<slot data-webjs-light data-projection="actual"${ownerAttr}${nameAttr}${extraAttrs}>${projected}</slot>`;
1549
- } else {
1550
- result += `<slot data-webjs-light data-projection="fallback"${ownerAttr}${nameAttr}${extraAttrs}>${fallback}</slot>`;
1551
- }
1552
- cursor = totalEnd;
1553
- slotRe.lastIndex = totalEnd;
1554
- }
1555
- result += rendered.slice(cursor);
1556
- return result;
1557
- }
1558
-
1559
- /** @param {string} s */
1560
- function escapeRegex(s) {
1561
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1562
- }
1563
-
1564
- /** @param {string} tag */
1565
- function isRawtextTag(tag) {
1566
- return tag === 'script' || tag === 'style';
1567
- }
1568
-
1569
- /**
1570
- * RCDATA elements: their content is text (character references aside), so a
1571
- * tag-shaped string inside one is not markup. Kept next to `isRawtextTag` so
1572
- * the two lists stay together rather than drifting apart.
1573
- * @param {string} tag
1574
- * @returns {boolean}
1575
- */
1576
- function isRcdataTag(tag) {
1577
- return tag === 'textarea' || tag === 'title';
1578
- }
1579
-
1580
- /**
1581
- * Elements whose content the HTML tokenizer never reads as markup, for the
1582
- * purposes of `inertRanges` only (#1128).
1583
- *
1584
- * Deliberately NOT `isRawtextTag`, even though it overlaps: that predicate is
1585
- * shared with the template tokenizer, where widening it would change how holes
1586
- * inside those elements are escaped. This one answers a narrower question,
1587
- * "can a tag-shaped string in here be a real element", and the answer is no for
1588
- * every raw-text and RCDATA element, not just the two the template path cares
1589
- * about. `<iframe>` with fallback markup is the realistic trigger.
1590
- *
1591
- * `<noscript>` is excluded on purpose: its content IS parsed as markup when
1592
- * scripting is disabled, which for a progressive-enhancement framework is the
1593
- * case that matters, so components inside it must keep rendering.
1594
- *
1595
- * @param {string} tag
1596
- * @returns {boolean}
1597
- */
1598
- function isTextOnlyTag(tag) {
1599
- return isRawtextTag(tag) || isRcdataTag(tag)
1600
- || tag === 'iframe' || tag === 'xmp' || tag === 'noembed'
1601
- || tag === 'noframes' || tag === 'plaintext';
1602
- }
1603
-
1604
- /**
1605
- * Minimal attribute string parser.
1606
- * @param {string} attrStr
1607
- * @returns {Record<string,string>}
1608
- */
1609
- function parseAttrs(attrStr) {
1610
- /** @type {Record<string,string>} */
1611
- const out = {};
1612
- const re = /([a-zA-Z_:][\w:.-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
1613
- let m;
1614
- while ((m = re.exec(attrStr)) !== null) {
1615
- out[m[1]] = m[2] ?? m[3] ?? m[4] ?? '';
1616
- }
1617
- return out;
1618
- }
1619
-
1620
- /**
1621
- * Seed the element's attributes from the source opening tag so reads like
1622
- * `this.getAttribute(name)` / `this.hasAttribute(name)` inside willUpdate /
1623
- * render return the real value during SSR. Goes through `setAttribute`, which
1624
- * both the server element shim (Node SSR) and a real `HTMLElement`
1625
- * (renderToString called in a browser, e.g. tests) implement, so the path
1626
- * does not depend on the shim's internal store. A bare Base-extending kit
1627
- * component without `setAttribute` is skipped.
1628
- *
1629
- * @param {any} instance
1630
- * @param {Record<string,string>} attrs parsed source attributes (data-webjs-prop-* already removed)
1631
- */
1632
- function seedServerAttrs(instance, attrs) {
1633
- if (!instance || typeof instance.setAttribute !== 'function') return;
1634
- for (const [name, raw] of Object.entries(attrs)) {
1635
- instance.setAttribute(name, decodeAttrEntities(raw));
1636
- }
1637
- }
1638
-
1639
- /**
1640
- * Append attributes the component set before render (reflected reflect:true
1641
- * properties, or an explicit `this.setAttribute` in the constructor /
1642
- * willUpdate) to the element's opening tag, skipping any name already present
1643
- * in the source tag. Reads via the standard `getAttributeNames` /
1644
- * `getAttribute` API so it works whether the instance is the server shim or a
1645
- * real `HTMLElement`. Returns the opening tag unchanged when there is nothing
1646
- * to add, so existing SSR output stays byte-identical when no component
1647
- * reflects, which preserves the elision on-vs-off differential invariant.
1648
- *
1649
- * @param {string} opening the element's opening tag, ending in `>`
1650
- * @param {any} instance
1651
- * @param {Set<string>} presentAttrNames lowercased names already in the source tag
1652
- * @returns {string}
1653
- */
1654
- /**
1655
- * Add the component host marker (`data-wj-host`) to an opening tag, unless it
1656
- * is already present. Insert before the closing `>` the same way
1657
- * `appendReflectedAttrs` does. Idempotent so a re-processed tag is unchanged.
1658
- * @param {string} opening the element's opening tag, ending in `>`
1659
- * @returns {string}
1660
- */
1661
- function withHostMarker(opening) {
1662
- if (/\sdata-wj-host(?=[\s>=])/i.test(opening)) return opening;
1663
- return `${opening.slice(0, -1)} data-wj-host>`;
1664
- }
1665
-
1666
- function appendReflectedAttrs(opening, instance, presentAttrNames) {
1667
- if (!instance || typeof instance.getAttributeNames !== 'function') return opening;
1668
- let extra = '';
1669
- for (const rawName of instance.getAttributeNames()) {
1670
- const name = String(rawName).toLowerCase();
1671
- if (presentAttrNames.has(name)) continue;
1672
- const value = instance.getAttribute(rawName);
1673
- extra += value === '' ? ` ${name}` : ` ${name}="${escapeAttr(String(value))}"`;
1674
- }
1675
- if (!extra) return opening;
1676
- // Insert before the closing `>` (the opening tag is normalised to end in
1677
- // `>`; a self-closing source tag was already rewritten without the slash).
1678
- return `${opening.slice(0, -1)}${extra}>`;
1679
- }
1680
-
1681
- /**
1682
- * Coerce attribute strings to typed properties on a component instance
1683
- * based on its static `properties` declaration.
1684
- */
1685
- function applyAttrsToInstance(instance, attrs, Cls) {
1686
- for (const [sourceName, sourceValue] of Object.entries(attrs)) {
1687
- // The browser LOWERCASES every attribute name while parsing an HTML
1688
- // document, so `cfgData="x"` reaches the client reader as `cfgdata` and a
1689
- // camelCase name can never match anything in `observedAttributes`.
1690
- // Resolving the source case here made SSR read a name the platform cannot
1691
- // deliver, which is the divergence, not the fix (#1341).
1692
- const resolved = resolveAttributeProperty(Cls, sourceName.toLowerCase());
1693
- // An attribute mapping to no attribute-backed property is IGNORED, exactly
1694
- // as `attributeChangedCallback` ignores it and as lit's reader does. This
1695
- // used to assign it as an instance property (`instance[propName] = raw`),
1696
- // which no browser upgrade ever reproduces, and which on a real
1697
- // HTMLElement could mutate DOM state through `id` / `hidden` / `slot`.
1698
- // `seedServerAttrs` has already applied every source attribute properly,
1699
- // so nothing needs the copy (#1341).
1700
- if (resolved === undefined) continue;
1701
- const { propName, def } = resolved;
1702
- // A browser decodes every character reference BEFORE any reader sees the
1703
- // value, so decode once here, for every branch, and hand the shared reader
1704
- // an already-decoded string exactly as the DOM hands the client one. It
1705
- // used to be a `decode` argument the reader applied on the JSON and
1706
- // converter branches alone, which left a `String`-typed prop holding the
1707
- // raw source text while `getAttribute()` on the client returned the decoded
1708
- // one (#1341).
1709
- //
1710
- // One reader for both sides (#1340): `readAttributeValue` in
1711
- // `attribute-reader.js` is the same function `attributeChangedCallback` in
1712
- // `component.js` calls, so a custom `converter.fromAttribute` runs here
1713
- // too, ahead of type coercion, and the #1253 unparseable-JSON fallback is
1714
- // shared rather than mirrored.
1715
- //
1716
- // A converter that THROWS is not caught here. It lands in the
1717
- // per-component error isolation below, which is deliberate: an author who
1718
- // supplies a converter owns the read, the same rule `_reflectAttribute`
1719
- // states for `toAttribute`. See the comment on `readAttributeValue`.
1720
- instance[propName] = readAttributeValue(def, decodeAttrEntities(sourceValue));
1721
- }
1722
- }
1723
-
1724
- /** @param {string} s */
1725
- function camelCase(s) {
1726
- return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1727
- }
1728
-
1729
- /**
1730
- * Inverse of camelCase. `userName` -> `user-name`, `userID` -> `user-i-d`.
1731
- * Used to serialize property-binding names into HTML attribute names,
1732
- * which are case-insensitive in the parser. The original JS property
1733
- * name is recovered via camelCase() on the consumer side.
1734
- *
1735
- * @param {string} s
1736
- */
1737
- function kebabCase(s) {
1738
- return s.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
1739
- }
1740
-
1741
- /** windows-1252 mappings the HTML tokenizer applies to the C1 range. */
1742
- const C1_REPLACEMENTS = {
1743
- 0x80: 0x20ac, 0x82: 0x201a, 0x83: 0x0192, 0x84: 0x201e, 0x85: 0x2026,
1744
- 0x86: 0x2020, 0x87: 0x2021, 0x88: 0x02c6, 0x89: 0x2030, 0x8a: 0x0160,
1745
- 0x8b: 0x2039, 0x8c: 0x0152, 0x8e: 0x017d, 0x91: 0x2018, 0x92: 0x2019,
1746
- 0x93: 0x201c, 0x94: 0x201d, 0x95: 0x2022, 0x96: 0x2013, 0x97: 0x2014,
1747
- 0x98: 0x02dc, 0x99: 0x2122, 0x9a: 0x0161, 0x9b: 0x203a, 0x9c: 0x0153,
1748
- 0x9e: 0x017e, 0x9f: 0x0178,
1749
- };
1750
-
1751
- // The trailing `;` is OPTIONAL on the named arm, because a browser decodes a
1752
- // legacy semicolon-less reference too. The callback decides which of the two
1753
- // forms it has; see `decodeNamed`.
1754
- const CHAR_REF = /&(?:#(\d+);?|#[xX]([0-9a-fA-F]+);?|([a-zA-Z][a-zA-Z0-9]*)(;?))/g;
1755
-
1756
- // A Map, not the imported object, so a name that collides with something on
1757
- // `Object.prototype` misses instead of returning a function. See `decodeNamed`.
1758
- const NAMED = new Map(Object.entries(NAMED_ENTITIES));
1759
- const LEGACY = new Set(LEGACY_NAMES);
1760
-
1761
- /**
1762
- * Decode HTML character references in an attribute value.
1763
- *
1764
- * `parseAttrs` hands back the literal characters between the quote marks, so
1765
- * nothing has decoded them yet, while a browser decodes EVERY reference before
1766
- * any reader sees the value. This closes that gap (#1341): the full WHATWG
1767
- * named table plus decimal and hexadecimal numeric references, with the
1768
- * tokenizer's own numeric fix-ups (null, a surrogate, and anything past
1769
- * U+10FFFF become U+FFFD; the C1 range maps through windows-1252). It replaced
1770
- * a three-entity `unescapeAttr`, which left a `String`-typed prop undecoded
1771
- * entirely and turned `&lt;script&gt;` into the half-decoded `<script&gt;`.
1772
- *
1773
- * SINGLE PASS on purpose. A replacement is never rescanned, so `&amp;lt;`
1774
- * decodes to the literal `&lt;` and never to `<`. The old function got that
1775
- * from replacing `&amp;` last, which does not generalise past three entities.
1776
- *
1777
- * The 106 legacy semicolon-LESS names are covered too, because a browser really
1778
- * does decode them and measurably: Chromium, Firefox, and WebKit all hand a
1779
- * reader U+00A0 for `s="&nbsp"`. Leaving them literal would have been a value
1780
- * divergence of exactly the kind this function exists to remove, not a
1781
- * harmless non-goal. The rule that governs them, in an ATTRIBUTE value, is a
1782
- * one-character LOOKAHEAD rather than deep tokenizer state, which is why it is
1783
- * implementable here. `decodeNamed` carries the rule and the reason it takes
1784
- * the shape it does; the short version is that `&nbsp` at the end of a value
1785
- * decodes while `&nbspx`, `&nbsp=x`, and `&notin` stay literal, all three
1786
- * verified against the three engines.
1787
- *
1788
- * The same function also decodes `data-webjs-fallback`, which is MARKUP, where
1789
- * the tokenizer applies no such carve-out. Using the attribute rule there is
1790
- * deliberate and strictly conservative: that payload is written by
1791
- * `escapeAttr`, which emits only `&amp;` / `&quot;` / `&lt;`, so every
1792
- * reference in it is semicolon-terminated and never reaches this path.
1793
- *
1794
- * @param {string} s
1795
- * @returns {string}
1796
- */
1797
- function decodeAttrEntities(s) {
1798
- // Load bearing, not a micro-optimisation: skipping the scan for the common
1799
- // no-`&` value is what makes this cheaper per attribute than the three
1800
- // chained `replace` calls it replaced, which paid for three passes always.
1801
- if (s.indexOf('&') === -1) return s;
1802
- return s.replace(CHAR_REF, (match, dec, hex, name, semi, offset) => {
1803
- if (dec !== undefined) return fromCodePoint(parseInt(dec, 10));
1804
- if (hex !== undefined) return fromCodePoint(parseInt(hex, 16));
1805
- return decodeNamed(match, name, semi === ';', s[offset + match.length]);
1806
- });
1807
- }
1808
-
1809
- /**
1810
- * Resolve one named reference, semicolon-terminated or legacy.
1811
- *
1812
- * The table is read through a `Map` rather than by indexing the imported
1813
- * object. An object-literal lookup resolves through `Object.prototype`, so
1814
- * `&constructor;` / `&toString;` / `&hasOwnProperty;` and four more returned a
1815
- * FUNCTION instead of `undefined` and threw on the spread in
1816
- * `codePointsToString`, a path `seedServerAttrs` reaches for every attribute of
1817
- * every custom element, which rendered the whole component as an SSR error box.
1818
- * A browser leaves those literal, since they are not named references, so the
1819
- * throw was a divergence of exactly the kind this file exists to remove. A
1820
- * `Map` has no prototype chain to fall through, which closes the shape rather
1821
- * than guarding one call site.
1822
- *
1823
- * WHY THERE IS NO LONGEST-PREFIX LOOP. The tokenizer consumes the longest name
1824
- * in the table, so `&notin` is `&not` followed by `in`. Here that always
1825
- * collapses to the whole name: `CHAR_REF` captures `[a-zA-Z][a-zA-Z0-9]*`, so a
1826
- * prefix SHORTER than the name is by construction followed by an ASCII
1827
- * alphanumeric, which is precisely when the attribute carve-out declines to
1828
- * decode. A loop over shorter prefixes could therefore only ever return
1829
- * `match`, which is what falling through to the end already does. `&notin`
1830
- * stays literal either way, verified against the three engines, though note it
1831
- * gets there by not being a legacy name rather than by the carve-out.
1832
- *
1833
- * That same greediness means an ASCII alphanumeric character can never follow
1834
- * the match: whatever follows is by construction not `[a-zA-Z0-9]`, or the
1835
- * capture would have eaten it. So only the `=` check is needed for the
1836
- * attribute carve-out. `&nbspx` is literal because `nbspx` is not a legacy
1837
- * name, NOT because of the lookahead; `&nbsp=x` is the shape the lookahead
1838
- * actually decides.
1839
- *
1840
- * @param {string} match the whole matched reference, returned unchanged when nothing decodes
1841
- * @param {string} name the name, with no `&` and no `;`
1842
- * @param {boolean} hadSemi
1843
- * @param {string|undefined} nextChar the character after the match, if any
1844
- * @returns {string}
1845
- */
1846
- function decodeNamed(match, name, hadSemi, nextChar) {
1847
- if (hadSemi) {
1848
- const cp = NAMED.get(name);
1849
- return cp === undefined ? match : codePointsToString(cp);
1850
- }
1851
- if (!LEGACY.has(name)) return match;
1852
- // The attribute carve-out: a legacy name decodes only when what follows is
1853
- // neither `=` nor an ASCII alphanumeric. Nothing following at all (the end of
1854
- // the value) decodes, which is the common `s="&nbsp"` shape. Because CHAR_REF
1855
- // captures greedily, what follows is never an ASCII alphanumeric, so only `=`
1856
- // needs to be checked here.
1857
- if (nextChar === '=') return match;
1858
- // Every legacy name is in the table under the same name, asserted by a test
1859
- // rather than left to trust, so this cannot miss.
1860
- return codePointsToString(NAMED.get(name));
1861
- }
1862
-
1863
- /** @param {number|number[]} cp */
1864
- function codePointsToString(cp) {
1865
- return typeof cp === 'number' ? String.fromCodePoint(cp) : String.fromCodePoint(...cp);
1866
- }
1867
-
1868
- /**
1869
- * The tokenizer's numeric character reference fix-ups.
1870
- * @param {number} n
1871
- * @returns {string}
1872
- */
1873
- function fromCodePoint(n) {
1874
- if (n === 0 || n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return '\uFFFD';
1875
- if (C1_REPLACEMENTS[n] !== undefined) return String.fromCodePoint(C1_REPLACEMENTS[n]);
1876
- return String.fromCodePoint(n);
1877
- }
1878
-
1879
- /**
1880
- * Decode `data-webjs-prop-<kebab>` attributes from a parsed attribute
1881
- * map, returning a map of camelCase property name to decoded value.
1882
- * Mutates `attrs` by deleting the consumed entries so they do not
1883
- * appear in the rendered output a second time.
1884
- *
1885
- * @param {Record<string,string>} attrs
1886
- * @returns {Record<string, unknown>}
1887
- */
1888
- function consumePropAttrs(attrs) {
1889
- /** @type {Record<string, unknown>} */
1890
- const props = {};
1891
- for (const key of Object.keys(attrs)) {
1892
- if (!key.startsWith('data-webjs-prop-')) continue;
1893
- const propName = camelCase(key.slice('data-webjs-prop-'.length));
1894
- try {
1895
- props[propName] = parse(decodeAttrEntities(attrs[key]));
1896
- } catch {
1897
- // Malformed payload. Skip silently so the rest of the component
1898
- // can still render. The client-side hydration will also try and
1899
- // fail, which is fine: undefined-prop semantics.
1900
- }
1901
- delete attrs[key];
1902
- }
1903
- return props;
1904
- }
1905
-
1906
- // ---------------------------------------------------------------------------
1907
- // Streaming renderer
1908
- // ---------------------------------------------------------------------------
1909
-
1910
- /**
1911
- * Render a TemplateResult (or any renderable value) to a `ReadableStream`
1912
- * that yields HTML chunks as strings.
1913
- *
1914
- * Works identically to {@link renderToString} but streams partial HTML as
1915
- * it is rendered: avoiding buffering the entire page in memory. For
1916
- * Suspense boundaries, the fallback is yielded immediately and resolved
1917
- * content is streamed afterwards at the end of the response.
1918
- *
1919
- * **AI hint:** Use `renderToStream` when you want to pipe SSR output
1920
- * directly into a `Response` for streaming delivery (e.g. HTTP chunked
1921
- * transfer). It accepts the same arguments as `renderToString`.
1922
- *
1923
- * @param {unknown} value A TemplateResult, string, array, or any renderable.
1924
- * @param {{ ssr?: boolean, suspenseCtx?: SuspenseCtx }} [opts]
1925
- * @returns {ReadableStream<string>}
1926
- */
1927
- export function renderToStream(value, opts = { ssr: true }) {
1928
- const ctx = opts && opts.suspenseCtx;
1929
- // Server dev flag for prod-silence of SSR error states (#483), same sourcing
1930
- // as renderToString: opts.dev wins, else inherit from the ctx, else undefined
1931
- // (NODE_ENV fallback). Back-fill the ctx so the streamed sub-renders share it.
1932
- const dev = opts && opts.dev !== undefined ? opts.dev : ctx && ctx.dev;
1933
- if (ctx && ctx.dev === undefined && dev !== undefined) ctx.dev = dev;
1934
- return new ReadableStream({
1935
- async start(controller) {
1936
- try {
1937
- if (opts && opts.ssr === false) {
1938
- // No DSD injection: just stream the raw rendered chunks.
1939
- await streamRender(value, ctx, controller, 'none');
1940
- } else {
1941
- // Render to string first to run DSD injection (which operates on
1942
- // the full HTML), then enqueue the result. This matches the
1943
- // semantics of renderToString but still gives us a stream.
1944
- const html = await render(value, ctx);
1945
- const full = await injectDSD(html, ctx, [], dev);
1946
- controller.enqueue(full);
1947
- }
1948
-
1949
- // Stream resolved Suspense boundaries after the main content.
1950
- if (ctx && ctx.pending.length) {
1951
- await streamSuspenseBoundaries(ctx, controller, dev);
1952
- }
1953
- controller.close();
1954
- } catch (err) {
1955
- controller.error(err);
1956
- }
1957
- },
1958
- });
1959
- }
1960
-
1961
- /**
1962
- * Recursively render a value, enqueuing HTML chunks into the stream
1963
- * controller as they become available.
1964
- *
1965
- * @param {unknown} value
1966
- * @param {SuspenseCtx} [ctx]
1967
- * @param {ReadableStreamDefaultController<string>} controller
1968
- */
1969
- async function streamRender(value, ctx, controller) {
1970
- if (value == null || value === false || value === true) return;
1971
- if (value && typeof /** @type any */ (value).then === 'function') {
1972
- value = await value;
1973
- return streamRender(value, ctx, controller);
1974
- }
1975
- if (isUnsafeHTML(value)) {
1976
- controller.enqueue(String(/** @type any */ (value).value ?? ''));
1977
- return;
1978
- }
1979
- if (isLive(value)) {
1980
- return streamRender(/** @type any */ (value).value, ctx, controller);
1981
- }
1982
- if (isWatch(value)) {
1983
- return streamRender(/** @type any */ (value).signal.get(), ctx, controller);
1984
- }
1985
- if (isKeyed(value)) {
1986
- return streamRender(/** @type any */ (value).value, ctx, controller);
1987
- }
1988
- if (isGuard(value)) {
1989
- return streamRender(/** @type any */ (value).fn(), ctx, controller);
1990
- }
1991
- if (isTemplateContent(value)) {
1992
- const tpl = /** @type any */ (value).template;
1993
- controller.enqueue(String(tpl?.innerHTML ?? ''));
1994
- return;
1995
- }
1996
- if (isRef(value)) {
1997
- return;
1998
- }
1999
- if (isCache(value)) {
2000
- return streamRender(/** @type any */ (value).value, ctx, controller);
2001
- }
2002
- if (isUntil(value)) {
2003
- const args = /** @type any */ (value).args;
2004
- for (const a of args) {
2005
- if (!a || typeof (/** @type any */ (a).then) !== 'function') {
2006
- return streamRender(a, ctx, controller);
2007
- }
2008
- }
2009
- if (args.length > 0) {
2010
- try {
2011
- const winner = await Promise.race(args.map((p) => Promise.resolve(p).catch(() => undefined)));
2012
- return streamRender(winner, ctx, controller);
2013
- } catch {
2014
- return;
2015
- }
2016
- }
2017
- return;
2018
- }
2019
- if (isAsyncAppend(value) || isAsyncReplace(value)) {
2020
- return;
2021
- }
2022
- if (Array.isArray(value)) {
2023
- for (const v of value) await streamRender(v, ctx, controller);
2024
- return;
2025
- }
2026
- if (isRepeat(value)) {
2027
- const r = /** @type any */ (value);
2028
- for (let i = 0; i < r.items.length; i++) {
2029
- await streamRender(r.templateFn(r.items[i], i), ctx, controller);
2030
- }
2031
- return;
2032
- }
2033
- if (isSuspense(value)) {
2034
- const s = /** @type any */ (value);
2035
- if (ctx) {
2036
- const id = `s${ctx.nextId++}`;
2037
- controller.enqueue(`<webjs-boundary id="${id}">`);
2038
- await streamRender(s.fallback, ctx, controller);
2039
- controller.enqueue(`</webjs-boundary>`);
2040
- ctx.pending.push({ id, promise: Promise.resolve(s.children) });
2041
- } else {
2042
- await streamRender(s.fallback, ctx, controller);
2043
- }
2044
- return;
2045
- }
2046
- if (isTemplate(value)) {
2047
- await streamTemplate(/** @type any */ (value), ctx, controller);
2048
- return;
2049
- }
2050
- controller.enqueue(escapeText(String(value)));
2051
- }
2052
-
2053
- /**
2054
- * Stream a TemplateResult by yielding each static string piece and
2055
- * processing each value hole incrementally.
2056
- *
2057
- * @param {import('./html.js').TemplateResult} tr
2058
- * @param {SuspenseCtx} [ctx]
2059
- * @param {ReadableStreamDefaultController<string>} controller
2060
- */
2061
- async function streamTemplate(tr, ctx, controller) {
2062
- const { strings, values } = tr;
2063
- let state = 'text';
2064
- let attrName = '';
2065
- let attrStart = 0;
2066
- let attrQuote = '';
2067
- let commentDashes = 0;
2068
- let currentTag = '';
2069
- let rawTail = '';
2070
- // Buffer used for attribute handling where we may need to backtrack.
2071
- let buf = '';
2072
- let tagStart = -1;
2073
- /** @type {string | null} */
2074
- let pendingActionId = null;
2075
- // Shapes on the CURRENT start tag that a bound form may not carry (#1155).
2076
- // Collected as the tag is scanned and judged at its `>`, because the action
2077
- // hole may come after them.
2078
- let pendingActionCount = 0;
2079
- /** @type {string[]} */
2080
- let pendingPropAttrs = [];
2081
- /** @type {string[]} */
2082
- let pendingSubmitterProps = [];
2083
- /** @type {string | null} */
2084
- let pendingSubmitterTag = null; // tag of a bound submitter, until it closes
2085
- let isCloseTag = false;
2086
-
2087
- // See the buffered machine for why this runs at the `>` rather than at the
2088
- // hole. `tagStart` indexes into `buf`, which is safe because `buf` is only
2089
- // flushed on a `text`-state hole and a start tag contains none.
2090
- const closeBoundFormTag = () => {
2091
- // Reset per tag whether or not this one was bound, so a later form is never
2092
- // judged on an earlier tag's shapes.
2093
- const propAttrs = pendingPropAttrs;
2094
- const submitterProps = pendingSubmitterProps;
2095
- const duplicateAction = pendingActionCount > 1;
2096
- const submitterTag = pendingSubmitterTag;
2097
- pendingPropAttrs = [];
2098
- pendingSubmitterProps = [];
2099
- pendingActionCount = 0;
2100
- pendingSubmitterTag = null;
2101
- if (pendingActionId != null) {
2102
- assertConvergentBoundForm({ duplicateAction, propAttrs });
2103
- const bound = bindFormActionStartTag(buf.slice(tagStart), pendingActionId);
2104
- buf = buf.slice(0, tagStart) + bound.tag + bound.hidden;
2105
- pendingActionId = null;
2106
- }
2107
- if (submitterTag != null) {
2108
- // #1307, the SAME injection as the buffered machine, through the same
2109
- // helper, so this second state machine cannot drift from it.
2110
- buf = buf.slice(0, tagStart)
2111
- + bindSubmitterStartTag(buf.slice(tagStart), submitterTag, { duplicateAction, propAttrs: submitterProps });
2112
- }
2113
- };
2114
- // #1155: a `.method` / `.enctype` / `.encoding` prop on a form is dropped
2115
- // here but applied for real in the browser, where all three are reflected IDL
2116
- // attributes, so a bound form carrying one submits differently with JS than
2117
- // without it. Recorded and refused at the `>`, once the tag's action hole is
2118
- // known.
2119
- const notePropAttr = (name, tag) => {
2120
- const t = String(tag).toLowerCase();
2121
- if (t === 'button' || t === 'input') {
2122
- // #1207: the submitter twin. `name` / `value` / `formAction` / `formMethod`
2123
- // / `formEnctype` all reflect on a submitter, so a `.prop` spelling is
2124
- // dropped here and written to the attribute in the browser.
2125
- if (isSubmitterReflectedProp(name)) pendingSubmitterProps.push(String(name));
2126
- return;
2127
- }
2128
- if (t !== 'form') return;
2129
- let n = String(name).toLowerCase();
2130
- if (n === 'encoding') n = 'enctype';
2131
- if (n === 'method' || n === 'enctype') pendingPropAttrs.push(String(name));
2132
- };
2133
- const noteActionHole = (name, tag) => {
2134
- const t = String(tag).toLowerCase();
2135
- const n = String(name).toLowerCase();
2136
- if ((t === 'form' && n === 'action') ||
2137
- ((t === 'button' || t === 'input') && n === 'formaction')) {
2138
- pendingActionCount += 1;
2139
- }
2140
- };
2141
-
2142
- // Same contract as the buffered machine, `allowRawtext` included: only the
2143
- // `tag-name` and `in-tag` exits ever entered rawtext here either, so a start
2144
- // tag ending on a bare or unquoted attribute must keep escaping its body.
2145
- const handleTagEnd = (allowRawtext) => {
2146
- closeBoundFormTag();
2147
- isCloseTag = false;
2148
- state = allowRawtext && isRawtextTag(currentTag) ? 'rawtext' : 'text';
2149
- if (state === 'rawtext') rawTail = '';
2150
- };
2151
-
2152
- for (let i = 0; i < strings.length; i++) {
2153
- const s = strings[i];
2154
- for (let j = 0; j < s.length; j++) {
2155
- const c = s[j];
2156
- switch (state) {
2157
- case 'text':
2158
- buf += c;
2159
- if (c === '<') { state = 'tag-open'; tagStart = buf.length - 1; isCloseTag = false; }
2160
- break;
2161
- case 'tag-open':
2162
- buf += c;
2163
- if (c === '!') state = 'bang-1';
2164
- else if (c === '/') { state = 'tag-name'; currentTag = ''; isCloseTag = true; }
2165
- else if (/[a-zA-Z]/.test(c)) { state = 'tag-name'; currentTag = c.toLowerCase(); }
2166
- else state = 'text';
2167
- break;
2168
- case 'bang-1':
2169
- buf += c;
2170
- state = c === '-' ? 'bang-dash' : 'tag-name';
2171
- break;
2172
- case 'bang-dash':
2173
- buf += c;
2174
- if (c === '-') { state = 'comment'; commentDashes = 0; }
2175
- else state = 'tag-name';
2176
- break;
2177
- case 'comment':
2178
- buf += c;
2179
- if (c === '-') commentDashes += 1;
2180
- else if (c === '>' && commentDashes >= 2) { state = 'text'; commentDashes = 0; }
2181
- else commentDashes = 0;
2182
- break;
2183
- case 'tag-name':
2184
- buf += c;
2185
- if (c === '>') {
2186
- handleTagEnd(true);
2187
- } else if (/\s/.test(c)) state = 'in-tag';
2188
- else currentTag += c.toLowerCase();
2189
- break;
2190
- case 'in-tag':
2191
- buf += c;
2192
- if (c === '>') {
2193
- handleTagEnd(true);
2194
- } else if (!/\s/.test(c) && c !== '/') {
2195
- state = 'attr-name';
2196
- attrName = c;
2197
- attrStart = buf.length - 1;
2198
- }
2199
- break;
2200
- case 'rawtext':
2201
- buf += c;
2202
- rawTail = (rawTail + c.toLowerCase()).slice(-9);
2203
- if (rawTail.endsWith('</script>') || rawTail.endsWith('</style>')) {
2204
- state = 'text';
2205
- rawTail = '';
2206
- currentTag = '';
2207
- }
2208
- break;
2209
- case 'attr-name':
2210
- if (c === '=') { state = 'after-eq'; buf += c; }
2211
- else if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; buf += c; }
2212
- else if (c === '>') { state = 'text'; attrName = ''; buf += c; handleTagEnd(false); }
2213
- else { attrName += c; buf += c; }
2214
- break;
2215
- case 'after-eq':
2216
- if (c === '"' || c === "'") { state = 'attr-quoted'; attrQuote = c; buf += c; }
2217
- else if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; buf += c; }
2218
- else if (c === '>') { state = 'text'; attrName = ''; buf += c; handleTagEnd(false); }
2219
- else { state = 'attr-unquoted'; buf += c; }
2220
- break;
2221
- case 'attr-unquoted':
2222
- if (/\s/.test(c)) { state = 'in-tag'; attrName = ''; buf += c; }
2223
- else if (c === '>') { state = 'text'; attrName = ''; buf += c; handleTagEnd(false); }
2224
- else buf += c;
2225
- break;
2226
- case 'attr-quoted':
2227
- buf += c;
2228
- if (c === attrQuote) { state = 'in-tag'; attrName = ''; }
2229
- break;
2230
- }
2231
- }
2232
-
2233
- // Flush the buffer before processing the value hole: but only when
2234
- // we're in text state (in attribute states we may need the buffer for
2235
- // backtracking).
2236
- if (i < values.length) {
2237
- let val = values[i];
2238
- if (val && typeof /** @type any */ (val).then === 'function') {
2239
- val = await val;
2240
- }
2241
- if (state === 'comment') {
2242
- buf += String(val ?? '');
2243
- commentDashes = 0;
2244
- } else if (state === 'rawtext') {
2245
- buf += String(val ?? '');
2246
- rawTail = '';
2247
- } else if (state === 'text') {
2248
- // Flush the buffered static content before streaming the value.
2249
- if (buf) { controller.enqueue(buf); buf = ''; }
2250
- await streamRender(val, ctx, controller);
2251
- } else if (state === 'after-eq') {
2252
- const prefix = attrName[0];
2253
- const name = attrName.slice(1);
2254
- const kind = BINDING_PREFIXES[prefix];
2255
- if (kind === 'event' || kind === 'prop') {
2256
- // Guard `prop` ONLY, matching the buffered machine. An `@action`
2257
- // event binding is dropped here and never stringified, and a
2258
- // function is the LEGITIMATE value for one (`<my-el @action=${fn}>`
2259
- // listens for an `action` event), so refusing it would be a false
2260
- // positive. `.action` differs where the property REFLECTS: on a form
2261
- // (and `.formAction` on a button or input) the client assignment
2262
- // writes the source into the DOM, so refusing at SSR keeps a page
2263
- // from rendering clean on the server and throwing on hydration.
2264
- // Elsewhere the property reflects nothing and a function stays
2265
- // legal, which is why the check below is gated on a hyphen-free
2266
- // tag. A custom element is excluded for a different reason than
2267
- // "it does not reflect": a prop declared `reflect: true` DOES
2268
- // reflect there, and used to write the source from its own setter.
2269
- // #1169 guards that at the setter (a function removes the
2270
- // attribute; an array carrying one does too, except under an
2271
- // Object/Array type, where JSON drops it losslessly), so it
2272
- // needs no commit-site check here.
2273
- //
2274
- // Unlike the buffered machine this drops EVERY prop, including
2275
- // `<webjs-suspense .fallback>`: there is no injectDSD pre-pass on
2276
- // this path (it is reached only through `renderToStream(v, { ssr:
2277
- // false })`), so there is no consumer for a `data-webjs-fallback`
2278
- // and emitting one would put an attribute in the markup that nothing
2279
- // reads.
2280
- if (kind === 'prop' && !currentTag.includes('-')) {
2281
- assertNotFunctionReflectedActionProp(val, name, currentTag);
2282
- notePropAttr(name, currentTag);
2283
- }
2284
- buf = buf.slice(0, attrStart);
2285
- state = 'in-tag';
2286
- attrName = '';
2287
- } else if (kind === 'bool') {
2288
- // A boolean binding stringifies nothing, so this never leaked, but
2289
- // `?action=${fn}` is meaningless in every case (a truthy function
2290
- // emits a bare `action=""`), and refusing it keeps the rule the docs
2291
- // state true for every sigil rather than true only when quoted.
2292
- assertNotFunctionActionAttr(val, name, currentTag);
2293
- buf = buf.slice(0, attrStart);
2294
- if (val) buf += `${name}=""`;
2295
- state = 'in-tag';
2296
- attrName = '';
2297
- } else if (isBoundFormAction(val, attrName, currentTag)) {
2298
- noteActionHole(attrName, currentTag);
2299
- // The SAME bindings as the buffered renderer (#1155, #1207), in the
2300
- // second machine, so `renderToStream(v, { ssr: false })` emits an
2301
- // identical form rather than refusing one the page renderer accepts.
2302
- if (currentTag === 'form') {
2303
- pendingActionId = assertIdentifiableAction(await resolveFormActionId(val), currentTag);
2304
- buf = buf.slice(0, attrStart).replace(/\s+$/, '');
2305
- } else {
2306
- assertSingleSubmitterAction(pendingSubmitterTag != null, currentTag);
2307
- const attrs = parseStartTagAttrs(buf.slice(tagStart));
2308
- if (attrs.has('name')) assertSubmitterHasNoName(attrs.get('name') || '', currentTag, false);
2309
- if (attrs.has('value')) assertSubmitterHasNoValue(currentTag);
2310
- if (attrs.has('form')) assertSubmitterHasNoFormAttribute(currentTag);
2311
- const subId = assertIdentifiableAction(await resolveFormActionId(val), currentTag);
2312
- pendingSubmitterTag = currentTag;
2313
- buf = buf.slice(0, attrStart) + `name="${FORM_ACTION_FIELD}" value="${escapeAttr(subId)}"`;
2314
- }
2315
- state = 'in-tag';
2316
- attrName = '';
2317
- } else {
2318
- noteActionHole(attrName, currentTag);
2319
- // The SAME guard as the buffered renderer above. This is a second,
2320
- // independent state machine, so it inherits nothing from that one;
2321
- // a change to the rule has to land in both. Reached only via
2322
- // `renderToStream(v, { ssr: false })`, which no page render uses, so
2323
- // this covers the public API surface rather than a page leak.
2324
- assertNotFunctionActionAttr(val, attrName, currentTag);
2325
- buf += `"${escapeAttr(String(val ?? ''))}"`;
2326
- state = 'in-tag';
2327
- attrName = '';
2328
- }
2329
- } else if (state === 'attr-quoted' || state === 'attr-unquoted') {
2330
- assertNotFunctionActionAttr(val, attrName, currentTag);
2331
- buf += escapeAttr(String(val ?? ''));
2332
- }
2333
- }
2334
- }
2335
-
2336
- // Flush any remaining buffer content.
2337
- if (buf) controller.enqueue(buf);
2338
- }
2339
-
2340
- /**
2341
- * After the main HTML has been streamed, resolve pending Suspense promises
2342
- * and stream their replacement content as out-of-order `<template>` tags
2343
- * with tiny inline scripts that swap the fallback for the resolved HTML.
2344
- *
2345
- * @param {SuspenseCtx} ctx
2346
- * @param {ReadableStreamDefaultController<string>} controller
2347
- * @param {boolean} [dev] server dev flag for prod-silence of a rejected
2348
- * streamed boundary (#483); undefined falls back to NODE_ENV
2349
- */
2350
- async function streamSuspenseBoundaries(ctx, controller, dev) {
2351
- // Resolve the per-request nonce once per call. The provider in
2352
- // @webjsdev/server sources it from AsyncLocalStorage; outside a
2353
- // request scope (or in the browser) the helper returns '' and we
2354
- // emit the script unnonced, which is fine on documents not under
2355
- // strict CSP and matches the no-nonce case for the rest of the
2356
- // SSR pipeline.
2357
- const nonce = cspNonce();
2358
- const nonceAttr = nonce ? ` nonce="${escapeAttr(nonce)}"` : '';
2359
- while (ctx.pending.length) {
2360
- const batch = ctx.pending.splice(0);
2361
- await Promise.all(
2362
- batch.map(async ({ id, promise }) => {
2363
- try {
2364
- const resolved = await promise;
2365
- const html = await render(resolved, ctx);
2366
- const full = await injectDSD(html, ctx, [], dev);
2367
- controller.enqueue(
2368
- `<template data-webjs-resolve="${id}">${full}</template>` +
2369
- `<script${nonceAttr}>` +
2370
- `(function(){` +
2371
- `var t=document.currentScript.previousElementSibling;` +
2372
- `var b=document.getElementById("${id}");` +
2373
- `if(b&&t){b.replaceWith(t.content.cloneNode(true));t.remove()}` +
2374
- `document.currentScript.remove()` +
2375
- `})()` +
2376
- `</script>`
2377
- );
2378
- } catch (err) {
2379
- console.error(`[webjs] Suspense boundary "${id}" rejected:`, err);
2380
- // Render a boundary-scoped error state rather than leaving the
2381
- // fallback stuck forever (#471). Dev surfaces the message; prod
2382
- // renders a silent empty element (no leak). A failure HERE (the
2383
- // error render itself throwing) leaves the fallback in place.
2384
- try {
2385
- const e = err instanceof Error ? err : new Error(String(err));
2386
- const errHtml = await injectDSD(await render(defaultSSRErrorTemplate('webjs-suspense', e, dev), ctx), ctx, [], dev);
2387
- controller.enqueue(
2388
- `<template data-webjs-resolve="${id}">${errHtml}</template>` +
2389
- `<script${nonceAttr}>` +
2390
- `(function(){` +
2391
- `var t=document.currentScript.previousElementSibling;` +
2392
- `var b=document.getElementById("${id}");` +
2393
- `if(b&&t){b.replaceWith(t.content.cloneNode(true));t.remove()}` +
2394
- `document.currentScript.remove()` +
2395
- `})()` +
2396
- `</script>`
2397
- );
2398
- } catch (errorRenderThrew) {
2399
- console.error(`[webjs] Suspense boundary "${id}" error render also threw:`, errorRenderThrew);
2400
- }
2401
- }
2402
- })
2403
- );
2404
- }
2405
- }
1
+ // Public surface, byte-identical to the pre-split module. `injectDSD` is
2
+ // deliberately NOT re-exported: it is internal to `render-server/`, nothing
3
+ // outside imports it, and `render-server.d.ts` does not declare it. This file
4
+ // backs the published `@webjsdev/core/server` subpath, so re-exporting it would
5
+ // widen the package's public API for a helper no consumer asked for.
6
+ export { renderToString, renderToStream } from './render-server/stream.js';