@interactive-inc/emdash-plugins 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +201 -2
  3. package/dist/builder/admin/get-editor-page-id.d.ts +3 -0
  4. package/dist/builder/admin/get-editor-page-id.d.ts.map +1 -0
  5. package/dist/builder/admin/get-editor-page-id.js +8 -0
  6. package/dist/builder/admin/get-editor-page-id.js.map +1 -0
  7. package/dist/builder/admin/get-page-preview.d.ts +7 -0
  8. package/dist/builder/admin/get-page-preview.d.ts.map +1 -0
  9. package/dist/builder/admin/get-page-preview.js +27 -0
  10. package/dist/builder/admin/get-page-preview.js.map +1 -0
  11. package/dist/builder/astro.d.ts +5 -0
  12. package/dist/builder/astro.d.ts.map +1 -0
  13. package/dist/builder/astro.js +56 -0
  14. package/dist/builder/astro.js.map +1 -0
  15. package/dist/builder/catalog.d.ts +1232 -0
  16. package/dist/builder/catalog.d.ts.map +1 -0
  17. package/dist/builder/catalog.js +111 -0
  18. package/dist/builder/catalog.js.map +1 -0
  19. package/dist/builder/constants.d.ts +5 -0
  20. package/dist/builder/constants.d.ts.map +1 -0
  21. package/dist/builder/constants.js +5 -0
  22. package/dist/builder/constants.js.map +1 -0
  23. package/dist/builder/document.d.ts +74 -0
  24. package/dist/builder/document.d.ts.map +1 -0
  25. package/dist/builder/document.js +172 -0
  26. package/dist/builder/document.js.map +1 -0
  27. package/dist/builder/extensions.d.ts +32 -0
  28. package/dist/builder/extensions.d.ts.map +1 -0
  29. package/dist/builder/extensions.js +30 -0
  30. package/dist/builder/extensions.js.map +1 -0
  31. package/dist/builder/list-limits.d.ts +7 -0
  32. package/dist/builder/list-limits.d.ts.map +1 -0
  33. package/dist/builder/list-limits.js +8 -0
  34. package/dist/builder/list-limits.js.map +1 -0
  35. package/dist/builder/middleware.d.ts +2 -0
  36. package/dist/builder/middleware.d.ts.map +1 -0
  37. package/dist/builder/middleware.js +13 -0
  38. package/dist/builder/middleware.js.map +1 -0
  39. package/dist/builder/motion-directive.d.ts +14 -0
  40. package/dist/builder/motion-directive.d.ts.map +1 -0
  41. package/dist/builder/motion-directive.js +14 -0
  42. package/dist/builder/motion-directive.js.map +1 -0
  43. package/dist/builder/motion-tokens.d.ts +114 -0
  44. package/dist/builder/motion-tokens.d.ts.map +1 -0
  45. package/dist/builder/motion-tokens.js +25 -0
  46. package/dist/builder/motion-tokens.js.map +1 -0
  47. package/dist/builder/options.d.ts +14 -0
  48. package/dist/builder/options.d.ts.map +1 -0
  49. package/dist/builder/options.js +20 -0
  50. package/dist/builder/options.js.map +1 -0
  51. package/dist/builder/plugin.d.ts +6 -0
  52. package/dist/builder/plugin.d.ts.map +1 -0
  53. package/dist/builder/plugin.js +15 -0
  54. package/dist/builder/plugin.js.map +1 -0
  55. package/dist/builder/portable-text.d.ts +9 -0
  56. package/dist/builder/portable-text.d.ts.map +1 -0
  57. package/dist/builder/portable-text.js +58 -0
  58. package/dist/builder/portable-text.js.map +1 -0
  59. package/dist/builder/resolve-page.d.ts +28 -0
  60. package/dist/builder/resolve-page.d.ts.map +1 -0
  61. package/dist/builder/resolve-page.js +99 -0
  62. package/dist/builder/resolve-page.js.map +1 -0
  63. package/dist/builder/runtime.d.ts +4 -0
  64. package/dist/builder/runtime.d.ts.map +1 -0
  65. package/dist/builder/runtime.js +99 -0
  66. package/dist/builder/runtime.js.map +1 -0
  67. package/dist/builder/safe-url.d.ts +3 -0
  68. package/dist/builder/safe-url.d.ts.map +1 -0
  69. package/dist/builder/safe-url.js +21 -0
  70. package/dist/builder/safe-url.js.map +1 -0
  71. package/dist/builder/server/load-page.d.ts +18 -0
  72. package/dist/builder/server/load-page.d.ts.map +1 -0
  73. package/dist/builder/server/load-page.js +37 -0
  74. package/dist/builder/server/load-page.js.map +1 -0
  75. package/dist/builder/server/page-response.d.ts +10 -0
  76. package/dist/builder/server/page-response.d.ts.map +1 -0
  77. package/dist/builder/server/page-response.js +12 -0
  78. package/dist/builder/server/page-response.js.map +1 -0
  79. package/package.json +95 -3
  80. package/src/builder/PageDocument.astro +27 -0
  81. package/src/builder/PageShell.astro +15 -0
  82. package/src/builder/StaticPageShell.astro +11 -0
  83. package/src/builder/admin/get-editor-page-id.ts +8 -0
  84. package/src/builder/admin/get-page-preview.ts +28 -0
  85. package/src/builder/admin/managed-page-field.tsx +4 -0
  86. package/src/builder/admin/page-preview-field.tsx +53 -0
  87. package/src/builder/admin/page-preview-frame.tsx +67 -0
  88. package/src/builder/admin.tsx +5 -0
  89. package/src/builder/astro.ts +53 -0
  90. package/src/builder/catalog.ts +117 -0
  91. package/src/builder/constants.ts +4 -0
  92. package/src/builder/document.ts +137 -0
  93. package/src/builder/extensions.ts +46 -0
  94. package/src/builder/island.tsx +8 -0
  95. package/src/builder/list-limits.ts +10 -0
  96. package/src/builder/middleware.ts +10 -0
  97. package/src/builder/motion-directive.ts +19 -0
  98. package/src/builder/motion-site.tsx +15 -0
  99. package/src/builder/motion-tokens.ts +40 -0
  100. package/src/builder/options.ts +20 -0
  101. package/src/builder/pages/[...slug].astro +11 -0
  102. package/src/builder/pages/preview/[id].astro +14 -0
  103. package/src/builder/plugin.ts +17 -0
  104. package/src/builder/portable-content.tsx +17 -0
  105. package/src/builder/portable-text.ts +63 -0
  106. package/src/builder/renderer.tsx +16 -0
  107. package/src/builder/resolve-page.ts +90 -0
  108. package/src/builder/reveal.tsx +321 -0
  109. package/src/builder/runtime.ts +92 -0
  110. package/src/builder/safe-url.ts +13 -0
  111. package/src/builder/server/load-page.ts +45 -0
  112. package/src/builder/server/page-response.ts +15 -0
  113. package/src/builder/site-view.tsx +60 -0
  114. package/src/builder/styles/site.css +1 -0
  115. package/src/builder/virtual.d.ts +13 -0
@@ -0,0 +1,137 @@
1
+ import { z } from 'zod';
2
+ import { componentContract, type ComponentExtensions } from './extensions.ts';
3
+ import { listLength, maxListItems } from './list-limits.ts';
4
+ import { maxMotionElements } from './motion-tokens.ts';
5
+ import type { AuthoredMotion } from './catalog.ts';
6
+
7
+ const name = z.string().regex(/^[a-z][a-z0-9_]*$/).max(60);
8
+ const statePath = z.string().regex(/^\/(page|data)(\/[a-zA-Z0-9_-]+)*$/).max(300);
9
+ const binding = z.union([
10
+ z.strictObject({ $state: statePath }),
11
+ z.strictObject({ $item: z.string().regex(/^[a-zA-Z0-9_]+(\/[a-zA-Z0-9_-]+)*$/).max(300) }),
12
+ z.strictObject({ $template: z.string().max(2000) }),
13
+ ]);
14
+ const elementSchema = z.strictObject({
15
+ type: z.string().regex(/^[A-Z][a-zA-Z0-9]{0,59}$/),
16
+ props: z.record(z.string(), z.unknown()),
17
+ children: z.array(z.string().min(1).max(80)).max(100).optional(),
18
+ repeat: z.strictObject({ statePath: z.string().regex(/^\/data\/[a-z][a-z0-9_]*$/), key: z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/) }).optional(),
19
+ visible: z.union([z.boolean(), z.strictObject({ $state: statePath })]).optional(),
20
+ });
21
+ export const themeSchema = z.strictObject({
22
+ accent: z.string().regex(/^#[0-9a-fA-F]{6}$/).default('#d4ff5a'),
23
+ background: z.string().regex(/^#[0-9a-fA-F]{6}$/).default('#f7f8f2'),
24
+ foreground: z.string().regex(/^#[0-9a-fA-F]{6}$/).default('#18221a'),
25
+ font: z.enum(['sans', 'serif']).default('sans'),
26
+ radius: z.enum(['none', 'sm', 'lg']).default('lg'),
27
+ });
28
+ const documentSchema = z.strictObject({
29
+ version: z.literal(1),
30
+ spec: z.strictObject({ root: z.string().min(1).max(80), elements: z.record(z.string().regex(/^[\w-]{1,80}$/), elementSchema) }),
31
+ theme: themeSchema.optional(),
32
+ data: z.record(name, z.strictObject({
33
+ collection: name,
34
+ id: z.string().min(1).max(200).optional(),
35
+ limit: z.number().int().min(1).max(maxListItems).optional(),
36
+ })).refine(value => Object.keys(value).length <= 8, 'At most eight data queries are allowed').optional(),
37
+ });
38
+ export type PageDocument = z.infer<typeof documentSchema>;
39
+ export type Theme = z.infer<typeof themeSchema>;
40
+ export type PageState = { page: { title: string; description: string; slug: string }; data: Record<string, unknown> };
41
+ export type ValidationResult = { success: true; document: PageDocument } | { success: false; errors: string[] };
42
+
43
+ function isBinding(value: unknown): boolean {
44
+ return !!value && typeof value === 'object' && Object.keys(value).some(key => key.startsWith('$'));
45
+ }
46
+
47
+ /** Validates both the catalog contract and bounded tree structure before storage or rendering. */
48
+ export function validateDocument(input: unknown, extensions: ComponentExtensions = {}): ValidationResult {
49
+ const { props: componentProps, containers: containerNames, motion: motionNames } = componentContract(extensions);
50
+ let serialized: string;
51
+ try { serialized = JSON.stringify(input); } catch { return { success: false, errors: ['Document must be JSON'] }; }
52
+ if (!serialized || serialized.length > 200000) return { success: false, errors: ['Document exceeds 200 KB'] };
53
+ const parsed = documentSchema.safeParse(input);
54
+ if (!parsed.success) return { success: false, errors: parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`) };
55
+ const document = parsed.data;
56
+ const elements = document.spec.elements;
57
+ const errors: string[] = [];
58
+ const keys = Object.keys(elements);
59
+ if (keys.length > 200) errors.push('At most 200 elements are allowed');
60
+ for (const [key, element] of Object.entries(elements)) {
61
+ if (!Object.hasOwn(componentProps, element.type)) { errors.push(`${key}: unregistered component`); continue; }
62
+ const shape = componentProps[element.type]!.shape;
63
+ for (const prop of Object.keys(element.props)) {
64
+ if (prop === 'motion' && !Object.hasOwn(shape, prop)) errors.push(element.type === 'Section'
65
+ ? `${key}.motion: Section stays still; animate the elements inside it`
66
+ : `${key}.motion: ${element.type} does not support motion; animate an element inside or around it`);
67
+ else if (!Object.hasOwn(shape, prop)) errors.push(`${key}.${prop}: unknown property`);
68
+ }
69
+ for (const [prop, validator] of Object.entries(shape)) {
70
+ const value = element.props[prop];
71
+ if (prop === 'motion' && isBinding(value)) { errors.push(`${key}.motion: motion cannot be bound to data`); continue; }
72
+ const result = isBinding(value) ? binding.safeParse(value) : (validator as z.ZodType).safeParse(value);
73
+ if (!result.success) {
74
+ const issue = result.error.issues[0];
75
+ errors.push(`${[key, prop, ...(issue?.path ?? [])].join('.')}: ${issue?.message}`);
76
+ }
77
+ }
78
+ if ((element.children?.length || element.repeat) && !containerNames.has(element.type)) errors.push(`${key}: only containers may have children or repeat`);
79
+ if (element.repeat) {
80
+ const source = element.repeat.statePath.slice(6);
81
+ if (!Object.hasOwn(document.data ?? {}, source)) errors.push(`${key}: repeat data source is missing`);
82
+ // A query with id loads one entry, which a repeat cannot list.
83
+ else if (document.data![source]!.id) errors.push(`${key}: repeat needs a list query without id`);
84
+ }
85
+ }
86
+ const visited = new Set<string>();
87
+ const walk = (key: string, depth: number, repeated: boolean) => {
88
+ if (depth > 24) { errors.push('Tree depth exceeds 24'); return; }
89
+ if (visited.has(key)) { errors.push(`${key}: cycle or shared child`); return; }
90
+ visited.add(key);
91
+ const element = Object.hasOwn(elements, key) ? elements[key] : undefined;
92
+ if (!element) { errors.push(`${key}: missing element`); return; }
93
+ if (repeated && element.repeat) errors.push(`${key}: nested repeats are not supported`);
94
+ const inRepeat = repeated || !!element.repeat;
95
+ for (const value of Object.values(element.props)) {
96
+ if (value && typeof value === 'object' && '$item' in value && !repeated) errors.push(`${key}: $item requires repeat`);
97
+ }
98
+ for (const child of element.children ?? []) walk(child, depth + 1, inRepeat);
99
+ };
100
+ walk(document.spec.root, 0, false);
101
+ for (const key of keys) if (!visited.has(key)) errors.push(`${key}: unreachable element`);
102
+ if (!errors.length) errors.push(...motionErrors(document, motionNames));
103
+ return errors.length ? { success: false, errors: errors.slice(0, 30) } : { success: true, document };
104
+ }
105
+
106
+ /**
107
+ * One element moves at a time: nothing animates inside a moving element, no Section
108
+ * sits inside one, and the children of a staggering container move with it instead
109
+ * of on their own. The limit counts what moves on the page, so every repeated copy counts.
110
+ */
111
+ function motionErrors(document: PageDocument, motionNames: Set<string>): string[] {
112
+ const errors: string[] = [];
113
+ let count = 0;
114
+ // `moving` is the element that moves this subtree and, for a staggered child, the container whose stagger moves it.
115
+ const walk = (key: string, copies: number, moving?: { key: string; by?: string }, staggering?: string) => {
116
+ const element = document.spec.elements[key]!;
117
+ const motion = element.props.motion as AuthoredMotion | undefined;
118
+ if (moving && element.type === 'Section') errors.push(`${key}: Section stays still, so ${moving.key} cannot move it; put motion on elements inside the Section`);
119
+ if (staggering) {
120
+ count += copies;
121
+ if (motion) errors.push(`${key}.motion: ${staggering} already staggers its children; remove this motion`);
122
+ else if (!motionNames.has(element.type)) errors.push(`${key}: ${element.type} cannot move, so ${staggering} cannot stagger it`);
123
+ } else if (motion && moving) errors.push(moving.by
124
+ ? `${key}.motion: ${moving.key} already moves with ${moving.by}'s stagger; remove this motion or the stagger on ${moving.by}`
125
+ : `${key}.motion: ${moving.key} already moves this element; keep motion on only one of them`);
126
+ else if (motion && !motion.stagger) count += copies;
127
+ if (motion?.stagger && !element.children?.length) errors.push(`${key}.motion: stagger needs children`);
128
+ const movesWith = moving ?? (staggering ? { key, by: staggering } : motion && !motion.stagger ? { key } : undefined);
129
+ const group = !movesWith && motion?.stagger ? key : undefined;
130
+ // Nested repeats are rejected earlier, so a copy count is at most one list long.
131
+ const items = element.repeat ? listLength(document, element.repeat.statePath.slice(6)) : 1;
132
+ for (const child of element.children ?? []) walk(child, copies * items, movesWith, group);
133
+ };
134
+ walk(document.spec.root, 1);
135
+ if (count > maxMotionElements) errors.push(`At most ${maxMotionElements} elements may move; this page moves up to ${count}, counting each staggered child and each repeated copy`);
136
+ return errors;
137
+ }
@@ -0,0 +1,46 @@
1
+ import type { ComponentType, ReactNode } from 'react';
2
+ import { z } from 'zod';
3
+ import { componentProps, containerNames, motionSchema } from './catalog.ts';
4
+ import type { RootComponent } from './motion-tokens.ts';
5
+
6
+ export type ComponentDefinition = {
7
+ props: z.ZodObject;
8
+ component: ComponentType<any>;
9
+ description: string;
10
+ container?: boolean;
11
+ /** The component renders its outermost element through `Root`, so documents may give it props.motion. */
12
+ motion?: boolean;
13
+ };
14
+ export type ComponentExtensions = Record<string, ComponentDefinition>;
15
+ export type { RootComponent, RootProps } from './motion-tokens.ts';
16
+ export function defineComponent<T extends z.ZodObject>(definition: {
17
+ props: T;
18
+ component: ComponentType<{ props: z.infer<T>; children?: ReactNode; Root: RootComponent }>;
19
+ description: string;
20
+ container?: boolean;
21
+ motion?: boolean;
22
+ }): ComponentDefinition { return definition; }
23
+
24
+ const reservedProps = ['style', 'dangerouslySetInnerHTML', 'innerHTML', 'children', 'motion', '__proto__', 'constructor', 'prototype'];
25
+
26
+ /** Host code alone can register components; documents cannot add executable code. */
27
+ export function componentContract(extensions: ComponentExtensions = {}) {
28
+ const props: Record<string, z.ZodObject> = { ...componentProps };
29
+ const containers = new Set(containerNames);
30
+ if (Object.keys(extensions).length > 100) throw new Error('At most 100 custom components are allowed');
31
+ for (const [name, definition] of Object.entries(extensions)) {
32
+ if (!/^[A-Z][a-zA-Z0-9]{0,59}$/.test(name) || Object.hasOwn(componentProps, name) || ['Object', 'Function'].includes(name)) throw new Error(`Invalid or reserved component name: ${name}`);
33
+ if (!(definition.props instanceof z.ZodObject) || typeof definition.component !== 'function' || !definition.description || !['boolean', 'undefined'].includes(typeof definition.motion)) throw new Error(`Invalid component definition: ${name}`);
34
+ for (const prop of Object.keys(definition.props.shape)) {
35
+ if (/^on/i.test(prop) || reservedProps.includes(prop) || prop.startsWith('$')) throw new Error(`Unsafe component property: ${name}.${prop}`);
36
+ }
37
+ props[name] = definition.motion ? definition.props.extend({ motion: motionSchema.optional() }) : definition.props;
38
+ z.toJSONSchema(props[name]); // MCP must be able to describe every registered schema.
39
+ if (definition.container) containers.add(name);
40
+ }
41
+ // A component moves exactly when its schema lists motion, as validation checks.
42
+ const motion = new Set(Object.keys(props).filter(name => Object.hasOwn(props[name]!.shape, 'motion')));
43
+ return { props, containers, motion };
44
+ }
45
+
46
+ export { safeUrl } from './safe-url.ts';
@@ -0,0 +1,8 @@
1
+ import components from 'virtual:emdash-plugins/builder/extensions';
2
+ import { MotionSite } from './motion-site.tsx';
3
+ import type { ResolvedView } from './resolve-page.ts';
4
+
5
+ /** Hydrated by PageShell. Host components come from the integration, never through island props. */
6
+ export default function SiteIsland({ view }: { view: ResolvedView }) {
7
+ return <MotionSite view={view} components={components} />;
8
+ }
@@ -0,0 +1,10 @@
1
+ import type { PageDocument } from './document.ts';
2
+
3
+ /** A list query returns at most this many entries, and this many when it sets no limit. */
4
+ export const maxListItems = 24;
5
+ export const defaultListItems = 6;
6
+
7
+ /** How many copies a repeat over this data source renders at most. */
8
+ export function listLength(document: PageDocument, source: string): number {
9
+ return document.data?.[source]?.limit ?? defaultListItems;
10
+ }
@@ -0,0 +1,10 @@
1
+ import { defineMiddleware } from 'astro:middleware';
2
+
3
+ export const onRequest = defineMiddleware(async (_context, next) => {
4
+ const response = await next();
5
+ if (!response.headers.has('X-Content-Type-Options')) response.headers.set('X-Content-Type-Options', 'nosniff');
6
+ if (!response.headers.has('Referrer-Policy')) response.headers.set('Referrer-Policy', 'no-referrer');
7
+ // The admin can embed its own site preview; other sites cannot frame this app.
8
+ if (!response.headers.has('Content-Security-Policy')) response.headers.set('Content-Security-Policy', "frame-ancestors 'self'; object-src 'none'; base-uri 'self'");
9
+ return response;
10
+ });
@@ -0,0 +1,19 @@
1
+ import type { ClientDirective } from 'astro';
2
+
3
+ declare module 'astro' {
4
+ interface AstroClientDirectives { 'client:builder-motion'?: boolean }
5
+ }
6
+
7
+ /**
8
+ * Hydrates the page island at once. Without IntersectionObserver, or when the visitor prefers
9
+ * reduced motion at load, the island never starts and downloads nothing: `data-motion-static`
10
+ * keeps the page final for this visit, even if the preference changes later.
11
+ */
12
+ const builderMotion: ClientDirective = (load, _options, island) => {
13
+ if (!('IntersectionObserver' in window) || matchMedia('(prefers-reduced-motion: reduce)').matches) {
14
+ island.setAttribute('data-motion-static', '');
15
+ return;
16
+ }
17
+ void load().then(run => run());
18
+ };
19
+ export default builderMotion;
@@ -0,0 +1,15 @@
1
+ import { useState } from 'react';
2
+ import { LazyMotion, domAnimation } from 'motion/react';
3
+ import { MotionStage, StageContext } from './reveal.tsx';
4
+ import { ResolvedSite } from './site-view.tsx';
5
+ import type { ComponentExtensions } from './extensions.ts';
6
+ import type { ResolvedView } from './resolve-page.ts';
7
+
8
+ type Props = { view: ResolvedView; components: ComponentExtensions };
9
+ /** The page island: the server renders each moving element transparent where it ends up, and the browser plays its entrance. */
10
+ export function MotionSite({ view, components }: Props) {
11
+ const [stage] = useState(() => new MotionStage());
12
+ return <StageContext value={stage}>
13
+ <LazyMotion features={domAnimation}><ResolvedSite view={view} components={components} /></LazyMotion>
14
+ </StageContext>;
15
+ }
@@ -0,0 +1,40 @@
1
+ import type { ComponentPropsWithoutRef, ComponentType, ReactNode } from 'react';
2
+
3
+ /**
4
+ * Every motion value a document can choose. Documents name a token; seconds, pixels and easing
5
+ * exist only here. Change them together with the README motion table and tests. An effect that
6
+ * animates anything besides opacity and transform also needs the final-state rules in site.css.
7
+ */
8
+ export const motionTokens = {
9
+ // Names follow the direction of travel: fade-up moves upward into place.
10
+ effect: {
11
+ fade: { from: { opacity: 0 }, to: { opacity: 1 } },
12
+ 'fade-up': { from: { opacity: 0, y: 24 }, to: { opacity: 1, y: 0 } },
13
+ 'fade-down': { from: { opacity: 0, y: -24 }, to: { opacity: 1, y: 0 } },
14
+ 'fade-left': { from: { opacity: 0, x: 32 }, to: { opacity: 1, x: 0 } },
15
+ 'fade-right': { from: { opacity: 0, x: -32 }, to: { opacity: 1, x: 0 } },
16
+ 'zoom-in': { from: { opacity: 0, scale: 0.94 }, to: { opacity: 1, scale: 1 } },
17
+ },
18
+ delay: { none: 0, short: 0.1, medium: 0.2, long: 0.4 },
19
+ duration: { fast: 0.3, normal: 0.5, slow: 0.8 },
20
+ stagger: { short: 0.05, medium: 0.08, long: 0.12 },
21
+ maxStaggerOffset: 0.6,
22
+ ease: [0.22, 1, 0.36, 1] as [number, number, number, number],
23
+ } as const;
24
+
25
+ export const maxMotionElements = 40;
26
+
27
+ export type MotionEffect = keyof typeof motionTokens.effect;
28
+ export type MotionDelay = keyof typeof motionTokens.delay;
29
+ export type MotionDuration = keyof typeof motionTokens.duration;
30
+ export type MotionStagger = keyof typeof motionTokens.stagger;
31
+ /** Motion after page resolution: defaults filled in; staggered children carry their group. */
32
+ export type ResolvedMotion = { effect: MotionEffect; delay: MotionDelay; duration: MotionDuration; stagger?: MotionStagger; group?: string };
33
+
34
+ /** Tags a host component may render through `Root`. */
35
+ export const rootTags = ['div', 'section', 'article', 'aside', 'header', 'footer', 'figure', 'blockquote', 'ul', 'ol', 'li', 'p', 'span', 'a', 'img', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;
36
+ export type RootTag = (typeof rootTags)[number];
37
+ export type MotionTag = RootTag | 'h1' | 'hr';
38
+ export type RootProps = { as?: RootTag; children?: ReactNode } & Omit<ComponentPropsWithoutRef<'div'>, 'children'> & { href?: string; src?: string; alt?: string };
39
+ /** Host components render their outermost element through Root so motion animates it without a wrapper. */
40
+ export type RootComponent = ComponentType<RootProps>;
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+
3
+ const prefix = z.string().regex(/^(?:\/[a-zA-Z0-9_-]+)*$/);
4
+ const optionsSchema = z.strictObject({
5
+ collection: z.string().regex(/^[a-z][a-z0-9_]*$/).max(60).default('pages'),
6
+ basePath: prefix.default(''),
7
+ previewPath: prefix.refine(value => value.length > 0 && !value.startsWith('/_emdash'), 'Preview path must be outside EmDash').default('/preview'),
8
+ homeSlug: z.string().regex(/^[a-zA-Z0-9_-]+$/).max(200).default('home'),
9
+ componentsModule: z.string().min(1).optional(),
10
+ // false keeps every page script-free and keeps componentsModule out of the browser bundle.
11
+ motion: z.boolean().default(true),
12
+ });
13
+ export type BuilderOptions = z.input<typeof optionsSchema>;
14
+ export type ResolvedOptions = z.output<typeof optionsSchema>;
15
+ export function resolveOptions(options: BuilderOptions = {}): ResolvedOptions {
16
+ const result = optionsSchema.parse(options);
17
+ if (result.basePath.startsWith('/_emdash')) throw new Error('Page routes must be outside EmDash');
18
+ if (result.basePath === result.previewPath || result.basePath.startsWith(`${result.previewPath}/`)) throw new Error('Page and preview routes overlap');
19
+ return result;
20
+ }
@@ -0,0 +1,11 @@
1
+ ---
2
+ import options from 'virtual:emdash-plugins/builder/config';
3
+ import components from 'virtual:emdash-plugins/builder/extensions';
4
+ import PageShell from 'virtual:emdash-plugins/builder/page-shell';
5
+ import { pageResponse } from '@interactive-inc/emdash-plugins/builder/server';
6
+ const slug = Astro.params.slug || options.homeSlug;
7
+ const { page, status } = await pageResponse(slug, options, components);
8
+ Astro.response.status = status;
9
+ Astro.response.headers.set('Cache-Control', 'private, no-store');
10
+ ---
11
+ <PageShell page={page} status={status} />
@@ -0,0 +1,14 @@
1
+ ---
2
+ import options from 'virtual:emdash-plugins/builder/config';
3
+ import components from 'virtual:emdash-plugins/builder/extensions';
4
+ import PageShell from 'virtual:emdash-plugins/builder/page-shell';
5
+ import { pageResponse } from '@interactive-inc/emdash-plugins/builder/server';
6
+ const result = await pageResponse(Astro.params.id ?? '', options, components);
7
+ // A preview URL must actually authorize this entry; a guessed ID cannot act as a draft URL.
8
+ const page = result.page?.isPreview ? result.page : null;
9
+ const status = page ? 200 : result.status === 503 ? 503 : 404;
10
+ Astro.response.status = status;
11
+ Astro.response.headers.set('Cache-Control', 'private, no-store');
12
+ Astro.response.headers.set('X-Robots-Tag', 'noindex, nofollow');
13
+ ---
14
+ <PageShell page={page} status={status} previewRoute />
@@ -0,0 +1,17 @@
1
+ import type { PluginDescriptor } from 'emdash';
2
+ import { pluginId, pluginVersion } from './constants.ts';
3
+ import { resolveOptions, type BuilderOptions } from './options.ts';
4
+ export type { BuilderOptions } from './options.ts';
5
+
6
+ /** Only serializable metadata is evaluated while Astro loads its configuration. */
7
+ export function builderPlugin(options: BuilderOptions = {}): PluginDescriptor {
8
+ const resolved = resolveOptions(options);
9
+ return {
10
+ id: pluginId, version: pluginVersion, format: 'native',
11
+ // Host components need builderIntegration()'s virtual module; with the integration registered, it also
12
+ // serves the plain runtime through a check that both were given the same options.
13
+ entrypoint: resolved.componentsModule ? 'virtual:emdash-plugins/builder/runtime' : '@interactive-inc/emdash-plugins/builder/runtime',
14
+ options: resolved,
15
+ adminEntry: '@interactive-inc/emdash-plugins/builder/admin',
16
+ };
17
+ }
@@ -0,0 +1,17 @@
1
+ import { PortableText } from '@portabletext/react';
2
+ import type { TypedObject } from '@portabletext/types';
3
+
4
+ // A paragraph cannot hold a figure: the browser would close it early and hydration would not match.
5
+ function ContentImage({ value, isInline }: { value: { src: string; alt?: string; caption?: string }; isInline: boolean }) {
6
+ const image = <img src={value.src} alt={value.alt ?? ''} loading="lazy" decoding="async" />;
7
+ return isInline ? image : <figure>{image}{value.caption && <figcaption>{value.caption}</figcaption>}</figure>;
8
+ }
9
+
10
+ /** Renders rich text as projectPortableText left it: link hrefs and image sources are already safe. */
11
+ export function PortableContent({ value }: { value: TypedObject[] }) {
12
+ return <PortableText value={value} components={{
13
+ marks: { link: ({ value, children }) => value?.href ? <a href={value.href}>{children}</a> : <span>{children}</span> },
14
+ types: { image: ContentImage, 'builder-omitted': () => null },
15
+ unknownType: () => null,
16
+ }} />;
17
+ }
@@ -0,0 +1,63 @@
1
+ import { z } from 'zod';
2
+ import { safeUrl } from './safe-url.ts';
3
+
4
+ const portableImageSchema = z.object({
5
+ asset: z.object({ _ref: z.string().min(1).max(300).optional(), url: z.string().optional() }),
6
+ alt: z.string().optional(),
7
+ caption: z.string().optional(),
8
+ });
9
+
10
+ type Item = Record<string, unknown>;
11
+ const isItem = (value: unknown): value is Item => !!value && typeof value === 'object' && !Array.isArray(value);
12
+ const keyOf = (value: Item) => typeof value._key === 'string' ? { _key: value._key } : {};
13
+ const strings = (value: Item, names: string[]) => Object.fromEntries(names.filter(name => typeof value[name] === 'string').map(name => [name, value[name]]));
14
+
15
+ /**
16
+ * A span's distinct marks with at most one link that renders an anchor. Two would nest <a> elements,
17
+ * which the browser splits apart, so the island's hydration would not match the server markup.
18
+ */
19
+ function spanMarks(marks: unknown, anchors: Set<string>): string[] {
20
+ if (!Array.isArray(marks)) return [];
21
+ let anchored = false;
22
+ return [...new Set(marks.filter(mark => typeof mark === 'string'))].filter(mark => !anchors.has(mark) || (!anchored && (anchored = true)));
23
+ }
24
+
25
+ /**
26
+ * Styles PortableContent renders. Any other falls back to <p>, which a list item wraps around its nested
27
+ * list; the browser splits a list out of a paragraph, so the island's hydration would not match.
28
+ */
29
+ const blockStyles = new Set(['normal', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote']);
30
+
31
+ function projectBlock(block: Item) {
32
+ const markDefs = Array.isArray(block.markDefs) ? block.markDefs.filter(isItem).map(definition => ({
33
+ _type: String(definition._type), ...keyOf(definition),
34
+ ...(definition._type === 'link' && safeUrl(definition.href) ? { href: definition.href } : {}),
35
+ })) : [];
36
+ const anchors = new Set(markDefs.flatMap(definition => 'href' in definition && typeof definition._key === 'string' ? [definition._key] : []));
37
+ const children = Array.isArray(block.children) ? block.children.filter(isItem).map(child => child._type === 'span'
38
+ ? { _type: 'span', ...keyOf(child), text: typeof child.text === 'string' ? child.text : '', marks: spanMarks(child.marks, anchors) }
39
+ : child._type === 'image' ? projectImage(child, true) : { _type: 'builder-omitted', ...keyOf(child) }) : [];
40
+ return { _type: 'block', ...keyOf(block), ...(blockStyles.has(block.style as string) ? { style: block.style } : {}), ...strings(block, ['listItem']), ...(typeof block.level === 'number' ? { level: block.level } : {}), markDefs, children };
41
+ }
42
+
43
+ /** An inline image sits inside a paragraph, which cannot hold a caption, so it keeps none. */
44
+ function projectImage(block: Item, inline = false) {
45
+ const image = portableImageSchema.safeParse(block);
46
+ const asset = image.data?.asset;
47
+ // An unsafe url renders nothing; it never falls back to _ref.
48
+ const src = asset && safeUrl(asset.url ?? (asset._ref ? `/_emdash/api/media/file/${encodeURIComponent(asset._ref)}` : ''), true);
49
+ if (!src) return { _type: 'builder-omitted', ...keyOf(block) };
50
+ const { alt, caption } = image.data!;
51
+ return { _type: 'image', ...keyOf(block), src, ...(alt !== undefined ? { alt } : {}), ...(caption !== undefined && !inline ? { caption } : {}) };
52
+ }
53
+
54
+ /**
55
+ * Keeps only what the renderer displays, so rich text sent to the browser never
56
+ * carries hidden fields or unknown block content. Link hrefs and image sources leave
57
+ * here display-ready; anything that would render nothing keeps only its position.
58
+ */
59
+ export function projectPortableText(value: unknown[]): Item[] {
60
+ return value.filter(isItem).map(block => block._type === 'block' ? projectBlock(block)
61
+ : block._type === 'image' ? projectImage(block)
62
+ : { _type: 'builder-omitted', ...keyOf(block) });
63
+ }
@@ -0,0 +1,16 @@
1
+ import { resolvePage, type ResolvedView } from './resolve-page.ts';
2
+ import { ResolvedSite } from './site-view.tsx';
3
+ import type { ComponentExtensions } from './extensions.ts';
4
+ import type { PageDocument, PageState } from './document.ts';
5
+
6
+ type Props = ({ view: ResolvedView } | { document: PageDocument; state: PageState }) & { components?: ComponentExtensions };
7
+
8
+ /**
9
+ * Server-renders a page for custom routes: pageResponse()'s `page.view`, or a document with
10
+ * the host's own state, resolved and revalidated here. Motion plays only in PageShell's
11
+ * island, so this always renders the final static page.
12
+ */
13
+ export function SiteRenderer({ components = {}, ...input }: Props) {
14
+ const view = 'view' in input ? input.view : resolvePage(input.document, input.state, components, { motion: false });
15
+ return <ResolvedSite view={view} components={components} />;
16
+ }
@@ -0,0 +1,90 @@
1
+ import { evaluateVisibility, resolvePropValue } from '@json-render/core';
2
+ import { componentContract, type ComponentExtensions } from './extensions.ts';
3
+ import { themeSchema, type PageDocument, type PageState } from './document.ts';
4
+ import { listLength } from './list-limits.ts';
5
+ import { projectPortableText } from './portable-text.ts';
6
+ import { safeUrl } from './safe-url.ts';
7
+ import type { AuthoredMotion } from './catalog.ts';
8
+ import type { ResolvedMotion } from './motion-tokens.ts';
9
+
10
+ export type ResolvedElement = { type: string; props: Record<string, unknown>; children?: string[] };
11
+ /** Exactly what a page renders: literal props only, no state, bindings, repeats or hidden elements. */
12
+ export type ResolvedView = { spec: { root: string; elements: Record<string, ResolvedElement> }; theme: Record<string, string>; motion: boolean };
13
+ type Options = { motion?: boolean };
14
+
15
+ // json-render resolves any `$`-keyed object again while rendering; resolved data must stay literal.
16
+ // toJSON first, as JSON does, so EmDash's Dates arrive as ISO strings instead of empty objects.
17
+ function literal(value: unknown): unknown {
18
+ const json = typeof (value as { toJSON?: unknown } | null | undefined)?.toJSON === 'function' ? (value as { toJSON(): unknown }).toJSON() : value;
19
+ if (Array.isArray(json)) return json.map(literal);
20
+ if (!json || typeof json !== 'object') return json;
21
+ return Object.fromEntries(Object.entries(json).filter(([key]) => !key.startsWith('$')).map(([key, item]) => [key, literal(item)]));
22
+ }
23
+
24
+ function displayed(type: string, props: Record<string, unknown>): Record<string, unknown> {
25
+ if (type === 'Link') return { ...props, href: safeUrl(props.href) ?? '' };
26
+ if (type === 'Image') return { ...props, src: safeUrl(props.src, true) ?? '' };
27
+ if (type === 'PortableText') return { ...props, value: projectPortableText(props.value as unknown[]) };
28
+ return props;
29
+ }
30
+
31
+ function themeStyle(document: PageDocument): Record<string, string> {
32
+ const theme = themeSchema.parse(document.theme ?? {});
33
+ return {
34
+ '--accent': theme.accent,
35
+ '--background': theme.background,
36
+ '--foreground': theme.foreground,
37
+ '--radius': { none: '0', sm: '0.5rem', lg: '1.5rem' }[theme.radius],
38
+ fontFamily: theme.font === 'serif' ? 'Georgia, "Noto Serif JP", serif' : 'Inter, "Noto Sans JP", system-ui, sans-serif',
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Applies data bindings, visibility and repeats on the server, then revalidates every
44
+ * bound value against the component contract and keeps only the fields it declares, so
45
+ * data cannot inject props. URLs and rich text leave here display-ready. The result is
46
+ * both what the server renders and the only page data sent to the browser.
47
+ */
48
+ export function resolvePage(document: PageDocument, state: PageState, extensions: ComponentExtensions = {}, { motion = true }: Options = {}): ResolvedView {
49
+ const { props: schemas } = componentContract(extensions);
50
+ const elements: Record<string, ResolvedElement> = {};
51
+ const errors: string[] = [];
52
+ const visit = (key: string, item: unknown, suffix: string, staggered?: ResolvedMotion): string | null => {
53
+ const element = document.spec.elements[key];
54
+ const context = { stateModel: state, repeatItem: item };
55
+ if (!element || !evaluateVisibility(element.visible, context)) return null;
56
+ const resolved = Object.fromEntries(Object.entries(element.props).map(([name, value]) => [name, name === 'motion' ? value : resolvePropValue(value, context)]));
57
+ // The parsed value, not the bound one: undeclared fields of nested objects are dropped before they reach the browser.
58
+ const parsed = schemas[element.type]?.strict().safeParse(resolved);
59
+ if (!parsed?.success) { errors.push(`${key}: bound data does not match ${element.type}`); return null; }
60
+ const id = `${key}${suffix}`;
61
+ const { motion: authored, ...props } = parsed.data as Record<string, unknown> & { motion?: AuthoredMotion };
62
+ const shown = literal(displayed(element.type, props)) as Record<string, unknown>;
63
+ // An Image without a safe src renders nothing, so neither it nor its alt reaches the browser.
64
+ if (element.type === 'Image' && !shown.src) return null;
65
+ const filled = motion && authored ? { effect: authored.effect, delay: authored.delay ?? 'none', duration: authored.duration ?? 'normal' } as const : undefined;
66
+ const group = filled && authored?.stagger ? { ...filled, stagger: authored.stagger, group: id } : undefined;
67
+ const own = staggered ?? (group ? undefined : filled);
68
+ const children: string[] = [];
69
+ const add = (child: string, childItem: unknown, childSuffix: string) => { const resolvedChild = visit(child, childItem, childSuffix, group); if (resolvedChild) children.push(resolvedChild); };
70
+ if (element.repeat) {
71
+ const source = element.repeat.statePath.slice(6);
72
+ const values = state.data[source];
73
+ if (!Array.isArray(values)) { errors.push(`${key}: repeat source must be a list`); return null; }
74
+ // Nested repeats are rejected by validation, so one index suffix keeps expanded IDs unique.
75
+ // With motion, never more copies than the query asks for, which is what the motion limit counts.
76
+ (motion ? values.slice(0, listLength(document, source)) : values).forEach((value, index) => { for (const child of element.children ?? []) add(child, value, `~${index}`); });
77
+ } else for (const child of element.children ?? []) add(child, item, suffix);
78
+ elements[id] = { type: element.type, props: { ...shown, ...(own ? { motion: own } : {}) }, ...(element.children || element.repeat ? { children } : {}) };
79
+ return id;
80
+ };
81
+ const root = visit(document.spec.root, undefined, '');
82
+ if (errors.length) throw new Error(errors.join('; '));
83
+ // A plain JSON copy is what the browser receives, so the server renders the same value.
84
+ const view: ResolvedView = JSON.parse(JSON.stringify({
85
+ spec: { root: root ?? document.spec.root, elements },
86
+ theme: themeStyle(document),
87
+ motion: Object.values(elements).some(element => element.props.motion),
88
+ }));
89
+ return view;
90
+ }