preact-render-to-string 6.4.2 → 6.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/commonjs.js +1 -1
  2. package/dist/commonjs.js.map +1 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/index.module.js +1 -1
  6. package/dist/index.module.js.map +1 -1
  7. package/dist/index.umd.js +1 -1
  8. package/dist/index.umd.js.map +1 -1
  9. package/dist/internal.d.ts +35 -0
  10. package/dist/jsx-entry.js +1 -1
  11. package/dist/jsx-entry.js.map +1 -1
  12. package/dist/jsx.js.map +1 -1
  13. package/dist/jsx.mjs +1 -1
  14. package/dist/jsx.mjs.map +1 -1
  15. package/dist/jsx.module.js +1 -1
  16. package/dist/jsx.module.js.map +1 -1
  17. package/dist/jsx.umd.js +1 -1
  18. package/dist/jsx.umd.js.map +1 -1
  19. package/dist/stream-node.js +786 -0
  20. package/dist/stream-node.js.map +1 -0
  21. package/dist/stream-node.module.js +786 -0
  22. package/dist/stream-node.module.js.map +1 -0
  23. package/dist/stream-node.umd.js +790 -0
  24. package/dist/stream-node.umd.js.map +1 -0
  25. package/dist/stream.js +2 -0
  26. package/dist/stream.js.map +1 -0
  27. package/dist/stream.module.js +2 -0
  28. package/dist/stream.module.js.map +1 -0
  29. package/dist/stream.umd.js +2 -0
  30. package/dist/stream.umd.js.map +1 -0
  31. package/jsx.d.ts +1 -1
  32. package/package.json +166 -157
  33. package/src/index.js +54 -18
  34. package/src/internal.d.ts +35 -0
  35. package/src/jsx.js +2 -4
  36. package/src/lib/chunked.js +97 -0
  37. package/src/lib/client.js +61 -0
  38. package/src/{constants.js → lib/constants.js} +3 -0
  39. package/src/{util.js → lib/util.js} +13 -1
  40. package/src/pretty.js +13 -13
  41. package/src/stream-node.js +60 -0
  42. package/src/stream.js +43 -0
  43. /package/src/{polyfills.js → lib/polyfills.js} +0 -0
@@ -0,0 +1,790 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('node:stream'), require('preact')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'node:stream', 'preact'], factory) :
4
+ (global = global || self, factory(global.preactRenderToString = {}, global.node_stream, global.preact));
5
+ }(this, (function (exports, node_stream, preact) {
6
+ const UNSAFE_NAME = /[\s\n\\/='"\0<>]/;
7
+ const NAMESPACE_REPLACE_REGEX = /^(xlink|xmlns|xml)([A-Z])/;
8
+ const HTML_LOWER_CASE = /^accessK|^auto[A-Z]|^cell|^ch|^col|cont|cross|dateT|encT|form[A-Z]|frame|hrefL|inputM|maxL|minL|noV|playsI|popoverT|readO|rowS|spellC|src[A-Z]|tabI|useM|item[A-Z]/;
9
+ const SVG_CAMEL_CASE = /^ac|^ali|arabic|basel|cap|clipPath$|clipRule$|color|dominant|enable|fill|flood|font|glyph[^R]|horiz|image|letter|lighting|marker[^WUH]|overline|panose|pointe|paint|rendering|shape|stop|strikethrough|stroke|text[^L]|transform|underline|unicode|units|^v[^i]|^w|^xH/; // DOM properties that should NOT have "px" added when numeric
10
+
11
+ const ENCODED_ENTITIES = /["&<]/;
12
+ /** @param {string} str */
13
+
14
+ function encodeEntities(str) {
15
+ // Skip all work for strings with no entities needing encoding:
16
+ if (str.length === 0 || ENCODED_ENTITIES.test(str) === false) return str;
17
+ let last = 0,
18
+ i = 0,
19
+ out = '',
20
+ ch = ''; // Seek forward in str until the next entity char:
21
+
22
+ for (; i < str.length; i++) {
23
+ switch (str.charCodeAt(i)) {
24
+ case 34:
25
+ ch = '&quot;';
26
+ break;
27
+
28
+ case 38:
29
+ ch = '&amp;';
30
+ break;
31
+
32
+ case 60:
33
+ ch = '&lt;';
34
+ break;
35
+
36
+ default:
37
+ continue;
38
+ } // Append skipped/buffered characters and the encoded entity:
39
+
40
+
41
+ if (i !== last) out += str.slice(last, i);
42
+ out += ch; // Start the next seek/buffer after the entity's offset:
43
+
44
+ last = i + 1;
45
+ }
46
+
47
+ if (i !== last) out += str.slice(last, i);
48
+ return out;
49
+ }
50
+ const JS_TO_CSS = {};
51
+ const IS_NON_DIMENSIONAL = new Set(['animation-iteration-count', 'border-image-outset', 'border-image-slice', 'border-image-width', 'box-flex', 'box-flex-group', 'box-ordinal-group', 'column-count', 'fill-opacity', 'flex', 'flex-grow', 'flex-negative', 'flex-order', 'flex-positive', 'flex-shrink', 'flood-opacity', 'font-weight', 'grid-column', 'grid-row', 'line-clamp', 'line-height', 'opacity', 'order', 'orphans', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'tab-size', 'widows', 'z-index', 'zoom']);
52
+ const CSS_REGEX = /[A-Z]/g; // Convert an Object style to a CSSText string
53
+
54
+ function styleObjToCss(s) {
55
+ let str = '';
56
+
57
+ for (let prop in s) {
58
+ let val = s[prop];
59
+
60
+ if (val != null && val !== '') {
61
+ const name = prop[0] == '-' ? prop : JS_TO_CSS[prop] || (JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase());
62
+ let suffix = ';';
63
+
64
+ if (typeof val === 'number' && // Exclude custom-attributes
65
+ !name.startsWith('--') && !IS_NON_DIMENSIONAL.has(name)) {
66
+ suffix = 'px;';
67
+ }
68
+
69
+ str = str + name + ':' + val + suffix;
70
+ }
71
+ }
72
+
73
+ return str || undefined;
74
+ }
75
+ /**
76
+ * @template T
77
+ */
78
+
79
+ class Deferred {
80
+ constructor() {
81
+ // eslint-disable-next-line lines-around-comment
82
+
83
+ /** @type {Promise<T>} */
84
+ this.promise = new Promise((resolve, reject) => {
85
+ this.resolve = resolve;
86
+ this.reject = reject;
87
+ });
88
+ }
89
+
90
+ }
91
+
92
+ // Options hooks
93
+ const DIFF = '__b';
94
+ const RENDER = '__r';
95
+ const DIFFED = 'diffed';
96
+ const COMMIT = '__c';
97
+ const SKIP_EFFECTS = '__s';
98
+ const CATCH_ERROR = '__e'; // VNode properties
99
+
100
+ const COMPONENT = '__c';
101
+ const CHILDREN = '__k';
102
+ const PARENT = '__';
103
+
104
+ const VNODE = '__v';
105
+ const DIRTY = '__d';
106
+ const NEXT_STATE = '__s';
107
+ const CHILD_DID_SUSPEND = '__c';
108
+
109
+ const EMPTY_ARR = [];
110
+ const isArray = Array.isArray;
111
+ const assign = Object.assign; // Global state for the current render pass
112
+
113
+ let beforeDiff, afterDiff, renderHook, ummountHook;
114
+ /**
115
+ * Render Preact JSX + Components to an HTML string.
116
+ * @param {VNode} vnode JSX Element / VNode to render
117
+ * @param {Object} [context={}] Initial root context object
118
+ * @param {RendererState} [_rendererState] for internal use
119
+ * @returns {string} serialized HTML
120
+ */
121
+
122
+ function renderToString(vnode, context, _rendererState) {
123
+ // Performance optimization: `renderToString` is synchronous and we
124
+ // therefore don't execute any effects. To do that we pass an empty
125
+ // array to `options._commit` (`__c`). But we can go one step further
126
+ // and avoid a lot of dirty checks and allocations by setting
127
+ // `options._skipEffects` (`__s`) too.
128
+ const previousSkipEffects = preact.options[SKIP_EFFECTS];
129
+ preact.options[SKIP_EFFECTS] = true; // store options hooks once before each synchronous render call
130
+
131
+ beforeDiff = preact.options[DIFF];
132
+ afterDiff = preact.options[DIFFED];
133
+ renderHook = preact.options[RENDER];
134
+ ummountHook = preact.options.unmount;
135
+ const parent = preact.h(preact.Fragment, null);
136
+ parent[CHILDREN] = [vnode];
137
+
138
+ try {
139
+ return _renderToString(vnode, context || EMPTY_OBJ, false, undefined, parent, false, _rendererState);
140
+ } catch (e) {
141
+ if (e.then) {
142
+ throw new Error('Use "renderToStringAsync" for suspenseful rendering.');
143
+ }
144
+
145
+ throw e;
146
+ } finally {
147
+ // options._commit, we don't schedule any effects in this library right now,
148
+ // so we can pass an empty queue to this hook.
149
+ if (preact.options[COMMIT]) preact.options[COMMIT](vnode, EMPTY_ARR);
150
+ preact.options[SKIP_EFFECTS] = previousSkipEffects;
151
+ EMPTY_ARR.length = 0;
152
+ }
153
+ }
154
+
155
+ function markAsDirty() {
156
+ this.__d = true;
157
+ }
158
+
159
+ const EMPTY_OBJ = {};
160
+ /**
161
+ * @param {VNode} vnode
162
+ * @param {Record<string, unknown>} context
163
+ */
164
+
165
+ function renderClassComponent(vnode, context) {
166
+ let type =
167
+ /** @type {import("preact").ComponentClass<typeof vnode.props>} */
168
+ vnode.type;
169
+ let isMounting = true;
170
+ let c;
171
+
172
+ if (vnode[COMPONENT]) {
173
+ isMounting = false;
174
+ c = vnode[COMPONENT];
175
+ c.state = c[NEXT_STATE];
176
+ } else {
177
+ c = new type(vnode.props, context);
178
+ }
179
+
180
+ vnode[COMPONENT] = c;
181
+ c[VNODE] = vnode;
182
+ c.props = vnode.props;
183
+ c.context = context; // turn off stateful re-rendering:
184
+
185
+ c[DIRTY] = true;
186
+ if (c.state == null) c.state = EMPTY_OBJ;
187
+
188
+ if (c[NEXT_STATE] == null) {
189
+ c[NEXT_STATE] = c.state;
190
+ }
191
+
192
+ if (type.getDerivedStateFromProps) {
193
+ c.state = assign({}, c.state, type.getDerivedStateFromProps(c.props, c.state));
194
+ } else if (isMounting && c.componentWillMount) {
195
+ c.componentWillMount(); // If the user called setState in cWM we need to flush pending,
196
+ // state updates. This is the same behaviour in React.
197
+
198
+ c.state = c[NEXT_STATE] !== c.state ? c[NEXT_STATE] : c.state;
199
+ } else if (!isMounting && c.componentWillUpdate) {
200
+ c.componentWillUpdate();
201
+ }
202
+
203
+ if (renderHook) renderHook(vnode);
204
+ return c.render(c.props, c.state, context);
205
+ }
206
+ /**
207
+ * Recursively render VNodes to HTML.
208
+ * @param {VNode|any} vnode
209
+ * @param {any} context
210
+ * @param {boolean} isSvgMode
211
+ * @param {any} selectValue
212
+ * @param {VNode} parent
213
+ * @param {boolean} asyncMode
214
+ * @param {RendererState | undefined} [renderer]
215
+ * @returns {string | Promise<string> | (string | Promise<string>)[]}
216
+ */
217
+
218
+
219
+ function _renderToString(vnode, context, isSvgMode, selectValue, parent, asyncMode, renderer) {
220
+ // Ignore non-rendered VNodes/values
221
+ if (vnode == null || vnode === true || vnode === false || vnode === '') {
222
+ return '';
223
+ } // Text VNodes: escape as HTML
224
+
225
+
226
+ if (typeof vnode !== 'object') {
227
+ if (typeof vnode === 'function') return '';
228
+ return encodeEntities(vnode + '');
229
+ } // Recurse into children / Arrays
230
+
231
+
232
+ if (isArray(vnode)) {
233
+ let rendered = '',
234
+ renderArray;
235
+ parent[CHILDREN] = vnode;
236
+
237
+ for (let i = 0; i < vnode.length; i++) {
238
+ let child = vnode[i];
239
+ if (child == null || typeof child === 'boolean') continue;
240
+
241
+ const childRender = _renderToString(child, context, isSvgMode, selectValue, parent, asyncMode, renderer);
242
+
243
+ if (typeof childRender === 'string') {
244
+ rendered += childRender;
245
+ } else {
246
+ renderArray = renderArray || [];
247
+ if (rendered) renderArray.push(rendered);
248
+ rendered = '';
249
+
250
+ if (Array.isArray(childRender)) {
251
+ renderArray.push(...childRender);
252
+ } else {
253
+ renderArray.push(childRender);
254
+ }
255
+ }
256
+ }
257
+
258
+ if (renderArray) {
259
+ if (rendered) renderArray.push(rendered);
260
+ return renderArray;
261
+ }
262
+
263
+ return rendered;
264
+ } // VNodes have {constructor:undefined} to prevent JSON injection:
265
+
266
+
267
+ if (vnode.constructor !== undefined) return '';
268
+ vnode[PARENT] = parent;
269
+ if (beforeDiff) beforeDiff(vnode);
270
+ let type = vnode.type,
271
+ props = vnode.props,
272
+ cctx = context,
273
+ contextType,
274
+ rendered,
275
+ component; // Invoke rendering on Components
276
+
277
+ if (typeof type === 'function') {
278
+ if (type === preact.Fragment) {
279
+ // Serialized precompiled JSX.
280
+ if (props.tpl) {
281
+ let out = '';
282
+
283
+ for (let i = 0; i < props.tpl.length; i++) {
284
+ out += props.tpl[i];
285
+
286
+ if (props.exprs && i < props.exprs.length) {
287
+ const value = props.exprs[i];
288
+ if (value == null) continue; // Check if we're dealing with a vnode or an array of nodes
289
+
290
+ if (typeof value === 'object' && (value.constructor === undefined || isArray(value))) {
291
+ out += _renderToString(value, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
292
+ } else {
293
+ // Values are pre-escaped by the JSX transform
294
+ out += value;
295
+ }
296
+ }
297
+ }
298
+
299
+ return out;
300
+ } else if (props.UNSTABLE_comment) {
301
+ // Fragments are the least used components of core that's why
302
+ // branching here for comments has the least effect on perf.
303
+ return '<!--' + encodeEntities(props.UNSTABLE_comment || '') + '-->';
304
+ }
305
+
306
+ rendered = props.children;
307
+ } else {
308
+ contextType = type.contextType;
309
+
310
+ if (contextType != null) {
311
+ let provider = context[contextType.__c];
312
+ cctx = provider ? provider.props.value : contextType.__;
313
+ }
314
+
315
+ if (type.prototype && typeof type.prototype.render === 'function') {
316
+ rendered =
317
+ /**#__NOINLINE__**/
318
+ renderClassComponent(vnode, cctx);
319
+ component = vnode[COMPONENT];
320
+ } else {
321
+ component = {
322
+ __v: vnode,
323
+ props,
324
+ context: cctx,
325
+ // silently drop state updates
326
+ setState: markAsDirty,
327
+ forceUpdate: markAsDirty,
328
+ __d: true,
329
+ // hooks
330
+ __h: []
331
+ };
332
+ vnode[COMPONENT] = component; // If a hook invokes setState() to invalidate the component during rendering,
333
+ // re-render it up to 25 times to allow "settling" of memoized states.
334
+ // Note:
335
+ // This will need to be updated for Preact 11 to use internal.flags rather than component._dirty:
336
+ // https://github.com/preactjs/preact/blob/d4ca6fdb19bc715e49fd144e69f7296b2f4daa40/src/diff/component.js#L35-L44
337
+
338
+ let count = 0;
339
+
340
+ while (component[DIRTY] && count++ < 25) {
341
+ component[DIRTY] = false;
342
+ if (renderHook) renderHook(vnode);
343
+ rendered = type.call(component, props, cctx);
344
+ }
345
+
346
+ component[DIRTY] = true;
347
+ }
348
+
349
+ if (component.getChildContext != null) {
350
+ context = assign({}, context, component.getChildContext());
351
+ }
352
+
353
+ if ((type.getDerivedStateFromError || component.componentDidCatch) && preact.options.errorBoundaries) {
354
+ let str = ''; // When a component returns a Fragment node we flatten it in core, so we
355
+ // need to mirror that logic here too
356
+
357
+ let isTopLevelFragment = rendered != null && rendered.type === preact.Fragment && rendered.key == null;
358
+ rendered = isTopLevelFragment ? rendered.props.children : rendered;
359
+
360
+ try {
361
+ str = _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
362
+ return str;
363
+ } catch (err) {
364
+ if (type.getDerivedStateFromError) {
365
+ component[NEXT_STATE] = type.getDerivedStateFromError(err);
366
+ }
367
+
368
+ if (component.componentDidCatch) {
369
+ component.componentDidCatch(err, {});
370
+ }
371
+
372
+ if (component[DIRTY]) {
373
+ rendered = renderClassComponent(vnode, context);
374
+ component = vnode[COMPONENT];
375
+
376
+ if (component.getChildContext != null) {
377
+ context = assign({}, context, component.getChildContext());
378
+ }
379
+
380
+ let isTopLevelFragment = rendered != null && rendered.type === preact.Fragment && rendered.key == null;
381
+ rendered = isTopLevelFragment ? rendered.props.children : rendered;
382
+ str = _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
383
+ }
384
+
385
+ return str;
386
+ } finally {
387
+ if (afterDiff) afterDiff(vnode);
388
+ vnode[PARENT] = null;
389
+ if (ummountHook) ummountHook(vnode);
390
+ }
391
+ }
392
+ } // When a component returns a Fragment node we flatten it in core, so we
393
+ // need to mirror that logic here too
394
+
395
+
396
+ let isTopLevelFragment = rendered != null && rendered.type === preact.Fragment && rendered.key == null && rendered.props.tpl == null;
397
+ rendered = isTopLevelFragment ? rendered.props.children : rendered;
398
+
399
+ try {
400
+ // Recurse into children before invoking the after-diff hook
401
+ const str = _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
402
+
403
+ if (afterDiff) afterDiff(vnode); // when we are dealing with suspense we can't do this...
404
+
405
+ vnode[PARENT] = null;
406
+ if (preact.options.unmount) preact.options.unmount(vnode);
407
+ return str;
408
+ } catch (error) {
409
+ if (!asyncMode && renderer && renderer.onError) {
410
+ let res = renderer.onError(error, vnode, child => _renderToString(child, context, isSvgMode, selectValue, vnode, asyncMode, renderer));
411
+ if (res !== undefined) return res;
412
+ let errorHook = preact.options[CATCH_ERROR];
413
+ if (errorHook) errorHook(error, vnode);
414
+ return '';
415
+ }
416
+
417
+ if (!asyncMode) throw error;
418
+ if (!error || typeof error.then !== 'function') throw error;
419
+
420
+ const renderNestedChildren = () => {
421
+ try {
422
+ return _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer);
423
+ } catch (e) {
424
+ if (!e || typeof e.then !== 'function') throw e;
425
+ return e.then(() => _renderToString(rendered, context, isSvgMode, selectValue, vnode, asyncMode, renderer), () => renderNestedChildren());
426
+ }
427
+ };
428
+
429
+ return error.then(() => renderNestedChildren());
430
+ }
431
+ } // Serialize Element VNodes to HTML
432
+
433
+
434
+ let s = '<' + type,
435
+ html = '',
436
+ children;
437
+
438
+ for (let name in props) {
439
+ let v = props[name];
440
+
441
+ switch (name) {
442
+ case 'children':
443
+ children = v;
444
+ continue;
445
+ // VDOM-specific props
446
+
447
+ case 'key':
448
+ case 'ref':
449
+ case '__self':
450
+ case '__source':
451
+ continue;
452
+ // prefer for/class over htmlFor/className
453
+
454
+ case 'htmlFor':
455
+ if ('for' in props) continue;
456
+ name = 'for';
457
+ break;
458
+
459
+ case 'className':
460
+ if ('class' in props) continue;
461
+ name = 'class';
462
+ break;
463
+ // Form element reflected properties
464
+
465
+ case 'defaultChecked':
466
+ name = 'checked';
467
+ break;
468
+
469
+ case 'defaultSelected':
470
+ name = 'selected';
471
+ break;
472
+ // Special value attribute handling
473
+
474
+ case 'defaultValue':
475
+ case 'value':
476
+ name = 'value';
477
+
478
+ switch (type) {
479
+ // <textarea value="a&b"> --> <textarea>a&amp;b</textarea>
480
+ case 'textarea':
481
+ children = v;
482
+ continue;
483
+ // <select value> is serialized as a selected attribute on the matching option child
484
+
485
+ case 'select':
486
+ selectValue = v;
487
+ continue;
488
+ // Add a selected attribute to <option> if its value matches the parent <select> value
489
+
490
+ case 'option':
491
+ if (selectValue == v && !('selected' in props)) {
492
+ s = s + ' selected';
493
+ }
494
+
495
+ break;
496
+ }
497
+
498
+ break;
499
+
500
+ case 'dangerouslySetInnerHTML':
501
+ html = v && v.__html;
502
+ continue;
503
+ // serialize object styles to a CSS string
504
+
505
+ case 'style':
506
+ if (typeof v === 'object') {
507
+ v = styleObjToCss(v);
508
+ }
509
+
510
+ break;
511
+
512
+ case 'acceptCharset':
513
+ name = 'accept-charset';
514
+ break;
515
+
516
+ case 'httpEquiv':
517
+ name = 'http-equiv';
518
+ break;
519
+
520
+ default:
521
+ {
522
+ if (NAMESPACE_REPLACE_REGEX.test(name)) {
523
+ name = name.replace(NAMESPACE_REPLACE_REGEX, '$1:$2').toLowerCase();
524
+ } else if (UNSAFE_NAME.test(name)) {
525
+ continue;
526
+ } else if ((name[4] === '-' || name === 'draggable') && v != null) {
527
+ // serialize boolean aria-xyz or draggable attribute values as strings
528
+ // `draggable` is an enumerated attribute and not Boolean. A value of `true` or `false` is mandatory
529
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable
530
+ v += '';
531
+ } else if (isSvgMode) {
532
+ if (SVG_CAMEL_CASE.test(name)) {
533
+ name = name === 'panose1' ? 'panose-1' : name.replace(/([A-Z])/g, '-$1').toLowerCase();
534
+ }
535
+ } else if (HTML_LOWER_CASE.test(name)) {
536
+ name = name.toLowerCase();
537
+ }
538
+ }
539
+ } // write this attribute to the buffer
540
+
541
+
542
+ if (v != null && v !== false && typeof v !== 'function') {
543
+ if (v === true || v === '') {
544
+ s = s + ' ' + name;
545
+ } else {
546
+ s = s + ' ' + name + '="' + encodeEntities(v + '') + '"';
547
+ }
548
+ }
549
+ }
550
+
551
+ if (UNSAFE_NAME.test(type)) {
552
+ // this seems to performs a lot better than throwing
553
+ // return '<!-- -->';
554
+ throw new Error(`${type} is not a valid HTML tag name in ${s}>`);
555
+ }
556
+
557
+ if (html) ; else if (typeof children === 'string') {
558
+ // single text child
559
+ html = encodeEntities(children);
560
+ } else if (children != null && children !== false && children !== true) {
561
+ // recurse into this element VNode's children
562
+ let childSvgMode = type === 'svg' || type !== 'foreignObject' && isSvgMode;
563
+ html = _renderToString(children, context, childSvgMode, selectValue, vnode, asyncMode, renderer);
564
+ }
565
+
566
+ if (afterDiff) afterDiff(vnode); // TODO: this was commented before
567
+
568
+ vnode[PARENT] = null;
569
+ if (ummountHook) ummountHook(vnode); // Emit self-closing tag for empty void elements:
570
+
571
+ if (!html && SELF_CLOSING.has(type)) {
572
+ return s + '/>';
573
+ }
574
+
575
+ const endTag = '</' + type + '>';
576
+ const startTag = s + '>';
577
+ if (Array.isArray(html)) return [startTag, ...html, endTag];else if (typeof html !== 'string') return [startTag, html, endTag];
578
+ return startTag + html + endTag;
579
+ }
580
+
581
+ const SELF_CLOSING = new Set(['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
582
+
583
+ /* eslint-disable no-var, key-spacing, object-curly-spacing, prefer-arrow-callback, semi, keyword-spacing */
584
+ function initPreactIslandElement() {
585
+ class PreactIslandElement extends HTMLElement {
586
+ connectedCallback() {
587
+ var d = this;
588
+ if (!d.isConnected) return;
589
+ let i = this.getAttribute('data-target');
590
+ if (!i) return;
591
+ var s,
592
+ e,
593
+ c = document.createNodeIterator(document, 128);
594
+
595
+ while (c.nextNode()) {
596
+ let n = c.referenceNode;
597
+ if (n.data == 'preact-island:' + i) s = n;else if (n.data == '/preact-island:' + i) e = n;
598
+ if (s && e) break;
599
+ }
600
+
601
+ if (s && e) {
602
+ var p = e.previousSibling;
603
+
604
+ while (p != s) {
605
+ if (!p || p == s) break;
606
+ e.parentNode.removeChild(p);
607
+ p = e.previousSibling;
608
+ }
609
+
610
+ requestAnimationFrame(() => {
611
+ for (let i = 0; i <= d.children.length; i++) {
612
+ const child = d.children[i];
613
+ e.parentNode.insertBefore(child, e);
614
+ }
615
+
616
+ d.parentNode.removeChild(d);
617
+ });
618
+ }
619
+ }
620
+
621
+ }
622
+
623
+ customElements.define('preact-island', PreactIslandElement);
624
+ }
625
+
626
+ const fn = initPreactIslandElement.toString();
627
+ const INIT_SCRIPT = fn.slice(fn.indexOf('{') + 1, fn.lastIndexOf('}')).replace(/\n\s+/gm, '');
628
+ function createInitScript() {
629
+ return `<script>(function(){${INIT_SCRIPT}}())</script>`;
630
+ }
631
+ /**
632
+ * @param {string} id
633
+ * @param {string} content
634
+ * @returns {string}
635
+ */
636
+
637
+ function createSubtree(id, content) {
638
+ return `<preact-island hidden data-target="${id}">${content}</preact-island>`;
639
+ }
640
+
641
+ /**
642
+ * @param {VNode} vnode
643
+ * @param {RenderToChunksOptions} options
644
+ * @returns {Promise<void>}
645
+ */
646
+
647
+ async function renderToChunks(vnode, {
648
+ context,
649
+ onWrite,
650
+ abortSignal
651
+ }) {
652
+ context = context || {};
653
+ /** @type {RendererState} */
654
+
655
+ const renderer = {
656
+ start: Date.now(),
657
+ abortSignal,
658
+ onWrite,
659
+ onError: handleError,
660
+ suspended: []
661
+ }; // Synchronously render the shell
662
+ // @ts-ignore - using third internal RendererState argument
663
+
664
+ const shell = renderToString(vnode, context, renderer);
665
+ onWrite(shell); // Wait for any suspended sub-trees if there are any
666
+
667
+ const len = renderer.suspended.length;
668
+
669
+ if (len > 0) {
670
+ onWrite('<div hidden>');
671
+ onWrite(createInitScript()); // We should keep checking all promises
672
+
673
+ await forkPromises(renderer);
674
+ onWrite('</div>');
675
+ }
676
+ }
677
+
678
+ async function forkPromises(renderer) {
679
+ if (renderer.suspended.length > 0) {
680
+ const suspensions = [...renderer.suspended];
681
+ await Promise.all(renderer.suspended.map(s => s.promise));
682
+ renderer.suspended = renderer.suspended.filter(s => !suspensions.includes(s));
683
+ await forkPromises(renderer);
684
+ }
685
+ }
686
+ /** @type {RendererErrorHandler} */
687
+
688
+
689
+ function handleError(error, vnode, renderChild) {
690
+ if (!error || !error.then) return; // walk up to the Suspense boundary
691
+
692
+ while (vnode = vnode[PARENT]) {
693
+ let component = vnode[COMPONENT];
694
+
695
+ if (component && component[CHILD_DID_SUSPEND]) {
696
+ break;
697
+ }
698
+ }
699
+
700
+ if (!vnode) return;
701
+ const id = vnode.__v;
702
+ const found = this.suspended.find(x => x.id === id);
703
+ const race = new Deferred();
704
+ const abortSignal = this.abortSignal;
705
+
706
+ if (abortSignal) {
707
+ // @ts-ignore 2554 - implicit undefined arg
708
+ if (abortSignal.aborted) race.resolve();else abortSignal.addEventListener('abort', race.resolve);
709
+ }
710
+
711
+ const promise = error.then(() => {
712
+ if (abortSignal && abortSignal.aborted) return;
713
+ const child = renderChild(vnode.props.children);
714
+ if (child) this.onWrite(createSubtree(id, child));
715
+ }, // TODO: Abort and send hydration code snippet to client
716
+ // to attempt to recover during hydration
717
+ this.onError);
718
+ this.suspended.push({
719
+ id,
720
+ vnode,
721
+ promise: Promise.race([promise, race.promise])
722
+ });
723
+ const fallback = renderChild(vnode.props.fallback);
724
+ return found ? '' : `<!--preact-island:${id}-->${fallback}<!--/preact-island:${id}-->`;
725
+ }
726
+
727
+ /**
728
+ * @typedef {object} RenderToPipeableStreamOptions
729
+ * @property {() => void} [onShellReady]
730
+ * @property {() => void} [onAllReady]
731
+ * @property {(error) => void} [onError]
732
+ */
733
+
734
+ /**
735
+ * @param {import('preact').VNode} vnode
736
+ * @param {RenderToPipeableStreamOptions} options
737
+ * @param {any} [context]
738
+ * @returns {{}}
739
+ */
740
+
741
+ function renderToPipeableStream(vnode, options, context) {
742
+ const encoder = new TextEncoder('utf-8');
743
+ const controller = new AbortController();
744
+ const stream = new node_stream.PassThrough();
745
+ renderToChunks(vnode, {
746
+ context,
747
+ abortSignal: controller.signal,
748
+ onError: error => {
749
+ if (options.onError) {
750
+ options.onError(error);
751
+ }
752
+
753
+ controller.abort(error);
754
+ },
755
+
756
+ onWrite(s) {
757
+ stream.write(encoder.encode(s));
758
+ }
759
+
760
+ }).then(() => {
761
+ options.onAllReady && options.onAllReady();
762
+ stream.end();
763
+ }).catch(error => {
764
+ stream.destroy(error);
765
+ });
766
+ Promise.resolve().then(() => {
767
+ options.onShellReady && options.onShellReady();
768
+ });
769
+ return {
770
+ abort() {
771
+ controller.abort();
772
+ stream.destroy(new Error('aborted'));
773
+ },
774
+
775
+ /**
776
+ * @param {import("stream").Writable} writable
777
+ */
778
+ pipe(writable) {
779
+ stream.pipe(writable, {
780
+ end: true
781
+ });
782
+ }
783
+
784
+ };
785
+ }
786
+
787
+ exports.renderToPipeableStream = renderToPipeableStream;
788
+
789
+ })));
790
+ //# sourceMappingURL=stream-node.umd.js.map