@shadow-js/web 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/dist/dev/attributes.d.ts +10 -5
- package/dist/dev/attributes.js +28 -51
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/autofocus.d.ts +0 -2
- package/dist/dev/autofocus.js +1 -2
- package/dist/dev/class-style.d.ts +6 -4
- package/dist/dev/class-style.js +25 -9
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/component.d.ts +0 -2
- package/dist/dev/component.js +1 -2
- package/dist/dev/control-flow/activity.d.ts +0 -2
- package/dist/dev/control-flow/activity.js +1 -2
- package/dist/dev/control-flow/branch.js +0 -1
- package/dist/dev/control-flow/client-only.d.ts +0 -2
- package/dist/dev/control-flow/client-only.js +1 -2
- package/dist/dev/control-flow/dynamic.d.ts +11 -4
- package/dist/dev/control-flow/dynamic.js +57 -41
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.d.ts +0 -2
- package/dist/dev/control-flow/error-boundary.js +1 -2
- package/dist/dev/control-flow/for.d.ts +0 -2
- package/dist/dev/control-flow/for.js +1 -2
- package/dist/dev/control-flow/fragment.d.ts +0 -2
- package/dist/dev/control-flow/fragment.js +1 -2
- package/dist/dev/control-flow/hot-link.js +1 -2
- package/dist/dev/control-flow/index-list.d.ts +0 -2
- package/dist/dev/control-flow/index-list.js +1 -2
- package/dist/dev/control-flow/lazy.d.ts +0 -2
- package/dist/dev/control-flow/lazy.js +1 -2
- package/dist/dev/control-flow/no-hydration.d.ts +0 -2
- package/dist/dev/control-flow/no-hydration.js +1 -2
- package/dist/dev/control-flow/portal.d.ts +0 -2
- package/dist/dev/control-flow/portal.js +3 -2
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/root-errors.d.ts +0 -2
- package/dist/dev/control-flow/root-errors.js +1 -2
- package/dist/dev/control-flow/show.d.ts +0 -2
- package/dist/dev/control-flow/show.js +1 -2
- package/dist/dev/control-flow/suspense-list.d.ts +0 -2
- package/dist/dev/control-flow/suspense-list.js +1 -2
- package/dist/dev/control-flow/suspense.d.ts +0 -2
- package/dist/dev/control-flow/suspense.js +1 -2
- package/dist/dev/control-flow/switch.d.ts +0 -2
- package/dist/dev/control-flow/switch.js +1 -2
- package/dist/dev/derived.d.ts +0 -2
- package/dist/dev/derived.js +1 -2
- package/dist/dev/element.d.ts +0 -2
- package/dist/dev/element.js +2 -3
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.d.ts +0 -2
- package/dist/dev/events.js +16 -46
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/head/components.d.ts +0 -2
- package/dist/dev/head/components.js +1 -2
- package/dist/dev/head/registry.js +1 -2
- package/dist/dev/head/server-head.d.ts +0 -2
- package/dist/dev/head/server-head.js +1 -2
- package/dist/dev/head/sink.js +1 -2
- package/dist/dev/head/use-head.d.ts +0 -2
- package/dist/dev/head/use-head.js +1 -2
- package/dist/dev/head/validate.d.ts +0 -2
- package/dist/dev/head/validate.js +1 -2
- package/dist/dev/hmr.d.ts +0 -2
- package/dist/dev/hmr.js +1 -2
- package/dist/dev/hydration.d.ts +0 -2
- package/dist/dev/hydration.js +1 -2
- package/dist/dev/insert.d.ts +15 -7
- package/dist/dev/insert.js +36 -15
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +2 -3
- package/dist/dev/internal/claim.js +19 -4
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +1 -2
- package/dist/dev/internal/diagnostics.d.ts +7 -5
- package/dist/dev/internal/diagnostics.js +15 -6
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/early-events.js +21 -4
- package/dist/dev/internal/early-events.js.map +1 -1
- package/dist/dev/internal/hydration-hooks.d.ts +0 -2
- package/dist/dev/internal/hydration-hooks.js +0 -1
- package/dist/dev/internal/hydration-scope.d.ts +0 -2
- package/dist/dev/internal/hydration-scope.js +1 -2
- package/dist/dev/internal/names.d.ts +0 -2
- package/dist/dev/internal/names.js +1 -2
- package/dist/dev/internal/portal-context.d.ts +0 -2
- package/dist/dev/internal/portal-context.js +1 -2
- package/dist/dev/internal/react-names.js +26 -63
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.d.ts +0 -2
- package/dist/dev/internal/reconcile.js +4 -8
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/internal/stream-context.d.ts +0 -2
- package/dist/dev/internal/stream-context.js +1 -2
- package/dist/dev/jsx/aria.d.ts +0 -2
- package/dist/dev/jsx/component.d.ts +0 -2
- package/dist/dev/jsx/events.d.ts +0 -2
- package/dist/dev/jsx/global.d.ts +5 -4
- package/dist/dev/jsx/html.d.ts +1 -2
- package/dist/dev/jsx/intrinsic.d.ts +0 -2
- package/dist/dev/jsx/mathml.d.ts +0 -2
- package/dist/dev/jsx/svg.d.ts +0 -2
- package/dist/dev/jsx/types.d.ts +0 -2
- package/dist/dev/jsx-runtime.d.ts +0 -2
- package/dist/dev/reactive.d.ts +0 -2
- package/dist/dev/reactive.js +1 -2
- package/dist/dev/render.d.ts +0 -2
- package/dist/dev/render.js +1 -2
- package/dist/dev/resource-hints.d.ts +0 -2
- package/dist/dev/resource-hints.js +5 -4
- package/dist/dev/resource-hints.js.map +1 -1
- package/dist/dev/select-value.d.ts +0 -2
- package/dist/dev/select-value.js +6 -17
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/attributes.d.ts +3 -2
- package/dist/dev/server/attributes.js +6 -3
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/class-style.d.ts +0 -2
- package/dist/dev/server/class-style.js +1 -2
- package/dist/dev/server/component.d.ts +0 -2
- package/dist/dev/server/component.js +1 -2
- package/dist/dev/server/derived.d.ts +0 -2
- package/dist/dev/server/derived.js +1 -2
- package/dist/dev/server/element.d.ts +0 -2
- package/dist/dev/server/element.js +9 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/errors.js +8 -3
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.d.ts +0 -2
- package/dist/dev/server/escape.js +15 -8
- package/dist/dev/server/escape.js.map +1 -1
- package/dist/dev/server/form-controls.d.ts +0 -2
- package/dist/dev/server/form-controls.js +6 -4
- package/dist/dev/server/form-controls.js.map +1 -1
- package/dist/dev/server/hydration-script.d.ts +0 -2
- package/dist/dev/server/hydration-script.js +1 -2
- package/dist/dev/server/index.d.ts +2 -1
- package/dist/dev/server/index.js +2 -1
- package/dist/dev/server/node.d.ts +0 -2
- package/dist/dev/server/node.js +1 -2
- package/dist/dev/server/portals.d.ts +0 -2
- package/dist/dev/server/portals.js +0 -1
- package/dist/dev/server/raw-text.d.ts +28 -0
- package/dist/dev/server/raw-text.js +66 -0
- package/dist/dev/server/raw-text.js.map +1 -0
- package/dist/dev/server/render.d.ts +2 -3
- package/dist/dev/server/render.js +3 -4
- package/dist/dev/server/render.js.map +1 -1
- package/dist/dev/server/serialize.d.ts +0 -2
- package/dist/dev/server/serialize.js +1 -2
- package/dist/dev/server/stream.d.ts +1 -3
- package/dist/dev/server/stream.js +3 -4
- package/dist/dev/server/stream.js.map +1 -1
- package/dist/dev/server.d.ts +2 -1
- package/dist/dev/server.js +2 -1
- package/dist/dev/spread.d.ts +0 -2
- package/dist/dev/spread.js +8 -56
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.d.ts +0 -2
- package/dist/dev/template.js +1 -2
- package/dist/dev/view-transition.d.ts +0 -2
- package/dist/dev/view-transition.js +1 -2
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/early-events.js +1 -1
- package/dist/prod/internal/early-events.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/resource-hints.js +1 -1
- package/dist/prod/resource-hints.js.map +1 -1
- package/dist/prod/select-value.js +1 -1
- package/dist/prod/select-value.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/errors.js +1 -1
- package/dist/prod/server/errors.js.map +1 -1
- package/dist/prod/server/escape.js +1 -1
- package/dist/prod/server/escape.js.map +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/form-controls.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/raw-text.js +2 -0
- package/dist/prod/server/raw-text.js.map +1 -0
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/render.js.map +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server/stream.js.map +1 -1
- package/dist/prod/server.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/element.js +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/early-events.js +1 -1
- package/dist/server/internal/early-events.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/resource-hints.js +1 -1
- package/dist/server/resource-hints.js.map +1 -1
- package/dist/server/select-value.js +1 -1
- package/dist/server/select-value.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/errors.js +1 -1
- package/dist/server/server/errors.js.map +1 -1
- package/dist/server/server/escape.js +1 -1
- package/dist/server/server/escape.js.map +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/form-controls.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/raw-text.js +2 -0
- package/dist/server/server/raw-text.js.map +1 -0
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/render.js.map +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server/stream.js.map +1 -1
- package/dist/server/server.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server-dev/attributes.js +28 -51
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/autofocus.js +1 -2
- package/dist/server-dev/class-style.js +25 -9
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/component.js +1 -2
- package/dist/server-dev/control-flow/activity.js +1 -2
- package/dist/server-dev/control-flow/branch.js +0 -1
- package/dist/server-dev/control-flow/client-only.js +1 -2
- package/dist/server-dev/control-flow/dynamic.js +23 -12
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +1 -2
- package/dist/server-dev/control-flow/for.js +1 -2
- package/dist/server-dev/control-flow/fragment.js +1 -2
- package/dist/server-dev/control-flow/hot-link.js +1 -2
- package/dist/server-dev/control-flow/index-list.js +1 -2
- package/dist/server-dev/control-flow/lazy.js +1 -2
- package/dist/server-dev/control-flow/no-hydration.js +1 -2
- package/dist/server-dev/control-flow/portal.js +3 -2
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/root-errors.js +1 -2
- package/dist/server-dev/control-flow/show.js +1 -2
- package/dist/server-dev/control-flow/suspense-list.js +1 -2
- package/dist/server-dev/control-flow/suspense.js +1 -2
- package/dist/server-dev/control-flow/switch.js +1 -2
- package/dist/server-dev/derived.js +1 -2
- package/dist/server-dev/element.js +4 -3
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +16 -46
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/head/components.js +1 -2
- package/dist/server-dev/head/registry.js +1 -2
- package/dist/server-dev/head/server-head.js +1 -2
- package/dist/server-dev/head/sink.js +1 -2
- package/dist/server-dev/head/use-head.js +1 -2
- package/dist/server-dev/head/validate.js +1 -2
- package/dist/server-dev/hydration.js +1 -2
- package/dist/server-dev/insert.js +36 -15
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/claim.js +19 -4
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +1 -2
- package/dist/server-dev/internal/diagnostics.js +15 -6
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/early-events.js +21 -4
- package/dist/server-dev/internal/early-events.js.map +1 -1
- package/dist/server-dev/internal/hydration-hooks.js +0 -1
- package/dist/server-dev/internal/hydration-scope.js +1 -2
- package/dist/server-dev/internal/names.js +1 -2
- package/dist/server-dev/internal/portal-context.js +1 -2
- package/dist/server-dev/internal/react-names.js +26 -63
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +4 -8
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/internal/stream-context.js +1 -2
- package/dist/server-dev/reactive.js +1 -2
- package/dist/server-dev/render.js +1 -2
- package/dist/server-dev/resource-hints.js +5 -4
- package/dist/server-dev/resource-hints.js.map +1 -1
- package/dist/server-dev/select-value.js +6 -17
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/attributes.js +6 -3
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/class-style.js +1 -2
- package/dist/server-dev/server/component.js +1 -2
- package/dist/server-dev/server/derived.js +1 -2
- package/dist/server-dev/server/element.js +9 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/errors.js +8 -3
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/escape.js +15 -8
- package/dist/server-dev/server/escape.js.map +1 -1
- package/dist/server-dev/server/form-controls.js +6 -4
- package/dist/server-dev/server/form-controls.js.map +1 -1
- package/dist/server-dev/server/hydration-script.js +1 -2
- package/dist/server-dev/server/index.js +2 -1
- package/dist/server-dev/server/node.js +1 -2
- package/dist/server-dev/server/portals.js +0 -1
- package/dist/server-dev/server/raw-text.js +86 -0
- package/dist/server-dev/server/raw-text.js.map +1 -0
- package/dist/server-dev/server/render.js +3 -4
- package/dist/server-dev/server/render.js.map +1 -1
- package/dist/server-dev/server/serialize.js +1 -2
- package/dist/server-dev/server/stream.js +3 -4
- package/dist/server-dev/server/stream.js.map +1 -1
- package/dist/server-dev/server.js +2 -1
- package/dist/server-dev/spread.js +8 -56
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -2
- package/dist/server-dev/view-transition.js +1 -2
- package/package.json +3 -2
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ServerHead } from "../head/server-head.js";
|
|
2
2
|
import { ServerPortals } from "./portals.js";
|
|
3
|
-
//#region src/server/stream.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Options of {@link renderToStream}.
|
|
6
5
|
* @since 1.0.0
|
|
@@ -18,7 +17,7 @@ export interface StreamOptions {
|
|
|
18
17
|
*/
|
|
19
18
|
readonly nonce?: string;
|
|
20
19
|
/**
|
|
21
|
-
* Upper bound for the whole stream, in milliseconds, a positive finite number. When it runs out, the stream errors with an
|
|
20
|
+
* Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an
|
|
22
21
|
* `SsrError` whose `code` is `SSR_TIMEOUT`.
|
|
23
22
|
* @default 30000
|
|
24
23
|
*/
|
|
@@ -90,5 +89,4 @@ export interface StreamOptions {
|
|
|
90
89
|
* @since 1.0.0
|
|
91
90
|
*/
|
|
92
91
|
export declare function renderToStream(code: () => unknown, options?: StreamOptions): ReadableStream<Uint8Array>;
|
|
93
|
-
//#endregion
|
|
94
92
|
//# sourceMappingURL=stream.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRootScope, resourceKey, withScope } from "../internal/hydration-scope.js";
|
|
2
|
-
import { SsrError } from "./errors.js";
|
|
2
|
+
import { MAX_TIMER_MS, SsrError } from "./errors.js";
|
|
3
3
|
import { escape } from "./escape.js";
|
|
4
4
|
import { StreamContext } from "../internal/stream-context.js";
|
|
5
5
|
import { attachRootErrors } from "../control-flow/root-errors.js";
|
|
@@ -7,7 +7,7 @@ import { portalCollectorFor, withPortalSink } from "./portals.js";
|
|
|
7
7
|
import { runWithServerHead } from "../head/server-head.js";
|
|
8
8
|
import { serialize } from "./serialize.js";
|
|
9
9
|
import { ResourceCacheContext, createRoot, untrack } from "@shadow-js/core";
|
|
10
|
-
|
|
10
|
+
// src/server/stream.ts
|
|
11
11
|
const RENDER_ID = /^[A-Za-z0-9_-]+$/;
|
|
12
12
|
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
13
13
|
/**
|
|
@@ -152,7 +152,7 @@ function renderToStream(code, options = {}) {
|
|
|
152
152
|
let rejectAbort = () => void 0;
|
|
153
153
|
const abort = new Promise((_resolve, reject) => {
|
|
154
154
|
rejectAbort = reject;
|
|
155
|
-
timer = setTimeout(() => reject(new SsrError("SSR_TIMEOUT", `The stream did not finish within ${timeoutMs} ms.`)), timeoutMs);
|
|
155
|
+
timer = setTimeout(() => reject(new SsrError("SSR_TIMEOUT", `The stream did not finish within ${timeoutMs} ms.`)), Math.min(timeoutMs, MAX_TIMER_MS));
|
|
156
156
|
});
|
|
157
157
|
const onAbort = () => rejectAbort(signal?.reason ?? /* @__PURE__ */ new Error("The render was aborted."));
|
|
158
158
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -229,7 +229,6 @@ function renderToStream(code, options = {}) {
|
|
|
229
229
|
}
|
|
230
230
|
});
|
|
231
231
|
}
|
|
232
|
-
//#endregion
|
|
233
232
|
export { renderToStream };
|
|
234
233
|
|
|
235
234
|
//# sourceMappingURL=stream.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number. When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n timeoutMs,\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,qBAAqB;;;;;AAK3B,MAAM,mBAAmB;;;;;;AA0BzB,MAAM,eACJ;AAOF,SAAS,OAAO,MAAc,OAAm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IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,GAC7B,KAAK,4CAA4C,SAAS,IAAI,UAAU,IAAI,EAAE,WAAU;IAE1F,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM;GAClC,SAAS,OAAO;IACd,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM,KAAK;GACvC;EACF;EACA,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,MAAM;EACrB;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,qBAAqB;;;;;AAK3B,MAAM,mBAAmB;;;;;;AA0BzB,MAAM,eACJ;AAOF,SAAS,OAAO,MAAc,OAAmC;CAG/D,OAAO,UADL,UAAU,KAAA,IAAY,KAAK,WAAW,MAAM,QAAQ,sBAAsB,EAAE,EAAE,GACrD,GAAG,KAAK;AACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eACd,MACA,UAAyB,CAAC,GACE;CAC5B,MAAM,WAAW,QAAQ,YAAY;CACrC,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,cAAc,YAAY,EAAE,YAAY,MAAM,CAAC,OAAO,SAAS,SAAS,GACjF,MAAM,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ssrTextArea } from "./server/form-controls.js";
|
|
10
10
|
import { HydrationScript, HydrationScriptOptions, generateHydrationScript } from "./server/hydration-script.js";
|
|
11
11
|
import { ServerPortals, createServerPortals } from "./server/portals.js";
|
|
12
|
+
import { ssrRawText } from "./server/raw-text.js";
|
|
12
13
|
import { AsyncRenderOptions, AsyncRenderResult, RenderOptions, renderToString, renderToStringAsync } from "./server/render.js";
|
|
13
14
|
import { deserialize, serialize } from "./server/serialize.js";
|
|
14
15
|
import { StreamOptions, renderToStream } from "./server/stream.js";
|
|
15
16
|
import { mergeProps } from "./server/index.js";
|
|
16
|
-
export { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
|
|
17
|
+
export { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
|
package/dist/dev/server.js
CHANGED
|
@@ -2,6 +2,7 @@ import { escape } from "./server/escape.js";
|
|
|
2
2
|
import { ssrAttribute } from "./server/attributes.js";
|
|
3
3
|
import { ssrClass, ssrStyle } from "./server/class-style.js";
|
|
4
4
|
import { ssrSelectValue, ssrTextArea } from "./server/form-controls.js";
|
|
5
|
+
import { ssrRawText } from "./server/raw-text.js";
|
|
5
6
|
import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./server/element.js";
|
|
6
7
|
import { createServerPortals } from "./server/portals.js";
|
|
7
8
|
import { normalizeTags } from "./head/validate.js";
|
|
@@ -13,4 +14,4 @@ import { renderToString, renderToStringAsync } from "./server/render.js";
|
|
|
13
14
|
import { deserialize, serialize } from "./server/serialize.js";
|
|
14
15
|
import { renderToStream } from "./server/stream.js";
|
|
15
16
|
import { mergeProps } from "./server/index.js";
|
|
16
|
-
export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
|
|
17
|
+
export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
|
package/dist/dev/spread.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/spread.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for
|
|
4
3
|
* `{...props}` on an element. The props are read inside a render effect, so a getter (or the props
|
|
@@ -45,5 +44,4 @@
|
|
|
45
44
|
* @since 1.0.0
|
|
46
45
|
*/
|
|
47
46
|
export declare function spread(el: Element, props: unknown, isSVG?: boolean, skipChildren?: boolean): void;
|
|
48
|
-
//#endregion
|
|
49
47
|
//# sourceMappingURL=spread.d.ts.map
|
package/dist/dev/spread.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { setAttribute, setAttributeNS, setBoolAttribute } from "./attributes.js";
|
|
2
2
|
import { autoFocus } from "./autofocus.js";
|
|
3
|
-
import { applyClass, classList, style } from "./class-style.js";
|
|
3
|
+
import { applyClass, asRecord, classList, style } from "./class-style.js";
|
|
4
4
|
import { claims } from "./internal/hydration-hooks.js";
|
|
5
5
|
import { bindRegion, createRegion } from "./insert.js";
|
|
6
6
|
import { IGNORED_KEYS, attributeName, eventPlan } from "./internal/react-names.js";
|
|
7
7
|
import { bindEvent } from "./events.js";
|
|
8
|
-
import {
|
|
8
|
+
import { plainText, setSelectValue } from "./select-value.js";
|
|
9
9
|
import { onCleanup, untrack, useRenderEffect } from "@shadow-js/core";
|
|
10
|
-
|
|
10
|
+
// src/spread.ts
|
|
11
11
|
/** The namespace of `xlink:` attributes (SVG's legacy links). */
|
|
12
12
|
const XLINK_NS = "http://www.w3.org/1999/xlink";
|
|
13
13
|
/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */
|
|
@@ -30,15 +30,6 @@ function nameOf(key) {
|
|
|
30
30
|
const colon = key.indexOf(":");
|
|
31
31
|
return colon === -1 ? key : key.slice(colon + 1);
|
|
32
32
|
}
|
|
33
|
-
/** Narrows an object value to a record of keys; arrays and primitives are not class maps. */
|
|
34
|
-
function asRecord(value) {
|
|
35
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
36
|
-
return value;
|
|
37
|
-
}
|
|
38
|
-
/** Text for innerHTML and textContent: null and undefined become the empty string. */
|
|
39
|
-
function plainText(value) {
|
|
40
|
-
return value === null || value === void 0 ? "" : String(value);
|
|
41
|
-
}
|
|
42
33
|
/** Reads every prop except children, inside the render effect so each read is tracked. */
|
|
43
34
|
function readEntries(props, textarea) {
|
|
44
35
|
const entries = [];
|
|
@@ -108,12 +99,8 @@ function applyKey(el, key, value, state, svg) {
|
|
|
108
99
|
if (unbind !== void 0) state.unbinders.set(key, unbind);
|
|
109
100
|
return;
|
|
110
101
|
}
|
|
111
|
-
if (key === "innerHTML") {
|
|
112
|
-
el.innerHTML = plainText(value);
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
if (key === "dangerouslySetInnerHTML") {
|
|
116
|
-
el.innerHTML = innerHtmlValue(value);
|
|
102
|
+
if (key === "innerHTML" || key === "dangerouslySetInnerHTML") {
|
|
103
|
+
el.innerHTML = key === "innerHTML" ? plainText(value) : innerHtmlValue(value);
|
|
117
104
|
return;
|
|
118
105
|
}
|
|
119
106
|
if (key === "textContent") {
|
|
@@ -134,7 +121,7 @@ function applyKey(el, key, value, state, svg) {
|
|
|
134
121
|
/**
|
|
135
122
|
* Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute
|
|
136
123
|
* under its React name. An `undefined` value removes the attribute or resets the property, which is how
|
|
137
|
-
*
|
|
124
|
+
* a prop that disappeared is undone.
|
|
138
125
|
*/
|
|
139
126
|
function writeKey(el, key, value, svg) {
|
|
140
127
|
if (key.startsWith("prop:")) Reflect.set(el, key.slice(5), value);
|
|
@@ -164,44 +151,10 @@ const STRING_PROPERTIES = /* @__PURE__ */ new Set(["value", "defaultValue"]);
|
|
|
164
151
|
*/
|
|
165
152
|
function liveDiffers(el, key, value, svg) {
|
|
166
153
|
if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;
|
|
167
|
-
if (key === "value" && el instanceof HTMLSelectElement) return
|
|
154
|
+
if (key === "value" && el instanceof HTMLSelectElement) return true;
|
|
168
155
|
const live = Reflect.get(el, key);
|
|
169
156
|
return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);
|
|
170
157
|
}
|
|
171
|
-
/** Undoes a prop that disappeared from the props object. */
|
|
172
|
-
function clearKey(el, key, state, svg) {
|
|
173
|
-
if (key === "ref") {
|
|
174
|
-
runRefCleanup(state);
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
if (key === "autoFocus") return;
|
|
178
|
-
if (key === "class" || key === "className") {
|
|
179
|
-
applyClass(el, void 0, svg);
|
|
180
|
-
return;
|
|
181
|
-
}
|
|
182
|
-
if (key === "style") {
|
|
183
|
-
state.styleValue = style(el, void 0, state.styleValue);
|
|
184
|
-
return;
|
|
185
|
-
}
|
|
186
|
-
if (key === "classList") {
|
|
187
|
-
state.classListValue = classList(el, void 0, state.classListValue);
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
if (isEventKey(key)) {
|
|
191
|
-
state.unbinders.get(key)?.();
|
|
192
|
-
state.unbinders.delete(key);
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
if (key === "innerHTML" || key === "dangerouslySetInnerHTML" || key === "textContent") {
|
|
196
|
-
el.textContent = "";
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
|
-
if (!svg && LIVE_PROPERTIES.has(key) && key in el) {
|
|
200
|
-
Reflect.set(el, key, STRING_PROPERTIES.has(key) ? "" : false);
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
203
|
-
writeKey(el, key, void 0, svg);
|
|
204
|
-
}
|
|
205
158
|
/**
|
|
206
159
|
* Applies the entries that changed since the last run and undoes the ones that disappeared.
|
|
207
160
|
* Unchanged values are skipped by identity, so only changed keys touch the DOM.
|
|
@@ -217,7 +170,7 @@ function applyEntries(el, entries, state, svg) {
|
|
|
217
170
|
for (const key of [...state.values.keys()]) {
|
|
218
171
|
if (current.has(key)) continue;
|
|
219
172
|
state.values.delete(key);
|
|
220
|
-
|
|
173
|
+
applyKey(el, key, void 0, state, svg);
|
|
221
174
|
}
|
|
222
175
|
}
|
|
223
176
|
/**
|
|
@@ -290,7 +243,6 @@ function spread(el, props, isSVG = false, skipChildren = false) {
|
|
|
290
243
|
applyEntries(el, entries, state, isSVG);
|
|
291
244
|
});
|
|
292
245
|
}
|
|
293
|
-
//#endregion
|
|
294
246
|
export { spread };
|
|
295
247
|
|
|
296
248
|
//# sourceMappingURL=spread.js.map
|
package/dist/dev/spread.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } from \"./internal/react-names\";\nimport { selectShows, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. */\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Text for innerHTML and textContent: null and undefined become the empty string. */\nfunction plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\") {\n el.innerHTML = plainText(value);\n return;\n }\n if (key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * {@link clearKey} undoes a prop.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"value\", \"defaultValue\"]);\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;\n if (key === \"value\" && el instanceof HTMLSelectElement) return !selectShows(el, value);\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/** Undoes a prop that disappeared from the props object. */\nfunction clearKey(el: Element, key: string, state: SpreadState, svg: boolean): void {\n if (key === \"ref\") {\n runRefCleanup(state);\n return;\n }\n // A focus request is not a state: removing the prop does not unfocus the element.\n if (key === \"autoFocus\") return;\n if (key === \"class\" || key === \"className\") {\n applyClass(el, undefined, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, undefined, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, undefined, state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\" || key === \"textContent\") {\n el.textContent = \"\";\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? \"\" : false);\n return;\n }\n writeKey(el, key, undefined, svg);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n clearKey(el, key, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const textarea = el.localName === \"textarea\";\n if (!skipChildren && !textarea) {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,SAAS,eAAe,OAAwB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,OAAO,UAAU,QAAQ,IAAI,OAAO,QAAQ,CAAC;AAC/C;;AAGA,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAezE,SAAS,WAAW,KAAsB;CACxC,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI;AAC9C;;AAGA,SAAS,OAAO,KAAqB;CACnC,MAAM,QAAQ,IAAI,QAAQ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AAO,IAAa,OAAgB,QAAQ,OAAO,eAAe,OAAa;CAC7F,IAAI,UAAU,QAAS,OAAO,UAAU,YAAY,OAAO,UAAU,YAAa;CAGlF,MAAM,aAAuB,OAAO,UAAU,aAAc,MAAwB,IAAI;CACxF,MAAM,WAAW,GAAG,cAAc;CAClC,IAAI,CAAC,gBAAgB,CAAC,UAAU;EAE9B,MAAM,UAAU,OAAO,QAAQ,WAAW,IACrC,OAAO,QAAQ,WAAW,IAAI,IAAI,KAAK,MAAM,KAAK,GAAG,UAAU,IAChE,KAAA;EACJ,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO;EAC7C,WAAW,cAAe,KAAK,CAAC,EAA6C,QAAQ;CACvF;CACA,MAAM,QAAqB;EACzB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;EACnB,YAAY,KAAA;EACZ,gBAAgB,KAAA;EAChB,YAAY,KAAA;CACd;CAEA,gBAAgB;EACd,KAAK,MAAM,UAAU,MAAM,UAAU,OAAO,GAAG,OAAO;EACtD,MAAM,UAAU,MAAM;EACtB,cAAc,KAAK;CACrB,CAAC;CACD,sBACQ,YAAY,KAAK,GAAG,QAAQ,IACjC,YAAY;EACX,aAAa,IAAI,SAAS,OAAO,KAAK;CACxC,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"value\", \"defaultValue\"]);\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const textarea = el.localName === \"textarea\";\n if (!skipChildren && !textarea) {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,SAAS,eAAe,OAAwB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,OAAO,UAAU,QAAQ,IAAI,OAAO,QAAQ,CAAC;AAC/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@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/template.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the
|
|
4
3
|
* static part of every element tree. The markup is parsed on the first call and cloned on every call
|
|
@@ -22,5 +21,4 @@
|
|
|
22
21
|
* @since 1.0.0
|
|
23
22
|
*/
|
|
24
23
|
export declare function template(html: string, flags?: number): () => Node;
|
|
25
|
-
//#endregion
|
|
26
24
|
//# sourceMappingURL=template.d.ts.map
|
package/dist/dev/template.js
CHANGED
|
@@ -3,7 +3,7 @@ import { MATHML_NS } from "./internal/names.js";
|
|
|
3
3
|
import { nextKey } from "./internal/hydration-scope.js";
|
|
4
4
|
import { checkClaimedTag } from "./internal/claim.js";
|
|
5
5
|
import { claims } from "./internal/hydration-hooks.js";
|
|
6
|
-
|
|
6
|
+
// src/template.ts
|
|
7
7
|
/** One start tag: its name, then its attribute text (group 1). */
|
|
8
8
|
const START_TAG = /<[a-zA-Z][^\s/>]*((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
|
|
9
9
|
/** One attribute inside the attribute text of a start tag: its name (group 1). */
|
|
@@ -114,7 +114,6 @@ function template(html, flags = 0) {
|
|
|
114
114
|
return fragment;
|
|
115
115
|
};
|
|
116
116
|
}
|
|
117
|
-
//#endregion
|
|
118
117
|
export { template };
|
|
119
118
|
|
|
120
119
|
//# sourceMappingURL=template.js.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Accessor } from "@shadow-js/core";
|
|
2
|
-
//#region src/view-transition.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Options of {@link startViewTransition}.
|
|
5
4
|
* @since 1.0.0
|
|
@@ -93,5 +92,4 @@ export interface ViewTransitionProps {
|
|
|
93
92
|
* @since 1.0.0
|
|
94
93
|
*/
|
|
95
94
|
export declare function ViewTransition(props: ViewTransitionProps): Accessor<unknown>;
|
|
96
|
-
//#endregion
|
|
97
95
|
//# sourceMappingURL=view-transition.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { flushSync, untrack, useEffect, useId } from "@shadow-js/core";
|
|
2
|
-
|
|
2
|
+
// src/view-transition.ts
|
|
3
3
|
/**
|
|
4
4
|
* Runs `update` inside a browser view transition, so the change animates from the old screen to the
|
|
5
5
|
* new one, and resolves when the animation has finished. Without the API (older browsers, or a
|
|
@@ -115,7 +115,6 @@ function setOrClear(element, property, value) {
|
|
|
115
115
|
if (value === void 0 || value === "") element.style.removeProperty(property);
|
|
116
116
|
else element.style.setProperty(property, value);
|
|
117
117
|
}
|
|
118
|
-
//#endregion
|
|
119
118
|
export { ViewTransition, startViewTransition };
|
|
120
119
|
|
|
121
120
|
//# sourceMappingURL=view-transition.js.map
|
package/dist/prod/attributes.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n
|
|
1
|
+
import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n=/^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/,r=/^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/,i=/^(?:javascript:|data:text\/html|vbscript:)/;function a(n){if(!t.test(n))throw e(n)}function o(e){return e.replace(/\p{Cc}/gu,``)}function s(e){return i.test(o(e).trim().toLowerCase())}function c(e,t){let r=e.toLowerCase();return n.test(r)?r===`values`?t.split(`;`).some(s):s(t):!1}function l(e,t){return t==null?null:t===!1?r.test(e)?`false`:null:t===!0?r.test(e)?`true`:``:String(t)}function u(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function d(e,t,n,r){let i=n.toLowerCase(),a=l(i,r);a===null?t===null?e.removeAttribute(n):e.removeAttributeNS(t,u(n)):/^on./.test(i)||(c(i,a)?`${n}`:t===null?e.getAttribute(n)!==a&&e.setAttribute(n,a):e.getAttributeNS(t,u(n))!==a&&e.setAttributeNS(t,n,a))}function f(e,t,n){a(t),d(e,null,t,n)}function p(e,t,n,r){a(n),d(e,t===``?null:t,n,r)}function m(e,t,n){a(t),e.toggleAttribute(t,!!n)}export{a as assertAttributeName,c as isUnsafeUrlAttribute,f as setAttribute,p as setAttributeNS,m as setBoolAttribute};
|
|
2
2
|
//# sourceMappingURL=attributes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","ENUMERATED_ATTRIBUTES","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","isStringValued","lowerName","stripControls","kept","char","text","code","isUnsafeUrl","normalized","value","prefix","isUnsafeUrlAttribute","attributeText","localPart","colon","qualified","commit","namespace","el","setAttribute","setAttributeNS","setBoolAttribute","present"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"srcdoc\",\n \"poster\",\n \"data\",\n \"values\",\n \"from\",\n \"to\",\n \"by\",\n]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES = new Set([\"draggable\", \"spellcheck\", \"contenteditable\"]);\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their boolean values are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters. Written as a loop so no control character appears in a regex. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `srcdoc`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own.\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.has(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n if (isUnsafeUrlAttribute(lowerName, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n const present = el.hasAttribute(name);\n if (value) {\n if (!present) el.setAttribute(name, \"\");\n } else if (present) {\n el.removeAttribute(name);\n }\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,kBAAiB,IAAI,IAAI,CAC7B,OACA,MACA,SACA,aACA,aACA,SACA,SACA,OACA,SACA,OACA,KACA,IACF,CAAC,EAGKC,kBAAwB,IAAI,IAAI,CAAC,YAAa,aAAc,iBAAiB,CAAC,EAG9EC,EAAsB,CAAC,cAAe,iBAAkB,WAAW,EAOzE,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAe,EAA4B,CAClD,OACEC,EAAU,WAAW,OAAO,GAC5BA,EAAU,WAAW,OAAO,GAC5BN,EAAsB,IAAIM,CAAS,CAEvC,CAGA,SAASC,EAAc,EAAsB,CAC3C,IAAIC,EAAO,GACX,IAAK,IAAMC,KAAQC,EAAM,CACvB,IAAMC,EAAOF,EAAK,WAAW,CAAC,EAC1BE,EAAO,KAASA,EAAO,KAAQA,EAAO,OAAO,GAAQF,EAC3D,CACA,OAAOD,CACT,CAGA,SAASI,EAAY,EAAwB,CAC3C,IAAMC,EAAaN,EAAcO,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,EAC3D,OAAOb,EAAoB,KAAM,GAAWY,EAAW,WAAWE,CAAM,CAAC,CAC3E,CAuBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAA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CAChFxB,EAAoBC,CAAI,EACxB,IAAMwB,EAAUJ,EAAG,aAAapB,CAAI,EAChCW,EACGa,GAASJ,EAAG,aAAapB,EAAM,EAAE,EAC7BwB,GACTJ,EAAG,gBAAgBpB,CAAI,CAE3B,C"}
|
|
1
|
+
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","stripControls","text","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAc,EAAsB,CAC3C,OAAOC,EAAK,QAAQ,WAAY,EAAE,CACpC,CAGA,SAASC,EAAY,EAAwB,CAC3C,OAAON,EAAoB,KAAKI,EAAcG,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,CAC3E,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYP,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKW,CAAS,EAE3BA,IAAc,SAAWF,EAAM,MAAM,GAAG,CAAC,CAAC,KAAKD,CAAW,EAAIA,EAAYC,CAAK,EAF1C,EAG9C,CAGA,SAASG,EAAc,EAAmB,EAA+B,CAIvE,OAHIH,GAAU,KAAoC,KAC9CA,IAAU,GAAcR,EAAc,KAAKU,CAAS,EAAI,QAAU,KAClEF,IAAU,GAAaR,EAAc,KAAKU,CAAS,EAAI,OAAS,GAC7D,OAAOF,CAAK,CACrB,CAGA,SAASI,EAAU,EAA2B,CAC5C,IAAMC,EAAQC,EAAU,QAAQ,GAAG,EACnC,OAAOD,IAAU,GAAKC,EAAYA,EAAU,MAAMD,EAAQ,CAAC,CAC7D,CAGA,SAASE,EAAO,EAAa,EAA0B,EAAmB,EAAsB,CAC9F,IAAML,EAAYI,EAAU,YAAY,EAClCR,EAAOK,EAAcD,EAAWF,CAAK,EACvCF,IAAS,KACPU,IAAc,KAAMC,EAAG,gBAAgBH,CAAS,EAC/CG,EAAG,kBAAkBD,EAAWJ,EAAUE,CAAS,CAAC,EAKvD,OAAO,KAAKJ,CAAS,IAErBD,EAAqBC,EAAWJ,CAAI,EACP,GAAgCQ,EAAhC,EAG7BE,IAAc,KACZC,EAAG,aAAaH,CAAS,IAAMR,GAAMW,EAAG,aAAaH,EAAWR,CAAI,EAC/DW,EAAG,eAAeD,EAAWJ,EAAUE,CAAS,CAAC,IAAMR,GAChEW,EAAG,eAAeD,EAAWF,EAAWR,CAAI,EAEhD,CA+BA,SAAgBY,EAAa,EAAa,EAAc,EAAsB,CAC5EhB,EAAoBC,CAAI,EACxBY,EAAOE,EAAI,KAAMd,EAAMK,CAAK,CAC9B,CAuBA,SAAgBW,EAAe,EAAa,EAAmB,EAAc,EAAsB,CACjGjB,EAAoBC,CAAI,EACxBY,EAAOE,EAAID,IAAc,GAAK,KAAOA,EAAWb,EAAMK,CAAK,CAC7D,CAoBA,SAAgBY,EAAiB,EAAa,EAAc,EAAsB,CAChFlB,EAAoBC,CAAI,EACxBc,EAAG,gBAAgBd,EAAM,EAAQK,CAAM,CACzC,C"}
|
package/dist/prod/class-style.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{cssValueText as e}from"./internal/css-units.js";import{HTML_NS as t}from"./internal/names.js";function n(e,t){let n=[[e]],r=[0],i=/* @__PURE__ */ new Set;for(;n.length>0;){let e=n.length-1,a=n[e],o=r[e]??0;if(a===void 0||o>=a.length){let e=n.pop();e!==void 0&&i.delete(e),r.pop();continue}r[e]=o+1;let s=a[o];if(Array.isArray(s)){if(i.has(s))throw TypeError(`SHADOW_CLASS_CYCLE`);i.add(s),n.push(s),r.push(0)}else if(typeof s==`string`)s!==``&&t.push(s);else if(typeof s==`number`)s!==0&&!Number.isNaN(s)&&t.push(String(s));else if(typeof s==`object`&&s){let e=s;for(let n of Object.keys(e))e[n]&&n!==``&&t.push(n)}}}function r(e){if(typeof e==`string`)return e;if(e==null||e===!1)return null;let t=[];return n(e,t),t.join(` `)}function i(e,t,n){let i=r(t);i===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==i&&e.setAttribute(`class`,i):e.className!==i&&(e.className=i)}function a(e,n){i(e,n,e.namespaceURI!==t)}function o(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function s(e,t,n){let r=t??{},i=n??{},a=/* @__PURE__ */ new Set([...Object.keys(i),...Object.keys(r)]);for(let t of a){let n
|
|
1
|
+
import{cssValueText as e}from"./internal/css-units.js";import{HTML_NS as t}from"./internal/names.js";function n(e,t){let n=[[e]],r=[0],i=/* @__PURE__ */ new Set;for(;n.length>0;){let e=n.length-1,a=n[e],o=r[e]??0;if(a===void 0||o>=a.length){let e=n.pop();e!==void 0&&i.delete(e),r.pop();continue}r[e]=o+1;let s=a[o];if(Array.isArray(s)){if(i.has(s))throw TypeError(`SHADOW_CLASS_CYCLE`);i.add(s),n.push(s),r.push(0)}else if(typeof s==`string`)s!==``&&t.push(s);else if(typeof s==`number`)s!==0&&!Number.isNaN(s)&&t.push(String(s));else if(typeof s==`object`&&s){let e=s;for(let n of Object.keys(e))e[n]&&n!==``&&t.push(n)}}}function r(e){if(typeof e==`string`)return e;if(e==null||e===!1)return null;let t=[];return n(e,t),t.join(` `)}function i(e,t,n){let i=r(t);i===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==i&&e.setAttribute(`class`,i):e.className!==i&&(e.className=i)}function a(e,n){i(e,n,e.namespaceURI!==t)}function o(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function s(e,t){return Object.hasOwn(e,t)&&!!e[t]}function c(e,t,n){let r=t??{},i=n??{},a=/* @__PURE__ */ new Set([...Object.keys(i),...Object.keys(r)]);for(let t of a){let n=s(r,t);if(n!==s(i,t))for(let r of t.split(/\s+/))r!==``&&e.classList.toggle(r,n)}return r}function l(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function u(t,n,r){let i=l(n);r==null||r===!1?t.style.removeProperty(i):t.style.setProperty(i,e(i,r))}function d(e,t,n){if(t==null||t===!1)return e.removeAttribute(`style`),t;if(typeof t!=`object`)return e.style.cssText=String(t),t;if(Array.isArray(t)){e.style.cssText=``;for(let n of t)if(typeof n==`string`)e.style.cssText+=`;${n}`;else if(n!=null&&n!==!1){if(typeof n!=`object`||Array.isArray(n))throw TypeError(`SHADOW_STYLE_ITEM`);d(e,n,{})}return t}let r={...t},i=o(n)??{};(typeof n==`string`||Array.isArray(n))&&(e.style.cssText=``);let a=/* @__PURE__ */ new Set([...Object.keys(i),...Object.keys(r)]);for(let t of a)Object.is(i[t],r[t])||u(e,t,r[t]);return r}export{i as applyClass,o as asRecord,c as classList,a as className,u as setStyleProperty,d as style,l as toCssProperty};
|
|
2
2
|
//# sourceMappingURL=class-style.js.map
|