@shadow-js/web 0.0.0-stage → 1.0.1
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 +18 -0
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/dist/dev/attributes.d.ts +88 -0
- package/dist/dev/attributes.js +195 -0
- package/dist/dev/attributes.js.map +1 -0
- package/dist/dev/autofocus.d.ts +30 -0
- package/dist/dev/autofocus.js +44 -0
- package/dist/dev/autofocus.js.map +1 -0
- package/dist/dev/class-style.d.ts +87 -0
- package/dist/dev/class-style.js +196 -0
- package/dist/dev/class-style.js.map +1 -0
- package/dist/dev/component.d.ts +21 -0
- package/dist/dev/component.js +41 -0
- package/dist/dev/component.js.map +1 -0
- package/dist/dev/control-flow/activity.d.ts +56 -0
- package/dist/dev/control-flow/activity.js +135 -0
- package/dist/dev/control-flow/activity.js.map +1 -0
- package/dist/dev/control-flow/branch.js +103 -0
- package/dist/dev/control-flow/branch.js.map +1 -0
- package/dist/dev/control-flow/client-only.d.ts +46 -0
- package/dist/dev/control-flow/client-only.js +49 -0
- package/dist/dev/control-flow/client-only.js.map +1 -0
- package/dist/dev/control-flow/dynamic.d.ts +80 -0
- package/dist/dev/control-flow/dynamic.js +133 -0
- package/dist/dev/control-flow/dynamic.js.map +1 -0
- package/dist/dev/control-flow/error-boundary.d.ts +70 -0
- package/dist/dev/control-flow/error-boundary.js +114 -0
- package/dist/dev/control-flow/error-boundary.js.map +1 -0
- package/dist/dev/control-flow/for.d.ts +78 -0
- package/dist/dev/control-flow/for.js +22 -0
- package/dist/dev/control-flow/for.js.map +1 -0
- package/dist/dev/control-flow/fragment.d.ts +36 -0
- package/dist/dev/control-flow/fragment.js +30 -0
- package/dist/dev/control-flow/fragment.js.map +1 -0
- package/dist/dev/control-flow/hot-link.js +63 -0
- package/dist/dev/control-flow/hot-link.js.map +1 -0
- package/dist/dev/control-flow/index-list.d.ts +46 -0
- package/dist/dev/control-flow/index-list.js +30 -0
- package/dist/dev/control-flow/index-list.js.map +1 -0
- package/dist/dev/control-flow/index.d.ts +15 -0
- package/dist/dev/control-flow/lazy.d.ts +56 -0
- package/dist/dev/control-flow/lazy.js +63 -0
- package/dist/dev/control-flow/lazy.js.map +1 -0
- package/dist/dev/control-flow/no-hydration.d.ts +37 -0
- package/dist/dev/control-flow/no-hydration.js +57 -0
- package/dist/dev/control-flow/no-hydration.js.map +1 -0
- package/dist/dev/control-flow/portal.d.ts +67 -0
- package/dist/dev/control-flow/portal.js +133 -0
- package/dist/dev/control-flow/portal.js.map +1 -0
- package/dist/dev/control-flow/root-errors.d.ts +23 -0
- package/dist/dev/control-flow/root-errors.js +32 -0
- package/dist/dev/control-flow/root-errors.js.map +1 -0
- package/dist/dev/control-flow/show.d.ts +99 -0
- package/dist/dev/control-flow/show.js +17 -0
- package/dist/dev/control-flow/show.js.map +1 -0
- package/dist/dev/control-flow/suspense-list.d.ts +63 -0
- package/dist/dev/control-flow/suspense-list.js +104 -0
- package/dist/dev/control-flow/suspense-list.js.map +1 -0
- package/dist/dev/control-flow/suspense.d.ts +51 -0
- package/dist/dev/control-flow/suspense.js +101 -0
- package/dist/dev/control-flow/suspense.js.map +1 -0
- package/dist/dev/control-flow/switch.d.ts +83 -0
- package/dist/dev/control-flow/switch.js +89 -0
- package/dist/dev/control-flow/switch.js.map +1 -0
- package/dist/dev/derived.d.ts +50 -0
- package/dist/dev/derived.js +33 -0
- package/dist/dev/derived.js.map +1 -0
- package/dist/dev/element.d.ts +38 -0
- package/dist/dev/element.js +104 -0
- package/dist/dev/element.js.map +1 -0
- package/dist/dev/events.d.ts +85 -0
- package/dist/dev/events.js +264 -0
- package/dist/dev/events.js.map +1 -0
- package/dist/dev/extend.d.ts +12 -0
- package/dist/dev/extend.js +12 -0
- package/dist/dev/head/components.d.ts +135 -0
- package/dist/dev/head/components.js +169 -0
- package/dist/dev/head/components.js.map +1 -0
- package/dist/dev/head/registry.js +67 -0
- package/dist/dev/head/registry.js.map +1 -0
- package/dist/dev/head/server-head.d.ts +52 -0
- package/dist/dev/head/server-head.js +75 -0
- package/dist/dev/head/server-head.js.map +1 -0
- package/dist/dev/head/sink.js +95 -0
- package/dist/dev/head/sink.js.map +1 -0
- package/dist/dev/head/use-head.d.ts +33 -0
- package/dist/dev/head/use-head.js +83 -0
- package/dist/dev/head/use-head.js.map +1 -0
- package/dist/dev/head/validate.d.ts +83 -0
- package/dist/dev/head/validate.js +267 -0
- package/dist/dev/head/validate.js.map +1 -0
- package/dist/dev/hmr.d.ts +80 -0
- package/dist/dev/hmr.js +123 -0
- package/dist/dev/hmr.js.map +1 -0
- package/dist/dev/hydration.d.ts +59 -0
- package/dist/dev/hydration.js +119 -0
- package/dist/dev/hydration.js.map +1 -0
- package/dist/dev/index.d.ts +45 -0
- package/dist/dev/index.js +34 -0
- package/dist/dev/insert.d.ts +95 -0
- package/dist/dev/insert.js +356 -0
- package/dist/dev/insert.js.map +1 -0
- package/dist/dev/internal/claim.d.ts +104 -0
- package/dist/dev/internal/claim.js +356 -0
- package/dist/dev/internal/claim.js.map +1 -0
- package/dist/dev/internal/css-units.js +25 -0
- package/dist/dev/internal/css-units.js.map +1 -0
- package/dist/dev/internal/diagnostics.d.ts +28 -0
- package/dist/dev/internal/diagnostics.js +37 -0
- package/dist/dev/internal/diagnostics.js.map +1 -0
- package/dist/dev/internal/early-events.js +75 -0
- package/dist/dev/internal/early-events.js.map +1 -0
- package/dist/dev/internal/hydration-hooks.d.ts +41 -0
- package/dist/dev/internal/hydration-hooks.js +26 -0
- package/dist/dev/internal/hydration-hooks.js.map +1 -0
- package/dist/dev/internal/hydration-scope.d.ts +129 -0
- package/dist/dev/internal/hydration-scope.js +155 -0
- package/dist/dev/internal/hydration-scope.js.map +1 -0
- package/dist/dev/internal/names.d.ts +31 -0
- package/dist/dev/internal/names.js +34 -0
- package/dist/dev/internal/names.js.map +1 -0
- package/dist/dev/internal/portal-context.d.ts +37 -0
- package/dist/dev/internal/portal-context.js +27 -0
- package/dist/dev/internal/portal-context.js.map +1 -0
- package/dist/dev/internal/react-names.js +115 -0
- package/dist/dev/internal/react-names.js.map +1 -0
- package/dist/dev/internal/reconcile.d.ts +38 -0
- package/dist/dev/internal/reconcile.js +121 -0
- package/dist/dev/internal/reconcile.js.map +1 -0
- package/dist/dev/internal/stream-context.d.ts +45 -0
- package/dist/dev/internal/stream-context.js +22 -0
- package/dist/dev/internal/stream-context.js.map +1 -0
- package/dist/dev/jsx/aria.d.ts +70 -0
- package/dist/dev/jsx/component.d.ts +87 -0
- package/dist/dev/jsx/events.d.ts +362 -0
- package/dist/dev/jsx/global.d.ts +209 -0
- package/dist/dev/jsx/html.d.ts +877 -0
- package/dist/dev/jsx/intrinsic.d.ts +57 -0
- package/dist/dev/jsx/mathml.d.ts +184 -0
- package/dist/dev/jsx/svg.d.ts +605 -0
- package/dist/dev/jsx/types.d.ts +174 -0
- package/dist/dev/jsx-dev-runtime.d.ts +10 -0
- package/dist/dev/jsx-dev-runtime.js +0 -0
- package/dist/dev/jsx-runtime.d.ts +92 -0
- package/dist/dev/jsx-runtime.js +0 -0
- package/dist/dev/reactive.d.ts +108 -0
- package/dist/dev/reactive.js +84 -0
- package/dist/dev/reactive.js.map +1 -0
- package/dist/dev/render.d.ts +34 -0
- package/dist/dev/render.js +51 -0
- package/dist/dev/render.js.map +1 -0
- package/dist/dev/resource-hints.d.ts +143 -0
- package/dist/dev/resource-hints.js +199 -0
- package/dist/dev/resource-hints.js.map +1 -0
- package/dist/dev/select-value.d.ts +22 -0
- package/dist/dev/select-value.js +50 -0
- package/dist/dev/select-value.js.map +1 -0
- package/dist/dev/server/attributes.d.ts +31 -0
- package/dist/dev/server/attributes.js +154 -0
- package/dist/dev/server/attributes.js.map +1 -0
- package/dist/dev/server/class-style.d.ts +44 -0
- package/dist/dev/server/class-style.js +172 -0
- package/dist/dev/server/class-style.js.map +1 -0
- package/dist/dev/server/component.d.ts +40 -0
- package/dist/dev/server/component.js +71 -0
- package/dist/dev/server/component.js.map +1 -0
- package/dist/dev/server/derived.d.ts +39 -0
- package/dist/dev/server/derived.js +25 -0
- package/dist/dev/server/derived.js.map +1 -0
- package/dist/dev/server/element.d.ts +87 -0
- package/dist/dev/server/element.js +215 -0
- package/dist/dev/server/element.js.map +1 -0
- package/dist/dev/server/errors.js +25 -0
- package/dist/dev/server/errors.js.map +1 -0
- package/dist/dev/server/escape.d.ts +28 -0
- package/dist/dev/server/escape.js +118 -0
- package/dist/dev/server/escape.js.map +1 -0
- package/dist/dev/server/form-controls.d.ts +48 -0
- package/dist/dev/server/form-controls.js +192 -0
- package/dist/dev/server/form-controls.js.map +1 -0
- package/dist/dev/server/hydration-script.d.ts +63 -0
- package/dist/dev/server/hydration-script.js +58 -0
- package/dist/dev/server/hydration-script.js.map +1 -0
- package/dist/dev/server/index.d.ts +16 -0
- package/dist/dev/server/index.js +16 -0
- package/dist/dev/server/node.d.ts +11 -0
- package/dist/dev/server/node.js +20 -0
- package/dist/dev/server/node.js.map +1 -0
- package/dist/dev/server/portals.d.ts +44 -0
- package/dist/dev/server/portals.js +98 -0
- package/dist/dev/server/portals.js.map +1 -0
- package/dist/dev/server/render.d.ts +127 -0
- package/dist/dev/server/render.js +255 -0
- package/dist/dev/server/render.js.map +1 -0
- package/dist/dev/server/serialize.d.ts +43 -0
- package/dist/dev/server/serialize.js +314 -0
- package/dist/dev/server/serialize.js.map +1 -0
- package/dist/dev/server/stream.d.ts +92 -0
- package/dist/dev/server/stream.js +234 -0
- package/dist/dev/server/stream.js.map +1 -0
- package/dist/dev/server.d.ts +16 -0
- package/dist/dev/server.js +16 -0
- package/dist/dev/spread.d.ts +47 -0
- package/dist/dev/spread.js +295 -0
- package/dist/dev/spread.js.map +1 -0
- package/dist/dev/template.d.ts +24 -0
- package/dist/dev/template.js +119 -0
- package/dist/dev/template.js.map +1 -0
- package/dist/dev/view-transition.d.ts +95 -0
- package/dist/dev/view-transition.js +120 -0
- package/dist/dev/view-transition.js.map +1 -0
- package/dist/prod/attributes.js +2 -0
- package/dist/prod/attributes.js.map +1 -0
- package/dist/prod/autofocus.js +2 -0
- package/dist/prod/autofocus.js.map +1 -0
- package/dist/prod/class-style.js +2 -0
- package/dist/prod/class-style.js.map +1 -0
- package/dist/prod/component.js +2 -0
- package/dist/prod/component.js.map +1 -0
- package/dist/prod/control-flow/activity.js +2 -0
- package/dist/prod/control-flow/activity.js.map +1 -0
- package/dist/prod/control-flow/branch.js +2 -0
- package/dist/prod/control-flow/branch.js.map +1 -0
- package/dist/prod/control-flow/client-only.js +2 -0
- package/dist/prod/control-flow/client-only.js.map +1 -0
- package/dist/prod/control-flow/dynamic.js +2 -0
- package/dist/prod/control-flow/dynamic.js.map +1 -0
- package/dist/prod/control-flow/error-boundary.js +2 -0
- package/dist/prod/control-flow/error-boundary.js.map +1 -0
- package/dist/prod/control-flow/for.js +2 -0
- package/dist/prod/control-flow/for.js.map +1 -0
- package/dist/prod/control-flow/fragment.js +2 -0
- package/dist/prod/control-flow/fragment.js.map +1 -0
- package/dist/prod/control-flow/hot-link.js +2 -0
- package/dist/prod/control-flow/hot-link.js.map +1 -0
- package/dist/prod/control-flow/index-list.js +2 -0
- package/dist/prod/control-flow/index-list.js.map +1 -0
- package/dist/prod/control-flow/lazy.js +2 -0
- package/dist/prod/control-flow/lazy.js.map +1 -0
- package/dist/prod/control-flow/no-hydration.js +2 -0
- package/dist/prod/control-flow/no-hydration.js.map +1 -0
- package/dist/prod/control-flow/portal.js +2 -0
- package/dist/prod/control-flow/portal.js.map +1 -0
- package/dist/prod/control-flow/root-errors.js +2 -0
- package/dist/prod/control-flow/root-errors.js.map +1 -0
- package/dist/prod/control-flow/show.js +2 -0
- package/dist/prod/control-flow/show.js.map +1 -0
- package/dist/prod/control-flow/suspense-list.js +2 -0
- package/dist/prod/control-flow/suspense-list.js.map +1 -0
- package/dist/prod/control-flow/suspense.js +2 -0
- package/dist/prod/control-flow/suspense.js.map +1 -0
- package/dist/prod/control-flow/switch.js +2 -0
- package/dist/prod/control-flow/switch.js.map +1 -0
- package/dist/prod/derived.js +2 -0
- package/dist/prod/derived.js.map +1 -0
- package/dist/prod/element.js +2 -0
- package/dist/prod/element.js.map +1 -0
- package/dist/prod/events.js +2 -0
- package/dist/prod/events.js.map +1 -0
- package/dist/prod/extend.js +1 -0
- package/dist/prod/head/components.js +2 -0
- package/dist/prod/head/components.js.map +1 -0
- package/dist/prod/head/registry.js +2 -0
- package/dist/prod/head/registry.js.map +1 -0
- package/dist/prod/head/server-head.js +2 -0
- package/dist/prod/head/server-head.js.map +1 -0
- package/dist/prod/head/sink.js +2 -0
- package/dist/prod/head/sink.js.map +1 -0
- package/dist/prod/head/use-head.js +2 -0
- package/dist/prod/head/use-head.js.map +1 -0
- package/dist/prod/head/validate.js +2 -0
- package/dist/prod/head/validate.js.map +1 -0
- package/dist/prod/hmr.js +2 -0
- package/dist/prod/hmr.js.map +1 -0
- package/dist/prod/hydration.js +2 -0
- package/dist/prod/hydration.js.map +1 -0
- package/dist/prod/index.js +1 -0
- package/dist/prod/insert.js +2 -0
- package/dist/prod/insert.js.map +1 -0
- package/dist/prod/internal/claim.js +2 -0
- package/dist/prod/internal/claim.js.map +1 -0
- package/dist/prod/internal/css-units.js +2 -0
- package/dist/prod/internal/css-units.js.map +1 -0
- package/dist/prod/internal/diagnostics.js +2 -0
- package/dist/prod/internal/diagnostics.js.map +1 -0
- package/dist/prod/internal/early-events.js +2 -0
- package/dist/prod/internal/early-events.js.map +1 -0
- package/dist/prod/internal/hydration-hooks.js +2 -0
- package/dist/prod/internal/hydration-hooks.js.map +1 -0
- package/dist/prod/internal/hydration-scope.js +2 -0
- package/dist/prod/internal/hydration-scope.js.map +1 -0
- package/dist/prod/internal/names.js +2 -0
- package/dist/prod/internal/names.js.map +1 -0
- package/dist/prod/internal/portal-context.js +2 -0
- package/dist/prod/internal/portal-context.js.map +1 -0
- package/dist/prod/internal/react-names.js +2 -0
- package/dist/prod/internal/react-names.js.map +1 -0
- package/dist/prod/internal/reconcile.js +2 -0
- package/dist/prod/internal/reconcile.js.map +1 -0
- package/dist/prod/internal/stream-context.js +2 -0
- package/dist/prod/internal/stream-context.js.map +1 -0
- package/dist/prod/jsx-dev-runtime.js +0 -0
- package/dist/prod/jsx-runtime.js +0 -0
- package/dist/prod/reactive.js +2 -0
- package/dist/prod/reactive.js.map +1 -0
- package/dist/prod/render.js +2 -0
- package/dist/prod/render.js.map +1 -0
- package/dist/prod/resource-hints.js +2 -0
- package/dist/prod/resource-hints.js.map +1 -0
- package/dist/prod/select-value.js +2 -0
- package/dist/prod/select-value.js.map +1 -0
- package/dist/prod/server/attributes.js +2 -0
- package/dist/prod/server/attributes.js.map +1 -0
- package/dist/prod/server/class-style.js +2 -0
- package/dist/prod/server/class-style.js.map +1 -0
- package/dist/prod/server/component.js +2 -0
- package/dist/prod/server/component.js.map +1 -0
- package/dist/prod/server/derived.js +2 -0
- package/dist/prod/server/derived.js.map +1 -0
- package/dist/prod/server/element.js +2 -0
- package/dist/prod/server/element.js.map +1 -0
- package/dist/prod/server/errors.js +2 -0
- package/dist/prod/server/errors.js.map +1 -0
- package/dist/prod/server/escape.js +2 -0
- package/dist/prod/server/escape.js.map +1 -0
- package/dist/prod/server/form-controls.js +3 -0
- package/dist/prod/server/form-controls.js.map +1 -0
- package/dist/prod/server/hydration-script.js +2 -0
- package/dist/prod/server/hydration-script.js.map +1 -0
- package/dist/prod/server/index.js +1 -0
- package/dist/prod/server/node.js +2 -0
- package/dist/prod/server/node.js.map +1 -0
- package/dist/prod/server/portals.js +2 -0
- package/dist/prod/server/portals.js.map +1 -0
- package/dist/prod/server/render.js +2 -0
- package/dist/prod/server/render.js.map +1 -0
- package/dist/prod/server/serialize.js +2 -0
- package/dist/prod/server/serialize.js.map +1 -0
- package/dist/prod/server/stream.js +2 -0
- package/dist/prod/server/stream.js.map +1 -0
- package/dist/prod/server.js +1 -0
- package/dist/prod/spread.js +2 -0
- package/dist/prod/spread.js.map +1 -0
- package/dist/prod/template.js +2 -0
- package/dist/prod/template.js.map +1 -0
- package/dist/prod/view-transition.js +2 -0
- package/dist/prod/view-transition.js.map +1 -0
- package/dist/server/attributes.js +2 -0
- package/dist/server/attributes.js.map +1 -0
- package/dist/server/autofocus.js +2 -0
- package/dist/server/autofocus.js.map +1 -0
- package/dist/server/class-style.js +2 -0
- package/dist/server/class-style.js.map +1 -0
- package/dist/server/component.js +2 -0
- package/dist/server/component.js.map +1 -0
- package/dist/server/control-flow/activity.js +2 -0
- package/dist/server/control-flow/activity.js.map +1 -0
- package/dist/server/control-flow/branch.js +2 -0
- package/dist/server/control-flow/branch.js.map +1 -0
- package/dist/server/control-flow/client-only.js +2 -0
- package/dist/server/control-flow/client-only.js.map +1 -0
- package/dist/server/control-flow/dynamic.js +2 -0
- package/dist/server/control-flow/dynamic.js.map +1 -0
- package/dist/server/control-flow/error-boundary.js +2 -0
- package/dist/server/control-flow/error-boundary.js.map +1 -0
- package/dist/server/control-flow/for.js +2 -0
- package/dist/server/control-flow/for.js.map +1 -0
- package/dist/server/control-flow/fragment.js +2 -0
- package/dist/server/control-flow/fragment.js.map +1 -0
- package/dist/server/control-flow/index-list.js +2 -0
- package/dist/server/control-flow/index-list.js.map +1 -0
- package/dist/server/control-flow/lazy.js +2 -0
- package/dist/server/control-flow/lazy.js.map +1 -0
- package/dist/server/control-flow/no-hydration.js +2 -0
- package/dist/server/control-flow/no-hydration.js.map +1 -0
- package/dist/server/control-flow/portal.js +2 -0
- package/dist/server/control-flow/portal.js.map +1 -0
- package/dist/server/control-flow/root-errors.js +2 -0
- package/dist/server/control-flow/root-errors.js.map +1 -0
- package/dist/server/control-flow/show.js +2 -0
- package/dist/server/control-flow/show.js.map +1 -0
- package/dist/server/control-flow/suspense-list.js +2 -0
- package/dist/server/control-flow/suspense-list.js.map +1 -0
- package/dist/server/control-flow/suspense.js +2 -0
- package/dist/server/control-flow/suspense.js.map +1 -0
- package/dist/server/control-flow/switch.js +2 -0
- package/dist/server/control-flow/switch.js.map +1 -0
- package/dist/server/derived.js +2 -0
- package/dist/server/derived.js.map +1 -0
- package/dist/server/element.js +2 -0
- package/dist/server/element.js.map +1 -0
- package/dist/server/events.js +2 -0
- package/dist/server/events.js.map +1 -0
- package/dist/server/extend.js +1 -0
- package/dist/server/head/components.js +2 -0
- package/dist/server/head/components.js.map +1 -0
- package/dist/server/head/registry.js +2 -0
- package/dist/server/head/registry.js.map +1 -0
- package/dist/server/head/server-head.js +2 -0
- package/dist/server/head/server-head.js.map +1 -0
- package/dist/server/head/sink.js +2 -0
- package/dist/server/head/sink.js.map +1 -0
- package/dist/server/head/use-head.js +2 -0
- package/dist/server/head/use-head.js.map +1 -0
- package/dist/server/head/validate.js +2 -0
- package/dist/server/head/validate.js.map +1 -0
- package/dist/server/hydration.js +2 -0
- package/dist/server/hydration.js.map +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/insert.js +2 -0
- package/dist/server/insert.js.map +1 -0
- package/dist/server/internal/claim.js +2 -0
- package/dist/server/internal/claim.js.map +1 -0
- package/dist/server/internal/css-units.js +2 -0
- package/dist/server/internal/css-units.js.map +1 -0
- package/dist/server/internal/diagnostics.js +2 -0
- package/dist/server/internal/diagnostics.js.map +1 -0
- package/dist/server/internal/early-events.js +2 -0
- package/dist/server/internal/early-events.js.map +1 -0
- package/dist/server/internal/hydration-hooks.js +2 -0
- package/dist/server/internal/hydration-hooks.js.map +1 -0
- package/dist/server/internal/hydration-scope.js +2 -0
- package/dist/server/internal/hydration-scope.js.map +1 -0
- package/dist/server/internal/names.js +2 -0
- package/dist/server/internal/names.js.map +1 -0
- package/dist/server/internal/portal-context.js +2 -0
- package/dist/server/internal/portal-context.js.map +1 -0
- package/dist/server/internal/react-names.js +2 -0
- package/dist/server/internal/react-names.js.map +1 -0
- package/dist/server/internal/reconcile.js +2 -0
- package/dist/server/internal/reconcile.js.map +1 -0
- package/dist/server/internal/stream-context.js +2 -0
- package/dist/server/internal/stream-context.js.map +1 -0
- package/dist/server/reactive.js +2 -0
- package/dist/server/reactive.js.map +1 -0
- package/dist/server/render.js +2 -0
- package/dist/server/render.js.map +1 -0
- package/dist/server/resource-hints.js +2 -0
- package/dist/server/resource-hints.js.map +1 -0
- package/dist/server/select-value.js +2 -0
- package/dist/server/select-value.js.map +1 -0
- package/dist/server/server/attributes.js +2 -0
- package/dist/server/server/attributes.js.map +1 -0
- package/dist/server/server/class-style.js +2 -0
- package/dist/server/server/class-style.js.map +1 -0
- package/dist/server/server/component.js +2 -0
- package/dist/server/server/component.js.map +1 -0
- package/dist/server/server/derived.js +2 -0
- package/dist/server/server/derived.js.map +1 -0
- package/dist/server/server/element.js +2 -0
- package/dist/server/server/element.js.map +1 -0
- package/dist/server/server/errors.js +2 -0
- package/dist/server/server/errors.js.map +1 -0
- package/dist/server/server/escape.js +2 -0
- package/dist/server/server/escape.js.map +1 -0
- package/dist/server/server/form-controls.js +3 -0
- package/dist/server/server/form-controls.js.map +1 -0
- package/dist/server/server/hydration-script.js +2 -0
- package/dist/server/server/hydration-script.js.map +1 -0
- package/dist/server/server/index.js +1 -0
- package/dist/server/server/node.js +2 -0
- package/dist/server/server/node.js.map +1 -0
- package/dist/server/server/portals.js +2 -0
- package/dist/server/server/portals.js.map +1 -0
- package/dist/server/server/render.js +2 -0
- package/dist/server/server/render.js.map +1 -0
- package/dist/server/server/serialize.js +2 -0
- package/dist/server/server/serialize.js.map +1 -0
- package/dist/server/server/stream.js +2 -0
- package/dist/server/server/stream.js.map +1 -0
- package/dist/server/server.js +1 -0
- package/dist/server/spread.js +2 -0
- package/dist/server/spread.js.map +1 -0
- package/dist/server/template.js +2 -0
- package/dist/server/template.js.map +1 -0
- package/dist/server/view-transition.js +2 -0
- package/dist/server/view-transition.js.map +1 -0
- package/dist/server-dev/attributes.js +195 -0
- package/dist/server-dev/attributes.js.map +1 -0
- package/dist/server-dev/autofocus.js +44 -0
- package/dist/server-dev/autofocus.js.map +1 -0
- package/dist/server-dev/class-style.js +196 -0
- package/dist/server-dev/class-style.js.map +1 -0
- package/dist/server-dev/component.js +41 -0
- package/dist/server-dev/component.js.map +1 -0
- package/dist/server-dev/control-flow/activity.js +40 -0
- package/dist/server-dev/control-flow/activity.js.map +1 -0
- package/dist/server-dev/control-flow/branch.js +103 -0
- package/dist/server-dev/control-flow/branch.js.map +1 -0
- package/dist/server-dev/control-flow/client-only.js +49 -0
- package/dist/server-dev/control-flow/client-only.js.map +1 -0
- package/dist/server-dev/control-flow/dynamic.js +105 -0
- package/dist/server-dev/control-flow/dynamic.js.map +1 -0
- package/dist/server-dev/control-flow/error-boundary.js +114 -0
- package/dist/server-dev/control-flow/error-boundary.js.map +1 -0
- package/dist/server-dev/control-flow/for.js +22 -0
- package/dist/server-dev/control-flow/for.js.map +1 -0
- package/dist/server-dev/control-flow/fragment.js +30 -0
- package/dist/server-dev/control-flow/fragment.js.map +1 -0
- package/dist/server-dev/control-flow/hot-link.js +56 -0
- package/dist/server-dev/control-flow/hot-link.js.map +1 -0
- package/dist/server-dev/control-flow/index-list.js +30 -0
- package/dist/server-dev/control-flow/index-list.js.map +1 -0
- package/dist/server-dev/control-flow/lazy.js +63 -0
- package/dist/server-dev/control-flow/lazy.js.map +1 -0
- package/dist/server-dev/control-flow/no-hydration.js +39 -0
- package/dist/server-dev/control-flow/no-hydration.js.map +1 -0
- package/dist/server-dev/control-flow/portal.js +133 -0
- package/dist/server-dev/control-flow/portal.js.map +1 -0
- package/dist/server-dev/control-flow/root-errors.js +32 -0
- package/dist/server-dev/control-flow/root-errors.js.map +1 -0
- package/dist/server-dev/control-flow/show.js +17 -0
- package/dist/server-dev/control-flow/show.js.map +1 -0
- package/dist/server-dev/control-flow/suspense-list.js +99 -0
- package/dist/server-dev/control-flow/suspense-list.js.map +1 -0
- package/dist/server-dev/control-flow/suspense.js +118 -0
- package/dist/server-dev/control-flow/suspense.js.map +1 -0
- package/dist/server-dev/control-flow/switch.js +89 -0
- package/dist/server-dev/control-flow/switch.js.map +1 -0
- package/dist/server-dev/derived.js +33 -0
- package/dist/server-dev/derived.js.map +1 -0
- package/dist/server-dev/element.js +65 -0
- package/dist/server-dev/element.js.map +1 -0
- package/dist/server-dev/events.js +264 -0
- package/dist/server-dev/events.js.map +1 -0
- package/dist/server-dev/extend.js +12 -0
- package/dist/server-dev/head/components.js +169 -0
- package/dist/server-dev/head/components.js.map +1 -0
- package/dist/server-dev/head/registry.js +67 -0
- package/dist/server-dev/head/registry.js.map +1 -0
- package/dist/server-dev/head/server-head.js +75 -0
- package/dist/server-dev/head/server-head.js.map +1 -0
- package/dist/server-dev/head/sink.js +95 -0
- package/dist/server-dev/head/sink.js.map +1 -0
- package/dist/server-dev/head/use-head.js +83 -0
- package/dist/server-dev/head/use-head.js.map +1 -0
- package/dist/server-dev/head/validate.js +267 -0
- package/dist/server-dev/head/validate.js.map +1 -0
- package/dist/server-dev/hydration.js +119 -0
- package/dist/server-dev/hydration.js.map +1 -0
- package/dist/server-dev/index.js +34 -0
- package/dist/server-dev/insert.js +356 -0
- package/dist/server-dev/insert.js.map +1 -0
- package/dist/server-dev/internal/claim.js +356 -0
- package/dist/server-dev/internal/claim.js.map +1 -0
- package/dist/server-dev/internal/css-units.js +25 -0
- package/dist/server-dev/internal/css-units.js.map +1 -0
- package/dist/server-dev/internal/diagnostics.js +37 -0
- package/dist/server-dev/internal/diagnostics.js.map +1 -0
- package/dist/server-dev/internal/early-events.js +75 -0
- package/dist/server-dev/internal/early-events.js.map +1 -0
- package/dist/server-dev/internal/hydration-hooks.js +26 -0
- package/dist/server-dev/internal/hydration-hooks.js.map +1 -0
- package/dist/server-dev/internal/hydration-scope.js +155 -0
- package/dist/server-dev/internal/hydration-scope.js.map +1 -0
- package/dist/server-dev/internal/names.js +34 -0
- package/dist/server-dev/internal/names.js.map +1 -0
- package/dist/server-dev/internal/portal-context.js +27 -0
- package/dist/server-dev/internal/portal-context.js.map +1 -0
- package/dist/server-dev/internal/react-names.js +115 -0
- package/dist/server-dev/internal/react-names.js.map +1 -0
- package/dist/server-dev/internal/reconcile.js +121 -0
- package/dist/server-dev/internal/reconcile.js.map +1 -0
- package/dist/server-dev/internal/stream-context.js +22 -0
- package/dist/server-dev/internal/stream-context.js.map +1 -0
- package/dist/server-dev/reactive.js +84 -0
- package/dist/server-dev/reactive.js.map +1 -0
- package/dist/server-dev/render.js +51 -0
- package/dist/server-dev/render.js.map +1 -0
- package/dist/server-dev/resource-hints.js +199 -0
- package/dist/server-dev/resource-hints.js.map +1 -0
- package/dist/server-dev/select-value.js +50 -0
- package/dist/server-dev/select-value.js.map +1 -0
- package/dist/server-dev/server/attributes.js +154 -0
- package/dist/server-dev/server/attributes.js.map +1 -0
- package/dist/server-dev/server/class-style.js +172 -0
- package/dist/server-dev/server/class-style.js.map +1 -0
- package/dist/server-dev/server/component.js +71 -0
- package/dist/server-dev/server/component.js.map +1 -0
- package/dist/server-dev/server/derived.js +25 -0
- package/dist/server-dev/server/derived.js.map +1 -0
- package/dist/server-dev/server/element.js +215 -0
- package/dist/server-dev/server/element.js.map +1 -0
- package/dist/server-dev/server/errors.js +25 -0
- package/dist/server-dev/server/errors.js.map +1 -0
- package/dist/server-dev/server/escape.js +118 -0
- package/dist/server-dev/server/escape.js.map +1 -0
- package/dist/server-dev/server/form-controls.js +192 -0
- package/dist/server-dev/server/form-controls.js.map +1 -0
- package/dist/server-dev/server/hydration-script.js +58 -0
- package/dist/server-dev/server/hydration-script.js.map +1 -0
- package/dist/server-dev/server/index.js +16 -0
- package/dist/server-dev/server/node.js +20 -0
- package/dist/server-dev/server/node.js.map +1 -0
- package/dist/server-dev/server/portals.js +98 -0
- package/dist/server-dev/server/portals.js.map +1 -0
- package/dist/server-dev/server/render.js +255 -0
- package/dist/server-dev/server/render.js.map +1 -0
- package/dist/server-dev/server/serialize.js +314 -0
- package/dist/server-dev/server/serialize.js.map +1 -0
- package/dist/server-dev/server/stream.js +234 -0
- package/dist/server-dev/server/stream.js.map +1 -0
- package/dist/server-dev/server.js +16 -0
- package/dist/server-dev/spread.js +295 -0
- package/dist/server-dev/spread.js.map +1 -0
- package/dist/server-dev/template.js +119 -0
- package/dist/server-dev/template.js.map +1 -0
- package/dist/server-dev/view-transition.js +89 -0
- package/dist/server-dev/view-transition.js.map +1 -0
- package/package.json +136 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"select-value.js","names":["listed","values","item","value","single","setSelectValue","select","wanted","option","selectShows"],"sources":["../../src/select-value.ts"],"sourcesContent":["/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n const values = new Set<string>();\n for (const item of value) {\n if (item !== null && item !== undefined) values.add(String(item));\n }\n return values;\n}\n\n/** The string a single value assigns to `select.value`; null and undefined clear the choice. */\nfunction single(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`).\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = single(value);\n}\n\n/** True when the select already shows `value` the way {@link setSelectValue} would leave it. @internal */\nexport function selectShows(select: HTMLSelectElement, value: unknown): boolean {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n return Array.from(select.options).every(\n (option) => option.selected === wanted.has(option.value),\n );\n }\n return select.value === single(value);\n}\n"],"mappings":"AACA,SAASA,EAAO,EAAwC,CACtD,IAAMC,kBAAS,IAAI,IACnB,IAAK,IAAMC,KAAQC,EACbD,GAAS,MAA4BD,EAAO,IAAI,OAAOC,CAAI,CAAC,EAElE,OAAOD,CACT,CAGA,SAASG,EAAO,EAAwB,CACtC,OAAOD,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAsBA,SAAgBE,EAAe,EAA2B,EAAsB,CAC9E,GAAIC,EAAO,UAAY,MAAM,QAAQH,CAAK,EAAG,CAC3C,IAAMI,EAASP,EAAOG,CAAK,EAC3B,IAAK,IAAMK,KAAU,MAAM,KAAKF,EAAO,OAAO,EAAG,EAAO,SAAWC,EAAO,IAAIC,EAAO,KAAK,CAE5F,KACA,GAAO,MAAQJ,EAAOD,CAAK,CAC7B,CAGA,SAAgBM,EAAY,EAA2B,EAAyB,CAC9E,GAAIH,EAAO,UAAY,MAAM,QAAQH,CAAK,EAAG,CAC3C,IAAMI,EAASP,EAAOG,CAAK,EAC3B,OAAO,MAAM,KAAKG,EAAO,OAAO,CAAC,CAAC,MAC/B,GAAWE,EAAO,WAAaD,EAAO,IAAIC,EAAO,KAAK,CACzD,CACF,CACA,OAAOF,EAAO,QAAUF,EAAOD,CAAK,CACtC,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{invalid as e}from"./errors.js";import{escapeHtml as t,resolveValue as n}from"./escape.js";const r=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,i=/* @__PURE__ */ new Set([`href`,`src`,`action`,`formaction`,`xlink:href`,`srcdoc`,`poster`,`data`]),a=/* @__PURE__ */ new Set([`values`,`from`,`to`,`by`]),o=/* @__PURE__ */ new Set([`draggable`,`spellcheck`,`contenteditable`]),s=/* @__PURE__ */ new Set([`async`,`autofocus`,`autoplay`,`checked`,`controls`,`default`,`defer`,`disabled`,`formnovalidate`,`hidden`,`inert`,`ismap`,`loop`,`multiple`,`muted`,`nomodule`,`novalidate`,`open`,`playsinline`,`readonly`,`required`,`reversed`,`selected`]),c=[`javascript:`,`data:text/html`,`vbscript:`];function l(t){if(!r.test(t))throw e(`INVALID_ATTRIBUTE_NAME`,`"${t}" is not a valid attribute name.`)}function u(e){return e.length>2&&e.startsWith(`on`)}function d(e){return e.startsWith(`aria-`)||e.startsWith(`data-`)||o.has(e)}function f(e){let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&(e<127||e>159)&&(t+=n)}return t}function p(e){let t=f(e).trim().toLowerCase();return c.some(e=>t.startsWith(e))}function m(e,t){return i.has(e)?p(t):a.has(e)&&t.split(`;`).some(p)}function h(e,t){return t==null?null:t===!1?d(e)?`false`:null:t===!0?d(e)?`true`:``:String(t)}function g(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be an attribute value.`)}function _(e,r,i=!1){l(e);let a=e.toLowerCase();if(u(a))return``;let o=n(r);if(g(o),i)return o?` ${e}`:``;let s=h(a,o);return s===null||m(a,s)?``:` ${e}="${t(s)}"`}export{s as BOOLEAN_ATTRIBUTES,l as assertAttributeName,h as attributeText,u as isEventName,p as isUnsafeUrl,_ as ssrAttribute};
|
|
2
|
+
//# sourceMappingURL=attributes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","ANIMATION_VALUE_ATTRIBUTES","ENUMERATED_ATTRIBUTES","BOOLEAN_ATTRIBUTES","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalid","isEventName","lowerName","isStringValued","stripControls","kept","char","text","code","isUnsafeUrl","normalized","value","prefix","isUnsafeAttributeValue","attributeText","assertNotSymbol","ssrAttribute","resolved","resolveValue","isBoolean","escapeHtml"],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"srcdoc\",\n \"poster\",\n \"data\",\n]);\n\n/**\n * SVG animation attributes (`animate`, `set`): with `attributeName=\"href\"` they write an `href` by animation, so their value\n * is checked like one. `values` is a `;` list and every entry is checked. Same as the client.\n */\nconst ANIMATION_VALUE_ATTRIBUTES: ReadonlySet<string> = new Set([\"values\", \"from\", \"to\", \"by\"]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"draggable\",\n \"spellcheck\",\n \"contenteditable\",\n]);\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only.\n * @internal\n */\nexport const BOOLEAN_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"async\",\n \"autofocus\",\n \"autoplay\",\n \"checked\",\n \"controls\",\n \"default\",\n \"defer\",\n \"disabled\",\n \"formnovalidate\",\n \"hidden\",\n \"inert\",\n \"ismap\",\n \"loop\",\n \"multiple\",\n \"muted\",\n \"nomodule\",\n \"novalidate\",\n \"open\",\n \"playsinline\",\n \"readonly\",\n \"required\",\n \"reversed\",\n \"selected\",\n]);\n\n/** URL prefixes (after normalization) that are never written. Same as the client. */\nconst UNSAFE_URL_PREFIXES: readonly string[] = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/** Throws a TypeError unless `name` can be written as an attribute name. @internal */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) {\n throw invalid(\"INVALID_ATTRIBUTE_NAME\", `\"${name}\" is not a valid attribute name.`);\n }\n}\n\n/** True for `on*` names, which never reach markup. Length matches the client's event test. @internal */\nexport function isEventName(lowerName: string): boolean {\n return lowerName.length > 2 && lowerName.startsWith(\"on\");\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their booleans 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, which browsers ignore inside a URL scheme. */\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, after the normalization browsers apply. @internal */\nexport function isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** True when `lowerName` carries a URL (or an animated one) and `value` would run script. */\nfunction isUnsafeAttributeValue(lowerName: string, value: string): boolean {\n if (URL_ATTRIBUTES.has(lowerName)) return isUnsafeUrl(value);\n return ANIMATION_VALUE_ATTRIBUTES.has(lowerName) && value.split(\";\").some(isUnsafeUrl);\n}\n\n/** Text to write for `value`, or null when the attribute is removed. Same rules as the client. @internal */\nexport function 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/** Refuses symbols, which have no markup form and would otherwise be coerced silently. */\nfunction assertNotSymbol(value: unknown): void {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be an attribute value.\");\n }\n}\n\n/**\n * Renders one attribute as markup with a leading space, or `\"\"` when the attribute is absent: the\n * helper the compiler's server output calls for a dynamic attribute. It applies the client's value\n * rules and URL check, so server and client agree on what is written.\n *\n * - `null`, `undefined` and `false` give `\"\"` (except `false` on `aria-*`, `data-*`, `draggable`,\n * `spellcheck` and `contenteditable`, which is written as `\"false\"`); `true` writes `=\"\"` (or\n * `\"true\"` for those same names). Other values are written as `String(value)`, HTML-escaped.\n * - URL attributes whose value would run script are dropped, with the check of\n * `isUnsafeUrlAttribute` (including the SVG animation attributes `values`, `from`, `to`, `by`).\n * - `on*` names are dropped: event handlers never reach markup.\n * - Accessors are called (untracked) until a plain value remains.\n *\n * @param name Attribute name, matching `[A-Za-z_:][A-Za-z0-9_:.-]*`. It is validated before\n * anything else, so an invalid name always throws.\n * @param value The value, or an accessor of it.\n * @param isBoolean `true` for a presence attribute such as `disabled`: a truthy value writes the bare\n * name, a falsy one writes nothing. Default: `false`.\n * @returns Markup such as `' title=\"a&b\"'`, or `\"\"`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an invalid name, and `UNRECOGNIZED_INSERT_VALUE`\n * when the value is a symbol.\n * @example\n * import { ssrAttribute } from \"@shadow-js/web/server\";\n *\n * ssrAttribute(\"title\", \"Tom & Jerry\"); // ' title=\"Tom & Jerry\"'\n * ssrAttribute(\"disabled\", true, true); // \" disabled\"\n * ssrAttribute(\"href\", \"javascript:alert(1)\"); // \"\"\n * @since 1.0.0\n */\nexport function ssrAttribute(name: string, value: unknown, isBoolean = false): string {\n assertAttributeName(name);\n const lowerName = name.toLowerCase();\n if (isEventName(lowerName)) return \"\";\n const resolved = resolveValue(value);\n assertNotSymbol(resolved);\n if (isBoolean) return resolved ? ` ${name}` : \"\";\n const text = attributeText(lowerName, resolved);\n if (text === null) return \"\";\n if (isUnsafeAttributeValue(lowerName, text)) return \"\";\n return ` ${name}=\"${escapeHtml(text)}\"`;\n}\n"],"mappings":"A,iGAIA,MAAMA,EAAiB,+BAGjBC,kBAAsC,IAAI,IAAI,CAClD,OACA,MACA,SACA,aACA,aACA,SACA,SACA,MACF,CAAC,EAMKC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AC9CA,IAAU,GAAcR,EAAeD,CAAS,EAAI,QAAU,KAC9DS,IAAU,GAAaR,EAAeD,CAAS,EAAI,OAAS,GACzD,OAAOS,CAAK,CACrB,CAGA,SAASI,EAAgB,EAAsB,CAC7C,GAAI,OAAOJ,GAAU,SACnB,MAAMX,EAAQ,4BAA6B,wCAAwC,CAEvF,CA+BA,SAAgBgB,EAAa,EAAc,EAAgB,EAAY,GAAe,CACpFlB,EAAoBC,CAAI,EACxB,IAAMG,EAAYH,EAAK,YAAY,EACnC,GAAIE,EAAYC,CAAS,EAAG,MAAO,GACnC,IAAMe,EAAWC,EAAaP,CAAK,EAEnC,GADAI,EAAgBE,CAAQ,EACpBE,EAAW,OAAOF,EAAW,IAAIlB,IAAS,GAC9C,IAAMQ,EAAOO,EAAcZ,EAAWe,CAAQ,EAG9C,OAFIV,IAAS,MACTM,EAAuBX,EAAWK,CAAI,EAAU,GAC7C,IAAIR,EAAK,IAAIqB,EAAWb,CAAI,EAAE,EACvC,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{cssValueText as e}from"../internal/css-units.js";import{invalid as t}from"./errors.js";import{isSsrNode as n}from"./node.js";import{escapeHtml as r,resolveValue as i}from"./escape.js";const a=/^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;function o(e,n){let r=[[e]],a=[0],o=/* @__PURE__ */ new Set;for(;r.length>0;){let e=r.length-1,s=r[e],c=a[e]??0;if(s===void 0||c>=s.length){let e=r.pop();e!==void 0&&o.delete(e),a.pop();continue}a[e]=c+1;let l=i(s[c]);if(Array.isArray(l)){if(o.has(l))throw TypeError(`A class array contains itself.`);o.add(l),r.push(l),a.push(0)}else if(typeof l==`string`)l!==``&&n.push(l);else if(typeof l==`number`)l!==0&&!Number.isNaN(l)&&n.push(String(l));else if(typeof l==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a class name.`);else if(typeof l==`object`&&l){let e=l;for(let t of Object.keys(e))t!==``&&i(e[t])&&n.push(t)}}}function s(e){let t=i(e);if(typeof t==`string`)return t;if(t==null||t===!1)return``;let n=[];return o(t,n),n.join(` `)}function c(e){let t=s(e);return t===``?``:` class="${r(t)}"`}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(e){let t=``,n=0,r=!1;for(let i of e)if(r)r=!1;else if(i===`\\`)r=!0;else if(t!==``)i===t&&(t=``);else if(i===`"`||i===`'`)t=i;else if(i===`(`)n+=1;else if(i===`)`)n=Math.max(0,n-1);else if((i===`;`||i===`{`||i===`}`)&&n===0)return!1;return t===``&&n===0&&!r}function d(r,o){let s=i(r);if(s!=null&&s!==!1){if(typeof s==`string`)s!==``&&o.push(s);else{if(typeof s!=`object`||n(s))throw t(`UNRECOGNIZED_INSERT_VALUE`,`A style must be a string, an object or an array of them.`);if(Array.isArray(s))for(let e of s){let t=i(e);if(Array.isArray(t))throw TypeError(`ssrStyle(): a style array may not contain another array.`);d(t,o)}else for(let n of Object.keys(s)){let r=l(n);if(!a.test(r))throw t(`INVALID_STYLE_PROPERTY`,`"${n}" is not a valid CSS property name.`);let c=i(Reflect.get(s,n));if(c==null||c===!1)continue;if(typeof c==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a style value.`);let d=e(r,c);u(d)&&o.push(`${r}:${d}`)}}}}function f(e){let t=[];return d(e,t),t.join(`;`)}function p(e){let t=f(e);return t===``?``:` style="${r(t)}"`}export{s as classText,o as collectClasses,u as isSafeCssValue,c as ssrClass,p as ssrStyle,f as styleText,l as toCssProperty};
|
|
2
|
+
//# sourceMappingURL=class-style.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"class-style.js","names":["CSS_PROPERTY","collectClasses","frames","root","cursors","open","top","frame","cursor","done","item","resolveValue","parts","invalid","record","key","classText","resolved","value","ssrClass","text","escapeHtml","toCssProperty","name","kebab","letter","isSafeCssValue","quote","depth","escaped","char","collectDeclarations","source","out","isSsrNode","property","cssValueText","styleText","declarations","ssrStyle"],"sources":["../../../src/server/class-style.ts"],"sourcesContent":["import { cssValueText } from \"../internal/css-units\";\nimport { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\nimport { isSsrNode } from \"./node\";\n\n/** A CSS property name: a custom property, or a lower-case name with an optional vendor dash. */\nconst CSS_PROPERTY = /^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;\n\n/**\n * Appends the class names found in `root` to `parts`, clsx-style. Iterative: array nesting depth\n * is controlled by the caller, so it must not reach the call stack.\n * @internal\n */\nexport function collectClasses(root: unknown, parts: string[]): void {\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const open = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) open.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = resolveValue(frame[cursor]);\n if (Array.isArray(item)) {\n if (open.has(item)) throw new TypeError(\"A class array contains itself.\");\n open.add(item);\n frames.push(item);\n cursors.push(0);\n } else if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (typeof item === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a class name.\");\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (key !== \"\" && resolveValue(record[key])) parts.push(key);\n }\n }\n }\n}\n\n/**\n * The class text for a class value, or \"\" when there is none. A string is used as it is.\n * @internal\n */\nexport function classText(value: unknown): string {\n const resolved = resolveValue(value);\n if (typeof resolved === \"string\") return resolved;\n if (resolved === null || resolved === undefined || resolved === false) return \"\";\n const parts: string[] = [];\n collectClasses(resolved, parts);\n return parts.join(\" \");\n}\n\n/**\n * Renders a `class` attribute from a class value: the helper the compiler's server output calls for\n * `class`, `className` and `classList`, with the same clsx rules as the client's `className`.\n *\n * @param value A string (used as is), or an array or object: non-empty strings, numbers other than\n * `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy. Accessors, also\n * inside arrays and as object values, are called. `null`, `undefined` and `false` give no class.\n * @returns Markup such as `' class=\"a b\"'` (HTML-escaped), or `\"\"` when there are no classes.\n * @throws TypeError when an array contains itself, and `UNRECOGNIZED_INSERT_VALUE` for a symbol.\n * @example\n * import { ssrClass } from \"@shadow-js/web/server\";\n *\n * ssrClass([\"card\", { \"card--active\": true, hidden: false }]); // ' class=\"card card--active\"'\n * ssrClass(null); // \"\"\n * @see ssrStyle\n * @since 1.0.0\n */\nexport function ssrClass(value: unknown): string {\n const text = classText(value);\n return text === \"\" ? \"\" : ` class=\"${escapeHtml(text)}\"`;\n}\n\n/** Converts a camelCase style name to CSS, keeping custom properties; `ms` gets its dash. @internal */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * True when a value cannot end its own declaration. A `;`, `{` or `}` outside quotes and\n * parentheses would start another declaration or rule, so such a value is dropped. Unbalanced\n * quotes or parentheses are dropped too, because they would swallow the declarations after them.\n * @internal\n */\nexport function isSafeCssValue(text: string): boolean {\n let quote = \"\";\n let depth = 0;\n let escaped = false;\n for (const char of text) {\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \"(\") {\n depth += 1;\n } else if (char === \")\") {\n depth = Math.max(0, depth - 1);\n } else if ((char === \";\" || char === \"{\" || char === \"}\") && depth === 0) {\n return false;\n }\n }\n return quote === \"\" && depth === 0 && !escaped;\n}\n\n/** Declarations for one style source, appended to `out` as raw (unescaped) CSS text. */\nfunction collectDeclarations(source: unknown, out: string[]): void {\n const value = resolveValue(source);\n if (value === null || value === undefined || value === false) return;\n if (typeof value === \"string\") {\n if (value !== \"\") out.push(value);\n return;\n }\n if (typeof value !== \"object\" || isSsrNode(value)) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A style must be a string, an object or an array of them.\",\n );\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n throw new TypeError(\"ssrStyle(): a style array may not contain another array.\");\n }\n collectDeclarations(resolved, out);\n }\n return;\n }\n for (const key of Object.keys(value)) {\n const property = toCssProperty(key);\n if (!CSS_PROPERTY.test(property)) {\n throw invalid(\"INVALID_STYLE_PROPERTY\", `\"${key}\" is not a valid CSS property name.`);\n }\n const resolved = resolveValue(Reflect.get(value, key));\n if (resolved === null || resolved === undefined || resolved === false) continue;\n if (typeof resolved === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a style value.\");\n }\n const text = cssValueText(property, resolved);\n if (!isSafeCssValue(text)) continue;\n out.push(`${property}:${text}`);\n }\n}\n\n/**\n * The declarations of a style value, joined with `;`, or \"\" when there are none. Later\n * declarations win in CSS, so earlier and later sources can be combined in order.\n * @internal\n */\nexport function styleText(value: unknown): string {\n const declarations: string[] = [];\n collectDeclarations(value, declarations);\n return declarations.join(\";\");\n}\n\n/**\n * Renders a `style` attribute from a style value: the helper the compiler's server output calls for\n * `style` and `style:` attributes. Sources in an array are written in order, so a later declaration\n * wins in CSS.\n *\n * @param value A string (written as is), an object of properties, or an array of strings and\n * objects (not nested). Object keys are camelCase (converted to kebab-case, `msTransform` gives\n * `-ms-transform`), kebab-case, or custom properties (`--gap`, kept). `null`, `undefined` and `false`\n * values are skipped; a number is in pixels unless it is `0`, the property is unitless (`opacity`,\n * `zIndex`, ...) or a custom property, as in React. A value that could end its own declaration (a\n * `;`, `{` or `}` outside quotes and parentheses, or an unbalanced quote or parenthesis) is dropped.\n * @returns Markup such as `' style=\"color:red\"'` (HTML-escaped), or `\"\"` when there is nothing to\n * write.\n * @throws TypeError `INVALID_STYLE_PROPERTY` for an invalid property name, `UNRECOGNIZED_INSERT_VALUE`\n * for a symbol or a value that is not a string, object or array, and a TypeError for a nested array.\n * @example\n * import { ssrStyle } from \"@shadow-js/web/server\";\n *\n * ssrStyle({ backgroundColor: \"red\", width: 10, \"--gap\": \"4px\" });\n * // ' style=\"background-color:red;width:10px;--gap:4px\"'\n * ssrStyle([{ color: \"red\" }, \"color: blue\"]); // the later declaration wins\n * @see ssrClass\n * @since 1.0.0\n */\nexport function ssrStyle(value: unknown): string {\n const text = styleText(value);\n return text === \"\" ? \"\" : ` style=\"${escapeHtml(text)}\"`;\n}\n"],"mappings":"A,+LAMA,MAAMA,EAAe,yCAOrB,SAAgBC,EAAe,EAAe,EAAuB,CACnE,IAAMC,EAAsB,CAAC,CAACC,CAAI,CAAC,EAC7BC,EAAoB,CAAC,CAAC,EACtBC,kBAAO,IAAI,IACjB,KAAOH,EAAO,OAAS,GAAG,CACxB,IAAMI,EAAMJ,EAAO,OAAS,EACtBK,EAAQL,EAAOI,GACfE,EAASJ,EAAQE,IAAQ,EAC/B,GAAIC,IAAU,IAAA,IAAaC,GAAUD,EAAM,OAAQ,CACjD,IAAME,EAAOP,EAAO,IAAI,EACpBO,IAAS,IAAA,IAAWJ,EAAK,OAAOI,CAAI,EACxCL,EAAQ,IAAI,EACZ,QACF,CACA,EAAQE,GAAOE,EAAS,EACxB,IAAME,EAAOC,EAAaJ,EAAMC,EAAO,EACvC,GAAI,MAAM,QAAQE,CAAI,EAAG,CACvB,GAAIL,EAAK,IAAIK,CAAI,EAAG,MAAU,UAAU,gCAAgC,EACxEL,EAAK,IAAIK,CAAI,EACbR,EAAO,KAAKQ,CAAI,EAChBN,EAAQ,K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EAAoBb,EAAOoB,CAAY,EAChCA,EAAa,KAAK,GAAG,CAC9B,CA0BA,SAAgBC,EAAS,EAAwB,CAC/C,IAAMnB,EAAOiB,EAAUnB,CAAK,EAC5B,OAAOE,IAAS,GAAK,GAAK,WAAWC,EAAWD,CAAI,EAAE,EACxD,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{currentScope as e,enterComponent as t}from"../internal/hydration-scope.js";import{untrack as n}from"@shadow-js/core";import{createOwner as r,runInScope as i}from"@shadow-js/core/extend";function a(n,a){if(typeof n!=`function`)throw TypeError(`createComponent(): the component must be a function.`);return t(()=>{let t=r();return t.idPrefix=e()?.id,i({owner:t,listener:null},()=>n(a))})}function o(e){let t,r=!1;return()=>{if(t!==void 0)return t.value;if(r)throw TypeError(`memo(): the computation read itself.`);r=!0;try{let r=n(e);return t={value:r},r}finally{r=!1}}}export{a as createComponent,o as memo};
|
|
2
|
+
//# sourceMappingURL=component.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"component.js","names":["createComponent","component","enterComponent","owner","createOwner","currentScope","runInScope","props","memo","slot","running","value","untrack","fn"],"sources":["../../../src/server/component.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { createOwner, runInScope } from \"@shadow-js/core/extend\";\nimport { currentScope, enterComponent } from \"../internal/hydration-scope\";\n\n/**\n * Calls a component on the server, untracked, with its own owner and hydration scope, so the\n * hydration keys it hands out depend only on where it sits in the tree. The server twin of the client\n * `createComponent`: compiled server output calls it for `<Component />`, and a hand-written render\n * entry calls it for the root component.\n *\n * @param component The component function.\n * @param props The props object; reactive props are getters.\n * @returns Whatever the component returns.\n * @throws TypeError when `component` is not a function. An error the component throws propagates.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function Card(props: { title: string }) {\n * return <h2>{props.title}</h2>;\n * }\n * const html = renderToString(() => createComponent(Card, { title: \"Hello\" }));\n * @since 1.0.0\n */\nexport function createComponent<P>(component: (props: P) => unknown, props: P): unknown {\n if (typeof component !== \"function\") {\n throw new TypeError(\"createComponent(): the component must be a function.\");\n }\n return enterComponent(() => {\n // The same owner structure as the browser, so `useId` prefixes agree (see the DOM createComponent).\n const owner = createOwner();\n owner.idPrefix = currentScope()?.id;\n // One scope switch (owner in, listener off): deep component trees are bounded by the call stack.\n return runInScope({ owner, listener: null }, () => component(props));\n });\n}\n\n/**\n * The server twin of `memo`: nothing is reactive during a server render, so it computes once, on the\n * first read, and returns the cached value on every later read. A call that throws is not cached\n * (the next read runs `fn` again).\n *\n * @param fn The computation; runs untracked, on the first read.\n * @returns An accessor of the cached value.\n * @throws TypeError from the accessor when `fn` reads the accessor itself while it runs, instead of\n * recursing. An error `fn` throws propagates from the read.\n * @example\n * import { memo } from \"@shadow-js/web/server\";\n *\n * const items = [3, 1, 2];\n * const sorted = memo(() => [...items].sort());\n * sorted(); // [1, 2, 3], computed now\n * sorted(); // the same array, cached\n * @since 1.0.0\n */\nexport function memo<T>(fn: () => T): () => T {\n let slot: { readonly value: T } | undefined;\n let running = false;\n return () => {\n if (slot !== undefined) return slot.value;\n if (running) throw new TypeError(\"memo(): the computation read itself.\");\n running = true;\n try {\n const value = untrack(fn);\n slot = { value };\n return value;\n } finally {\n running = false;\n }\n };\n}\n"],"mappings":"A,iMAuBA,SAAgBA,EAAmB,EAAkC,EAAmB,CACtF,GAAI,OAAOC,GAAc,WACvB,MAAU,UAAU,sDAAsD,EAE5E,OAAOC,MAAqB,CAE1B,IAAMC,EAAQC,EAAY,EAG1B,MAFA,GAAM,SAAWC,EAAa,CAAC,EAAE,GAE1BC,EAAW,CAAE,QAAO,SAAU,IAAK,MAASL,EAAUM,CAAK,CAAC,CACrE,CAAC,CACH,CAoBA,SAAgBC,EAAQ,EAAsB,CAC5C,IAAIC,EACAC,EAAU,GACd,UAAa,CACX,GAAID,IAAS,IAAA,GAAW,OAAOA,EAAK,MACpC,GAAIC,EAAS,MAAU,UAAU,sCAAsC,EACvE,EAAU,GACV,GAAI,CACF,IAAMC,EAAQC,EAAQC,CAAE,EAExB,MADA,GAAO,CAAE,OAAM,EACRF,CACT,QAAU,CACR,EAAU,EACZ,CACF,CACF,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"derived.js","names":["derived","current","compute","read","args"],"sources":["../../../src/server/derived.ts"],"sourcesContent":["/**\n * The server twin of the client `Derived`: what {@link derived} returns. Nothing is reactive on the\n * server, so it holds the value computed once. Read it as `x.value` or call it as `x()`.\n *\n * @example\n * import { derived } from \"@shadow-js/web/server\";\n *\n * const total = derived(() => 20 * 3);\n * total.value; // 60\n * total(); // 60\n * @see derived\n * @since 1.0.0\n */\nexport interface Derived<T> {\n /**\n * Returns the value. When the value is a function, calls it with `args` and returns its result\n * instead, so a derived function stays callable.\n */\n (...args: unknown[]): unknown;\n /** The value `compute` returned. */\n readonly value: T;\n}\n\n/**\n * The server twin of the client `derived`, which the compiler emits for `const x = <expression\n * reading signals>` inside a component. On the server it calls `compute` once, immediately, and\n * returns a constant {@link Derived}.\n *\n * @param compute The computation. Runs once, when `derived` is called; an error it throws propagates.\n * @returns A {@link Derived} holding the result.\n * @example\n * import { derived } from \"@shadow-js/web/server\";\n *\n * const greeting = derived(() => (name: string) => `Hello, ${name}`);\n * greeting(\"Ada\"); // \"Hello, Ada\": a derived function stays callable\n * @see Derived\n * @since 1.0.0\n */\nexport function derived<T>(compute: () => T): Derived<T> {\n const current = compute();\n const read = ((...args: unknown[]): unknown =>\n typeof current === \"function\"\n ? (current as (...a: unknown[]) => unknown)(...args)\n : current) as {\n (...args: unknown[]): unknown;\n value: T;\n };\n Object.defineProperty(read, \"value\", { value: current });\n return read as Derived<T>;\n}\n"],"mappings":"AAsCA,SAAgBA,EAAW,EAA8B,CACvD,IAAMC,EAAUC,EAAQ,EAClBC,IAAS,GAAGC,IAChB,OAAOH,GAAY,WACdA,EAAyC,GAAGG,CAAI,EACjDH,GAKN,OADA,OAAO,eAAeE,EAAM,QAAS,CAAE,MAAOF,CAAQ,CAAC,EAChDE,CACT,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n}from"../internal/react-names.js";import{invalid as r}from"./errors.js";import{SsrNode as i,isSsrNode as a}from"./node.js";import{escape as o,escapeHtml as s,resolveValue as c}from"./escape.js";import{BOOLEAN_ATTRIBUTES as l,isEventName as u,ssrAttribute as d}from"./attributes.js";import{classText as f,ssrStyle as p,styleText as m}from"./class-style.js";import{markSelectedOptions as h,textareaContent as g}from"./form-controls.js";const _=/^[A-Za-z][A-Za-z0-9-]*$/,v=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`command`,`embed`,`hr`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),y=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`,`children`,`ref`]);function b(e){if(typeof e==`object`&&e)return Reflect.get(e,`__html`)}function x(e,...t){if(!Array.isArray(e)||e.length!==t.length+1)throw TypeError(`ssr(): parts must have one more entry than there are holes.`);let n=e[0]??``;for(let r=0;r<t.length;r+=1){let i=t[r];if(typeof i==`string`)n+=i;else if(a(i))n+=i.t;else throw TypeError(`ssr(): a hole must be an escaped string or an SsrNode.`);n+=e[r+1]??``}return new i(n)}function S(e){if(typeof e!=`string`)throw TypeError(`ssrRaw(): the markup must be a string.`);return new i(e)}function C(){let t=e();return t===void 0?``:` data-hk="${s(t)}"`}function w(e,a,x=void 0,S=!1,w=!1){if(typeof e!=`string`||!_.test(e))throw r(`INVALID_TAG_NAME`,`"${String(e)}" is not a valid tag name.`);let O=e.toLowerCase(),k=O===`select`,A=O===`textarea`,j={},M=!1,N=!1,P=S?C():``,F=[],I=``,L;if(typeof a==`object`&&a)for(let e of Object.keys(a)){if(y.has(e)||t.has(e)||e===`ref`||e.startsWith(`on:`)||e.startsWith(`use:`)||e.startsWith(`prop:`)||u(e)||S&&e===`data-hk`)continue;let r=c(Reflect.get(a,e));if(e===`class`||e===`className`){let e=f(r);e!==``&&F.push(e)}else if(e===`classList`)E(r,F);else if(e===`style`)I=m(r);else if(e===`innerHTML`)L=D(r);else if(e===`dangerouslySetInnerHTML`)L=D(c(b(r)));else if((k||A)&&e===`value`)j.value=r,M=!0;else if((k||A)&&e===`defaultValue`)j.fallback=r,N=!0;else if(e.startsWith(`attr:`))P+=d(e.slice(5),r);else if(e.startsWith(`bool:`))P+=d(e.slice(5),r,!0);else if(e===`defaultValue`||e===`defaultChecked`){let t=e===`defaultValue`?`value`:`checked`;Object.hasOwn(a,t)||(P+=d(t,r,t===`checked`))}else{let t=n(e,w);P+=d(t,r,l.has(t))}}if(F.length>0&&(P+=` class="${s(F.join(` `))}"`),I!==``&&(P+=p(I)),v.has(O))return new i(`<${e}${P}>`);let R=L===void 0?o(x===void 0?T(a):x):L;if(L===void 0&&(M||N)){let e=M?j.value:j.fallback;R=A?g(e):h(e,R)}return new i(`<${e}${P}>${R}</${e}>`)}function T(e){if(typeof e==`object`&&e)return Reflect.get(e,`children`)}function E(e,t){if(typeof e==`object`&&e&&!Array.isArray(e))for(let n of Object.keys(e))n!==``&&c(Reflect.get(e,n))&&t.push(n)}function D(e){if(e==null)return``;if(a(e))return e.t;if(typeof e==`symbol`)throw r(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be innerHTML.`);return String(e)}export{x as ssr,w as ssrElement,C as ssrHydrationKey,S as ssrRaw};
|
|
2
|
+
//# sourceMappingURL=element.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"element.js","names":["TAG_NAME","VOID_ELEMENTS","SKIPPED_KEYS","innerHtmlOfValue","value","ssr","holes","parts","html","index","hole","isSsrNode","SsrNode","ssrRaw","ssrHydrationKey","key","nextKey","escapeHtml","ssrElement","tag","invalid","lowerTag","isSelect","isTextarea","control","hasValue","hasFallback","attributes","needsKey","classes","style","innerHtml","props","IGNORED_KEYS","isEventName","resolveValue","text","classText","collectTruthyKeys","styleText","plainHtml","ssrAttribute","name","attributeName","svg","BOOLEAN_ATTRIBUTES","ssrStyle","content","escape","children","propsChildren","textareaContent","markSelectedOptions","out"],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS } from \"../internal/react-names\";\nimport { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, <Ada></p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"<b>escaped</b><!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n attributes += ssrAttribute(name, value, BOOLEAN_ATTRIBUTES.has(name));\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n let content =\n innerHtml !== undefined\n ? innerHtml\n : escape(children === undefined ? propsChildren(props) : children);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":"A,shBAWA,M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C,GAAIpC,GAAU,KAA6B,MAAO,GAClD,GAAIO,EAAUP,CAAK,EAAG,OAAOA,EAAM,EACnC,GAAI,OAAOA,GAAU,SACnB,MAAMgB,EAAQ,4BAA6B,+BAA+B,EAC5E,OAAO,OAAOhB,CAAK,CACrB,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":["SsrError","code","invalid"],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n"],"mappings":"AAQA,IAAaA,EAAb,cAA8B,KAAM,CAClC,KACA,YAAY,EAAoB,EAAgB,CAC9C,MAA+C,UAAUC,GAAM,EAC/D,KAAK,KAAO,WACZ,KAAK,KAAOA,CACd,CACF,EAOA,SAAgBC,EAAQ,EAAc,EAA2B,CAC/D,MAAO,gBAAI,UAAmD,UAAUD,GAAM,CAChF,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{invalid as e}from"./errors.js";import{isSsrNode as t}from"./node.js";import{untrack as n}from"@shadow-js/core";const r={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},i=/[&<>"']/g;function a(e){return e.replace(i,e=>r[e]??e)}function o(e){let t=e;for(let e=0;typeof t==`function`;e+=1){if(e>=1e3)throw TypeError(`An accessor returns accessors more than 1000 levels deep.`);t=n(t)}return t}function s(n,r){if(n!=null&&typeof n!=`boolean`){if(typeof n==`string`)r.push(a(n));else if(typeof n==`number`||typeof n==`bigint`)r.push(String(n));else{if(typeof n==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be rendered.`);t(n)?r.push(n.t):typeof n!=`object`&&r.push(a(String(n)))}}}function c(e){let t=[],n=[],r=[],i=/* @__PURE__ */ new Set,a=e;for(;;){let e=o(a);if(Array.isArray(e)){if(i.has(e))throw TypeError(`escape(): an array contains itself.`);i.add(e),n.push(e),r.push(0)}else s(e,t);let c,l=!1;for(;!l&&n.length>0;){let e=n.length-1,t=n[e],a=r[e]??0;if(t===void 0)break;a<t.length?(r[e]=a+1,c=t[a],l=!0):(n.pop(),r.pop(),i.delete(t))}if(!l)return t.join(``);a=c}}export{c as escape,a as escapeHtml,o as resolveValue};
|
|
2
|
+
//# sourceMappingURL=escape.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"escape.js","names":["accessor","HTML_ESCAPES","HTML_SPECIAL","escapeHtml","text","char","resolveValue","current","value","layer","untrack","appendLeaf","out","invalid","isSsrNode","escape","frames","cursors","open","item","resolved","next","found","top","frame","cursor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array. */\nfunction appendLeaf(value: unknown, out: string[]): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(escapeHtml(value));\n return;\n }\n // Numbers and bigints never contain markup characters.\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n out.push(String(value));\n return;\n }\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be rendered.\");\n }\n if (isSsrNode(value)) {\n out.push(value.t);\n return;\n }\n // Any other object is not trusted markup. Dev fails loudly; production renders nothing.\n if (typeof value === \"object\") {\n if (__DEV__) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.\",\n );\n }\n return;\n }\n out.push(escapeHtml(String(value)));\n}\n\n/**\n * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls\n * for every dynamic child, and what the renderers call on the app's result.\n *\n * - Strings are escaped (`& < > \" '`); numbers and bigints are written as they are; `null`,\n * `undefined` and booleans render nothing.\n * - `SsrNode` values (from `ssr`, `ssrRaw` and the other helpers) pass through unchanged: they were\n * escaped when they were built.\n * - Accessors are called (untracked) and their result is rendered; a chain of more than 1000\n * accessors returning accessors throws.\n * - Arrays are flattened in order, with an explicit stack, so nesting depth is not limited by the\n * call stack.\n * - Plain objects throw in development builds and render nothing in production builds.\n *\n * @param value The value to render.\n * @returns The escaped markup.\n * @throws TypeError when an array contains itself, for a symbol (`UNRECOGNIZED_INSERT_VALUE`), for an\n * object that is not an `SsrNode` (`UNRECOGNIZED_INSERT_VALUE`, development builds only), and for an\n * accessor chain deeper than 1000.\n * @example\n * import { escape } from \"@shadow-js/web/server\";\n *\n * const name = () => \"<Ada>\";\n * escape([\"Hello, \", name, null, 3]); // \"Hello, <Ada>3\"\n * @since 1.0.0\n */\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nexport function escape(value: unknown): string {\n const out: string[] = [];\n const frames: unknown[][] = [];\n const cursors: number[] = [];\n const open = new Set<unknown[]>();\n let item: unknown = value;\n for (;;) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n if (open.has(resolved)) throw new TypeError(\"escape(): an array contains itself.\");\n open.add(resolved);\n frames.push(resolved);\n cursors.push(0);\n } else {\n appendLeaf(resolved, out);\n }\n // Find the next item, closing every array that has no items left.\n let next: unknown;\n let found = false;\n while (!found && frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined) break;\n if (cursor < frame.length) {\n cursors[top] = cursor + 1;\n next = frame[cursor];\n found = true;\n } else {\n frames.pop();\n cursors.pop();\n open.delete(frame);\n }\n }\n if (!found) return out.join(\"\");\n item = next;\n }\n}\n"],"mappings":"A,sHAIA,MAAMC,EAAiD,CACrD,IAAK,QACL,IAAK,OACL,IAAK,OACL,IAAK,SACL,IAAK,OACP,EAEMC,EAAe,WAUrB,SAAgBC,EAAW,EAAsB,CAC/C,OAAOC,EAAK,QAAQF,EAAe,GAASD,EAAaI,IAASA,CAAI,CACxE,CAOA,SAAgBC,EAAa,EAAyB,CACpD,IAAIC,EAAUC,EACd,IAAK,IAAIC,EAAQ,EAAG,OAAOF,GAAY,WAAY,GAAS,EAAG,CAC7D,GAAIE,GAA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EAErB,CACA,GAAI,CAACF,EAAO,OAAOV,EAAI,KAAK,EAAE,EAC9B,EAAOS,CACT,CACF,C"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{invalid as e}from"./errors.js";import{SsrNode as t}from"./node.js";import{escape as n,escapeHtml as r,resolveValue as i}from"./escape.js";function a(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a form control value.`);return t==null?``:String(t)}function o(e){let t=r(a(i(e))),n=t.charAt(0);return n===`
|
|
2
|
+
`||n===`\r`?`\n${t}`:t}function s(e){return new t(o(e))}function c(e){let t=i(e);if(!Array.isArray(t))return{values:/* @__PURE__ */ new Set([a(t)]),many:!1};let n=/* @__PURE__ */ new Set;for(let e of t){let t=i(e);t!=null&&n.add(a(t))}return{values:n,many:!0}}const l=/[ \t\n\f\r]+/g,u=/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi,d={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`},f=/<!--[\s\S]*?-->|<[^>]*>/g;function p(e){return e.replace(u,(e,t,n,r)=>{if(r!==void 0)return d[r.toLowerCase()]??e;let i=t===void 0?Number.parseInt(n??``,16):Number(t);return Number.isInteger(i)&&i>=0&&i<=1114111&&!(i>=55296&&i<=57343)?String.fromCodePoint(i):e})}function m(e,t){let n=``;for(let r=t;r<e.length;r+=1){let t=e.charAt(r);if(n!==``)t===n&&(n=``);else if(t===`"`||t===`'`)n=t;else if(t===`>`)return r}return-1}function h(e,t,n){n.lastIndex=t;let r=n.exec(e);return p(e.slice(t,r===null?e.length:r.index).replace(f,``)).replace(l,` `).trim()}function g(e,t){let n=``,r=0,i=0,a=!1,o=/* @__PURE__ */ RegExp(`\\s+([^\\s"'<>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+)))?`,`g`),s=/* @__PURE__ */ RegExp(`<\\/?(?:option|optgroup)(?=[\\s/>])`,`gi`);for(;;){let c=e.indexOf(`<option`,i);if(c===-1)break;let l=c+7;if(i=l,!/[\s/>]/.test(e.charAt(l)))continue;let u=m(e,l);if(u===-1)break;let d=e.slice(l,u),f,g=-1,_=-1;o.lastIndex=0;for(let e=o.exec(d);e!==null;e=o.exec(d)){let t=(e[1]??``).toLowerCase();t===`selected`?(g=e.index,_=e.index+e[0].length):t===`value`&&f===void 0&&(f=p(e[2]??e[3]??e[4]??``))}let v=(t.many||!a)&&t.values.has(f??h(e,u+1,s));if(v&&(a=!0),v&&g===-1){let t=d.endsWith(`/`)?d.length-1:d.length;n+=`${e.slice(r,l+t)} selected`,r=l+t}else!v&&g!==-1&&(n+=e.slice(r,l+g),r=l+_);i=u}return r===0?e:n+e.slice(r)}function _(e,r){return new t(v(e,n(r)))}function v(e,t){return g(t,c(e))}export{v as markSelectedOptions,_ as ssrSelectValue,s as ssrTextArea,o as textareaContent};
|
|
3
|
+
//# sourceMappingURL=form-controls.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form-controls.js","names":["valueText","value","invalid","textareaContent","html","escapeHtml","resolveValue","first","ssrTextArea","SsrNode","wantedValues","resolved","values","item","one","WHITESPACE","ENTITY","NAMED_ENTITIES","TAGS","decodeEntities","text","named","whole","code","decimal","hex","tagEnd","quote","index","from","char","optionText","boundary","boundaries","markOptions","out","copied","at","found","attribute","start","attributesFrom","end","source","selectedAt","selectedEnd","match","name","matches","wanted","slash","ssrSelectValue","markSelectedOptions","escape","children"],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n const html = escapeHtml(valueText(resolveValue(value)));\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves <b>tags</b></textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and ` ` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":"A,iJAaA,SAASA,EAAU,EAAwB,CACzC,GAAI,OAAOC,GAAU,SACnB,MAAMC,EAAQ,4BAA6B,0CAA0C,EAEvF,OAAOD,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAOA,SAAgBE,EAAgB,EAAwB,CACtD,IAAMC,EAAOC,EAAWL,EAAUM,EAAaL,CAAK,CAAC,CAAC,EAChDM,EAAQH,EAAK,OAAO,CAAC,EAC3B,OAAOG,I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AAM,EAAE,EAEjE,CAEA,IAAME,GACHC,EAAO,MAAQ,CAACX,IAAUW,EAAO,OAAO,IAAIhD,GAAS8B,EAAW3B,EAAMsC,EAAM,EAAGT,CAAU,CAAC,EAE7F,GADIe,IAAS,EAAQ,IACjBA,GAAWJ,IAAe,GAAI,CAChC,IAAMM,EAAQP,EAAO,SAAS,GAAG,EAAIA,EAAO,OAAS,EAAIA,EAAO,OAChE,GAAO,GAAGvC,EAAK,MAAMgC,EAAQK,EAAiBS,CAAK,EAAE,WACrD,EAAST,EAAiBS,CAC5B,KAAW,CAACF,GAAWJ,IAAe,KACpC,GAAOxC,EAAK,MAAMgC,EAAQK,EAAiBG,CAAU,EACrD,EAASH,EAAiBI,GAE5B,EAAKH,CACP,CACA,OAAON,IAAW,EAAIhC,EAAO+B,EAAM/B,EAAK,MAAMgC,CAAM,CACtD,CA2BA,SAAgBe,EAAe,EAAgB,EAA4B,CACzE,OAAO,IAAI1C,EAAQ2C,EAAoBnD,EAAOoD,EAAOC,CAAQ,CAAC,CAAC,CACjE,CAGA,SAAgBF,EAAoB,EAAgB,EAAsB,CACxE,OAAOlB,EAAY9B,EAAMM,EAAaT,CAAK,CAAC,CAC9C,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ssrRaw as e}from"./element.js";import{DEFAULT_EARLY_EVENTS as t,captureScriptBody as n}from"../internal/early-events.js";const r=/^[A-Za-z0-9+/=_-]+$/;function i(e={}){let i=e.nonce,a=i!==void 0&&r.test(i)?` nonce="${i}"`:``,o=e.eventNames??t;return`<script${a}>${n(o)}<\/script>`}function a(t={}){return e(i(t))}export{a as HydrationScript,i as generateHydrationScript};
|
|
2
|
+
//# sourceMappingURL=hydration-script.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hydration-script.js","names":["NONCE","generateHydrationScript","nonce","options","attribute","names","DEFAULT_EARLY_EVENTS","captureScriptBody","HydrationScript","ssrRaw","props"],"sources":["../../../src/server/hydration-script.ts"],"sourcesContent":["import { captureScriptBody, DEFAULT_EARLY_EVENTS } from \"../internal/early-events\";\nimport { ssrRaw } from \"./element\";\n\n/**\n * Options of {@link generateHydrationScript} and {@link HydrationScript}.\n * @since 1.0.0\n */\nexport interface HydrationScriptOptions {\n /**\n * CSP nonce for the script. It is written only when it is a plain token (letters, digits, `+`, `/`,\n * `=`, `_`, `-`); any other value is ignored and the script gets no nonce.\n * @default undefined (no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Event types to capture before hydration. Only plain lower-case names (`[a-z]+`) are kept; others\n * are skipped.\n * @default [\"click\", \"input\"]\n */\n readonly eventNames?: readonly string[];\n}\n\nconst NONCE = /^[A-Za-z0-9+/=_-]+$/;\n\n/**\n * Returns the inline `<script>` that records the events a user makes before the app has hydrated, so\n * `hydrate()` can replay them once its handlers are attached (a click made while the bundle loads is\n * not lost). Put it in the `<head>` of the server-rendered page, before the bundle.\n *\n * @param options The CSP nonce and the event types to capture. Undefined uses the defaults of\n * {@link HydrationScriptOptions}.\n * @returns The script element as a string of markup.\n * @example\n * import { generateHydrationScript, renderToString } from \"@shadow-js/web/server\";\n *\n * function page(app: () => unknown, nonce: string): string {\n * const body = renderToString(app);\n * return `<html><head>${generateHydrationScript({ nonce })}</head><body>${body}</body></html>`;\n * }\n * @see HydrationScript\n * @since 1.0.0\n */\nexport function generateHydrationScript(options: HydrationScriptOptions = {}): string {\n const nonce = options.nonce;\n const attribute = nonce !== undefined && NONCE.test(nonce) ? ` nonce=\"${nonce}\"` : \"\";\n const names = options.eventNames ?? DEFAULT_EARLY_EVENTS;\n return `<script${attribute}>${captureScriptBody(names)}</script>`;\n}\n\n/**\n * {@link generateHydrationScript} as a component, for a document rendered with server JSX:\n * `<HydrationScript nonce={nonce} />` in the `<head>`.\n *\n * @param props The CSP nonce and the event types to capture. Undefined uses the defaults of\n * {@link HydrationScriptOptions}.\n * @returns The script as trusted raw markup.\n * @example\n * import { createComponent, HydrationScript, renderToString } from \"@shadow-js/web/server\";\n *\n * function Document() {\n * return (\n * <html>\n * <head>\n * <HydrationScript nonce=\"r4nd0m\" />\n * </head>\n * <body>Hello</body>\n * </html>\n * );\n * }\n * const html = renderToString(() => createComponent(Document, {}));\n * @see generateHydrationScript\n * @since 1.0.0\n */\nexport function HydrationScript(props: HydrationScriptOptions = {}): unknown {\n return ssrRaw(generateHydrationScript(props));\n}\n"],"mappings":"A,gIAsBA,MAAMA,EAAQ,sBAoBd,SAAgBC,EAAwB,EAAkC,CAAC,EAAW,CACpF,IAAMC,EAAQC,EAAQ,MAChBC,EAAYF,IAAU,IAAA,IAAaF,EAAM,KAAKE,CAAK,EAAI,WAAWA,EAAM,GAAK,GAC7EG,EAAQF,EAAQ,YAAcG,EACpC,MAAO,UAAUF,EAAU,GAAGG,EAAkBF,CAAK,EAAE,WACzD,CA0BA,SAAgBG,EAAgB,EAAgC,CAAC,EAAY,CAC3E,OAAOC,EAAOR,EAAwBS,CAAK,CAAC,CAC9C,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{escape as e}from"./escape.js";import{ssrAttribute as t}from"./attributes.js";import{ssrClass as n,ssrStyle as r}from"./class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./form-controls.js";import{ssr as o,ssrElement as s,ssrHydrationKey as c,ssrRaw as l}from"./element.js";import{createServerPortals as u}from"./portals.js";import{normalizeTags as d}from"../head/validate.js";import{createServerHead as f}from"../head/server-head.js";import{createComponent as p,memo as m}from"./component.js";import{derived as h}from"./derived.js";import{HydrationScript as g,generateHydrationScript as _}from"./hydration-script.js";import{renderToString as v,renderToStringAsync as y}from"./render.js";import{deserialize as b,serialize as x}from"./serialize.js";import{renderToStream as S}from"./stream.js";import{mergeProps as C}from"@shadow-js/core";export{g as HydrationScript,p as createComponent,f as createServerHead,u as createServerPortals,h as derived,b as deserialize,e as escape,_ as generateHydrationScript,m as memo,C as mergeProps,d as normalizeTags,S as renderToStream,v as renderToString,y as renderToStringAsync,x as serialize,o as ssr,t as ssrAttribute,n as ssrClass,s as ssrElement,c as ssrHydrationKey,l as ssrRaw,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","names":["SsrNode","t","isSsrNode","value"],"sources":["../../../src/server/node.ts"],"sourcesContent":["/**\n * Markup that is already safe to insert: the only value `escape` writes without encoding.\n * A class instance, not a `{ t }` shape, so a plain object parsed from user input can never be\n * mistaken for trusted markup.\n * @internal\n */\nexport class SsrNode {\n readonly t: string;\n constructor(t: string) {\n this.t = t;\n }\n}\n\n/** True for values created by the server helpers. @internal */\nexport function isSsrNode(value: unknown): value is SsrNode {\n return value instanceof SsrNode;\n}\n"],"mappings":"AAMA,IAAaA,EAAb,KAAqB,CACnB,EACA,YAAY,EAAW,CACrB,KAAK,EAAIC,CACX,CACF,EAGA,SAAgBC,EAAU,EAAkC,CAC1D,OAAOC,aAAiBH,CAC1B,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{SsrError as n}from"./errors.js";import{escape as r}from"./escape.js";import{PortalContext as i}from"../internal/portal-context.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new n(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,i,a){if(a===null||n===void 0)return;let o=t(e(n),()=>r(i()));a.add(n,o)}function u(e,t){return i({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
|
|
2
|
+
//# sourceMappingURL=portals.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"portals.js","names":["PortalCollector","key","SsrError","html","out","collectors","createServerPortals","collector","portals","collectorOf","renderServerPortal","sink","withScope","childScope","escape","children","withPortalSink","PortalContext","build","portalCollectorFor"],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":"A,qNAuCA,IAAaA,EAAb,KAAmD,CACjD,wBAA2B,IAAI,IAE/B,IAAI,EAAa,EAAoB,CACnC,GAAI,CAAC,KAAK,QAAQ,IAAIC,CAAG,GAAK,KAAK,QAAQ,MAAA,IACzC,MAAM,IAAIC,EACR,mBACA,kFACF,EAEF,KAAK,QAAQ,IAAID,EAAKE,CAAI,CAC5B,CAGA,OAAc,CACZ,KAAK,QAAQ,MAAM,CACrB,CAEA,MAAe,CACb,IAAIC,EAAM,GACV,IAAK,GAAM,CAACH,EAAKE,KAAS,KAAK,QAC7B,GAAO,cAAcF,EAAI,KAAKE,EAAK,cAAcF,EAAI,KAEvD,OAAOG,CACT,CACF,EAEA,MAAMC,kBAAa,IAAI,QAmBvB,SAAgBC,GAAqC,CACnD,IAAMC,EAAY,IAAIP,EAChBQ,EAAyB,CAAE,SAAYD,EAAU,KAAK,CAAE,EAE9D,OADAF,EAAW,IAAIG,EAASD,CAAS,EAC1BC,CACT,CAOA,SAAgBC,EAAY,EAAyC,CACnE,IAAMF,EAAYF,EAAW,IAAIG,CAAO,EACxC,GAAID,IAAc,IAAA,GAChB,MAAU,UAAU,qDAAqD,EAE3E,OAAOA,CACT,CAaA,SAAgBG,EACd,EACA,EACA,EACM,CACN,GAAIC,IAAS,MAAQV,IAAQ,IAAA,GAAW,OACxC,IAAME,EAAOS,EAAUC,EAAWZ,CAAG,MAASa,EAAOC,EAAS,CAAC,CAAC,EAChEJ,EAAK,IAAIV,EAAKE,CAAI,CACpB,CAOA,SAAgBa,EAAkB,EAAyB,EAAmB,CAO5E,OANaC,EAAc,CACzB,MAAON,EACP,IAAI,UAAW,CACb,OAAOO,EAAM,CACf,CACF,CACW,CAAC,CAAa,CAC3B,CAOA,SAAgBC,EAAmB,EAA4D,CAC7F,GAAIX,IAAY,IAAA,GAAW,OAAO,KAClC,IAAMD,EAAYE,EAAYD,CAAO,EAErC,OADAD,EAAU,MAAM,EACTA,CACT,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{SsrError as r}from"./errors.js";import{escape as i}from"./escape.js";import{attachRootErrors as a}from"../control-flow/root-errors.js";import{portalCollectorFor as o,withPortalSink as s}from"./portals.js";import{runWithServerHead as c}from"../head/server-head.js";import{ResourceCacheContext as l,createRoot as u}from"@shadow-js/core";const d=/^[A-Za-z0-9_-]+$/;function f(e){if(typeof e!=`string`||!d.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function p(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function m(t,r,o,u,d,f){return a(f),s(d,()=>l({value:o,get children(){return c(u,()=>n(e(r),()=>i(t())))}}))()}function h(e,t){let n=f(t?.renderId??`0`),r=o(t?.portals),i=p(t);return u(a=>{try{return m(e,n,null,t?.head,r,i)}finally{a()}})}function g(e,n,r,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},d={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let n=t(e);return s.add(n),n},read:e=>r.has(e)?{value:r.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return u(t=>(i?.clear(),a?.clear(),{html:m(e,n,p,i,a,d),requested:s,tracked:c,errors:l,dispose:t}))}function _(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function v(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function y(e,t){let n={};for(let r of e)t.has(r)&&v(n,r,t.get(r));return n}function b(e){if(e.canceled)throw new r(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function x(e,t,n,i,a,o,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){b(i);let u=g(e,t,c,a,o,s);if(i.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),_(u.errors,s),{html:u.html,data:y(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));b(i);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return _(u.errors,s),{html:u.html,data:y(u.requested,c)};if(l>=n)throw new r(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function S(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function C(e,t){let n=f(t?.renderId??`0`),{timeoutMs:i,maxPasses:a}=S(t),s={canceled:!1,roots:[]},c,l=new Promise((e,t)=>{c=setTimeout(()=>{s.canceled=!0,t(new r(`SSR_TIMEOUT`,`The render did not finish within ${i} ms.`))},i)});try{let r=o(t?.portals);return await Promise.race([x(e,n,a,s,t?.head,r,p(t)),l])}finally{clearTimeout(c),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{h as renderToString,C as renderToStringAsync};
|
|
2
|
+
//# sourceMappingURL=render.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render.js","names":["RENDER_ID","checkRenderId","renderId","reportersOf","options","renderMarkup","attachRootErrors","reporters","withPortalSink","portals","ResourceCacheContext","cache","runWithServerHead","head","withScope","createRootScope","escape","code","renderToString","portalCollectorFor","createRoot","dispose","runPass","requested","tracked","errors","error","user","seen","key","resourceKey","explicit","settled","reportPass","defineData","target","collectData","data","assertActive","job","SsrError","runPasses","pass","current","results","entry","advanced","index","result","maxPasses","checkAsyncOptions","timeoutMs","renderToStringAsync","timer","expired","reject"],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } 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 { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\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 render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\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 return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\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 if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n }, timeoutMs);\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":"A,ubAuFA,MAEMA,EAAY,mBAGlB,SAASC,EAAc,EAA0B,CAC/C,GAAI,OAAOC,GAAa,UAAY,CAACF,EAAU,KAAKE,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,OAAOA,CACT,CAMA,SAASC,EAAY,EAAsD,CACzE,MAAO,CACL,GAAIC,GAAS,gBAAkB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAeA,EAAQ,aAAc,EACvF,GAAIA,GAAS,kBAAoB,IAAA,GAAY,CAAC,EAAI,CAAE,gBAAiBA,EAAQ,eAAgB,CAC/F,CACF,CAOA,SAASC,EACP,EACA,EACA,EACA,EACA,EACA,EACQ,CAGR,OAFAC,EAAiBC,CAAS,EAGxBC,EAAeC,MACbC,EAAqB,CACnB,MAAOC,EACP,IAAI,UAAW,CACb,OAAOC,EAAkBC,MACvBC,EAAUC,EAAgBb,CAAQ,MAASc,EAAOC,EAAK,CAAC,CAAC,CAC3D,CACF,CACF,CAAC,CACH,CAAC,CACD,CACJ,CA0BA,SAAgBC,EAAe,EAAqB,EAAiC,CACnF,IAAMhB,EAAWD,EAAcG,GAAS,UAAY,GAAG,EACjDK,EAAUU,EAAmBf,GAAS,OAAO,EAC7CG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ace(t,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function r(e){return Number.isFinite(e)&&!Object.is(e,-0)?e:{$:`num`,v:Object.is(e,-0)?`-0`:String(e)}}const i=/* @__PURE__ */ new Map([[`Int8Array`,Int8Array],[`Uint8Array`,Uint8Array],[`Uint8ClampedArray`,Uint8ClampedArray],[`Int16Array`,Int16Array],[`Uint16Array`,Uint16Array],[`Int32Array`,Int32Array],[`Uint32Array`,Uint32Array],[`Float32Array`,Float32Array],[`Float64Array`,Float64Array],[`BigInt64Array`,BigInt64Array],[`BigUint64Array`,BigUint64Array],[`DataView`,DataView]]);function a(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function o(e){let t;try{t=atob(e)}catch{throw f(`binary data is not valid base64.`)}let n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function s(e){for(let[t,n]of i)if(e instanceof n)return t}function c(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(t){let i=[],o=/* @__PURE__ */ new Map,l=[],u=e=>{let t=o.get(e);if(t!==void 0)return t;let n=i.length;return i.push(null),o.set(e,n),l.push({value:e,slot:n}),n},d=t=>{if(t===void 0)return{$:`u`};if(t===null||typeof t==`boolean`||typeof t==`string`)return t;if(typeof t==`number`)return r(t);if(typeof t==`bigint`)return{$:`big`,v:t.toString()};if(typeof t==`object`)return{$:`ref`,i:u(t)};throw e(`UNSERIALIZABLE_VALUE`,`A ${typeof t} cannot be serialized.`)},f=t=>{if(t instanceof Date)return{$:`date`,v:d(t.getTime())};if(t instanceof ArrayBuffer)return{$:`buf`,v:a(new Uint8Array(t))};if(ArrayBuffer.isView(t)){let e=s(t);if(e!==void 0)return{$:`bin`,k:e,v:a(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}}if(t instanceof URL)return{$:`url`,v:t.href};if(t instanceof Map){let e=[];for(let[n,r]of t)e.push([d(n),d(r)]);return{$:`map`,e}}if(t instanceof Set){let e=[];for(let n of t)e.push(d(n));return{$:`set`,e}}if(Array.isArray(t)){let e=[];for(let n=0;n<t.length;n+=1)e.push(d(t[n]));return{$:`arr`,e}}if(!c(t))throw e(`UNSERIALIZABLE_VALUE`,`Only plain objects, arrays, Map, Set, Date, URL, ArrayBuffer and typed arrays can be serialized.`);let n=[];for(let e of Object.keys(t))n.push([e,d(Reflect.get(t,e))]);return{$:`obj`,e:n}},p=d(t);for(let e=0;e<l.length;e+=1){let t=l[e];if(t===void 0)break;i[t.slot]=f(t.value)}return n(JSON.stringify({r:p,t:i}))}function u(e,t){return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function d(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function f(e){return/* @__PURE__ */ TypeError(`deserialize(): ${e}`)}function p(e){if(e===null||typeof e==`boolean`||typeof e==`string`||typeof e==`number`)return e;if(!d(e))throw f(`unexpected value.`);let t=u(e,`$`);if(t!==`u`){if(t===`num`){let t=u(e,`v`);if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===`-0`)return-0;throw f(`unknown number.`)}if(t===`big`){let t=u(e,`v`);if(typeof t!=`string`)throw f(`bigint without digits.`);return BigInt(t)}throw f(`unknown tag.`)}}function m(e,t){if(d(e)&&u(e,`$`)===`ref`){let n=u(e,`i`);if(typeof n!=`number`||!Number.isInteger(n)||n<0||n>=t.length)throw f(`reference outside the table.`);return t[n]}return p(e)}function h(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function g(e){if(!d(e))throw f(`table entry is not an object.`);let t=u(e,`$`);if(t===`obj`)return Object.create(null);if(t===`arr`)return[];if(t===`map`)return/* @__PURE__ */ new Map;if(t===`set`)return/* @__PURE__ */ new Set;if(t===`date`){let t=p(u(e,`v`));if(typeof t!=`number`)throw f(`date without a time.`);return new Date(t)}if(t===`buf`||t===`bin`){let n=u(e,`v`);if(typeof n!=`string`)throw f(`binary entry without data.`);let r=o(n),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);if(t===`buf`)return a;let s=u(e,`k`),c=typeof s==`string`?i.get(s):void 0;if(c===void 0)throw f(`unknown binary kind.`);try{return new c(a)}catch{throw f(`binary data does not fit its type.`)}}if(t===`url`){let t=u(e,`v`);if(typeof t!=`string`)throw f(`url without an href.`);return new URL(t)}throw f(`unknown table entry.`)}function _(e,t,n){let r=u(e,`$`);if(r===`date`||r===`url`||r===`buf`||r===`bin`)return;let i=u(e,`e`);if(!Array.isArray(i))throw f(`entry without a list.`);if(r===`obj`&&typeof t==`object`&&t)for(let e of i){if(!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`)throw f(`object entry is not a key and value.`);h(t,e[0],m(e[1],n))}else if(r===`arr`&&Array.isArray(t))for(let e of i)t.push(m(e,n));else if(r===`map`&&t instanceof Map)for(let e of i){if(!Array.isArray(e)||e.length!==2)throw f(`map entry is not a pair.`);t.set(m(e[0],n),m(e[1],n))}else if(r===`set`&&t instanceof Set)for(let e of i)t.add(m(e,n));else throw f(`entry does not match its tag.`)}function v(e){let t=JSON.parse(e);if(!d(t))throw f(`payload is not an object.`);let n=u(t,`t`);if(!Array.isArray(n))throw f(`payload has no table.`);let r=[];for(let e of n)r.push(g(e));for(let e=0;e<n.length;e+=1){let t=n[e];d(t)&&_(t,r[e],r)}return m(u(t,`r`),r)}export{v as deserialize,l as serialize};
|
|
2
|
+
//# sourceMappingURL=serialize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serialize.js","names":["UNSAFE_TEXT","escapeForScript","json","char","encodeNumber","value","BINARY_KINDS","toBase64","binary","offset","bytes","fromBase64","text","malformed","i","binaryKindOf","name","ctor","isPlainObject","proto","serialize","table","index","queue","slotOf","existing","slot","encodeValue","invalid","encodeEntry","kind","pairs","key","item","items","root","data","head","entry","own","record","isRecord","detail","decodeScalar","tag","decodeValue","defineOwn","target","createEntry","time","buffer","href","fillEntry","pair","deserialize","payload","made"],"sources":["../../../src/server/serialize.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n\n/*\n * Wire format: {\"r\": <value>, \"t\": [<entry>, ...]}. Containers (objects, arrays, Map, Set, Date,\n * URL) live in the table and refer to each other by index, so cycles and shared references keep\n * their identity and the walk needs no recursion. A value is a JSON primitive, or a tagged object:\n * {\"$\":\"u\"} undefined\n * {\"$\":\"num\",\"v\":\"NaN\"|\"Infinity\"|\"-Infinity\"|\"-0\"}\n * {\"$\":\"big\",\"v\":\"<decimal>\"} bigint\n * {\"$\":\"ref\",\"i\":<index>} a table entry\n * Table entries are {\"$\":\"obj\",\"e\":[[key,value],...]}, {\"$\":\"arr\",\"e\":[...]},\n * {\"$\":\"map\",\"e\":[[key,value],...]}, {\"$\":\"set\",\"e\":[...]}, {\"$\":\"date\",\"v\":<number>},\n * {\"$\":\"url\",\"v\":\"<href>\"}. Plain objects are read with own properties only and rebuilt with a\n * null prototype, so \"__proto__\" or \"constructor\" keys are ordinary data.\n */\n\n/** Characters that may not appear raw in the output: they would end a script element or a line. */\nconst UNSAFE_TEXT = /[<>&\\u2028\\u2029]/g;\n\n/** Escapes text for `<script type=\"application/json\">`: the JSON stays valid, the markup cannot close. */\nfunction escapeForScript(json: string): string {\n return json.replace(\n UNSAFE_TEXT,\n (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/** Encodes a number that JSON cannot carry exactly. */\nfunction encodeNumber(value: number): unknown {\n if (Number.isFinite(value) && !Object.is(value, -0)) return value;\n return { $: \"num\", v: Object.is(value, -0) ? \"-0\" : String(value) };\n}\n\n/** Binary types the wire format carries, by the name written on the wire. */\ntype BinaryConstructor = new (buffer: ArrayBuffer) => ArrayBufferView;\nconst BINARY_KINDS: ReadonlyMap<string, BinaryConstructor> = new Map<string, BinaryConstructor>([\n [\"Int8Array\", Int8Array],\n [\"Uint8Array\", Uint8Array],\n [\"Uint8ClampedArray\", Uint8ClampedArray],\n [\"Int16Array\", Int16Array],\n [\"Uint16Array\", Uint16Array],\n [\"Int32Array\", Int32Array],\n [\"Uint32Array\", Uint32Array],\n [\"Float32Array\", Float32Array],\n [\"Float64Array\", Float64Array],\n [\"BigInt64Array\", BigInt64Array],\n [\"BigUint64Array\", BigUint64Array],\n [\"DataView\", DataView],\n]);\n\n/** Base64 of `bytes`, converted in chunks so a large buffer cannot overflow the call stack. */\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Bytes of a base64 text; malformed text throws a TypeError. */\nfunction fromBase64(text: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(text);\n } catch {\n throw malformed(\"binary data is not valid base64.\");\n }\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/** The wire name of a typed array or DataView, or undefined for anything else. */\nfunction binaryKindOf(value: object): string | undefined {\n for (const [name, ctor] of BINARY_KINDS) {\n if (value instanceof ctor) return name;\n }\n return undefined;\n}\n\n/** True for plain objects: prototype is Object.prototype or none. */\nfunction isPlainObject(value: object): boolean {\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Serializes data for embedding in a page, as JSON that is safe inside a\n * `<script type=\"application/json\">` element. It carries what JSON cannot: undefined, NaN,\n * infinities, -0, bigint, Date, URL, Map, Set, ArrayBuffer, typed arrays and DataView (copied: views\n * that shared a buffer come back as independent copies), plus shared references and cycles between\n * plain objects and arrays. Read it back with {@link deserialize}.\n *\n * @param data The value to serialize.\n * @returns JSON text with `<`, `>`, `&`, U+2028 and U+2029 written as `\\u` escapes, so it cannot\n * close the script element.\n * @throws TypeError `UNSERIALIZABLE_VALUE` for a function, a symbol, or an object that is not one of\n * the supported kinds (a class instance, for example).\n * @example\n * import { serialize } from \"@shadow-js/web/server\";\n *\n * const data = { user: { name: \"Ada\" }, seen: new Set([1, 2]), at: new Date(0) };\n * const tag = `<script type=\"application/json\" id=\"data\">${serialize(data)}</script>`;\n * @see deserialize\n * @since 1.0.0\n */\nexport function serialize(data: unknown): string {\n const table: unknown[] = [];\n const index = new Map<object, number>();\n const queue: Array<{ readonly value: object; readonly slot: number }> = [];\n\n const slotOf = (value: object): number => {\n const existing = index.get(value);\n if (existing !== undefined) return existing;\n const slot = table.length;\n table.push(null);\n index.set(value, slot);\n queue.push({ value, slot });\n return slot;\n };\n\n const encodeValue = (value: unknown): unknown => {\n if (value === undefined) return { $: \"u\" };\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") return value;\n if (typeof value === \"number\") return encodeNumber(value);\n if (typeof value === \"bigint\") return { $: \"big\", v: value.toString() };\n if (typeof value === \"object\") return { $: \"ref\", i: slotOf(value) };\n throw invalid(\"UNSERIALIZABLE_VALUE\", `A ${typeof value} cannot be serialized.`);\n };\n\n const encodeEntry = (value: object): unknown => {\n if (value instanceof Date) return { $: \"date\", v: encodeValue(value.getTime()) };\n if (value instanceof ArrayBuffer) return { $: \"buf\", v: toBase64(new Uint8Array(value)) };\n if (ArrayBuffer.isView(value)) {\n const kind = binaryKindOf(value);\n if (kind !== undefined) {\n const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n return { $: \"bin\", k: kind, v: toBase64(bytes) };\n }\n }\n if (value instanceof URL) return { $: \"url\", v: value.href };\n if (value instanceof Map) {\n const pairs: unknown[] = [];\n for (const [key, item] of value) pairs.push([encodeValue(key), encodeValue(item)]);\n return { $: \"map\", e: pairs };\n }\n if (value instanceof Set) {\n const items: unknown[] = [];\n for (const item of value) items.push(encodeValue(item));\n return { $: \"set\", e: items };\n }\n if (Array.isArray(value)) {\n const items: unknown[] = [];\n // An index loop, so holes in a sparse array become undefined instead of being skipped.\n for (let i = 0; i < value.length; i += 1) items.push(encodeValue(value[i]));\n return { $: \"arr\", e: items };\n }\n if (!isPlainObject(value)) {\n throw invalid(\n \"UNSERIALIZABLE_VALUE\",\n \"Only plain objects, arrays, Map, Set, Date, URL, ArrayBuffer and typed arrays can be serialized.\",\n );\n }\n const pairs: unknown[] = [];\n for (const key of Object.keys(value)) pairs.push([key, encodeValue(Reflect.get(value, key))]);\n return { $: \"obj\", e: pairs };\n };\n\n const root = encodeValue(data);\n for (let head = 0; head < queue.length; head += 1) {\n const entry = queue[head];\n if (entry === undefined) break;\n table[entry.slot] = encodeEntry(entry.value);\n }\n return escapeForScript(JSON.stringify({ r: root, t: table }));\n}\n\n/** Reads an own property of a parsed JSON object; never reaches the prototype chain. */\nfunction own(record: object, key: string): unknown {\n return Object.hasOwn(record, key) ? Reflect.get(record, key) : undefined;\n}\n\n/** True for a non-null, non-array object. */\nfunction isRecord(value: unknown): value is object {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Throws the TypeError for a payload that is not in the wire format. */\nfunction malformed(detail: string): TypeError {\n return new TypeError(`deserialize(): ${detail}`);\n}\n\n/** Decodes a value that cannot refer to other entries (used while the table is created). */\nfunction decodeScalar(value: unknown): unknown {\n if (\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"string\" ||\n typeof value === \"number\"\n ) {\n return value;\n }\n if (!isRecord(value)) throw malformed(\"unexpected value.\");\n const tag = own(value, \"$\");\n if (tag === \"u\") return undefined;\n if (tag === \"num\") {\n const text = own(value, \"v\");\n if (text === \"NaN\") return Number.NaN;\n if (text === \"Infinity\") return Number.POSITIVE_INFINITY;\n if (text === \"-Infinity\") return Number.NEGATIVE_INFINITY;\n if (text === \"-0\") return -0;\n throw malformed(\"unknown number.\");\n }\n if (tag === \"big\") {\n const text = own(value, \"v\");\n if (typeof text !== \"string\") throw malformed(\"bigint without digits.\");\n return BigInt(text);\n }\n throw malformed(\"unknown tag.\");\n}\n\n/**\n * Rebuilds a value from the table. Plain objects get a null prototype; their keys are defined as\n * own data properties, so no key can reach or replace a prototype.\n */\nfunction decodeValue(value: unknown, table: readonly unknown[]): unknown {\n if (isRecord(value) && own(value, \"$\") === \"ref\") {\n const slot = own(value, \"i\");\n if (typeof slot !== \"number\" || !Number.isInteger(slot) || slot < 0 || slot >= table.length) {\n throw malformed(\"reference outside the table.\");\n }\n return table[slot];\n }\n return decodeScalar(value);\n}\n\n/** Defines an own data property; never assigns, so no setter or prototype is involved. */\nfunction defineOwn(target: object, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Creates an empty container for a table entry, or the value of a scalar entry. */\nfunction createEntry(entry: unknown): unknown {\n if (!isRecord(entry)) throw malformed(\"table entry is not an object.\");\n const tag = own(entry, \"$\");\n if (tag === \"obj\") return Object.create(null) as object;\n if (tag === \"arr\") return [];\n if (tag === \"map\") return new Map<unknown, unknown>();\n if (tag === \"set\") return new Set<unknown>();\n if (tag === \"date\") {\n const time = decodeScalar(own(entry, \"v\"));\n if (typeof time !== \"number\") throw malformed(\"date without a time.\");\n return new Date(time);\n }\n if (tag === \"buf\" || tag === \"bin\") {\n const text = own(entry, \"v\");\n if (typeof text !== \"string\") throw malformed(\"binary entry without data.\");\n const bytes = fromBase64(text);\n // A copy that owns exactly these bytes, so a view never exposes a larger buffer.\n const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n if (tag === \"buf\") return buffer;\n const kind = own(entry, \"k\");\n const ctor = typeof kind === \"string\" ? BINARY_KINDS.get(kind) : undefined;\n if (ctor === undefined) throw malformed(\"unknown binary kind.\");\n try {\n return new ctor(buffer as ArrayBuffer);\n } catch {\n throw malformed(\"binary data does not fit its type.\");\n }\n }\n if (tag === \"url\") {\n const href = own(entry, \"v\");\n if (typeof href !== \"string\") throw malformed(\"url without an href.\");\n return new URL(href);\n }\n throw malformed(\"unknown table entry.\");\n}\n\n/** Fills one container from its entry list. Date and URL entries are already complete. */\nfunction fillEntry(entry: object, target: unknown, table: readonly unknown[]): void {\n const tag = own(entry, \"$\");\n if (tag === \"date\" || tag === \"url\" || tag === \"buf\" || tag === \"bin\") return;\n const items = own(entry, \"e\");\n if (!Array.isArray(items)) throw malformed(\"entry without a list.\");\n if (tag === \"obj\" && target !== null && typeof target === \"object\") {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== \"string\") {\n throw malformed(\"object entry is not a key and value.\");\n }\n defineOwn(target, pair[0], decodeValue(pair[1], table));\n }\n } else if (tag === \"arr\" && Array.isArray(target)) {\n for (const item of items) target.push(decodeValue(item, table));\n } else if (tag === \"map\" && target instanceof Map) {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2) throw malformed(\"map entry is not a pair.\");\n target.set(decodeValue(pair[0], table), decodeValue(pair[1], table));\n }\n } else if (tag === \"set\" && target instanceof Set) {\n for (const item of items) target.add(decodeValue(item, table));\n } else {\n throw malformed(\"entry does not match its tag.\");\n }\n}\n\n/**\n * Rebuilds the value {@link serialize} wrote, with its shared references and cycles. Plain objects\n * come back with a null prototype (so a `__proto__` key is ordinary data), and malformed input throws\n * instead of producing a partial value. No code is evaluated.\n *\n * @param text JSON text produced by {@link serialize}.\n * @returns The rebuilt value.\n * @throws SyntaxError when `text` is not JSON; TypeError when the JSON is not in the format\n * `serialize` writes.\n * @example\n * import { deserialize, serialize } from \"@shadow-js/web/server\";\n *\n * const copy = deserialize(serialize({ tags: new Set([\"a\"]), total: 10n })) as {\n * tags: Set<string>;\n * total: bigint;\n * };\n * copy.tags.has(\"a\"); // true\n * @see serialize\n * @since 1.0.0\n */\nexport function deserialize(text: string): unknown {\n const payload: unknown = JSON.parse(text);\n if (!isRecord(payload)) throw malformed(\"payload is not an object.\");\n const table = own(payload, \"t\");\n if (!Array.isArray(table)) throw malformed(\"payload has no table.\");\n const made: unknown[] = [];\n for (const entry of table) made.push(createEntry(entry));\n for (let slot = 0; slot < table.length; slot += 1) {\n const entry = table[slot];\n if (isRecord(entry)) fillEnt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kC,EAAO,IAAIF,EAAYQ,EAAK,GAAIhC,CAAK,EAAGwB,EAAYQ,EAAK,GAAIhC,CAAK,CAAC,CACrE,MACK,GAAIuB,IAAQ,OAASG,aAAkB,IAC5C,IAAK,IAAMd,KAAQC,EAAOa,EAAO,IAAIF,EAAYZ,EAAMZ,CAAK,CAAC,OAE7D,MAAMR,EAAU,+BAA+B,CAEnD,CAsBA,SAAgByC,EAAY,EAAuB,CACjD,IAAMC,EAAmB,KAAK,MAAM3C,CAAI,EACxC,GAAI,CAAC6B,EAASc,CAAO,EAAG,MAAM1C,EAAU,2BAA2B,EACnE,IAAMQ,EAAQkB,EAAIgB,EAAS,GAAG,EAC9B,GAAI,CAAC,MAAM,QAAQlC,CAAK,EAAG,MAAMR,EAAU,uBAAuB,EAClE,IAAM2C,EAAkB,CAAC,EACzB,IAAK,IAAMlB,KAASjB,EAAOmC,EAAK,KAAKR,EAAYV,CAAK,CAAC,EACvD,IAAK,IAAIZ,EAAO,EAAGA,EAAOL,EAAM,OAAQ,GAAQ,EAAG,CACjD,IAAMiB,EAAQjB,EAAMK,GAChBe,EAASH,CAAK,GAAGc,EAAUd,EAAOkB,EAAK9B,GAAO8B,CAAI,CACxD,CACA,OAAOX,EAAYN,EAAIgB,EAAS,GAAG,EAAGC,CAAI,CAC5C,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{SsrError as r}from"./errors.js";import{escape as i}from"./escape.js";import{StreamContext as a}from"../internal/stream-context.js";import{attachRootErrors as o}from"../control-flow/root-errors.js";import{portalCollectorFor as s,withPortalSink as c}from"./portals.js";import{runWithServerHead as l}from"../head/server-head.js";import{serialize as u}from"./serialize.js";import{ResourceCacheContext as d,createRoot as f,untrack as p}from"@shadow-js/core";const m=/^[A-Za-z0-9_-]+$/;function h(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function g(g,_={}){let v=_.renderId??`0`;if(typeof v!=`string`||!m.test(v))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let y=_.timeoutMs??3e4;if(typeof y!=`number`||!(y>0)||!Number.isFinite(y))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let b=_.signal,x=s(_.portals),S=new TextEncoder,C=[],w=()=>{let e=[];for(let t of C.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},T=!1,E,D=()=>void 0;return new ReadableStream({async start(s){let m=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,k=e=>{if(b?.aborted)throw b.reason;T||s.enqueue(S.encode(e))},A=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};C.push(r);let s={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>m.has(e)?{value:m.get(e)}:void 0,track:(e,t,n)=>{O.set(e,t);let i=t.then(t=>{m.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>O.get(e)},u={defer:e=>{r.boundaries.push(e)}},p={onCaughtError:e=>{r.answered?_.onCaughtError?.(e):r.caught.push(e)},..._.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?_.onUncaughtError?.(e):r.uncaught.push(e)}}};return _.head?.clear(),x?.clear(),r.html=f(t=>(r.dispose=t,o(p),a({value:u,get children(){return c(x,()=>d({value:s,get children(){return l(_.head,()=>n(e(v),()=>i(g())))}}))}})()())),r},j=()=>void 0,M=new Promise((e,t)=>{j=t,E=setTimeout(()=>t(new r(`SSR_TIMEOUT`,`The stream did not finish within ${y} ms.`)),y)}),N=()=>j(b?.reason??/* @__PURE__ */ Error(`The render was aborted.`));b?.addEventListener(`abort`,N,{once:!0});let P=()=>{clearTimeout(E),b?.removeEventListener(`abort`,N),w()};D=e=>{j(e),P()},M.catch(()=>void 0);try{if(b?.aborted)throw b.reason;let e=A();for(let t=1;e.held.length>0&&(await Promise.race([M,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>m.has(e.key)));t+=1){if(t>=10)throw new r(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=A()}e.answered=!0,p(()=>{for(let t of e.caught)_.onCaughtError?.(t);for(let t of e.uncaught)_.onUncaughtError?.(t);_.onShellReady?.(e.html)}),k(e.boundaries.length>0?e.html+h(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,_.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))k(`<template id="s:${t.id}"></template>`+h(`$S(${JSON.stringify(t.id)},1)`,_.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=m.size;await Promise.race([M,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,k(`<template id="s:${e.id}">${t}</template>`+h(`$S(${JSON.stringify(e.id)})`,_.nonce)))}n=m.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let i={};for(let t of e.requested)m.has(t)&&Object.defineProperty(i,t,{value:m.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(i).length>0&&k(`<script type="application/json" data-sh="${v}">${u(i)}<\/script>`),P(),T||s.close()}catch(e){P(),T||s.error(e)}},cancel(e){T=!0,D(e)}})}export{g as renderToStream};
|
|
2
|
+
//# sourceMappingURL=stream.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream.js","names":["RENDER_ID","script","nonce","body","renderToStream","renderId","options","timeoutMs","signal","portals","portalCollectorFor","encoder","passes","disposeAll","errors","pass","error","canceled","timer","cancelRender","settled","fetching","push","controller","text","renderPass","cache","key","resourceKey","explicit","promise","entry","value","trackOptions","sink","boundary","reporters","createRoot","stop","attachRootErrors","StreamContext","withPortalSink","ResourceCacheContext","runWithServerHead","withScope","createRootScope","escape","code","rejectAbort","abort","reject","SsrError","onAbort","cleanup","reason","answer","round","held","untrack","failRemaining","strikes","settledBefore","current","emitted","html","data","serialize"],"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":"A,6iBA6EA,MAAMA,EAAY,mBAwClB,SAASC,EAAO,EAAc,EAAmC,CAG/D,MAAO,UADLC,IAAU,IAAA,GAAY,GAAK,WAAWA,EAAM,QAAQ,qBAAsB,EAAE,EAAE,GACrD,GAAGC,EAAK,WACrC,CA+BA,SAAgBC,EACd,EACA,EAAyB,CAAC,EACE,CAC5B,IAAMC,EAAWC,EAAQ,UAAY,IACrC,GAAI,OAAOD,GAAa,UAAY,CAACL,EAAU,KAAKK,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,IAAME,EAAYD,EAAQ,WAAa,IACvC,GAAI,OAAOC,GAAc,UAAY,EAAEA,EAAY,IAAM,CAAC,OAAO,SAASA,CAAS,EACjF,MAAU,UAAU,6DAA6D,EAEnF,IAAMC,EAASF,EAAQ,OACjBG,EAAUC,EAAmBJ,EA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C9B,MAAM,QAAQ,KAAK,CAAC6B,EAAO,QAAQ,KAAK,CAAC,GAAGM,EAAO,QAAQ,CAAC,CAAC,CAAC,EAC9D,IAAMO,EAAUP,EAAO,WACvB,EAAO,WAAa,CAAC,EACrB,IAAIQ,EAAU,GACd,IAAK,IAAM5B,KAAY2B,EAAS,CAC9B,IAAME,EAAO7B,EAAS,QAAQ,EAC1B6B,IAAS,OACb,EAAU,GACV1C,EACE,mBAAmBa,EAAS,GAAG,IAAI6B,EAAK,aACtC/D,EAAO,MAAM,KAAK,UAAUkC,EAAS,EAAE,EAAE,GAAI7B,EAAQ,KAAK,CAC9D,EACF,CAEA,EAAUc,EAAQ,OAASyC,GAAiB,CAACE,EAAUH,EAAU,EAAI,EACjEL,EAAO,WAAW,OAAS,GAAKK,GAAW,GAAGD,EAAc,CAClE,CAEA,IAAMM,EAAgC,CAAC,EACvC,IAAK,IAAMtC,KAAO4B,EAAO,UAClBnC,EAAQ,IAAIO,CAAG,GACpB,OAAO,eAAesC,EAAMtC,EAAK,CAC/B,MAAOP,EAAQ,IAAIO,CAAG,EACtB,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EAEC,OAAO,KAAKsC,CAAI,CAAC,CAAC,OAAS,GAC7B3C,EAAK,4CAA4CjB,EAAS,IAAI6D,EAAUD,CAAI,EAAE,WAAU,EAE1FZ,EAAQ,EACHpC,GAAUM,EAAW,MAAM,CAClC,OAASP,EAAO,CACdqC,EAAQ,EACHpC,GAAUM,EAAW,MAAMP,CAAK,CACvC,CACF,EACA,OAAO,EAAQ,CACb,EAAW,GACXG,EAAamC,CAAM,CACrB,CACF,CAAC,CACH,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{escape as e}from"./server/escape.js";import{ssrAttribute as t}from"./server/attributes.js";import{ssrClass as n,ssrStyle as r}from"./server/class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./server/form-controls.js";import{ssr as o,ssrElement as s,ssrHydrationKey as c,ssrRaw as l}from"./server/element.js";import{createServerPortals as u}from"./server/portals.js";import{normalizeTags as d}from"./head/validate.js";import{createServerHead as f}from"./head/server-head.js";import{createComponent as p,memo as m}from"./server/component.js";import{derived as h}from"./server/derived.js";import{HydrationScript as g,generateHydrationScript as _}from"./server/hydration-script.js";import{renderToString as v,renderToStringAsync as y}from"./server/render.js";import{deserialize as b,serialize as x}from"./server/serialize.js";import{renderToStream as S}from"./server/stream.js";import{mergeProps as C}from"./server/index.js";export{g as HydrationScript,p as createComponent,f as createServerHead,u as createServerPortals,h as derived,b as deserialize,e as escape,_ as generateHydrationScript,m as memo,C as mergeProps,d as normalizeTags,S as renderToStream,v as renderToString,y as renderToStringAsync,x as serialize,o as ssr,t as ssrAttribute,n as ssrClass,s as ssrElement,c as ssrHydrationKey,l as ssrRaw,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,classList as a,style as o}from"./class-style.js";import{claims as s}from"./internal/hydration-hooks.js";import{bindRegion as c,createRegion as l}from"./insert.js";import{IGNORED_KEYS as u,attributeName as d,eventPlan as f}from"./internal/react-names.js";import{bindEvent as p}from"./events.js";import{selectShows as m,setSelectValue as h}from"./select-value.js";import{onCleanup as g,untrack as _,useRenderEffect as v}from"@shadow-js/core";function y(e){return typeof e!=`object`||!e?``:w(Reflect.get(e,`__html`))}const b=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]);function x(e){return e.length>2&&e.startsWith(`on`)}function S(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function C(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function w(e){return e==null?``:String(e)}function T(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))b.has(S(a))||u.has(a)||(a===`children`?t&&(r=Reflect.get(e,a),i=!0):n.push([a,Reflect.get(e,a)]));return i&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n}function E(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,_(t))}function D(e,t,n,s,c){if(t===`ref`){if(E(s),typeof n==`function`){let t=n,r=_(()=>t(e));typeof r==`function`&&(s.refCleanup=r)}}else if(t===`autoFocus`)s.autoFocused||(s.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,c);else if(t===`style`)s.styleValue=o(e,n,s.styleValue);else if(t===`classList`)s.classListValue=a(e,C(n),s.classListValue);else if(x(t)){s.unbinders.get(t)?.(),s.unbinders.delete(t);let r=f(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=p(e,r.type,i,!0,r.capture);a!==void 0&&s.unbinders.set(t,a)}else t===`innerHTML`?e.innerHTML=w(n):t===`dangerouslySetInnerHTML`?e.innerHTML=y(n):t===`textContent`?e.textContent=w(n):!c&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?h(e,n):!c&&k.has(t)&&t in e?(j(e,t,n,c)&&Reflect.set(e,t,A.has(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=w(n))):O(e,t,n,c)}function O(r,i,a,o){if(i.startsWith(`prop:`))Reflect.set(r,i.slice(5),a);else if(i.startsWith(`attr:`))e(r,i.slice(5),a);else if(i.startsWith(`bool:`))n(r,i.slice(5),a);else{let n=d(i,o);n.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,n,a):e(r,n,a)}}const k=/* @__PURE__ */ new Set([`value`,`checked`,`selected`,`muted`,`indeterminate`,`defaultValue`,`defaultChecked`]),A=/* @__PURE__ */ new Set([`value`,`defaultValue`]);function j(e,t,n,r){if(r||!k.has(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!m(e,n);let i=Reflect.get(e,t);return A.has(t)?i!==w(n):i!==!!n}function M(e,t,n,r){t===`ref`?E(n):t!==`autoFocus`&&(t===`class`||t===`className`?i(e,void 0,r):t===`style`?n.styleValue=o(e,void 0,n.styleValue):t===`classList`?n.classListValue=a(e,void 0,n.classListValue):x(t)?(n.unbinders.get(t)?.(),n.unbinders.delete(t)):t===`innerHTML`||t===`dangerouslySetInnerHTML`||t===`textContent`?e.textContent=``:!r&&k.has(t)&&t in e?Reflect.set(e,t,A.has(t)?``:!1):O(e,t,void 0,r))}function N(e,t,n,r){let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(n.values.has(a)&&Object.is(n.values.get(a),o)&&!j(e,a,o,r))&&(n.values.set(a,o),D(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),M(e,t,n,r))}function P(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=e.localName===`textarea`;if(!r&&!a){let t=s.current.isClaiming()?s.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,n=l(e,null,t);c(n,()=>i()?.children)}let o={values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0};g(()=>{for(let e of o.unbinders.values())e();o.unbinders.clear(),E(o)}),v(()=>T(i(),a),t=>{N(e,t,o,n)})}export{P as spread};
|
|
2
|
+
//# sourceMappingURL=spread.js.map
|