@cardenelabs/dragon 0.40.0 → 0.41.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cardenelabs/dragon",
3
- "version": "0.40.0",
3
+ "version": "0.41.1",
4
4
  "description": "Dragon — 動く図を、人は行ごとの記法で、AI は JSON で書く。時系列図と構成図を段ごとに動かし、mp4・GIF・HTML・PNG に書き出す。",
5
5
  "license": "MIT",
6
6
  "author": "cardene777",
@@ -52,6 +52,16 @@
52
52
  "types": "./dist/export.d.cts",
53
53
  "default": "./dist/export.cjs"
54
54
  }
55
+ },
56
+ "./node": {
57
+ "import": {
58
+ "types": "./dist/node.d.ts",
59
+ "default": "./dist/node.js"
60
+ },
61
+ "require": {
62
+ "types": "./dist/node.d.cts",
63
+ "default": "./dist/node.cjs"
64
+ }
55
65
  }
56
66
  },
57
67
  "files": [
@@ -39,6 +39,12 @@ const LAUNCH_TEXT: Record<NotationLang, { missing: string; cannotLaunch: string;
39
39
  },
40
40
  };
41
41
 
42
+ /** 撮る頁が字の file を読めない時の断りの文。読めない file を `"<字の名前>" <字の範囲>` で並べて名指す (#3212) */
43
+ const FONT_TEXT: Record<NotationLang, (faces: string[]) => string> = {
44
+ ja: (faces) => `書き出しに埋める字の file を Chromium が読めない (${faces.join("、")})`,
45
+ en: (faces) => `Chromium cannot read the font files embedded in the export (${faces.join("; ")})`,
46
+ };
47
+
42
48
  /** 画面なしの Chromium を起こす。起こせない時は、渡した言葉で入れ方を添えて断る */
43
49
  export async function launch(lang: NotationLang): Promise<Browser> {
44
50
  const text = LAUNCH_TEXT[lang];
@@ -70,8 +76,9 @@ export interface Stage {
70
76
  /**
71
77
  * 図 1 枚を置いた頁を開き、字が読み込まれるまで待つ。`body` は頁の地の CSS。
72
78
  * 図は置く前から止めておく。置いてから止めると、止めるまでに進んだ分だけ毎回絵がずれる。
79
+ * 字の file を 1 つでも読めない時は、読めない file を `lang` の言葉で名指して断る。
73
80
  */
74
- export async function stage(browser: Browser, svg: string, fontCss: string, body: string): Promise<Stage> {
81
+ export async function stage(browser: Browser, svg: string, fontCss: string, body: string, lang: NotationLang): Promise<Stage> {
75
82
  const { width, height } = sizeOf(svg);
76
83
  const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: SCALE });
77
84
  const paused = svg.replace(/^<svg\b/, '<svg style="--play:paused;--at:0"');
@@ -86,12 +93,17 @@ export async function stage(browser: Browser, svg: string, fontCss: string, body
86
93
  });
87
94
  await page.goto("http://localhost/");
88
95
  await page.waitForFunction(() => "__tools" in window);
89
- await page.evaluate(async () => {
90
- const loads: Promise<FontFace>[] = [];
91
- document.fonts.forEach((face) => loads.push(face.load()));
92
- await Promise.all(loads);
96
+ const unreadable = await page.evaluate(async () => {
97
+ const faces: FontFace[] = [];
98
+ document.fonts.forEach((face) => faces.push(face));
99
+ const loads = await Promise.allSettled(faces.map((face) => face.load()));
93
100
  await document.fonts.ready;
101
+ return faces.filter((_, i) => loads[i]?.status === "rejected").map((face) => `"${face.family.replace(/^["']|["']$/g, "")}" ${face.unicodeRange}`);
94
102
  });
103
+ if (unreadable.length) {
104
+ await page.close();
105
+ throw new Error(FONT_TEXT[lang](unreadable));
106
+ }
95
107
  return { page, width, height };
96
108
  }
97
109
 
@@ -4,6 +4,9 @@
4
4
  * 同梱した字の package は、字の範囲ごとに分けた file (woff2) と、file ごとの範囲の表 (`unicode.json`) を持つ。
5
5
  * 描く字が入る file だけを、描く字だけに削り、`data:` で埋めた `@font-face` にする。
6
6
  * 太さの軸は、値の表 (`TYPE`) が使う太さの間に縮める。
7
+ *
8
+ * 形を 1 つも持たない字の file を Chromium は読まない。空白の類だけを描く file には、
9
+ * 同じ file の形のある字を 1 つ足して削る。足した字は `unicode-range` に載せないので描かれない (#3212)。
7
10
  */
8
11
  import { readFileSync } from "node:fs";
9
12
  import { readFile } from "node:fs/promises";
@@ -39,6 +42,20 @@ function ranges(list: string): [number, number][] {
39
42
 
40
43
  const hex = (code: number): string => `U+${code.toString(16).toUpperCase()}`;
41
44
 
45
+ /** 形を持たない字 (空白の類、書式の字、制御の字) か */
46
+ const shapeless = (char: string): boolean => /^[\s\p{Cf}\p{Cc}]$/u.test(char);
47
+
48
+ /** 範囲の中で最初の、形を持つ字。空白の類だけを描く file を読める形にするために足す */
49
+ function shapedIn(span: [number, number][]): string | undefined {
50
+ for (const [from, to] of span) {
51
+ for (let code = from; code <= to; code++) {
52
+ const char = String.fromCodePoint(code);
53
+ if (!shapeless(char)) return char;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
58
+
42
59
  /** 字を空白ごと集める。改行は字の file に要らない */
43
60
  export function charsOf(texts: string[]): string[] {
44
61
  return [...new Set([...texts.join("")])].filter((char) => char !== "\n" && char !== "\r" && char !== "\t").sort();
@@ -57,8 +74,9 @@ export async function fontFaces(chars: string[]): Promise<string> {
57
74
  return span.some(([from, to]) => code >= from && code <= to);
58
75
  });
59
76
  if (!own.length) return "";
77
+ const filler = own.every(shapeless) ? (shapedIn(span) ?? "") : "";
60
78
  const file = join(base, "files", `${name}-${key.replace(/[[\]]/g, "")}-wght-normal.woff2`);
61
- const woff2 = await subsetFont(await readFile(file), own.join(""), { targetFormat: "woff2", variationAxes: { wght: WEIGHT } });
79
+ const woff2 = await subsetFont(await readFile(file), own.join("") + filler, { targetFormat: "woff2", variationAxes: { wght: WEIGHT } });
62
80
  const unicode = own.map((char) => hex(char.codePointAt(0) ?? 0)).join(",");
63
81
  return `@font-face{font-family:"${family}";font-style:normal;font-display:block;font-weight:${WEIGHT.min} ${WEIGHT.max};src:url(data:font/woff2;base64,${woff2.toString("base64")}) format("woff2");unicode-range:${unicode}}`;
64
82
  });
@@ -100,13 +100,13 @@ export async function exportDiagram(input: unknown, options: ExportOptions): Pro
100
100
  const browser = await launch(lang);
101
101
  try {
102
102
  if (formats.includes("png")) {
103
- const fixed = await stage(browser, rendered.svg, fontCss, "");
103
+ const fixed = await stage(browser, rendered.svg, fontCss, "", lang);
104
104
  outputs.push(["png", await still(fixed, timeline.stills[timeline.stills.length - 1] ?? 0)]);
105
105
  }
106
106
  if (mp4 || gif) {
107
107
  const fps = mp4 ? (options.fps ?? DEFAULTS.fps) : (options.gifFps ?? DEFAULTS.gifFps);
108
108
  const gifEvery = gif ? Math.max(1, Math.round(fps / (options.gifFps ?? DEFAULTS.gifFps))) : 0;
109
- const shot = await film(await stage(browser, videoSvg, fontCss, `${vars};background:var(--bg)`), {
109
+ const shot = await film(await stage(browser, videoSvg, fontCss, `${vars};background:var(--bg)`, lang), {
110
110
  total: timeline.total,
111
111
  fps,
112
112
  mp4,
package/src/index.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * 図の原本は JSON で、人は行の頭の英語の語で行の種類を決める dragon記法で書く。記法と JSON は行き来でき、
5
5
  * JSON は JSON Schema 1 本で検査する。原本から図を描き、頁に置いて段ごとに動かす。
6
- * 頁に字を読み込むのは別の入口 `@cardenelabs/dragon/fonts`。
6
+ * 頁に字を読み込むのは別の入口 `@cardenelabs/dragon/fonts`、原本の file を移すのは Node でだけ動く入口 `@cardenelabs/dragon/node`。
7
+ * この入口は頁を束ねる道具が読むため、Node の組み込みの module を読む部品を置かない (#3206)。
7
8
  */
8
9
  export { extractDiagrams, type Fence } from "./markdown";
9
10
  export { type LineError, type ParseOptions, type Parsed, parseNotation } from "./parser";
@@ -27,7 +28,7 @@ export {
27
28
  validateDiagram,
28
29
  type ViewMode,
29
30
  } from "./schema";
30
- export { FORMAT_VERSION, type Migrated, migrateFile, type Read, readDiagram } from "./version";
31
+ export { FORMAT_VERSION, type Read, readDiagram } from "./version";
31
32
  export type {
32
33
  Layout,
33
34
  Point,
package/src/node.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Node でだけ動く部品の入口 (#3206)。
3
+ *
4
+ * 原本の file を読み書きする部品は、頁で描く入口 (`index.ts`) に置かない。
5
+ * 頁を束ねる道具 (Next.js の Turbopack など) は、呼ぶかどうかに関わらず入口の file の読み込みを全て解くため、
6
+ * 頁の入口に Node の組み込みの module を読む部品が 1 つでも在ると、ブラウザ向けの build が止まる。
7
+ */
8
+ import { readFile } from "node:fs/promises";
9
+ import { FORMAT_VERSION, readDiagram } from "./version";
10
+
11
+ export interface Migrated {
12
+ changed: boolean;
13
+ from: number;
14
+ to: number;
15
+ }
16
+
17
+ /** 原本の file を今の版へ移す。今の版の file には触れない。 */
18
+ export async function migrateFile(path: string): Promise<Migrated> {
19
+ const input: unknown = JSON.parse(await readFile(path, "utf8"));
20
+ const read = readDiagram(input);
21
+ if (!read.ok) throw new Error(`${path} を移せない: ${read.errors.map((error) => `${error.pointer} ${error.message}`).join(" / ")}`);
22
+ return { changed: false, from: read.diagram.version, to: FORMAT_VERSION };
23
+ }
package/src/version.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * 原本の形式の版。
3
3
  *
4
4
  * 道具より新しい版の図は描かずに断る。古い版の図は、版を 1 つずつ上げる変換を通して読み、
5
- * 原本の file を書き換えるのは移行の命令 (`migrateFile`) だけにする。
5
+ * 原本の file を書き換えるのは移行の命令 (`migrateFile`、Node でだけ動く入口 `node.ts`) だけにする。
6
6
  * 今は版 1 しか無いため、版を上げる変換はまだ持たない。版 2 を作る時に、版 1 から 2 への変換と
7
7
  * 古い版を読んだ時の警告をここに足す。
8
8
  */
@@ -15,12 +15,6 @@ export const FORMAT_VERSION = 1;
15
15
 
16
16
  export type Read = { ok: true; diagram: Diagram; warnings: string[] } | { ok: false; errors: FieldError[] };
17
17
 
18
- export interface Migrated {
19
- changed: boolean;
20
- from: number;
21
- to: number;
22
- }
23
-
24
18
  function newerThanTool(input: unknown): number | undefined {
25
19
  if (typeof input !== "object" || input === null) return undefined;
26
20
  const version = (input as { version?: unknown }).version;
@@ -40,16 +34,3 @@ export function readDiagram(input: unknown, options: CheckOptions = {}): Read {
40
34
  if (!checked.ok) return checked;
41
35
  return { ok: true, diagram: input as Diagram, warnings: [] };
42
36
  }
43
-
44
- /**
45
- * 原本の file を今の版へ移す。今の版の file には触れない。
46
- *
47
- * file を読むので、画面で描く入口からは呼ばない。node の file の命令は呼んだ時に初めて読み込む。
48
- */
49
- export async function migrateFile(path: string): Promise<Migrated> {
50
- const { readFile } = await import("node:fs/promises");
51
- const input: unknown = JSON.parse(await readFile(path, "utf8"));
52
- const read = readDiagram(input);
53
- if (!read.ok) throw new Error(`${path} を移せない: ${read.errors.map((error) => `${error.pointer} ${error.message}`).join(" / ")}`);
54
- return { changed: false, from: read.diagram.version, to: FORMAT_VERSION };
55
- }