@tschk/moonshine-astro 0.4.4 → 0.4.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +127 -3
  2. package/package.json +6 -5
  3. package/src/ssr.ts +233 -0
package/README.md CHANGED
@@ -18,6 +18,7 @@ import { fromMoonshineSignal, crepusRenderer } from "@tschk/moonshine-astro";
18
18
  | ------------ | ---------------------------------------------- |
19
19
  | `.` | Native signal bridges and lazy native renderer |
20
20
  | `./compiler` | Legacy Astro compiler re-exports |
21
+ | `./ssr` | Independent synchronous Astro source factories |
21
22
 
22
23
  `crepusRenderer` preserves its compatibility name but renders native server
23
24
  factories, escaped metadata, API JSON and SPA shells. Install
@@ -31,6 +32,129 @@ called, so signal bridge consumers do not load server rendering.
31
32
  Legacy entries require their optional host peers: `astro`. They cannot be
32
33
  aliased over arbitrary host-compiled output to remove the host.
33
34
 
34
- The compiler entry still requires Astro. Native rendering expects compiled Moonshine server factories; it does not execute Astro frontmatter or implement the Astro compiler result shapes.
35
- Source parsing and compilation belong to Crepuscularity; these root runtime
36
- changes do not establish full Astro source support.
35
+ The compiler entry still requires Astro. The independent `/ssr` entry supplies
36
+ factories for Crepuscularity-authored server modules; it does not implement
37
+ Astro's compiled component ABI. It preserves HTML attributes, normalizes
38
+ `class:list` and style objects, escapes ordinary children and keeps component
39
+ props independent of any host runtime.
40
+
41
+ Local Crepuscularity integration now lowers fenced `.astro` frontmatter into
42
+ per-render synchronous factories, including typed `Props`, `Astro.props`, static
43
+ imports, imported children, conditionals and simple maps. This compiler work is
44
+ not yet published. Scriptless entry files retain the older scope-based template
45
+ path. Parsing and lowering stay in Crepuscularity.
46
+
47
+ This remains a bounded source slice: top-level await, dynamic imports,
48
+ client directives, script/style blocks, runtime exports, async children, and
49
+ Astro globals other than `Astro.props` are unsupported. Hydration and arbitrary
50
+ host-compiled output are unsupported. Use the legacy compiler explicitly for
51
+ applications requiring the full Astro compiler contract.
52
+
53
+ Run the authored-source regression with an explicitly supplied local compiler:
54
+
55
+ ```sh
56
+ MOONSHINE_CREPUS_COMPILER=/absolute/path/to/crepus bun test packages/adapter-astro/test/standalone.test.ts
57
+ ```
58
+
59
+ It checks prop/interpolation capture, deferred component setup, short-circuit
60
+ values, optional maps, slots and component prop identity in isolated Bun and Node
61
+ consumers. Without the variable,
62
+ that compiler integration case is explicitly skipped; runtime cases still run.
63
+
64
+ The local authored compiler retains whitespace in `pre`/`textarea`, including
65
+ nested elements and expression boundaries, and keeps same-line root sibling
66
+ separators. These factories serialize initial newlines using literal HTML rules;
67
+ the browser consumes the first newline after `pre`/`textarea`. Ordinary native
68
+ DOM factories keep their existing textarea property-value behavior.
69
+
70
+ Conditional and mapped markup retains text punctuation, including apostrophes,
71
+ colons, question marks and operator-like text. Nested template substitutions
72
+ work in child and attribute expressions, while quoted attribute braces stay literal.
73
+ Authored regex/division boundaries use Crepuscularity's existing JavaScript
74
+ parser, including nested templates, attributes and JavaScript groups. Astro
75
+ void tags stay in the markup frontend; no host runtime or parser enters the SDK.
76
+ Namespace/directive attributes, generic `Props`, and map callbacks with
77
+ index/destructuring/block bodies are not yet supported. These parser limits remain work in Crepuscularity.
78
+
79
+ Local component prop spreads now preserve ordinary JavaScript override order,
80
+ getter evaluation and own string/symbol keys. Forwarding `Astro.props` works
81
+ through imported components; ordinary `children`/`slots` props remain separate
82
+ from projected slots. Spread `class:list` normalizes against the final `class`
83
+ after overrides. Nullish spreads contribute no props. Slot outlet spreads remain
84
+ rejected. Compiler lowering is local and unpublished.
85
+
86
+ Local intrinsic spreads use ordered attribute segments rather than merged props.
87
+ Own enumerable string getters run once, in order, with coercion before the next
88
+ getter/expression; inherited and symbol keys are ignored. Function values stringify
89
+ without invocation. Literal and dynamic boolean values retain their separate
90
+ rules. Repeated attributes (including spread classes) remain separate; HTML parsing
91
+ keeps the first. Authored `class` plus `class:list` combines at the directive position.
92
+ The opt-in `/ssr` compiler helpers are `sourceAttribute`, `sourceSpread` and
93
+ `sourceElement`; ordinary no-spread factories retain their existing path.
94
+
95
+ Moonshine retains its server constraints: event attributes are filtered, invalid
96
+ names throw, script/style elements and spread directives/namespaces reject.
97
+ These differ from Astro's more permissive spread handling. Nullish spreads are
98
+ empty; string/array index keys fail attribute-name validation. Raw-content-looking
99
+ names remain escaped ordinary attributes, not HTML injection instructions.
100
+
101
+ An authored fixture passes three fresh SSR requests in Bun and minified Node,
102
+ plus Chromium parsing, input editing and form reset with no client script. Six
103
+ parsed cases match actual Astro 7.4.0 attribute helpers, with event filtering
104
+ recorded separately. The reference uses compiler 4.0.0 segment output and runtime
105
+ helpers separately, not a complete host compilation/rendering comparison. The
106
+ fixture is 5,860 gzip bytes; an ordinary no-spread control stays 12,844 raw bytes
107
+ and changes from 4,902 to 4,903 gzip bytes. No host bundle or speed claim.
108
+
109
+ Without prop spreads, combined `class` and `class:list` use the existing helper.
110
+ The ordinary class evaluates first at the directive position. Empty HTML classes
111
+ are omitted. Component factories omit an empty normalized class-list prop while
112
+ retaining an explicitly supplied empty ordinary `class` prop.
113
+
114
+ Local authored slot lowering now supports default and nonempty literal named
115
+ slots, grouping of same-name children, named Fragments and forwarding through
116
+ imported layouts. An explicit empty slot suppresses fallback; whitespace-only
117
+ ordinary component content supplies no slot. Projected HTML loses the marker,
118
+ while projected components retain their ordinary `slot` prop. Dynamic/empty
119
+ outlet names and misplaced markers reject explicitly. `Astro.slots.render`, the
120
+ slot bag, method extraction, computed/optional access and unrelated Astro globals
121
+ remain unsupported.
122
+
123
+ Local source now supports ordinary `Astro.slots.has(nameExpression)` calls in
124
+ frontmatter and template expressions, including dynamic strings and nested
125
+ `Astro.props` reads. For example:
126
+
127
+ ```astro
128
+ ---
129
+ interface Props { lookup?: string }
130
+ const present = Astro.slots.has(Astro.props.lookup ?? "head");
131
+ ---
132
+ <section data-present={String(present)}><slot name="head">fallback</slot></section>
133
+ ```
134
+
135
+ Presence uses the existing native own-slot protocol: an explicitly empty supplied
136
+ slot counts, missing/inherited names do not. The query never renders content or
137
+ reads its value. It works without a slot outlet; an unused child that would throw
138
+ stays unevaluated. Shadowed local `Astro` bindings remain ordinary JavaScript.
139
+ Native own-slot behavior differs from Astro's inherited-name and reserved-member
140
+ quirks; it does not implement the host Slots instance ABI.
141
+
142
+ The real Astro 7.4.0 Slots class and @astrojs/compiler 4.0.0 were checked separately
143
+ for presence values and emitted slot shapes. Six native source cases pass
144
+ repeated fresh Bun/minified Node SSR, with dynamic argument evaluation once and
145
+ no Astro/React/parser WASM in the runtime graph. Both source/declaration type
146
+ lanes pass. The native fixture is 5,592 gzip bytes; there is no full host bundle
147
+ or timing comparison. A no-slot control bundle is byte-identical before/after
148
+ the helper addition. Compiler changes remain local and unpublished.
149
+
150
+ Generated calls use the compiler-facing `sourceComponent` / `sourceSlot` /
151
+ `sourceHasSlot` contract. Slot values stay outside ordinary props, including `children` and
152
+ `slots`. Props and template interpolations capture when the parent constructs
153
+ its template; component frontmatter runs during serialization, once per
154
+ invocation. Unused slot content stays lazy, repeated outlets render it again,
155
+ and fallback interpolations capture eagerly while fallback components defer.
156
+ Deferred content retains its caller's native SSR owner. Construct these helpers
157
+ inside `renderToString(() => ...)`; ordinary public `h` invocation is unchanged.
158
+ This compiler integration is local and unpublished. The companion runtime
159
+ helpers are available in SDK 0.4.22. This is not Astro's compiled component ABI;
160
+ async rendering, hydration and full slot/source coverage remain incomplete.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-astro",
3
- "version": "0.4.4",
3
+ "version": "0.4.49",
4
4
  "description": "Native signal bridges and rendering with optional legacy astro entries",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -8,18 +8,19 @@
8
8
  "types": "./src/index.ts",
9
9
  "exports": {
10
10
  ".": "./src/index.ts",
11
- "./compiler": "./src/compiler.ts"
11
+ "./compiler": "./src/compiler.ts",
12
+ "./ssr": "./src/ssr.ts"
12
13
  },
13
14
  "dependencies": {
14
- "@tschk/moonshine": "^0.4.4",
15
- "@tschk/moonshine-dom": "^0.4.4"
15
+ "@tschk/moonshine": "^0.4.48",
16
+ "@tschk/moonshine-dom": "^0.4.48"
16
17
  },
17
18
  "devDependencies": {
18
19
  "typescript": "7.0.2"
19
20
  },
20
21
  "peerDependencies": {
21
22
  "astro": ">=4",
22
- "@tschk/moonshine-framework": "^0.4.4"
23
+ "@tschk/moonshine-framework": "^0.4.48"
23
24
  },
24
25
  "peerDependenciesMeta": {
25
26
  "astro": {
package/src/ssr.ts ADDED
@@ -0,0 +1,233 @@
1
+ /** Independent synchronous Astro source factories; no host compiler ABI. */
2
+ export * from "@tschk/moonshine-dom/ssr";
3
+ import {
4
+ h as nativeH,
5
+ hAttributes,
6
+ hAttributeEntries,
7
+ defer,
8
+ scopeSSRChild,
9
+ type HTML,
10
+ type SSRChild,
11
+ } from "@tschk/moonshine-dom/ssr";
12
+
13
+ const booleanAttributes = new Set(
14
+ "allowfullscreen async autofocus autoplay checked controls default defer disabled disablepictureinpicture disableremoteplayback formnovalidate inert loop muted nomodule novalidate open playsinline readonly required reversed scoped seamless selected itemscope".split(
15
+ " ",
16
+ ),
17
+ );
18
+
19
+ /** Compiler-facing class:list normalization, independent of clsx. */
20
+ export function classList(value: unknown): string {
21
+ if (!value) return "";
22
+ if (typeof value === "string" || typeof value === "number")
23
+ return String(value);
24
+ if (Array.isArray(value))
25
+ return value.map(classList).filter(Boolean).join(" ");
26
+ if (typeof value === "object") {
27
+ const classes: string[] = [];
28
+ for (const key in value) if (Reflect.get(value, key)) classes.push(key);
29
+ return classes.join(" ");
30
+ }
31
+ return "";
32
+ }
33
+
34
+ /** Compiler-facing interpolation normalization for synchronous Astro factories. */
35
+ export function sourceChild(value: unknown): SSRChild {
36
+ if (!value && value !== 0) return undefined;
37
+ if (value === true) return "true";
38
+ if (Array.isArray(value)) return value.map(sourceChild);
39
+ if (typeof value === "function") return () => sourceChild(value());
40
+ if (
41
+ typeof value === "object" &&
42
+ value !== null &&
43
+ "then" in value &&
44
+ typeof value.then === "function"
45
+ ) {
46
+ void Promise.resolve(value).catch(() => {});
47
+ throw new TypeError(
48
+ "Async Astro children are unsupported; use synchronous server data",
49
+ );
50
+ }
51
+ return value as SSRChild;
52
+ }
53
+
54
+ function style(value: object): string {
55
+ return Object.entries(value)
56
+ .filter(
57
+ ([, item]) =>
58
+ typeof item === "number" || (typeof item === "string" && item.trim()),
59
+ )
60
+ .map(
61
+ ([key, item]) =>
62
+ `${key[0] === "-" || key[1] === "-" ? key : key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}:${item}`,
63
+ )
64
+ .join(";");
65
+ }
66
+
67
+ function attribute(
68
+ tag: string,
69
+ name: string,
70
+ value: unknown,
71
+ dynamic: boolean,
72
+ ): string | undefined {
73
+ if (value == null) return undefined;
74
+ if (!dynamic && typeof value === "string") return value;
75
+ const lower = name.toLowerCase();
76
+ if (
77
+ booleanAttributes.has(lower) ||
78
+ (["download", "hidden", "popover"].includes(lower) &&
79
+ typeof value === "boolean")
80
+ ) {
81
+ if (tag.includes("-") && lower !== "popover") return String(value);
82
+ return value ? "" : undefined;
83
+ }
84
+ if (name === "style" && typeof value === "object") {
85
+ if (Array.isArray(value) && value.length === 2)
86
+ return `${style(value[0] ?? {})};${value[1]}`;
87
+ return style(value);
88
+ }
89
+ return String(value);
90
+ }
91
+
92
+ export type SourceSlots = Readonly<Record<string, SSRChild>>;
93
+
94
+ function captureProps<P extends object>(props: P): P {
95
+ return { ...props };
96
+ }
97
+
98
+ /** Compiler-facing component invocation; slots remain outside ordinary props. */
99
+ export function sourceComponent<P extends object>(
100
+ component: (props: P, slots: SourceSlots) => SSRChild,
101
+ props: P,
102
+ slots: Readonly<Record<string, () => SSRChild>> = {},
103
+ ): SSRChild {
104
+ const captured = captureProps(props);
105
+ const values = captured as Record<string, unknown>;
106
+ if (values["class:list"] !== undefined) {
107
+ const list = values["class:list"];
108
+ delete values["class:list"];
109
+ const normalized = classList([values.class, list]);
110
+ if (normalized) values.class = normalized;
111
+ else delete values.class;
112
+ }
113
+ const supplied: SourceSlots = Object.fromEntries(
114
+ Object.entries(slots).map(([name, render]) => [
115
+ name,
116
+ scopeSSRChild(() => sourceChild(render())),
117
+ ]),
118
+ );
119
+ let result: { value: SSRChild } | { error: unknown } | undefined;
120
+ return scopeSSRChild(
121
+ defer(() => {
122
+ if (!result) {
123
+ try {
124
+ result = {
125
+ value: nativeH(
126
+ (actual: P) => sourceChild(component(actual, supplied)),
127
+ captured,
128
+ ),
129
+ };
130
+ } catch (error) {
131
+ result = { error };
132
+ }
133
+ }
134
+ if ("error" in result) throw result.error;
135
+ return result.value;
136
+ }),
137
+ );
138
+ }
139
+
140
+ /** Presence selects a slot, including an explicitly empty supplied slot. */
141
+ export function sourceSlot(
142
+ slots: SourceSlots,
143
+ name = "default",
144
+ fallback?: SSRChild,
145
+ ): SSRChild {
146
+ return sourceChild(Object.hasOwn(slots, name) ? slots[name] : fallback);
147
+ }
148
+
149
+ /** Check native slot presence without evaluating its supplied content. */
150
+ export function sourceHasSlot(slots: SourceSlots, name: string): boolean {
151
+ return Object.hasOwn(slots, name);
152
+ }
153
+
154
+ export function h<P extends object>(
155
+ component: (props: P & { children?: SSRChild }) => SSRChild,
156
+ props: P | null,
157
+ ...children: SSRChild[]
158
+ ): SSRChild;
159
+ export function h(
160
+ tag: string,
161
+ props?: Record<string, unknown> | null,
162
+ ...children: SSRChild[]
163
+ ): HTML;
164
+ export function h(
165
+ tag: string | ((props: any) => SSRChild),
166
+ props: Record<string, unknown> | null = null,
167
+ ...children: SSRChild[]
168
+ ): SSRChild {
169
+ if (typeof tag === "function") {
170
+ const captured = props == null ? null : captureProps(props);
171
+ return nativeH(tag, captured, ...children.map(sourceChild));
172
+ }
173
+ const attributes = Object.fromEntries(
174
+ Object.keys(props ?? {}).map((name) => [
175
+ name === "className" ? "class" : name,
176
+ () => {
177
+ const supplied = props![name];
178
+ const dynamic = typeof supplied === "function";
179
+ return attribute(tag, name, dynamic ? supplied() : supplied, dynamic);
180
+ },
181
+ ]),
182
+ );
183
+ return hAttributes(tag, attributes, ...children.map(sourceChild));
184
+ }
185
+
186
+ /** Encoded compiler-facing attribute; repeated names remain separate entries. */
187
+ export type SourceAttribute = readonly [
188
+ name: string,
189
+ value: string | undefined,
190
+ ];
191
+
192
+ /** Coerce at the authored position, before subsequent expressions or getters. */
193
+ export function sourceAttribute(
194
+ tag: string,
195
+ name: string,
196
+ supplied: unknown,
197
+ dynamic = false,
198
+ ): SourceAttribute {
199
+ if (!/^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/.test(name)) {
200
+ throw new TypeError("Invalid server attribute name");
201
+ }
202
+ if (name.includes(":") && name !== "class:list") {
203
+ throw new TypeError(
204
+ `Unsupported Astro spread directive or namespace: ${name}`,
205
+ );
206
+ }
207
+ const outputName =
208
+ name === "class:list" || name === "className" ? "class" : name;
209
+ const value = /^on/i.test(name)
210
+ ? undefined
211
+ : name === "class:list"
212
+ ? classList(supplied) || undefined
213
+ : attribute(tag, name, supplied, dynamic);
214
+ return [outputName, value];
215
+ }
216
+
217
+ /** Read and coerce own string keys in order, without invoking function data. */
218
+ export function sourceSpread(tag: string, value: unknown): SourceAttribute[] {
219
+ if (value == null) return [];
220
+ const object = Object(value) as Record<string, unknown>;
221
+ return Object.keys(object).map((name) =>
222
+ sourceAttribute(tag, name, object[name], true),
223
+ );
224
+ }
225
+
226
+ /** Compiler-facing intrinsic with ordered, already captured source attributes. */
227
+ export function sourceElement(
228
+ tag: string,
229
+ entries: ReadonlyArray<SourceAttribute>,
230
+ ...children: SSRChild[]
231
+ ): HTML {
232
+ return hAttributeEntries(tag, entries, ...children.map(sourceChild));
233
+ }