@avocadostudio-ai/richtext 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Avocado Studio Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # @avocadostudio-ai/richtext
2
+
3
+ The Avocado Studio rich-text grammar, and converters between it and the shapes
4
+ three CMSes actually store.
5
+
6
+ No runtime dependencies, and no knowledge of React, the orchestrator or any CMS
7
+ client — the CMS types are structural, so a one-off migration script can convert
8
+ a dataset without installing anything else.
9
+
10
+ ## Two layers
11
+
12
+ **The grammar** (`parse.ts`) is the markdown subset an Avocado `richtext` string
13
+ is written in — sized to exactly what the property panel's editor can produce,
14
+ so anything a person can type comes back rendered rather than as punctuation. It
15
+ is a parser only: it returns tokens, and what a heading or a link looks like on
16
+ screen belongs to the calling surface.
17
+
18
+ **The pivot** (`doc.ts`) is a ProseMirror document — the shape the property
19
+ panel edits natively. Every format converts to and from it rather than to and
20
+ from each other, so a fourth CMS costs one converter pair instead of three.
21
+
22
+ ```
23
+ Contentful ─┐ ┌─ Contentful
24
+ Portable Text ├─→ RichTextDoc ─→ ─┤─ Portable Text
25
+ Strapi Blocks ─┤ (the pivot) ├─ Strapi Blocks
26
+ markdown ──────┘ └─ markdown
27
+ ```
28
+
29
+ ## Converters
30
+
31
+ | CMS | in | out |
32
+ | --- | --- | --- |
33
+ | Avocado markdown | `fromMarkdown` | `toMarkdown` |
34
+ | Sanity Portable Text | `fromPortableText` | `toPortableText` |
35
+ | Contentful Rich Text | `fromContentful` | `toContentful` |
36
+ | Strapi 5 Blocks | `fromStrapiBlocks` | `toStrapiBlocks` |
37
+
38
+ ```ts
39
+ import { fromPortableText, toPortableText } from "@avocadostudio-ai/richtext"
40
+
41
+ // read
42
+ const doc = fromPortableText(sanityBlock.body)
43
+
44
+ // write — `previous` is what makes this an update rather than a replacement
45
+ const body = toPortableText(doc, { previous: storedBlock.body })
46
+ ```
47
+
48
+ ## What survives
49
+
50
+ Node and mark `type` are open strings, not a union of the names we know. A
51
+ Portable Text block with a custom `_type`, a Contentful embedded entry, a
52
+ decorator some space enabled last week: none of them are in the vocabulary, and
53
+ a closed type would force each converter to throw them away. They ride through
54
+ the pivot as `avocadoUnknownBlock` carrying the source object under `attrs.data`
55
+ and come back out unchanged.
56
+
57
+ Passing `previous` to `toPortableText` goes further: an unchanged block is
58
+ re-emitted as *the stored object itself*, so keys, annotations and fields no
59
+ converter here understands are preserved byte-for-byte, and the CMS sees a diff
60
+ of what actually changed rather than "every block replaced".
61
+
62
+ `mergeRichTextDoc(next, previous)` is the same idea between two documents. It
63
+ carries stored keys onto a rebuilt document and puts back the blocks the rebuild
64
+ could not have contained — which is what makes it safe for the ops engine to
65
+ parse a planner's plain-string rewrite into a document without deleting the
66
+ embedded entry sitting in the middle of it.
67
+
68
+ ## What does not
69
+
70
+ Every format is missing something another one has, and the gaps are documented
71
+ at each conversion rather than papered over:
72
+
73
+ - **markdown has no underline** and no way to name a CMS's own decorator. Those
74
+ marks drop off in `toMarkdown` and the text stays. A value that needs them
75
+ should be stored as a document, not flattened.
76
+ - **markdown has no image** in this grammar — the editor has no image node and
77
+ deletes them — so an `![alt](src)` keeps its alt text. Images belong in an
78
+ `f.image` field.
79
+ - **Contentful has no code block**; `code` is a mark on text, so a code block
80
+ becomes a code-marked paragraph.
81
+ - **Portable Text and Strapi Blocks have no thematic break**, so a
82
+ `horizontalRule` is dropped rather than faked as a paragraph of dashes.
83
+ - **Heading levels clamp to h2–h6 when flattening to markdown**, because a page
84
+ body never owns the page's `h1`. The document path does not clamp — that is
85
+ the integration's outline, not ours.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Contentful Rich Text <-> the pivot document.
3
+ *
4
+ * Contentful is the recursive one: a `document` node containing block nodes
5
+ * containing inline nodes containing text, every node carrying a `data` object
6
+ * and a `nodeType` from a closed vocabulary. Two consequences shape this file.
7
+ *
8
+ * A link is a *node*, not a mark. `hyperlink` wraps the text it decorates, so a
9
+ * run of pivot text nodes sharing one link mark has to be gathered back into a
10
+ * single wrapper on the way out, and unwrapped into per-text marks on the way
11
+ * in — otherwise a two-word link comes back as two adjacent links.
12
+ *
13
+ * Nothing in a Contentful document is addressable. There are no keys, no
14
+ * per-node identity, and the API takes the whole field value on every write —
15
+ * so unlike Portable Text there is nothing to merge against and no `previous`
16
+ * parameter here. Content the vocabulary does not cover (embedded entries and
17
+ * assets, tables) still rides through as `avocadoUnknownBlock` so that editing
18
+ * the prose around an embedded entry does not delete it.
19
+ */
20
+ import { type RichTextDoc } from "./doc.ts";
21
+ export type ContentfulMark = {
22
+ type: string;
23
+ };
24
+ export type ContentfulNode = {
25
+ nodeType: string;
26
+ data?: Record<string, unknown>;
27
+ content?: ContentfulNode[];
28
+ value?: string;
29
+ marks?: ContentfulMark[];
30
+ };
31
+ export type ContentfulDocument = {
32
+ nodeType: "document";
33
+ data: Record<string, unknown>;
34
+ content: ContentfulNode[];
35
+ };
36
+ /** Convert a Contentful Rich Text document into the pivot document. */
37
+ export declare function fromContentful(document: unknown): RichTextDoc;
38
+ /** Convert the pivot document back to a Contentful Rich Text document. */
39
+ export declare function toContentful(doc: RichTextDoc): ContentfulDocument;
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Contentful Rich Text <-> the pivot document.
3
+ *
4
+ * Contentful is the recursive one: a `document` node containing block nodes
5
+ * containing inline nodes containing text, every node carrying a `data` object
6
+ * and a `nodeType` from a closed vocabulary. Two consequences shape this file.
7
+ *
8
+ * A link is a *node*, not a mark. `hyperlink` wraps the text it decorates, so a
9
+ * run of pivot text nodes sharing one link mark has to be gathered back into a
10
+ * single wrapper on the way out, and unwrapped into per-text marks on the way
11
+ * in — otherwise a two-word link comes back as two adjacent links.
12
+ *
13
+ * Nothing in a Contentful document is addressable. There are no keys, no
14
+ * per-node identity, and the API takes the whole field value on every write —
15
+ * so unlike Portable Text there is nothing to merge against and no `previous`
16
+ * parameter here. Content the vocabulary does not cover (embedded entries and
17
+ * assets, tables) still rides through as `avocadoUnknownBlock` so that editing
18
+ * the prose around an embedded entry does not delete it.
19
+ */
20
+ import { MARK, NODE } from "./doc.js";
21
+ const HEADING_NODE = /^heading-([1-6])$/;
22
+ /**
23
+ * Contentful's mark vocabulary, and the pivot marks they are.
24
+ *
25
+ * `strikethrough` is not in every space: it was added to the vocabulary later
26
+ * than the rest, and an environment whose field validation predates it rejects
27
+ * the mark. Reading one is always safe; writing one to an old space is not.
28
+ */
29
+ const CONTENTFUL_TO_MARK = {
30
+ bold: MARK.bold,
31
+ italic: MARK.italic,
32
+ underline: MARK.underline,
33
+ code: MARK.code,
34
+ strikethrough: MARK.strike
35
+ };
36
+ const MARK_TO_CONTENTFUL = Object.fromEntries(Object.entries(CONTENTFUL_TO_MARK).map(([contentful, mark]) => [mark, contentful]));
37
+ /** Link node types, and the pivot mark name each becomes. */
38
+ const LINK_NODES = new Set(["hyperlink", "entry-hyperlink", "asset-hyperlink"]);
39
+ function isObject(value) {
40
+ return typeof value === "object" && value !== null && !Array.isArray(value);
41
+ }
42
+ // ---------------------------------------------------------------------------
43
+ // Contentful -> document
44
+ // ---------------------------------------------------------------------------
45
+ function marksToPivot(marks) {
46
+ const out = [];
47
+ for (const mark of marks ?? []) {
48
+ if (typeof mark?.type !== "string")
49
+ continue;
50
+ // An unmapped mark keeps its own name rather than being dropped: a space
51
+ // may declare `superscript`, and the pivot is open enough to hold it.
52
+ out.push({ type: CONTENTFUL_TO_MARK[mark.type] ?? mark.type });
53
+ }
54
+ return out;
55
+ }
56
+ function inlineToPivot(nodes) {
57
+ const out = [];
58
+ for (const node of nodes ?? []) {
59
+ if (node.nodeType === "text") {
60
+ const text = typeof node.value === "string" ? node.value : "";
61
+ if (text.length === 0)
62
+ continue;
63
+ const marks = marksToPivot(node.marks);
64
+ out.push({ type: NODE.text, text, ...(marks.length > 0 ? { marks } : {}) });
65
+ continue;
66
+ }
67
+ if (LINK_NODES.has(node.nodeType)) {
68
+ const attrs = node.nodeType === "hyperlink"
69
+ ? { href: typeof node.data?.uri === "string" ? node.data.uri : "" }
70
+ : { href: "", data: node.data ?? {} };
71
+ const linkMark = { type: node.nodeType === "hyperlink" ? MARK.link : node.nodeType, attrs };
72
+ for (const child of inlineToPivot(node.content)) {
73
+ out.push({ ...child, marks: [...(child.marks ?? []), linkMark] });
74
+ }
75
+ continue;
76
+ }
77
+ // An inline embed. No text to keep, so keep the node.
78
+ out.push({ type: NODE.unknown, attrs: { data: node } });
79
+ }
80
+ return out;
81
+ }
82
+ function blockToPivot(node) {
83
+ const heading = HEADING_NODE.exec(node.nodeType);
84
+ if (heading) {
85
+ const content = inlineToPivot(node.content);
86
+ const base = { type: NODE.heading, attrs: { level: Number(heading[1]) } };
87
+ return [content.length > 0 ? { ...base, content } : base];
88
+ }
89
+ switch (node.nodeType) {
90
+ case "paragraph": {
91
+ const content = inlineToPivot(node.content);
92
+ return [content.length > 0 ? { type: NODE.paragraph, content } : { type: NODE.paragraph }];
93
+ }
94
+ case "unordered-list":
95
+ case "ordered-list":
96
+ return [
97
+ {
98
+ type: node.nodeType === "ordered-list" ? NODE.orderedList : NODE.bulletList,
99
+ content: (node.content ?? [])
100
+ .filter((child) => child.nodeType === "list-item")
101
+ .map((child) => ({
102
+ type: NODE.listItem,
103
+ content: (child.content ?? []).flatMap(blockToPivot)
104
+ }))
105
+ }
106
+ ];
107
+ case "blockquote":
108
+ return [{ type: NODE.blockquote, content: (node.content ?? []).flatMap(blockToPivot) }];
109
+ case "hr":
110
+ return [{ type: NODE.horizontalRule }];
111
+ default:
112
+ return [{ type: NODE.unknown, attrs: { data: node } }];
113
+ }
114
+ }
115
+ /** Convert a Contentful Rich Text document into the pivot document. */
116
+ export function fromContentful(document) {
117
+ if (!isObject(document) || document.nodeType !== "document")
118
+ return { type: "doc", content: [] };
119
+ const content = Array.isArray(document.content) ? document.content : [];
120
+ return { type: "doc", content: content.filter(isObject).flatMap(blockToPivot) };
121
+ }
122
+ // ---------------------------------------------------------------------------
123
+ // document -> Contentful
124
+ // ---------------------------------------------------------------------------
125
+ function linkMarkOf(node) {
126
+ const mark = node.marks?.find((m) => m.type === MARK.link || LINK_NODES.has(m.type));
127
+ if (!mark)
128
+ return undefined;
129
+ return { type: mark.type === MARK.link ? "hyperlink" : mark.type, attrs: mark.attrs ?? {} };
130
+ }
131
+ function textToContentful(node) {
132
+ const marks = [];
133
+ for (const mark of node.marks ?? []) {
134
+ if (mark.type === MARK.link || LINK_NODES.has(mark.type))
135
+ continue;
136
+ marks.push({ type: MARK_TO_CONTENTFUL[mark.type] ?? mark.type });
137
+ }
138
+ return { nodeType: "text", value: node.text ?? "", marks, data: {} };
139
+ }
140
+ function linkData(nodeType, attrs) {
141
+ if (nodeType === "hyperlink")
142
+ return { uri: typeof attrs.href === "string" ? attrs.href : "" };
143
+ return isObject(attrs.data) ? attrs.data : {};
144
+ }
145
+ /**
146
+ * Serialise inline nodes, gathering adjacent text that shares one link into a
147
+ * single wrapper node. Contentful models a link as a node around its text, so
148
+ * emitting one wrapper per text node would split every multi-span link in two.
149
+ */
150
+ function inlineToContentful(nodes) {
151
+ const out = [];
152
+ let openLink;
153
+ const flush = () => {
154
+ openLink = undefined;
155
+ };
156
+ for (const node of nodes ?? []) {
157
+ if (node.type === NODE.unknown && isObject(node.attrs?.data)) {
158
+ flush();
159
+ out.push(node.attrs.data);
160
+ continue;
161
+ }
162
+ if (node.type === NODE.hardBreak) {
163
+ // Contentful has no break node — a newline inside the text value is how
164
+ // the reference renderers express a soft break.
165
+ const target = openLink ? openLink.node.content : out;
166
+ const last = target?.[target.length - 1];
167
+ if (last && typeof last.value === "string")
168
+ last.value += "\n";
169
+ continue;
170
+ }
171
+ if (typeof node.text !== "string" || node.text.length === 0)
172
+ continue;
173
+ const link = linkMarkOf(node);
174
+ if (!link) {
175
+ flush();
176
+ out.push(textToContentful(node));
177
+ continue;
178
+ }
179
+ const key = `${link.type}::${JSON.stringify(link.attrs)}`;
180
+ if (!openLink || openLink.key !== key) {
181
+ openLink = {
182
+ key,
183
+ node: { nodeType: link.type, data: linkData(link.type, link.attrs), content: [] }
184
+ };
185
+ out.push(openLink.node);
186
+ }
187
+ openLink.node.content.push(textToContentful(node));
188
+ }
189
+ return out;
190
+ }
191
+ function nodeToContentful(node) {
192
+ switch (node.type) {
193
+ case NODE.paragraph:
194
+ return [{ nodeType: "paragraph", data: {}, content: inlineToContentful(node.content) }];
195
+ case NODE.heading: {
196
+ const level = typeof node.attrs?.level === "number" ? Math.min(6, Math.max(1, node.attrs.level)) : 2;
197
+ return [{ nodeType: `heading-${level}`, data: {}, content: inlineToContentful(node.content) }];
198
+ }
199
+ case NODE.bulletList:
200
+ case NODE.orderedList:
201
+ return [
202
+ {
203
+ nodeType: node.type === NODE.orderedList ? "ordered-list" : "unordered-list",
204
+ data: {},
205
+ content: (node.content ?? []).map((item) => ({
206
+ nodeType: "list-item",
207
+ data: {},
208
+ content: (item.content ?? []).flatMap(nodeToContentful)
209
+ }))
210
+ }
211
+ ];
212
+ case NODE.blockquote:
213
+ return [{ nodeType: "blockquote", data: {}, content: (node.content ?? []).flatMap(nodeToContentful) }];
214
+ case NODE.codeBlock: {
215
+ /*
216
+ * Contentful has no code *block* — `code` is a mark on text. The closest
217
+ * faithful rendering is a paragraph whose text carries that mark, which
218
+ * is what the reference renderers style as a code span. Round-tripping a
219
+ * code block through Contentful therefore returns a code-marked
220
+ * paragraph, not a code block.
221
+ */
222
+ const code = (node.content ?? []).map((c) => c.text ?? "").join("");
223
+ return [
224
+ {
225
+ nodeType: "paragraph",
226
+ data: {},
227
+ content: [{ nodeType: "text", value: code, marks: [{ type: "code" }], data: {} }]
228
+ }
229
+ ];
230
+ }
231
+ case NODE.horizontalRule:
232
+ return [{ nodeType: "hr", data: {}, content: [] }];
233
+ case NODE.unknown:
234
+ return isObject(node.attrs?.data) ? [node.attrs.data] : [];
235
+ default:
236
+ return (node.content ?? []).flatMap(nodeToContentful);
237
+ }
238
+ }
239
+ /** Convert the pivot document back to a Contentful Rich Text document. */
240
+ export function toContentful(doc) {
241
+ return {
242
+ nodeType: "document",
243
+ data: {},
244
+ content: (doc.content ?? []).flatMap(nodeToContentful)
245
+ };
246
+ }
package/dist/doc.d.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The pivot format: a ProseMirror document.
3
+ *
4
+ * Every CMS in this package models rich text differently — Contentful nests a
5
+ * recursive `document` tree, Sanity keeps a flat array of Portable Text blocks,
6
+ * Strapi a flat Slate-shaped array — and Avocado's own `richtext` fields hold a
7
+ * markdown string. Converting each pair directly would need six converters and
8
+ * would still lose whatever the two ends did not have in common. Instead every
9
+ * format converts to and from one shape, and that shape is the ProseMirror
10
+ * document the property panel already edits natively (`RichTextJsonField`).
11
+ *
12
+ * The types are deliberately open — `type` is a `string`, not a union of the
13
+ * names we know. A Portable Text block with a custom `_type`, a Contentful
14
+ * `embedded-entry-block`, a mark some space enabled last week: none of them are
15
+ * in our vocabulary, and a closed union would force each converter to throw the
16
+ * value away. They ride through the pivot as data instead, which is what makes
17
+ * a round trip through Avocado non-destructive for content Avocado cannot edit.
18
+ *
19
+ * Node and mark names are Tiptap's, because the editor is Tiptap: `paragraph`,
20
+ * `heading`, `bulletList`, `orderedList`, `listItem`, `blockquote`, `codeBlock`,
21
+ * `horizontalRule`, `hardBreak`, `text`; marks `bold`, `italic`, `strike`,
22
+ * `code`, `underline`, `link`.
23
+ */
24
+ export type RichTextMark = {
25
+ type: string;
26
+ attrs?: Record<string, unknown> | null;
27
+ };
28
+ export type RichTextNode = {
29
+ type: string;
30
+ attrs?: Record<string, unknown> | null;
31
+ content?: RichTextNode[];
32
+ marks?: RichTextMark[];
33
+ text?: string;
34
+ };
35
+ export type RichTextDoc = {
36
+ type: "doc";
37
+ content: RichTextNode[];
38
+ };
39
+ /** Node names this package produces and understands. */
40
+ export declare const NODE: {
41
+ readonly doc: "doc";
42
+ readonly paragraph: "paragraph";
43
+ readonly heading: "heading";
44
+ readonly bulletList: "bulletList";
45
+ readonly orderedList: "orderedList";
46
+ readonly listItem: "listItem";
47
+ readonly blockquote: "blockquote";
48
+ readonly codeBlock: "codeBlock";
49
+ readonly horizontalRule: "horizontalRule";
50
+ readonly hardBreak: "hardBreak";
51
+ readonly text: "text";
52
+ /**
53
+ * A block the pivot could not model — a Portable Text `_type` we do not know,
54
+ * a Contentful embedded entry, a Strapi image. It carries the source object
55
+ * untouched under `attrs.data` so the converter back out can re-emit it
56
+ * unchanged. The editor registers a matching read-only node, so it also
57
+ * survives a trip through the property panel in its original position.
58
+ */
59
+ readonly unknown: "avocadoUnknownBlock";
60
+ };
61
+ /** Mark names this package produces and understands. */
62
+ export declare const MARK: {
63
+ readonly bold: "bold";
64
+ readonly italic: "italic";
65
+ readonly strike: "strike";
66
+ readonly code: "code";
67
+ readonly underline: "underline";
68
+ readonly link: "link";
69
+ };
70
+ /**
71
+ * A richtext value stored as a document rather than a markdown string.
72
+ *
73
+ * The same signature `block-manifest.ts` keys its `isProseMirrorDocSchema` off:
74
+ * an object whose `type` is the literal `"doc"`. Anything else — a markdown
75
+ * string included — is not a document and must not be handed to the converters.
76
+ */
77
+ export declare function isRichTextDoc(value: unknown): value is RichTextDoc;
78
+ export declare function emptyDoc(): RichTextDoc;
79
+ /** Parse an Avocado markdown richtext value into the pivot document. */
80
+ export declare function fromMarkdown(markdown: string): RichTextDoc;
81
+ export declare function escapeMarkdownText(text: string): string;
82
+ /** Serialise the pivot document to an Avocado markdown richtext value. */
83
+ export declare function toMarkdown(input: RichTextDoc | RichTextNode[]): string;