@nhtio/adk 0.1.0-master-92655816 → 0.1.0-master-bfedd81c

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 (296) hide show
  1. package/CHANGELOG.md +132 -9
  2. package/batteries/embeddings/openai/adapter.cjs +1 -1
  3. package/batteries/embeddings/openai/adapter.mjs +1 -1
  4. package/batteries/embeddings/webllm/adapter.cjs +1 -1
  5. package/batteries/embeddings/webllm/adapter.mjs +1 -1
  6. package/batteries/llm/ollama/adapter.cjs +5 -5
  7. package/batteries/llm/ollama/adapter.mjs +5 -5
  8. package/batteries/llm/ollama/helpers.cjs +11 -2
  9. package/batteries/llm/ollama/helpers.cjs.map +1 -1
  10. package/batteries/llm/ollama/helpers.mjs +11 -2
  11. package/batteries/llm/ollama/helpers.mjs.map +1 -1
  12. package/batteries/llm/ollama/validation.cjs +1 -1
  13. package/batteries/llm/ollama/validation.mjs +1 -1
  14. package/batteries/llm/openai_chat_completions/adapter.cjs +5 -5
  15. package/batteries/llm/openai_chat_completions/adapter.mjs +5 -5
  16. package/batteries/llm/openai_chat_completions/helpers.cjs +21 -2
  17. package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -1
  18. package/batteries/llm/openai_chat_completions/helpers.mjs +21 -2
  19. package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -1
  20. package/batteries/llm/openai_chat_completions/validation.cjs +1 -1
  21. package/batteries/llm/openai_chat_completions/validation.mjs +1 -1
  22. package/batteries/llm/webllm_chat_completions/adapter.cjs +5 -5
  23. package/batteries/llm/webllm_chat_completions/adapter.mjs +5 -5
  24. package/batteries/llm/webllm_chat_completions/validation.cjs +1 -1
  25. package/batteries/llm/webllm_chat_completions/validation.mjs +1 -1
  26. package/batteries/media/builder.d.ts +245 -0
  27. package/batteries/media/contracts.cjs +119 -0
  28. package/batteries/media/contracts.cjs.map +1 -0
  29. package/batteries/media/contracts.d.ts +321 -0
  30. package/batteries/media/contracts.mjs +110 -0
  31. package/batteries/media/contracts.mjs.map +1 -0
  32. package/batteries/media/engines/audio_decode.cjs +92 -0
  33. package/batteries/media/engines/audio_decode.cjs.map +1 -0
  34. package/batteries/media/engines/audio_decode.d.ts +46 -0
  35. package/batteries/media/engines/audio_decode.mjs +90 -0
  36. package/batteries/media/engines/audio_decode.mjs.map +1 -0
  37. package/batteries/media/engines/execa_executor.cjs +64 -0
  38. package/batteries/media/engines/execa_executor.cjs.map +1 -0
  39. package/batteries/media/engines/execa_executor.d.ts +54 -0
  40. package/batteries/media/engines/execa_executor.mjs +62 -0
  41. package/batteries/media/engines/execa_executor.mjs.map +1 -0
  42. package/batteries/media/engines/fs_workspace.cjs +84 -0
  43. package/batteries/media/engines/fs_workspace.cjs.map +1 -0
  44. package/batteries/media/engines/fs_workspace.d.ts +51 -0
  45. package/batteries/media/engines/fs_workspace.mjs +82 -0
  46. package/batteries/media/engines/fs_workspace.mjs.map +1 -0
  47. package/batteries/media/engines/jimp.cjs +116 -0
  48. package/batteries/media/engines/jimp.cjs.map +1 -0
  49. package/batteries/media/engines/jimp.d.ts +32 -0
  50. package/batteries/media/engines/jimp.mjs +114 -0
  51. package/batteries/media/engines/jimp.mjs.map +1 -0
  52. package/batteries/media/engines/sharp.cjs +120 -0
  53. package/batteries/media/engines/sharp.cjs.map +1 -0
  54. package/batteries/media/engines/sharp.d.ts +42 -0
  55. package/batteries/media/engines/sharp.mjs +117 -0
  56. package/batteries/media/engines/sharp.mjs.map +1 -0
  57. package/batteries/media/engines/soffice.cjs +246 -0
  58. package/batteries/media/engines/soffice.cjs.map +1 -0
  59. package/batteries/media/engines/soffice.d.ts +39 -0
  60. package/batteries/media/engines/soffice.mjs +244 -0
  61. package/batteries/media/engines/soffice.mjs.map +1 -0
  62. package/batteries/media/engines/tesseract_js.cjs +87 -0
  63. package/batteries/media/engines/tesseract_js.cjs.map +1 -0
  64. package/batteries/media/engines/tesseract_js.d.ts +41 -0
  65. package/batteries/media/engines/tesseract_js.mjs +85 -0
  66. package/batteries/media/engines/tesseract_js.mjs.map +1 -0
  67. package/batteries/media/engines/transformers_asr.cjs +111 -0
  68. package/batteries/media/engines/transformers_asr.cjs.map +1 -0
  69. package/batteries/media/engines/transformers_asr.d.ts +41 -0
  70. package/batteries/media/engines/transformers_asr.mjs +109 -0
  71. package/batteries/media/engines/transformers_asr.mjs.map +1 -0
  72. package/batteries/media/exceptions.d.ts +103 -0
  73. package/batteries/media/forge.cjs +403 -0
  74. package/batteries/media/forge.cjs.map +1 -0
  75. package/batteries/media/forge.d.ts +90 -0
  76. package/batteries/media/forge.mjs +399 -0
  77. package/batteries/media/forge.mjs.map +1 -0
  78. package/batteries/media/formats.d.ts +72 -0
  79. package/batteries/media/index.d.ts +136 -0
  80. package/batteries/media/lint.cjs +339 -0
  81. package/batteries/media/lint.cjs.map +1 -0
  82. package/batteries/media/lint.d.ts +117 -0
  83. package/batteries/media/lint.mjs +331 -0
  84. package/batteries/media/lint.mjs.map +1 -0
  85. package/batteries/media/pipe.d.ts +66 -0
  86. package/batteries/media/plan.d.ts +133 -0
  87. package/batteries/media/registry.d.ts +92 -0
  88. package/batteries/media/runtime.d.ts +105 -0
  89. package/batteries/media/steps/doc.d.ts +33 -0
  90. package/batteries/media/steps/image_audio.d.ts +24 -0
  91. package/batteries/media/steps/ingest.d.ts +25 -0
  92. package/batteries/media/steps/pages.d.ts +18 -0
  93. package/batteries/media/steps/sheet.d.ts +36 -0
  94. package/batteries/media/steps/slides.d.ts +35 -0
  95. package/batteries/media/steps/text.d.ts +43 -0
  96. package/batteries/media/validate.d.ts +49 -0
  97. package/batteries/media/verbs.d.ts +126 -0
  98. package/batteries/media.cjs +3049 -0
  99. package/batteries/media.cjs.map +1 -0
  100. package/batteries/media.mjs +3009 -0
  101. package/batteries/media.mjs.map +1 -0
  102. package/batteries/storage/flydrive.cjs +1 -1
  103. package/batteries/storage/flydrive.mjs +1 -1
  104. package/batteries/storage/in_memory.cjs +1 -1
  105. package/batteries/storage/in_memory.mjs +1 -1
  106. package/batteries/storage/opfs.cjs +1 -1
  107. package/batteries/storage/opfs.mjs +1 -1
  108. package/batteries/tools/_shared/index.d.ts +142 -0
  109. package/batteries/tools/_shared.cjs +173 -0
  110. package/batteries/tools/_shared.cjs.map +1 -0
  111. package/batteries/tools/_shared.mjs +164 -0
  112. package/batteries/tools/_shared.mjs.map +1 -0
  113. package/batteries/tools/color.cjs +2 -2
  114. package/batteries/tools/color.mjs +2 -2
  115. package/batteries/tools/comparison.cjs +3 -3
  116. package/batteries/tools/comparison.mjs +3 -3
  117. package/batteries/tools/data_structure.cjs +3 -3
  118. package/batteries/tools/data_structure.mjs +3 -3
  119. package/batteries/tools/datetime_extended.cjs +3 -3
  120. package/batteries/tools/datetime_extended.mjs +3 -3
  121. package/batteries/tools/datetime_math.cjs +3 -3
  122. package/batteries/tools/datetime_math.mjs +3 -3
  123. package/batteries/tools/encoding.cjs +3 -3
  124. package/batteries/tools/encoding.mjs +3 -3
  125. package/batteries/tools/formatting.cjs +3 -3
  126. package/batteries/tools/formatting.mjs +3 -3
  127. package/batteries/tools/geo_basics.cjs +2 -2
  128. package/batteries/tools/geo_basics.mjs +2 -2
  129. package/batteries/tools/index.d.ts +2 -0
  130. package/batteries/tools/math.cjs +3 -3
  131. package/batteries/tools/math.mjs +3 -3
  132. package/batteries/tools/memory.cjs +6 -6
  133. package/batteries/tools/memory.mjs +6 -6
  134. package/batteries/tools/parsing.cjs +4 -4
  135. package/batteries/tools/parsing.mjs +4 -4
  136. package/batteries/tools/retrievables.cjs +5 -5
  137. package/batteries/tools/retrievables.mjs +5 -5
  138. package/batteries/tools/scrapper/exceptions.d.ts +21 -0
  139. package/batteries/tools/scrapper/index.d.ts +172 -0
  140. package/batteries/tools/scrapper/shared.d.ts +146 -0
  141. package/batteries/tools/scrapper.cjs +8 -0
  142. package/batteries/tools/scrapper.mjs +2 -0
  143. package/batteries/tools/searxng/index.d.ts +54 -20
  144. package/batteries/tools/searxng.cjs +2 -1
  145. package/batteries/tools/searxng.mjs +2 -2
  146. package/batteries/tools/standing_instructions.cjs +4 -4
  147. package/batteries/tools/standing_instructions.mjs +4 -4
  148. package/batteries/tools/statistics.cjs +4 -4
  149. package/batteries/tools/statistics.mjs +4 -4
  150. package/batteries/tools/string_processing.cjs +3 -3
  151. package/batteries/tools/string_processing.mjs +3 -3
  152. package/batteries/tools/structured_data.cjs +3 -3
  153. package/batteries/tools/structured_data.mjs +3 -3
  154. package/batteries/tools/text_analysis.cjs +3 -3
  155. package/batteries/tools/text_analysis.mjs +3 -3
  156. package/batteries/tools/text_comparison.cjs +2 -2
  157. package/batteries/tools/text_comparison.mjs +2 -2
  158. package/batteries/tools/time.cjs +3 -3
  159. package/batteries/tools/time.mjs +3 -3
  160. package/batteries/tools/unit_conversion.cjs +2 -2
  161. package/batteries/tools/unit_conversion.mjs +2 -2
  162. package/batteries/tools/web_retrieval/index.d.ts +186 -0
  163. package/batteries/tools/web_retrieval.cjs +206 -0
  164. package/batteries/tools/web_retrieval.cjs.map +1 -0
  165. package/batteries/tools/web_retrieval.mjs +201 -0
  166. package/batteries/tools/web_retrieval.mjs.map +1 -0
  167. package/batteries/tools.cjs +13 -1
  168. package/batteries/tools.mjs +4 -2
  169. package/batteries/vector/arangodb.cjs +1 -1
  170. package/batteries/vector/arangodb.mjs +1 -1
  171. package/batteries/vector/clickhouse.cjs +1 -1
  172. package/batteries/vector/clickhouse.mjs +1 -1
  173. package/batteries/vector/cloudflare.cjs +1 -1
  174. package/batteries/vector/cloudflare.mjs +1 -1
  175. package/batteries/vector/couchbase.cjs +1 -1
  176. package/batteries/vector/couchbase.mjs +1 -1
  177. package/batteries/vector/duckdb.cjs +1 -1
  178. package/batteries/vector/duckdb.mjs +1 -1
  179. package/batteries/vector/elasticsearch.cjs +1 -1
  180. package/batteries/vector/elasticsearch.mjs +1 -1
  181. package/batteries/vector/filters.cjs +1 -1
  182. package/batteries/vector/filters.mjs +1 -1
  183. package/batteries/vector/hnswlib.cjs +1 -1
  184. package/batteries/vector/hnswlib.mjs +1 -1
  185. package/batteries/vector/lancedb.cjs +1 -1
  186. package/batteries/vector/lancedb.mjs +1 -1
  187. package/batteries/vector/mariadb.cjs +1 -1
  188. package/batteries/vector/mariadb.mjs +1 -1
  189. package/batteries/vector/meilisearch.cjs +1 -1
  190. package/batteries/vector/meilisearch.mjs +1 -1
  191. package/batteries/vector/migrate.cjs +1 -1
  192. package/batteries/vector/migrate.mjs +1 -1
  193. package/batteries/vector/mongodb.cjs +1 -1
  194. package/batteries/vector/mongodb.mjs +1 -1
  195. package/batteries/vector/neo4j.cjs +1 -1
  196. package/batteries/vector/neo4j.mjs +1 -1
  197. package/batteries/vector/opensearch.cjs +1 -1
  198. package/batteries/vector/opensearch.mjs +1 -1
  199. package/batteries/vector/oracle23ai.cjs +1 -1
  200. package/batteries/vector/oracle23ai.mjs +1 -1
  201. package/batteries/vector/pinecone.cjs +1 -1
  202. package/batteries/vector/pinecone.mjs +1 -1
  203. package/batteries/vector/redis.cjs +1 -1
  204. package/batteries/vector/redis.mjs +1 -1
  205. package/batteries/vector/retrievable.cjs +1 -1
  206. package/batteries/vector/retrievable.mjs +1 -1
  207. package/batteries/vector/s3vectors.cjs +1 -1
  208. package/batteries/vector/s3vectors.mjs +1 -1
  209. package/batteries/vector/solr.cjs +1 -1
  210. package/batteries/vector/solr.mjs +1 -1
  211. package/batteries/vector/surrealdb.cjs +1 -1
  212. package/batteries/vector/surrealdb.mjs +1 -1
  213. package/batteries/vector/typesense.cjs +1 -1
  214. package/batteries/vector/typesense.mjs +1 -1
  215. package/batteries/vector/vespa.cjs +1 -1
  216. package/batteries/vector/vespa.mjs +1 -1
  217. package/batteries/vector/weaviate.cjs +1 -1
  218. package/batteries/vector/weaviate.mjs +1 -1
  219. package/batteries.cjs +13 -1
  220. package/batteries.mjs +4 -2
  221. package/{common-DwyIhf5B.mjs → common-DYDUi99O.mjs} +7 -7
  222. package/{common-DwyIhf5B.mjs.map → common-DYDUi99O.mjs.map} +1 -1
  223. package/{common-Do0PmqEC.js → common-DZl3ADJs.js} +7 -7
  224. package/{common-Do0PmqEC.js.map → common-DZl3ADJs.js.map} +1 -1
  225. package/common.cjs +7 -7
  226. package/common.d.ts +1 -1
  227. package/common.mjs +7 -7
  228. package/{dispatch_runner-Bh12zRee.mjs → dispatch_runner--ZhdDWRZ.mjs} +3 -3
  229. package/{dispatch_runner-Bh12zRee.mjs.map → dispatch_runner--ZhdDWRZ.mjs.map} +1 -1
  230. package/{dispatch_runner-BCfDikZn.js → dispatch_runner-nHDKkxye.js} +3 -3
  231. package/{dispatch_runner-BCfDikZn.js.map → dispatch_runner-nHDKkxye.js.map} +1 -1
  232. package/dispatch_runner.cjs +1 -1
  233. package/dispatch_runner.mjs +1 -1
  234. package/eslint.cjs +1 -1
  235. package/eslint.mjs +1 -1
  236. package/exceptions-C7FSHEnV.mjs +87 -0
  237. package/exceptions-C7FSHEnV.mjs.map +1 -0
  238. package/exceptions-CQi_lNs1.js +152 -0
  239. package/exceptions-CQi_lNs1.js.map +1 -0
  240. package/forge.cjs +4 -4
  241. package/forge.mjs +4 -4
  242. package/guards.cjs +8 -8
  243. package/guards.mjs +8 -8
  244. package/index.cjs +11 -11
  245. package/index.mjs +11 -11
  246. package/mcp/adk-docs-corpus.json +1 -1
  247. package/package.json +277 -154
  248. package/scrapper-BXlRzMaG.js +463 -0
  249. package/scrapper-BXlRzMaG.js.map +1 -0
  250. package/scrapper-DKy8Cx3L.mjs +433 -0
  251. package/scrapper-DKy8Cx3L.mjs.map +1 -0
  252. package/{searxng-oL3Z5Qo2.mjs → searxng-Cxsfv_sr.mjs} +78 -87
  253. package/searxng-Cxsfv_sr.mjs.map +1 -0
  254. package/{searxng-COD67eJC.js → searxng-DMV9TpMv.js} +85 -88
  255. package/searxng-DMV9TpMv.js.map +1 -0
  256. package/skills/adk-assembly/SKILL.md +2 -2
  257. package/{spooled_artifact-BsM1EfRB.mjs → spooled_artifact-7eePq7JA.mjs} +3 -3
  258. package/{spooled_artifact-BsM1EfRB.mjs.map → spooled_artifact-7eePq7JA.mjs.map} +1 -1
  259. package/{spooled_artifact-B6XRZYFt.js → spooled_artifact-DX8LLyUX.js} +3 -3
  260. package/{spooled_artifact-B6XRZYFt.js.map → spooled_artifact-DX8LLyUX.js.map} +1 -1
  261. package/spooled_artifact.cjs +2 -2
  262. package/spooled_artifact.mjs +2 -2
  263. package/{spooled_markdown_artifact-DyevhaL6.js → spooled_markdown_artifact-ClX72lek.js} +3 -3
  264. package/{spooled_markdown_artifact-DyevhaL6.js.map → spooled_markdown_artifact-ClX72lek.js.map} +1 -1
  265. package/{spooled_markdown_artifact-DJnjD3Ti.mjs → spooled_markdown_artifact-wkrBF3oX.mjs} +3 -3
  266. package/{spooled_markdown_artifact-DJnjD3Ti.mjs.map → spooled_markdown_artifact-wkrBF3oX.mjs.map} +1 -1
  267. package/{thought-DzcSu2Y6.mjs → thought-B_vxAiKU.mjs} +3 -3
  268. package/{thought-DzcSu2Y6.mjs.map → thought-B_vxAiKU.mjs.map} +1 -1
  269. package/{thought-DhElxSkZ.js → thought-DLwpF7MI.js} +3 -3
  270. package/{thought-DhElxSkZ.js.map → thought-DLwpF7MI.js.map} +1 -1
  271. package/{tool-DjUJeSzk.js → tool-D5WGVIcI.js} +3 -3
  272. package/{tool-DjUJeSzk.js.map → tool-D5WGVIcI.js.map} +1 -1
  273. package/{tool-DMvZFz9h.mjs → tool-wMYMVl60.mjs} +3 -3
  274. package/{tool-DMvZFz9h.mjs.map → tool-wMYMVl60.mjs.map} +1 -1
  275. package/{tool_call-DhAW70EY.mjs → tool_call-B4-_-vjG.mjs} +4 -4
  276. package/{tool_call-DhAW70EY.mjs.map → tool_call-B4-_-vjG.mjs.map} +1 -1
  277. package/{tool_call-CGec5078.js → tool_call-DixVlW40.js} +4 -4
  278. package/{tool_call-CGec5078.js.map → tool_call-DixVlW40.js.map} +1 -1
  279. package/{tool_registry-BuMKln6b.mjs → tool_registry-791Vrjtf.mjs} +142 -142
  280. package/tool_registry-791Vrjtf.mjs.map +1 -0
  281. package/{tool_registry-C5wfDxaq.js → tool_registry-CKJPze3j.js} +141 -141
  282. package/tool_registry-CKJPze3j.js.map +1 -0
  283. package/{turn_runner-CfrZZ-ZJ.js → turn_runner-HXImLGIn.js} +5 -5
  284. package/{turn_runner-CfrZZ-ZJ.js.map → turn_runner-HXImLGIn.js.map} +1 -1
  285. package/{turn_runner-BQCupiHC.mjs → turn_runner-ZyYO-Kti.mjs} +5 -5
  286. package/{turn_runner-BQCupiHC.mjs.map → turn_runner-ZyYO-Kti.mjs.map} +1 -1
  287. package/turn_runner.cjs +1 -1
  288. package/turn_runner.mjs +1 -1
  289. package/validate-BFaUYHDN.js +1298 -0
  290. package/validate-BFaUYHDN.js.map +1 -0
  291. package/validate-DSZ3wicB.mjs +1215 -0
  292. package/validate-DSZ3wicB.mjs.map +1 -0
  293. package/searxng-COD67eJC.js.map +0 -1
  294. package/searxng-oL3Z5Qo2.mjs.map +0 -1
  295. package/tool_registry-BuMKln6b.mjs.map +0 -1
  296. package/tool_registry-C5wfDxaq.js.map +0 -1
@@ -0,0 +1,244 @@
1
+ import { implementsBinaryExecutor, implementsScratchWorkspace } from "../contracts.mjs";
2
+ import { t as E_INVALID_MEDIA_PIPELINE_CONFIG } from "../../../exceptions-C7FSHEnV.mjs";
3
+ //#region src/batteries/media/engines/soffice.ts
4
+ /**
5
+ * The LibreOffice-backed {@link @nhtio/adk/batteries/media/contracts!MediaEngine}: document,
6
+ * spreadsheet, and presentation conversion via the `soffice` binary.
7
+ *
8
+ * @module @nhtio/adk/batteries/media/engines/soffice
9
+ *
10
+ * @remarks
11
+ * Document conversion is the one capability in the media battery with no mature
12
+ * cross-environment equivalent, so this engine is binary-backed by design. It composes the
13
+ * two BYO runtime contracts: a {@link @nhtio/adk/batteries/media/contracts!BinaryExecutor}
14
+ * runs the invocation (bundled: `execa_executor`) and a
15
+ * {@link @nhtio/adk/batteries/media/contracts!ScratchWorkspace} exchanges bytes with it
16
+ * (bundled: `fs_workspace`). The executor and workspace must agree on path visibility —
17
+ * that pairing is the consumer's composition decision.
18
+ *
19
+ * One engine, one capability kind: the conversion matrix is declared as convert capability
20
+ * groups (each format silo converts within itself plus to PDF/HTML; PDF converts to
21
+ * html/txt/docx/odt). The spreadsheet group covers ODS/legacy-xls to xlsx — what used to be
22
+ * a separate "normalize" engine is just an edge in the matrix.
23
+ */
24
+ var MIME_BY_TARGET = {
25
+ pdf: "application/pdf",
26
+ html: "text/html",
27
+ txt: "text/plain",
28
+ md: "text/markdown",
29
+ csv: "text/csv",
30
+ json: "application/json",
31
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
32
+ doc: "application/msword",
33
+ rtf: "application/rtf",
34
+ odt: "application/vnd.oasis.opendocument.text",
35
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
36
+ xls: "application/vnd.ms-excel",
37
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
38
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
39
+ ppt: "application/vnd.ms-powerpoint",
40
+ odp: "application/vnd.oasis.opendocument.presentation"
41
+ };
42
+ var EXT_BY_MIME = {
43
+ "application/pdf": "pdf",
44
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
45
+ "application/msword": "doc",
46
+ "application/rtf": "rtf",
47
+ "text/rtf": "rtf",
48
+ "application/vnd.oasis.opendocument.text": "odt",
49
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
50
+ "application/vnd.ms-excel": "xls",
51
+ "application/vnd.oasis.opendocument.spreadsheet": "ods",
52
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
53
+ "application/vnd.ms-powerpoint": "ppt",
54
+ "application/vnd.oasis.opendocument.presentation": "odp",
55
+ "text/plain": "txt",
56
+ "text/html": "html",
57
+ "text/csv": "csv"
58
+ };
59
+ /** Server-parity conversion matrix: same-silo targets plus pdf/html. */
60
+ var TARGETS_BY_EXT = {
61
+ docx: [
62
+ "pdf",
63
+ "html",
64
+ "txt",
65
+ "md",
66
+ "odt",
67
+ "doc",
68
+ "rtf"
69
+ ],
70
+ odt: [
71
+ "pdf",
72
+ "html",
73
+ "txt",
74
+ "md",
75
+ "docx",
76
+ "doc",
77
+ "rtf"
78
+ ],
79
+ doc: [
80
+ "pdf",
81
+ "html",
82
+ "txt",
83
+ "md",
84
+ "docx",
85
+ "odt",
86
+ "rtf"
87
+ ],
88
+ rtf: [
89
+ "pdf",
90
+ "html",
91
+ "txt",
92
+ "md",
93
+ "docx",
94
+ "odt",
95
+ "doc"
96
+ ],
97
+ xlsx: [
98
+ "pdf",
99
+ "html",
100
+ "csv",
101
+ "json",
102
+ "ods",
103
+ "xls"
104
+ ],
105
+ ods: [
106
+ "pdf",
107
+ "html",
108
+ "csv",
109
+ "json",
110
+ "xlsx",
111
+ "xls"
112
+ ],
113
+ xls: [
114
+ "pdf",
115
+ "html",
116
+ "csv",
117
+ "json",
118
+ "xlsx",
119
+ "ods"
120
+ ],
121
+ pptx: [
122
+ "pdf",
123
+ "html",
124
+ "odp",
125
+ "ppt"
126
+ ],
127
+ odp: [
128
+ "pdf",
129
+ "html",
130
+ "pptx",
131
+ "ppt"
132
+ ],
133
+ ppt: [
134
+ "pdf",
135
+ "html",
136
+ "pptx",
137
+ "odp"
138
+ ],
139
+ pdf: [
140
+ "html",
141
+ "txt",
142
+ "docx",
143
+ "odt"
144
+ ]
145
+ };
146
+ /** soffice convert-to filter token per target (md goes via txt; json via csv). */
147
+ var CONVERT_TOKEN = {
148
+ md: "txt:Text",
149
+ json: "csv"
150
+ };
151
+ var validateOptions = (options, name) => {
152
+ if (typeof options?.path !== "string" || options.path.length === 0) throw new E_INVALID_MEDIA_PIPELINE_CONFIG([`${name} requires the soffice binary path`]);
153
+ if (!implementsBinaryExecutor(options.executor)) throw new E_INVALID_MEDIA_PIPELINE_CONFIG([`${name} requires an executor implementing the BinaryExecutor contract`]);
154
+ if (typeof options.workspace !== "function") throw new E_INVALID_MEDIA_PIPELINE_CONFIG([`${name} requires a workspace factory (e.g. fsScratchWorkspace({ root }))`]);
155
+ };
156
+ var runSoffice = async (options, bytes, inputExt, convertTo, outputExt, signal) => {
157
+ const workspace = await options.workspace();
158
+ if (!implementsScratchWorkspace(workspace)) throw new E_INVALID_MEDIA_PIPELINE_CONFIG(["the workspace factory minted a value that does not implement ScratchWorkspace"]);
159
+ try {
160
+ const inputPath = await workspace.materialize(bytes, `input.${inputExt}`);
161
+ const result = await options.executor.exec({
162
+ cmd: options.path,
163
+ args: [
164
+ "--headless",
165
+ "--nologo",
166
+ "--nodefault",
167
+ "--norestore",
168
+ "--nolockcheck",
169
+ "--convert-to",
170
+ convertTo,
171
+ "--outdir",
172
+ workspace.dir(),
173
+ inputPath
174
+ ],
175
+ timeoutMs: options.timeoutMs ?? 12e4,
176
+ signal
177
+ });
178
+ if (result.failed) {
179
+ const detail = result.stderr || result.stdout || `exit code ${result.exitCode}`;
180
+ throw new Error(`LibreOffice conversion failed: ${detail}`);
181
+ }
182
+ const files = await workspace.list();
183
+ const produced = files.find((f) => f.toLowerCase().endsWith(`.${outputExt}`) && f !== `input.${inputExt}`);
184
+ if (!produced) throw new Error(`LibreOffice reported success but produced no .${outputExt} output (files: ${files.join(", ")})`);
185
+ return workspace.read(`${workspace.dir()}/${produced}`);
186
+ } finally {
187
+ await workspace.dispose();
188
+ }
189
+ };
190
+ /** The MIME types of one extension group, for capability `from` declarations. */
191
+ var MIMES_OF = (exts) => Object.entries(EXT_BY_MIME).filter(([, ext]) => exts.includes(ext)).map(([mime]) => mime);
192
+ /**
193
+ * Construct the LibreOffice engine.
194
+ *
195
+ * @param options - Binary path, executor, workspace factory, timeout.
196
+ * @returns The engine, declaring one convert capability group per format silo.
197
+ */
198
+ var sofficeEngine = (options) => {
199
+ validateOptions(options, "sofficeEngine");
200
+ const convert = async (request) => {
201
+ const inputExt = EXT_BY_MIME[request.mimeType.toLowerCase().split(";")[0].trim()];
202
+ if (!inputExt) throw new Error(`unsupported input MIME for conversion: ${request.mimeType}`);
203
+ const targets = TARGETS_BY_EXT[inputExt] ?? [];
204
+ if (!targets.includes(request.to)) throw new Error(`cannot convert ${inputExt} to ${request.to}; supported: ${targets.join(", ")}`);
205
+ const convertTo = CONVERT_TOKEN[request.to] ?? request.to;
206
+ const outputExt = request.to === "md" ? "txt" : request.to === "json" ? "csv" : request.to;
207
+ let bytes = await runSoffice(options, request.bytes, inputExt, convertTo, outputExt, request.signal);
208
+ let mimeType = MIME_BY_TARGET[request.to] ?? "application/octet-stream";
209
+ if (request.to === "json") {
210
+ const rows = new TextDecoder().decode(bytes).split(/\r?\n/).filter((line) => line.length > 0).map((line) => line.split(","));
211
+ bytes = new TextEncoder().encode(JSON.stringify(rows));
212
+ mimeType = MIME_BY_TARGET.json;
213
+ }
214
+ return { outputs: [{
215
+ bytes,
216
+ mimeType
217
+ }] };
218
+ };
219
+ const group = (exts, to) => ({
220
+ from: MIMES_OF(exts),
221
+ to,
222
+ convert
223
+ });
224
+ return {
225
+ id: "soffice",
226
+ converts: [
227
+ group(["docx"], TARGETS_BY_EXT.docx),
228
+ group(["odt"], TARGETS_BY_EXT.odt),
229
+ group(["doc"], TARGETS_BY_EXT.doc),
230
+ group(["rtf"], TARGETS_BY_EXT.rtf),
231
+ group(["xlsx"], TARGETS_BY_EXT.xlsx),
232
+ group(["ods"], TARGETS_BY_EXT.ods),
233
+ group(["xls"], TARGETS_BY_EXT.xls),
234
+ group(["pptx"], TARGETS_BY_EXT.pptx),
235
+ group(["odp"], TARGETS_BY_EXT.odp),
236
+ group(["ppt"], TARGETS_BY_EXT.ppt),
237
+ group(["pdf"], TARGETS_BY_EXT.pdf)
238
+ ]
239
+ };
240
+ };
241
+ //#endregion
242
+ export { sofficeEngine };
243
+
244
+ //# sourceMappingURL=soffice.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"soffice.mjs","names":[],"sources":["../../../../src/batteries/media/engines/soffice.ts"],"sourcesContent":["/**\n * The LibreOffice-backed {@link @nhtio/adk/batteries/media/contracts!MediaEngine}: document,\n * spreadsheet, and presentation conversion via the `soffice` binary.\n *\n * @module @nhtio/adk/batteries/media/engines/soffice\n *\n * @remarks\n * Document conversion is the one capability in the media battery with no mature\n * cross-environment equivalent, so this engine is binary-backed by design. It composes the\n * two BYO runtime contracts: a {@link @nhtio/adk/batteries/media/contracts!BinaryExecutor}\n * runs the invocation (bundled: `execa_executor`) and a\n * {@link @nhtio/adk/batteries/media/contracts!ScratchWorkspace} exchanges bytes with it\n * (bundled: `fs_workspace`). The executor and workspace must agree on path visibility —\n * that pairing is the consumer's composition decision.\n *\n * One engine, one capability kind: the conversion matrix is declared as convert capability\n * groups (each format silo converts within itself plus to PDF/HTML; PDF converts to\n * html/txt/docx/odt). The spreadsheet group covers ODS/legacy-xls to xlsx — what used to be\n * a separate \"normalize\" engine is just an edge in the matrix.\n */\n\nimport { E_INVALID_MEDIA_PIPELINE_CONFIG } from '../exceptions'\nimport { implementsBinaryExecutor, implementsScratchWorkspace } from '../contracts'\nimport type {\n MediaEngine,\n ConvertCapability,\n ConvertRequest,\n ConvertResult,\n BinaryExecutor,\n ScratchWorkspaceFactory,\n} from '../contracts'\n\n/** Options for {@link sofficeEngine}. */\nexport interface SofficeEngineOptions {\n /** Path (or resolvable name) of the soffice binary. */\n path: string\n /** Runs the soffice invocation. Required — no platform default. */\n executor: BinaryExecutor\n /** Mints a scratch dir per invocation whose paths the executor can open. Required. */\n workspace: ScratchWorkspaceFactory\n /** Per-invocation timeout. Default 120000. */\n timeoutMs?: number\n}\n\nconst MIME_BY_TARGET: Record<string, string> = {\n pdf: 'application/pdf',\n html: 'text/html',\n txt: 'text/plain',\n md: 'text/markdown',\n csv: 'text/csv',\n json: 'application/json',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n doc: 'application/msword',\n rtf: 'application/rtf',\n odt: 'application/vnd.oasis.opendocument.text',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n xls: 'application/vnd.ms-excel',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n ppt: 'application/vnd.ms-powerpoint',\n odp: 'application/vnd.oasis.opendocument.presentation',\n}\n\nconst EXT_BY_MIME: Record<string, string> = {\n 'application/pdf': 'pdf',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',\n 'application/msword': 'doc',\n 'application/rtf': 'rtf',\n 'text/rtf': 'rtf',\n 'application/vnd.oasis.opendocument.text': 'odt',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n 'application/vnd.ms-excel': 'xls',\n 'application/vnd.oasis.opendocument.spreadsheet': 'ods',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',\n 'application/vnd.ms-powerpoint': 'ppt',\n 'application/vnd.oasis.opendocument.presentation': 'odp',\n 'text/plain': 'txt',\n 'text/html': 'html',\n 'text/csv': 'csv',\n}\n\n/** Server-parity conversion matrix: same-silo targets plus pdf/html. */\nconst TARGETS_BY_EXT: Record<string, readonly string[]> = {\n docx: ['pdf', 'html', 'txt', 'md', 'odt', 'doc', 'rtf'],\n odt: ['pdf', 'html', 'txt', 'md', 'docx', 'doc', 'rtf'],\n doc: ['pdf', 'html', 'txt', 'md', 'docx', 'odt', 'rtf'],\n rtf: ['pdf', 'html', 'txt', 'md', 'docx', 'odt', 'doc'],\n xlsx: ['pdf', 'html', 'csv', 'json', 'ods', 'xls'],\n ods: ['pdf', 'html', 'csv', 'json', 'xlsx', 'xls'],\n xls: ['pdf', 'html', 'csv', 'json', 'xlsx', 'ods'],\n pptx: ['pdf', 'html', 'odp', 'ppt'],\n odp: ['pdf', 'html', 'pptx', 'ppt'],\n ppt: ['pdf', 'html', 'pptx', 'odp'],\n pdf: ['html', 'txt', 'docx', 'odt'],\n}\n\n/** soffice convert-to filter token per target (md goes via txt; json via csv). */\nconst CONVERT_TOKEN: Record<string, string> = {\n md: 'txt:Text',\n json: 'csv',\n}\n\nconst validateOptions = (options: SofficeEngineOptions, name: string): void => {\n if (typeof options?.path !== 'string' || options.path.length === 0) {\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([`${name} requires the soffice binary path`])\n }\n if (!implementsBinaryExecutor(options.executor)) {\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n `${name} requires an executor implementing the BinaryExecutor contract`,\n ])\n }\n if (typeof options.workspace !== 'function') {\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n `${name} requires a workspace factory (e.g. fsScratchWorkspace({ root }))`,\n ])\n }\n}\n\nconst runSoffice = async (\n options: SofficeEngineOptions,\n bytes: Uint8Array,\n inputExt: string,\n convertTo: string,\n outputExt: string,\n signal?: AbortSignal\n): Promise<Uint8Array> => {\n const workspace = await options.workspace()\n if (!implementsScratchWorkspace(workspace)) {\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n 'the workspace factory minted a value that does not implement ScratchWorkspace',\n ])\n }\n try {\n const inputPath = await workspace.materialize(bytes, `input.${inputExt}`)\n const result = await options.executor.exec({\n cmd: options.path,\n args: [\n '--headless',\n '--nologo',\n '--nodefault',\n '--norestore',\n '--nolockcheck',\n '--convert-to',\n convertTo,\n '--outdir',\n workspace.dir(),\n inputPath,\n ],\n timeoutMs: options.timeoutMs ?? 120_000,\n signal,\n })\n if (result.failed) {\n const detail = result.stderr || result.stdout || `exit code ${result.exitCode}`\n throw new Error(`LibreOffice conversion failed: ${detail}`)\n }\n const files = await workspace.list()\n const produced = files.find(\n (f) => f.toLowerCase().endsWith(`.${outputExt}`) && f !== `input.${inputExt}`\n )\n if (!produced) {\n throw new Error(\n `LibreOffice reported success but produced no .${outputExt} output (files: ${files.join(', ')})`\n )\n }\n return workspace.read(`${workspace.dir()}/${produced}`)\n } finally {\n await workspace.dispose()\n }\n}\n\n/** The MIME types of one extension group, for capability `from` declarations. */\nconst MIMES_OF = (exts: readonly string[]): string[] =>\n Object.entries(EXT_BY_MIME)\n .filter(([, ext]) => exts.includes(ext))\n .map(([mime]) => mime)\n\n/**\n * Construct the LibreOffice engine.\n *\n * @param options - Binary path, executor, workspace factory, timeout.\n * @returns The engine, declaring one convert capability group per format silo.\n */\nexport const sofficeEngine = (options: SofficeEngineOptions): MediaEngine => {\n validateOptions(options, 'sofficeEngine')\n\n const convert = async (request: ConvertRequest): Promise<ConvertResult> => {\n const mime = request.mimeType.toLowerCase().split(';')[0].trim()\n const inputExt = EXT_BY_MIME[mime]\n if (!inputExt) throw new Error(`unsupported input MIME for conversion: ${request.mimeType}`)\n const targets = TARGETS_BY_EXT[inputExt] ?? []\n if (!targets.includes(request.to)) {\n throw new Error(\n `cannot convert ${inputExt} to ${request.to}; supported: ${targets.join(', ')}`\n )\n }\n const convertTo = CONVERT_TOKEN[request.to] ?? request.to\n const outputExt = request.to === 'md' ? 'txt' : request.to === 'json' ? 'csv' : request.to\n let bytes = await runSoffice(\n options,\n request.bytes,\n inputExt,\n convertTo,\n outputExt,\n request.signal\n )\n let mimeType = MIME_BY_TARGET[request.to] ?? 'application/octet-stream'\n if (request.to === 'json') {\n // soffice emits CSV; lower to a JSON array-of-arrays for predictable structure.\n const text = new TextDecoder().decode(bytes)\n const rows = text\n .split(/\\r?\\n/)\n .filter((line) => line.length > 0)\n .map((line) => line.split(','))\n bytes = new TextEncoder().encode(JSON.stringify(rows))\n mimeType = MIME_BY_TARGET.json\n }\n return { outputs: [{ bytes, mimeType }] }\n }\n\n // One capability group per uniform from×to block of the matrix.\n const group = (exts: readonly string[], to: readonly string[]): ConvertCapability => ({\n from: MIMES_OF(exts),\n to,\n convert,\n })\n\n return {\n id: 'soffice',\n converts: [\n group(['docx'], TARGETS_BY_EXT.docx),\n group(['odt'], TARGETS_BY_EXT.odt),\n group(['doc'], TARGETS_BY_EXT.doc),\n group(['rtf'], TARGETS_BY_EXT.rtf),\n group(['xlsx'], TARGETS_BY_EXT.xlsx),\n group(['ods'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EACpF,MAAM,SAAS,IAAI;EACnB;EACA;CACF;CAEA,OAAO;EACL,IAAI;EACJ,UAAU;GACR,MAAM,CAAC,MAAM,GAAG,eAAe,IAAI;GACnC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;GACjC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;GACjC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;GACjC,MAAM,CAAC,MAAM,GAAG,eAAe,IAAI;GACnC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;GACjC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;GACjC,MAAM,CAAC,MAAM,GAAG,eAAe,IAAI;GACnC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;GACjC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;GACjC,MAAM,CAAC,KAAK,GAAG,eAAe,GAAG;EACnC;CACF;AACF"}
@@ -0,0 +1,87 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ require("../../../chunk-Ble4zEEl.js");
3
+ const require_tool_registry = require("../../../tool_registry-CKJPze3j.js");
4
+ require("../../../guards.cjs");
5
+ const require_exceptions = require("../../../exceptions-CQi_lNs1.js");
6
+ //#region src/batteries/media/engines/tesseract_js.ts
7
+ /**
8
+ * A cross-environment OCR {@link @nhtio/adk/batteries/media/contracts!MediaEngine}
9
+ * backed by tesseract.js (WASM Tesseract — Node and browsers, no binary).
10
+ *
11
+ * @module @nhtio/adk/batteries/media/engines/tesseract_js
12
+ *
13
+ * @remarks
14
+ * The local-by-default OCR engine. Language data files download on first use of each
15
+ * language; point `langPath`/`cachePath` at a writable location to control where (the
16
+ * factory requires `languages` up front so a deployment never silently fetches packs for
17
+ * languages it didn't plan for). Workers are created per recognize call and terminated in
18
+ * `finally` — slower than a pooled setup but leak-free by construction; consumers who need
19
+ * pooling can BYO an engine that holds a worker.
20
+ *
21
+ * `tesseract.js` is an optional peer dependency, lazily imported on first actual use.
22
+ *
23
+ * Declares one convert capability: `image/*` to `txt`/`hocr`/`json` (OCR is a format
24
+ * conversion — image in, text out). Language hints ride `request.options.languages`.
25
+ */
26
+ /**
27
+ * Construct the tesseract.js OCR engine.
28
+ *
29
+ * @param options - Languages (required) and data-path overrides.
30
+ * @returns The engine.
31
+ */
32
+ var tesseractJsEngine = (options) => {
33
+ if (!Array.isArray(options?.languages) || options.languages.length === 0) throw new require_exceptions.E_INVALID_MEDIA_PIPELINE_CONFIG(["tesseractJsEngine requires languages (e.g. [\"eng\"]) — language packs download on first use and are never chosen silently"]);
34
+ let modPromise;
35
+ const getModule = () => {
36
+ modPromise ??= Promise.resolve(options.tesseract ? options.tesseract() : import("tesseract.js")).catch((err) => {
37
+ throw new require_exceptions.E_INVALID_MEDIA_PIPELINE_CONFIG([`the tesseract.js engine could not load its peer dependency "tesseract.js": ${require_tool_registry.isError(err) ? err.message : String(err)} — install it (pnpm add tesseract.js)`]);
38
+ });
39
+ return modPromise;
40
+ };
41
+ const convert = async (request) => {
42
+ const mod = await getModule();
43
+ const languages = request.options?.languages ?? options.languages;
44
+ const worker = await mod.createWorker(languages, void 0, {
45
+ ...options.langPath ? { langPath: options.langPath } : {},
46
+ ...options.cachePath ? { cachePath: options.cachePath } : {}
47
+ });
48
+ try {
49
+ const result = await worker.recognize(typeof globalThis.Buffer !== "undefined" ? globalThis.Buffer.from(request.bytes.buffer, request.bytes.byteOffset, request.bytes.byteLength) : new Blob([request.bytes], { type: request.mimeType }));
50
+ let text = result.data.text;
51
+ let mimeType = "text/plain";
52
+ if (request.to === "json") {
53
+ text = JSON.stringify({
54
+ text: result.data.text,
55
+ confidence: result.data.confidence
56
+ });
57
+ mimeType = "application/json";
58
+ } else if (request.to === "hocr") {
59
+ const hocr = result.data.hocr;
60
+ text = hocr ?? result.data.text;
61
+ mimeType = hocr ? "text/html" : "text/plain";
62
+ }
63
+ return { outputs: [{
64
+ bytes: new TextEncoder().encode(text),
65
+ mimeType
66
+ }] };
67
+ } finally {
68
+ await worker.terminate();
69
+ }
70
+ };
71
+ return {
72
+ id: "tesseract.js",
73
+ converts: [{
74
+ from: ["image/*"],
75
+ to: [
76
+ "txt",
77
+ "hocr",
78
+ "json"
79
+ ],
80
+ convert
81
+ }]
82
+ };
83
+ };
84
+ //#endregion
85
+ exports.tesseractJsEngine = tesseractJsEngine;
86
+
87
+ //# sourceMappingURL=tesseract_js.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tesseract_js.cjs","names":[],"sources":["../../../../src/batteries/media/engines/tesseract_js.ts"],"sourcesContent":["/**\n * A cross-environment OCR {@link @nhtio/adk/batteries/media/contracts!MediaEngine}\n * backed by tesseract.js (WASM Tesseract — Node and browsers, no binary).\n *\n * @module @nhtio/adk/batteries/media/engines/tesseract_js\n *\n * @remarks\n * The local-by-default OCR engine. Language data files download on first use of each\n * language; point `langPath`/`cachePath` at a writable location to control where (the\n * factory requires `languages` up front so a deployment never silently fetches packs for\n * languages it didn't plan for). Workers are created per recognize call and terminated in\n * `finally` — slower than a pooled setup but leak-free by construction; consumers who need\n * pooling can BYO an engine that holds a worker.\n *\n * `tesseract.js` is an optional peer dependency, lazily imported on first actual use.\n *\n * Declares one convert capability: `image/*` to `txt`/`hocr`/`json` (OCR is a format\n * conversion — image in, text out). Language hints ride `request.options.languages`.\n */\n\nimport { isError } from '@nhtio/adk/guards'\nimport { E_INVALID_MEDIA_PIPELINE_CONFIG } from '../exceptions'\nimport type * as TesseractNS from 'tesseract.js'\nimport type { MediaEngine, ConvertRequest, ConvertResult } from '../contracts'\n\ntype TesseractModule = typeof TesseractNS\n\n/** Options for {@link tesseractJsEngine}. */\nexport interface TesseractJsEngineOptions {\n /** Languages to load, e.g. `['eng']`. REQUIRED — language packs download on first use. */\n languages: readonly string[]\n /** Where language data is fetched from / cached (forwarded to createWorker). */\n langPath?: string\n /** Local cache directory for downloaded language data. */\n cachePath?: string\n /** Override the module resolution. Default: `import('tesseract.js')`. */\n tesseract?: () => TesseractModule | Promise<TesseractModule>\n}\n\n/**\n * Construct the tesseract.js OCR engine.\n *\n * @param options - Languages (required) and data-path overrides.\n * @returns The engine.\n */\nexport const tesseractJsEngine = (options: TesseractJsEngineOptions): MediaEngine => {\n if (!Array.isArray(options?.languages) || options.languages.length === 0) {\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n 'tesseractJsEngine requires languages (e.g. [\"eng\"]) — language packs download on first use and are never chosen silently',\n ])\n }\n let modPromise: Promise<TesseractModule> | undefined\n const getModule = (): Promise<TesseractModule> => {\n modPromise ??= Promise.resolve(\n options.tesseract ? options.tesseract() : import('tesseract.js')\n ).catch((err) => {\n const detail = isError(err) ? err.message : String(err)\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n `the tesseract.js engine could not load its peer dependency \"tesseract.js\": ${detail} — install it (pnpm add tesseract.js)`,\n ])\n })\n return modPromise\n }\n\n const convert = async (request: ConvertRequest): Promise<ConvertResult> => {\n const mod = await getModule()\n const languages = (request.options?.languages ?? options.languages) as string[]\n const worker = await mod.createWorker(languages, undefined, {\n ...(options.langPath ? { langPath: options.langPath } : {}),\n ...(options.cachePath ? { cachePath: options.cachePath } : {}),\n })\n try {\n const result = await worker.recognize(\n // tesseract.js accepts Buffer/Blob/ImageLike; raw bytes work via Buffer in Node\n typeof globalThis.Buffer !== 'undefined'\n ? globalThis.Buffer.from(\n request.bytes.buffer,\n request.bytes.byteOffset,\n request.bytes.byteLength\n )\n : new Blob([request.bytes as BlobPart], { type: request.mimeType })\n )\n let text = result.data.text\n let mimeType = 'text/plain'\n if (request.to === 'json') {\n text = JSON.stringify({ text: result.data.text, confidence: result.data.confidence })\n mimeType = 'application/json'\n } else if (request.to === 'hocr') {\n // hocr requires opting into the output at recognize time in tesseract.js v5+;\n // fall back to text when unavailable rather than failing the read.\n const hocr = (result.data as { hocr?: string | null }).hocr\n text = hocr ?? result.data.text\n mimeType = hocr ? 'text/html' : 'text/plain'\n }\n return { outputs: [{ bytes: new TextEncoder().encode(text), mimeType }] }\n }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AAM,YAAY,OAAO,KAAK;IAAW,CAAC;IACpF,WAAW;GACb,OAAO,IAAI,QAAQ,OAAO,QAAQ;IAGhC,MAAM,OAAQ,OAAO,KAAkC;IACvD,OAAO,QAAQ,OAAO,KAAK;IAC3B,WAAW,OAAO,cAAc;GAClC;GACA,OAAO,EAAE,SAAS,CAAC;IAAE,OAAO,IAAI,YAAY,EAAE,OAAO,IAAI;IAAG;GAAS,CAAC,EAAE;EAC1E,UAAU;GACR,MAAM,OAAO,UAAU;EACzB;CACF;CAEA,OAAO;EACL,IAAI;EACJ,UAAU,CACR;GACE,MAAM,CAAC,SAAS;GAChB,IAAI;IAAC;IAAO;IAAQ;GAAM;GAC1B;EACF,CACF;CACF;AACF"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A cross-environment OCR {@link @nhtio/adk/batteries/media/contracts!MediaEngine}
3
+ * backed by tesseract.js (WASM Tesseract — Node and browsers, no binary).
4
+ *
5
+ * @module @nhtio/adk/batteries/media/engines/tesseract_js
6
+ *
7
+ * @remarks
8
+ * The local-by-default OCR engine. Language data files download on first use of each
9
+ * language; point `langPath`/`cachePath` at a writable location to control where (the
10
+ * factory requires `languages` up front so a deployment never silently fetches packs for
11
+ * languages it didn't plan for). Workers are created per recognize call and terminated in
12
+ * `finally` — slower than a pooled setup but leak-free by construction; consumers who need
13
+ * pooling can BYO an engine that holds a worker.
14
+ *
15
+ * `tesseract.js` is an optional peer dependency, lazily imported on first actual use.
16
+ *
17
+ * Declares one convert capability: `image/*` to `txt`/`hocr`/`json` (OCR is a format
18
+ * conversion — image in, text out). Language hints ride `request.options.languages`.
19
+ */
20
+ import type * as TesseractNS from 'tesseract.js';
21
+ import type { MediaEngine } from "../contracts";
22
+ type TesseractModule = typeof TesseractNS;
23
+ /** Options for {@link tesseractJsEngine}. */
24
+ export interface TesseractJsEngineOptions {
25
+ /** Languages to load, e.g. `['eng']`. REQUIRED — language packs download on first use. */
26
+ languages: readonly string[];
27
+ /** Where language data is fetched from / cached (forwarded to createWorker). */
28
+ langPath?: string;
29
+ /** Local cache directory for downloaded language data. */
30
+ cachePath?: string;
31
+ /** Override the module resolution. Default: `import('tesseract.js')`. */
32
+ tesseract?: () => TesseractModule | Promise<TesseractModule>;
33
+ }
34
+ /**
35
+ * Construct the tesseract.js OCR engine.
36
+ *
37
+ * @param options - Languages (required) and data-path overrides.
38
+ * @returns The engine.
39
+ */
40
+ export declare const tesseractJsEngine: (options: TesseractJsEngineOptions) => MediaEngine;
41
+ export {};
@@ -0,0 +1,85 @@
1
+ import { o as isError } from "../../../tool_registry-791Vrjtf.mjs";
2
+ import "../../../guards.mjs";
3
+ import { t as E_INVALID_MEDIA_PIPELINE_CONFIG } from "../../../exceptions-C7FSHEnV.mjs";
4
+ //#region src/batteries/media/engines/tesseract_js.ts
5
+ /**
6
+ * A cross-environment OCR {@link @nhtio/adk/batteries/media/contracts!MediaEngine}
7
+ * backed by tesseract.js (WASM Tesseract — Node and browsers, no binary).
8
+ *
9
+ * @module @nhtio/adk/batteries/media/engines/tesseract_js
10
+ *
11
+ * @remarks
12
+ * The local-by-default OCR engine. Language data files download on first use of each
13
+ * language; point `langPath`/`cachePath` at a writable location to control where (the
14
+ * factory requires `languages` up front so a deployment never silently fetches packs for
15
+ * languages it didn't plan for). Workers are created per recognize call and terminated in
16
+ * `finally` — slower than a pooled setup but leak-free by construction; consumers who need
17
+ * pooling can BYO an engine that holds a worker.
18
+ *
19
+ * `tesseract.js` is an optional peer dependency, lazily imported on first actual use.
20
+ *
21
+ * Declares one convert capability: `image/*` to `txt`/`hocr`/`json` (OCR is a format
22
+ * conversion — image in, text out). Language hints ride `request.options.languages`.
23
+ */
24
+ /**
25
+ * Construct the tesseract.js OCR engine.
26
+ *
27
+ * @param options - Languages (required) and data-path overrides.
28
+ * @returns The engine.
29
+ */
30
+ var tesseractJsEngine = (options) => {
31
+ if (!Array.isArray(options?.languages) || options.languages.length === 0) throw new E_INVALID_MEDIA_PIPELINE_CONFIG(["tesseractJsEngine requires languages (e.g. [\"eng\"]) — language packs download on first use and are never chosen silently"]);
32
+ let modPromise;
33
+ const getModule = () => {
34
+ modPromise ??= Promise.resolve(options.tesseract ? options.tesseract() : import("tesseract.js")).catch((err) => {
35
+ throw new E_INVALID_MEDIA_PIPELINE_CONFIG([`the tesseract.js engine could not load its peer dependency "tesseract.js": ${isError(err) ? err.message : String(err)} — install it (pnpm add tesseract.js)`]);
36
+ });
37
+ return modPromise;
38
+ };
39
+ const convert = async (request) => {
40
+ const mod = await getModule();
41
+ const languages = request.options?.languages ?? options.languages;
42
+ const worker = await mod.createWorker(languages, void 0, {
43
+ ...options.langPath ? { langPath: options.langPath } : {},
44
+ ...options.cachePath ? { cachePath: options.cachePath } : {}
45
+ });
46
+ try {
47
+ const result = await worker.recognize(typeof globalThis.Buffer !== "undefined" ? globalThis.Buffer.from(request.bytes.buffer, request.bytes.byteOffset, request.bytes.byteLength) : new Blob([request.bytes], { type: request.mimeType }));
48
+ let text = result.data.text;
49
+ let mimeType = "text/plain";
50
+ if (request.to === "json") {
51
+ text = JSON.stringify({
52
+ text: result.data.text,
53
+ confidence: result.data.confidence
54
+ });
55
+ mimeType = "application/json";
56
+ } else if (request.to === "hocr") {
57
+ const hocr = result.data.hocr;
58
+ text = hocr ?? result.data.text;
59
+ mimeType = hocr ? "text/html" : "text/plain";
60
+ }
61
+ return { outputs: [{
62
+ bytes: new TextEncoder().encode(text),
63
+ mimeType
64
+ }] };
65
+ } finally {
66
+ await worker.terminate();
67
+ }
68
+ };
69
+ return {
70
+ id: "tesseract.js",
71
+ converts: [{
72
+ from: ["image/*"],
73
+ to: [
74
+ "txt",
75
+ "hocr",
76
+ "json"
77
+ ],
78
+ convert
79
+ }]
80
+ };
81
+ };
82
+ //#endregion
83
+ export { tesseractJsEngine };
84
+
85
+ //# sourceMappingURL=tesseract_js.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tesseract_js.mjs","names":[],"sources":["../../../../src/batteries/media/engines/tesseract_js.ts"],"sourcesContent":["/**\n * A cross-environment OCR {@link @nhtio/adk/batteries/media/contracts!MediaEngine}\n * backed by tesseract.js (WASM Tesseract — Node and browsers, no binary).\n *\n * @module @nhtio/adk/batteries/media/engines/tesseract_js\n *\n * @remarks\n * The local-by-default OCR engine. Language data files download on first use of each\n * language; point `langPath`/`cachePath` at a writable location to control where (the\n * factory requires `languages` up front so a deployment never silently fetches packs for\n * languages it didn't plan for). Workers are created per recognize call and terminated in\n * `finally` — slower than a pooled setup but leak-free by construction; consumers who need\n * pooling can BYO an engine that holds a worker.\n *\n * `tesseract.js` is an optional peer dependency, lazily imported on first actual use.\n *\n * Declares one convert capability: `image/*` to `txt`/`hocr`/`json` (OCR is a format\n * conversion — image in, text out). Language hints ride `request.options.languages`.\n */\n\nimport { isError } from '@nhtio/adk/guards'\nimport { E_INVALID_MEDIA_PIPELINE_CONFIG } from '../exceptions'\nimport type * as TesseractNS from 'tesseract.js'\nimport type { MediaEngine, ConvertRequest, ConvertResult } from '../contracts'\n\ntype TesseractModule = typeof TesseractNS\n\n/** Options for {@link tesseractJsEngine}. */\nexport interface TesseractJsEngineOptions {\n /** Languages to load, e.g. `['eng']`. REQUIRED — language packs download on first use. */\n languages: readonly string[]\n /** Where language data is fetched from / cached (forwarded to createWorker). */\n langPath?: string\n /** Local cache directory for downloaded language data. */\n cachePath?: string\n /** Override the module resolution. Default: `import('tesseract.js')`. */\n tesseract?: () => TesseractModule | Promise<TesseractModule>\n}\n\n/**\n * Construct the tesseract.js OCR engine.\n *\n * @param options - Languages (required) and data-path overrides.\n * @returns The engine.\n */\nexport const tesseractJsEngine = (options: TesseractJsEngineOptions): MediaEngine => {\n if (!Array.isArray(options?.languages) || options.languages.length === 0) {\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n 'tesseractJsEngine requires languages (e.g. [\"eng\"]) — language packs download on first use and are never chosen silently',\n ])\n }\n let modPromise: Promise<TesseractModule> | undefined\n const getModule = (): Promise<TesseractModule> => {\n modPromise ??= Promise.resolve(\n options.tesseract ? options.tesseract() : import('tesseract.js')\n ).catch((err) => {\n const detail = isError(err) ? err.message : String(err)\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n `the tesseract.js engine could not load its peer dependency \"tesseract.js\": ${detail} — install it (pnpm add tesseract.js)`,\n ])\n })\n return modPromise\n }\n\n const convert = async (request: ConvertRequest): Promise<ConvertResult> => {\n const mod = await getModule()\n const languages = (request.options?.languages ?? options.languages) as string[]\n const worker = await mod.createWorker(languages, undefined, {\n ...(options.langPath ? { langPath: options.langPath } : {}),\n ...(options.cachePath ? { cachePath: options.cachePath } : {}),\n })\n try {\n const result = await worker.recognize(\n // tesseract.js accepts Buffer/Blob/ImageLike; raw bytes work via Buffer in Node\n typeof globalThis.Buffer !== 'undefined'\n ? globalThis.Buffer.from(\n request.bytes.buffer,\n request.bytes.byteOffset,\n request.bytes.byteLength\n )\n : new Blob([request.bytes as BlobPart], { type: request.mimeType })\n )\n let text = result.data.text\n let mimeType = 'text/plain'\n if (request.to === 'json') {\n text = JSON.stringify({ text: result.data.text, confidence: result.data.confidence })\n mimeType = 'application/json'\n } else if (request.to === 'hocr') {\n // hocr requires opting into the output at recognize time in tesseract.js v5+;\n // fall back to text when unavailable rather than failing the read.\n const hocr = (result.data as { hocr?: string | null }).hocr\n text = hocr ?? result.data.text\n mimeType = hocr ? 'text/html' : 'text/plain'\n }\n return { outputs: [{ bytes: new TextEncoder().encode(text), mimeType }] }\n } finally {\n await worker.terminate()\n }\n }\n\n return {\n id: 'tesseract.js',\n converts: [\n {\n from: ['image/*'],\n to: ['txt', 'hocr', 'json'],\n convert,\n },\n ],\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAa,qBAAqB,YAAmD;CACnF,IAAI,CAAC,MAAM,QAAQ,SAAS,SAAS,KAAK,QAAQ,UAAU,WAAW,GACrE,MAAM,IAAI,gCAAgC,CACxC,4HACF,CAAC;CAEH,IAAI;CACJ,MAAM,kB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AU,CACR;GACE,MAAM,CAAC,SAAS;GAChB,IAAI;IAAC;IAAO;IAAQ;GAAM;GAC1B;EACF,CACF;CACF;AACF"}
@@ -0,0 +1,111 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ require("../../../chunk-Ble4zEEl.js");
3
+ const require_tool_registry = require("../../../tool_registry-CKJPze3j.js");
4
+ require("../../../guards.cjs");
5
+ const require_batteries_media_contracts = require("../contracts.cjs");
6
+ const require_exceptions = require("../../../exceptions-CQi_lNs1.js");
7
+ //#region src/batteries/media/engines/transformers_asr.ts
8
+ /**
9
+ * A cross-environment transcription {@link @nhtio/adk/batteries/media/contracts!MediaEngine}
10
+ * backed by `@huggingface/transformers` Whisper (ONNX in Node, WASM/WebGPU in browsers).
11
+ *
12
+ * @module @nhtio/adk/batteries/media/engines/transformers_asr
13
+ *
14
+ * @remarks
15
+ * The local-by-default speech-to-text engine: no external API, no binary. Declares one
16
+ * convert capability: the virtual `pcm` token to `txt`/`srt`/`vtt`/`json` (transcription is a
17
+ * format conversion — PCM in, text out). The Whisper model id is REQUIRED — models are
18
+ * multi-hundred-megabyte downloads on first use and the battery never triggers one silently
19
+ * (the loud-config rule). Input is 16 kHz mono PCM, exactly what the transcribe step
20
+ * supplies; `lang`/`translate` ride `request.options`. `srt`/`vtt` output is assembled from
21
+ * chunk timestamps; `json` returns the chunk structure verbatim.
22
+ *
23
+ * `@huggingface/transformers` is an optional peer dependency, lazily imported on first
24
+ * actual use.
25
+ */
26
+ var pad = (n, width = 2) => String(Math.floor(n)).padStart(width, "0");
27
+ var formatTimestamp = (seconds, separator) => {
28
+ const h = Math.floor(seconds / 3600);
29
+ const m = Math.floor(seconds % 3600 / 60);
30
+ const s = Math.floor(seconds % 60);
31
+ const ms = Math.floor(seconds % 1 * 1e3);
32
+ return `${pad(h)}:${pad(m)}:${pad(s)}${separator}${String(ms).padStart(3, "0")}`;
33
+ };
34
+ var toSubtitles = (chunks, kind) => {
35
+ const sep = kind === "srt" ? "," : ".";
36
+ const blocks = chunks.map((chunk, i) => {
37
+ const [start, end] = chunk.timestamp;
38
+ const range = `${formatTimestamp(start, sep)} --> ${formatTimestamp(end ?? start, sep)}`;
39
+ return kind === "srt" ? `${i + 1}\n${range}\n${chunk.text.trim()}` : `${range}\n${chunk.text.trim()}`;
40
+ });
41
+ return kind === "vtt" ? `WEBVTT\n\n${blocks.join("\n\n")}\n` : `${blocks.join("\n\n")}\n`;
42
+ };
43
+ /**
44
+ * Construct the transformers.js Whisper ASR engine.
45
+ *
46
+ * @param options - Model id (required) and overrides.
47
+ * @returns The engine.
48
+ */
49
+ var transformersAsrEngine = (options) => {
50
+ if (typeof options?.model !== "string" || options.model.length === 0) throw new require_exceptions.E_INVALID_MEDIA_PIPELINE_CONFIG(["transformersAsrEngine requires an explicit Whisper model id (e.g. onnx-community/whisper-base) — models are large downloads and are never chosen silently"]);
51
+ let pipePromise;
52
+ const getPipeline = () => {
53
+ pipePromise ??= (async () => {
54
+ let mod;
55
+ try {
56
+ mod = await (options.transformers ? options.transformers() : import("@huggingface/transformers"));
57
+ } catch (err) {
58
+ throw new require_exceptions.E_INVALID_MEDIA_PIPELINE_CONFIG([`the transformers ASR engine could not load its peer dependency "@huggingface/transformers": ${require_tool_registry.isError(err) ? err.message : String(err)} — install it (pnpm add @huggingface/transformers)`]);
59
+ }
60
+ return await mod.pipeline("automatic-speech-recognition", options.model, { ...options.pipelineOptions ?? {} });
61
+ })();
62
+ return pipePromise;
63
+ };
64
+ const convert = async (request) => {
65
+ const pipe = await getPipeline();
66
+ const lang = request.options?.lang;
67
+ const translate = request.options?.translate;
68
+ const wantsTimestamps = request.to === "srt" || request.to === "vtt" || request.to === "json";
69
+ const result = await pipe(require_batteries_media_contracts.bytesToPcm(request.bytes), {
70
+ ...lang ? { language: lang } : {},
71
+ ...translate ? { task: "translate" } : {},
72
+ ...wantsTimestamps ? { return_timestamps: true } : {},
73
+ chunk_length_s: 30
74
+ });
75
+ const output = Array.isArray(result) ? result[0] : result;
76
+ let text;
77
+ let mimeType = "text/plain";
78
+ if (request.to === "json") {
79
+ text = JSON.stringify({
80
+ text: output.text,
81
+ chunks: output.chunks ?? []
82
+ });
83
+ mimeType = "application/json";
84
+ } else if (request.to === "srt" || request.to === "vtt") text = toSubtitles(output.chunks ?? [{
85
+ timestamp: [0, null],
86
+ text: output.text
87
+ }], request.to);
88
+ else text = output.text.trim();
89
+ return { outputs: [{
90
+ bytes: new TextEncoder().encode(text),
91
+ mimeType
92
+ }] };
93
+ };
94
+ return {
95
+ id: "transformers-asr",
96
+ converts: [{
97
+ from: [require_batteries_media_contracts.PCM_MIME],
98
+ to: [
99
+ "txt",
100
+ "srt",
101
+ "vtt",
102
+ "json"
103
+ ],
104
+ convert
105
+ }]
106
+ };
107
+ };
108
+ //#endregion
109
+ exports.transformersAsrEngine = transformersAsrEngine;
110
+
111
+ //# sourceMappingURL=transformers_asr.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transformers_asr.cjs","names":[],"sources":["../../../../src/batteries/media/engines/transformers_asr.ts"],"sourcesContent":["/**\n * A cross-environment transcription {@link @nhtio/adk/batteries/media/contracts!MediaEngine}\n * backed by `@huggingface/transformers` Whisper (ONNX in Node, WASM/WebGPU in browsers).\n *\n * @module @nhtio/adk/batteries/media/engines/transformers_asr\n *\n * @remarks\n * The local-by-default speech-to-text engine: no external API, no binary. Declares one\n * convert capability: the virtual `pcm` token to `txt`/`srt`/`vtt`/`json` (transcription is a\n * format conversion — PCM in, text out). The Whisper model id is REQUIRED — models are\n * multi-hundred-megabyte downloads on first use and the battery never triggers one silently\n * (the loud-config rule). Input is 16 kHz mono PCM, exactly what the transcribe step\n * supplies; `lang`/`translate` ride `request.options`. `srt`/`vtt` output is assembled from\n * chunk timestamps; `json` returns the chunk structure verbatim.\n *\n * `@huggingface/transformers` is an optional peer dependency, lazily imported on first\n * actual use.\n */\n\nimport { isError } from '@nhtio/adk/guards'\nimport { bytesToPcm, PCM_MIME } from '../contracts'\nimport { E_INVALID_MEDIA_PIPELINE_CONFIG } from '../exceptions'\nimport type * as TransformersNS from '@huggingface/transformers'\nimport type { MediaEngine, ConvertRequest, ConvertResult } from '../contracts'\n\ntype TransformersModule = typeof TransformersNS\n\ninterface AsrChunk {\n timestamp: [number, number | null]\n text: string\n}\n\ninterface AsrPipelineOutput {\n text: string\n chunks?: AsrChunk[]\n}\n\ntype AsrPipelineFn = (\n audio: Float32Array,\n options: Record<string, unknown>\n) => Promise<AsrPipelineOutput | AsrPipelineOutput[]>\n\n/** Options for {@link transformersAsrEngine}. */\nexport interface TransformersAsrEngineOptions {\n /**\n * The Whisper model id, e.g. `onnx-community/whisper-base`. REQUIRED — no default, no\n * surprise downloads.\n */\n model: string\n /** Override the module resolution. Default: `import('@huggingface/transformers')`. */\n transformers?: () => TransformersModule | Promise<TransformersModule>\n /** Extra options forwarded to `pipeline()` (device, dtype, cache_dir…). */\n pipelineOptions?: Record<string, unknown>\n}\n\nconst pad = (n: number, width = 2): string => String(Math.floor(n)).padStart(width, '0')\n\nconst formatTimestamp = (seconds: number, separator: ',' | '.'): string => {\n const h = Math.floor(seconds / 3600)\n const m = Math.floor((seconds % 3600) / 60)\n const s = Math.floor(seconds % 60)\n const ms = Math.floor((seconds % 1) * 1000)\n return `${pad(h)}:${pad(m)}:${pad(s)}${separator}${String(ms).padStart(3, '0')}`\n}\n\nconst toSubtitles = (chunks: AsrChunk[], kind: 'srt' | 'vtt'): string => {\n const sep = kind === 'srt' ? ',' : '.'\n const blocks = chunks.map((chunk, i) => {\n const [start, end] = chunk.timestamp\n const range = `${formatTimestamp(start, sep)} --> ${formatTimestamp(end ?? start, sep)}`\n return kind === 'srt'\n ? `${i + 1}\\n${range}\\n${chunk.text.trim()}`\n : `${range}\\n${chunk.text.trim()}`\n })\n return kind === 'vtt' ? `WEBVTT\\n\\n${blocks.join('\\n\\n')}\\n` : `${blocks.join('\\n\\n')}\\n`\n}\n\n/**\n * Construct the transformers.js Whisper ASR engine.\n *\n * @param options - Model id (required) and overrides.\n * @returns The engine.\n */\nexport const transformersAsrEngine = (options: TransformersAsrEngineOptions): MediaEngine => {\n if (typeof options?.model !== 'string' || options.model.length === 0) {\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n 'transformersAsrEngine requires an explicit Whisper model id (e.g. onnx-community/whisper-base) — models are large downloads and are never chosen silently',\n ])\n }\n let pipePromise: Promise<AsrPipelineFn> | undefined\n const getPipeline = (): Promise<AsrPipelineFn> => {\n pipePromise ??= (async () => {\n let mod: TransformersModule\n try {\n mod = await (options.transformers\n ? options.transformers()\n : import('@huggingface/transformers'))\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n throw new E_INVALID_MEDIA_PIPELINE_CONFIG([\n `the transformers ASR engine could not load its peer dependency \"@huggingface/transformers\": ${detail} — install it (pnpm add @huggingface/transformers)`,\n ])\n }\n const pipe = await mod.pipeline('automatic-speech-recognition', options.model, {\n ...(options.pipelineOptions ?? {}),\n } as never)\n return pipe as unknown as AsrPipelineFn\n })()\n return pipePromise\n }\n\n const convert = async (request: ConvertRequest): Promise<ConvertResult> => {\n const pipe = await getPipeline()\n const lang = request.options?.lang\n const translate = request.options?.translate\n const wantsTimestamps = request.to === 'srt' || request.to === 'vtt' || request.to === 'json'\n const result = await pipe(bytesToPcm(request.bytes), {\n ...(lang ? { language: lang } : {}),\n ...(translate ? { task: 'translate' } : {}),\n ...(wantsTimestamps ? { return_timestamps: true } : {}),\n chunk_length_s: 30,\n })\n const output = Array.isArray(result) ? result[0] : result\n let text: string\n let mimeType = 'text/plain'\n if (request.to === 'json') {\n text = JSON.stringify({ text: output.text, chunks: output.chunks ?? [] })\n mimeType = 'application/json'\n } else if (request.to === 'srt' || request.to === 'vtt') {\n const chunks = output.chunks ?? [\n { timestamp: [0, null] as [number, null], text: output.text },\n ]\n text = toSubtitles(chunks, request.to)\n } else {\n text = output.text.trim()\n }\n return { outputs: [{ bytes: new TextEncoder().encode(text), mimeType }] }\n }\n\n return {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