@tozd/prosemirror 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 reasonable and customary use in describing the
141
+ origin of the Work and 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 Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
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 [yyyy] [name of copyright owner]
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/NOTICE ADDED
@@ -0,0 +1,22 @@
1
+ The ported Go packages are derivative works of the corresponding ProseMirror
2
+ (https://prosemirror.net/) packages, used under the MIT license:
3
+
4
+ Copyright (C) 2015-2017 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in
14
+ all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # Go port of ProseMirror
2
+
3
+ [![pkg.go.dev](https://pkg.go.dev/badge/gitlab.com/tozd/go/prosemirror)](https://pkg.go.dev/gitlab.com/tozd/go/prosemirror)
4
+ [![NPM](https://img.shields.io/npm/v/@tozd/prosemirror.svg)](https://www.npmjs.com/package/@tozd/prosemirror)
5
+ [![Go Report Card](https://goreportcard.com/badge/gitlab.com/tozd/go/prosemirror)](https://goreportcard.com/report/gitlab.com/tozd/go/prosemirror)
6
+ [![pipeline status](https://gitlab.com/tozd/go/prosemirror/badges/main/pipeline.svg?ignore_skipped=true)](https://gitlab.com/tozd/go/prosemirror/-/pipelines)
7
+ [![coverage report](https://gitlab.com/tozd/go/prosemirror/badges/main/coverage.svg)](https://gitlab.com/tozd/go/prosemirror/-/graphs/main/charts)
8
+
9
+ A Go port of [ProseMirror](https://prosemirror.net/) for server-side parsing, validation, and canonical HTML
10
+ serialization of documents, with a TypeScript companion (the `@tozd/prosemirror` NPM package) that builds the same
11
+ schema in the browser from the same shareable JSON.
12
+
13
+ The components currently available:
14
+
15
+ - `model` package, ported from [prosemirror-model](https://github.com/ProseMirror/prosemirror-model) v1.25.8 – the
16
+ document model: schemas, nodes, marks, content expressions, HTML fragment parsing, and canonical HTML serialization.
17
+
18
+ Each ported component mirrors the structure of its ProseMirror
19
+ TypeScript source so the two can be kept in sync. See [PORTING.md](PORTING.md)
20
+ for the porting contract.
21
+
22
+ It is used by [PeerDB](https://gitlab.com/peerdb/peerdb), a collaborative database.
23
+
24
+ ## Installation
25
+
26
+ ### Go installation
27
+
28
+ You can add it to your project using `go get`:
29
+
30
+ ```sh
31
+ go get gitlab.com/tozd/go/prosemirror/model
32
+ ```
33
+
34
+ It requires Go 1.25 or newer.
35
+
36
+ ### TypeScript/JavaScript installation
37
+
38
+ You can add frontend utilities for Go port of ProseMirror to your project using `npm`:
39
+
40
+ ```sh
41
+ npm install --save @tozd/prosemirror prosemirror-model
42
+ ```
43
+
44
+ It requires node 22 or newer.
45
+
46
+ ## Usage
47
+
48
+ ### Go usage
49
+
50
+ ```go
51
+ schema, errE := model.NewSchema(schemaJSON, map[string]model.AttrValidator{
52
+ "linkURL": validateLinkURL,
53
+ })
54
+ if errE != nil {
55
+ // Handle the error.
56
+ }
57
+
58
+ doc, errE := model.ParseHTML(schema, `<p>Hello, <b>world</b>!</p>`, model.ParseOptions{})
59
+ if errE != nil {
60
+ // Handle the error.
61
+ }
62
+
63
+ canonical := model.SerializeHTML(doc)
64
+
65
+ ok, errE := model.IsCanonicalHTML(schema, canonical, model.ParseOptions{})
66
+ // ok is true: serializing a parsed document always yields the canonical form.
67
+ ```
68
+
69
+ See full package documentation with examples on [pkg.go.dev](https://pkg.go.dev/gitlab.com/tozd/go/prosemirror#section-documentation).
70
+
71
+ ### TypeScript/JavaScript usage
72
+
73
+ The same schema JSON can be built into a ProseMirror schema in the browser:
74
+
75
+ ```ts
76
+ import { buildSchema } from "@tozd/prosemirror"
77
+
78
+ const schema = buildSchema(schemaJSON, { linkURL: validateLinkURL })
79
+ ```
80
+
81
+ `buildSchema` takes a parsed schema JSON object and a registry of named attribute validators and returns a
82
+ `prosemirror-model` `Schema`, with `parseDOM` and `toDOM` derived from the dialect, the browser-usable counterpart of
83
+ `model.NewSchema`. `prosemirror-model` is a peer dependency. The frontend and the Go backend build the same schema from
84
+ one shared JSON definition.
85
+
86
+ ## Schema JSON dialect
87
+
88
+ Schemas are described by a single JSON document that can be shared with a ProseMirror TypeScript implementation.
89
+ Functions cannot live in JSON, so attribute validators are referenced by name (resolved against a registry passed to
90
+ `model.NewSchema`) and the HTML mapping is declarative (`toHTML` and `parseHTML` keys on nodes and marks).
91
+ `model.NewSchema` accepts any spec in this dialect, not only the example schema shipped as a fixture: `toHTML` covers
92
+ the declarative subset of ProseMirror's `DOMOutputSpec` (including nested elements such as a code block rendered as
93
+ `pre` wrapping `code`), and `parseHTML` accepts a full CSS selector in `tag` (matched with
94
+ [cascadia](https://github.com/andybalholm/cascadia)), style rules keyed on an inline CSS declaration
95
+ (`{"style": "font-weight=bold"}`), and a `namespace` constraint, alongside `context` and `priority`. See
96
+ [PORTING.md](PORTING.md) for the full specification of the dialect.
97
+
98
+ The one documented fidelity boundary is style matching: a style rule matches only an element's own inline longhand
99
+ declarations and does not perform CSSOM shorthand expansion or value normalization. So `style="font-weight: bold"`
100
+ matches a `font-weight` rule, but `style="font: bold 12px serif"` (which exposes `font-weight` only after shorthand
101
+ expansion in a browser) does not. Everything else parses identically to the browser. Editor-only behaviors and the
102
+ transform and collaboration layers are out of scope.
103
+
104
+ ## Related projects
105
+
106
+ - [prosemirror-go](https://github.com/cozy/prosemirror-go) – a similar port which is somewhat stale and is
107
+ licensed under AGPL.
108
+
109
+ ## GitHub mirror
110
+
111
+ There is also a [read-only GitHub mirror available](https://github.com/tozd/go-prosemirror),
112
+ if you need to fork the project there.
113
+
114
+ ## Disclaimer
115
+
116
+ Port has been fully generated and maintained by AI.
117
+
118
+ ## License
119
+
120
+ Licensed under the Apache License, Version 2.0 (see [LICENSE](LICENSE)). The ported packages are derivative works of the
121
+ corresponding [ProseMirror](https://prosemirror.net/) packages, used under the MIT license (see [NOTICE](NOTICE)).
@@ -0,0 +1,66 @@
1
+ import type { Attrs, DOMOutputSpec, MarkSpec, NodeSpec, ParseOptions, ParseRule, Node as PMNode } from "prosemirror-model";
2
+ import { Schema } from "prosemirror-model";
3
+ export interface AttributeSpecJSON {
4
+ default?: unknown;
5
+ validate?: string;
6
+ onInvalid?: "rejectRule" | "drop";
7
+ }
8
+ export interface ToHTMLJSON {
9
+ tag: string;
10
+ attrs?: string[];
11
+ content?: ToHTMLJSON;
12
+ }
13
+ export interface ParseRuleJSON {
14
+ tag?: string;
15
+ style?: string;
16
+ namespace?: string;
17
+ context?: string;
18
+ priority?: number;
19
+ preserveWhitespace?: boolean | "full";
20
+ attrs?: Record<string, unknown>;
21
+ }
22
+ export interface NodeSpecJSON {
23
+ content?: string;
24
+ marks?: string;
25
+ group?: string;
26
+ inline?: boolean;
27
+ atom?: boolean;
28
+ code?: boolean;
29
+ whitespace?: "pre" | "normal";
30
+ linebreakReplacement?: boolean;
31
+ defining?: boolean;
32
+ selectable?: boolean;
33
+ attrs?: Record<string, AttributeSpecJSON>;
34
+ toHTML?: ToHTMLJSON;
35
+ parseHTML?: ParseRuleJSON[];
36
+ }
37
+ export interface MarkSpecJSON {
38
+ group?: string;
39
+ code?: boolean;
40
+ excludes?: string;
41
+ spanning?: boolean;
42
+ inclusive?: boolean;
43
+ attrs?: Record<string, AttributeSpecJSON>;
44
+ toHTML?: ToHTMLJSON;
45
+ parseHTML?: ParseRuleJSON[];
46
+ }
47
+ export interface SchemaJSON {
48
+ topNode?: string;
49
+ nodes: Record<string, NodeSpecJSON>;
50
+ marks?: Record<string, MarkSpecJSON>;
51
+ }
52
+ export type Validator = (value: unknown) => boolean;
53
+ export declare function buildParseRule(ruleJSON: ParseRuleJSON, attrSpecs: Record<string, AttributeSpecJSON> | undefined, validators: Record<string, Validator>): ParseRule;
54
+ export declare function buildOutputSpec(toHTML: ToHTMLJSON, attrs: Attrs, hole: boolean): DOMOutputSpec;
55
+ export declare function buildAttrs(attrsJSON: Record<string, AttributeSpecJSON>): Record<string, {
56
+ default?: unknown;
57
+ }>;
58
+ export declare function translateNodeSpec(json: NodeSpecJSON, validators: Record<string, Validator>): NodeSpec;
59
+ export declare function translateMarkSpec(json: MarkSpecJSON, validators: Record<string, Validator>): MarkSpec;
60
+ export declare function buildSchema(spec: SchemaJSON, validators?: Record<string, Validator>): Schema;
61
+ export declare function escapeHTML(text: string): string;
62
+ export declare function serializeDOM(node: Node): string;
63
+ export declare function htmlToDoc(schema: Schema, html: string, options?: ParseOptions, domDocument?: Document): PMNode;
64
+ export declare function docToHtml(schema: Schema, doc: PMNode, domDocument?: Document): string;
65
+ export declare function isCanonicalHTML(schema: Schema, html: string, options?: ParseOptions, domDocument?: Document): boolean;
66
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAQ,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,IAAI,IAAI,MAAM,EAAgC,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BAAiB,CAAC,IAAI,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAcrG;AAOD,wBAAgB,WAAW,CAAC,IAAI,EAAE,UAAU,EAAE,UAAU,GAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAM,GAAG,MAAM,CAUhG;AAYD,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAWD,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CA0B/C;AAMD,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,EAAE,WAAW,GAAE,QAAmB,GAAG,MAAM,CAI5H;AAMD,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,WAAW,GAAE,QAAmB,GAAG,MAAM,CAO/F;AAKD,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,EAAE,WAAW,GAAE,QAAmB,GAAG,OAAO,CAEnI"}
package/dist/index.js ADDED
@@ -0,0 +1,266 @@
1
+ // ProseMirror frontend utilities for Go port of ProseMirror. It provides:
2
+ //
3
+ // A builder for ProseMirror Schema from the schema JSON dialect described in the "Schema JSON dialect" section of PORTING.md, the same dialect the Go port parses.
4
+ // Given an already-parsed schema JSON object and a registry of named attribute validators, it produces a prosemirror-model Schema (with parseDOM and toDOM derived
5
+ // from the dialect) that a frontend can use directly.
6
+ //
7
+ // A canonical HTML serializer (serializeDOM, with escapeHTML) that stringifies the DOM produced by prosemirror-model's DOMSerializer into the same canonical HTML
8
+ // the Go SerializeHTML emits (the same five-character escaping, lowercased tags, double-quoted attributes, void-element handling, and pre newline rule), so a
9
+ // frontend can compute the same canonical HTML as the backend.
10
+ //
11
+ // HTML conversion helpers (htmlToDoc, docToHtml, isCanonicalHTML) that parse an HTML string into a document of a given schema, serialize a document back to its
12
+ // canonical HTML, and report whether HTML is already canonical (its parse/serialize round trip is the identity), matching the Go ParseHTML/SerializeHTML and the
13
+ // claim-validity check IsCanonicalHTML.
14
+ import { DOMParser, DOMSerializer, Schema } from "prosemirror-model";
15
+ // Builds a ProseMirror parse rule from a dialect parseHTML rule. Constant attribute entries (number/boolean/null) become static rule attrs;
16
+ // string entries are attribute extraction and become a getAttrs function which reads the named HTML attribute, falls back to the attribute spec
17
+ // default when the attribute is absent (rejecting the rule when the attribute is required), and applies the named validator when one is
18
+ // configured: on failure, onInvalid "rejectRule" (the default) rejects the rule and "drop" replaces the value with the default.
19
+ export function buildParseRule(ruleJSON, attrSpecs, validators) {
20
+ // Style rules produce marks and match an inline CSS declaration; their attrs are always constants (the declarative dialect does not extract from the
21
+ // style value). Tag rules match a CSS selector, optionally restricted by namespace, and may extract attributes from the element.
22
+ if (ruleJSON.style !== undefined) {
23
+ const rule = { style: ruleJSON.style };
24
+ if (ruleJSON.context !== undefined)
25
+ rule.context = ruleJSON.context;
26
+ if (ruleJSON.priority !== undefined)
27
+ rule.priority = ruleJSON.priority;
28
+ if (ruleJSON.attrs !== undefined)
29
+ rule.attrs = ruleJSON.attrs;
30
+ return rule;
31
+ }
32
+ const rule = { tag: ruleJSON.tag };
33
+ if (ruleJSON.namespace !== undefined)
34
+ rule.namespace = ruleJSON.namespace;
35
+ if (ruleJSON.context !== undefined)
36
+ rule.context = ruleJSON.context;
37
+ if (ruleJSON.priority !== undefined)
38
+ rule.priority = ruleJSON.priority;
39
+ if (ruleJSON.preserveWhitespace !== undefined)
40
+ rule.preserveWhitespace = ruleJSON.preserveWhitespace;
41
+ if (ruleJSON.attrs !== undefined) {
42
+ const constants = {};
43
+ const extracted = {};
44
+ for (const [attrName, value] of Object.entries(ruleJSON.attrs)) {
45
+ if (typeof value === "string") {
46
+ extracted[attrName] = value;
47
+ }
48
+ else {
49
+ constants[attrName] = value;
50
+ }
51
+ }
52
+ if (Object.keys(extracted).length === 0) {
53
+ rule.attrs = constants;
54
+ }
55
+ else {
56
+ rule.getAttrs = (dom) => {
57
+ const attrs = { ...constants };
58
+ for (const [attrName, htmlAttr] of Object.entries(extracted)) {
59
+ const attrSpec = attrSpecs?.[attrName];
60
+ if (attrSpec === undefined) {
61
+ throw new Error(`parse rule for tag "${ruleJSON.tag}" extracts undeclared attribute "${attrName}"`);
62
+ }
63
+ const hasDefault = Object.prototype.hasOwnProperty.call(attrSpec, "default");
64
+ const value = dom.getAttribute(htmlAttr);
65
+ if (value === null) {
66
+ if (!hasDefault) {
67
+ return false;
68
+ }
69
+ attrs[attrName] = attrSpec.default;
70
+ continue;
71
+ }
72
+ if (attrSpec.validate !== undefined) {
73
+ const validator = validators[attrSpec.validate];
74
+ if (validator === undefined) {
75
+ throw new Error(`unknown validator "${attrSpec.validate}" for attribute "${attrName}"`);
76
+ }
77
+ if (!validator(value)) {
78
+ if ((attrSpec.onInvalid ?? "rejectRule") === "drop") {
79
+ attrs[attrName] = attrSpec.default;
80
+ continue;
81
+ }
82
+ return false;
83
+ }
84
+ }
85
+ attrs[attrName] = value;
86
+ }
87
+ return attrs;
88
+ };
89
+ }
90
+ }
91
+ return rule;
92
+ }
93
+ // Builds a DOMOutputSpec from a (possibly nested) dialect toHTML spec against concrete attribute values: "{attr}" placeholders in the tag are substituted
94
+ // with String(value) and the attribute object is built from the listed attribute names, skipping null/undefined values. When the spec has a content field
95
+ // the element wraps the nested spec, so the content hole (when hole is true, for nodes with content and for marks) sits at the innermost element.
96
+ export function buildOutputSpec(toHTML, attrs, hole) {
97
+ const tag = toHTML.tag.replace(/\{([^{}]+)\}/g, (_match, name) => String(attrs[name]));
98
+ const attrsObj = {};
99
+ for (const name of toHTML.attrs ?? []) {
100
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
101
+ const value = attrs[name];
102
+ if (value === null || value === undefined) {
103
+ continue;
104
+ }
105
+ attrsObj[name] = value;
106
+ }
107
+ if (toHTML.content !== undefined) {
108
+ return [tag, attrsObj, buildOutputSpec(toHTML.content, attrs, hole)];
109
+ }
110
+ return (hole ? [tag, attrsObj, 0] : [tag, attrsObj]);
111
+ }
112
+ // Translates the attrs object of a node/mark spec, keeping only the "default" key (validate/onInvalid govern HTML parse behavior and are handled
113
+ // by buildParseRule; passing them to ProseMirror would change node creation semantics).
114
+ export function buildAttrs(attrsJSON) {
115
+ const attrs = {};
116
+ for (const [name, attrJSON] of Object.entries(attrsJSON)) {
117
+ attrs[name] = Object.prototype.hasOwnProperty.call(attrJSON, "default") ? { default: attrJSON.default } : {};
118
+ }
119
+ return attrs;
120
+ }
121
+ export function translateNodeSpec(json, validators) {
122
+ const spec = {};
123
+ if (json.content !== undefined)
124
+ spec.content = json.content;
125
+ if (json.marks !== undefined)
126
+ spec.marks = json.marks;
127
+ if (json.group !== undefined)
128
+ spec.group = json.group;
129
+ if (json.inline !== undefined)
130
+ spec.inline = json.inline;
131
+ if (json.atom !== undefined)
132
+ spec.atom = json.atom;
133
+ if (json.code !== undefined)
134
+ spec.code = json.code;
135
+ if (json.whitespace !== undefined)
136
+ spec.whitespace = json.whitespace;
137
+ if (json.linebreakReplacement !== undefined)
138
+ spec.linebreakReplacement = json.linebreakReplacement;
139
+ if (json.defining !== undefined)
140
+ spec.defining = json.defining;
141
+ if (json.selectable !== undefined)
142
+ spec.selectable = json.selectable;
143
+ if (json.attrs !== undefined)
144
+ spec.attrs = buildAttrs(json.attrs);
145
+ // A node's parse rules are tag rules; style rules produce marks and the dialect (like the Go side) only allows them on mark types.
146
+ if (json.parseHTML !== undefined)
147
+ spec.parseDOM = json.parseHTML.map((rule) => buildParseRule(rule, json.attrs, validators));
148
+ if (json.toHTML !== undefined) {
149
+ const toHTML = json.toHTML;
150
+ const hasContent = Boolean(json.content);
151
+ spec.toDOM = (node) => buildOutputSpec(toHTML, node.attrs, hasContent);
152
+ }
153
+ return spec;
154
+ }
155
+ export function translateMarkSpec(json, validators) {
156
+ const spec = {};
157
+ if (json.group !== undefined)
158
+ spec.group = json.group;
159
+ if (json.code !== undefined)
160
+ spec.code = json.code;
161
+ if (json.excludes !== undefined)
162
+ spec.excludes = json.excludes;
163
+ if (json.spanning !== undefined)
164
+ spec.spanning = json.spanning;
165
+ if (json.inclusive !== undefined)
166
+ spec.inclusive = json.inclusive;
167
+ if (json.attrs !== undefined)
168
+ spec.attrs = buildAttrs(json.attrs);
169
+ if (json.parseHTML !== undefined)
170
+ spec.parseDOM = json.parseHTML.map((rule) => buildParseRule(rule, json.attrs, validators));
171
+ if (json.toHTML !== undefined) {
172
+ const toHTML = json.toHTML;
173
+ spec.toDOM = (mark) => buildOutputSpec(toHTML, mark.attrs, true);
174
+ }
175
+ return spec;
176
+ }
177
+ // Builds a prosemirror-model Schema from a parsed schema JSON object. The validators registry resolves the validate names referenced by attribute specs;
178
+ // it defaults to empty, so a schema that references a validator must supply it (an unknown validator throws during HTML parsing).
179
+ //
180
+ // JSON.parse preserves the declaration order of (non-numeric) object keys, which determines mark rank, parse rule precedence, and group expansion order,
181
+ // matching the strict decoding on the Go side; pass the object from JSON.parse to preserve that order.
182
+ export function buildSchema(spec, validators = {}) {
183
+ const nodes = {};
184
+ for (const [name, nodeSpec] of Object.entries(spec.nodes)) {
185
+ nodes[name] = translateNodeSpec(nodeSpec, validators);
186
+ }
187
+ const marks = {};
188
+ for (const [name, markSpec] of Object.entries(spec.marks ?? {})) {
189
+ marks[name] = translateMarkSpec(markSpec, validators);
190
+ }
191
+ return new Schema({ topNode: spec.topNode, nodes, marks });
192
+ }
193
+ // The five characters escaped in text and attribute values; everything else, including U+00A0, is emitted raw.
194
+ const GO_HTML_ESCAPES = {
195
+ "&": "&amp;",
196
+ "'": "&#39;",
197
+ "<": "&lt;",
198
+ ">": "&gt;",
199
+ '"': "&#34;",
200
+ };
201
+ // Escapes the five characters the Go canonical serializer escapes in text and attribute values, leaving everything else (including U+00A0) raw.
202
+ export function escapeHTML(text) {
203
+ return text.replace(/[&'<>"]/g, (c) => GO_HTML_ESCAPES[c]);
204
+ }
205
+ // The full HTML spec void element set, emitted as an open tag only; this keeps any schema well formed.
206
+ const VOID_ELEMENTS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
207
+ const ELEMENT_NODE = 1;
208
+ const TEXT_NODE = 3;
209
+ // Recursive string serialization of the DOM produced by DOMSerializer: lowercase tags, attributes always double-quoted in DOM order, void elements emitted as the
210
+ // open tag only, and one extra "\n" after a pre open tag whose first child is a text node starting with "\n" (the HTML parser drops one newline right after the pre
211
+ // open tag, so the doubled form keeps the parse round trip lossless). It produces the same canonical HTML as the Go SerializeHTML.
212
+ export function serializeDOM(node) {
213
+ if (node.nodeType === TEXT_NODE) {
214
+ return escapeHTML(node.data);
215
+ }
216
+ if (node.nodeType !== ELEMENT_NODE) {
217
+ // DOMSerializer produces only elements and text nodes.
218
+ return "";
219
+ }
220
+ const element = node;
221
+ const tag = element.tagName.toLowerCase();
222
+ let out = "<" + tag;
223
+ for (let i = 0; i < element.attributes.length; i++) {
224
+ const attr = element.attributes[i];
225
+ out += " " + attr.name + '="' + escapeHTML(attr.value) + '"';
226
+ }
227
+ out += ">";
228
+ if (VOID_ELEMENTS.has(tag)) {
229
+ return out;
230
+ }
231
+ if (tag === "pre" && element.firstChild !== null && element.firstChild.nodeType === TEXT_NODE && element.firstChild.data.startsWith("\n")) {
232
+ out += "\n";
233
+ }
234
+ for (const child of element.childNodes) {
235
+ out += serializeDOM(child);
236
+ }
237
+ return out + "</" + tag + ">";
238
+ }
239
+ // htmlToDoc parses an HTML string into a document of the given schema: it assigns the HTML to the innerHTML of a detached div (the HTML fragment parsing the browser
240
+ // uses) and runs the schema's DOMParser over it. options are the prosemirror-model parse options, notably preserveWhitespace. domDocument supplies the DOM
241
+ // implementation used to create the container; it defaults to the global document, so a browser caller can omit it, while a non-browser caller (for example one using
242
+ // jsdom) passes its document.
243
+ export function htmlToDoc(schema, html, options = {}, domDocument = document) {
244
+ const container = domDocument.createElement("div");
245
+ container.innerHTML = html;
246
+ return DOMParser.fromSchema(schema).parse(container, options);
247
+ }
248
+ // docToHtml serializes a document to its canonical HTML form: it runs the schema's DOMSerializer to build a DOM fragment and stringifies it with serializeDOM,
249
+ // producing the same canonical HTML the Go SerializeHTML emits. The output is a pure function of the document (the same on every browser engine), so collaborating
250
+ // clients can compare HTML against their own editor state directly. domDocument supplies the DOM implementation used to build the fragment; it defaults to the global
251
+ // document, so a browser caller can omit it, while a non-browser caller passes its document.
252
+ export function docToHtml(schema, doc, domDocument = document) {
253
+ const fragment = DOMSerializer.fromSchema(schema).serializeFragment(doc.content, { document: domDocument });
254
+ let html = "";
255
+ for (const child of fragment.childNodes) {
256
+ html += serializeDOM(child);
257
+ }
258
+ return html;
259
+ }
260
+ // isCanonicalHTML reports whether html is already in the canonical form docToHtml produces: parsing it into the schema and serializing it back is the identity. The
261
+ // parse options have to match those used to produce the canonical HTML for the answer to be meaningful. It mirrors the Go IsCanonicalHTML and is the HTML claim
262
+ // validity check on the frontend.
263
+ export function isCanonicalHTML(schema, html, options = {}, domDocument = document) {
264
+ return docToHtml(schema, htmlToDoc(schema, html, options, domDocument), domDocument) === html;
265
+ }
266
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,EAAE;AACF,mKAAmK;AACnK,mKAAmK;AACnK,sDAAsD;AACtD,EAAE;AACF,kKAAkK;AAClK,8JAA8J;AAC9J,+DAA+D;AAC/D,EAAE;AACF,gKAAgK;AAChK,iKAAiK;AACjK,wCAAwC;AAIxC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAA;AA+DpE,4IAA4I;AAC5I,gJAAgJ;AAChJ,wIAAwI;AACxI,gIAAgI;AAChI,MAAM,UAAU,cAAc,CAAC,QAAuB,EAAE,SAAwD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,eAAe,CAAC,MAAc,EAAE,IAAY,EAAE,UAAwB,EAAE,EAAE,cAAwB,QAAQ;IACxH,OAAO,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,CAAC,EAAE,WAAW,CAAC,KAAK,IAAI,CAAA;AAC/F,CAAC"}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@tozd/prosemirror",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "ProseMirror frontend utilities for Go port of ProseMirror.",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://gitlab.com/tozd/go/prosemirror.git"
13
+ },
14
+ "module": "./dist/index.js",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "files": [
18
+ "src",
19
+ "dist",
20
+ "NOTICE",
21
+ "!src/*.test.ts"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.json",
25
+ "typecheck": "tsc -p tsconfig.eslint.json",
26
+ "lint": "eslint --fix src scripts",
27
+ "fmt": "prettier src scripts package.json --write",
28
+ "test": "vitest",
29
+ "coverage": "vitest --coverage",
30
+ "test-ci": "vitest run --reporter junit --reporter default --outputFile tests.xml --coverage",
31
+ "generate-fixtures": "tsx scripts/generate-fixtures.ts",
32
+ "upgrade": "ncu -u",
33
+ "prepare": "npm run build"
34
+ },
35
+ "peerDependencies": {
36
+ "prosemirror-model": "^1.25.8"
37
+ },
38
+ "devDependencies": {
39
+ "@eslint/compat": "^2.0.5",
40
+ "@eslint/js": "^9.39.1",
41
+ "@types/jsdom": "^28.0.3",
42
+ "@types/node": "^24.0.0",
43
+ "@vitest/coverage-v8": "^4.1.5",
44
+ "eslint": "^9.39.1",
45
+ "eslint-config-prettier": "^10.1.8",
46
+ "globals": "^17.5.0",
47
+ "jsdom": "^29.1.1",
48
+ "npm-check-updates": "^21.0.3",
49
+ "prettier": "^3.8.3",
50
+ "prettier-plugin-organize-imports": "^4.3.0",
51
+ "prosemirror-model": "^1.25.8",
52
+ "tsx": "^4.22.4",
53
+ "typescript": "^5.9.3",
54
+ "typescript-eslint": "^8.59.0",
55
+ "vitest": "^4.1.5"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
60
+ }
package/src/index.ts ADDED
@@ -0,0 +1,315 @@
1
+ // ProseMirror frontend utilities for Go port of ProseMirror. It provides:
2
+ //
3
+ // A builder for ProseMirror Schema from the schema JSON dialect described in the "Schema JSON dialect" section of PORTING.md, the same dialect the Go port parses.
4
+ // Given an already-parsed schema JSON object and a registry of named attribute validators, it produces a prosemirror-model Schema (with parseDOM and toDOM derived
5
+ // from the dialect) that a frontend can use directly.
6
+ //
7
+ // A canonical HTML serializer (serializeDOM, with escapeHTML) that stringifies the DOM produced by prosemirror-model's DOMSerializer into the same canonical HTML
8
+ // the Go SerializeHTML emits (the same five-character escaping, lowercased tags, double-quoted attributes, void-element handling, and pre newline rule), so a
9
+ // frontend can compute the same canonical HTML as the backend.
10
+ //
11
+ // HTML conversion helpers (htmlToDoc, docToHtml, isCanonicalHTML) that parse an HTML string into a document of a given schema, serialize a document back to its
12
+ // canonical HTML, and report whether HTML is already canonical (its parse/serialize round trip is the identity), matching the Go ParseHTML/SerializeHTML and the
13
+ // claim-validity check IsCanonicalHTML.
14
+
15
+ import type { Attrs, DOMOutputSpec, Mark, MarkSpec, NodeSpec, ParseOptions, ParseRule, Node as PMNode, StyleParseRule, TagParseRule } from "prosemirror-model"
16
+
17
+ import { DOMParser, DOMSerializer, Schema } from "prosemirror-model"
18
+
19
+ // Shapes of the schema JSON dialect.
20
+
21
+ export interface AttributeSpecJSON {
22
+ default?: unknown
23
+ validate?: string
24
+ onInvalid?: "rejectRule" | "drop"
25
+ }
26
+
27
+ export interface ToHTMLJSON {
28
+ tag: string
29
+ attrs?: string[]
30
+ content?: ToHTMLJSON
31
+ }
32
+
33
+ export interface ParseRuleJSON {
34
+ tag?: string
35
+ style?: string
36
+ namespace?: string
37
+ context?: string
38
+ priority?: number
39
+ preserveWhitespace?: boolean | "full"
40
+ attrs?: Record<string, unknown>
41
+ }
42
+
43
+ export interface NodeSpecJSON {
44
+ content?: string
45
+ marks?: string
46
+ group?: string
47
+ inline?: boolean
48
+ atom?: boolean
49
+ code?: boolean
50
+ whitespace?: "pre" | "normal"
51
+ linebreakReplacement?: boolean
52
+ defining?: boolean
53
+ selectable?: boolean
54
+ attrs?: Record<string, AttributeSpecJSON>
55
+ toHTML?: ToHTMLJSON
56
+ parseHTML?: ParseRuleJSON[]
57
+ }
58
+
59
+ export interface MarkSpecJSON {
60
+ group?: string
61
+ code?: boolean
62
+ excludes?: string
63
+ spanning?: boolean
64
+ inclusive?: boolean
65
+ attrs?: Record<string, AttributeSpecJSON>
66
+ toHTML?: ToHTMLJSON
67
+ parseHTML?: ParseRuleJSON[]
68
+ }
69
+
70
+ export interface SchemaJSON {
71
+ topNode?: string
72
+ nodes: Record<string, NodeSpecJSON>
73
+ marks?: Record<string, MarkSpecJSON>
74
+ }
75
+
76
+ // A named attribute validator returns true when the value is acceptable. The registry passed to buildSchema maps validator names used in the schema JSON
77
+ // to these functions; a schema referencing a name that is not in the registry is an error.
78
+ export type Validator = (value: unknown) => boolean
79
+
80
+ // Builds a ProseMirror parse rule from a dialect parseHTML rule. Constant attribute entries (number/boolean/null) become static rule attrs;
81
+ // string entries are attribute extraction and become a getAttrs function which reads the named HTML attribute, falls back to the attribute spec
82
+ // default when the attribute is absent (rejecting the rule when the attribute is required), and applies the named validator when one is
83
+ // configured: on failure, onInvalid "rejectRule" (the default) rejects the rule and "drop" replaces the value with the default.
84
+ export function buildParseRule(ruleJSON: ParseRuleJSON, attrSpecs: Record<string, AttributeSpecJSON> | undefined, validators: Record<string, Validator>): ParseRule {
85
+ // Style rules produce marks and match an inline CSS declaration; their attrs are always constants (the declarative dialect does not extract from the
86
+ // style value). Tag rules match a CSS selector, optionally restricted by namespace, and may extract attributes from the element.
87
+ if (ruleJSON.style !== undefined) {
88
+ const rule: StyleParseRule = { style: ruleJSON.style }
89
+ if (ruleJSON.context !== undefined) rule.context = ruleJSON.context
90
+ if (ruleJSON.priority !== undefined) rule.priority = ruleJSON.priority
91
+ if (ruleJSON.attrs !== undefined) rule.attrs = ruleJSON.attrs
92
+ return rule
93
+ }
94
+ const rule: TagParseRule = { tag: ruleJSON.tag! }
95
+ if (ruleJSON.namespace !== undefined) rule.namespace = ruleJSON.namespace
96
+ if (ruleJSON.context !== undefined) rule.context = ruleJSON.context
97
+ if (ruleJSON.priority !== undefined) rule.priority = ruleJSON.priority
98
+ if (ruleJSON.preserveWhitespace !== undefined) rule.preserveWhitespace = ruleJSON.preserveWhitespace
99
+ if (ruleJSON.attrs !== undefined) {
100
+ const constants: Record<string, unknown> = {}
101
+ const extracted: Record<string, string> = {}
102
+ for (const [attrName, value] of Object.entries(ruleJSON.attrs)) {
103
+ if (typeof value === "string") {
104
+ extracted[attrName] = value
105
+ } else {
106
+ constants[attrName] = value
107
+ }
108
+ }
109
+ if (Object.keys(extracted).length === 0) {
110
+ rule.attrs = constants
111
+ } else {
112
+ rule.getAttrs = (dom: HTMLElement): Attrs | false => {
113
+ const attrs: Record<string, unknown> = { ...constants }
114
+ for (const [attrName, htmlAttr] of Object.entries(extracted)) {
115
+ const attrSpec = attrSpecs?.[attrName]
116
+ if (attrSpec === undefined) {
117
+ throw new Error(`parse rule for tag "${ruleJSON.tag}" extracts undeclared attribute "${attrName}"`)
118
+ }
119
+ const hasDefault = Object.prototype.hasOwnProperty.call(attrSpec, "default")
120
+ const value = dom.getAttribute(htmlAttr)
121
+ if (value === null) {
122
+ if (!hasDefault) {
123
+ return false
124
+ }
125
+ attrs[attrName] = attrSpec.default
126
+ continue
127
+ }
128
+ if (attrSpec.validate !== undefined) {
129
+ const validator = validators[attrSpec.validate]
130
+ if (validator === undefined) {
131
+ throw new Error(`unknown validator "${attrSpec.validate}" for attribute "${attrName}"`)
132
+ }
133
+ if (!validator(value)) {
134
+ if ((attrSpec.onInvalid ?? "rejectRule") === "drop") {
135
+ attrs[attrName] = attrSpec.default
136
+ continue
137
+ }
138
+ return false
139
+ }
140
+ }
141
+ attrs[attrName] = value
142
+ }
143
+ return attrs
144
+ }
145
+ }
146
+ }
147
+ return rule
148
+ }
149
+
150
+ // Builds a DOMOutputSpec from a (possibly nested) dialect toHTML spec against concrete attribute values: "{attr}" placeholders in the tag are substituted
151
+ // with String(value) and the attribute object is built from the listed attribute names, skipping null/undefined values. When the spec has a content field
152
+ // the element wraps the nested spec, so the content hole (when hole is true, for nodes with content and for marks) sits at the innermost element.
153
+ export function buildOutputSpec(toHTML: ToHTMLJSON, attrs: Attrs, hole: boolean): DOMOutputSpec {
154
+ const tag = toHTML.tag.replace(/\{([^{}]+)\}/g, (_match, name: string) => String(attrs[name]))
155
+ const attrsObj: Record<string, unknown> = {}
156
+ for (const name of toHTML.attrs ?? []) {
157
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
158
+ const value = attrs[name]
159
+ if (value === null || value === undefined) {
160
+ continue
161
+ }
162
+ attrsObj[name] = value
163
+ }
164
+ if (toHTML.content !== undefined) {
165
+ return [tag, attrsObj, buildOutputSpec(toHTML.content, attrs, hole)] as DOMOutputSpec
166
+ }
167
+ return (hole ? [tag, attrsObj, 0] : [tag, attrsObj]) as DOMOutputSpec
168
+ }
169
+
170
+ // Translates the attrs object of a node/mark spec, keeping only the "default" key (validate/onInvalid govern HTML parse behavior and are handled
171
+ // by buildParseRule; passing them to ProseMirror would change node creation semantics).
172
+ export function buildAttrs(attrsJSON: Record<string, AttributeSpecJSON>): Record<string, { default?: unknown }> {
173
+ const attrs: Record<string, { default?: unknown }> = {}
174
+ for (const [name, attrJSON] of Object.entries(attrsJSON)) {
175
+ attrs[name] = Object.prototype.hasOwnProperty.call(attrJSON, "default") ? { default: attrJSON.default } : {}
176
+ }
177
+ return attrs
178
+ }
179
+
180
+ export function translateNodeSpec(json: NodeSpecJSON, validators: Record<string, Validator>): NodeSpec {
181
+ const spec: NodeSpec = {}
182
+ if (json.content !== undefined) spec.content = json.content
183
+ if (json.marks !== undefined) spec.marks = json.marks
184
+ if (json.group !== undefined) spec.group = json.group
185
+ if (json.inline !== undefined) spec.inline = json.inline
186
+ if (json.atom !== undefined) spec.atom = json.atom
187
+ if (json.code !== undefined) spec.code = json.code
188
+ if (json.whitespace !== undefined) spec.whitespace = json.whitespace
189
+ if (json.linebreakReplacement !== undefined) spec.linebreakReplacement = json.linebreakReplacement
190
+ if (json.defining !== undefined) spec.defining = json.defining
191
+ if (json.selectable !== undefined) spec.selectable = json.selectable
192
+ if (json.attrs !== undefined) spec.attrs = buildAttrs(json.attrs)
193
+ // A node's parse rules are tag rules; style rules produce marks and the dialect (like the Go side) only allows them on mark types.
194
+ if (json.parseHTML !== undefined) spec.parseDOM = json.parseHTML.map((rule) => buildParseRule(rule, json.attrs, validators)) as TagParseRule[]
195
+ if (json.toHTML !== undefined) {
196
+ const toHTML = json.toHTML
197
+ const hasContent = Boolean(json.content)
198
+ spec.toDOM = (node: PMNode): DOMOutputSpec => buildOutputSpec(toHTML, node.attrs, hasContent)
199
+ }
200
+ return spec
201
+ }
202
+
203
+ export function translateMarkSpec(json: MarkSpecJSON, validators: Record<string, Validator>): MarkSpec {
204
+ const spec: MarkSpec = {}
205
+ if (json.group !== undefined) spec.group = json.group
206
+ if (json.code !== undefined) spec.code = json.code
207
+ if (json.excludes !== undefined) spec.excludes = json.excludes
208
+ if (json.spanning !== undefined) spec.spanning = json.spanning
209
+ if (json.inclusive !== undefined) spec.inclusive = json.inclusive
210
+ if (json.attrs !== undefined) spec.attrs = buildAttrs(json.attrs)
211
+ if (json.parseHTML !== undefined) spec.parseDOM = json.parseHTML.map((rule) => buildParseRule(rule, json.attrs, validators))
212
+ if (json.toHTML !== undefined) {
213
+ const toHTML = json.toHTML
214
+ spec.toDOM = (mark: Mark): DOMOutputSpec => buildOutputSpec(toHTML, mark.attrs, true)
215
+ }
216
+ return spec
217
+ }
218
+
219
+ // Builds a prosemirror-model Schema from a parsed schema JSON object. The validators registry resolves the validate names referenced by attribute specs;
220
+ // it defaults to empty, so a schema that references a validator must supply it (an unknown validator throws during HTML parsing).
221
+ //
222
+ // JSON.parse preserves the declaration order of (non-numeric) object keys, which determines mark rank, parse rule precedence, and group expansion order,
223
+ // matching the strict decoding on the Go side; pass the object from JSON.parse to preserve that order.
224
+ export function buildSchema(spec: SchemaJSON, validators: Record<string, Validator> = {}): Schema {
225
+ const nodes: Record<string, NodeSpec> = {}
226
+ for (const [name, nodeSpec] of Object.entries(spec.nodes)) {
227
+ nodes[name] = translateNodeSpec(nodeSpec, validators)
228
+ }
229
+ const marks: Record<string, MarkSpec> = {}
230
+ for (const [name, markSpec] of Object.entries(spec.marks ?? {})) {
231
+ marks[name] = translateMarkSpec(markSpec, validators)
232
+ }
233
+ return new Schema({ topNode: spec.topNode, nodes, marks })
234
+ }
235
+
236
+ // The five characters escaped in text and attribute values; everything else, including U+00A0, is emitted raw.
237
+ const GO_HTML_ESCAPES: Record<string, string> = {
238
+ "&": "&amp;",
239
+ "'": "&#39;",
240
+ "<": "&lt;",
241
+ ">": "&gt;",
242
+ '"': "&#34;",
243
+ }
244
+
245
+ // Escapes the five characters the Go canonical serializer escapes in text and attribute values, leaving everything else (including U+00A0) raw.
246
+ export function escapeHTML(text: string): string {
247
+ return text.replace(/[&'<>"]/g, (c) => GO_HTML_ESCAPES[c])
248
+ }
249
+
250
+ // The full HTML spec void element set, emitted as an open tag only; this keeps any schema well formed.
251
+ const VOID_ELEMENTS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"])
252
+
253
+ const ELEMENT_NODE = 1
254
+ const TEXT_NODE = 3
255
+
256
+ // Recursive string serialization of the DOM produced by DOMSerializer: lowercase tags, attributes always double-quoted in DOM order, void elements emitted as the
257
+ // open tag only, and one extra "\n" after a pre open tag whose first child is a text node starting with "\n" (the HTML parser drops one newline right after the pre
258
+ // open tag, so the doubled form keeps the parse round trip lossless). It produces the same canonical HTML as the Go SerializeHTML.
259
+ export function serializeDOM(node: Node): string {
260
+ if (node.nodeType === TEXT_NODE) {
261
+ return escapeHTML((node as Text).data)
262
+ }
263
+ if (node.nodeType !== ELEMENT_NODE) {
264
+ // DOMSerializer produces only elements and text nodes.
265
+ return ""
266
+ }
267
+ const element = node as Element
268
+ const tag = element.tagName.toLowerCase()
269
+ let out = "<" + tag
270
+ for (let i = 0; i < element.attributes.length; i++) {
271
+ const attr = element.attributes[i]
272
+ out += " " + attr.name + '="' + escapeHTML(attr.value) + '"'
273
+ }
274
+ out += ">"
275
+ if (VOID_ELEMENTS.has(tag)) {
276
+ return out
277
+ }
278
+ if (tag === "pre" && element.firstChild !== null && element.firstChild.nodeType === TEXT_NODE && (element.firstChild as Text).data.startsWith("\n")) {
279
+ out += "\n"
280
+ }
281
+ for (const child of element.childNodes) {
282
+ out += serializeDOM(child)
283
+ }
284
+ return out + "</" + tag + ">"
285
+ }
286
+
287
+ // htmlToDoc parses an HTML string into a document of the given schema: it assigns the HTML to the innerHTML of a detached div (the HTML fragment parsing the browser
288
+ // uses) and runs the schema's DOMParser over it. options are the prosemirror-model parse options, notably preserveWhitespace. domDocument supplies the DOM
289
+ // implementation used to create the container; it defaults to the global document, so a browser caller can omit it, while a non-browser caller (for example one using
290
+ // jsdom) passes its document.
291
+ export function htmlToDoc(schema: Schema, html: string, options: ParseOptions = {}, domDocument: Document = document): PMNode {
292
+ const container = domDocument.createElement("div")
293
+ container.innerHTML = html
294
+ return DOMParser.fromSchema(schema).parse(container, options)
295
+ }
296
+
297
+ // docToHtml serializes a document to its canonical HTML form: it runs the schema's DOMSerializer to build a DOM fragment and stringifies it with serializeDOM,
298
+ // producing the same canonical HTML the Go SerializeHTML emits. The output is a pure function of the document (the same on every browser engine), so collaborating
299
+ // clients can compare HTML against their own editor state directly. domDocument supplies the DOM implementation used to build the fragment; it defaults to the global
300
+ // document, so a browser caller can omit it, while a non-browser caller passes its document.
301
+ export function docToHtml(schema: Schema, doc: PMNode, domDocument: Document = document): string {
302
+ const fragment = DOMSerializer.fromSchema(schema).serializeFragment(doc.content, { document: domDocument })
303
+ let html = ""
304
+ for (const child of fragment.childNodes) {
305
+ html += serializeDOM(child)
306
+ }
307
+ return html
308
+ }
309
+
310
+ // isCanonicalHTML reports whether html is already in the canonical form docToHtml produces: parsing it into the schema and serializing it back is the identity. The
311
+ // parse options have to match those used to produce the canonical HTML for the answer to be meaningful. It mirrors the Go IsCanonicalHTML and is the HTML claim
312
+ // validity check on the frontend.
313
+ export function isCanonicalHTML(schema: Schema, html: string, options: ParseOptions = {}, domDocument: Document = document): boolean {
314
+ return docToHtml(schema, htmlToDoc(schema, html, options, domDocument), domDocument) === html
315
+ }