@conloca/astro-cms 0.2.0 → 0.2.2

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 (98) hide show
  1. package/README.md +23 -20
  2. package/dist/internal/page-handler.astro +8 -2
  3. package/dist/ts/node/content.d.ts +1 -2
  4. package/dist/ts/node/content.d.ts.map +1 -1
  5. package/dist/ts/node/content.js +1 -1
  6. package/dist/ts/node/content.js.map +1 -1
  7. package/dist/ts/src/checks.d.ts +3 -3
  8. package/dist/ts/src/checks.d.ts.map +1 -1
  9. package/dist/ts/src/checks.js +3 -3
  10. package/dist/ts/src/checks.js.map +1 -1
  11. package/dist/ts/src/cms-handler.js +2 -1
  12. package/dist/ts/src/cms-handler.js.map +1 -1
  13. package/dist/ts/src/collections.d.ts +35 -56
  14. package/dist/ts/src/collections.d.ts.map +1 -1
  15. package/dist/ts/src/collections.js +77 -74
  16. package/dist/ts/src/collections.js.map +1 -1
  17. package/dist/ts/src/entries.d.ts +44 -0
  18. package/dist/ts/src/entries.d.ts.map +1 -0
  19. package/dist/ts/src/entries.js +48 -0
  20. package/dist/ts/src/entries.js.map +1 -0
  21. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -1
  22. package/dist/ts/src/handlers/collection-content-api.js +7 -2
  23. package/dist/ts/src/handlers/collection-content-api.js.map +1 -1
  24. package/dist/ts/src/handlers/collection-names.d.ts +9 -0
  25. package/dist/ts/src/handlers/collection-names.d.ts.map +1 -0
  26. package/dist/ts/src/handlers/collection-names.js +9 -0
  27. package/dist/ts/src/handlers/collection-names.js.map +1 -0
  28. package/dist/ts/src/handlers/page-render-core.d.ts +31 -12
  29. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -1
  30. package/dist/ts/src/handlers/page-render-core.js +38 -17
  31. package/dist/ts/src/handlers/page-render-core.js.map +1 -1
  32. package/dist/ts/src/index.d.ts +2 -2
  33. package/dist/ts/src/index.d.ts.map +1 -1
  34. package/dist/ts/src/index.js +1 -3
  35. package/dist/ts/src/index.js.map +1 -1
  36. package/dist/ts/src/internal/collection-parsers.d.ts +26 -0
  37. package/dist/ts/src/internal/collection-parsers.d.ts.map +1 -0
  38. package/dist/ts/src/internal/collection-parsers.js +34 -0
  39. package/dist/ts/src/internal/collection-parsers.js.map +1 -0
  40. package/dist/ts/src/internal/entry-issues.d.ts +8 -0
  41. package/dist/ts/src/internal/entry-issues.d.ts.map +1 -0
  42. package/dist/ts/src/internal/entry-issues.js +19 -0
  43. package/dist/ts/src/internal/entry-issues.js.map +1 -0
  44. package/dist/ts/src/internal/entry-validation.d.ts +93 -0
  45. package/dist/ts/src/internal/entry-validation.d.ts.map +1 -0
  46. package/dist/ts/src/internal/entry-validation.js +228 -0
  47. package/dist/ts/src/internal/entry-validation.js.map +1 -0
  48. package/dist/ts/src/lib/content-config-guard.d.ts +2 -0
  49. package/dist/ts/src/lib/content-config-guard.d.ts.map +1 -1
  50. package/dist/ts/src/lib/content-config-guard.js +5 -1
  51. package/dist/ts/src/lib/content-config-guard.js.map +1 -1
  52. package/dist/ts/src/lib/virtual-module-generators.d.ts +13 -0
  53. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -1
  54. package/dist/ts/src/lib/virtual-module-generators.js +18 -0
  55. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -1
  56. package/dist/ts/src/loader.d.ts +9 -12
  57. package/dist/ts/src/loader.d.ts.map +1 -1
  58. package/dist/ts/src/loader.js +19 -16
  59. package/dist/ts/src/loader.js.map +1 -1
  60. package/dist/ts/src/page-schemas.d.ts +1 -1
  61. package/dist/ts/src/page-schemas.d.ts.map +1 -1
  62. package/dist/ts/src/page-schemas.js +1 -1
  63. package/dist/ts/src/page-schemas.js.map +1 -1
  64. package/dist/ts/src/plugin-spa.d.ts +12 -0
  65. package/dist/ts/src/plugin-spa.d.ts.map +1 -1
  66. package/dist/ts/src/plugin-spa.js +33 -6
  67. package/dist/ts/src/plugin-spa.js.map +1 -1
  68. package/dist/ts/src/tiptap-html-static.d.ts +13 -12
  69. package/dist/ts/src/tiptap-html-static.d.ts.map +1 -1
  70. package/dist/ts/src/tiptap-html-static.js +104 -54
  71. package/dist/ts/src/tiptap-html-static.js.map +1 -1
  72. package/dist/virtual-modules.d.ts +14 -0
  73. package/node/content.ts +10 -1
  74. package/package.json +15 -10
  75. package/src/checks.ts +3 -2
  76. package/src/cms-handler.ts +2 -1
  77. package/src/collections.ts +119 -79
  78. package/src/entries.ts +111 -0
  79. package/src/handlers/collection-content-api.ts +7 -2
  80. package/src/handlers/collection-names.ts +8 -0
  81. package/src/handlers/page-handler.astro +8 -2
  82. package/src/handlers/page-render-core.ts +65 -17
  83. package/src/index.ts +6 -7
  84. package/src/internal/collection-parsers.ts +51 -0
  85. package/src/internal/entry-issues.ts +23 -0
  86. package/src/internal/entry-validation.ts +305 -0
  87. package/src/lib/content-config-guard.ts +8 -3
  88. package/src/lib/virtual-module-generators.ts +20 -0
  89. package/src/loader.ts +33 -17
  90. package/src/page-schemas.ts +4 -0
  91. package/src/plugin-spa.ts +49 -10
  92. package/src/tiptap-html-static.ts +114 -64
  93. package/src/virtual-modules.d.ts +14 -0
  94. package/dist/ts/src/internal/page-collection-schema.d.ts +0 -44
  95. package/dist/ts/src/internal/page-collection-schema.d.ts.map +0 -1
  96. package/dist/ts/src/internal/page-collection-schema.js +0 -152
  97. package/dist/ts/src/internal/page-collection-schema.js.map +0 -1
  98. package/src/internal/page-collection-schema.ts +0 -210
package/src/loader.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { createContentAPI } from '@conloca/content-api/reader';
2
2
  import type { Loader, LoaderContext } from 'astro/loaders';
3
+ import { describeEntryIssues } from './internal/entry-issues.js';
4
+ import type { EntryParser } from './internal/entry-validation.js';
3
5
 
4
6
  export interface ConlocaLoaderOptions {
5
7
  /** Must equal the content.config key this loader is mounted under — load() asserts it. */
@@ -8,21 +10,16 @@ export interface ConlocaLoaderOptions {
8
10
  site?: string;
9
11
  /** Collection kind. If not provided, defaults to 'fragment' for 'fragments' collection, 'page' otherwise. */
10
12
  kind?: 'page' | 'fragment' | 'data';
13
+ /**
14
+ * Validates every entry before it is stored; a failing entry fails the load
15
+ * with its file and every issue. The collection factories pass the generated
16
+ * Typia parsers for the collection's kind and host schemas. Without it, the
17
+ * entry is stored as loaded (and whatever `schema` the collection was
18
+ * declared with still runs through `parseData`).
19
+ */
20
+ parseEntry?: EntryParser<Record<string, unknown>>;
11
21
  }
12
22
 
13
- /**
14
- * Entry fields this loader owns, written into every entry's data in load().
15
- *
16
- * None of them belong to `pageMetaSchema`, so under a page collection's schema
17
- * they survive only through the loose index signature. A host page-meta field
18
- * of the same name would replace the loader's value — a host `puckData` shape
19
- * would empty the page tree of every page in the built site.
20
- * `buildPageCollectionSchema` refuses those names with an error.
21
- *
22
- * Adding a field to the record built in load() also means reserving it here.
23
- */
24
- export const LOADER_RESERVED_FIELDS = ['created', 'modified', 'name', 'data', 'mdx', 'puckData'] as const;
25
-
26
23
  /**
27
24
  * Custom Astro content loader for Conloca CMS.
28
25
  * Loads content from the Conloca content directory into Astro collections.
@@ -97,9 +94,9 @@ export function conlocaLoader(options: ConlocaLoaderOptions): Loader {
97
94
  }
98
95
  }
99
96
 
100
- // Any key added here that is not part of pageMetaSchema must also be
101
- // listed in LOADER_RESERVED_FIELDS, or a host page-meta field of the
102
- // same name will replace it on every page.
97
+ // Any key added here that is not part of PageMeta must also be
98
+ // listed in LOADER_RESERVED_FIELDS (internal/entry-validation.ts),
99
+ // or a host page-meta field of the same name will replace it on every page.
103
100
  const data: Record<string, unknown> = {
104
101
  id: manifest.id,
105
102
  locale,
@@ -123,11 +120,19 @@ export function conlocaLoader(options: ConlocaLoaderOptions): Loader {
123
120
  data.puckData = puckData;
124
121
  }
125
122
 
123
+ const validatedData = options.parseEntry
124
+ ? validEntryData(options.parseEntry, data, {
125
+ collection: context.collection,
126
+ id: entryId,
127
+ filePath: localeVersion.sourcePath,
128
+ })
129
+ : data;
130
+
126
131
  // filePath feeds Astro's error location: without it a validation
127
132
  // failure names only the opaque content id, not a file to open.
128
133
  const parsedData = await parseData({
129
134
  id: entryId,
130
- data,
135
+ data: validatedData,
131
136
  ...(localeVersion.sourcePath ? { filePath: localeVersion.sourcePath } : {}),
132
137
  });
133
138
 
@@ -143,3 +148,14 @@ export function conlocaLoader(options: ConlocaLoaderOptions): Loader {
143
148
  },
144
149
  };
145
150
  }
151
+
152
+ /** The parsed entry data, or the build error naming the entry, its file and every issue. */
153
+ function validEntryData(
154
+ parseEntry: EntryParser<Record<string, unknown>>,
155
+ data: Record<string, unknown>,
156
+ where: { collection: string; id: string; filePath?: string },
157
+ ): Record<string, unknown> {
158
+ const result = parseEntry(data);
159
+ if (!result.success) throw new Error(describeEntryIssues(result.issues, where));
160
+ return result.data;
161
+ }
@@ -4,11 +4,15 @@
4
4
  */
5
5
  export {
6
6
  type CoreFieldsMode,
7
+ type DataSchemas,
8
+ defineHostSchema,
7
9
  definePageSchema,
8
10
  type FieldHint,
9
11
  type FieldHintCommon,
10
12
  type FieldHints,
11
13
  type FieldHintVariant,
14
+ type HostSchema,
15
+ type HostSchemaType,
12
16
  type PageSchemaDescriptor,
13
17
  type PageSchemaEntry,
14
18
  type PageSchemaGroup,
package/src/plugin-spa.ts CHANGED
@@ -55,6 +55,7 @@ const ACORN_DEFAULT_SHIM_PATH = join(__dirname, '..', '..', 'internal', 'acorn-d
55
55
  const TIPTAP_HTML_SHIM_PATH = join(__dirname, 'tiptap-html-static.js');
56
56
 
57
57
  import {
58
+ generateContentSchemasModule,
58
59
  generateLayoutModule,
59
60
  generatePuckConfigModule,
60
61
  generateRoutingConfigModule,
@@ -69,11 +70,13 @@ const RESOLVED_VIRTUAL_CONFIG = `\0${VIRTUAL_CONFIG_MODULE}`;
69
70
  const VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';
70
71
  const VIRTUAL_LAYOUT = 'virtual:conloca-layout';
71
72
  const VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';
73
+ const VIRTUAL_CONTENT_SCHEMAS = 'virtual:conloca-content-schemas';
72
74
 
73
75
  // Resolved IDs (with \0 prefix to prevent file resolution)
74
76
  const RESOLVED_ROUTING_CONFIG = `\0${VIRTUAL_ROUTING_CONFIG}`;
75
77
  const RESOLVED_LAYOUT = `\0${VIRTUAL_LAYOUT}`;
76
78
  const RESOLVED_PUCK_CONFIG = `\0${VIRTUAL_PUCK_CONFIG}`;
79
+ const RESOLVED_CONTENT_SCHEMAS = `\0${VIRTUAL_CONTENT_SCHEMAS}`;
77
80
 
78
81
  // Virtual modules for hydration system
79
82
  const VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';
@@ -107,6 +110,19 @@ export interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {
107
110
  puckConfigPath: string; // Path to the puck config module (should be .tsx file with React components)
108
111
  schemasPath?: string; // Path to the schemas module (exports { dataSchemas, pageSchemas, mdxComponents })
109
112
 
113
+ /**
114
+ * Module exporting the `pageSchemas` and/or `dataSchemas` the content config
115
+ * hands conlocaPages() and conlocaData(). A draft preview builds the same
116
+ * entry parsers from them and parses each draft as the build parses an
117
+ * entry, so it gets the stored values and fails where the build would. It
118
+ * loads in the preview server, so it may import schema code only (Typia
119
+ * host schemas, definePageSchema) — the module the content config imports
120
+ * them from, not the editor's `schemasPath` barrel.
121
+ *
122
+ * @example './src/page-schemas.ts'
123
+ */
124
+ contentSchemasPath?: string;
125
+
110
126
  /**
111
127
  * Default layout for content pages.
112
128
  * When provided without routing config, enables routing with catch-all pattern.
@@ -542,11 +558,15 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
542
558
  templates?: unknown;
543
559
  mdxPagesEnabled: boolean;
544
560
  locales?: { list: string[]; defaultLocale: string };
561
+ assetsBasePath: string;
545
562
  assetRefBase?: string;
546
563
  dataBindings?: EditorDataBindings;
547
564
  } = {
548
565
  basename: cmsRoute,
549
566
  apiBaseUrl: `${cmsRoute}/api`,
567
+ // The media surfaces' thumbnails, served by the content API under the
568
+ // same route; the editor's own default only covers a CMS at /__cms.
569
+ assetsBasePath: `${cmsRoute}/api/assets/serve`,
550
570
  siteBaseUrl: options.siteBaseUrl,
551
571
  enableDevtools: options.enableDevtools ?? true,
552
572
  queryClientOptions: options.queryClientOptions,
@@ -560,7 +580,8 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
560
580
  // Forward the locale list so the SPA stops hardcoding en/nl/fr in
561
581
  // the create-page dialog. The integration receives this from the
562
582
  // top-level `locales` option, which can in turn be produced by
563
- // `localesFromAstroI18n` / `localesFromStarlight`.
583
+ // `localesFromAstroI18n` / `localesFromStarlight`; without it the
584
+ // `astro:config:setup` hook fills it from sites.json.
564
585
  locales: options.locales ? { list: options.locales.list, defaultLocale: options.locales.defaultLocale } : undefined,
565
586
  };
566
587
 
@@ -612,14 +633,22 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
612
633
  // virtual module, the editor's data bindings below, and
613
634
  // `astro:routes:resolved` — reads them after this, so they all
614
635
  // observe the resolved values.
636
+ const siteName = resolveSiteName(routingConfig?.siteName, sitesConfig.sites);
637
+ const locale = resolveLocale(routingConfig?.locale, options.locales?.defaultLocale, siteName, sitesConfig);
615
638
  if (resolvedRoutingConfig) {
616
- resolvedRoutingConfig.siteName = resolveSiteName(routingConfig?.siteName, sitesConfig.sites);
617
- resolvedRoutingConfig.locale = resolveLocale(
618
- routingConfig?.locale,
619
- options.locales?.defaultLocale,
620
- resolvedRoutingConfig.siteName,
621
- sitesConfig,
622
- );
639
+ resolvedRoutingConfig.siteName = siteName;
640
+ resolvedRoutingConfig.locale = locale;
641
+ }
642
+ // Without the `locales` option the editor offers the site's own
643
+ // languages from sites.json — the list the server checks a new page
644
+ // against — starting from the locale the site renders. Left unset, the
645
+ // editor guessed English: a site in any other language could not
646
+ // create a page, and its new fragments were never rendered.
647
+ if (!options.locales) {
648
+ spaConfig.locales = {
649
+ list: sitesConfig.sites[siteName]?.locales ?? sitesConfig.globalLocales,
650
+ defaultLocale: locale,
651
+ };
623
652
  }
624
653
  // Pick the first site that declares an `mdxPages` path. Today's
625
654
  // integration supports a single `mdxPages` per project;
@@ -749,7 +778,10 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
749
778
  // richtext section died there with "The 'contextifiedObject'
750
779
  // argument must be an vm.Context". Both specifiers resolve to a
751
780
  // shim that writes the markup as a string, with no DOM and no
752
- // vm, so the same output comes out on every engine.
781
+ // vm, so the same output comes out on every engine. The alias
782
+ // reaches the editor in the browser too, and the field stores
783
+ // HTML, so the shim also reads it back: with the browser's own
784
+ // parser there, with linkedom on the server.
753
785
  { find: /^@tiptap\/html(\/server)?$/, replacement: TIPTAP_HTML_SHIM_PATH },
754
786
  ],
755
787
  },
@@ -799,6 +831,9 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
799
831
  if (id === VIRTUAL_PUCK_CONFIG) {
800
832
  return RESOLVED_PUCK_CONFIG;
801
833
  }
834
+ if (id === VIRTUAL_CONTENT_SCHEMAS) {
835
+ return RESOLVED_CONTENT_SCHEMAS;
836
+ }
802
837
  // Hydration virtual modules
803
838
  if (id === VIRTUAL_HYDRATION_REGISTRY) {
804
839
  return RESOLVED_HYDRATION_REGISTRY;
@@ -823,6 +858,11 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
823
858
  if (id === RESOLVED_PUCK_CONFIG) {
824
859
  return generatePuckConfigModule(options.puckConfigPath);
825
860
  }
861
+ if (id === RESOLVED_CONTENT_SCHEMAS) {
862
+ return generateContentSchemasModule(
863
+ options.contentSchemasPath ? resolve(options.contentSchemasPath) : undefined,
864
+ );
865
+ }
826
866
  // Hydration virtual modules
827
867
  if (id === RESOLVED_HYDRATION_REGISTRY) {
828
868
  // Always scan - paths are auto-derived from puckConfigPath
@@ -944,7 +984,6 @@ initHydration(componentRegistry)
944
984
  'clsx',
945
985
  'tailwind-merge',
946
986
  // Content processing
947
- 'zod',
948
987
  'yaml',
949
988
  'nanoid',
950
989
  'sort-keys',
@@ -1,84 +1,134 @@
1
- // Drop-in replacement for `@tiptap/html` in server bundles: same named exports,
2
- // no DOM anywhere. The richtext field render imports `generateHTML`/`generateJSON`
1
+ // Drop-in replacement for `@tiptap/html` wherever the site's build resolves it, in
2
+ // the editor and in the server render alike: same named exports, no happy-dom and
3
+ // no `node:vm`. The richtext field render imports `generateHTML`/`generateJSON`
3
4
  // from `@tiptap/html`; its browser build needs `window`, and its `/server` build
4
5
  // fakes one with happy-dom — whose `Window` constructor calls `node:vm`
5
6
  // (`Script.runInContext`). Workers runtimes ship `node:vm` as a stub, so that
6
- // call throws at render time and every richtext section on the page dies. The
7
- // static renderer walks the ProseMirror document and writes the markup as a
8
- // string instead, so the same output comes out on any engine.
7
+ // call throws at render time and every richtext section on the page dies. Here
8
+ // ProseMirror's own serializer, the one `@tiptap/html` runs, writes into a few
9
+ // string-backed elements instead of a DOM, so the same markup comes out on any
10
+ // engine; reading HTML back takes the browser's own parser, or linkedom where
11
+ // there is none.
12
+ import { type Extensions, getSchema, type JSONContent } from '@tiptap/core';
9
13
  import {
10
- escapeHTML,
11
- renderJSONContentToString,
12
- serializeChildrenToHTMLString,
13
- } from '@tiptap/static-renderer/json/html-string';
14
- import { domOutputSpecToHTMLString, renderToElement } from '@tiptap/static-renderer/pm/html-string';
14
+ DOMSerializer,
15
+ type ParseOptions,
16
+ DOMParser as ProseMirrorDOMParser,
17
+ Node as ProseMirrorNode,
18
+ } from '@tiptap/pm/model';
19
+ import { parseHTML } from 'linkedom/worker';
15
20
 
16
- type RenderArgs = Parameters<typeof renderToElement<string>>[0];
17
- type RichTextContent = RenderArgs['content'];
18
- type RichTextExtensions = RenderArgs['extensions'];
19
- type ElementSpec = Parameters<typeof domOutputSpecToHTMLString>[0];
21
+ // Elements the HTML parser closes on its own, so a DOM serializer writes no end tag.
22
+ const VOID_ELEMENTS = new Set([
23
+ 'area',
24
+ 'base',
25
+ 'br',
26
+ 'col',
27
+ 'embed',
28
+ 'hr',
29
+ 'img',
30
+ 'input',
31
+ 'link',
32
+ 'meta',
33
+ 'param',
34
+ 'source',
35
+ 'track',
36
+ 'wbr',
37
+ ]);
20
38
 
21
- // Void elements the HTML parser closes on its own. The static renderer writes
22
- // them self-closing (`<br/>`); a DOM serializer writes `<br>`. Both parse
23
- // identically, but the rendered markup is compared byte for byte against the
24
- // DOM output, so normalize to the DOM spelling.
25
- const VOID_ELEMENTS = /<(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)((?:\s[^>]*?)?)\/>/gi;
39
+ const escapeText = (text: string) =>
40
+ text
41
+ .replace(/&/g, '&amp;')
42
+ .replace(/\u00a0/g, '&nbsp;')
43
+ .replace(/</g, '&lt;')
44
+ .replace(/>/g, '&gt;');
45
+
46
+ const escapeAttribute = (value: string) => escapeText(value).replace(/"/g, '&quot;');
47
+
48
+ class StringText {
49
+ readonly nodeType = 3;
50
+ constructor(private readonly text: string) {}
51
+ toString(): string {
52
+ return escapeText(this.text);
53
+ }
54
+ }
26
55
 
27
56
  /**
28
- * Drops the attributes an extension left empty. A DOM serializer skips those;
29
- * the string renderer would spell them out as the text "null" (`class="null"`
30
- * on every link, `type="null"` on every ordered list).
57
+ * An element as far as ProseMirror's serializer uses one: attributes in the
58
+ * order they were set, children appended. Having no `style` object, it takes
59
+ * `style` as a plain attribute, as written.
31
60
  */
32
- function withoutEmptyAttributes(spec: ElementSpec): ElementSpec {
33
- if (!Array.isArray(spec)) {
34
- return spec;
61
+ class StringElement {
62
+ readonly nodeType = 1;
63
+ private readonly attributes = new Map<string, string>();
64
+ private readonly children: (StringElement | StringText)[] = [];
65
+ constructor(private readonly tagName: string) {}
66
+
67
+ setAttribute(name: string, value: unknown): void {
68
+ this.attributes.set(name, String(value));
35
69
  }
36
70
 
37
- const [tag, ...parts] = spec;
38
- const cleaned: [string, ...unknown[]] = [
39
- tag,
40
- ...parts.map((part: unknown, index) => {
41
- // Position 0 of the rest holds the attributes, unless the element has
42
- // none — then a nested element spec sits there instead.
43
- if (Array.isArray(part) && typeof part[0] === 'string') {
44
- return withoutEmptyAttributes(part as [string, ...unknown[]]);
45
- }
46
- if (index !== 0 || part === null || typeof part !== 'object') {
47
- return part;
48
- }
49
- return Object.fromEntries(Object.entries(part).filter(([, value]) => value !== null && value !== undefined));
50
- }),
51
- ];
71
+ setAttributeNS(_namespace: string | null, name: string, value: unknown): void {
72
+ this.setAttribute(name, value);
73
+ }
52
74
 
53
- return cleaned;
54
- }
75
+ appendChild<T extends StringElement | StringText>(child: T): T {
76
+ this.children.push(child);
77
+ return child;
78
+ }
55
79
 
56
- /** Generates HTML from a ProseMirror JSON document, without a DOM. */
57
- export function generateHTML(doc: RichTextContent, extensions: RichTextExtensions): string {
58
- const html = renderToElement<string>({
59
- // The string renderer's own generic defaults describe plain JSON marks;
60
- // this walk hands it ProseMirror ones. Same function, narrower input.
61
- renderer: renderJSONContentToString as RenderArgs['renderer'],
62
- domOutputSpecToElement: (spec) => domOutputSpecToHTMLString(withoutEmptyAttributes(spec)),
63
- mapDefinedTypes: {
64
- doc: ({ children }) => serializeChildrenToHTMLString(children),
65
- text: ({ node }) => escapeHTML(node.text ?? ''),
66
- },
67
- content: doc,
68
- extensions,
69
- });
80
+ get innerHTML(): string {
81
+ return this.children.join('');
82
+ }
70
83
 
71
- return html.replace(VOID_ELEMENTS, '<$1$2>');
84
+ toString(): string {
85
+ const attributes = [...this.attributes].map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join('');
86
+ const open = `<${this.tagName}${attributes}>`;
87
+ return VOID_ELEMENTS.has(this.tagName) ? open : `${open}${this.innerHTML}</${this.tagName}>`;
88
+ }
72
89
  }
73
90
 
91
+ const stringDocument = {
92
+ createElement: (tagName: string) => new StringElement(tagName),
93
+ createElementNS: (_namespace: string, tagName: string) => new StringElement(tagName),
94
+ createTextNode: (text: string) => new StringText(text),
95
+ };
96
+
74
97
  /**
75
- * Parsing an HTML string back into ProseMirror JSON needs a real HTML parser,
76
- * which no DOM-free server runtime provides. Richtext values written by the
77
- * editor are already ProseMirror JSON, so this only trips on hand-authored HTML
78
- * strings — and says so instead of failing deep inside a fake DOM.
98
+ * Generates HTML from a ProseMirror JSON document, without a DOM. The
99
+ * serializer keeps a mark's element open across the runs that share it, so a
100
+ * link with one underlined word stays one link.
79
101
  */
80
- export function generateJSON(_html: string, _extensions: RichTextExtensions): Record<string, unknown> {
81
- throw new Error(
82
- 'generateJSON cannot parse HTML without a DOM. Store richtext values as tiptap JSON documents instead of HTML strings.',
102
+ export function generateHTML(doc: JSONContent, extensions: Extensions): string {
103
+ const schema = getSchema(extensions);
104
+ const root = new StringElement('div');
105
+ // The string-backed elements cover every DOM call the serializer makes, under types of their own.
106
+ DOMSerializer.fromSchema(schema).serializeFragment(
107
+ ProseMirrorNode.fromJSON(schema, doc).content,
108
+ { document: stringDocument as unknown as Document },
109
+ root as unknown as HTMLElement,
83
110
  );
111
+ return root.innerHTML;
112
+ }
113
+
114
+ /**
115
+ * Reads an HTML string into a ProseMirror JSON document. The richtext field stores
116
+ * the editor's HTML and its render reads it back through here. A browser parses
117
+ * with its own DOMParser; a server render has none, so linkedom parses there —
118
+ * plain JavaScript without `node:vm`, so it runs in Workers runtimes too.
119
+ */
120
+ export function generateJSON(html: string, extensions: Extensions, options?: ParseOptions): Record<string, unknown> {
121
+ const parser = ProseMirrorDOMParser.fromSchema(getSchema(extensions));
122
+ if (typeof globalThis.DOMParser === 'function') {
123
+ const { body } = new globalThis.DOMParser().parseFromString(html, 'text/html');
124
+ return parser.parse(body, options).toJSON();
125
+ }
126
+
127
+ const { document } = parseHTML(`<!DOCTYPE html><html><body>${html}</body></html>`);
128
+ // linkedom's elements implement the part of the DOM ProseMirror reads, under types of their own.
129
+ const doc = parser.parse(document.body as unknown as Node, options).toJSON();
130
+ // linkedom answers `getAttribute('class')` with "" for an element that has no
131
+ // class, where a browser answers null, so every link would read back with an
132
+ // empty class and render as `class=""`. Give the null back.
133
+ return JSON.parse(JSON.stringify(doc), (key, value) => (key === 'class' && value === '' ? null : value));
84
134
  }
@@ -57,6 +57,20 @@ declare module 'virtual:conloca-puck-config' {
57
57
  export default config;
58
58
  }
59
59
 
60
+ /**
61
+ * Virtual module: virtual:conloca-content-schemas
62
+ *
63
+ * The site's `contentSchemasPath` module (the `pageSchemas` / `dataSchemas`
64
+ * its content config hands the collection factories), imported on the first
65
+ * call only; an empty object when the site names none. A preview render
66
+ * builds its collections' entry parsers from it.
67
+ */
68
+ declare module 'virtual:conloca-content-schemas' {
69
+ import type { DataSchemas, PageSchemas } from '@conloca/cms-spa/page-schema-define';
70
+
71
+ export function loadContentSchemas(): Promise<{ pageSchemas?: PageSchemas; dataSchemas?: DataSchemas }>;
72
+ }
73
+
60
74
  /**
61
75
  * Virtual module: virtual:conloca-hydration-entry
62
76
  *
@@ -1,44 +0,0 @@
1
- import { type PageSchemas } from '@conloca/cms-spa/page-schema-define';
2
- import type { ContentMeta } from '@conloca/content-api';
3
- import { type PageMeta } from '@conloca/content-api/schemas';
4
- import { z } from 'zod';
5
- /**
6
- * Fold every page-schema descriptor into one Zod object of host meta fields.
7
- * Requiredness is not preserved — the caller always `.partial()`s this for the
8
- * collection, because Astro validates the whole `pages` pile.
9
- *
10
- * The merged object has one slot per field name, so two descriptors may only
11
- * declare the same name by sharing the same field schema instance — last-wins
12
- * would silently rewrite what the earlier prefix's pages are validated
13
- * against, failing them with a Zod error that names neither descriptor.
14
- */
15
- export declare function hostFieldsFromPageSchemas(pageSchemas: PageSchemas): z.ZodObject<z.ZodRawShape>;
16
- /**
17
- * A page collection entry as the loader delivers it: the validated
18
- * `pageMetaSchema` fields, the loader-written record fields (`created`,
19
- * `modified`, `name`, `puckData` — admitted by the loose index at runtime),
20
- * and the host's meta fields through `ContentMeta`/`HostPageMeta`.
21
- */
22
- export type ConlocaPageEntry = ContentMeta & PageMeta & {
23
- created?: string | Date;
24
- modified?: string | Date;
25
- name?: string;
26
- puckData?: unknown;
27
- };
28
- /**
29
- * The schema Astro validates page entries against: the host's page-meta fields
30
- * (all optional) with conloca's structural fields layered over them, loose so
31
- * undeclared top-level fields still reach the rendered page.
32
- *
33
- * Looseness is TOP-LEVEL ONLY. A nested `z.object()` still strips undeclared
34
- * nested keys; a host that wants them preserved has to write `z.looseObject()`.
35
- *
36
- * Rewrite bans (.default / .coerce / .transform / .catch) walk nested objects,
37
- * arrays, and unions. `.partial()` is still shallow.
38
- *
39
- * Internal on purpose: `src/collections.ts` is a published entry (the
40
- * `./collections` subpath), so anything exported from there is frozen under
41
- * semver. Nothing outside this package consumes it.
42
- */
43
- export declare function buildPageCollectionSchema(hostFields: z.ZodObject<z.ZodRawShape>): z.ZodType<ConlocaPageEntry>;
44
- //# sourceMappingURL=page-collection-schema.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"page-collection-schema.d.ts","sourceRoot":"","sources":["../../../../src/internal/page-collection-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAA0B,MAAM,qCAAqC,CAAC;AAC/F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,KAAK,QAAQ,EAAkB,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAwGxB;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,WAAW,EAAE,WAAW,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CA4B9F;AAED;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,WAAW,GACxC,QAAQ,GAAG;IACT,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAc7G"}