@interactive-inc/emdash-plugins 0.1.1 → 0.2.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 (51) hide show
  1. package/README.md +72 -4
  2. package/dist/builder/admin/get-editor-page-id.d.ts +6 -1
  3. package/dist/builder/admin/get-editor-page-id.d.ts.map +1 -1
  4. package/dist/builder/admin/get-editor-page-id.js +5 -4
  5. package/dist/builder/admin/get-editor-page-id.js.map +1 -1
  6. package/dist/builder/admin/get-page-preview.d.ts +25 -6
  7. package/dist/builder/admin/get-page-preview.d.ts.map +1 -1
  8. package/dist/builder/admin/get-page-preview.js +19 -5
  9. package/dist/builder/admin/get-page-preview.js.map +1 -1
  10. package/dist/builder/catalog.d.ts +3 -3
  11. package/dist/builder/catalog.d.ts.map +1 -1
  12. package/dist/builder/catalog.js +7 -4
  13. package/dist/builder/catalog.js.map +1 -1
  14. package/dist/builder/constants.d.ts +1 -1
  15. package/dist/builder/constants.js +1 -1
  16. package/dist/builder/middleware.d.ts.map +1 -1
  17. package/dist/builder/middleware.js +12 -4
  18. package/dist/builder/middleware.js.map +1 -1
  19. package/dist/builder/options.d.ts +8 -0
  20. package/dist/builder/options.d.ts.map +1 -1
  21. package/dist/builder/options.js +13 -2
  22. package/dist/builder/options.js.map +1 -1
  23. package/dist/builder/runtime.d.ts.map +1 -1
  24. package/dist/builder/runtime.js +53 -17
  25. package/dist/builder/runtime.js.map +1 -1
  26. package/dist/builder/server/load-page.d.ts +5 -1
  27. package/dist/builder/server/load-page.d.ts.map +1 -1
  28. package/dist/builder/server/load-page.js +14 -2
  29. package/dist/builder/server/load-page.js.map +1 -1
  30. package/dist/builder/server/page-response.d.ts +1 -0
  31. package/dist/builder/server/page-response.d.ts.map +1 -1
  32. package/dist/builder/server/page-response.js +4 -2
  33. package/dist/builder/server/page-response.js.map +1 -1
  34. package/dist/builder/site-path.d.ts +7 -0
  35. package/dist/builder/site-path.d.ts.map +1 -0
  36. package/dist/builder/site-path.js +21 -0
  37. package/dist/builder/site-path.js.map +1 -0
  38. package/package.json +1 -1
  39. package/src/builder/admin/get-editor-page-id.ts +8 -4
  40. package/src/builder/admin/get-page-preview.ts +22 -6
  41. package/src/builder/admin/page-preview-field.tsx +11 -5
  42. package/src/builder/catalog.ts +9 -5
  43. package/src/builder/constants.ts +1 -1
  44. package/src/builder/middleware.ts +11 -4
  45. package/src/builder/options.ts +12 -2
  46. package/src/builder/pages/[...slug].astro +4 -1
  47. package/src/builder/pages/preview/[id].astro +1 -1
  48. package/src/builder/runtime.ts +48 -17
  49. package/src/builder/server/load-page.ts +14 -2
  50. package/src/builder/server/page-response.ts +4 -2
  51. package/src/builder/site-path.ts +14 -0
@@ -6,17 +6,27 @@ import { pluginId, pluginVersion } from './constants.ts';
6
6
  import { resolveOptions, type BuilderOptions } from './options.ts';
7
7
  import { componentContract, type ComponentExtensions } from './extensions.ts';
8
8
  import { maxMotionElements, motionTokens } from './motion-tokens.ts';
9
+ import { isSitePath } from './site-path.ts';
9
10
 
10
11
  // EmDash's Contributor role is the lowest role that may read drafts.
11
12
  const contributorRole = 20;
12
13
  const documentInput = z.object({ document: z.unknown() });
13
- const pageInput = z.object({ id: z.string().min(1).max(200) });
14
+ const pageInput = z.object({ collection: z.string().regex(/^[a-z][a-z0-9_]*$/).max(60).optional(), id: z.string().min(1).max(200) });
15
+
16
+ /** The entry's own site path from its collection's URL pattern; null when the pattern cannot address a draft. */
17
+ function entryPath(pattern: string, entry: { id: string; slug: string | null }): string | null {
18
+ const filled = pattern.replaceAll('{slug}', encodeURIComponent(entry.slug || entry.id)).replaceAll('{id}', encodeURIComponent(entry.id)).replace(/\/{2,}/g, '/');
19
+ const path = filled.length > 1 && filled.endsWith('/') ? filled.slice(0, -1) : filled;
20
+ // Date tokens have no value before publication, and EmDash's own routes never show a page.
21
+ return isSitePath(path) ? path : null;
22
+ }
14
23
 
15
24
  export function createPlugin(input: BuilderOptions = {}, components: ComponentExtensions = {}) {
16
25
  const options = resolveOptions(input);
17
26
  const contract = componentContract(components);
18
27
  const validate = (document: unknown) => validateDocument(document, components);
19
28
  const guide = createPageGuide(options);
29
+ const fields = new Map(options.collections.map(item => [item.name, item.field]));
20
30
  const schemas = Object.fromEntries(Object.entries(contract.props).map(([name, props]) => [name, { props: z.toJSONSchema(props), ...(components[name] ? { description: components[name].description, container: !!components[name].container, motion: !!components[name].motion } : {}) }]));
21
31
  const motion = {
22
32
  enabled: options.motion,
@@ -25,7 +35,7 @@ export function createPlugin(input: BuilderOptions = {}, components: ComponentEx
25
35
  };
26
36
  return definePlugin({
27
37
  id: pluginId, version: pluginVersion,
28
- capabilities: ['content:read', 'content:write', 'hooks.content-policy:register'],
38
+ capabilities: ['content:read', 'content:write', 'schema:read', 'hooks.content-policy:register'],
29
39
  admin: {
30
40
  entry: '@interactive-inc/emdash-plugins/builder/admin',
31
41
  fieldWidgets: [
@@ -37,29 +47,37 @@ export function createPlugin(input: BuilderOptions = {}, components: ComponentEx
37
47
  'content:beforeSave': {
38
48
  errorPolicy: 'abort',
39
49
  handler: async event => {
40
- if (event.collection !== options.collection) return;
41
- if (!event.isNew && !Object.hasOwn(event.content, 'document')) return;
42
- const result = validate(event.content.document);
50
+ const field = fields.get(event.collection);
51
+ if (field === undefined) return;
52
+ if (!event.isNew && !Object.hasOwn(event.content, field)) return;
53
+ // An added collection's entry may have no page body yet; the default collection is nothing without one.
54
+ if (event.content[field] == null && event.collection !== options.collection) return;
55
+ const result = validate(event.content[field]);
43
56
  if (!result.success) throw new ContentSaveRejectedError(`Page JSON is invalid: ${result.errors.join('; ')}`);
44
- return { ...event.content, document: result.document };
57
+ return { ...event.content, [field]: result.document };
45
58
  },
46
59
  },
47
60
  'content:beforePublish': {
48
61
  errorPolicy: 'abort',
49
62
  handler: async event => {
50
- if (event.collection !== options.collection) return;
51
- const data = event.content.data;
52
- const document = data && typeof data === 'object' && 'document' in data ? data.document : event.content.document;
63
+ const field = fields.get(event.collection);
64
+ if (field === undefined) return;
65
+ const { content } = event;
66
+ const data = content.data && typeof content.data === 'object' && !Array.isArray(content.data) ? content.data as Record<string, unknown> : null;
67
+ // EmDash passes the stored entry: its fields sit in data, empty ones left out, next to id, type and status.
68
+ const isEntry = data !== null && typeof content.id === 'string';
69
+ const document = data && Object.hasOwn(data, field) ? data[field] : isEntry ? undefined : content[field];
70
+ if (document == null && event.collection !== options.collection) return;
53
71
  const result = validate(document);
54
72
  if (!result.success) return { cancel: true, reason: `Invalid page JSON: ${result.errors.join('; ')}` };
55
73
  },
56
74
  },
57
75
  },
58
76
  routes: {
59
- configuration: { permission: 'content:read', handler: async () => ({ collection: options.collection, previewPath: options.previewPath }) },
77
+ configuration: { permission: 'content:read', handler: async () => ({ collection: options.collection, previewPath: options.previewPath, collections: options.collections }) },
60
78
  catalog: {
61
79
  permission: 'content:read',
62
- handler: async () => ({ version: 1, components: { ...componentSchemas, ...Object.fromEntries(Object.entries(components).map(([name]) => [name, schemas[name].props])) }, descriptions: schemas, motion, guide, configuration: { collection: options.collection, basePath: options.basePath, previewPath: options.previewPath, homeSlug: options.homeSlug } }),
80
+ handler: async () => ({ version: 1, components: { ...componentSchemas, ...Object.fromEntries(Object.entries(components).map(([name]) => [name, schemas[name].props])) }, descriptions: schemas, motion, guide, configuration: { collection: options.collection, collections: options.collections, basePath: options.basePath, previewPath: options.previewPath, homeSlug: options.homeSlug } }),
63
81
  },
64
82
  validate: {
65
83
  permission: 'content:read',
@@ -72,21 +90,34 @@ export function createPlugin(input: BuilderOptions = {}, components: ComponentEx
72
90
  handler: async ctx => {
73
91
  // Defense in depth: plugin capabilities must not widen a caller's draft access.
74
92
  if (!ctx.user || ctx.user.role < contributorRole) throw new Error('Draft access is required');
75
- const page = await ctx.content?.get(options.collection, pageInput.parse(ctx.input).id);
93
+ const input = pageInput.parse(ctx.input);
94
+ const collection = input.collection ?? options.collection;
95
+ // Only configured collections: this route must not sign draft links for the rest of the site.
96
+ if (!fields.has(collection)) throw new Error(`Collection ${collection} is not configured for builder documents`);
97
+ const page = await ctx.content?.get(collection, input.id);
76
98
  if (!page) throw new Error('Page not found');
77
99
  const previewSecret = process.env.EMDASH_PREVIEW_SECRET;
78
100
  if (!previewSecret) throw new Error('Configure EMDASH_PREVIEW_SECRET before creating preview links');
79
- return {
80
- url: await getPreviewUrl({ collection: options.collection, id: page.id, secret: previewSecret, expiresIn: '15m', pathPattern: `${options.previewPath}/{id}` }),
81
- expiresIn: 900,
82
- };
101
+ let pathPattern = `${options.previewPath}/{id}`;
102
+ if (collection !== options.collection) {
103
+ // Other collections are drawn by the host's own route, at the entry's site URL.
104
+ const pattern = (await ctx.schema?.getCollection(collection))?.urlPattern;
105
+ if (!pattern) throw new Error(`Set a URL pattern on collection ${collection} before creating preview links`);
106
+ const path = entryPath(pattern, page);
107
+ if (!path) throw new Error(`The URL pattern of collection ${collection} must be a site path made of {slug} or {id}`);
108
+ pathPattern = path;
109
+ }
110
+ const url = await getPreviewUrl({ collection, id: page.id, secret: previewSecret, expiresIn: '15m', pathPattern });
111
+ // The signer parses the path as a URL; the link must still be the path that was checked.
112
+ if (collection !== options.collection && !url.startsWith(`${pathPattern}?_preview=`)) throw new Error(`The URL pattern of collection ${collection} must be a site path made of {slug} or {id}`);
113
+ return { url, expiresIn: 900 };
83
114
  },
84
115
  },
85
116
  },
86
117
  mcp: { tools: {
87
118
  catalog: { description: 'Read the supported site components, JSON property schemas, data bindings, theme tokens, and the page creation workflow.', route: 'catalog', input: z.object({}) },
88
119
  validate: { description: 'Validate a complete page document before saving it with EmDash content_create or content_update. Does not save or publish.', route: 'validate', input: documentInput },
89
- preview: { description: 'Create a 15-minute signed preview URL for one saved page. Use after saving a draft, before content_publish.', route: 'preview', input: pageInput },
120
+ preview: { description: `Create a 15-minute signed preview URL for one saved entry. Use after saving a draft, before content_publish. collection is one of ${options.collections.map(item => item.name).join(', ')}; omit it for ${options.collection}.`, route: 'preview', input: pageInput },
90
121
  } },
91
122
  });
92
123
  }
@@ -17,13 +17,25 @@ export type LoadedPage = {
17
17
  isPreview: boolean;
18
18
  };
19
19
 
20
- /** All reads go through EmDash's published-entry and scoped preview checks. */
20
+ /** The entry is visible but its document field is empty, as an added collection allows. */
21
+ export const emptyDocument = Symbol('emptyDocument');
22
+
23
+ /** A page always has a document; an entry without one is an error here. */
21
24
  export async function loadPage(identifier: string, input: BuilderOptions = {}, components: ComponentExtensions = {}): Promise<LoadedPage | null> {
25
+ const page = await readPage(identifier, input, components);
26
+ if (page === emptyDocument) throw new Error('Stored page JSON is invalid');
27
+ return page;
28
+ }
29
+
30
+ /** All reads go through EmDash's published-entry and scoped preview checks. */
31
+ export async function readPage(identifier: string, input: BuilderOptions = {}, components: ComponentExtensions = {}): Promise<LoadedPage | typeof emptyDocument | null> {
22
32
  const options = resolveOptions(input);
23
33
  const { entry, error, isPreview } = await getEmDashEntry(options.collection, identifier);
24
34
  if (error) throw new Error('Could not load page');
25
35
  if (!entry) return null;
26
- const validated = validateDocument(entry.data.document, components);
36
+ const stored = entry.data[options.collections[0]!.field];
37
+ if (stored == null) return emptyDocument;
38
+ const validated = validateDocument(stored, components);
27
39
  if (!validated.success) throw new Error('Stored page JSON is invalid');
28
40
  const document = validated.document;
29
41
  const title = typeof entry.data.title === 'string' ? entry.data.title : '';
@@ -1,12 +1,14 @@
1
- import { loadPage, type LoadedPage } from './load-page.ts';
1
+ import { emptyDocument, readPage, type LoadedPage } from './load-page.ts';
2
2
 
3
3
  import type { BuilderOptions } from '../options.ts';
4
4
  import type { ComponentExtensions } from '../extensions.ts';
5
5
 
6
+ /** Status 200 without a page: the entry is visible and has no document to draw. */
6
7
  type Result = { page: LoadedPage | null; status: number };
7
8
  export async function pageResponse(identifier: string, options: BuilderOptions = {}, components: ComponentExtensions = {}): Promise<Result> {
8
9
  try {
9
- const page = await loadPage(identifier, options, components);
10
+ const page = await readPage(identifier, options, components);
11
+ if (page === emptyDocument) return { page: null, status: 200 };
10
12
  return { page, status: page ? 200 : 404 };
11
13
  } catch (error) {
12
14
  console.error('[emdash-plugins/builder] Page resolution failed', error);
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A path of this site that a signed preview may point to. Every segment must mean the same thing to
3
+ * a URL parser and to the router, which decodes more than once: after one decoding nothing is left
4
+ * to decode, and no segment is a separator, a dot segment or EmDash's own prefix (wherever the site is mounted).
5
+ */
6
+ export function isSitePath(path: string): boolean {
7
+ if (!/^(?:\/[A-Za-z0-9._~!*'()%-]+)+$/.test(path)) return false;
8
+ return path.slice(1).split('/').every(segment => {
9
+ let decoded: string;
10
+ try { decoded = decodeURIComponent(segment); } catch { return false; }
11
+ // eslint-disable-next-line no-control-regex -- control characters are exactly what must not pass
12
+ return !/[%/\\\u0000-\u001f\u007f-\u009f]/.test(decoded) && decoded !== '.' && decoded !== '..' && decoded.toLowerCase() !== '_emdash';
13
+ });
14
+ }