@riebeckite/diagram 0.0.0-stage → 0.0.33

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 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 CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @riebeckite/diagram
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [日本語](./README_ja.md)
4
+
5
+ Shared HAST, figure, diagnostics, render-session, client lifecycle, and plugin-definition utilities for Riebeckite diagram plugins.
package/README_ja.md ADDED
@@ -0,0 +1,5 @@
1
+ # @riebeckite/diagram
2
+
3
+ [English](./README.md)
4
+
5
+ Riebeckite の Diagram プラグインで共有する HAST、figure、診断、描画セッション、クライアントライフサイクル、Plugin 定義のユーティリティです。
@@ -0,0 +1,2 @@
1
+ export type { DiagramClientContext, DiagramClientRenderer, } from "./src/client.js";
2
+ export { detectDiagramTheme, renderPendingDiagrams } from "./src/client.js";
package/dist/client.js ADDED
@@ -0,0 +1,33 @@
1
+ // src/client.ts
2
+ async function renderPendingDiagrams(kind, renderer, context = {}) {
3
+ const root = context.root ?? document;
4
+ const selector = `[data-diagram="${CSS.escape(kind)}"][data-diagram-status="pending"]`;
5
+ const cleanups = [];
6
+ for (const figure of Array.from(
7
+ root.querySelectorAll(selector)
8
+ )) {
9
+ if (context.signal?.aborted || !figure.isConnected) break;
10
+ try {
11
+ const cleanup = await renderer(figure, context);
12
+ if (cleanup) cleanups.push(cleanup);
13
+ if (!context.signal?.aborted && figure.isConnected)
14
+ figure.dataset.diagramStatus = "rendered";
15
+ } catch {
16
+ if (!context.signal?.aborted && figure.isConnected) {
17
+ figure.dataset.diagramStatus = "error";
18
+ figure.querySelector("[data-diagram-fallback]")?.setAttribute("open", "");
19
+ }
20
+ }
21
+ }
22
+ return () => {
23
+ for (const cleanup of cleanups) cleanup();
24
+ };
25
+ }
26
+ function detectDiagramTheme() {
27
+ const theme = document.documentElement.dataset.theme;
28
+ return theme === "dark" || theme !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
29
+ }
30
+ export {
31
+ detectDiagramTheme,
32
+ renderPendingDiagrams
33
+ };
@@ -0,0 +1,7 @@
1
+ export { resolveDiagramCaption } from "./src/caption.js";
2
+ export { reportDiagramDiagnostic } from "./src/diagnostic.js";
3
+ export { buildDiagramFigure, deterministicDiagramId } from "./src/figure.js";
4
+ export { element, findDiagramBlocks, getStringProperty, getTextContent, hasClass, mergeClassName, text, visitElements, } from "./src/hast.js";
5
+ export { defineDiagramPlugin } from "./src/plugin.js";
6
+ export { createRenderSession } from "./src/session.js";
7
+ export type { DiagramBlock, DiagramBuildRenderer, DiagramBuildResult, DiagramCaptionStrategy, DiagramContent, DiagramErrorKind, DiagramFigureInput, DiagramNode, DiagramPluginDefinition, DiagramRenderMode, DiagramSession, } from "./src/types.js";
package/dist/index.js ADDED
@@ -0,0 +1,340 @@
1
+ // src/hast.ts
2
+ function findDiagramBlocks(tree, options) {
3
+ const languages = new Set(options.languages);
4
+ const blocks = [];
5
+ visit(tree, (node, parent, index) => {
6
+ if (!parent || index === void 0 || node.tagName !== "pre") return;
7
+ const code = node.children?.find(isCode);
8
+ const language = code ? findLanguage(code) : null;
9
+ if (!code || !language || !languages.has(language)) return;
10
+ blocks.push({
11
+ pre: node,
12
+ code,
13
+ parent,
14
+ index,
15
+ source: getTextContent(code).trim(),
16
+ language
17
+ });
18
+ });
19
+ return blocks;
20
+ }
21
+ function getTextContent(node) {
22
+ if (node.type === "text" && typeof node.value === "string") return node.value;
23
+ return (node.children ?? []).map(getTextContent).join("");
24
+ }
25
+ function visitElements(node, visitor, parent, index) {
26
+ if (node.type === "element") visitor(node, parent, index);
27
+ for (const [childIndex, child] of [...node.children ?? []].entries())
28
+ visitElements(child, visitor, node, childIndex);
29
+ }
30
+ function stringProperty(node, key) {
31
+ const value = node.properties?.[key];
32
+ if (typeof value === "string") return value;
33
+ if (Array.isArray(value)) return value.join(" ");
34
+ return null;
35
+ }
36
+ var getStringProperty = stringProperty;
37
+ function hasClass(node, className) {
38
+ const value = node.properties?.className;
39
+ const classes = Array.isArray(value) ? value.map(String) : typeof value === "string" ? value.split(/\s+/) : [];
40
+ return classes.includes(className);
41
+ }
42
+ function mergeClassName(current, next) {
43
+ const value = Array.isArray(current) ? current.join(" ") : typeof current === "string" ? current : "";
44
+ return value ? `${value} ${next}` : next;
45
+ }
46
+ function element(tagName, properties = {}, children = []) {
47
+ return { type: "element", tagName, properties, children };
48
+ }
49
+ function text(value) {
50
+ return { type: "text", value };
51
+ }
52
+ function visit(node, visitor, parent, index) {
53
+ visitor(node, parent, index);
54
+ for (const [childIndex, child] of [...node.children ?? []].entries())
55
+ visit(child, visitor, node, childIndex);
56
+ }
57
+ function isCode(node) {
58
+ return node.type === "element" && node.tagName === "code";
59
+ }
60
+ function findLanguage(node) {
61
+ const value = node.properties?.className;
62
+ const classes = Array.isArray(value) ? value.map(String) : typeof value === "string" ? value.split(/\s+/) : [];
63
+ return classes.find((name) => name.startsWith("language-"))?.slice("language-".length) ?? null;
64
+ }
65
+
66
+ // src/caption.ts
67
+ function resolveDiagramCaption(block, strategies = []) {
68
+ const title = stringProperty(block.pre, "title") ?? stringProperty(block.code, "title");
69
+ if (title?.trim()) return title.trim();
70
+ for (const strategy of strategies) {
71
+ const caption = strategy(block)?.trim();
72
+ if (caption) return caption;
73
+ }
74
+ return null;
75
+ }
76
+
77
+ // src/diagnostic.ts
78
+ function reportDiagramDiagnostic(file, input) {
79
+ const reporter = file?.message;
80
+ if (typeof reporter !== "function") return;
81
+ const diagnostic = reporter.call(file, input.message);
82
+ if (diagnostic && typeof diagnostic === "object")
83
+ Object.assign(diagnostic, { source: input.source, ruleId: input.ruleId });
84
+ }
85
+
86
+ // src/figure.ts
87
+ function deterministicDiagramId(kind, source) {
88
+ let hash = 0;
89
+ for (const character of source)
90
+ hash = hash * 31 + character.charCodeAt(0) | 0;
91
+ return `rb-${kind}-${Math.abs(hash).toString(36)}`;
92
+ }
93
+ function buildDiagramFigure(input) {
94
+ const labelId = `${input.id}-caption`;
95
+ const children = [];
96
+ if (input.caption)
97
+ children.push(
98
+ element(
99
+ "figcaption",
100
+ {
101
+ id: labelId,
102
+ className: `${input.className}__caption`,
103
+ dataDiagramCaption: "true"
104
+ },
105
+ [text(input.caption)]
106
+ )
107
+ );
108
+ children.push(buildContent(input, labelId));
109
+ if (input.fallback)
110
+ children.push(
111
+ element(
112
+ "details",
113
+ {
114
+ className: `${input.className}__fallback rb-source-fallback`,
115
+ dataDiagramFallback: "true"
116
+ },
117
+ [
118
+ element("summary", {}, [
119
+ text(input.fallbackLabel ?? "Diagram source")
120
+ ]),
121
+ element("pre", {}, [element("code", {}, [text(input.source)])])
122
+ ]
123
+ )
124
+ );
125
+ return element(
126
+ "figure",
127
+ {
128
+ className: input.className,
129
+ dataDiagram: input.kind,
130
+ dataDiagramStatus: input.status,
131
+ dataDiagramId: input.id,
132
+ ...input.attributes
133
+ },
134
+ children
135
+ );
136
+ }
137
+ function buildContent(input, labelId) {
138
+ const properties = {
139
+ className: `${input.className}__canvas`,
140
+ dataDiagramContent: "true",
141
+ role: "img",
142
+ ariaLabelledby: input.caption ? labelId : void 0,
143
+ ariaLabel: input.caption ? void 0 : input.label
144
+ };
145
+ if (input.content.kind === "canvas")
146
+ return element("canvas", { ...properties, ...input.content.attrs }, []);
147
+ if (input.content.kind === "image")
148
+ return element(
149
+ "img",
150
+ {
151
+ ...properties,
152
+ src: input.content.src,
153
+ alt: input.content.alt ?? input.label,
154
+ loading: "lazy"
155
+ },
156
+ []
157
+ );
158
+ return element("div", properties, [
159
+ { type: "raw", value: input.content.svg }
160
+ ]);
161
+ }
162
+
163
+ // src/plugin.ts
164
+ import {
165
+ createClientEntry,
166
+ createStyleAsset,
167
+ definePlugin
168
+ } from "@riebeckite/core";
169
+ function defineDiagramPlugin(definition) {
170
+ return definePlugin({
171
+ name: definition.name,
172
+ order: definition.order,
173
+ options: definition.options,
174
+ processedContentCache: definition.processedContentCache,
175
+ validateOptions: definition.validateOptions,
176
+ extendHtmlPipeline: (pipeline) => pipeline.use(definition.rehype, definition.options),
177
+ assets: definition.style ? [createStyleAsset(definition.name, definition.style)] : void 0,
178
+ clientEntries: definition.client ? [
179
+ createClientEntry(
180
+ definition.name,
181
+ definition.client.moduleSpecifier,
182
+ definition.client.exportName,
183
+ void 0,
184
+ "page",
185
+ "context"
186
+ )
187
+ ] : void 0
188
+ });
189
+ }
190
+
191
+ // src/session.ts
192
+ function createRenderSession(options) {
193
+ let queue = Promise.resolve();
194
+ let disposed = false;
195
+ let resourceLoaded = false;
196
+ let resource;
197
+ const enqueue = (task) => {
198
+ const current = queue.then(task, task);
199
+ queue = current.then(
200
+ () => void 0,
201
+ () => void 0
202
+ );
203
+ return current;
204
+ };
205
+ const ensureResource = async () => {
206
+ if (resourceLoaded || !options.launch) return resource;
207
+ resource = await options.launch();
208
+ resourceLoaded = true;
209
+ return resource;
210
+ };
211
+ const run = async (source, context) => {
212
+ if (disposed)
213
+ return {
214
+ ok: false,
215
+ kind: "aborted",
216
+ message: "Diagram render session is disposed."
217
+ };
218
+ if (context.signal?.aborted)
219
+ return {
220
+ ok: false,
221
+ kind: "aborted",
222
+ message: "Diagram rendering was aborted."
223
+ };
224
+ try {
225
+ const currentResource = await ensureResource();
226
+ const result = await renderOnce(
227
+ options.render,
228
+ source,
229
+ context,
230
+ currentResource,
231
+ options.timeoutMs
232
+ );
233
+ if (result.ok === true || !options.retry?.(result)) return result;
234
+ return await renderOnce(
235
+ options.render,
236
+ source,
237
+ context,
238
+ currentResource,
239
+ options.timeoutMs
240
+ );
241
+ } catch (error) {
242
+ return {
243
+ ok: false,
244
+ kind: "renderer-error",
245
+ message: error instanceof Error ? error.message : String(error)
246
+ };
247
+ }
248
+ };
249
+ return {
250
+ render(source, context) {
251
+ return enqueue(() => run(source, context));
252
+ },
253
+ dispose() {
254
+ return enqueue(async () => {
255
+ if (disposed) return;
256
+ disposed = true;
257
+ if (resourceLoaded) await options.cleanup?.(resource);
258
+ resource = void 0;
259
+ resourceLoaded = false;
260
+ });
261
+ }
262
+ };
263
+ }
264
+ async function renderOnce(render, source, context, resource, timeoutMs) {
265
+ const controller = new AbortController();
266
+ const abort = () => controller.abort();
267
+ context.signal?.addEventListener("abort", abort, { once: true });
268
+ try {
269
+ const result = await withTimeout(
270
+ render(
271
+ source,
272
+ { id: context.id, theme: context.theme, signal: controller.signal },
273
+ resource
274
+ ),
275
+ timeoutMs,
276
+ controller
277
+ );
278
+ if (context.signal?.aborted) {
279
+ return {
280
+ ok: false,
281
+ kind: "aborted",
282
+ message: "Diagram rendering was aborted."
283
+ };
284
+ }
285
+ return result;
286
+ } catch (error) {
287
+ if (context.signal?.aborted) {
288
+ return {
289
+ ok: false,
290
+ kind: "aborted",
291
+ message: "Diagram rendering was aborted."
292
+ };
293
+ }
294
+ if (error instanceof RenderTimeoutError) {
295
+ return {
296
+ ok: false,
297
+ kind: "timeout",
298
+ message: "Diagram rendering timed out."
299
+ };
300
+ }
301
+ return {
302
+ ok: false,
303
+ kind: "renderer-error",
304
+ message: error instanceof Error ? error.message : String(error)
305
+ };
306
+ } finally {
307
+ context.signal?.removeEventListener("abort", abort);
308
+ }
309
+ }
310
+ var RenderTimeoutError = class extends Error {
311
+ };
312
+ function withTimeout(promise, timeoutMs, controller) {
313
+ if (!timeoutMs) return promise;
314
+ let timer;
315
+ const timeout = new Promise((_, reject) => {
316
+ timer = setTimeout(() => {
317
+ controller.abort();
318
+ reject(new RenderTimeoutError());
319
+ }, timeoutMs);
320
+ });
321
+ return Promise.race([promise, timeout]).finally(() => {
322
+ if (timer) clearTimeout(timer);
323
+ });
324
+ }
325
+ export {
326
+ buildDiagramFigure,
327
+ createRenderSession,
328
+ defineDiagramPlugin,
329
+ deterministicDiagramId,
330
+ element,
331
+ findDiagramBlocks,
332
+ getStringProperty,
333
+ getTextContent,
334
+ hasClass,
335
+ mergeClassName,
336
+ reportDiagramDiagnostic,
337
+ resolveDiagramCaption,
338
+ text,
339
+ visitElements
340
+ };
@@ -0,0 +1,2 @@
1
+ import type { DiagramBlock, DiagramCaptionStrategy } from "./types.js";
2
+ export declare function resolveDiagramCaption(block: DiagramBlock, strategies?: readonly DiagramCaptionStrategy[]): string | null;
@@ -0,0 +1,7 @@
1
+ export type DiagramClientContext = {
2
+ root?: ParentNode;
3
+ signal?: AbortSignal;
4
+ };
5
+ export type DiagramClientRenderer = (figure: HTMLElement, context: DiagramClientContext) => Promise<undefined | (() => void)> | undefined | (() => void);
6
+ export declare function renderPendingDiagrams(kind: string, renderer: DiagramClientRenderer, context?: DiagramClientContext): Promise<() => void>;
7
+ export declare function detectDiagramTheme(): "light" | "dark";
@@ -0,0 +1,5 @@
1
+ export declare function reportDiagramDiagnostic(file: unknown, input: {
2
+ source: string;
3
+ ruleId: string;
4
+ message: string;
5
+ }): void;
@@ -0,0 +1,3 @@
1
+ import type { DiagramFigureInput, DiagramNode } from "./types.js";
2
+ export declare function deterministicDiagramId(kind: string, source: string): string;
3
+ export declare function buildDiagramFigure(input: DiagramFigureInput): DiagramNode;
@@ -0,0 +1,12 @@
1
+ import type { DiagramBlock, DiagramNode } from "./types.js";
2
+ export declare function findDiagramBlocks(tree: DiagramNode, options: {
3
+ languages: readonly string[];
4
+ }): DiagramBlock[];
5
+ export declare function getTextContent(node: DiagramNode): string;
6
+ export declare function visitElements(node: DiagramNode, visitor: (node: DiagramNode, parent?: DiagramNode, index?: number) => void, parent?: DiagramNode, index?: number): void;
7
+ export declare function stringProperty(node: DiagramNode, key: string): string | null;
8
+ export declare const getStringProperty: typeof stringProperty;
9
+ export declare function hasClass(node: DiagramNode, className: string): boolean;
10
+ export declare function mergeClassName(current: unknown, next: string): string;
11
+ export declare function element(tagName: string, properties?: Record<string, unknown>, children?: DiagramNode[]): DiagramNode;
12
+ export declare function text(value: string): DiagramNode;
@@ -0,0 +1,2 @@
1
+ import type { DiagramPluginDefinition } from "./types.js";
2
+ export declare function defineDiagramPlugin<TOptions>(definition: DiagramPluginDefinition<TOptions>): import("@riebeckite/core").RiebeckitePlugin<TOptions>;
@@ -0,0 +1,10 @@
1
+ import type { DiagramBuildRenderer, DiagramBuildResult, DiagramSession } from "./types.js";
2
+ export declare function createRenderSession<TResource = undefined>(options: {
3
+ render: DiagramBuildRenderer<TResource>;
4
+ launch?: () => Promise<TResource>;
5
+ cleanup?: (resource: TResource) => Promise<void> | void;
6
+ timeoutMs?: number;
7
+ retry?: (result: Extract<DiagramBuildResult, {
8
+ ok: false;
9
+ }>) => boolean;
10
+ }): DiagramSession;
@@ -0,0 +1,79 @@
1
+ import type { ConfigValidationIssue, RiebeckitePlugin } from "@riebeckite/core";
2
+ export type DiagramNode = {
3
+ type: string;
4
+ tagName?: string;
5
+ properties?: Record<string, unknown>;
6
+ children?: DiagramNode[];
7
+ value?: string;
8
+ [key: string]: unknown;
9
+ };
10
+ export type DiagramBlock = {
11
+ pre: DiagramNode;
12
+ code: DiagramNode;
13
+ parent: DiagramNode;
14
+ index: number;
15
+ source: string;
16
+ language: string;
17
+ };
18
+ export type DiagramCaptionStrategy = (block: DiagramBlock) => string | null | undefined;
19
+ export type DiagramContent = {
20
+ kind: "svg";
21
+ svg: string;
22
+ } | {
23
+ kind: "canvas";
24
+ attrs?: Record<string, string>;
25
+ } | {
26
+ kind: "image";
27
+ src: string;
28
+ alt?: string;
29
+ };
30
+ export type DiagramFigureInput = {
31
+ className: string;
32
+ id: string;
33
+ source: string;
34
+ caption?: string | null;
35
+ label: string;
36
+ content: DiagramContent;
37
+ fallback?: boolean;
38
+ fallbackLabel?: string;
39
+ status: "pending" | "rendered" | "error";
40
+ kind: string;
41
+ attributes?: Record<string, string | undefined>;
42
+ };
43
+ export type DiagramErrorKind = "invalid-diagram" | "renderer-error" | "timeout" | "aborted";
44
+ export type DiagramBuildResult = {
45
+ ok: true;
46
+ svg: string;
47
+ } | {
48
+ ok: false;
49
+ kind: DiagramErrorKind;
50
+ message: string;
51
+ retryable?: boolean;
52
+ };
53
+ export type DiagramBuildRenderer<TResource = undefined> = (source: string, context: {
54
+ id: string;
55
+ theme?: string;
56
+ signal: AbortSignal;
57
+ }, resource: TResource) => Promise<DiagramBuildResult>;
58
+ export type DiagramSession = {
59
+ render(source: string, context: {
60
+ id: string;
61
+ theme?: string;
62
+ signal?: AbortSignal;
63
+ }): Promise<DiagramBuildResult>;
64
+ dispose(): Promise<void>;
65
+ };
66
+ export type DiagramRenderMode = "build" | "client" | "both";
67
+ export type DiagramPluginDefinition<TOptions> = {
68
+ name: string;
69
+ order?: number;
70
+ options?: TOptions;
71
+ processedContentCache: NonNullable<RiebeckitePlugin["processedContentCache"]>;
72
+ validateOptions?: (options: TOptions | undefined) => readonly ConfigValidationIssue[];
73
+ rehype: (options: TOptions | undefined) => unknown;
74
+ style?: string;
75
+ client?: {
76
+ moduleSpecifier: string;
77
+ exportName: string;
78
+ };
79
+ };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@riebeckite/diagram",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.33",
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
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "LICENSE",
25
+ "README.md",
26
+ "README_ja.md",
27
+ "dist"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@riebeckite/core": "0.0.33"
34
+ },
35
+ "devDependencies": {
36
+ "@riebeckite/test": "0.0.33",
37
+ "tsx": "^4.22.4"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/Rerurate514/riebeckite.git",
42
+ "directory": "packages/diagram"
43
+ },
44
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
47
+ },
48
+ "description": "Shared diagram infrastructure for Riebeckite plugins.",
49
+ "keywords": [
50
+ "riebeckite",
51
+ "diagram",
52
+ "plugin"
53
+ ],
54
+ "engines": {
55
+ "node": "^20.19.0 || >=22.12.0"
56
+ },
57
+ "sideEffects": false,
58
+ "scripts": {
59
+ "build": "node ../../scripts/build_package.mjs",
60
+ "test": "node --import tsx --test \"test/*.test.ts\""
61
+ }
6
62
  }