@riebeckite/plugin-d2 0.0.1
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 +201 -0
- package/README.md +129 -0
- package/README_ja.md +104 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +63 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +433 -0
- package/dist/src/hast.d.ts +7 -0
- package/dist/src/init.d.ts +10 -0
- package/dist/src/rehype.d.ts +2 -0
- package/dist/src/render-static.d.ts +5 -0
- package/dist/src/types.d.ts +73 -0
- package/package.json +62 -0
- package/style.css +65 -0
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 Rerurate_514
|
|
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,129 @@
|
|
|
1
|
+
# @riebeckite/plugin-d2
|
|
2
|
+
|
|
3
|
+
D2 diagram rendering for ` ```d2 ` code blocks.
|
|
4
|
+
|
|
5
|
+
[日本語](./README_ja.md)
|
|
6
|
+
|
|
7
|
+
## Overview
|
|
8
|
+
|
|
9
|
+
`d2()` replaces D2 code blocks with a `<figure class="rb-d2">` that renders to
|
|
10
|
+
SVG. Diagrams are rendered at build time by the D2 WebAssembly engine running in
|
|
11
|
+
Node, with an automatic client-side fallback. It runs with `order: -10`.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { defineConfig } from "@riebeckite/core";
|
|
17
|
+
import { d2 } from "@riebeckite/plugin-d2";
|
|
18
|
+
|
|
19
|
+
export default defineConfig({
|
|
20
|
+
// ...
|
|
21
|
+
plugins: [
|
|
22
|
+
d2({
|
|
23
|
+
render: "build",
|
|
24
|
+
theme: { light: 0, dark: 1 },
|
|
25
|
+
layout: "dagre",
|
|
26
|
+
}),
|
|
27
|
+
],
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Syntax
|
|
32
|
+
|
|
33
|
+
````markdown
|
|
34
|
+
```d2 title="Request flow"
|
|
35
|
+
client -> server: request
|
|
36
|
+
server -> database: query
|
|
37
|
+
```
|
|
38
|
+
````
|
|
39
|
+
|
|
40
|
+
A caption can also be written as the first line of the block. D2 uses `#` for
|
|
41
|
+
comments, so a leading `# caption: ...` line is treated as a caption and removed
|
|
42
|
+
before rendering:
|
|
43
|
+
|
|
44
|
+
````markdown
|
|
45
|
+
```d2
|
|
46
|
+
# caption: Request flow
|
|
47
|
+
client -> server: request
|
|
48
|
+
```
|
|
49
|
+
````
|
|
50
|
+
|
|
51
|
+
## Behavior
|
|
52
|
+
|
|
53
|
+
### Build
|
|
54
|
+
|
|
55
|
+
- Replaces each ` ```d2 ` `<pre>` with a `figure.rb-d2` containing:
|
|
56
|
+
- `figcaption.rb-d2__caption` — from the code block title or a
|
|
57
|
+
`# caption: ...` line
|
|
58
|
+
- `div.rb-d2__canvas` — the diagram (`role="img"`, labelled by the caption
|
|
59
|
+
when present)
|
|
60
|
+
- `details.rb-d2__fallback` — collapsible diagram source
|
|
61
|
+
- Static SVG is rendered at build time when `render` is `"build"` or `"both"`
|
|
62
|
+
by running the D2.js WebAssembly engine (`@d2lang/d2`) directly in Node. No
|
|
63
|
+
browser, network access, or system D2 binary is required.
|
|
64
|
+
- The generated figure always carries `data-d2`, `data-d2-source`, and
|
|
65
|
+
`data-d2-layout` attributes. `data-d2` is `rendered` when static SVG is
|
|
66
|
+
present and `pending` when the client must take over.
|
|
67
|
+
- Invalid diagrams report `ruleId: "invalid-diagram"`; renderer failures report
|
|
68
|
+
`ruleId: "renderer-error"`. When build SVG is unavailable, the figure remains
|
|
69
|
+
`data-d2="pending"` for client fallback.
|
|
70
|
+
|
|
71
|
+
### Client (`initD2Diagrams`)
|
|
72
|
+
|
|
73
|
+
- Loads D2.js as an ESM module from jsDelivr unless `globalThis.d2` or an
|
|
74
|
+
injected module is provided
|
|
75
|
+
- Renders every `[data-d2="pending"]` figure; failures set `data-d2="error"`
|
|
76
|
+
(placeholder message via CSS)
|
|
77
|
+
- When `theme` is `{ light, dark }`, the theme is chosen from
|
|
78
|
+
`html[data-theme]` or `prefers-color-scheme`
|
|
79
|
+
|
|
80
|
+
## Options
|
|
81
|
+
|
|
82
|
+
| Option | Type | Default | Description |
|
|
83
|
+
| ------ | ---- | ------- | ----------- |
|
|
84
|
+
| `render` | `"build" \| "client" \| "both"` | `"build"` | When diagrams are rendered |
|
|
85
|
+
| `theme` | `number \| { light: number; dark: number }` | `{ light: 0, dark: 1 }` | D2 theme id(s) |
|
|
86
|
+
| `layout` | `"dagre" \| "elk"` | `"dagre"` | D2 layout engine |
|
|
87
|
+
| `caption` | `boolean` | `true` | Show title / `# caption:` as `figcaption` |
|
|
88
|
+
| `fallback` | `boolean` | `true` | Show the diagram source in `<details>` |
|
|
89
|
+
| `className` | `string` | `"rb-d2"` | Base CSS class for the figure |
|
|
90
|
+
|
|
91
|
+
`render` modes:
|
|
92
|
+
|
|
93
|
+
- `"build"` — render SVG at build time; diagrams that fail fall back to client
|
|
94
|
+
rendering
|
|
95
|
+
- `"client"` — skip build-time rendering, render in the browser only
|
|
96
|
+
- `"both"` — compatibility alias. It currently behaves like `"build"`: build
|
|
97
|
+
first, then client fallback only when build rendering fails
|
|
98
|
+
|
|
99
|
+
## Offline requirements
|
|
100
|
+
|
|
101
|
+
Build-time rendering is fully offline: `@d2lang/d2` ships a WebAssembly build
|
|
102
|
+
that is loaded from `node_modules`. Client rendering (`render: "client"` or a
|
|
103
|
+
build failure) downloads D2.js from jsDelivr; point `moduleUrl` at a self-hosted
|
|
104
|
+
copy if the deployment has no outbound network access.
|
|
105
|
+
|
|
106
|
+
## Output hooks
|
|
107
|
+
|
|
108
|
+
- Set `globalThis.d2` to a preloaded D2.js module to skip the CDN import.
|
|
109
|
+
- Pass `api` and `moduleUrl` to `initD2Diagrams()` when calling it directly.
|
|
110
|
+
|
|
111
|
+
## Exports
|
|
112
|
+
|
|
113
|
+
- `d2(options?)` — plugin factory (`d2Plugin` is an alias)
|
|
114
|
+
- `initD2Diagrams` — client initializer
|
|
115
|
+
- Types: `D2Options`, `D2ClientOptions`, `D2RenderMode`, `D2Layout`, `D2Theme`,
|
|
116
|
+
`D2ModuleApi`
|
|
117
|
+
|
|
118
|
+
## Limitations
|
|
119
|
+
|
|
120
|
+
- A diagram is rendered per build with a fresh D2 worker; very large batches pay
|
|
121
|
+
the WASM startup cost repeatedly.
|
|
122
|
+
- `layout: "elk"` uses D2's ELK engine, which is slower than `dagre`.
|
|
123
|
+
- Multi-board and animated D2 output are not configured by this plugin.
|
|
124
|
+
- The renderer is `@d2lang/d2` (MPL-2.0), the current package for the D2.js WASM
|
|
125
|
+
build; `@terrastruct/d2` is its compatibility alias.
|
|
126
|
+
|
|
127
|
+
## See also
|
|
128
|
+
|
|
129
|
+
- [Plugin guide](../../docs/plugins_en.md)
|
package/README_ja.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# @riebeckite/plugin-d2
|
|
2
|
+
|
|
3
|
+
` ```d2 ` コードブロックを SVG の図として表示するプラグインです。既定ではビルド時に描画し、描画できなかった図だけをブラウザ側で再試行します。
|
|
4
|
+
|
|
5
|
+
[English](./README.md)
|
|
6
|
+
|
|
7
|
+
## 設定する
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { defineConfig } from "@riebeckite/core";
|
|
11
|
+
import { d2 } from "@riebeckite/plugin-d2";
|
|
12
|
+
|
|
13
|
+
export default defineConfig({
|
|
14
|
+
// ...
|
|
15
|
+
plugins: [
|
|
16
|
+
d2({
|
|
17
|
+
render: "build",
|
|
18
|
+
theme: { light: 0, dark: 1 },
|
|
19
|
+
layout: "dagre",
|
|
20
|
+
}),
|
|
21
|
+
],
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
このプラグインは `order: -10` で実行されます。
|
|
26
|
+
|
|
27
|
+
## 記法
|
|
28
|
+
|
|
29
|
+
````markdown
|
|
30
|
+
```d2 title="リクエストの流れ"
|
|
31
|
+
client -> server: request
|
|
32
|
+
server -> database: query
|
|
33
|
+
```
|
|
34
|
+
````
|
|
35
|
+
|
|
36
|
+
キャプションはコードブロックの先頭行にも書けます。D2 は `#` をコメントとして扱うため、先頭の `# caption: ...` 行をキャプションとして取り込み、描画前に取り除きます。
|
|
37
|
+
|
|
38
|
+
````markdown
|
|
39
|
+
```d2
|
|
40
|
+
# caption: リクエストの流れ
|
|
41
|
+
client -> server: request
|
|
42
|
+
```
|
|
43
|
+
````
|
|
44
|
+
|
|
45
|
+
## どのように描画されるか
|
|
46
|
+
|
|
47
|
+
### ビルド時
|
|
48
|
+
|
|
49
|
+
` ```d2 ` のコードブロックは `figure.rb-d2` に置き換わります。
|
|
50
|
+
|
|
51
|
+
- `figcaption.rb-d2__caption`: コードブロックの title、または `# caption:` 行
|
|
52
|
+
- `div.rb-d2__canvas`: 図本体(`role="img"`、キャプションがある場合はそれをラベルに使用)
|
|
53
|
+
- `details.rb-d2__fallback`: 元の D2 記法を折りたたんで表示
|
|
54
|
+
|
|
55
|
+
`render: "build"` または `"both"` では、D2.js の WebAssembly 版(`@d2lang/d2`)を Node 上で直接実行して静的な SVG を生成します。ブラウザ、ネットワーク接続、D2 本体のインストールはいずれも不要です。
|
|
56
|
+
|
|
57
|
+
生成される figure には常に `data-d2`、`data-d2-source`、`data-d2-layout` が付きます。`data-d2` は静的 SVG があれば `rendered`、クライアント側の描画に委ねる場合は `pending` になります。
|
|
58
|
+
|
|
59
|
+
構文エラーは `invalid-diagram`、描画環境の問題は `renderer-error` として区別して診断します。
|
|
60
|
+
|
|
61
|
+
### クライアント側
|
|
62
|
+
|
|
63
|
+
`initD2Diagrams` は保留中の図だけを描画します。D2.js がなければ jsDelivr から ESM として読み込みます。描画に失敗した場合は `data-d2="error"` となり、CSS のプレースホルダー表示に切り替わります。
|
|
64
|
+
|
|
65
|
+
明暗別のテーマを指定した場合は、`html[data-theme]` を優先し、なければ OS の配色設定に従います。
|
|
66
|
+
|
|
67
|
+
## オプション
|
|
68
|
+
|
|
69
|
+
| 項目 | 既定値 | 説明 |
|
|
70
|
+
| --- | --- | --- |
|
|
71
|
+
| `render` | `"build"` | `"build"`、`"client"`、`"both"` のいずれで描画するか |
|
|
72
|
+
| `theme` | `{ light: 0, dark: 1 }` | D2 のテーマ ID、または明暗別のテーマ ID |
|
|
73
|
+
| `layout` | `"dagre"` | D2 のレイアウトエンジン(`"dagre"` または `"elk"`) |
|
|
74
|
+
| `caption` | `true` | タイトルまたは `# caption:` をキャプションとして表示する |
|
|
75
|
+
| `fallback` | `true` | 元の D2 記法を `<details>` に残す |
|
|
76
|
+
| `className` | `"rb-d2"` | figure に付ける基準クラス |
|
|
77
|
+
|
|
78
|
+
`"client"` はビルド時の描画を行いません。`"both"` は後方互換の値で、現在は `"build"` と同じくビルドを優先し、失敗時だけクライアント側へ切り替えます。
|
|
79
|
+
|
|
80
|
+
## オフラインでの利用
|
|
81
|
+
|
|
82
|
+
ビルド時の描画は完全にオフラインです。`@d2lang/d2` が同梱する WebAssembly を `node_modules` から読み込むだけで、外部通信は発生しません。クライアント側の描画(`render: "client"` またはビルド失敗時)は jsDelivr から D2.js を取得します。外部通信を避けたい場合は `moduleUrl` に自前でホストしたモジュールを指定してください。
|
|
83
|
+
|
|
84
|
+
## 出力のフック
|
|
85
|
+
|
|
86
|
+
- `globalThis.d2` に読み込み済みの D2.js モジュールを設定すると、CDN からの読み込みを省略できます
|
|
87
|
+
- `initD2Diagrams()` を直接呼ぶ場合は `api` と `moduleUrl` を渡せます
|
|
88
|
+
|
|
89
|
+
## 主なエクスポート
|
|
90
|
+
|
|
91
|
+
- `d2(options?)`: プラグインを作成する(`d2Plugin` は別名)
|
|
92
|
+
- `initD2Diagrams`: クライアント側の描画を初期化する
|
|
93
|
+
- 型: `D2Options`、`D2ClientOptions`、`D2RenderMode`、`D2Layout`、`D2Theme`、`D2ModuleApi`
|
|
94
|
+
|
|
95
|
+
## 制限
|
|
96
|
+
|
|
97
|
+
- 図ごとに新しい D2 ワーカーを起動するため、大量の図を含むビルドでは WASM の起動コストが繰り返し発生します
|
|
98
|
+
- `layout: "elk"` は D2 の ELK エンジンを使うため `dagre` より遅くなります
|
|
99
|
+
- マルチボードやアニメーション付きの出力はこのプラグインでは設定できません
|
|
100
|
+
- レンダラーには `@d2lang/d2`(MPL-2.0)を使用しています。`@terrastruct/d2` はその後方互換パッケージです
|
|
101
|
+
|
|
102
|
+
## 関連資料
|
|
103
|
+
|
|
104
|
+
- [プラグインシステム](../../../docs/ja/plugin-system.md)
|
package/dist/client.d.ts
ADDED
package/dist/client.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// src/init.ts
|
|
2
|
+
var DEFAULT_THEME = { light: 0, dark: 1 };
|
|
3
|
+
var DEFAULT_MODULE_URL = "https://cdn.jsdelivr.net/npm/@d2lang/d2@0.1.34/dist/browser/index.js";
|
|
4
|
+
async function initD2Diagrams(options = {}) {
|
|
5
|
+
const figures = Array.from(
|
|
6
|
+
document.querySelectorAll('[data-d2="pending"]')
|
|
7
|
+
);
|
|
8
|
+
if (figures.length === 0) return;
|
|
9
|
+
const api = options.api ?? await loadD2(options.moduleUrl);
|
|
10
|
+
if (!api) return;
|
|
11
|
+
const renderer = new api.D2();
|
|
12
|
+
try {
|
|
13
|
+
for (const [index, figure] of figures.entries()) {
|
|
14
|
+
await renderFigure(renderer, figure, index, options);
|
|
15
|
+
}
|
|
16
|
+
} finally {
|
|
17
|
+
await renderer.dispose?.();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function renderFigure(renderer, figure, index, options) {
|
|
21
|
+
const source = figure.dataset.d2Source;
|
|
22
|
+
const canvas = figure.querySelector("[data-d2-canvas]");
|
|
23
|
+
if (!source || !canvas) return;
|
|
24
|
+
try {
|
|
25
|
+
const compiled = await renderer.compile(source, {
|
|
26
|
+
layout: options.layout ?? figure.dataset.d2Layout ?? "dagre",
|
|
27
|
+
themeID: selectTheme(options.theme ?? DEFAULT_THEME),
|
|
28
|
+
salt: `rb-d2-client-${index}`
|
|
29
|
+
});
|
|
30
|
+
const svg = await renderer.render(compiled.diagram, {
|
|
31
|
+
...compiled.renderOptions,
|
|
32
|
+
noXMLTag: true
|
|
33
|
+
});
|
|
34
|
+
canvas.innerHTML = svg;
|
|
35
|
+
figure.dataset.d2 = "rendered";
|
|
36
|
+
} catch {
|
|
37
|
+
figure.dataset.d2 = "error";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function loadD2(moduleUrl = DEFAULT_MODULE_URL) {
|
|
41
|
+
const injected = globalThis.d2;
|
|
42
|
+
if (injected) return injected;
|
|
43
|
+
try {
|
|
44
|
+
const imported = await import(
|
|
45
|
+
/* @vite-ignore */
|
|
46
|
+
moduleUrl
|
|
47
|
+
);
|
|
48
|
+
if (typeof imported?.D2 !== "function") return void 0;
|
|
49
|
+
return imported;
|
|
50
|
+
} catch {
|
|
51
|
+
return void 0;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function selectTheme(theme) {
|
|
55
|
+
if (typeof theme === "number") return theme;
|
|
56
|
+
return prefersDark() ? theme.dark : theme.light;
|
|
57
|
+
}
|
|
58
|
+
function prefersDark() {
|
|
59
|
+
return document.documentElement.dataset.theme === "dark" ? true : document.documentElement.dataset.theme === "light" ? false : window.matchMedia("(prefers-color-scheme: dark)").matches;
|
|
60
|
+
}
|
|
61
|
+
export {
|
|
62
|
+
initD2Diagrams
|
|
63
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { D2Options } from "./src/types.js";
|
|
2
|
+
export type { D2ClientOptions, D2Layout, D2ModuleApi, D2Options, D2RenderMode, D2Theme, } from "./src/types.js";
|
|
3
|
+
export declare function d2(options?: D2Options): import("@riebeckite/core").RiebeckitePlugin<D2Options>;
|
|
4
|
+
/** Alias matching the `*Plugin` convention used by several packages. */
|
|
5
|
+
export declare const d2Plugin: typeof d2;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __esm = (fn, res, err) => function __init() {
|
|
4
|
+
if (err) throw err[0];
|
|
5
|
+
try {
|
|
6
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
7
|
+
} catch (e) {
|
|
8
|
+
throw err = [e], e;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// src/hast.ts
|
|
17
|
+
function visitElements(node, visitor, parent, index) {
|
|
18
|
+
if (isElementNode(node)) visitor(node, parent, index);
|
|
19
|
+
for (const [childIndex, child] of [...getChildren(node)].entries()) {
|
|
20
|
+
visitElements(
|
|
21
|
+
child,
|
|
22
|
+
visitor,
|
|
23
|
+
hasChildren(node) ? node : parent,
|
|
24
|
+
childIndex
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function element(tagName, properties = {}, children = []) {
|
|
29
|
+
return { type: "element", tagName, properties, children };
|
|
30
|
+
}
|
|
31
|
+
function text(value) {
|
|
32
|
+
return { type: "text", value };
|
|
33
|
+
}
|
|
34
|
+
function getTextContent(node) {
|
|
35
|
+
if (node.type === "text" && "value" in node && typeof node.value === "string") {
|
|
36
|
+
return node.value;
|
|
37
|
+
}
|
|
38
|
+
return getChildren(node).map(getTextContent).join("");
|
|
39
|
+
}
|
|
40
|
+
function getStringProperty(node, key) {
|
|
41
|
+
const value = node.properties?.[key];
|
|
42
|
+
if (typeof value === "string") return value;
|
|
43
|
+
if (Array.isArray(value)) return value.join(" ");
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
function hasClass(node, className) {
|
|
47
|
+
const value = node.properties?.className;
|
|
48
|
+
const classes = Array.isArray(value) ? value.map(String) : typeof value === "string" ? value.split(/\s+/) : [];
|
|
49
|
+
return classes.includes(className);
|
|
50
|
+
}
|
|
51
|
+
function isElementNode(node) {
|
|
52
|
+
return node.type === "element";
|
|
53
|
+
}
|
|
54
|
+
function hasChildren(node) {
|
|
55
|
+
return Array.isArray(node.children);
|
|
56
|
+
}
|
|
57
|
+
function getChildren(node) {
|
|
58
|
+
const children = node.children;
|
|
59
|
+
return Array.isArray(children) ? children : [];
|
|
60
|
+
}
|
|
61
|
+
var init_hast = __esm({
|
|
62
|
+
"src/hast.ts"() {
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// src/render-static.ts
|
|
67
|
+
var render_static_exports = {};
|
|
68
|
+
__export(render_static_exports, {
|
|
69
|
+
renderD2StaticSvg: () => renderD2StaticSvg
|
|
70
|
+
});
|
|
71
|
+
import { existsSync } from "node:fs";
|
|
72
|
+
import { createRequire } from "node:module";
|
|
73
|
+
import { join } from "node:path";
|
|
74
|
+
import { pathToFileURL } from "node:url";
|
|
75
|
+
async function renderD2StaticSvg(id, source, options) {
|
|
76
|
+
return enqueueD2Render(async () => {
|
|
77
|
+
let renderer;
|
|
78
|
+
try {
|
|
79
|
+
const module = await importD2Module();
|
|
80
|
+
renderer = new module.D2();
|
|
81
|
+
} catch (error) {
|
|
82
|
+
return {
|
|
83
|
+
ok: false,
|
|
84
|
+
kind: "renderer-error",
|
|
85
|
+
message: `Failed to load the D2 renderer: ${formatError(error)}`
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
let compiled;
|
|
90
|
+
try {
|
|
91
|
+
compiled = await withTimeout(
|
|
92
|
+
renderer.compile(source, {
|
|
93
|
+
layout: options.layout,
|
|
94
|
+
themeID: options.themeID,
|
|
95
|
+
salt: id
|
|
96
|
+
}),
|
|
97
|
+
"D2 compilation timed out."
|
|
98
|
+
);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
kind: error instanceof D2TimeoutError ? "renderer-error" : "invalid-diagram",
|
|
103
|
+
message: formatError(error)
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
let svg;
|
|
107
|
+
try {
|
|
108
|
+
svg = await withTimeout(
|
|
109
|
+
Promise.resolve(
|
|
110
|
+
renderer.render(compiled.diagram, {
|
|
111
|
+
...compiled.renderOptions,
|
|
112
|
+
noXMLTag: true
|
|
113
|
+
})
|
|
114
|
+
),
|
|
115
|
+
"D2 rendering timed out."
|
|
116
|
+
);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
kind: "renderer-error",
|
|
121
|
+
message: formatError(error)
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
if (typeof svg !== "string" || !svg.includes("<svg")) {
|
|
125
|
+
return {
|
|
126
|
+
ok: false,
|
|
127
|
+
kind: "renderer-error",
|
|
128
|
+
message: "D2 renderer returned an invalid SVG."
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
return { ok: true, svg };
|
|
132
|
+
} finally {
|
|
133
|
+
if (typeof renderer.dispose === "function") {
|
|
134
|
+
try {
|
|
135
|
+
await renderer.dispose();
|
|
136
|
+
} catch {
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
async function importD2Module() {
|
|
143
|
+
const importModule = new Function(
|
|
144
|
+
"specifier",
|
|
145
|
+
"return import(specifier)"
|
|
146
|
+
);
|
|
147
|
+
try {
|
|
148
|
+
return normalizeD2Module(await importModule(D2_PACKAGE));
|
|
149
|
+
} catch (error) {
|
|
150
|
+
const fallback = resolveD2FromWorkingDirectory();
|
|
151
|
+
if (!fallback) throw error;
|
|
152
|
+
return normalizeD2Module(await importModule(fallback));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function normalizeD2Module(value) {
|
|
156
|
+
const module = value;
|
|
157
|
+
const D2 = typeof module?.D2 === "function" ? module.D2 : module?.default?.D2;
|
|
158
|
+
if (typeof D2 !== "function") {
|
|
159
|
+
throw new Error("The D2 module did not export a D2 class.");
|
|
160
|
+
}
|
|
161
|
+
return { D2 };
|
|
162
|
+
}
|
|
163
|
+
function resolveD2FromWorkingDirectory() {
|
|
164
|
+
try {
|
|
165
|
+
const require2 = createRequire(join(process.cwd(), "package.json"));
|
|
166
|
+
const resolved = require2.resolve(D2_PACKAGE);
|
|
167
|
+
const esm = resolved.replace(/dist[\\/]node-cjs[\\/]index\.js$/, "dist/node-esm/index.js").replace(/dist[\\/]cjs[\\/]index\.js$/, "dist/esm/index.js");
|
|
168
|
+
const target = esm !== resolved && existsSync(esm) ? esm : resolved;
|
|
169
|
+
return pathToFileURL(target).href;
|
|
170
|
+
} catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function withTimeout(promise, message) {
|
|
175
|
+
let timer;
|
|
176
|
+
const timeout = new Promise((_, reject) => {
|
|
177
|
+
timer = setTimeout(
|
|
178
|
+
() => reject(new D2TimeoutError(message)),
|
|
179
|
+
RENDER_TIMEOUT_MS
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
183
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
async function enqueueD2Render(render) {
|
|
187
|
+
const current = renderQueue.then(render, render);
|
|
188
|
+
renderQueue = current.catch(() => void 0);
|
|
189
|
+
return current;
|
|
190
|
+
}
|
|
191
|
+
function formatError(error) {
|
|
192
|
+
if (error instanceof Error) return error.message;
|
|
193
|
+
return String(error);
|
|
194
|
+
}
|
|
195
|
+
var RENDER_TIMEOUT_MS, D2_PACKAGE, D2TimeoutError, renderQueue;
|
|
196
|
+
var init_render_static = __esm({
|
|
197
|
+
"src/render-static.ts"() {
|
|
198
|
+
RENDER_TIMEOUT_MS = 3e4;
|
|
199
|
+
D2_PACKAGE = "@d2lang/d2";
|
|
200
|
+
D2TimeoutError = class extends Error {
|
|
201
|
+
};
|
|
202
|
+
renderQueue = Promise.resolve();
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
// src/rehype.ts
|
|
207
|
+
var rehype_exports = {};
|
|
208
|
+
__export(rehype_exports, {
|
|
209
|
+
rehypeD2: () => rehypeD2
|
|
210
|
+
});
|
|
211
|
+
function rehypeD2(options = {}) {
|
|
212
|
+
const resolved = {
|
|
213
|
+
render: options.render ?? "build",
|
|
214
|
+
theme: options.theme ?? DEFAULT_THEME,
|
|
215
|
+
layout: options.layout ?? DEFAULT_LAYOUT,
|
|
216
|
+
caption: options.caption !== false,
|
|
217
|
+
fallback: options.fallback !== false,
|
|
218
|
+
className: options.className?.trim() || DEFAULT_CLASS_NAME
|
|
219
|
+
};
|
|
220
|
+
return async (tree, file) => {
|
|
221
|
+
const replacements = [];
|
|
222
|
+
visitElements(tree, (node, parent, index) => {
|
|
223
|
+
if (!parent || index === void 0 || !isD2CodeBlock(node)) return;
|
|
224
|
+
replacements.push(replaceD2Block(parent, index, node, file, resolved));
|
|
225
|
+
});
|
|
226
|
+
await Promise.all(replacements);
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
async function replaceD2Block(parent, index, pre, file, options) {
|
|
230
|
+
const code = findDirectChild(pre, "code");
|
|
231
|
+
const rawSource = code ? getTextContent(code).trim() : getTextContent(pre).trim();
|
|
232
|
+
const { caption, body: source } = extractCaption(rawSource, pre, code);
|
|
233
|
+
const id = `rr-d2-${hashSource(source)}`;
|
|
234
|
+
const renderResult = shouldRenderAtBuild(options.render) ? await renderStaticSvg(id, source, options.theme, options.layout, file) : null;
|
|
235
|
+
const staticSvg = renderResult?.ok ? renderResult.svg : null;
|
|
236
|
+
parent.children = parent.children ?? [];
|
|
237
|
+
parent.children[index] = buildFigure({
|
|
238
|
+
className: options.className,
|
|
239
|
+
id,
|
|
240
|
+
source,
|
|
241
|
+
caption: options.caption ? caption : null,
|
|
242
|
+
layout: options.layout,
|
|
243
|
+
staticSvg,
|
|
244
|
+
fallback: options.fallback,
|
|
245
|
+
clientFallback: shouldRenderAtClient(options.render) || renderResult?.ok === false
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function buildFigure(input) {
|
|
249
|
+
const base = input.className;
|
|
250
|
+
const labelId = `${input.id}-caption`;
|
|
251
|
+
const children = [];
|
|
252
|
+
if (input.caption) {
|
|
253
|
+
children.push(
|
|
254
|
+
element("figcaption", { id: labelId, className: `${base}__caption` }, [
|
|
255
|
+
text(input.caption)
|
|
256
|
+
])
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
children.push(
|
|
260
|
+
element(
|
|
261
|
+
"div",
|
|
262
|
+
{
|
|
263
|
+
className: `${base}__canvas`,
|
|
264
|
+
dataD2Canvas: "true",
|
|
265
|
+
role: "img",
|
|
266
|
+
ariaLabelledby: input.caption ? labelId : void 0,
|
|
267
|
+
ariaLabel: input.caption ? void 0 : "D2 diagram"
|
|
268
|
+
},
|
|
269
|
+
input.staticSvg ? [{ type: "raw", value: input.staticSvg }] : []
|
|
270
|
+
)
|
|
271
|
+
);
|
|
272
|
+
if (input.fallback) {
|
|
273
|
+
children.push(
|
|
274
|
+
element("details", { className: `${base}__fallback` }, [
|
|
275
|
+
element("summary", {}, [text("Diagram source")]),
|
|
276
|
+
element("pre", {}, [element("code", {}, [text(input.source)])])
|
|
277
|
+
])
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
return element(
|
|
281
|
+
"figure",
|
|
282
|
+
{
|
|
283
|
+
className: base,
|
|
284
|
+
dataD2: input.staticSvg ? "rendered" : "pending",
|
|
285
|
+
dataD2Source: input.source,
|
|
286
|
+
dataD2Layout: input.layout
|
|
287
|
+
},
|
|
288
|
+
children
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
async function renderStaticSvg(id, source, theme, layout, file) {
|
|
292
|
+
try {
|
|
293
|
+
const { renderD2StaticSvg: renderD2StaticSvg2 } = await Promise.resolve().then(() => (init_render_static(), render_static_exports));
|
|
294
|
+
const result = await renderD2StaticSvg2(id, source, {
|
|
295
|
+
themeID: selectTheme(theme, "light"),
|
|
296
|
+
layout
|
|
297
|
+
});
|
|
298
|
+
if (result.ok === false) {
|
|
299
|
+
reportD2Diagnostic(file, result.message, result.kind);
|
|
300
|
+
const label = result.kind === "invalid-diagram" ? "invalid diagram" : "renderer failed";
|
|
301
|
+
console.warn(`[d2] ${label}: ${result.message}`);
|
|
302
|
+
}
|
|
303
|
+
return result;
|
|
304
|
+
} catch (error) {
|
|
305
|
+
const message = formatError2(error);
|
|
306
|
+
reportD2Diagnostic(file, message, "renderer-error");
|
|
307
|
+
console.warn(`[d2] renderer failed: ${message}`);
|
|
308
|
+
return { ok: false, kind: "renderer-error", message };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
function reportD2Diagnostic(file, message, kind) {
|
|
312
|
+
const reporter = file?.message;
|
|
313
|
+
if (typeof reporter !== "function") return;
|
|
314
|
+
const diagnostic = reporter.call(
|
|
315
|
+
file,
|
|
316
|
+
kind === "invalid-diagram" ? `Invalid D2 diagram: ${message}` : `D2 renderer failed: ${message}`
|
|
317
|
+
);
|
|
318
|
+
if (diagnostic && typeof diagnostic === "object") {
|
|
319
|
+
Object.assign(diagnostic, {
|
|
320
|
+
source: "@riebeckite/plugin-d2",
|
|
321
|
+
ruleId: kind
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function isD2CodeBlock(node) {
|
|
326
|
+
if (node.tagName !== "pre") return false;
|
|
327
|
+
const code = findDirectChild(node, "code");
|
|
328
|
+
return Boolean(code && hasClass(code, "language-d2"));
|
|
329
|
+
}
|
|
330
|
+
function findDirectChild(node, tagName) {
|
|
331
|
+
return node.children?.find(
|
|
332
|
+
(child) => child.type === "element" && child.tagName === tagName
|
|
333
|
+
) ?? null;
|
|
334
|
+
}
|
|
335
|
+
function extractCaption(source, pre, code) {
|
|
336
|
+
const title = getStringProperty(pre, "title") ?? getStringProperty(code ?? pre, "title");
|
|
337
|
+
const match = CAPTION_PATTERN.exec(source);
|
|
338
|
+
const caption = title ?? match?.[1] ?? null;
|
|
339
|
+
const body = match ? `${source.slice(0, match.index)}${source.slice(match.index + match[0].length)}` : source;
|
|
340
|
+
return { caption: caption?.trim() || null, body: body.trim() };
|
|
341
|
+
}
|
|
342
|
+
function shouldRenderAtBuild(render) {
|
|
343
|
+
return render === "build" || render === "both";
|
|
344
|
+
}
|
|
345
|
+
function shouldRenderAtClient(render) {
|
|
346
|
+
return render === "client";
|
|
347
|
+
}
|
|
348
|
+
function selectTheme(theme, mode) {
|
|
349
|
+
return typeof theme === "number" ? theme : theme[mode];
|
|
350
|
+
}
|
|
351
|
+
function hashSource(source) {
|
|
352
|
+
let hash = 0;
|
|
353
|
+
for (const char of source) hash = hash * 31 + char.charCodeAt(0) | 0;
|
|
354
|
+
return Math.abs(hash).toString(36);
|
|
355
|
+
}
|
|
356
|
+
function formatError2(error) {
|
|
357
|
+
if (error instanceof Error) return error.message;
|
|
358
|
+
return String(error);
|
|
359
|
+
}
|
|
360
|
+
var DEFAULT_THEME, DEFAULT_CLASS_NAME, DEFAULT_LAYOUT, CAPTION_PATTERN;
|
|
361
|
+
var init_rehype = __esm({
|
|
362
|
+
"src/rehype.ts"() {
|
|
363
|
+
init_hast();
|
|
364
|
+
DEFAULT_THEME = { light: 0, dark: 1 };
|
|
365
|
+
DEFAULT_CLASS_NAME = "rb-d2";
|
|
366
|
+
DEFAULT_LAYOUT = "dagre";
|
|
367
|
+
CAPTION_PATTERN = /^#\s*caption\s*:\s*(.+)$/im;
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
// index.ts
|
|
372
|
+
import {
|
|
373
|
+
createClientEntry,
|
|
374
|
+
createStyleAsset,
|
|
375
|
+
definePlugin
|
|
376
|
+
} from "@riebeckite/core";
|
|
377
|
+
var LAYOUTS = ["dagre", "elk"];
|
|
378
|
+
function d2(options = {}) {
|
|
379
|
+
return definePlugin({
|
|
380
|
+
name: "d2",
|
|
381
|
+
order: -10,
|
|
382
|
+
options,
|
|
383
|
+
validateOptions: validateD2Options,
|
|
384
|
+
extendHtmlPipeline: (pipeline) => {
|
|
385
|
+
pipeline.use(rehypeD2Lazy, options);
|
|
386
|
+
},
|
|
387
|
+
assets: [createStyleAsset("d2")],
|
|
388
|
+
clientEntries: [createClientEntry("d2", "initD2Diagrams")]
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
var d2Plugin = d2;
|
|
392
|
+
function validateD2Options(options) {
|
|
393
|
+
if (!options) return [];
|
|
394
|
+
const issues = [];
|
|
395
|
+
if (options.render !== void 0 && options.render !== "build" && options.render !== "client" && options.render !== "both") {
|
|
396
|
+
issues.push({
|
|
397
|
+
path: "render",
|
|
398
|
+
message: 'Expected "build", "client", or "both".'
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
if (options.layout !== void 0 && !LAYOUTS.includes(options.layout)) {
|
|
402
|
+
issues.push({ path: "layout", message: 'Expected "dagre" or "elk".' });
|
|
403
|
+
}
|
|
404
|
+
if (!isD2Theme(options.theme)) {
|
|
405
|
+
issues.push({
|
|
406
|
+
path: "theme",
|
|
407
|
+
message: "Expected a theme number or an object with light and dark numbers."
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
for (const key of ["caption", "fallback"]) {
|
|
411
|
+
if (options[key] !== void 0 && typeof options[key] !== "boolean") {
|
|
412
|
+
issues.push({ path: key, message: "Expected a boolean." });
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (options.className !== void 0 && (typeof options.className !== "string" || options.className.trim() === "")) {
|
|
416
|
+
issues.push({ path: "className", message: "Expected a non-empty string." });
|
|
417
|
+
}
|
|
418
|
+
return issues;
|
|
419
|
+
}
|
|
420
|
+
function isD2Theme(value) {
|
|
421
|
+
return value === void 0 || typeof value === "number" || typeof value === "object" && value !== null && "light" in value && "dark" in value && typeof value.light === "number" && typeof value.dark === "number";
|
|
422
|
+
}
|
|
423
|
+
function rehypeD2Lazy(options = {}) {
|
|
424
|
+
return async (tree, file) => {
|
|
425
|
+
const { rehypeD2: rehypeD22 } = await Promise.resolve().then(() => (init_rehype(), rehype_exports));
|
|
426
|
+
const transformer = rehypeD22(options);
|
|
427
|
+
await transformer(tree, file);
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
export {
|
|
431
|
+
d2,
|
|
432
|
+
d2Plugin
|
|
433
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ElementNode, HastNode, ParentNode, TextNode } from "./types.js";
|
|
2
|
+
export declare function visitElements(node: HastNode, visitor: (node: ElementNode, parent?: ParentNode, index?: number) => void, parent?: ParentNode, index?: number): void;
|
|
3
|
+
export declare function element(tagName: string, properties?: Record<string, unknown>, children?: HastNode[]): ElementNode;
|
|
4
|
+
export declare function text(value: string): TextNode;
|
|
5
|
+
export declare function getTextContent(node: HastNode): string;
|
|
6
|
+
export declare function getStringProperty(node: ElementNode, key: string): string | null;
|
|
7
|
+
export declare function hasClass(node: ElementNode, className: string): boolean;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { D2ClientOptions } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Renders every pending D2 figure in the document.
|
|
4
|
+
*
|
|
5
|
+
* The initializer is intentionally dependency-free at bundle time: D2.js is
|
|
6
|
+
* imported from `moduleUrl` in the browser, so a site that renders D2 at build
|
|
7
|
+
* time never ships the WASM renderer to visitors unless it opts into the
|
|
8
|
+
* `"client"` render mode.
|
|
9
|
+
*/
|
|
10
|
+
export declare function initD2Diagrams(options?: D2ClientOptions): Promise<void>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export type D2RenderMode = "build" | "client" | "both";
|
|
2
|
+
export type D2Layout = "dagre" | "elk";
|
|
3
|
+
/**
|
|
4
|
+
* D2 theme id, or a light/dark pair of theme ids. D2's default theme is `0`;
|
|
5
|
+
* `1` is the built-in dark theme.
|
|
6
|
+
*/
|
|
7
|
+
export type D2Theme = number | {
|
|
8
|
+
light: number;
|
|
9
|
+
dark: number;
|
|
10
|
+
};
|
|
11
|
+
export type D2Options = {
|
|
12
|
+
render?: D2RenderMode;
|
|
13
|
+
theme?: D2Theme;
|
|
14
|
+
layout?: D2Layout;
|
|
15
|
+
caption?: boolean;
|
|
16
|
+
fallback?: boolean;
|
|
17
|
+
/** Base CSS class for the generated figure. Defaults to `"rb-d2"`. */
|
|
18
|
+
className?: string;
|
|
19
|
+
};
|
|
20
|
+
export type D2BuildRenderErrorKind = "invalid-diagram" | "renderer-error";
|
|
21
|
+
export type D2BuildRenderResult = {
|
|
22
|
+
ok: true;
|
|
23
|
+
svg: string;
|
|
24
|
+
} | {
|
|
25
|
+
ok: false;
|
|
26
|
+
kind: D2BuildRenderErrorKind;
|
|
27
|
+
message: string;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Minimal structural surface of the D2.js instance used by the browser
|
|
31
|
+
* initializer. Declaring it locally keeps `@d2lang/d2` out of the published
|
|
32
|
+
* type surface.
|
|
33
|
+
*/
|
|
34
|
+
export type D2InstanceApi = {
|
|
35
|
+
compile(source: string, options?: Record<string, unknown>): Promise<{
|
|
36
|
+
diagram: unknown;
|
|
37
|
+
renderOptions?: Record<string, unknown>;
|
|
38
|
+
}>;
|
|
39
|
+
render(diagram: unknown, options?: Record<string, unknown>): Promise<string> | string;
|
|
40
|
+
dispose?(): Promise<void> | void;
|
|
41
|
+
};
|
|
42
|
+
export type D2ModuleApi = {
|
|
43
|
+
D2: new () => D2InstanceApi;
|
|
44
|
+
};
|
|
45
|
+
export type D2ClientOptions = {
|
|
46
|
+
theme?: D2Theme;
|
|
47
|
+
layout?: D2Layout;
|
|
48
|
+
/** A preloaded D2.js module. When omitted, `moduleUrl` is imported. */
|
|
49
|
+
api?: D2ModuleApi;
|
|
50
|
+
/** ESM URL used to load D2.js in the browser. */
|
|
51
|
+
moduleUrl?: string;
|
|
52
|
+
};
|
|
53
|
+
export type ElementNode = {
|
|
54
|
+
type: string;
|
|
55
|
+
tagName?: string;
|
|
56
|
+
properties?: Record<string, unknown>;
|
|
57
|
+
children?: HastNode[];
|
|
58
|
+
};
|
|
59
|
+
export type ParentNode = HastNode & {
|
|
60
|
+
children?: HastNode[];
|
|
61
|
+
};
|
|
62
|
+
export type TextNode = {
|
|
63
|
+
type: "text";
|
|
64
|
+
value: string;
|
|
65
|
+
};
|
|
66
|
+
export type RawNode = {
|
|
67
|
+
type: "raw";
|
|
68
|
+
value: string;
|
|
69
|
+
};
|
|
70
|
+
export type HastNode = ElementNode | TextNode | RawNode | {
|
|
71
|
+
type: string;
|
|
72
|
+
[key: string]: unknown;
|
|
73
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@riebeckite/plugin-d2",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"source": "./index.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./client": {
|
|
16
|
+
"types": "./dist/client.d.ts",
|
|
17
|
+
"import": "./dist/client.js",
|
|
18
|
+
"source": "./client.ts",
|
|
19
|
+
"default": "./dist/client.js"
|
|
20
|
+
},
|
|
21
|
+
"./style.css": "./style.css"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@d2lang/d2": "^0.1.34",
|
|
25
|
+
"@riebeckite/core": "0.0.1"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"LICENSE",
|
|
32
|
+
"README.md",
|
|
33
|
+
"README_ja.md",
|
|
34
|
+
"dist",
|
|
35
|
+
"style.css"
|
|
36
|
+
],
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "https://github.com/Rerurate514/riebeckite.git",
|
|
40
|
+
"directory": "packages/plugins/d2"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/Rerurate514/riebeckite#readme",
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/Rerurate514/riebeckite/issues"
|
|
45
|
+
},
|
|
46
|
+
"description": "D2 diagram rendering for Riebeckite code blocks.",
|
|
47
|
+
"keywords": [
|
|
48
|
+
"riebeckite",
|
|
49
|
+
"plugin",
|
|
50
|
+
"d2",
|
|
51
|
+
"diagrams"
|
|
52
|
+
],
|
|
53
|
+
"engines": {
|
|
54
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
55
|
+
},
|
|
56
|
+
"sideEffects": [
|
|
57
|
+
"./style.css"
|
|
58
|
+
],
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "node ../../../scripts/build_package.mjs"
|
|
61
|
+
}
|
|
62
|
+
}
|
package/style.css
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
.rb-d2 {
|
|
2
|
+
--rb-d2-paper: var(--rb-color-paper, #ffffff);
|
|
3
|
+
--rb-d2-ink: var(--rb-color-ink, #000000);
|
|
4
|
+
--rb-d2-muted: var(--rb-color-muted, #69645c);
|
|
5
|
+
--rb-d2-rule: var(
|
|
6
|
+
--rb-color-border,
|
|
7
|
+
color-mix(in srgb, var(--rb-d2-ink) 18%, transparent)
|
|
8
|
+
);
|
|
9
|
+
--rb-d2-accent: var(--rb-color-accent, #686868);
|
|
10
|
+
margin: 2rem 0;
|
|
11
|
+
border: 1px solid var(--rb-d2-rule);
|
|
12
|
+
background: color-mix(in srgb, var(--rb-d2-paper) 96%, var(--rb-d2-ink));
|
|
13
|
+
color: var(--rb-d2-ink);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
.rb-d2__caption {
|
|
17
|
+
padding: 0.625rem 0.75rem;
|
|
18
|
+
border-bottom: 1px solid var(--rb-d2-rule);
|
|
19
|
+
color: var(--rb-d2-muted);
|
|
20
|
+
font-size: 0.875rem;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
.rb-d2__canvas {
|
|
24
|
+
overflow: auto;
|
|
25
|
+
padding: 1rem;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
.rb-d2__canvas > svg {
|
|
29
|
+
display: block;
|
|
30
|
+
justify-self: center;
|
|
31
|
+
max-width: 100%;
|
|
32
|
+
height: auto;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
.rb-d2__fallback {
|
|
36
|
+
border-top: 1px solid var(--rb-d2-rule);
|
|
37
|
+
color: var(--rb-d2-muted);
|
|
38
|
+
font-size: 0.8125rem;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
.rb-d2__fallback summary {
|
|
42
|
+
cursor: pointer;
|
|
43
|
+
padding: 0.5rem 0.75rem;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
.rb-d2__fallback pre {
|
|
47
|
+
overflow: auto;
|
|
48
|
+
margin: 0 1rem;
|
|
49
|
+
padding: 0.75rem;
|
|
50
|
+
border-top: 1px solid var(--rb-d2-rule);
|
|
51
|
+
color: var(--rb-d2-ink);
|
|
52
|
+
background: color-mix(in srgb, var(--rb-d2-ink) 6%, transparent);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
.rb-d2[data-d2="error"] .rb-d2__canvas::before,
|
|
56
|
+
.rb-d2[data-d2="pending"] .rb-d2__canvas:empty::before {
|
|
57
|
+
content: "Diagram could not be rendered.";
|
|
58
|
+
color: var(--rb-d2-muted);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
html[data-theme="dark"] .rb-d2,
|
|
62
|
+
html.dark .rb-d2 {
|
|
63
|
+
--rb-d2-paper: var(--rb-color-ink, #000000);
|
|
64
|
+
--rb-d2-ink: var(--rb-color-paper, #ffffff);
|
|
65
|
+
}
|