@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,15 +6,24 @@ import { pluginId, pluginVersion } from "./constants.js";
6
6
  import { resolveOptions } from "./options.js";
7
7
  import { componentContract } from "./extensions.js";
8
8
  import { maxMotionElements, motionTokens } from "./motion-tokens.js";
9
+ import { isSitePath } from "./site-path.js";
9
10
  // EmDash's Contributor role is the lowest role that may read drafts.
10
11
  const contributorRole = 20;
11
12
  const documentInput = z.object({ document: z.unknown() });
12
- const pageInput = z.object({ id: z.string().min(1).max(200) });
13
+ const pageInput = z.object({ collection: z.string().regex(/^[a-z][a-z0-9_]*$/).max(60).optional(), id: z.string().min(1).max(200) });
14
+ /** The entry's own site path from its collection's URL pattern; null when the pattern cannot address a draft. */
15
+ function entryPath(pattern, entry) {
16
+ const filled = pattern.replaceAll('{slug}', encodeURIComponent(entry.slug || entry.id)).replaceAll('{id}', encodeURIComponent(entry.id)).replace(/\/{2,}/g, '/');
17
+ const path = filled.length > 1 && filled.endsWith('/') ? filled.slice(0, -1) : filled;
18
+ // Date tokens have no value before publication, and EmDash's own routes never show a page.
19
+ return isSitePath(path) ? path : null;
20
+ }
13
21
  export function createPlugin(input = {}, components = {}) {
14
22
  const options = resolveOptions(input);
15
23
  const contract = componentContract(components);
16
24
  const validate = (document) => validateDocument(document, components);
17
25
  const guide = createPageGuide(options);
26
+ const fields = new Map(options.collections.map(item => [item.name, item.field]));
18
27
  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 } : {}) }]));
19
28
  const motion = {
20
29
  enabled: options.motion,
@@ -23,7 +32,7 @@ export function createPlugin(input = {}, components = {}) {
23
32
  };
24
33
  return definePlugin({
25
34
  id: pluginId, version: pluginVersion,
26
- capabilities: ['content:read', 'content:write', 'hooks.content-policy:register'],
35
+ capabilities: ['content:read', 'content:write', 'schema:read', 'hooks.content-policy:register'],
27
36
  admin: {
28
37
  entry: '@interactive-inc/emdash-plugins/builder/admin',
29
38
  fieldWidgets: [
@@ -35,23 +44,33 @@ export function createPlugin(input = {}, components = {}) {
35
44
  'content:beforeSave': {
36
45
  errorPolicy: 'abort',
37
46
  handler: async (event) => {
38
- if (event.collection !== options.collection)
47
+ const field = fields.get(event.collection);
48
+ if (field === undefined)
49
+ return;
50
+ if (!event.isNew && !Object.hasOwn(event.content, field))
39
51
  return;
40
- if (!event.isNew && !Object.hasOwn(event.content, 'document'))
52
+ // An added collection's entry may have no page body yet; the default collection is nothing without one.
53
+ if (event.content[field] == null && event.collection !== options.collection)
41
54
  return;
42
- const result = validate(event.content.document);
55
+ const result = validate(event.content[field]);
43
56
  if (!result.success)
44
57
  throw new ContentSaveRejectedError(`Page JSON is invalid: ${result.errors.join('; ')}`);
45
- return { ...event.content, document: result.document };
58
+ return { ...event.content, [field]: result.document };
46
59
  },
47
60
  },
48
61
  'content:beforePublish': {
49
62
  errorPolicy: 'abort',
50
63
  handler: async (event) => {
51
- if (event.collection !== options.collection)
64
+ const field = fields.get(event.collection);
65
+ if (field === undefined)
66
+ return;
67
+ const { content } = event;
68
+ const data = content.data && typeof content.data === 'object' && !Array.isArray(content.data) ? content.data : null;
69
+ // EmDash passes the stored entry: its fields sit in data, empty ones left out, next to id, type and status.
70
+ const isEntry = data !== null && typeof content.id === 'string';
71
+ const document = data && Object.hasOwn(data, field) ? data[field] : isEntry ? undefined : content[field];
72
+ if (document == null && event.collection !== options.collection)
52
73
  return;
53
- const data = event.content.data;
54
- const document = data && typeof data === 'object' && 'document' in data ? data.document : event.content.document;
55
74
  const result = validate(document);
56
75
  if (!result.success)
57
76
  return { cancel: true, reason: `Invalid page JSON: ${result.errors.join('; ')}` };
@@ -59,10 +78,10 @@ export function createPlugin(input = {}, components = {}) {
59
78
  },
60
79
  },
61
80
  routes: {
62
- configuration: { permission: 'content:read', handler: async () => ({ collection: options.collection, previewPath: options.previewPath }) },
81
+ configuration: { permission: 'content:read', handler: async () => ({ collection: options.collection, previewPath: options.previewPath, collections: options.collections }) },
63
82
  catalog: {
64
83
  permission: 'content:read',
65
- 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 } }),
84
+ 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 } }),
66
85
  },
67
86
  validate: {
68
87
  permission: 'content:read',
@@ -76,23 +95,40 @@ export function createPlugin(input = {}, components = {}) {
76
95
  // Defense in depth: plugin capabilities must not widen a caller's draft access.
77
96
  if (!ctx.user || ctx.user.role < contributorRole)
78
97
  throw new Error('Draft access is required');
79
- const page = await ctx.content?.get(options.collection, pageInput.parse(ctx.input).id);
98
+ const input = pageInput.parse(ctx.input);
99
+ const collection = input.collection ?? options.collection;
100
+ // Only configured collections: this route must not sign draft links for the rest of the site.
101
+ if (!fields.has(collection))
102
+ throw new Error(`Collection ${collection} is not configured for builder documents`);
103
+ const page = await ctx.content?.get(collection, input.id);
80
104
  if (!page)
81
105
  throw new Error('Page not found');
82
106
  const previewSecret = process.env.EMDASH_PREVIEW_SECRET;
83
107
  if (!previewSecret)
84
108
  throw new Error('Configure EMDASH_PREVIEW_SECRET before creating preview links');
85
- return {
86
- url: await getPreviewUrl({ collection: options.collection, id: page.id, secret: previewSecret, expiresIn: '15m', pathPattern: `${options.previewPath}/{id}` }),
87
- expiresIn: 900,
88
- };
109
+ let pathPattern = `${options.previewPath}/{id}`;
110
+ if (collection !== options.collection) {
111
+ // Other collections are drawn by the host's own route, at the entry's site URL.
112
+ const pattern = (await ctx.schema?.getCollection(collection))?.urlPattern;
113
+ if (!pattern)
114
+ throw new Error(`Set a URL pattern on collection ${collection} before creating preview links`);
115
+ const path = entryPath(pattern, page);
116
+ if (!path)
117
+ throw new Error(`The URL pattern of collection ${collection} must be a site path made of {slug} or {id}`);
118
+ pathPattern = path;
119
+ }
120
+ const url = await getPreviewUrl({ collection, id: page.id, secret: previewSecret, expiresIn: '15m', pathPattern });
121
+ // The signer parses the path as a URL; the link must still be the path that was checked.
122
+ if (collection !== options.collection && !url.startsWith(`${pathPattern}?_preview=`))
123
+ throw new Error(`The URL pattern of collection ${collection} must be a site path made of {slug} or {id}`);
124
+ return { url, expiresIn: 900 };
89
125
  },
90
126
  },
91
127
  },
92
128
  mcp: { tools: {
93
129
  catalog: { description: 'Read the supported site components, JSON property schemas, data bindings, theme tokens, and the page creation workflow.', route: 'catalog', input: z.object({}) },
94
130
  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 },
95
- 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 },
131
+ 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 },
96
132
  } },
97
133
  });
98
134
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":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AAI,KAAK,CAAC,iCAAiC,UAAU,6CAA6C,CAAC,CAAC;oBAChM,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;gBACjC,CAAC;aACF;SACF;QACD,GAAG,EAAE,EAAE,KAAK,EAAE;gBACZ,OAAO,EAAE,EAAE,WAAW,EAAE,yHAAyH,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;gBAC1L,QAAQ,EAAE,EAAE,WAAW,EAAE,4HAA4H,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,aAAa,EAAE;gBAChM,OAAO,EAAE,EAAE,WAAW,EAAE,qIAAqI,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,OAAO,CAAC,UAAU,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE;aAC/R,EAAE;KACJ,CAAC,CAAC;AACL,CAAC"}
@@ -13,6 +13,10 @@ export type LoadedPage = {
13
13
  view: ResolvedView;
14
14
  isPreview: boolean;
15
15
  };
16
- /** All reads go through EmDash's published-entry and scoped preview checks. */
16
+ /** The entry is visible but its document field is empty, as an added collection allows. */
17
+ export declare const emptyDocument: unique symbol;
18
+ /** A page always has a document; an entry without one is an error here. */
17
19
  export declare function loadPage(identifier: string, input?: BuilderOptions, components?: ComponentExtensions): Promise<LoadedPage | null>;
20
+ /** All reads go through EmDash's published-entry and scoped preview checks. */
21
+ export declare function readPage(identifier: string, input?: BuilderOptions, components?: ComponentExtensions): Promise<LoadedPage | typeof emptyDocument | null>;
18
22
  //# sourceMappingURL=load-page.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-page.d.ts","sourceRoot":"","sources":["../../../src/builder/server/load-page.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KA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EAA0E;IAC1E,IAAI,EAAE,YAAY,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,2FAA2F;AAC3F,eAAO,MAAM,aAAa,eAA0B,CAAC;AAErD,2EAA2E;AAC3E,wBAAsB,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,GAAE,cAAmB,EAAE,UAAU,GAAE,mBAAwB,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAI/I;AAED,+EAA+E;AAC/E,wBAAsB,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,GAAE,cAAmB,EAAE,UAAU,GAAE,mBAAwB,GAAG,OAAO,CAAC,UAAU,GAAG,OAAO,aAAa,GAAG,IAAI,CAAC,CA0BtK"}
@@ -3,15 +3,27 @@ import { getEmDashCollection, getEmDashEntry } from 'emdash';
3
3
  import { validateDocument } from "../document.js";
4
4
  import { defaultListItems } from "../list-limits.js";
5
5
  import { resolvePage } from "../resolve-page.js";
6
- /** All reads go through EmDash's published-entry and scoped preview checks. */
6
+ /** The entry is visible but its document field is empty, as an added collection allows. */
7
+ export const emptyDocument = Symbol('emptyDocument');
8
+ /** A page always has a document; an entry without one is an error here. */
7
9
  export async function loadPage(identifier, input = {}, components = {}) {
10
+ const page = await readPage(identifier, input, components);
11
+ if (page === emptyDocument)
12
+ throw new Error('Stored page JSON is invalid');
13
+ return page;
14
+ }
15
+ /** All reads go through EmDash's published-entry and scoped preview checks. */
16
+ export async function readPage(identifier, input = {}, components = {}) {
8
17
  const options = resolveOptions(input);
9
18
  const { entry, error, isPreview } = await getEmDashEntry(options.collection, identifier);
10
19
  if (error)
11
20
  throw new Error('Could not load page');
12
21
  if (!entry)
13
22
  return null;
14
- const validated = validateDocument(entry.data.document, components);
23
+ const stored = entry.data[options.collections[0].field];
24
+ if (stored == null)
25
+ return emptyDocument;
26
+ const validated = validateDocument(stored, components);
15
27
  if (!validated.success)
16
28
  throw new Error('Stored page JSON is invalid');
17
29
  const document = validated.document;
@@ -1 +1 @@
1
- {"version":3,"file":"load-page.js","sourceRoot":"","sources":["../../../src/builder/server/load-page.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAuB,MAAM,eAAe,CAAC;AAEpE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAqC,MAAM,gBAAgB,CAAC;AACrF,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAqB,MAAM,oBAAoB,CAAC;AAcpE,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,UAAkB,EAAE,QAAwB,EAAE,EAAE,aAAkC,EAAE;IACjH,MAAM,OAAO,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;IACtC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,MAAM,cAAc,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;IACzF,IAAI,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAClD,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,MAAM,SAAS,GAAG,gBAAgB,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IACpE,IAAI,CAAC,SAAS,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACvE,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC;IACpC,MAAM,KAAK,GAAG,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3E,MAAM,WAAW,GAAG,OAAO,KAAK,CAAC,IAAI,CAAC,WAAW,KAAK,QAAQ,CAAC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,GAAG,WAAW,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAClF,OAAO,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AACtF,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { type LoadedPage } from './load-page.ts';
2
2
  import type { BuilderOptions } from '../options.ts';
3
3
  import type { ComponentExtensions } from '../extensions.ts';
4
+ /** Status 200 without a page: the entry is visible and has no document to draw. */
4
5
  type Result = {
5
6
  page: LoadedPage | null;
6
7
  status: number;
@@ -1 +1 @@
1
- {"version":3,"file":"page-response.d.ts","sourceRoot":"","sources":["../../../src/builder/server/page-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAE5D,KAAK,MAAM,GAAG;IAAE,IAAI,EAAE,UAAU,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAC1D,wBAAsB,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,EAAE,UAAU,GAAE,mBAAwB,GAAG,OAAO,CAAC,MAAM,CAAC,CAQ1I"}
1
+ {"version":3,"file":"page-response.d.ts","sourceRoot":"","sources":["../../../src/builder/server/page-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAE5D,mFAAmF;AACnF,KAAK,MAAM,GAAG;IAAE,IAAI,EAAE,UAAU,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAC1D,wBAAsB,YAAY,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,EAAE,UAAU,GAAE,mBAAwB,GAAG,OAAO,CAAC,MAAM,CAAC,CAS1I"}
@@ -1,7 +1,9 @@
1
- import { loadPage } from "./load-page.js";
1
+ import { emptyDocument, readPage } from "./load-page.js";
2
2
  export async function pageResponse(identifier, options = {}, components = {}) {
3
3
  try {
4
- const page = await loadPage(identifier, options, components);
4
+ const page = await readPage(identifier, options, components);
5
+ if (page === emptyDocument)
6
+ return { page: null, status: 200 };
5
7
  return { page, status: page ? 200 : 404 };
6
8
  }
7
9
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"page-response.js","sourceRoot":"","sources":["../../../src/builder/server/page-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAmB,MAAM,gBAAgB,CAAC;AAM3D,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,UAAkB,EAAE,UAA0B,EAAE,EAAE,aAAkC,EAAE;IACvH,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,UAAU,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QAC7D,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;IAC5C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACxE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;IACrC,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"page-response.js","sourceRoot":"","sources":["../../../src/builder/server/page-response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAmB,MAAM,gBAAgB,CAAC;AAO1E,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,UAAkB,EAAE,UAA0B,EAAE,EAAE,aAAkC,EAAE;IACvH,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,UAAU,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QAC7D,IAAI,IAAI,KAAK,aAAa;YAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;QAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;IAC5C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACxE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;IACrC,CAAC;AACH,CAAC"}
@@ -0,0 +1,7 @@
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 declare function isSitePath(path: string): boolean;
7
+ //# sourceMappingURL=site-path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-path.d.ts","sourceRoot":"","sources":["../../src/builder/site-path.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAQhD"}
@@ -0,0 +1,21 @@
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) {
7
+ if (!/^(?:\/[A-Za-z0-9._~!*'()%-]+)+$/.test(path))
8
+ return false;
9
+ return path.slice(1).split('/').every(segment => {
10
+ let decoded;
11
+ try {
12
+ decoded = decodeURIComponent(segment);
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ // eslint-disable-next-line no-control-regex -- control characters are exactly what must not pass
18
+ return !/[%/\\\u0000-\u001f\u007f-\u009f]/.test(decoded) && decoded !== '.' && decoded !== '..' && decoded.toLowerCase() !== '_emdash';
19
+ });
20
+ }
21
+ //# sourceMappingURL=site-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-path.js","sourceRoot":"","sources":["../../src/builder/site-path.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,IAAI,CAAC,iCAAiC,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAChE,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE;QAC9C,IAAI,OAAe,CAAC;QACpB,IAAI,CAAC;YAAC,OAAO,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC;QAAC,CAAC;QAAC,MAAM,CAAC;YAAC,OAAO,KAAK,CAAC;QAAC,CAAC;QACtE,iGAAiG;QACjG,OAAO,CAAC,kCAAkC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,GAAG,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,KAAK,SAAS,CAAC;IACzI,CAAC,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interactive-inc/emdash-plugins",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "EmDash plugins by Interactive Inc. builder: chat-authored json-render pages, MCP tools and previews",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,8 +1,12 @@
1
- /** Resolve only saved Pages entries; new-entry and unrelated editors have no preview. */
2
- export const getEditorPageId = (pathname: string, collection = 'pages'): string | null => {
1
+ export type EditorEntry = { collection: string; id: string };
2
+
3
+ /** Resolve only saved entries of the given collections; new-entry and unrelated editors have no preview. */
4
+ export const getEditorEntry = (pathname: string, collections: readonly string[]): EditorEntry | null => {
3
5
  const match = /^(?:\/_emdash\/admin)?\/content\/([^/]+)\/([^/]+)\/?$/.exec(pathname);
4
6
 
5
- if (!match || match[1] !== collection || match[2] === 'new') return null;
7
+ if (!match || !collections.includes(match[1]!) || match[2] === 'new') return null;
6
8
 
7
- return match[2];
9
+ return { collection: match[1]!, id: match[2]! };
8
10
  };
11
+
12
+ export const getEditorPageId = (pathname: string, collection = 'pages'): string | null => getEditorEntry(pathname, [collection])?.id ?? null;
@@ -1,14 +1,27 @@
1
1
  import { z } from 'zod';
2
2
  import { pluginId } from '../constants.ts';
3
+ import { isSitePath } from '../site-path.ts';
3
4
 
4
5
  const previewResponse = z.object({ success: z.literal(true), data: z.object({ url: z.string() }) });
6
+ const collectionName = z.string().regex(/^[a-z][a-z0-9_]*$/);
7
+ const configurationResponse = z.object({ success: z.literal(true), data: z.object({
8
+ collection: collectionName,
9
+ previewPath: z.string().regex(/^(?:\/[a-zA-Z0-9_-]+)+$/),
10
+ collections: z.array(z.object({ name: collectionName, field: z.string() })).optional(),
11
+ }) });
12
+ export type PreviewConfiguration = z.infer<typeof configurationResponse>['data'];
13
+ export type PreviewTarget = { id: string; collection?: string; previewPath?: string };
5
14
 
6
- /** Only the authenticated EmDash route can issue the page-scoped preview token. */
7
- export const getPagePreview = async (id: string, signal: AbortSignal, previewPath = '/preview'): Promise<string> => {
15
+ /**
16
+ * Only the authenticated EmDash route can issue the entry-scoped preview token.
17
+ * Without a collection the URL must sit under the builder preview path; with one it is the entry's own site page.
18
+ */
19
+ export const getPagePreview = async (target: string | PreviewTarget, signal: AbortSignal, previewPath = '/preview'): Promise<string> => {
20
+ const { id, collection, previewPath: path = previewPath } = typeof target === 'string' ? { id: target } : target;
8
21
  const response = await fetch(`/_emdash/api/plugins/${pluginId}/preview`, {
9
22
  method: 'POST', credentials: 'same-origin', signal,
10
23
  headers: { 'Content-Type': 'application/json', 'X-EmDash-Request': '1' },
11
- body: JSON.stringify({ id }),
24
+ body: JSON.stringify(collection === undefined ? { id } : { collection, id }),
12
25
  });
13
26
  const parsed = previewResponse.safeParse(await response.json());
14
27
 
@@ -16,13 +29,16 @@ export const getPagePreview = async (id: string, signal: AbortSignal, previewPat
16
29
 
17
30
  const value = parsed.data.data.url;
18
31
  const url = new URL(value, 'https://builder.invalid');
19
- if (!value.startsWith(`${previewPath}/`) || url.origin !== 'https://builder.invalid' || !url.pathname.startsWith(`${previewPath}/`) || !url.searchParams.get('_preview')) throw new Error('プレビューURLが不正です。');
32
+ // The frame may show only a signed page of this site, written exactly as the browser will request it.
33
+ const local = url.origin === 'https://builder.invalid' && value === `${url.pathname}${url.search}` && !value.startsWith('//') && !!url.searchParams.get('_preview');
34
+ const expected = collection === undefined ? value.startsWith(`${path}/`) : isSitePath(url.pathname);
35
+ if (!local || !expected) throw new Error('プレビューURLが不正です。');
20
36
  return value;
21
37
  };
22
38
 
23
- export async function getPreviewConfiguration(signal: AbortSignal): Promise<{ collection: string; previewPath: string }> {
39
+ export async function getPreviewConfiguration(signal: AbortSignal): Promise<PreviewConfiguration> {
24
40
  const response = await fetch(`/_emdash/api/plugins/${pluginId}/configuration`, { credentials: 'same-origin', signal, headers: { 'X-EmDash-Request': '1' } });
25
- const result = z.object({ success: z.literal(true), data: z.object({ collection: z.string().regex(/^[a-z][a-z0-9_]*$/), previewPath: z.string().regex(/^(?:\/[a-zA-Z0-9_-]+)+$/) }) }).safeParse(await response.json());
41
+ const result = configurationResponse.safeParse(await response.json());
26
42
  if (!response.ok || !result.success) throw new Error('プレビュー設定を読み込めませんでした。');
27
43
  return result.data.data;
28
44
  }
@@ -1,10 +1,12 @@
1
1
  import { useEffect, useState } from 'react';
2
- import { getEditorPageId } from './get-editor-page-id.ts';
2
+ import { getEditorEntry } from './get-editor-page-id.ts';
3
3
  import { getPagePreview, getPreviewConfiguration } from './get-page-preview.ts';
4
4
  import { PagePreviewFrame } from './page-preview-frame.tsx';
5
5
 
6
6
  type Props = { value: unknown };
7
7
  type Configuration = Awaited<ReturnType<typeof getPreviewConfiguration>>;
8
+
9
+ const collectionNames = (configuration: Configuration) => configuration.collections?.map(item => item.name) ?? [configuration.collection];
8
10
  type Load<T> = { status: 'pending' } | { status: 'success'; data: T } | { status: 'error'; message: string };
9
11
 
10
12
  const errorMessage = (error: unknown) => error instanceof Error ? error.message : 'プレビューを読み込めませんでした。';
@@ -17,8 +19,12 @@ export function PagePreviewField(props: Props) {
17
19
  const [configuration, setConfiguration] = useState<Load<Configuration>>({ status: 'pending' });
18
20
  const [preview, setPreview] = useState<Load<string>>({ status: 'pending' });
19
21
  const pathname = typeof window === 'undefined' ? '' : window.location.pathname;
20
- const pageId = configuration.status === 'success' ? getEditorPageId(pathname, configuration.data.collection) : null;
21
- const previewPath = configuration.status === 'success' ? configuration.data.previewPath : undefined;
22
+ const settings = configuration.status === 'success' ? configuration.data : null;
23
+ const entry = settings ? getEditorEntry(pathname, collectionNames(settings)) : null;
24
+ const pageId = entry?.id ?? null;
25
+ // The default collection keeps the request and the strict path check it always had.
26
+ const collection = entry && entry.collection !== settings?.collection ? entry.collection : undefined;
27
+ const previewPath = settings?.previewPath;
22
28
  const valueKey = JSON.stringify(props.value ?? null);
23
29
 
24
30
  useEffect(() => {
@@ -34,12 +40,12 @@ export function PagePreviewField(props: Props) {
34
40
  if (pageId === null) return;
35
41
  const controller = new AbortController();
36
42
  setPreview({ status: 'pending' });
37
- getPagePreview(pageId, controller.signal, previewPath).then(
43
+ getPagePreview({ id: pageId, collection, previewPath }, controller.signal).then(
38
44
  data => setPreview({ status: 'success', data }),
39
45
  error => { if (!controller.signal.aborted) setPreview({ status: 'error', message: errorMessage(error) }); },
40
46
  );
41
47
  return () => controller.abort();
42
- }, [pageId, previewPath, valueKey]);
48
+ }, [pageId, collection, previewPath, valueKey]);
43
49
 
44
50
  if (configuration.status === 'error') return <p role="alert">{configuration.message}</p>;
45
51
  if (configuration.status === 'pending') return <p role="status">プレビューを読み込んでいます…</p>;
@@ -1,7 +1,7 @@
1
1
  import { defineCatalog } from '@json-render/core';
2
2
  import { schema } from '@json-render/react/schema';
3
3
  import { z } from 'zod';
4
- import { resolveOptions, type ResolvedOptions } from './options.ts';
4
+ import { resolveOptions, type BuilderOptions, type ResolvedOptions } from './options.ts';
5
5
  import { defaultListItems } from './list-limits.ts';
6
6
  import { maxMotionElements, motionTokens } from './motion-tokens.ts';
7
7
 
@@ -98,8 +98,12 @@ For lists put stagger: ${list(motionTokens.stagger)} on a Stack or Grid. The con
98
98
  Never put motion on a Section, on an element that contains a Section, or inside an element that already moves. motion is a literal object, never a $state/$item binding; there are no custom timings, easing, CSS or scripts. At most ${maxMotionElements} elements may move per page: each staggered child and each repeated copy counts, and a list repeats up to its limit (${defaultListItems} when unset).
99
99
  Visitors who prefer reduced motion, views without JavaScript and the admin preview show the final static page, so every page must read well without motion.`;
100
100
 
101
- /** The MCP guide reflects the host's configured collection and routes. */
102
- export function createPageGuide(options: ResolvedOptions = resolveOptions()): string {
101
+ const others = (options: ResolvedOptions) => options.collections.length < 2 ? '' : `
102
+ These collections also hold a document, in the named field next to their own fields: ${options.collections.slice(1).map(item => `${item.name} (data.${item.field})`).join(', ')}. There the document is optional: an entry may exist without one. Read their other fields with schema_get_collection and save with content_create/content_update on that collection. Their pages are drawn by the site at the collection's URL; pass collection to the builder preview tool to preview them.`;
103
+
104
+ /** The MCP guide reflects the host's configured collections and routes. */
105
+ export function createPageGuide(input: BuilderOptions = {}): string {
106
+ const options = resolveOptions(input);
103
107
  return `Build pages as a versioned document: {version:1,spec:{root,elements},theme?,data?}.
104
108
  Elements are {type,props,children?}. Only the supplied catalog components are allowed.
105
109
  Bind props with {"$state":"/page/title"}, {"$state":"/data/article/title"}, or {"$item":"title"} inside a repeat.
@@ -108,8 +112,8 @@ A visible condition is a boolean or {"$state":"/data/article/image"}.
108
112
  Data sources are named EmDash queries: {posts:{collection:"posts",limit:6}} or {article:{collection:"posts",id:"my-slug"}}.
109
113
  All data reads use EmDash public/preview rules. A page preview token does not grant access to unrelated drafts.
110
114
  Theme: {accent:"#hex",background:"#hex",foreground:"#hex",font:"sans"|"serif",radius:"none"|"sm"|"lg"}.
111
- Use ${options.homeSlug} as the home-page slug. Other page slugs form their URL. Save using core content_create/content_update on collection ${options.collection}, with data:{title,description?,document}. Keep _rev for updates and publication.
112
- Public pages use the prefix ${options.basePath || '/'}; signed previews use ${options.previewPath}.
115
+ Use ${options.homeSlug} as the home-page slug. Other page slugs form their URL. Save using core content_create/content_update on collection ${options.collection}, with data:{title,description?,${options.collections[0]!.field}}. Keep _rev for updates and publication.
116
+ Public pages use the prefix ${options.basePath || '/'}; signed previews use ${options.previewPath}.${others(options)}
113
117
  Use the builder validate tool before saving and preview before publishing. Never store executable code, arbitrary CSS, or fetch URLs.
114
118
  ${options.motion ? motionGuide : 'Motion is disabled on this site; omit props.motion.'}`;
115
119
  }
@@ -1,4 +1,4 @@
1
1
  /** Stable plugin identity. Widget names, MCP scopes and plugin API routes derive from this ID. */
2
2
  export const pluginId = 'builder';
3
3
  /** Kept equal to package.json by tests/builder/constants.test.ts. */
4
- export const pluginVersion = '0.1.1';
4
+ export const pluginVersion = '0.2.0';
@@ -1,20 +1,27 @@
1
1
  import type { MiddlewareHandler } from 'astro';
2
2
 
3
- export const onRequest: MiddlewareHandler = async (_context, next) => {
3
+ export const onRequest: MiddlewareHandler = async (context, next) => {
4
+ // A signed preview may be any host route; none of them belongs in a search index.
5
+ const preview = context.url?.searchParams.has('_preview') ?? false;
4
6
  const response = await next();
5
7
  try {
6
- addSecurityHeaders(response.headers);
8
+ addSecurityHeaders(response.headers, preview);
7
9
  return response;
8
10
  } catch (error) {
9
11
  // Response.redirect() and fetch() responses have immutable headers, so copy them into a new response.
10
12
  if (!(error instanceof TypeError)) throw error;
11
13
  const copy = new Response(response.body, { status: response.status, statusText: response.statusText, headers: response.headers });
12
- addSecurityHeaders(copy.headers);
14
+ addSecurityHeaders(copy.headers, preview);
13
15
  return copy;
14
16
  }
15
17
  };
16
18
 
17
- function addSecurityHeaders(headers: Headers) {
19
+ function addSecurityHeaders(headers: Headers, preview: boolean) {
20
+ if (preview) {
21
+ // Directives after a crawler name apply to that crawler only, so the rule for everyone goes first; the host's own value follows.
22
+ const own = headers.get('X-Robots-Tag');
23
+ if (!own?.startsWith('noindex, nofollow')) headers.set('X-Robots-Tag', own ? `noindex, nofollow, ${own}` : 'noindex, nofollow');
24
+ }
18
25
  if (!headers.has('X-Content-Type-Options')) headers.set('X-Content-Type-Options', 'nosniff');
19
26
  if (!headers.has('Referrer-Policy')) headers.set('Referrer-Policy', 'no-referrer');
20
27
  // The admin can embed its own site preview; other sites cannot frame this app.
@@ -1,8 +1,14 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  const prefix = z.string().regex(/^(?:\/[a-zA-Z0-9_-]+)*$/);
4
+ const name = z.string().regex(/^[a-z][a-z0-9_]*$/).max(60);
5
+ // "data" is where EmDash keeps an entry's fields, so a field of that name could not be told apart from them.
6
+ const documentCollection = z.strictObject({ name, field: name.refine(value => value !== 'data', 'The document field cannot be named data').default('document') });
4
7
  const optionsSchema = z.strictObject({
5
- collection: z.string().regex(/^[a-z][a-z0-9_]*$/).max(60).default('pages'),
8
+ // Served by the public and preview routes, and the default for the preview tool.
9
+ collection: name.default('pages'),
10
+ // More collections whose document field is validated and previewed; their pages are the host's own routes.
11
+ collections: z.array(z.union([name.transform(value => ({ name: value, field: 'document' })), documentCollection])).default([]),
6
12
  basePath: prefix.default(''),
7
13
  previewPath: prefix.refine(value => value.length > 0 && !value.startsWith('/_emdash'), 'Preview path must be outside EmDash').default('/preview'),
8
14
  homeSlug: z.string().regex(/^[a-zA-Z0-9_-]+$/).max(200).default('home'),
@@ -12,9 +18,13 @@ const optionsSchema = z.strictObject({
12
18
  });
13
19
  export type BuilderOptions = z.input<typeof optionsSchema>;
14
20
  export type ResolvedOptions = z.output<typeof optionsSchema>;
21
+ /** The result always lists the default collection first, so resolving it again changes nothing. */
15
22
  export function resolveOptions(options: BuilderOptions = {}): ResolvedOptions {
16
23
  const result = optionsSchema.parse(options);
17
24
  if (result.basePath.startsWith('/_emdash')) throw new Error('Page routes must be outside EmDash');
18
25
  if (result.basePath === result.previewPath || result.basePath.startsWith(`${result.previewPath}/`)) throw new Error('Page and preview routes overlap');
19
- return result;
26
+ const names = result.collections.map(item => item.name);
27
+ if (new Set(names).size !== names.length) throw new Error('Each collection may be listed only once');
28
+ const primary = result.collections.find(item => item.name === result.collection) ?? { name: result.collection, field: 'document' };
29
+ return { ...result, collections: [primary, ...result.collections.filter(item => item !== primary)] };
20
30
  }
@@ -4,7 +4,10 @@ import components from 'virtual:emdash-plugins/builder/extensions';
4
4
  import PageShell from 'virtual:emdash-plugins/builder/page-shell';
5
5
  import { pageResponse } from '@interactive-inc/emdash-plugins/builder/server';
6
6
  const slug = Astro.params.slug || options.homeSlug;
7
- const { page, status } = await pageResponse(slug, options, components);
7
+ const result = await pageResponse(slug, options, components);
8
+ // These routes only draw documents; a stored entry without one cannot be shown.
9
+ const { page } = result;
10
+ const status = !page && result.status === 200 ? 503 : result.status;
8
11
  Astro.response.status = status;
9
12
  Astro.response.headers.set('Cache-Control', 'private, no-store');
10
13
  ---
@@ -6,7 +6,7 @@ import { pageResponse } from '@interactive-inc/emdash-plugins/builder/server';
6
6
  const result = await pageResponse(Astro.params.id ?? '', options, components);
7
7
  // A preview URL must actually authorize this entry; a guessed ID cannot act as a draft URL.
8
8
  const page = result.page?.isPreview ? result.page : null;
9
- const status = page ? 200 : result.status === 503 ? 503 : 404;
9
+ const status = page ? 200 : result.status === 503 || (result.status === 200 && !result.page) ? 503 : 404;
10
10
  Astro.response.status = status;
11
11
  Astro.response.headers.set('Cache-Control', 'private, no-store');
12
12
  Astro.response.headers.set('X-Robots-Tag', 'noindex, nofollow');