@biunow/agent-biutalk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/bin/server.js +355 -0
  2. package/engine/AGENTS.md +1414 -0
  3. package/engine/CLAUDE.md +1 -0
  4. package/engine/LICENSE +21 -0
  5. package/engine/README.md +216 -0
  6. package/engine/bin/explainroo.js +19 -0
  7. package/engine/dev/audio-lab.mjs +268 -0
  8. package/engine/docs/media/contact-sheet.jpg +0 -0
  9. package/engine/docs/media/dns-poster.jpg +0 -0
  10. package/engine/docs/media/intro-poster.jpg +0 -0
  11. package/engine/docs/media/logo-dark.png +0 -0
  12. package/engine/docs/media/logo-light.png +0 -0
  13. package/engine/docs/media/looks-dark.webp +0 -0
  14. package/engine/docs/media/looks-light.webp +0 -0
  15. package/engine/docs/media/product-demo.webp +0 -0
  16. package/engine/docs/media/rebase-poster.jpg +0 -0
  17. package/engine/docs/media/sizes-dark.webp +0 -0
  18. package/engine/docs/media/sizes-light.webp +0 -0
  19. package/engine/engine/audio/dsp.js +69 -0
  20. package/engine/engine/audio/instruments.js +147 -0
  21. package/engine/engine/audio/music.js +576 -0
  22. package/engine/engine/audio/pcm.js +93 -0
  23. package/engine/engine/audio/rng.js +40 -0
  24. package/engine/engine/audio/sfx.js +287 -0
  25. package/engine/engine/audio/soundtrack.js +201 -0
  26. package/engine/engine/audio/synth.js +721 -0
  27. package/engine/engine/audio/theory.js +105 -0
  28. package/engine/engine/audio/wav.js +47 -0
  29. package/engine/engine/captions.js +131 -0
  30. package/engine/engine/clips.js +107 -0
  31. package/engine/engine/code.js +179 -0
  32. package/engine/engine/director.js +475 -0
  33. package/engine/engine/frame.html +135 -0
  34. package/engine/engine/icons/LICENSE-lucide.txt +43 -0
  35. package/engine/engine/icons/lucide-tags.json +1 -0
  36. package/engine/engine/icons/lucide.json +1 -0
  37. package/engine/engine/layout.js +69 -0
  38. package/engine/engine/pathdata.js +234 -0
  39. package/engine/engine/pen.js +240 -0
  40. package/engine/engine/player.html +67 -0
  41. package/engine/engine/player.js +219 -0
  42. package/engine/engine/readability.js +9 -0
  43. package/engine/engine/runtime.js +690 -0
  44. package/engine/engine/stage.js +2247 -0
  45. package/engine/engine/studio.html +216 -0
  46. package/engine/engine/text.js +81 -0
  47. package/engine/engine/themes.js +360 -0
  48. package/engine/engine/transitions.js +161 -0
  49. package/engine/engine/ui.js +1042 -0
  50. package/engine/engine/upload.js +32 -0
  51. package/engine/engine/util.js +204 -0
  52. package/engine/examples/callbacks-to-async-await/code-versions.js +34 -0
  53. package/engine/examples/callbacks-to-async-await/scenes.js +106 -0
  54. package/engine/examples/callbacks-to-async-await/script.md +22 -0
  55. package/engine/examples/callbacks-to-async-await/video.json +16 -0
  56. package/engine/examples/circle-area/scenes.js +228 -0
  57. package/engine/examples/circle-area/script.md +37 -0
  58. package/engine/examples/circle-area/video.json +14 -0
  59. package/engine/examples/explainroo-intro/scenes.js +133 -0
  60. package/engine/examples/explainroo-intro/script.md +27 -0
  61. package/engine/examples/explainroo-intro/video.json +8 -0
  62. package/engine/examples/how-dns-works/scenes.js +130 -0
  63. package/engine/examples/how-dns-works/script.md +28 -0
  64. package/engine/examples/how-dns-works/video.json +8 -0
  65. package/engine/examples/leap-years/scenes.js +156 -0
  66. package/engine/examples/leap-years/script.md +25 -0
  67. package/engine/examples/leap-years/video.json +16 -0
  68. package/engine/examples/leap-years-ja/scenes.js +194 -0
  69. package/engine/examples/leap-years-ja/script.md +32 -0
  70. package/engine/examples/leap-years-ja/video.json +17 -0
  71. package/engine/examples/merge-vs-rebase/scenes.js +129 -0
  72. package/engine/examples/merge-vs-rebase/script.md +22 -0
  73. package/engine/examples/merge-vs-rebase/video.json +8 -0
  74. package/engine/examples/password-storage-zh/scenes.js +185 -0
  75. package/engine/examples/password-storage-zh/script.md +25 -0
  76. package/engine/examples/password-storage-zh/video.json +19 -0
  77. package/engine/examples/sqlite-demo/README.md +19 -0
  78. package/engine/examples/sqlite-demo/scenes.js +423 -0
  79. package/engine/examples/sqlite-demo/script.md +35 -0
  80. package/engine/examples/sqlite-demo/video.json +17 -0
  81. package/engine/examples/unspar-demo/assets/fonts/Figtree-400.woff2 +0 -0
  82. package/engine/examples/unspar-demo/assets/fonts/Figtree-500.woff2 +0 -0
  83. package/engine/examples/unspar-demo/assets/fonts/Figtree-600.woff2 +0 -0
  84. package/engine/examples/unspar-demo/assets/fonts/Figtree-700.woff2 +0 -0
  85. package/engine/examples/unspar-demo/assets/fonts/Figtree-OFL.txt +93 -0
  86. package/engine/examples/unspar-demo/assets/unspar-logo.svg +23 -0
  87. package/engine/examples/unspar-demo/scenes.js +367 -0
  88. package/engine/examples/unspar-demo/script.md +25 -0
  89. package/engine/examples/unspar-demo/video.json +21 -0
  90. package/engine/examples/why-is-the-sky-blue-es/scenes.js +160 -0
  91. package/engine/examples/why-is-the-sky-blue-es/script.md +22 -0
  92. package/engine/examples/why-is-the-sky-blue-es/video.json +15 -0
  93. package/engine/fonts/ArchitectsDaughter-400-latin-ext.woff2 +0 -0
  94. package/engine/fonts/ArchitectsDaughter-400-latin.woff2 +0 -0
  95. package/engine/fonts/CabinSketch-400-latin.woff2 +0 -0
  96. package/engine/fonts/CabinSketch-700-latin.woff2 +0 -0
  97. package/engine/fonts/InstrumentSerif-400-italic-latin-ext.woff2 +0 -0
  98. package/engine/fonts/InstrumentSerif-400-italic-latin.woff2 +0 -0
  99. package/engine/fonts/InstrumentSerif-400-normal-latin-ext.woff2 +0 -0
  100. package/engine/fonts/InstrumentSerif-400-normal-latin.woff2 +0 -0
  101. package/engine/fonts/Inter-400-latin-ext.woff2 +0 -0
  102. package/engine/fonts/Inter-400-latin.woff2 +0 -0
  103. package/engine/fonts/JetBrainsMono-400-latin-ext.woff2 +0 -0
  104. package/engine/fonts/JetBrainsMono-400-latin.woff2 +0 -0
  105. package/engine/fonts/Kalam-400-latin-ext.woff2 +0 -0
  106. package/engine/fonts/Kalam-400-latin.woff2 +0 -0
  107. package/engine/fonts/Kalam-700-latin-ext.woff2 +0 -0
  108. package/engine/fonts/Kalam-700-latin.woff2 +0 -0
  109. package/engine/fonts/NotoSansDevanagari-400.ttf +0 -0
  110. package/engine/fonts/NotoSansDevanagari-700.ttf +0 -0
  111. package/engine/fonts/PatrickHand-400-latin-ext.woff2 +0 -0
  112. package/engine/fonts/PatrickHand-400-latin.woff2 +0 -0
  113. package/engine/fonts/PlusJakartaSans-600-latin-ext.woff2 +0 -0
  114. package/engine/fonts/PlusJakartaSans-600-latin.woff2 +0 -0
  115. package/engine/fonts/SpaceGrotesk-500-latin-ext.woff2 +0 -0
  116. package/engine/fonts/SpaceGrotesk-500-latin.woff2 +0 -0
  117. package/engine/fonts/fonts.json +216 -0
  118. package/engine/fonts/licenses/ArchitectsDaughter-OFL.txt +93 -0
  119. package/engine/fonts/licenses/CabinSketch-OFL.txt +93 -0
  120. package/engine/fonts/licenses/InstrumentSerif-OFL.txt +93 -0
  121. package/engine/fonts/licenses/Inter-OFL.txt +93 -0
  122. package/engine/fonts/licenses/JetBrainsMono-OFL.txt +93 -0
  123. package/engine/fonts/licenses/Kalam-OFL.txt +93 -0
  124. package/engine/fonts/licenses/NotoSansDevanagari-OFL.txt +118 -0
  125. package/engine/fonts/licenses/PatrickHand-OFL.txt +93 -0
  126. package/engine/fonts/licenses/PlusJakartaSans-OFL.txt +93 -0
  127. package/engine/fonts/licenses/SpaceGrotesk-OFL.txt +93 -0
  128. package/engine/package-lock.json +1201 -0
  129. package/engine/package.json +67 -0
  130. package/engine/scripts/build-icons.mjs +74 -0
  131. package/engine/scripts/fetch-fonts.mjs +68 -0
  132. package/engine/skills/explainroo/SKILL.md +51 -0
  133. package/engine/src/align.js +357 -0
  134. package/engine/src/browser.js +121 -0
  135. package/engine/src/capture.js +315 -0
  136. package/engine/src/chapters.js +32 -0
  137. package/engine/src/cli.js +421 -0
  138. package/engine/src/clips.js +19 -0
  139. package/engine/src/elevenlabs.js +90 -0
  140. package/engine/src/env.js +16 -0
  141. package/engine/src/export.js +187 -0
  142. package/engine/src/ffmpeg.js +103 -0
  143. package/engine/src/fonts.js +86 -0
  144. package/engine/src/g2p.py +76 -0
  145. package/engine/src/images.js +151 -0
  146. package/engine/src/licenses/misaki-Apache-2.0.txt +201 -0
  147. package/engine/src/math.js +83 -0
  148. package/engine/src/models.js +161 -0
  149. package/engine/src/phonemes.js +162 -0
  150. package/engine/src/pipeline.js +63 -0
  151. package/engine/src/project.js +331 -0
  152. package/engine/src/qa.js +186 -0
  153. package/engine/src/recordings.js +89 -0
  154. package/engine/src/render.js +156 -0
  155. package/engine/src/script.js +266 -0
  156. package/engine/src/server.js +288 -0
  157. package/engine/src/subtitles.js +78 -0
  158. package/engine/src/timeline.js +55 -0
  159. package/engine/src/voice.js +240 -0
  160. package/engine/src/wav.js +98 -0
  161. package/engine/templates/starter/scenes.js +31 -0
  162. package/engine/templates/starter/script.md +14 -0
  163. package/engine/test/align.test.js +108 -0
  164. package/engine/test/brand.test.js +41 -0
  165. package/engine/test/browser.test.js +89 -0
  166. package/engine/test/camera-browser.test.js +225 -0
  167. package/engine/test/caption-phrases.test.js +35 -0
  168. package/engine/test/capture-browser.test.js +90 -0
  169. package/engine/test/capture-fixture.js +46 -0
  170. package/engine/test/capture.test.js +62 -0
  171. package/engine/test/chapters.test.js +41 -0
  172. package/engine/test/cjk-browser.test.js +101 -0
  173. package/engine/test/cjk.test.js +232 -0
  174. package/engine/test/cli-exit.test.js +25 -0
  175. package/engine/test/cli.test.js +116 -0
  176. package/engine/test/clips-browser.test.js +125 -0
  177. package/engine/test/clips.test.js +67 -0
  178. package/engine/test/code-morph-browser.test.js +99 -0
  179. package/engine/test/code-morph.test.js +110 -0
  180. package/engine/test/contrast-browser.test.js +63 -0
  181. package/engine/test/contrast.test.js +80 -0
  182. package/engine/test/director.test.js +316 -0
  183. package/engine/test/engine-pure.test.js +29 -0
  184. package/engine/test/export-browser.test.js +224 -0
  185. package/engine/test/export.test.js +96 -0
  186. package/engine/test/fixtures/capture.html +55 -0
  187. package/engine/test/formats-pace.test.js +104 -0
  188. package/engine/test/languages-browser.test.js +78 -0
  189. package/engine/test/languages.test.js +140 -0
  190. package/engine/test/looks-browser.test.js +109 -0
  191. package/engine/test/looks-preview.test.js +57 -0
  192. package/engine/test/looks.test.js +130 -0
  193. package/engine/test/math-browser.test.js +114 -0
  194. package/engine/test/math.test.js +54 -0
  195. package/engine/test/multi-size-browser.test.js +133 -0
  196. package/engine/test/multi-size.test.js +116 -0
  197. package/engine/test/phonemes.test.js +92 -0
  198. package/engine/test/readability-browser.test.js +36 -0
  199. package/engine/test/readability.test.js +20 -0
  200. package/engine/test/render-options.test.js +52 -0
  201. package/engine/test/script.test.js +67 -0
  202. package/engine/test/server.test.js +256 -0
  203. package/engine/test/stills-browser.test.js +70 -0
  204. package/engine/test/subtitles.test.js +83 -0
  205. package/engine/test/timeline.test.js +31 -0
  206. package/engine/test/transparent-browser.test.js +123 -0
  207. package/engine/test/ui-kit.test.js +96 -0
  208. package/engine/test/upload-browser.test.js +55 -0
  209. package/engine/test/voice-providers.test.js +338 -0
  210. package/lib/host.mjs +480 -0
  211. package/manifest.json +54 -0
  212. package/package.json +8 -4
  213. package/skills/biutalk/SKILL.md +21 -0
  214. package/studio/app.js +209 -0
  215. package/studio/assert-panel-permit.mjs +67 -0
  216. package/studio/composer.css +354 -0
  217. package/studio/composer.js +169 -0
  218. package/studio/index.html +82 -0
  219. package/studio/looks/blueprint.svg +21 -0
  220. package/studio/looks/chalk.svg +15 -0
  221. package/studio/looks/clean.svg +20 -0
  222. package/studio/looks/editorial.svg +18 -0
  223. package/studio/looks/midnight.svg +17 -0
  224. package/studio/looks/paper.svg +11 -0
  225. package/studio/select-menu.js +268 -0
  226. package/studio/styles.css +4 -0
  227. package/README.md +0 -3
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,83 @@
1
+ // Typesets locally in Node. The page gets paths, not fonts or SVG references.
2
+ import fs from 'node:fs';
3
+ import crypto from 'node:crypto';
4
+ import path from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { absolutize, parsePath, serialize } from '../engine/pathdata.js';
7
+
8
+ export const MAX_TEX_LENGTH = 4096;
9
+ let ready;
10
+
11
+ export function mathHash(tex, display = true) {
12
+ return crypto.createHash('sha256').update(JSON.stringify(['mathjax-4.1.3-1', tex, display])).digest('hex');
13
+ }
14
+
15
+ export async function typesetMath(tex, display = true, cacheFile = null) {
16
+ if (typeof tex !== 'string' || tex.length > MAX_TEX_LENGTH) throw new Error(`math: use a TeX string of at most ${MAX_TEX_LENGTH} characters`);
17
+ if (typeof display !== 'boolean') throw new Error('math: display must be true or false');
18
+ if (cacheFile && fs.existsSync(cacheFile)) return JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
19
+ ready ??= import('mathjax').then(({ default: mj }) => mj.init({
20
+ // MathJax imports its parts by file path. On Windows a bare path like
21
+ // D:\\... is not a valid import specifier, so hand it a file URL.
22
+ loader: {
23
+ load: ['input/tex', 'output/svg'],
24
+ require: (file) => import(path.isAbsolute(file) ? pathToFileURL(file).href : file),
25
+ failed: (error) => { throw error; },
26
+ },
27
+ tex: {
28
+ packages: { '[-]': ['autoload', 'require', 'noundefined'] },
29
+ formatError: (_jax, error) => { throw new Error(error.message); },
30
+ },
31
+ svg: { fontCache: 'none' },
32
+ }));
33
+ const mj = await ready;
34
+ if (!mj?.startup) throw new Error('math: MathJax could not start. Run npm install in the explainroo folder.');
35
+ // Each formula has its own macros and equation counters, whatever the order.
36
+ const doc = mj.startup.mathjax.document('', { InputJax: mj.startup.getInputJax(), OutputJax: mj.startup.getOutputJax() });
37
+ const node = await doc.convertPromise(tex, { display });
38
+ const a = mj.startup.adaptor;
39
+ const svg = a.firstChild(node);
40
+ const viewBox = a.getAttribute(svg, 'viewBox').split(/\s+/).map(Number);
41
+ const paths = [];
42
+ const walk = (node, matrix) => {
43
+ matrix = svgTransform(matrix, a.getAttribute(node, 'transform') || '');
44
+ const kind = a.kind(node);
45
+ let d = kind === 'path' ? a.getAttribute(node, 'd') : null;
46
+ if (kind === 'rect') {
47
+ const x = Number(a.getAttribute(node, 'x') || 0);
48
+ const y = Number(a.getAttribute(node, 'y') || 0);
49
+ const w = Number(a.getAttribute(node, 'width'));
50
+ const h = Number(a.getAttribute(node, 'height'));
51
+ d = `M${x} ${y}h${w}v${h}h${-w}Z`;
52
+ }
53
+ if (kind === 'text' || kind === 'use') throw new Error('math: this character has no glyph path; use TeX symbols');
54
+ if (d) paths.push(serialize(absolutize(parsePath(d)).map(({ c, v }) => {
55
+ if (c === 'A') throw new Error('math: this glyph has an unsupported arc');
56
+ const points = [];
57
+ for (let i = 0; i < v.length; i += 2) points.push(matrix[0] * v[i] + matrix[2] * v[i + 1] + matrix[4], matrix[1] * v[i] + matrix[3] * v[i + 1] + matrix[5]);
58
+ return { c, v: points };
59
+ })));
60
+ for (const child of a.childNodes(node)) if (!a.kind(child).startsWith('#')) walk(child, matrix);
61
+ };
62
+ walk(svg, [1, 0, 0, 1, 0, 0]);
63
+ const result = { paths, viewBox, unitsPerEm: 1000, ascent: -viewBox[1], descent: viewBox[1] + viewBox[3] };
64
+ if (cacheFile) fs.writeFileSync(cacheFile, JSON.stringify(result));
65
+ return result;
66
+ }
67
+
68
+ function multiply(a, b) {
69
+ return [a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1], a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3], a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]];
70
+ }
71
+
72
+ function svgTransform(matrix, source) {
73
+ for (const [, name, args] of source.matchAll(/(\w+)\(([^)]*)\)/g)) {
74
+ const n = args.trim().split(/[\s,]+/).map(Number);
75
+ let m;
76
+ if (name === 'translate') m = [1, 0, 0, 1, n[0], n[1] ?? 0];
77
+ else if (name === 'scale') m = [n[0], 0, 0, n[1] ?? n[0], 0, 0];
78
+ else if (name === 'matrix') m = n;
79
+ else throw new Error(`math: unsupported SVG transform "${name}"`);
80
+ matrix = multiply(matrix, m);
81
+ }
82
+ return matrix;
83
+ }
@@ -0,0 +1,161 @@
1
+ // Local speech models: Kokoro for the voice, Whisper for word timing and checks.
2
+ // Both run on the CPU through ONNX Runtime and are downloaded from Hugging Face
3
+ // on first use into ~/.cache/explainroo/models (or $EXPLAINROO_CACHE/models).
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ export const TTS_MODEL = 'onnx-community/Kokoro-82M-v1.0-ONNX';
8
+ export const ASR_MODEL = 'onnx-community/whisper-base.en_timestamped';
9
+ export const MULTILINGUAL_ASR_MODEL = 'onnx-community/whisper-small_timestamped';
10
+ export const TTS_SAMPLE_RATE = 24000;
11
+
12
+ export const LANGUAGES = {
13
+ en: 'af_heart', es: 'ef_dora', fr: 'ff_siwis', it: 'if_sara', 'pt-br': 'pf_dora', hi: 'hf_alpha', ja: 'jf_alpha', zh: 'zf_xiaobei',
14
+ };
15
+
16
+ export function voiceLanguage(id) {
17
+ return { a: 'en', b: 'en', e: 'es', f: 'fr', i: 'it', p: 'pt-br', h: 'hi', j: 'ja', z: 'zh' }[id[0]];
18
+ }
19
+
20
+ export function asrModel(language = 'en') {
21
+ return language === 'en' ? ASR_MODEL : MULTILINGUAL_ASR_MODEL;
22
+ }
23
+
24
+ export function cacheRoot() {
25
+ return process.env.EXPLAINROO_CACHE || path.join(os.homedir(), '.cache', 'explainroo');
26
+ }
27
+
28
+ export function ttsDtype() {
29
+ const d = process.env.EXPLAINROO_TTS_DTYPE || 'fp32';
30
+ if (!['fp32', 'fp16', 'q8', 'q4', 'q4f16'].includes(d)) throw new Error(`EXPLAINROO_TTS_DTYPE must be fp32, fp16, q8, q4 or q4f16, not "${d}"`);
31
+ return d;
32
+ }
33
+
34
+ let transformers = null;
35
+ async function lib() {
36
+ if (!transformers) {
37
+ transformers = await import('@huggingface/transformers');
38
+ transformers.env.cacheDir = path.join(cacheRoot(), 'models');
39
+ transformers.env.allowRemoteModels = process.env.EXPLAINROO_OFFLINE !== '1';
40
+ }
41
+ return transformers;
42
+ }
43
+
44
+ function progressLogger(label, log) {
45
+ if (!log) return undefined;
46
+ const files = new Map();
47
+ let last = 0;
48
+ return (p) => {
49
+ if (p.status === 'progress' && p.total > 5e6 && p.loaded < p.total) {
50
+ files.set(p.file, { loaded: p.loaded, total: p.total });
51
+ const now = Date.now();
52
+ if (now - last < 1500) return;
53
+ last = now;
54
+ let loaded = 0;
55
+ let total = 0;
56
+ for (const f of files.values()) { loaded += f.loaded; total += f.total; }
57
+ log(`downloading ${label}: ${(loaded / 1e6).toFixed(0)} / ${(total / 1e6).toFixed(0)} MB`);
58
+ }
59
+ };
60
+ }
61
+
62
+ let ttsPromise = null;
63
+ export function loadTTS({ log } = {}) {
64
+ if (!ttsPromise) {
65
+ ttsPromise = (async () => {
66
+ await lib();
67
+ const { KokoroTTS } = await import('kokoro-js');
68
+ return KokoroTTS.from_pretrained(TTS_MODEL, {
69
+ dtype: ttsDtype(),
70
+ device: 'cpu',
71
+ progress_callback: progressLogger('voice model', log),
72
+ });
73
+ })();
74
+ }
75
+ return ttsPromise;
76
+ }
77
+
78
+ const asrPromises = new Map();
79
+ export function loadASR({ log, language = 'en' } = {}) {
80
+ const model = asrModel(language);
81
+ if (!asrPromises.has(model)) {
82
+ asrPromises.set(model, (async () => {
83
+ const { pipeline } = await lib();
84
+ return pipeline('automatic-speech-recognition', model, {
85
+ dtype: 'q8',
86
+ progress_callback: progressLogger('speech check model', log),
87
+ });
88
+ })());
89
+ }
90
+ return asrPromises.get(model);
91
+ }
92
+
93
+ // samples: Float32Array at 16 kHz. Returns [{ text, start, end }].
94
+ export async function transcribeWords(samples, { log, language = 'en' } = {}) {
95
+ const asr = await loadASR({ log, language });
96
+ const r = await asr(samples, { return_timestamps: 'word', chunk_length_s: 30, stride_length_s: 5,
97
+ ...(language === 'en' ? {} : { language: language === 'pt-br' ? 'pt' : language, task: 'transcribe' }),
98
+ });
99
+ return {
100
+ text: (r.text || '').trim(),
101
+ words: (r.chunks || []).map((c) => ({ text: c.text.trim(), start: c.timestamp[0] ?? 0, end: c.timestamp[1] ?? c.timestamp[0] ?? 0 })),
102
+ };
103
+ }
104
+
105
+ // Kokoro v1.0 voices for the supported languages.
106
+ export const VOICES = {
107
+ af_heart: 'American English, female (default)',
108
+ af_bella: 'American English, female',
109
+ af_nicole: 'American English, female',
110
+ af_aoede: 'American English, female',
111
+ af_kore: 'American English, female',
112
+ af_sarah: 'American English, female',
113
+ af_nova: 'American English, female',
114
+ af_sky: 'American English, female',
115
+ af_alloy: 'American English, female',
116
+ af_jessica: 'American English, female',
117
+ af_river: 'American English, female',
118
+ am_michael: 'American English, male',
119
+ am_fenrir: 'American English, male',
120
+ am_puck: 'American English, male',
121
+ am_echo: 'American English, male',
122
+ am_eric: 'American English, male',
123
+ am_liam: 'American English, male',
124
+ am_onyx: 'American English, male',
125
+ am_adam: 'American English, male',
126
+ am_santa: 'American English, male',
127
+ bf_emma: 'British English, female',
128
+ bf_isabella: 'British English, female',
129
+ bf_alice: 'British English, female',
130
+ bf_lily: 'British English, female',
131
+ bm_george: 'British English, male',
132
+ bm_fable: 'British English, male',
133
+ bm_lewis: 'British English, male',
134
+ bm_daniel: 'British English, male',
135
+ ef_dora: 'Spanish, female (default)',
136
+ em_alex: 'Spanish, male',
137
+ em_santa: 'Spanish, male',
138
+ ff_siwis: 'French, female (default)',
139
+ if_sara: 'Italian, female (default)',
140
+ im_nicola: 'Italian, male',
141
+ pf_dora: 'Brazilian Portuguese, female (default)',
142
+ pm_alex: 'Brazilian Portuguese, male',
143
+ pm_santa: 'Brazilian Portuguese, male',
144
+ hf_alpha: 'Hindi, female (default)',
145
+ hf_beta: 'Hindi, female',
146
+ hm_omega: 'Hindi, male',
147
+ hm_psi: 'Hindi, male',
148
+ jf_alpha: 'Japanese, female (default)',
149
+ jf_gongitsune: 'Japanese, female',
150
+ jf_nezumi: 'Japanese, female',
151
+ jf_tebukuro: 'Japanese, female',
152
+ jm_kumo: 'Japanese, male',
153
+ zf_xiaobei: 'Mandarin Chinese, female (default)',
154
+ zf_xiaoni: 'Mandarin Chinese, female',
155
+ zf_xiaoxiao: 'Mandarin Chinese, female',
156
+ zf_xiaoyi: 'Mandarin Chinese, female',
157
+ zm_yunjian: 'Mandarin Chinese, male',
158
+ zm_yunxi: 'Mandarin Chinese, male',
159
+ zm_yunxia: 'Mandarin Chinese, male',
160
+ zm_yunyang: 'Mandarin Chinese, male',
161
+ };
@@ -0,0 +1,162 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const ESPEAK_LANGUAGES = { es: 'es', fr: 'fr-fr', it: 'it', 'pt-br': 'pt-br', hi: 'hi' };
5
+ // Adapted from misaki's EspeakG2P (Apache-2.0, see licenses/).
6
+ // https://github.com/hexgrad/misaki/blob/main/misaki/espeak.py
7
+ // Kokoro v1.0 keeps nasal vowels, unlike misaki's v2.0 mapping.
8
+ const E2M = {
9
+ 'a^ɪ': 'I', 'a^ʊ': 'W', 'd^z': 'ʣ', 'd^ʒ': 'ʤ', 'e^ɪ': 'A',
10
+ 'o^ʊ': 'O', 'ə^ʊ': 'Q', 's^s': 'S', 't^s': 'ʦ', 't^ʃ': 'ʧ', 'ɔ^ɪ': 'Y',
11
+ };
12
+
13
+ export function mapPhonemes(ipa) {
14
+ let ps = ipa.trim();
15
+ for (const [old, replacement] of Object.entries(E2M).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) ps = ps.replaceAll(old, replacement);
16
+ return ps.replaceAll('^', '').replaceAll('-', '').replaceAll('«', '(').replaceAll('»', ')');
17
+ }
18
+
19
+ function binary() {
20
+ return process.env.EXPLAINROO_ESPEAK || 'espeak-ng';
21
+ }
22
+
23
+ const INSTALL = 'espeak-ng is needed for this language. Linux: sudo apt install espeak-ng. macOS: brew install espeak-ng. Windows: use the installer at https://github.com/espeak-ng/espeak-ng/releases. Or set EXPLAINROO_ESPEAK to its binary.';
24
+
25
+ export function espeakVersion() {
26
+ const r = spawnSync(binary(), ['--version'], { encoding: 'utf8', timeout: 5000 });
27
+ return !r.error && r.status === 0 ? r.stdout.trim().split('\n')[0] : null;
28
+ }
29
+
30
+ export async function phonemize(texts, language) {
31
+ if (['ja', 'zh'].includes(language)) return misakiPhonemes(texts, language);
32
+ const lang = ESPEAK_LANGUAGES[language];
33
+ if (!lang) throw new Error('espeak-ng supports es, fr, it, pt-br and hi here.');
34
+ const input = [];
35
+ const parts = texts.map(text => {
36
+ // Preserve punctuation outside espeak, as misaki's phonemizer backend does.
37
+ const prepared = text.replaceAll('«', '“').replaceAll('»', '”').replaceAll('(', '«').replaceAll(')', '»');
38
+ return prepared.split(/([;:,.!?¡¿—…"«»“”{}\[\]।]+|\s*\n\s*)/u).map((part, i) => {
39
+ if (i % 2 || !part.trim()) return { text: part };
40
+ const index = input.length;
41
+ input.push(part.trim());
42
+ return { index, before: /^\s*/.exec(part)[0], after: /\s*$/.exec(part)[0] };
43
+ });
44
+ });
45
+ if (!input.length) return parts.map(p => mapPhonemes(p.map(x => x.text).join('')));
46
+ const output = await new Promise((resolve, reject) => {
47
+ // Without --stdin, espeak processes each input line separately.
48
+ const child = spawn(binary(), ['-q', '-b', '1', '-v', lang, '--ipa=1', '--tie=^'], { stdio: ['pipe', 'pipe', 'pipe'] });
49
+ let stdout = '';
50
+ let stderr = '';
51
+ child.stdout.setEncoding('utf8').on('data', data => { stdout += data; });
52
+ child.stderr.setEncoding('utf8').on('data', data => { stderr += data; });
53
+ child.on('error', e => reject(new Error(['ENOENT', 'EACCES'].includes(e.code) ? INSTALL : 'espeak-ng could not start. Check EXPLAINROO_ESPEAK.')));
54
+ child.stdin.on('error', () => {});
55
+ child.on('close', code => {
56
+ if (code !== 0) return reject(new Error('espeak-ng could not read the text. Check its installation and EXPLAINROO_ESPEAK.'));
57
+ const lines = stdout.trimEnd().split(/\r?\n/);
58
+ if (lines.length !== input.length || lines.some(line => !line.trim()) || stderr.trim()) return reject(new Error('espeak-ng returned incomplete phonemes. Check its installation and EXPLAINROO_ESPEAK.'));
59
+ resolve(lines.map(line => line.replace(/\([a-z-]+\)/g, '').trim()));
60
+ });
61
+ child.stdin.end(input.join('\n') + '\n');
62
+ });
63
+ return parts.map(p => mapPhonemes(p.map(x => x.index === undefined ? x.text : x.before + output[x.index] + x.after).join('')));
64
+ }
65
+
66
+ export function generateSpeech(tts, text, { language = 'en', voice, speed, phonemes } = {}) {
67
+ if (language === 'en') return tts.generate(text, { voice, speed });
68
+ const { input_ids } = tts.tokenizer(phonemes, { truncation: true });
69
+ return tts.generate_from_ids(input_ids, { voice, speed });
70
+ }
71
+
72
+ function python() {
73
+ return process.env.EXPLAINROO_PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
74
+ }
75
+
76
+ function misakiInstall(language) {
77
+ return `Python with misaki is needed for ${language === 'ja' ? 'Japanese' : 'Chinese'}. Run: ${python()} -m pip install "misaki[${language}]".${language === 'ja' ? ` Then run: ${python()} -m unidic download.` : ''} Or set EXPLAINROO_PYTHON to a Python with these packages.`;
78
+ }
79
+
80
+ export function misakiAvailable(language) {
81
+ const r = spawnSync(python(), [fileURLToPath(new URL('./g2p.py', import.meta.url)), language], { input: JSON.stringify(language === 'ja' ? '日本語' : '中文') + '\n', encoding: 'utf8', timeout: 15000 });
82
+ if (r.error || r.status !== 0) return false;
83
+ try {
84
+ const phonemes = JSON.parse(r.stdout);
85
+ return typeof phonemes === 'string' && !!phonemes.trim();
86
+ } catch { return false; }
87
+ }
88
+
89
+ // misaki leaves Latin words like "API" or "JavaScript" as letters, which the
90
+ // Japanese and Chinese voices garble. They are read as English instead, with
91
+ // the espeak-ng build and fixes kokoro-js uses for English.
92
+ const LATIN = /[A-Za-z]+(?:['’][A-Za-z]+)*(?:[\s-]+[A-Za-z]+(?:['’][A-Za-z]+)*)*/g;
93
+
94
+ async function englishPhonemes(text) {
95
+ const { phonemize: espeakWasm } = await import('phonemizer');
96
+ return (await espeakWasm(text, 'en-us')).join(' ').replace(/ʲ/g, 'j').replace(/r/g, 'ɹ').replace(/x/g, 'k').replace(/ɬ/g, 'l').trim();
97
+ }
98
+
99
+ // misaki reads "365.2422" as 365, a pause and 2422. In Japanese the digits
100
+ // after the point are read one by one: 365点二四二二.
101
+ function japaneseDecimals(text) {
102
+ return text.replace(/(\d)\.(\d+)/g, (m, whole, digits) => whole + '点' + Array.from(digits, d => '〇一二三四五六七八九'[d]).join(''));
103
+ }
104
+
105
+ async function misakiPhonemes(texts, language) {
106
+ if (language === 'ja') texts = texts.map(japaneseDecimals);
107
+ const parts = texts.map(text => {
108
+ const list = [];
109
+ let last = 0;
110
+ for (const m of text.matchAll(LATIN)) {
111
+ if (m.index > last) list.push({ text: text.slice(last, m.index) });
112
+ list.push({ text: m[0], latin: true });
113
+ last = m.index + m[0].length;
114
+ }
115
+ if (last < text.length) list.push({ text: text.slice(last) });
116
+ return list;
117
+ });
118
+ const native = parts.flat().filter(p => !p.latin && p.text.trim());
119
+ const phonemes = await runMisaki(native.map(p => p.text), language, line => typeof line === 'string');
120
+ native.forEach((p, i) => { p.phonemes = phonemes[i]; });
121
+ for (const p of parts.flat()) if (p.latin) p.phonemes = await englishPhonemes(p.text);
122
+ return parts.map(list => {
123
+ const joined = list.map(p => p.phonemes?.trim()).filter(Boolean).join(' ');
124
+ if (!joined) throw new Error('misaki returned incomplete phonemes. Check its installation and EXPLAINROO_PYTHON.');
125
+ return joined;
126
+ });
127
+ }
128
+
129
+ // Katakana readings of Japanese text, from the dictionary misaki installs:
130
+ // [start, end, reading] for each word, counted in characters.
131
+ export function japaneseReadings(texts) {
132
+ return runMisaki(texts, 'ja-readings', line => Array.isArray(line) && line.every(t => Array.isArray(t) && t.length === 3));
133
+ }
134
+
135
+ async function runMisaki(texts, mode, valid) {
136
+ const language = mode.slice(0, 2);
137
+ if (!texts.length) return [];
138
+ return new Promise((resolve, reject) => {
139
+ const child = spawn(python(), [fileURLToPath(new URL('./g2p.py', import.meta.url)), mode], { stdio: ['pipe', 'pipe', 'pipe'] });
140
+ let stdout = '';
141
+ let stderr = '';
142
+ child.stdout.setEncoding('utf8').on('data', data => { stdout += data; });
143
+ child.stderr.setEncoding('utf8').on('data', data => { stderr += data; });
144
+ child.stdin.on('error', () => {});
145
+ child.on('error', () => reject(new Error(misakiInstall(language))));
146
+ child.on('close', code => {
147
+ if (code !== 0) {
148
+ const said = stderr.trim().split(/\r?\n/).at(-1);
149
+ return reject(new Error(misakiInstall(language) + (said ? ` Python said: ${said}` : '')));
150
+ }
151
+ try {
152
+ // misaki drops punctuation in Japanese, so a piece may come back empty.
153
+ const lines = stdout.trimEnd().split(/\r?\n/).map(line => JSON.parse(line));
154
+ if (lines.length !== texts.length || !lines.every(valid)) throw new Error();
155
+ resolve(lines);
156
+ } catch {
157
+ reject(new Error('misaki returned incomplete phonemes. Check its installation and EXPLAINROO_PYTHON.'));
158
+ }
159
+ });
160
+ child.stdin.end(texts.map(text => JSON.stringify(text)).join('\n') + '\n');
161
+ });
162
+ }
@@ -0,0 +1,63 @@
1
+ // Shared steps: voice + timeline, the page state the engine loads, and a
2
+ // session that runs the engine in headless Chrome.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import crypto from 'node:crypto';
6
+ import { ensureFonts } from './fonts.js';
7
+ import { synthesize } from './voice.js';
8
+ import { buildTimeline } from './timeline.js';
9
+ import { listAssets, loadProject } from './project.js';
10
+ import { startServer } from './server.js';
11
+ import { launch, openEngine } from './browser.js';
12
+
13
+ export async function prepare(project, { log = () => {}, force = false } = {}) {
14
+ await ensureFonts(project.config.language, { log });
15
+ const voices = await synthesize(project, { log, force });
16
+ const timeline = buildTimeline(project, voices);
17
+ fs.mkdirSync(project.paths.build, { recursive: true });
18
+ fs.writeFileSync(path.join(project.paths.build, 'timeline.json'), JSON.stringify(timeline, null, 2));
19
+ return { voices, timeline };
20
+ }
21
+
22
+ function fileStamp(p) {
23
+ try {
24
+ const st = fs.statSync(p);
25
+ return `${st.mtimeMs}:${st.size}`;
26
+ } catch {
27
+ return 'missing';
28
+ }
29
+ }
30
+
31
+ export function makeState(project, timeline) {
32
+ const assets = listAssets(project.dir);
33
+ const stamp = [
34
+ fileStamp(project.paths.scenes),
35
+ ...(project.paths.look ? [fileStamp(project.paths.look)] : []),
36
+ ...assets.map((a) => a + '@' + fileStamp(path.join(project.dir, a))),
37
+ ...fs.readdirSync(project.dir).filter((f) => f.endsWith('.js') || f.endsWith('.mjs')).map((f) => f + '@' + fileStamp(path.join(project.dir, f))),
38
+ ].join('|');
39
+ const version = crypto.createHash('sha1').update(stamp + JSON.stringify(timeline) + JSON.stringify(project.config)).digest('hex').slice(0, 12);
40
+ return { config: project.config, timeline, assets, version, title: project.config.title };
41
+ }
42
+
43
+ // Runs fn(page, ctx) with the engine loaded at `scale`, then cleans up.
44
+ export async function withEngine(project, timeline, { scale = 1, pages = 1, transparent = false, log = () => {} } = {}, fn) {
45
+ const state = makeState(project, timeline);
46
+ const server = await startServer({ projectDir: project.dir, getState: () => state, log });
47
+ let browser = null;
48
+ try {
49
+ browser = await launch();
50
+ const list = [];
51
+ for (let i = 0; i < pages; i++) {
52
+ list.push(await openEngine(browser, server.url, { scale, transparent, onConsole: (type, text) => { if (type === 'error') log(`page: ${text}`); } }));
53
+ }
54
+ return await fn(pages === 1 ? list[0] : list, { server, state });
55
+ } finally {
56
+ if (browser) await browser.close();
57
+ await server.close();
58
+ }
59
+ }
60
+
61
+ export function reloadProject(project) {
62
+ return loadProject(project.dir, { size: project.sizeOverride });
63
+ }