shadow-claw 1.59.6 → 1.60.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 (358) hide show
  1. package/.well-known/mcp/server-card.json +1 -1
  2. package/.well-known/mcp.json +1 -1
  3. package/README.md +6 -2
  4. package/dist/cli/build/build.js +1 -1
  5. package/dist/cli/chunk-3C5izdQW.js +1 -0
  6. package/dist/cli/chunk-B-75h9gX.js +1 -0
  7. package/dist/cli/{chunk-C9o6lXP3.js → chunk-B7Kn-otm.js} +1 -1
  8. package/dist/cli/{chunk-YX32FcN7.js → chunk-BBczgswQ.js} +1 -1
  9. package/dist/cli/{chunk-DcNxjqH6.js → chunk-BE-lYWcn.js} +1 -1
  10. package/dist/cli/{chunk-DJqHK-qS.js → chunk-BECr0WxI.js} +11 -11
  11. package/dist/cli/chunk-BEz1PD1_.js +1 -0
  12. package/dist/cli/chunk-BLzI1Fp2.js +1 -0
  13. package/dist/cli/{chunk-yiVdvGCJ.js → chunk-BVSC1MNQ.js} +11 -11
  14. package/dist/cli/{chunk-CX2itile.js → chunk-BdWcep6o.js} +1 -1
  15. package/dist/cli/{chunk-DLde6nuO.js → chunk-BfTpnSS4.js} +1 -1
  16. package/dist/cli/{chunk-D2_eAO83.js → chunk-BgvqTf7w.js} +1 -1
  17. package/dist/cli/chunk-BwsJfUT3.js +1 -0
  18. package/dist/cli/{chunk--PFY91kE.js → chunk-C9b4b7c_.js} +1 -1
  19. package/dist/cli/{chunk-D3y7h9Xe.js → chunk-CAw9XYFe.js} +1 -1
  20. package/dist/cli/chunk-CFCcbFs2.js +396 -0
  21. package/dist/cli/{chunk-Cnjb8Usu.js → chunk-CTarF4FC.js} +1 -1
  22. package/dist/cli/{chunk-DM4xsTry.js → chunk-Cbq5hpjb.js} +4 -4
  23. package/dist/cli/chunk-CjTjKy_v.js +310 -0
  24. package/dist/cli/chunk-Cjyu4cr_.js +36 -0
  25. package/dist/cli/{chunk-DUGZPka_.js → chunk-ClMKygjZ.js} +1 -1
  26. package/dist/cli/chunk-Cppnq1KF.js +1 -0
  27. package/dist/cli/{chunk-DvemF16v.js → chunk-D9QCNFMO.js} +1 -1
  28. package/dist/cli/chunk-DB21BMqt.js +7 -0
  29. package/dist/cli/{chunk-_Vo-o_e3.js → chunk-DHoIWvCc.js} +1 -1
  30. package/dist/cli/chunk-DZEN9T5y.js +1 -0
  31. package/dist/cli/{chunk-5rLO4DWS.js → chunk-Dl14OyYO.js} +9 -9
  32. package/dist/cli/chunk-Dl_vv0dI.js +1 -0
  33. package/dist/cli/chunk-Dpmfhlyl.js +1 -0
  34. package/dist/cli/{chunk-BrR1DOBS.js → chunk-Du7Xtucq.js} +1 -1
  35. package/dist/cli/{chunk-Bc_weULz.js → chunk-DxcDFUi_.js} +1 -1
  36. package/dist/cli/{chunk-Dt7-hzJU.js → chunk-DyyEWbV7.js} +1 -1
  37. package/dist/cli/chunk-N0x3mXU0.js +1 -0
  38. package/dist/cli/{chunk-CGoE4llV.js → chunk-V-w0Bata.js} +1 -1
  39. package/dist/cli/{chunk-C8DBACtx.js → chunk-ZxDxSSn-.js} +1 -1
  40. package/dist/cli/chunk-lPvFUkd5.js +7 -0
  41. package/dist/cli/{chunk-Ctg5L55n.js → chunk-n5s-sCdU.js} +1 -1
  42. package/dist/cli/{chunk-Dw8GndPD.js → chunk-nD9VPVMq.js} +1 -1
  43. package/dist/cli/{chunk-Cq_kQohv.js → chunk-rFuy8aS_.js} +1 -1
  44. package/dist/cli/{chunk-Bq38OubR.js → chunk-wjM6JXWa.js} +1 -1
  45. package/dist/cli/{chunk-3wTukVof.js → chunk-zcES9rut.js} +1 -1
  46. package/dist/cli/cli.js +3 -3
  47. package/dist/headless-agent.js +2 -2
  48. package/dist/lib/{app-routes-DJdIjp2V.js → app-routes-BXiRvlNl.js} +7 -25
  49. package/dist/lib/{app-routes-DJdIjp2V.js.map → app-routes-BXiRvlNl.js.map} +1 -1
  50. package/dist/lib/{attachment-capabilities-Dbb-4ZP5.js → attachment-capabilities-BjkEPip8.js} +2 -2
  51. package/dist/lib/{attachment-capabilities-Dbb-4ZP5.js.map → attachment-capabilities-BjkEPip8.js.map} +1 -1
  52. package/dist/lib/{channel-Dlru5ofR.js → channel-DB77spML.js} +3 -3
  53. package/dist/lib/{channel-Dlru5ofR.js.map → channel-DB77spML.js.map} +1 -1
  54. package/dist/lib/{chat-template-BuuLY8l7.js → chat-template-DPEKGJhB.js} +2 -2
  55. package/dist/lib/{chat-template-BuuLY8l7.js.map → chat-template-DPEKGJhB.js.map} +1 -1
  56. package/dist/lib/{compact-context-BtR55YPU.js → compact-context-Q9t9aL1e.js} +19 -19
  57. package/dist/lib/{compact-context-BtR55YPU.js.map → compact-context-Q9t9aL1e.js.map} +1 -1
  58. package/dist/lib/components/common/shadow-claw-provider-model-picker.js +1 -1
  59. package/dist/lib/components/index.js +27 -27
  60. package/dist/lib/components/settings/shadow-claw-accounts.js +1 -1
  61. package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
  62. package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
  63. package/dist/lib/components/settings/shadow-claw-git.js +1 -1
  64. package/dist/lib/components/settings/shadow-claw-integrations.js +1 -1
  65. package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
  66. package/dist/lib/components/settings/shadow-claw-mcp-remote.js +1 -1
  67. package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
  68. package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
  69. package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
  70. package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
  71. package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
  72. package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
  73. package/dist/lib/components/shadow-claw-a2ui.js +1 -1
  74. package/dist/lib/components/shadow-claw-accounts.js +1 -1
  75. package/dist/lib/components/shadow-claw-channel-config.js +1 -1
  76. package/dist/lib/components/shadow-claw-channels.js +1 -1
  77. package/dist/lib/components/shadow-claw-chat.js +1 -1
  78. package/dist/lib/components/shadow-claw-control-plane.js +1 -1
  79. package/dist/lib/components/shadow-claw-conversations.js +1 -1
  80. package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
  81. package/dist/lib/components/shadow-claw-files.js +1 -1
  82. package/dist/lib/components/shadow-claw-git.js +1 -1
  83. package/dist/lib/components/shadow-claw-integrations.js +1 -1
  84. package/dist/lib/components/shadow-claw-llm.js +1 -1
  85. package/dist/lib/components/shadow-claw-mcp-remote.js +1 -1
  86. package/dist/lib/components/shadow-claw-networking.js +1 -1
  87. package/dist/lib/components/shadow-claw-notifications.js +1 -1
  88. package/dist/lib/components/shadow-claw-page-header.js +1 -1
  89. package/dist/lib/components/shadow-claw-pages.js +1 -1
  90. package/dist/lib/components/shadow-claw-peerjs.js +1 -1
  91. package/dist/lib/components/shadow-claw-provider-model-picker.js +1 -1
  92. package/dist/lib/components/shadow-claw-settings.js +1 -1
  93. package/dist/lib/components/shadow-claw-storage.js +1 -1
  94. package/dist/lib/components/shadow-claw-task-server.js +1 -1
  95. package/dist/lib/components/shadow-claw-tasks.js +1 -1
  96. package/dist/lib/components/shadow-claw-terminal.js +1 -1
  97. package/dist/lib/components/shadow-claw-tools.js +1 -1
  98. package/dist/lib/components/shadow-claw-webvm.js +1 -1
  99. package/dist/lib/components/shadow-claw.js +1 -1
  100. package/dist/lib/{config-DxNI3TlW.js → config-BrHR97zt.js} +2 -2
  101. package/dist/lib/{config-DxNI3TlW.js.map → config-BrHR97zt.js.map} +1 -1
  102. package/dist/lib/{configure-peer-js-ChDhOZU4.js → configure-peer-js-CgFiwoxY.js} +3 -3
  103. package/dist/lib/{configure-peer-js-ChDhOZU4.js.map → configure-peer-js-CgFiwoxY.js.map} +1 -1
  104. package/dist/lib/{connections-DC4NZkJE.js → connections-C1FWsBsE.js} +2 -2
  105. package/dist/lib/{connections-DC4NZkJE.js.map → connections-C1FWsBsE.js.map} +1 -1
  106. package/dist/lib/content/build-attachment-content-blocks.d.ts +2 -0
  107. package/dist/lib/{credentials-5vpz0XPk.js → credentials-CZbngHXW.js} +2 -2
  108. package/dist/lib/{credentials-5vpz0XPk.js.map → credentials-CZbngHXW.js.map} +1 -1
  109. package/dist/lib/{discover-skills-CD0sKvAI.js → discover-skills-CXyaWHKi.js} +13 -13
  110. package/dist/lib/{discover-skills-CD0sKvAI.js.map → discover-skills-CXyaWHKi.js.map} +1 -1
  111. package/dist/lib/{download-group-file-Dk3qaxhJ.js → download-group-file-D0wgg10Q.js} +2 -2
  112. package/dist/lib/{download-group-file-Dk3qaxhJ.js.map → download-group-file-D0wgg10Q.js.map} +1 -1
  113. package/dist/lib/{file-viewer-B4pRW-_G.js → file-viewer-DOfvX6yy.js} +5 -5
  114. package/dist/lib/{file-viewer-B4pRW-_G.js.map → file-viewer-DOfvX6yy.js.map} +1 -1
  115. package/dist/lib/{get-or-create-subscriber-id-HCcgDEPz.js → get-or-create-subscriber-id-wyzaML7Z.js} +2 -2
  116. package/dist/lib/{get-or-create-subscriber-id-HCcgDEPz.js.map → get-or-create-subscriber-id-wyzaML7Z.js.map} +1 -1
  117. package/dist/lib/{git-B3Q1euc5.js → git-CogDRlEz.js} +5 -5
  118. package/dist/lib/{git-B3Q1euc5.js.map → git-CogDRlEz.js.map} +1 -1
  119. package/dist/lib/{iframe-bridge-scripts-D8iuFhUk.js → iframe-bridge-scripts-Dx825LLG.js} +2 -2
  120. package/dist/lib/{iframe-bridge-scripts-D8iuFhUk.js.map → iframe-bridge-scripts-Dx825LLG.js.map} +1 -1
  121. package/dist/lib/index.js +28 -28
  122. package/dist/lib/{init-chat-split-resize-B0ODULx9.js → init-chat-split-resize-Cc0bd2z9.js} +2 -2
  123. package/dist/lib/{init-chat-split-resize-B0ODULx9.js.map → init-chat-split-resize-Cc0bd2z9.js.map} +1 -1
  124. package/dist/lib/{init-control-plane-C1FRRmjC.js → init-control-plane-CEGdzgWX.js} +15 -15
  125. package/dist/lib/{init-control-plane-C1FRRmjC.js.map → init-control-plane-CEGdzgWX.js.map} +1 -1
  126. package/dist/lib/{invoke-agent-CzN7sVh-.js → invoke-agent-cac3gCsj.js} +11 -11
  127. package/dist/lib/{invoke-agent-CzN7sVh-.js.map → invoke-agent-cac3gCsj.js.map} +1 -1
  128. package/dist/lib/{markdown-mbNo7cV3.js → markdown--6vTAPEH.js} +2 -2
  129. package/dist/lib/{markdown-mbNo7cV3.js.map → markdown--6vTAPEH.js.map} +1 -1
  130. package/dist/lib/{mcp-reconnect-3T7yWGEY.js → mcp-reconnect-BeqQvNWO.js} +3 -3
  131. package/dist/lib/{mcp-reconnect-3T7yWGEY.js.map → mcp-reconnect-BeqQvNWO.js.map} +1 -1
  132. package/dist/lib/{model-ranking-DGNSWYwN.js → model-ranking-BhsJV7vb.js} +2 -2
  133. package/dist/lib/{model-ranking-DGNSWYwN.js.map → model-ranking-BhsJV7vb.js.map} +1 -1
  134. package/dist/lib/{move-group-entry-NMTJ59M9.js → move-group-entry-D8dptMg0.js} +5 -5
  135. package/dist/lib/{move-group-entry-NMTJ59M9.js.map → move-group-entry-D8dptMg0.js.map} +1 -1
  136. package/dist/lib/{orchestrator-B8FV1V7x.js → orchestrator-BBAwy9Nm.js} +24 -24
  137. package/dist/lib/{orchestrator-B8FV1V7x.js.map → orchestrator-BBAwy9Nm.js.map} +1 -1
  138. package/dist/lib/{orchestrator-i_QJ-o22.js → orchestrator-cRBe3lhq.js} +11 -11
  139. package/dist/lib/orchestrator-cRBe3lhq.js.map +1 -0
  140. package/dist/lib/{parse-path-DPCn-HwI.js → parse-path-BOHQP_IQ.js} +3 -3
  141. package/dist/lib/{parse-path-DPCn-HwI.js.map → parse-path-BOHQP_IQ.js.map} +1 -1
  142. package/dist/lib/{peerjs-z5zeioPV.js → peerjs-BLg8aGUj.js} +8 -8
  143. package/dist/lib/{peerjs-z5zeioPV.js.map → peerjs-BLg8aGUj.js.map} +1 -1
  144. package/dist/lib/{process-peer-query-param-CJp7w7AU.js → process-peer-query-param-BnsVnxzH.js} +5 -5
  145. package/dist/lib/{process-peer-query-param-CJp7w7AU.js.map → process-peer-query-param-BnsVnxzH.js.map} +1 -1
  146. package/dist/lib/{process-pending-shared-payloads-B6_TlBFA.js → process-pending-shared-payloads-DBZfZOOa.js} +4 -4
  147. package/dist/lib/{process-pending-shared-payloads-B6_TlBFA.js.map → process-pending-shared-payloads-DBZfZOOa.js.map} +1 -1
  148. package/dist/lib/{process-room-query-param-C3FFGGn6.js → process-room-query-param-B8EYg_-r.js} +4 -4
  149. package/dist/lib/{process-room-query-param-C3FFGGn6.js.map → process-room-query-param-B8EYg_-r.js.map} +1 -1
  150. package/dist/lib/{provider-DcQZypu5.js → provider-BC9KPI14.js} +3 -3
  151. package/dist/lib/{provider-DcQZypu5.js.map → provider-BC9KPI14.js.map} +1 -1
  152. package/dist/lib/{push-client-Cx5rMs6J.js → push-client-CAm6UMvE.js} +5 -5
  153. package/dist/lib/{push-client-Cx5rMs6J.js.map → push-client-CAm6UMvE.js.map} +1 -1
  154. package/dist/lib/{read-group-file-bytes-CXOG_YyM.js → read-group-file-bytes-UQIk1eJG.js} +2 -2
  155. package/dist/lib/{read-group-file-bytes-CXOG_YyM.js.map → read-group-file-bytes-UQIk1eJG.js.map} +1 -1
  156. package/dist/lib/{rooms-CwlkYLDU.js → rooms-Dzphx3rK.js} +2 -2
  157. package/dist/lib/{rooms-CwlkYLDU.js.map → rooms-Dzphx3rK.js.map} +1 -1
  158. package/dist/lib/{shadow-claw-DoQ7fgl5.js → shadow-claw-CGl8tXtG.js} +17 -20
  159. package/dist/lib/shadow-claw-CGl8tXtG.js.map +1 -0
  160. package/dist/lib/{shadow-claw-a2ui-Br6qJMs1.js → shadow-claw-a2ui-lG0vQbW8.js} +2 -2
  161. package/dist/lib/{shadow-claw-a2ui-Br6qJMs1.js.map → shadow-claw-a2ui-lG0vQbW8.js.map} +1 -1
  162. package/dist/lib/{shadow-claw-accounts-BTDILfWw.js → shadow-claw-accounts-CkqyCxwp.js} +3 -3
  163. package/dist/lib/{shadow-claw-accounts-BTDILfWw.js.map → shadow-claw-accounts-CkqyCxwp.js.map} +1 -1
  164. package/dist/lib/{shadow-claw-channel-config-IKiL34tI.js → shadow-claw-channel-config-BNIWCdsL.js} +4 -4
  165. package/dist/lib/{shadow-claw-channel-config-IKiL34tI.js.map → shadow-claw-channel-config-BNIWCdsL.js.map} +1 -1
  166. package/dist/lib/{shadow-claw-channels-JgEzuHWK.js → shadow-claw-channels-C2QSn4Ew.js} +3 -3
  167. package/dist/lib/{shadow-claw-channels-JgEzuHWK.js.map → shadow-claw-channels-C2QSn4Ew.js.map} +1 -1
  168. package/dist/lib/{shadow-claw-chat-SGUDT31r.js → shadow-claw-chat-Wx3y9y6c.js} +15 -15
  169. package/dist/lib/{shadow-claw-chat-SGUDT31r.js.map → shadow-claw-chat-Wx3y9y6c.js.map} +1 -1
  170. package/dist/lib/{shadow-claw-control-plane-CRWFZ3vD.js → shadow-claw-control-plane-D5E4cFGu.js} +7 -7
  171. package/dist/lib/{shadow-claw-control-plane-CRWFZ3vD.js.map → shadow-claw-control-plane-D5E4cFGu.js.map} +1 -1
  172. package/dist/lib/{shadow-claw-conversations-D23GJ7qo.js → shadow-claw-conversations-BtDv7GRW.js} +7 -7
  173. package/dist/lib/{shadow-claw-conversations-D23GJ7qo.js.map → shadow-claw-conversations-BtDv7GRW.js.map} +1 -1
  174. package/dist/lib/{shadow-claw-file-viewer-C1V8WTiU.js → shadow-claw-file-viewer-CG40kwWV.js} +10 -10
  175. package/dist/lib/{shadow-claw-file-viewer-C1V8WTiU.js.map → shadow-claw-file-viewer-CG40kwWV.js.map} +1 -1
  176. package/dist/lib/{shadow-claw-files-DN7irmE1.js → shadow-claw-files-BOUULrlX.js} +11 -11
  177. package/dist/lib/{shadow-claw-files-DN7irmE1.js.map → shadow-claw-files-BOUULrlX.js.map} +1 -1
  178. package/dist/lib/{shadow-claw-git-D-1oIh65.js → shadow-claw-git-BeHV73_9.js} +6 -6
  179. package/dist/lib/{shadow-claw-git-D-1oIh65.js.map → shadow-claw-git-BeHV73_9.js.map} +1 -1
  180. package/dist/lib/{shadow-claw-integrations-CZjnm7cM.js → shadow-claw-integrations-RZZ-m-Id.js} +4 -4
  181. package/dist/lib/{shadow-claw-integrations-CZjnm7cM.js.map → shadow-claw-integrations-RZZ-m-Id.js.map} +1 -1
  182. package/dist/lib/{shadow-claw-llm-4Gefh5FN.js → shadow-claw-llm-KONyWKZM.js} +9 -9
  183. package/dist/lib/{shadow-claw-llm-4Gefh5FN.js.map → shadow-claw-llm-KONyWKZM.js.map} +1 -1
  184. package/dist/lib/{shadow-claw-mcp-remote-B9ssb3YV.js → shadow-claw-mcp-remote-BKFROurv.js} +4 -4
  185. package/dist/lib/{shadow-claw-mcp-remote-B9ssb3YV.js.map → shadow-claw-mcp-remote-BKFROurv.js.map} +1 -1
  186. package/dist/lib/{shadow-claw-networking-BN5BB4hb.js → shadow-claw-networking-Diy3JJkc.js} +2 -2
  187. package/dist/lib/{shadow-claw-networking-BN5BB4hb.js.map → shadow-claw-networking-Diy3JJkc.js.map} +1 -1
  188. package/dist/lib/{shadow-claw-notifications-71KARtkY.js → shadow-claw-notifications-C-upPa-4.js} +3 -3
  189. package/dist/lib/{shadow-claw-notifications-71KARtkY.js.map → shadow-claw-notifications-C-upPa-4.js.map} +1 -1
  190. package/dist/lib/{shadow-claw-page-header-DMGO-TSe.js → shadow-claw-page-header-C_Qr3xZM.js} +2 -2
  191. package/dist/lib/{shadow-claw-page-header-DMGO-TSe.js.map → shadow-claw-page-header-C_Qr3xZM.js.map} +1 -1
  192. package/dist/lib/{shadow-claw-pages-BiRM6qiA.js → shadow-claw-pages-CfAjUKgd.js} +11 -11
  193. package/dist/lib/{shadow-claw-pages-BiRM6qiA.js.map → shadow-claw-pages-CfAjUKgd.js.map} +1 -1
  194. package/dist/lib/{shadow-claw-peerjs-BZu7jNSe.js → shadow-claw-peerjs-t4YibS9s.js} +6 -6
  195. package/dist/lib/{shadow-claw-peerjs-BZu7jNSe.js.map → shadow-claw-peerjs-t4YibS9s.js.map} +1 -1
  196. package/dist/lib/{shadow-claw-provider-model-picker-BXYXEobD.js → shadow-claw-provider-model-picker-B-Ct4yW-.js} +2 -2
  197. package/dist/lib/{shadow-claw-provider-model-picker-BXYXEobD.js.map → shadow-claw-provider-model-picker-B-Ct4yW-.js.map} +1 -1
  198. package/dist/lib/{shadow-claw-settings-CcT5EK08.js → shadow-claw-settings-Cg5V0e9g.js} +7 -7
  199. package/dist/lib/{shadow-claw-settings-CcT5EK08.js.map → shadow-claw-settings-Cg5V0e9g.js.map} +1 -1
  200. package/dist/lib/{shadow-claw-storage-eTOpbvpi.js → shadow-claw-storage-C7tCnsSG.js} +5 -5
  201. package/dist/lib/{shadow-claw-storage-eTOpbvpi.js.map → shadow-claw-storage-C7tCnsSG.js.map} +1 -1
  202. package/dist/lib/{shadow-claw-task-server-DFImTUbw.js → shadow-claw-task-server-BObsRdf8.js} +2 -2
  203. package/dist/lib/{shadow-claw-task-server-DFImTUbw.js.map → shadow-claw-task-server-BObsRdf8.js.map} +1 -1
  204. package/dist/lib/{shadow-claw-tasks-BjaxsmUx.js → shadow-claw-tasks-B2EEqrcY.js} +9 -9
  205. package/dist/lib/{shadow-claw-tasks-BjaxsmUx.js.map → shadow-claw-tasks-B2EEqrcY.js.map} +1 -1
  206. package/dist/lib/{shadow-claw-terminal-C-4wreFe.js → shadow-claw-terminal-DSHfO2b9.js} +2 -2
  207. package/dist/lib/{shadow-claw-terminal-C-4wreFe.js.map → shadow-claw-terminal-DSHfO2b9.js.map} +1 -1
  208. package/dist/lib/{shadow-claw-tools-COdrGZJk.js → shadow-claw-tools-DwPBADua.js} +7 -7
  209. package/dist/lib/{shadow-claw-tools-COdrGZJk.js.map → shadow-claw-tools-DwPBADua.js.map} +1 -1
  210. package/dist/lib/{shadow-claw-webvm-sxqVjO0L.js → shadow-claw-webvm-CY4qGaMB.js} +3 -3
  211. package/dist/lib/{shadow-claw-webvm-sxqVjO0L.js.map → shadow-claw-webvm-CY4qGaMB.js.map} +1 -1
  212. package/dist/lib/{sync-web-mcp-registration-D4hdUwtv.js → sync-web-mcp-registration-BiOZvW-R.js} +6 -6
  213. package/dist/lib/{sync-web-mcp-registration-D4hdUwtv.js.map → sync-web-mcp-registration-BiOZvW-R.js.map} +1 -1
  214. package/dist/lib/{system-prompt-DT_KeYaL.js → system-prompt-CxJ3Nx4c.js} +9 -8
  215. package/dist/lib/system-prompt-CxJ3Nx4c.js.map +1 -0
  216. package/dist/lib/{tools-Beuyh8y1.js → tools-B8OJ4sMF.js} +4 -4
  217. package/dist/lib/{tools-Beuyh8y1.js.map → tools-B8OJ4sMF.js.map} +1 -1
  218. package/dist/lib/{transformers-DydnReu4.js → transformers-BMURofG6.js} +2 -2
  219. package/dist/lib/{transformers-DydnReu4.js.map → transformers-BMURofG6.js.map} +1 -1
  220. package/dist/lib/{trusted-types-CfwZl_rr.js → trusted-types-HwsGS5Nj.js} +19 -17
  221. package/dist/lib/{trusted-types-CfwZl_rr.js.map → trusted-types-HwsGS5Nj.js.map} +1 -1
  222. package/dist/lib/{upload-group-file-BbBzjTcN.js → upload-group-file-CJpoNjEb.js} +3 -3
  223. package/dist/lib/{upload-group-file-BbBzjTcN.js.map → upload-group-file-CJpoNjEb.js.map} +1 -1
  224. package/dist/lib/utils/index.js +1 -1
  225. package/dist/lib/utils/namespaced-storage.js +1 -1
  226. package/dist/lib/utils/runtime-assets.js +1 -1
  227. package/dist/lib/utils/utils.js +1 -1
  228. package/dist/lib/{webmcp-DCfAFiIO.js → webmcp-BoMTvgmX.js} +3 -3
  229. package/dist/lib/{webmcp-DCfAFiIO.js.map → webmcp-BoMTvgmX.js.map} +1 -1
  230. package/dist/lib/{write-group-file-bytes-Ccn-VFUU.js → write-group-file-bytes-CNT7DqOZ.js} +3 -3
  231. package/dist/lib/{write-group-file-bytes-Ccn-VFUU.js.map → write-group-file-bytes-CNT7DqOZ.js.map} +1 -1
  232. package/dist/public/.well-known/mcp/server-card.json +1 -1
  233. package/dist/public/.well-known/mcp.json +1 -1
  234. package/dist/public/AGENTS.md +3 -1
  235. package/dist/public/README.md +6 -2
  236. package/dist/public/agent.worker.js +1 -1
  237. package/dist/public/attachment-capabilities-AdwXt3--.js +1 -0
  238. package/dist/public/{channel-BylT3rJC.js → channel-DIpDQekL.js} +1 -1
  239. package/dist/public/{chat-template-DPHJy7tr.js → chat-template-CXKs8lFR.js} +1 -1
  240. package/dist/public/compact-context-BQ2ZXoAc.js +5 -0
  241. package/dist/public/{compact-context-BINQh64w.js → compact-context-dHitmPsV.js} +2 -2
  242. package/dist/public/config-C16fFWtP.js +1 -0
  243. package/dist/public/{configure-peer-js-DChhcOfe.js → configure-peer-js-DV1rqvFX.js} +1 -1
  244. package/dist/public/{connections-CHaw0VqP.js → connections-Dxwj8yK_.js} +1 -1
  245. package/dist/public/{create-model-cache-fetch-DQebkoPL.js → create-model-cache-fetch-B0mSCEk6.js} +1 -1
  246. package/dist/public/{credentials-CgVqS119.js → credentials-CJUQ5Ep2.js} +1 -1
  247. package/dist/public/{custom-element-security-kiDhPfb8.js → custom-element-security-B2daIE5r.js} +2 -2
  248. package/dist/public/{discover-skills-Cvmx5I9V.js → discover-skills-BWJB8HUA.js} +6 -6
  249. package/dist/public/docs/architecture/overview.md +1 -1
  250. package/dist/public/docs/example/article/index.html +29 -30
  251. package/dist/public/docs/example/article.html +29 -30
  252. package/dist/public/docs/publishing/index.html +29 -30
  253. package/dist/public/docs/publishing.html +29 -30
  254. package/dist/public/docs/skill-creator/index.html +29 -30
  255. package/dist/public/docs/skill-creator.html +29 -30
  256. package/dist/public/docs/subsystems/attachment-capabilities.md +14 -1
  257. package/dist/public/docs/subsystems/cli.md +95 -51
  258. package/dist/public/docs/subsystems/pages.md +5 -0
  259. package/dist/public/{download-group-file-BapoRgfU.js → download-group-file-BkMH-JKi.js} +1 -1
  260. package/dist/public/e2e/README.md +1 -1
  261. package/dist/public/{e2e-bridge-C0g8vZKr.js → e2e-bridge-lP2qqiv3.js} +1 -1
  262. package/dist/public/get-group-dir-D--BiEyk.js +1 -0
  263. package/dist/public/{get-or-create-subscriber-id-GvRZYXwA.js → get-or-create-subscriber-id-jVHnQfbr.js} +1 -1
  264. package/dist/public/{git-CaAAZfVd.js → git-DjmQ16rm.js} +2 -2
  265. package/dist/public/{iframe-bridge-scripts-BnqtKhE4.js → iframe-bridge-scripts-CO0izGjW.js} +1 -1
  266. package/dist/public/index.html +29 -30
  267. package/dist/public/index.js +1 -1
  268. package/dist/public/{init-chat-split-resize-Btonoy8u.js → init-chat-split-resize-C8AqCCiK.js} +1 -1
  269. package/dist/public/init-control-plane-Ctz7FI8M.js +1 -0
  270. package/dist/public/{invoke-agent-B3Osw6K7.js → invoke-agent-C_geruwq.js} +1 -1
  271. package/dist/public/llms.txt +1 -1
  272. package/dist/public/main/index.html +29 -30
  273. package/dist/public/main/memory/index.html +29 -30
  274. package/dist/public/main/memory.html +29 -30
  275. package/dist/public/main.html +29 -30
  276. package/dist/public/{markdown-CPbU4r1U.js → markdown-CDSb5Hrl.js} +1 -1
  277. package/dist/public/{mcp-reconnect-CzROVsXG.js → mcp-reconnect-iPZPihwX.js} +1 -1
  278. package/dist/public/{memory-storage-BkoMlxOr.js → memory-storage-2m7KZ-aP.js} +1 -1
  279. package/dist/public/{model-ranking-CK0iBo3Z.js → model-ranking-BgOSaNIy.js} +1 -1
  280. package/dist/public/{move-group-entry-CTxoq7lw.js → move-group-entry-QQ9Hkk54.js} +1 -1
  281. package/dist/public/{orchestrator-BrDjQbGf.js → orchestrator-C1kaTltu.js} +2 -2
  282. package/dist/public/orchestrator-Li1UAsv7.js +63 -0
  283. package/dist/public/{peerjs-CgF4Iz5W.js → peerjs-DbBryE-9.js} +1 -1
  284. package/dist/public/{process-peer-query-param-BL2k0Hu-.js → process-peer-query-param-DQIgr3KL.js} +1 -1
  285. package/dist/public/{process-pending-shared-payloads-C1AgGvn8.js → process-pending-shared-payloads-Ctb-TFqB.js} +1 -1
  286. package/dist/public/{process-room-query-param-DM0QCq3_.js → process-room-query-param-F-XnIVoZ.js} +1 -1
  287. package/dist/public/provider-YPZmsuHR.js +1 -0
  288. package/dist/public/{push-client-DJEOz7bi.js → push-client-DRx9Eggz.js} +1 -1
  289. package/dist/public/{rooms-C6LXIJl4.js → rooms-BurBI7is.js} +1 -1
  290. package/dist/public/service-worker/init.js +1 -1
  291. package/dist/public/service-worker.js +1 -1
  292. package/dist/public/shadow-claw-Bg9AQ5x_.js +1176 -0
  293. package/dist/public/{shadow-claw-accounts--4hd_oCz.js → shadow-claw-accounts-B3mjYI0M.js} +1 -1
  294. package/dist/public/{shadow-claw-card-IbNlZAdK.js → shadow-claw-card-tcXRS1GF.js} +1 -1
  295. package/dist/public/{shadow-claw-channels-Vq_pPGa2.js → shadow-claw-channels-BiSfLvWv.js} +1 -1
  296. package/dist/public/{shadow-claw-chat-D7_GS25e.js → shadow-claw-chat-N5jMsXZZ.js} +3 -3
  297. package/dist/public/{shadow-claw-control-plane-WTMEV8_p.js → shadow-claw-control-plane-DFVe_Xdq.js} +2 -2
  298. package/dist/public/{shadow-claw-conversations-CLQgU1IT.js → shadow-claw-conversations-wAR06_ya.js} +1 -1
  299. package/dist/public/{shadow-claw-empty-state-D4CrFGsN.js → shadow-claw-empty-state-CnPm3NVM.js} +1 -1
  300. package/dist/public/{shadow-claw-file-viewer-BhqiqLWQ.js → shadow-claw-file-viewer-sZN_FCDW.js} +4 -4
  301. package/dist/public/{shadow-claw-files-senDiG9l.js → shadow-claw-files-CnvkCbd4.js} +2 -2
  302. package/dist/public/{shadow-claw-git-DOOCqY23.js → shadow-claw-git-BBHfClGk.js} +2 -2
  303. package/dist/public/{shadow-claw-integrations-Bsvc3Agq.js → shadow-claw-integrations-DvdBqzRJ.js} +1 -1
  304. package/dist/public/{shadow-claw-llm-actYICAk.js → shadow-claw-llm-YfohG519.js} +2 -2
  305. package/dist/public/{shadow-claw-mcp-remote-BYUgrK3v.js → shadow-claw-mcp-remote-BAVbf5pi.js} +1 -1
  306. package/dist/public/{shadow-claw-networking-Dk3p5Ny_.js → shadow-claw-networking-CZ4LWPW7.js} +1 -1
  307. package/dist/public/{shadow-claw-notifications-CzPAlay8.js → shadow-claw-notifications-BHwyREkG.js} +1 -1
  308. package/dist/public/{shadow-claw-page-header-CjJpVkyL.js → shadow-claw-page-header-De6Qf6eY.js} +1 -1
  309. package/dist/public/{shadow-claw-page-header-action-button-2DH5O1TD.js → shadow-claw-page-header-action-button-FSOhTc9z.js} +1 -1
  310. package/dist/public/{shadow-claw-pages-3r5I-wI8.js → shadow-claw-pages-D_oPyDca.js} +6 -6
  311. package/dist/public/{shadow-claw-pdf-viewer-BiCEwsoY.js → shadow-claw-pdf-viewer-CrU4wqRq.js} +1 -1
  312. package/dist/public/{shadow-claw-settings-DgB9RSZN.js → shadow-claw-settings-DkUhvxVr.js} +2 -2
  313. package/dist/public/{shadow-claw-storage-JB_43nd8.js → shadow-claw-storage-D0o56Tjw.js} +1 -1
  314. package/dist/public/{shadow-claw-task-server-oi5UIxdA.js → shadow-claw-task-server-4rkroO9K.js} +1 -1
  315. package/dist/public/{shadow-claw-tasks-CnyiOt81.js → shadow-claw-tasks-BdP7lmvu.js} +3 -3
  316. package/dist/public/{shadow-claw-terminal-BC3RynHt.js → shadow-claw-terminal-DVHX7Fsu.js} +1 -1
  317. package/dist/public/{shadow-claw-toast-YjG--2Za.js → shadow-claw-toast-B9Y9tSkW.js} +1 -1
  318. package/dist/public/{shadow-claw-tools-Bbwk4vlT.js → shadow-claw-tools-BwwY53Lr.js} +1 -1
  319. package/dist/public/{shadow-claw-webvm-HZqzl2H5.js → shadow-claw-webvm-CXGdkCNM.js} +1 -1
  320. package/dist/public/{sync-web-mcp-registration-BaH2nAP0.js → sync-web-mcp-registration-DVK_IhXZ.js} +1 -1
  321. package/dist/public/{system-prompt-Dck3N8T0.js → system-prompt-BmswoQwF.js} +2 -2
  322. package/dist/public/{tools-DHA1dK2I.js → tools-D-52Zmfc.js} +1 -1
  323. package/dist/public/{transformers-C-DuTM2K.js → transformers-CQ9ss9rD.js} +1 -1
  324. package/dist/public/{upload-group-file-Cejr3zo1.js → upload-group-file-A8kB7lvO.js} +1 -1
  325. package/dist/public/{webmcp-CMRtu57-.js → webmcp-DIUZjVF5.js} +1 -1
  326. package/dist/public/{workbox-92eae37e.js → workbox-e4022e15.js} +1 -1
  327. package/dist/public/{write-group-file-CmJuVQNO.js → write-group-file-R67DjJ-q.js} +1 -1
  328. package/dist/public/{write-group-file-bytes-Cejr3zo1.js → write-group-file-bytes-A8kB7lvO.js} +1 -1
  329. package/dist/public/{zip-reader-CuQ13eLe.js → zip-reader-JHoTbATw.js} +1 -1
  330. package/dist/server.js +6 -6
  331. package/package.json +1 -1
  332. package/dist/cli/chunk-2gZFafgY.js +0 -1
  333. package/dist/cli/chunk-BFziiMKt.js +0 -7
  334. package/dist/cli/chunk-BM3llsxb.js +0 -1
  335. package/dist/cli/chunk-BUNoeMKY.js +0 -36
  336. package/dist/cli/chunk-Bj5qFsDi.js +0 -7
  337. package/dist/cli/chunk-Bj95zm-y.js +0 -1
  338. package/dist/cli/chunk-BpyP-esT.js +0 -1
  339. package/dist/cli/chunk-CX696s3_.js +0 -1
  340. package/dist/cli/chunk-DRxCrCAA.js +0 -139
  341. package/dist/cli/chunk-DjbCHa0h.js +0 -1
  342. package/dist/cli/chunk-Ds5-K-9o.js +0 -1
  343. package/dist/cli/chunk-DsQhAF31.js +0 -1
  344. package/dist/cli/chunk-VM-dECyG.js +0 -1
  345. package/dist/cli/chunk-gvNsvav0.js +0 -225
  346. package/dist/cli/chunk-heu2xRw1.js +0 -1
  347. package/dist/lib/orchestrator-i_QJ-o22.js.map +0 -1
  348. package/dist/lib/shadow-claw-DoQ7fgl5.js.map +0 -1
  349. package/dist/lib/system-prompt-DT_KeYaL.js.map +0 -1
  350. package/dist/public/app-routes-V_-URXc5.js +0 -1
  351. package/dist/public/attachment-capabilities-B6ibLwQB.js +0 -1
  352. package/dist/public/compact-context-CX4H8V57.js +0 -5
  353. package/dist/public/config-C-YdSFZB.js +0 -1
  354. package/dist/public/get-group-dir-DL44kvqW.js +0 -1
  355. package/dist/public/init-control-plane-BoJijVtf.js +0 -1
  356. package/dist/public/orchestrator-CaUpEVkQ.js +0 -63
  357. package/dist/public/provider-DNIL4-Hw.js +0 -1
  358. package/dist/public/shadow-claw-DdgeYPg5.js +0 -1176
@@ -1,9 +1,9 @@
1
- import{i as e,o as t,t as n}from"./chunk-B--rR4-3.js";import{t as r}from"./chunk-NnrQYKRo.js";import{n as i,t as a}from"./chunk-DpWnkQpI.js";import{createRequire as o}from"node:module";import s from"node:path";import{spawnSync as c}from"node:child_process";import l from"process";import{Buffer as u}from"buffer";import d from"fs";import f from"node:events";import p from"node:stream";import m from"path";import{availableParallelism as h}from"node:os";import{createHash as g}from"node:crypto";import _ from"url";import{Readable as v}from"stream";import y from"node:util";import{createRequire as b}from"module";import{pipeline as x}from"stream/promises";let S=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:`1.30.0`},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);S=e}},get logLevel(){return S}},"logLevel",{enumerable:!0});const C=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},ee=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r},w=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new le(`float32`,u,[1,4,n,r]):new le(`float32`,u,[1,3,n,r])},T=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,w(o,s)}throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(w(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return w(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},te=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new le({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ne=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new le({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},E=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new le({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},D=(e,t,n)=>new le({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),re=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),ie=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]);let ae=!1;const oe=()=>{if(!ae){ae=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(re.set(`int64`,BigInt64Array),ie.set(BigInt64Array,`int64`)),t&&(re.set(`uint64`,BigUint64Array),ie.set(BigUint64Array,`uint64`)),r?(re.set(`float16`,n),ie.set(n,`float16`)):re.set(`float16`,Uint16Array)}},se=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},ce=(e,t)=>{switch(e.location){case`cpu`:return new le(e.type,e.data,t);case`cpu-pinned`:return new le({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new le({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new le({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new le({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var le=class{constructor(e,t,n){oe();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=re.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=re.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=ie.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=se(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return T(e,t)}static fromTexture(e,t){return te(e,t)}static fromGpuBuffer(e,t){return ne(e,t)}static fromMLTensor(e,t){return E(e,t)}static fromPinnedBuffer(e,t,n){return D(e,t,n)}toDataURL(e){return C(this,e)}toImageData(e){return ee(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ce(this,e)}};const ue=le,de=e=>e!=null
1
+ import{i as e,o as t,t as n}from"./chunk-B--rR4-3.js";import{t as r}from"./chunk-NnrQYKRo.js";import{n as i,t as a}from"./chunk-DpWnkQpI.js";import{createRequire as o}from"node:module";import s from"node:path";import{spawnSync as c}from"node:child_process";import l from"process";import{createHash as u}from"node:crypto";import{Buffer as d}from"buffer";import f from"fs";import p from"node:events";import m from"node:stream";import h from"path";import{availableParallelism as g}from"node:os";import _ from"url";import{Readable as v}from"stream";import y from"node:util";import{createRequire as b}from"module";import{pipeline as x}from"stream/promises";let S=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:`1.30.0`},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);S=e}},get logLevel(){return S}},"logLevel",{enumerable:!0});const C=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},ee=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r},w=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new le(`float32`,u,[1,4,n,r]):new le(`float32`,u,[1,3,n,r])},T=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,w(o,s)}throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(w(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return w(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},te=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new le({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ne=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new le({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},E=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new le({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},D=(e,t,n)=>new le({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),re=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),ie=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]);let ae=!1;const oe=()=>{if(!ae){ae=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(re.set(`int64`,BigInt64Array),ie.set(BigInt64Array,`int64`)),t&&(re.set(`uint64`,BigUint64Array),ie.set(BigUint64Array,`uint64`)),r?(re.set(`float16`,n),ie.set(n,`float16`)):re.set(`float16`,Uint16Array)}},se=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},ce=(e,t)=>{switch(e.location){case`cpu`:return new le(e.type,e.data,t);case`cpu-pinned`:return new le({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new le({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new le({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new le({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var le=class{constructor(e,t,n){oe();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=re.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=re.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=ie.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=se(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return T(e,t)}static fromTexture(e,t){return te(e,t)}static fromGpuBuffer(e,t){return ne(e,t)}static fromMLTensor(e,t){return E(e,t)}static fromPinnedBuffer(e,t,n){return D(e,t,n)}toDataURL(e){return C(this,e)}toImageData(e){return ee(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ce(this,e)}};const ue=le,de=e=>e!=null
2
2
  /*!
3
3
  Copyright 2013 Lovell Fuller and others.
4
4
  SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- ;var O={defined:de,object:e=>typeof e==`object`,plainObject:e=>Object.prototype.toString.call(e)===`[object Object]`,fn:e=>typeof e==`function`,bool:e=>typeof e==`boolean`,buffer:e=>e instanceof u,typedArray:e=>{if(de(e))switch(e.constructor){case Uint8Array:case Uint8ClampedArray:case Int8Array:case Uint16Array:case Int16Array:case Uint32Array:case Int32Array:case Float32Array:case Float64Array:return!0}return!1},arrayBuffer:e=>e instanceof ArrayBuffer,string:e=>typeof e==`string`&&e.length>0,number:e=>typeof e==`number`&&Number.isFinite(e),integer:e=>Number.isInteger(e),inRange:(e,t,n)=>e>=t&&e<=n,inArray:(e,t)=>t.includes(e),invalidParameterError:(e,t,n)=>{let r;try{r=String(n).slice(0,100)}catch{}return/* @__PURE__ */ Error(`Expected ${t} for ${e} but received ${r} of type ${typeof n}`)},nativeError:(e,t)=>(t.message=e.message,t)},fe=/* @__PURE__ */ n(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||
6
+ ;var O={defined:de,object:e=>typeof e==`object`,plainObject:e=>Object.prototype.toString.call(e)===`[object Object]`,fn:e=>typeof e==`function`,bool:e=>typeof e==`boolean`,buffer:e=>e instanceof d,typedArray:e=>{if(de(e))switch(e.constructor){case Uint8Array:case Uint8ClampedArray:case Int8Array:case Uint16Array:case Int16Array:case Uint32Array:case Int32Array:case Float32Array:case Float64Array:return!0}return!1},arrayBuffer:e=>e instanceof ArrayBuffer,string:e=>typeof e==`string`&&e.length>0,number:e=>typeof e==`number`&&Number.isFinite(e),integer:e=>Number.isInteger(e),inRange:(e,t,n)=>e>=t&&e<=n,inArray:(e,t)=>t.includes(e),invalidParameterError:(e,t,n)=>{let r;try{r=String(n).slice(0,100)}catch{}return/* @__PURE__ */ Error(`Expected ${t} for ${e} but received ${r} of type ${typeof n}`)},nativeError:(e,t)=>(t.message=e.message,t)},fe=/* @__PURE__ */ n(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||
7
7
  /* istanbul ignore next */9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),pe=/* @__PURE__ */ n(((e,t)=>{t.exports=typeof l==`object`&&l.env&&l.env.NODE_DEBUG&&/\bsemver\b/i.test(l.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),me=/* @__PURE__ */ n(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=fe(),a=pe();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),he=/* @__PURE__ */ n(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),ge=/* @__PURE__ */ n(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),_e=/* @__PURE__ */ n(((e,t)=>{let n=pe(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=fe(),{safeRe:a,t:o}=me(),s=he(),{compareIdentifiers:c}=ge(),l=(e,t)=>{let n=t.split(`.`);if(n.length>e.length)return!1;for(let t=0;t<n.length;t++)if(c(e[t],n[t])!==0)return!1;return!0};t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);this.prerelease=l[4]?l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e!==i)return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e!==i)return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];if(n===!1&&(r=[t]),l(this.prerelease,t)){let e=this.prerelease[t.split(`.`).length];isNaN(e)&&(this.prerelease=r)}else this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),ve=/* @__PURE__ */ n(((e,t)=>{let n=_e();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),ye=/* @__PURE__ */ n(((e,t)=>{let n=ve();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),be=/* @__PURE__ */ n(((e,t)=>{let n=ve();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),xe=/* @__PURE__ */ n(((e,t)=>{let n=_e();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),Se=/* @__PURE__ */ n(((e,t)=>{let n=ve();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),Ce=/* @__PURE__ */ n(((e,t)=>{let n=_e();t.exports=(e,t)=>new n(e,t).major})),we=/* @__PURE__ */ n(((e,t)=>{let n=_e();t.exports=(e,t)=>new n(e,t).minor})),Te=/* @__PURE__ */ n(((e,t)=>{let n=_e();t.exports=(e,t)=>new n(e,t).patch})),Ee=/* @__PURE__ */ n(((e,t)=>{let n=ve();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),De=/* @__PURE__ */ n(((e,t)=>{let n=_e();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),Oe=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t,r)=>n(t,e,r)})),ke=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t)=>n(e,t,!0)})),Ae=/* @__PURE__ */ n(((e,t)=>{let n=_e();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),je=/* @__PURE__ */ n(((e,t)=>{let n=Ae();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),Me=/* @__PURE__ */ n(((e,t)=>{let n=Ae();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),Ne=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t,r)=>n(e,t,r)>0})),Pe=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t,r)=>n(e,t,r)<0})),Fe=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t,r)=>n(e,t,r)===0})),Ie=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t,r)=>n(e,t,r)!==0})),Le=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t,r)=>n(e,t,r)>=0})),Re=/* @__PURE__ */ n(((e,t)=>{let n=De();t.exports=(e,t,r)=>n(e,t,r)<=0})),ze=/* @__PURE__ */ n(((e,t)=>{let n=Fe(),r=Ie(),i=Ne(),a=Le(),o=Pe(),s=Re();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),Be=/* @__PURE__ */ n(((e,t)=>{let n=_e(),r=ve(),{safeRe:i,t:a}=me();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2],c=o[3]||`0`,l=o[4]||`0`,u=t.includePrerelease&&o[5]?`-${o[5]}`:``,d=t.includePrerelease&&o[6]?`+${o[6]}`:``;return r(`${s}.${c}.${l}${u}${d}`,t)}})),Ve=/* @__PURE__ */ n(((e,t)=>{let n=ve(),r=fe(),i=_e(),a=(e,t,n)=>{if(!r.RELEASE_TYPES.includes(t))return null;let i=o(e,n);return i&&s(i,t)},o=(e,t)=>{let r=e instanceof i?e.version:e;return n(r,t)},s=(e,t)=>{if(c(t))return e.version;switch(e.prerelease=[],t){case`major`:e.minor=0,e.patch=0;break;case`minor`:e.patch=0}return e.format()},c=e=>e.startsWith(`pre`);t.exports=a})),He=/* @__PURE__ */ n(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=/* @__PURE__ */ new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),Ue=/* @__PURE__ */ n(((e,t)=>{let n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!_(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&v(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(g,``);let t=((this.options.includePrerelease&&m)|(this.options.loose&&h))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];e=e.replace(s,re(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[u.COMPARATORTRIM],d),o(`comparator trim`,e),e=e.replace(c[u.TILDETRIM],f),o(`tilde trim`,e),e=e.replace(c[u.CARETTRIM],p),o(`caret trim`,e);let l=e.split(` `).map(e=>b(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(l=l.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[u.COMPARATORLOOSE])))),o(`range list`,l);let v=/* @__PURE__ */ new Map,y=l.map(e=>new a(e,this.options));for(let e of y){if(_(e))return[e];v.set(e.value,e)}v.size>1&&v.has(``)&&v.delete(``);let x=[...v.values()];return r.set(t,x),x}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>y(e,n)&&t.set.some(t=>y(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(ie(this.set[t],e,this.options))return!0;return!1}};let r=new(He()),i=he(),a=We(),o=pe(),s=_e(),{safeRe:c,src:l,t:u,comparatorTrimReplace:d,tildeTrimReplace:f,caretTrimReplace:p}=me(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:h}=fe(),g=new RegExp(l[u.BUILD],`g`),_=e=>e.value===`<0.0.0-0`,v=e=>e.value===``,y=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},b=(e,t)=>(e=e.replace(c[u.BUILD],``),o(`comp`,e,t),e=w(e,t),o(`caret`,e),e=C(e,t),o(`tildes`,e),e=te(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),x=e=>!e||e.toLowerCase()===`x`||e===`*`,S=(e,t,n)=>x(e)&&!x(t)||x(t)&&n&&!x(n),C=(e,t)=>e.trim().split(/\s+/).map(e=>ee(e,t)).join(` `),ee=(e,t)=>{let n=t.loose?c[u.TILDELOOSE]:c[u.TILDE],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`tilde`,e,t,n,i,a,s);let c;return x(n)?c=``:x(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:x(a)?c=`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:s?(o(`replaceTilde pr`,s),c=`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`):c=`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`,o(`tilde return`,c),c})},w=(e,t)=>e.trim().split(/\s+/).map(e=>T(e,t)).join(` `),T=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[u.CARETLOOSE]:c[u.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return x(n)?c=``:x(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:x(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},te=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>ne(e,t)).join(` `)),ne=(e,t)=>{e=e.trim();let n=t.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{if(o(`xRange`,e,n,r,i,a,s,c),S(i,a,s))return e;let l=x(i),u=l||x(a),d=u||x(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[u.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?u.GTE0PRE:u.GTE0],``)),re=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=x(r)?``:x(i)?`>=${r}.0.0${e?`-0`:``}`:x(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=x(l)?``:x(u)?`<${+l+1}.0.0-0`:x(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),ie=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),We=/* @__PURE__ */ n(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.value=this.semver===n?``:this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),this.semver=r[2]?new c(r[2],this.options.loose):n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``||new l(t.value,n).test(this.value):t.operator===``?t.value===``||new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=he(),{safeRe:i,t:a}=me(),o=ze(),s=pe(),c=_e(),l=Ue()})),Ge=/* @__PURE__ */ n(((e,t)=>{let n=Ue();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),Ke=/* @__PURE__ */ n(((e,t)=>{let n=Ue();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),qe=/* @__PURE__ */ n(((e,t)=>{let n=_e(),r=Ue();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),Je=/* @__PURE__ */ n(((e,t)=>{let n=_e(),r=Ue();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),Ye=/* @__PURE__ */ n(((e,t)=>{let n=_e(),r=Ue(),i=Ne();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;
8
8
  /* istanbul ignore next */
9
9
  default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),Xe=/* @__PURE__ */ n(((e,t)=>{let n=Ue();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),Ze=/* @__PURE__ */ n(((e,t)=>{let n=_e(),r=We(),{ANY:i}=r,a=Ue(),o=Ge(),s=Ne(),c=Pe(),l=Re(),u=Le();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),Qe=/* @__PURE__ */ n(((e,t)=>{let n=Ze();t.exports=(e,t,r)=>n(e,t,`>`,r)})),$e=/* @__PURE__ */ n(((e,t)=>{let n=Ze();t.exports=(e,t,r)=>n(e,t,`<`,r)})),et=/* @__PURE__ */ n(((e,t)=>{let n=Ue();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),tt=/* @__PURE__ */ n(((e,t)=>{let n=Ge(),r=De();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),nt=/* @__PURE__ */ n(((e,t)=>{let n=Ue(),r=We(),{ANY:i}=r,a=Ge(),o=De(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=/* @__PURE__ */ new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!e.test(s.semver))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!e.test(u.semver))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),rt=/* @__PURE__ */ n(((e,t)=>{let n=me(),r=fe(),i=_e(),a=ge();t.exports={parse:ve(),valid:ye(),clean:be(),inc:xe(),diff:Se(),major:Ce(),minor:we(),patch:Te(),prerelease:Ee(),compare:De(),rcompare:Oe(),compareLoose:ke(),compareBuild:Ae(),sort:je(),rsort:Me(),gt:Ne(),lt:Pe(),eq:Fe(),neq:Ie(),gte:Le(),lte:Re(),cmp:ze(),coerce:Be(),truncate:Ve(),Comparator:We(),Range:Ue(),satisfies:Ge(),toComparators:Ke(),maxSatisfying:qe(),minSatisfying:Je(),minVersion:Ye(),validRange:Xe(),outside:Ze(),gtr:Qe(),ltr:$e(),intersects:et(),simplifyRange:tt(),subset:nt(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}})),it={name:`sharp`,description:`High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images`,version:`0.35.5`,author:`Lovell Fuller <npm@lovell.info>`,homepage:`https://sharp.pixelplumbing.com`,contributors:/* @__PURE__ */ `Pierre Inglebert <pierre.inglebert@gmail.com>,Jonathan Ong <jonathanrichardong@gmail.com>,Chanon Sajjamanochai <chanon.s@gmail.com>,Juliano Julio <julianojulio@gmail.com>,Daniel Gasienica <daniel@gasienica.ch>,Julian Walker <julian@fiftythree.com>,Amit Pitaru <pitaru.amit@gmail.com>,Brandon Aaron <hello.brandon@aaron.sh>,Andreas Lind <andreas@one.com>,Maurus Cuelenaere <mcuelenaere@gmail.com>,Linus Unnebäck <linus@folkdatorn.se>,Victor Mateevitsi <mvictoras@gmail.com>,Alaric Holloway <alaric.holloway@gmail.com>,Bernhard K. Weisshuhn <bkw@codingforce.com>,Chris Riley <criley@primedia.com>,David Carley <dacarley@gmail.com>,John Tobin <john@limelightmobileinc.com>,Kenton Gray <kentongray@gmail.com>,Felix Bünemann <Felix.Buenemann@gmail.com>,Samy Al Zahrani <samyalzahrany@gmail.com>,Chintan Thakkar <lemnisk8@gmail.com>,F. Orlando Galashan <frulo@gmx.de>,Kleis Auke Wolthuizen <info@kleisauke.nl>,Matt Hirsch <mhirsch@media.mit.edu>,Matthias Thoemmes <thoemmes@gmail.com>,Patrick Paskaris <patrick@paskaris.gr>,Jérémy Lal <kapouer@melix.org>,Rahul Nanwani <r.nanwani@gmail.com>,Alice Monday <alice0meta@gmail.com>,Kristo Jorgenson <kristo.jorgenson@gmail.com>,YvesBos <yves_bos@outlook.com>,Guy Maliar <guy@tailorbrands.com>,Nicolas Coden <nicolas@ncoden.fr>,Matt Parrish <matt.r.parrish@gmail.com>,Marcel Bretschneider <marcel.bretschneider@gmail.com>,Matthew McEachen <matthew+github@mceachen.org>,Jarda Kotěšovec <jarda.kotesovec@gmail.com>,Kenric D'Souza <kenric.dsouza@gmail.com>,Oleh Aleinyk <oleg.aleynik@gmail.com>,Marcel Bretschneider <marcel.bretschneider@gmail.com>,Andrea Bianco <andrea.bianco@unibas.ch>,Rik Heywood <rik@rik.org>,Thomas Parisot <hi@oncletom.io>,Nathan Graves <nathanrgraves+github@gmail.com>,Tom Lokhorst <tom@lokhorst.eu>,Espen Hovlandsdal <espen@hovlandsdal.com>,Sylvain Dumont <sylvain.dumont35@gmail.com>,Alun Davies <alun.owain.davies@googlemail.com>,Aidan Hoolachan <ajhoolachan21@gmail.com>,Axel Eirola <axel.eirola@iki.fi>,Freezy <freezy@xbmc.org>,Daiz <taneli.vatanen@gmail.com>,Julian Aubourg <j@ubourg.net>,Keith Belovay <keith@picthrive.com>,Michael B. Klein <mbklein@gmail.com>,Jordan Prudhomme <jordan@raboland.fr>,Ilya Ovdin <iovdin@gmail.com>,Andargor <andargor@yahoo.com>,Paul Neave <paul.neave@gmail.com>,Brendan Kennedy <brenwken@gmail.com>,Brychan Bennett-Odlum <git@brychan.io>,Edward Silverton <e.silverton@gmail.com>,Roman Malieiev <aromaleev@gmail.com>,Tomas Szabo <tomas.szabo@deftomat.com>,Robert O'Rourke <robert@o-rourke.org>,Guillermo Alfonso Varela Chouciño <guillevch@gmail.com>,Christian Flintrup <chr@gigahost.dk>,Manan Jadhav <manan@motionden.com>,Leon Radley <leon@radley.se>,alza54 <alza54@thiocod.in>,Jacob Smith <jacob@frende.me>,Michael Nutt <michael@nutt.im>,Brad Parham <baparham@gmail.com>,Taneli Vatanen <taneli.vatanen@gmail.com>,Joris Dugué <zaruike10@gmail.com>,Chris Banks <christopher.bradley.banks@gmail.com>,Ompal Singh <ompal.hitm09@gmail.com>,Brodan <christopher.hranj@gmail.com>,Ankur Parihar <ankur.github@gmail.com>,Brahim Ait elhaj <brahima@gmail.com>,Mart Jansink <m.jansink@gmail.com>,Lachlan Newman <lachnewman007@gmail.com>,Dennis Beatty <dennis@dcbeatty.com>,Ingvar Stepanyan <me@rreverser.com>,Don Denton <don@happycollision.com>,Dmytro Tiapukhin <cool.gegeg@gmail.com>,Florian Lefebvre <contact@florian-lefebvre.dev>`.split(`,`),scripts:{build:`node install/build.js`,"build:dist":`node scripts/build.mjs`,clean:`rm -rf src/build/ test/fixtures/output.*`,test:`npm run lint && npm run test-unit`,lint:`npm run lint-cpp && npm run lint-js && npm run lint-types && npm run lint-publish`,"lint-cpp":`cpplint --quiet src/*.h src/*.cc`,"lint-js":`biome lint`,"lint-publish":`publint --strict`,"lint-types":`tsd --files ./test/types/sharp.test-d.{cts,mts}`,"test-leak":`./test/leak/leak.sh`,"test-unit":`node --experimental-test-coverage test/unit.mjs`,"package-from-local-build":`node npm/from-local-build.js`,"package-wasm-wrappers":`node npm/wasm-wrappers.js`,"package-release-notes":`node npm/release-notes.js`,"docs-build":`node docs/build.mjs`,"docs-serve":`cd docs && npm start`,"docs-publish":`cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp`},type:`commonjs`,files:[`dist`,`install`,`lib/index.d.ts`,`src/*.{cc,h,gyp}`],main:`./dist/index.cjs`,module:`./dist/index.mjs`,types:`./dist/index.d.mts`,exports:{".":{import:{types:`./dist/index.d.mts`,default:`./dist/index.mjs`},require:{types:`./dist/index.d.cts`,default:`./dist/index.cjs`}}},sideEffects:!0,repository:{type:`git`,url:`git+https://github.com/lovell/sharp.git`},keywords:[`jpeg`,`png`,`webp`,`avif`,`tiff`,`gif`,`svg`,`jp2`,`dzi`,`image`,`resize`,`thumbnail`,`crop`,`embed`,`libvips`,`vips`],dependencies:{"@img/colour":`^1.1.0`,"detect-libc":`^2.1.2`,semver:`^7.8.5`},optionalDependencies:{"@img/sharp-darwin-arm64":`0.35.5`,"@img/sharp-darwin-x64":`0.35.5`,"@img/sharp-freebsd-wasm32":`0.35.5`,"@img/sharp-libvips-darwin-arm64":`1.3.4`,"@img/sharp-libvips-darwin-x64":`1.3.4`,"@img/sharp-libvips-linux-arm":`1.3.4`,"@img/sharp-libvips-linux-arm64":`1.3.4`,"@img/sharp-libvips-linux-ppc64":`1.3.4`,"@img/sharp-libvips-linux-riscv64":`1.3.4`,"@img/sharp-libvips-linux-s390x":`1.3.4`,"@img/sharp-libvips-linux-x64":`1.3.4`,"@img/sharp-libvips-linuxmusl-arm64":`1.3.4`,"@img/sharp-libvips-linuxmusl-x64":`1.3.4`,"@img/sharp-linux-arm":`0.35.5`,"@img/sharp-linux-arm64":`0.35.5`,"@img/sharp-linux-ppc64":`0.35.5`,"@img/sharp-linux-riscv64":`0.35.5`,"@img/sharp-linux-s390x":`0.35.5`,"@img/sharp-linux-x64":`0.35.5`,"@img/sharp-linuxmusl-arm64":`0.35.5`,"@img/sharp-linuxmusl-x64":`0.35.5`,"@img/sharp-webcontainers-wasm32":`0.35.5`,"@img/sharp-win32-arm64":`0.35.5`,"@img/sharp-win32-ia32":`0.35.5`,"@img/sharp-win32-x64":`0.35.5`},peerDependenciesMeta:{"@types/node":{optional:!0}},devDependencies:{"@biomejs/biome":`^2.5.14`,"@cpplint/cli":`^0.1.0`,"@emnapi/runtime":`^1.11.3`,"@img/sharp-libvips-dev":`1.3.4`,"@img/sharp-libvips-dev-wasm32":`1.3.4`,"@img/sharp-libvips-win32-arm64":`1.3.4`,"@img/sharp-libvips-win32-ia32":`1.3.4`,"@img/sharp-libvips-win32-x64":`1.3.4`,"@types/node":`*`,emnapi:`^1.11.3`,"exif-reader":`^2.0.3`,icc:`^4.0.0`,"node-addon-api":`^8.9.2`,"node-gyp":`^12.4.0`,publint:`^0.3.24`,"tar-fs":`^3.1.3`,tsd:`^0.33.0`,yauzl:`^3.4.0`},license:`Apache-2.0`,engines:{node:`>=20.9.0`},config:{libvips:`>=8.18.7`},funding:{url:`https://opencollective.com/libvips`}},at=/* @__PURE__ */ t(rt(),1),ot=/* @__PURE__ */ t(r(),1)
@@ -13,7 +13,7 @@ SPDX-License-Identifier: Apache-2.0
13
13
  */
14
14
  ;
15
15
  /* node:coverage ignore next */
16
- const st=l.env.npm_package_config_libvips||it.config.libvips,ct=at.default.coerce(st).version,lt=[`darwin-arm64`,`darwin-x64`,`freebsd-arm64`,`freebsd-x64`,`linux-arm`,`linux-arm64`,`linux-ppc64`,`linux-riscv64`,`linux-s390x`,`linux-wasm32`,`linux-x64`,`linuxmusl-arm64`,`linuxmusl-x64`,`win32-arm64`,`win32-ia32`,`win32-x64`],ut={encoding:`utf8`,shell:!0},dt=e=>{e instanceof Error?console.error(`sharp: Installation error: ${e.message}`):console.log(`sharp: ${e}`)},ft=()=>ot.default.isNonGlibcLinuxSync()?ot.default.familySync():``,pt=()=>`${l.platform}${ft()}-${l.arch}`,mt=()=>{if(yt())return`wasm32`;let{npm_config_arch:e,npm_config_platform:t,npm_config_libc:n}=l.env,r=typeof n==`string`?n:ft();return`${t||l.platform}${r}-${e||l.arch}`},ht=()=>{try{return e(`@img/sharp-libvips-dev-${mt()}/include`)}catch{try{return e(`@img/sharp-libvips-dev/include`)}catch{}}return``},gt=()=>{try{return e(`@img/sharp-libvips-dev/cplusplus`)}catch{}return``},_t=()=>{try{return e(`@img/sharp-libvips-dev-${mt()}/lib`)}catch{try{return e(`@img/sharp-libvips-${mt()}/lib`)}catch{}}return``},vt=()=>{if(l.release?.name===`node`&&l.versions&&!at.default.satisfies(l.versions.node,it.engines.node))return{found:l.versions.node,expected:it.engines.node}},yt=()=>{let{CC:e}=l.env;return!!e?.endsWith(`/emcc`)},bt=()=>l.platform===`darwin`&&l.arch===`x64`&&(c(`sysctl sysctl.proc_translated`,ut).stdout||``).trim()===`sysctl.proc_translated: 1`,xt=e=>g(`sha512`).update(e).digest(`hex`),St=()=>{try{let e=xt(`imgsharp-libvips-${mt()}`),t=at.default.coerce(it.optionalDependencies[`@img/sharp-libvips-${mt()}`],{includePrerelease:!0}).version;return xt(`${e}npm:${t}`).slice(0,10)}catch{}return``},Ct=()=>c(`node-gyp rebuild --directory=src ${yt()?`--nodedir=emscripten`:``}`,{...ut,stdio:`inherit`}).status,wt=()=>l.platform===`win32`?``:(c(`pkg-config --modversion vips-cpp`,{...ut,env:{...l.env,PKG_CONFIG_PATH:Dt()}}).stdout||``).trim(),Tt=()=>{try{let e=(c(`brew`,[`--prefix`],{encoding:`utf8`}).stdout||``).trim();if(e)return`${e}/lib/pkgconfig`}catch{}},Et=()=>{try{let e=(c(`pkg-config`,[`--variable`,`pc_path`,`pkg-config`],{encoding:`utf8`}).stdout||``).trim();if(e)return e}catch{}},Dt=()=>l.platform===`win32`?``:[Tt(),Et(),l.env.PKG_CONFIG_PATH].filter(Boolean).join(`:`),Ot=(e,t,n)=>(n&&n(`Detected ${t}, skipping search for globally-installed libvips`),e);var kt={minimumLibvipsVersion:ct,prebuiltPlatforms:lt,buildPlatformArch:mt,buildSharpLibvipsIncludeDir:ht,buildSharpLibvipsCPlusPlusDir:gt,buildSharpLibvipsLibDir:_t,isUnsupportedNodeRuntime:vt,runtimePlatformArch:pt,log:dt,yarnLocator:St,spawnRebuild:Ct,globalLibvipsVersion:wt,pkgConfigPath:Dt,useGlobalLibvips:e=>{if(l.env.SHARP_IGNORE_GLOBAL_LIBVIPS)return Ot(!1,`SHARP_IGNORE_GLOBAL_LIBVIPS`,e);if(l.env.SHARP_FORCE_GLOBAL_LIBVIPS)return Ot(!0,`SHARP_FORCE_GLOBAL_LIBVIPS`,e);
16
+ const st=l.env.npm_package_config_libvips||it.config.libvips,ct=at.default.coerce(st).version,lt=[`darwin-arm64`,`darwin-x64`,`freebsd-arm64`,`freebsd-x64`,`linux-arm`,`linux-arm64`,`linux-ppc64`,`linux-riscv64`,`linux-s390x`,`linux-wasm32`,`linux-x64`,`linuxmusl-arm64`,`linuxmusl-x64`,`win32-arm64`,`win32-ia32`,`win32-x64`],ut={encoding:`utf8`,shell:!0},dt=e=>{e instanceof Error?console.error(`sharp: Installation error: ${e.message}`):console.log(`sharp: ${e}`)},ft=()=>ot.default.isNonGlibcLinuxSync()?ot.default.familySync():``,pt=()=>`${l.platform}${ft()}-${l.arch}`,mt=()=>{if(yt())return`wasm32`;let{npm_config_arch:e,npm_config_platform:t,npm_config_libc:n}=l.env,r=typeof n==`string`?n:ft();return`${t||l.platform}${r}-${e||l.arch}`},ht=()=>{try{return e(`@img/sharp-libvips-dev-${mt()}/include`)}catch{try{return e(`@img/sharp-libvips-dev/include`)}catch{}}return``},gt=()=>{try{return e(`@img/sharp-libvips-dev/cplusplus`)}catch{}return``},_t=()=>{try{return e(`@img/sharp-libvips-dev-${mt()}/lib`)}catch{try{return e(`@img/sharp-libvips-${mt()}/lib`)}catch{}}return``},vt=()=>{if(l.release?.name===`node`&&l.versions&&!at.default.satisfies(l.versions.node,it.engines.node))return{found:l.versions.node,expected:it.engines.node}},yt=()=>{let{CC:e}=l.env;return!!e?.endsWith(`/emcc`)},bt=()=>l.platform===`darwin`&&l.arch===`x64`&&(c(`sysctl sysctl.proc_translated`,ut).stdout||``).trim()===`sysctl.proc_translated: 1`,xt=e=>u(`sha512`).update(e).digest(`hex`),St=()=>{try{let e=xt(`imgsharp-libvips-${mt()}`),t=at.default.coerce(it.optionalDependencies[`@img/sharp-libvips-${mt()}`],{includePrerelease:!0}).version;return xt(`${e}npm:${t}`).slice(0,10)}catch{}return``},Ct=()=>c(`node-gyp rebuild --directory=src ${yt()?`--nodedir=emscripten`:``}`,{...ut,stdio:`inherit`}).status,wt=()=>l.platform===`win32`?``:(c(`pkg-config --modversion vips-cpp`,{...ut,env:{...l.env,PKG_CONFIG_PATH:Dt()}}).stdout||``).trim(),Tt=()=>{try{let e=(c(`brew`,[`--prefix`],{encoding:`utf8`}).stdout||``).trim();if(e)return`${e}/lib/pkgconfig`}catch{}},Et=()=>{try{let e=(c(`pkg-config`,[`--variable`,`pc_path`,`pkg-config`],{encoding:`utf8`}).stdout||``).trim();if(e)return e}catch{}},Dt=()=>l.platform===`win32`?``:[Tt(),Et(),l.env.PKG_CONFIG_PATH].filter(Boolean).join(`:`),Ot=(e,t,n)=>(n&&n(`Detected ${t}, skipping search for globally-installed libvips`),e);var kt={minimumLibvipsVersion:ct,prebuiltPlatforms:lt,buildPlatformArch:mt,buildSharpLibvipsIncludeDir:ht,buildSharpLibvipsCPlusPlusDir:gt,buildSharpLibvipsLibDir:_t,isUnsupportedNodeRuntime:vt,runtimePlatformArch:pt,log:dt,yarnLocator:St,spawnRebuild:Ct,globalLibvipsVersion:wt,pkgConfigPath:Dt,useGlobalLibvips:e=>{if(l.env.SHARP_IGNORE_GLOBAL_LIBVIPS)return Ot(!1,`SHARP_IGNORE_GLOBAL_LIBVIPS`,e);if(l.env.SHARP_FORCE_GLOBAL_LIBVIPS)return Ot(!0,`SHARP_FORCE_GLOBAL_LIBVIPS`,e);
17
17
  /* node:coverage ignore next 3 */
18
18
  if(bt())return Ot(!1,`Rosetta`,e);let t=wt();
19
19
  /* node:coverage ignore next */
@@ -30,12 +30,12 @@ let Lt;const Rt=[];try{Lt=At(`../src/build/Release/sharp-${It}-${jt}.node`)}catc
30
30
  Copyright 2013 Lovell Fuller and others.
31
31
  SPDX-License-Identifier: Apache-2.0
32
32
  */
33
- const zt=y.debuglog(`sharp`),Bt=e=>{Vt.queue.emit(`change`,e)},Vt=function(e,t){if(arguments.length===1&&!O.defined(e))throw Error(`Invalid input`);return this instanceof Vt?(p.Duplex.call(this),this.options={topOffsetPre:-1,leftOffsetPre:-1,widthPre:-1,heightPre:-1,topOffsetPost:-1,leftOffsetPost:-1,widthPost:-1,heightPost:-1,width:-1,height:-1,canvas:`crop`,position:0,resizeBackground:[0,0,0,255],angle:0,rotationAngle:0,rotationBackground:[0,0,0,255],rotateBefore:!1,orientBefore:!1,flip:!1,flop:!1,extendTop:0,extendBottom:0,extendLeft:0,extendRight:0,extendBackground:[0,0,0,255],extendWith:`background`,withoutEnlargement:!1,withoutReduction:!1,affineMatrix:[],affineBackground:[0,0,0,255],affineIdx:0,affineIdy:0,affineOdx:0,affineOdy:0,affineInterpolator:this.constructor.interpolators.bilinear,kernel:`lanczos3`,fastShrinkOnLoad:!0,tint:[-1,0,0,0],flatten:!1,flattenBackground:[0,0,0],unflatten:!1,negate:!1,negateAlpha:!0,medianSize:0,blurSigma:0,precision:`integer`,minAmpl:.2,sharpenSigma:0,sharpenM1:1,sharpenM2:2,sharpenX1:2,sharpenY2:10,sharpenY3:20,threshold:0,thresholdGrayscale:!0,trimBackground:[],trimThreshold:-1,trimLineArt:!1,trimMargin:0,dilateWidth:0,erodeWidth:0,gamma:0,gammaOut:0,greyscale:!1,normalise:!1,normaliseLower:1,normaliseUpper:99,claheWidth:0,claheHeight:0,claheMaxSlope:3,brightness:1,saturation:1,hue:0,lightness:0,booleanBufferIn:null,booleanFileIn:``,joinChannelIn:[],extractChannel:-1,removeAlpha:!1,ensureAlpha:-1,colourspace:`srgb`,colourspacePipeline:`last`,composite:[],fileOut:``,formatOut:`input`,streamOut:!1,typedArrayOut:!1,keepMetadata:0,withMetadataOrientation:-1,withMetadataDensity:0,withIccProfile:``,withExif:{},withExifMerge:!0,withXmp:``,keepGainMap:!1,withGainMap:!1,resolveWithObject:!1,loop:-1,delay:[],jpegQuality:80,jpegProgressive:!1,jpegChromaSubsampling:`4:2:0`,jpegTrellisQuantisation:!1,jpegOvershootDeringing:!1,jpegOptimiseScans:!1,jpegOptimiseCoding:!0,jpegQuantisationTable:0,pngProgressive:!1,pngCompressionLevel:6,pngAdaptiveFiltering:!1,pngPalette:!1,pngQuality:100,pngEffort:7,pngBitdepth:8,pngDither:1,jp2Quality:80,jp2TileHeight:512,jp2TileWidth:512,jp2Lossless:!1,jp2ChromaSubsampling:`4:4:4`,webpQuality:80,webpAlphaQuality:100,webpLossless:!1,webpNearLossless:!1,webpSmartSubsample:!1,webpSmartDeblock:!1,webpPreset:`default`,webpEffort:4,webpMinSize:!1,webpMixed:!1,webpExact:!1,gifBitdepth:8,gifEffort:7,gifDither:1,gifInterFrameMaxError:0,gifInterPaletteMaxError:3,gifKeepDuplicateFrames:!1,gifReuse:!0,gifProgressive:!1,tiffQuality:80,tiffCompression:`jpeg`,tiffBigtiff:!1,tiffPredictor:`horizontal`,tiffPyramid:!1,tiffMiniswhite:!1,tiffBitdepth:0,tiffTile:!1,tiffTileHeight:256,tiffTileWidth:256,tiffXres:1,tiffYres:1,tiffResolutionUnit:`inch`,heifQuality:50,heifLossless:!1,heifCompression:`av1`,heifEffort:4,heifChromaSubsampling:`4:4:4`,heifBitdepth:8,heifTune:`auto`,jxlDistance:1,jxlDecodingTier:0,jxlEffort:7,jxlLossless:!1,rawDepth:`uchar`,tileSize:256,tileOverlap:0,tileContainer:`fs`,tileLayout:`dz`,tileFormat:`last`,tileDepth:`last`,tileAngle:0,tileSkipBlanks:-1,tileBackground:[255,255,255,255],tileCentre:!1,tileId:`https://example.com/iiif`,tileBasename:``,timeoutSeconds:0,linearA:[],linearB:[],pdfBackground:[255,255,255,255],debuglog:e=>{this.emit(`warning`,e),zt(e)},queueListener:Bt},this.options.input=this._createInputDescriptor(e,t,{allowStream:!0}),this):new Vt(e,t)};Object.setPrototypeOf(Vt.prototype,p.Duplex.prototype),Object.setPrototypeOf(Vt,p.Duplex);function Ht(){let e=this.constructor.call(),{debuglog:t,queueListener:n,...r}=this.options;return e.options=structuredClone(r),e.options.debuglog=t,e.options.queueListener=n,this._isStreamInput()&&this._whenStreamInFinished(()=>{this._flattenBufferIn(),e.options.input.buffer=this.options.input.buffer,e.emit(`finish`)}),e}Object.assign(Vt.prototype,{clone:Ht});
33
+ const zt=y.debuglog(`sharp`),Bt=e=>{Vt.queue.emit(`change`,e)},Vt=function(e,t){if(arguments.length===1&&!O.defined(e))throw Error(`Invalid input`);return this instanceof Vt?(m.Duplex.call(this),this.options={topOffsetPre:-1,leftOffsetPre:-1,widthPre:-1,heightPre:-1,topOffsetPost:-1,leftOffsetPost:-1,widthPost:-1,heightPost:-1,width:-1,height:-1,canvas:`crop`,position:0,resizeBackground:[0,0,0,255],angle:0,rotationAngle:0,rotationBackground:[0,0,0,255],rotateBefore:!1,orientBefore:!1,flip:!1,flop:!1,extendTop:0,extendBottom:0,extendLeft:0,extendRight:0,extendBackground:[0,0,0,255],extendWith:`background`,withoutEnlargement:!1,withoutReduction:!1,affineMatrix:[],affineBackground:[0,0,0,255],affineIdx:0,affineIdy:0,affineOdx:0,affineOdy:0,affineInterpolator:this.constructor.interpolators.bilinear,kernel:`lanczos3`,fastShrinkOnLoad:!0,tint:[-1,0,0,0],flatten:!1,flattenBackground:[0,0,0],unflatten:!1,negate:!1,negateAlpha:!0,medianSize:0,blurSigma:0,precision:`integer`,minAmpl:.2,sharpenSigma:0,sharpenM1:1,sharpenM2:2,sharpenX1:2,sharpenY2:10,sharpenY3:20,threshold:0,thresholdGrayscale:!0,trimBackground:[],trimThreshold:-1,trimLineArt:!1,trimMargin:0,dilateWidth:0,erodeWidth:0,gamma:0,gammaOut:0,greyscale:!1,normalise:!1,normaliseLower:1,normaliseUpper:99,claheWidth:0,claheHeight:0,claheMaxSlope:3,brightness:1,saturation:1,hue:0,lightness:0,booleanBufferIn:null,booleanFileIn:``,joinChannelIn:[],extractChannel:-1,removeAlpha:!1,ensureAlpha:-1,colourspace:`srgb`,colourspacePipeline:`last`,composite:[],fileOut:``,formatOut:`input`,streamOut:!1,typedArrayOut:!1,keepMetadata:0,withMetadataOrientation:-1,withMetadataDensity:0,withIccProfile:``,withExif:{},withExifMerge:!0,withXmp:``,keepGainMap:!1,withGainMap:!1,resolveWithObject:!1,loop:-1,delay:[],jpegQuality:80,jpegProgressive:!1,jpegChromaSubsampling:`4:2:0`,jpegTrellisQuantisation:!1,jpegOvershootDeringing:!1,jpegOptimiseScans:!1,jpegOptimiseCoding:!0,jpegQuantisationTable:0,pngProgressive:!1,pngCompressionLevel:6,pngAdaptiveFiltering:!1,pngPalette:!1,pngQuality:100,pngEffort:7,pngBitdepth:8,pngDither:1,jp2Quality:80,jp2TileHeight:512,jp2TileWidth:512,jp2Lossless:!1,jp2ChromaSubsampling:`4:4:4`,webpQuality:80,webpAlphaQuality:100,webpLossless:!1,webpNearLossless:!1,webpSmartSubsample:!1,webpSmartDeblock:!1,webpPreset:`default`,webpEffort:4,webpMinSize:!1,webpMixed:!1,webpExact:!1,gifBitdepth:8,gifEffort:7,gifDither:1,gifInterFrameMaxError:0,gifInterPaletteMaxError:3,gifKeepDuplicateFrames:!1,gifReuse:!0,gifProgressive:!1,tiffQuality:80,tiffCompression:`jpeg`,tiffBigtiff:!1,tiffPredictor:`horizontal`,tiffPyramid:!1,tiffMiniswhite:!1,tiffBitdepth:0,tiffTile:!1,tiffTileHeight:256,tiffTileWidth:256,tiffXres:1,tiffYres:1,tiffResolutionUnit:`inch`,heifQuality:50,heifLossless:!1,heifCompression:`av1`,heifEffort:4,heifChromaSubsampling:`4:4:4`,heifBitdepth:8,heifTune:`auto`,jxlDistance:1,jxlDecodingTier:0,jxlEffort:7,jxlLossless:!1,rawDepth:`uchar`,tileSize:256,tileOverlap:0,tileContainer:`fs`,tileLayout:`dz`,tileFormat:`last`,tileDepth:`last`,tileAngle:0,tileSkipBlanks:-1,tileBackground:[255,255,255,255],tileCentre:!1,tileId:`https://example.com/iiif`,tileBasename:``,timeoutSeconds:0,linearA:[],linearB:[],pdfBackground:[255,255,255,255],debuglog:e=>{this.emit(`warning`,e),zt(e)},queueListener:Bt},this.options.input=this._createInputDescriptor(e,t,{allowStream:!0}),this):new Vt(e,t)};Object.setPrototypeOf(Vt.prototype,m.Duplex.prototype),Object.setPrototypeOf(Vt,m.Duplex);function Ht(){let e=this.constructor.call(),{debuglog:t,queueListener:n,...r}=this.options;return e.options=structuredClone(r),e.options.debuglog=t,e.options.queueListener=n,this._isStreamInput()&&this._whenStreamInFinished(()=>{this._flattenBufferIn(),e.options.input.buffer=this.options.input.buffer,e.emit(`finish`)}),e}Object.assign(Vt.prototype,{clone:Ht});
34
34
  /*!
35
35
  Copyright 2013 Lovell Fuller and others.
36
36
  SPDX-License-Identifier: Apache-2.0
37
37
  */
38
- const Ut={left:`low`,top:`low`,low:`low`,center:`centre`,centre:`centre`,right:`high`,bottom:`high`,high:`high`},Wt=[`failOn`,`limitInputPixels`,`limitInputChannels`,`unlimited`,`animated`,`autoOrient`,`density`,`ignoreIcc`,`page`,`pages`,`sequentialRead`,`jp2`,`openSlide`,`pdf`,`raw`,`svg`,`tiff`,`openSlideLevel`,`pdfBackground`,`tiffSubifd`];function Gt(e){let t=Wt.filter(t=>O.defined(e[t])).map(t=>[t,e[t]]);return t.length?Object.fromEntries(t):void 0}function Kt(e,t,n){let r={autoOrient:!1,failOn:`warning`,limitInputPixels:16383**2,limitInputChannels:5,ignoreIcc:!1,unlimited:!1,sequentialRead:!0};if(O.string(e))r.file=e;else if(O.buffer(e)){if(e.length===0)throw Error(`Input Buffer is empty`);r.buffer=e}else if(O.arrayBuffer(e)){if(e.byteLength===0)throw Error(`Input bit Array is empty`);r.buffer=u.from(e,0,e.byteLength)}else if(O.typedArray(e)){if(e.length===0)throw Error(`Input Bit Array is empty`);r.buffer=u.from(e.buffer,e.byteOffset,e.byteLength)}else if(O.plainObject(e)&&!O.defined(t))t=e,Gt(t)&&(r.buffer=[]);else if(!O.defined(e)&&!O.defined(t)&&O.object(n)&&n.allowStream)r.buffer=[];else if(Array.isArray(e)){if(e.length>1){if(!this.options.joining)this.options.joining=!0,this.options.join=e.map(e=>this._createInputDescriptor(e));else throw Error(`Recursive join is unsupported`)}else throw Error(`Expected at least two images to join`)}else throw Error(`Unsupported input '${e}' of type ${typeof e}${O.defined(t)?` when also providing options of type ${typeof t}`:``}`);if(O.object(t)){if(O.defined(t.failOn)){if(O.string(t.failOn)&&O.inArray(t.failOn,[`none`,`truncated`,`error`,`warning`]))r.failOn=t.failOn;else throw O.invalidParameterError(`failOn`,`one of: none, truncated, error, warning`,t.failOn)}if(O.defined(t.autoOrient)){if(O.bool(t.autoOrient))r.autoOrient=t.autoOrient;else throw O.invalidParameterError(`autoOrient`,`boolean`,t.autoOrient)}if(O.defined(t.density)){if(O.number(t.density)&&O.inRange(t.density,1,1e5))r.density=t.density;else throw O.invalidParameterError(`density`,`number between 1 and 100000`,t.density)}if(O.defined(t.ignoreIcc)){if(O.bool(t.ignoreIcc))r.ignoreIcc=t.ignoreIcc;else throw O.invalidParameterError(`ignoreIcc`,`boolean`,t.ignoreIcc)}if(O.defined(t.limitInputPixels)){if(O.bool(t.limitInputPixels))r.limitInputPixels=t.limitInputPixels?16383**2:0;else if(O.integer(t.limitInputPixels)&&O.inRange(t.limitInputPixels,0,2**53-1))r.limitInputPixels=t.limitInputPixels;else throw O.invalidParameterError(`limitInputPixels`,`positive integer`,t.limitInputPixels)}if(O.defined(t.limitInputChannels)){if(O.bool(t.limitInputChannels))r.limitInputChannels=t.limitInputChannels?5:0;else if(O.integer(t.limitInputChannels)&&O.inRange(t.limitInputChannels,0,2**53-1))r.limitInputChannels=t.limitInputChannels;else throw O.invalidParameterError(`limitInputChannels`,`positive integer`,t.limitInputChannels)}if(O.defined(t.unlimited)){if(O.bool(t.unlimited))r.unlimited=t.unlimited;else throw O.invalidParameterError(`unlimited`,`boolean`,t.unlimited)}if(O.defined(t.sequentialRead)){if(O.bool(t.sequentialRead))r.sequentialRead=t.sequentialRead;else throw O.invalidParameterError(`sequentialRead`,`boolean`,t.sequentialRead)}if(O.defined(t.raw)){if(O.object(t.raw)&&O.integer(t.raw.width)&&O.inRange(t.raw.width,1,1e8)&&O.integer(t.raw.height)&&O.inRange(t.raw.height,1,1e8)&&O.integer(t.raw.channels)&&O.inRange(t.raw.channels,1,4))switch(r.rawWidth=t.raw.width,r.rawHeight=t.raw.height,r.rawChannels=t.raw.channels,e.constructor){case Uint8Array:case Uint8ClampedArray:r.rawDepth=`uchar`;break;case Int8Array:r.rawDepth=`char`;break;case Uint16Array:r.rawDepth=`ushort`;break;case Int16Array:r.rawDepth=`short`;break;case Uint32Array:r.rawDepth=`uint`;break;case Int32Array:r.rawDepth=`int`;break;case Float32Array:r.rawDepth=`float`;break;case Float64Array:r.rawDepth=`double`;break;default:r.rawDepth=`uchar`}else throw Error(`Expected width, height and channels for raw pixel input`);if(r.rawPremultiplied=!1,O.defined(t.raw.premultiplied)){if(O.bool(t.raw.premultiplied))r.rawPremultiplied=t.raw.premultiplied;else throw O.invalidParameterError(`raw.premultiplied`,`boolean`,t.raw.premultiplied)}if(r.rawPageHeight=0,O.defined(t.raw.pageHeight)){if(O.integer(t.raw.pageHeight)&&t.raw.pageHeight>0&&t.raw.pageHeight<=t.raw.height){if(t.raw.height%t.raw.pageHeight!==0)throw Error(`Expected raw.height ${t.raw.height} to be a multiple of raw.pageHeight ${t.raw.pageHeight}`);r.rawPageHeight=t.raw.pageHeight}else throw O.invalidParameterError(`raw.pageHeight`,`positive integer`,t.raw.pageHeight)}}if(O.defined(t.animated)){if(O.bool(t.animated))r.pages=t.animated?-1:1;else throw O.invalidParameterError(`animated`,`boolean`,t.animated)}if(O.defined(t.pages)){if(O.integer(t.pages)&&O.inRange(t.pages,-1,1e5))r.pages=t.pages;else throw O.invalidParameterError(`pages`,`integer between -1 and 100000`,t.pages)}if(O.defined(t.page)){if(O.integer(t.page)&&O.inRange(t.page,0,1e5))r.page=t.page;else throw O.invalidParameterError(`page`,`integer between 0 and 100000`,t.page)}if(O.object(t.openSlide)&&O.defined(t.openSlide.level)){if(O.integer(t.openSlide.level)&&O.inRange(t.openSlide.level,0,256))r.openSlideLevel=t.openSlide.level;else throw O.invalidParameterError(`openSlide.level`,`integer between 0 and 256`,t.openSlide.level)}else if(O.defined(t.level)){if(O.integer(t.level)&&O.inRange(t.level,0,256))r.openSlideLevel=t.level;else throw O.invalidParameterError(`level`,`integer between 0 and 256`,t.level)}if(O.object(t.tiff)&&O.defined(t.tiff.subifd)){if(O.integer(t.tiff.subifd)&&O.inRange(t.tiff.subifd,-1,1e5))r.tiffSubifd=t.tiff.subifd;else throw O.invalidParameterError(`tiff.subifd`,`integer between -1 and 100000`,t.tiff.subifd)}else if(O.defined(t.subifd)){if(O.integer(t.subifd)&&O.inRange(t.subifd,-1,1e5))r.tiffSubifd=t.subifd;else throw O.invalidParameterError(`subifd`,`integer between -1 and 100000`,t.subifd)}if(O.object(t.svg)){if(O.defined(t.svg.stylesheet)){if(O.string(t.svg.stylesheet))r.svgStylesheet=t.svg.stylesheet;else throw O.invalidParameterError(`svg.stylesheet`,`string`,t.svg.stylesheet)}if(O.defined(t.svg.highBitdepth)){if(O.bool(t.svg.highBitdepth))r.svgHighBitdepth=t.svg.highBitdepth;else throw O.invalidParameterError(`svg.highBitdepth`,`boolean`,t.svg.highBitdepth)}}if(O.object(t.pdf)&&O.defined(t.pdf.background)?r.pdfBackground=this._getBackgroundColourOption(t.pdf.background):O.defined(t.pdfBackground)&&(r.pdfBackground=this._getBackgroundColourOption(t.pdfBackground)),O.object(t.jp2)&&O.defined(t.jp2.oneshot)){if(O.bool(t.jp2.oneshot))r.jp2Oneshot=t.jp2.oneshot;else throw O.invalidParameterError(`jp2.oneshot`,`boolean`,t.jp2.oneshot)}if(O.defined(t.create)){if(O.object(t.create)&&O.integer(t.create.width)&&O.inRange(t.create.width,1,1e8)&&O.integer(t.create.height)&&O.inRange(t.create.height,1,1e8)&&O.integer(t.create.channels)){if(r.createWidth=t.create.width,r.createHeight=t.create.height,r.createChannels=t.create.channels,r.createPageHeight=0,O.defined(t.create.pageHeight)){if(O.integer(t.create.pageHeight)&&t.create.pageHeight>0&&t.create.pageHeight<=t.create.height){if(t.create.height%t.create.pageHeight!==0)throw Error(`Expected create.height ${t.create.height} to be a multiple of create.pageHeight ${t.create.pageHeight}`);r.createPageHeight=t.create.pageHeight}else throw O.invalidParameterError(`create.pageHeight`,`positive integer`,t.create.pageHeight)}if(O.defined(t.create.noise)){if(!O.object(t.create.noise))throw Error(`Expected noise to be an object`);if(t.create.noise.type!==`gaussian`)throw Error(`Only gaussian noise is supported at the moment`);if(r.createNoiseType=t.create.noise.type,!O.inRange(t.create.channels,1,4))throw O.invalidParameterError(`create.channels`,`number between 1 and 4`,t.create.channels);if(r.createNoiseMean=128,O.defined(t.create.noise.mean)){if(O.number(t.create.noise.mean)&&O.inRange(t.create.noise.mean,0,1e4))r.createNoiseMean=t.create.noise.mean;else throw O.invalidParameterError(`create.noise.mean`,`number between 0 and 10000`,t.create.noise.mean)}if(r.createNoiseSigma=30,O.defined(t.create.noise.sigma)){if(O.number(t.create.noise.sigma)&&O.inRange(t.create.noise.sigma,0,1e4))r.createNoiseSigma=t.create.noise.sigma;else throw O.invalidParameterError(`create.noise.sigma`,`number between 0 and 10000`,t.create.noise.sigma)}}else if(O.defined(t.create.background)){if(!O.inRange(t.create.channels,3,4))throw O.invalidParameterError(`create.channels`,`number between 3 and 4`,t.create.channels);r.createBackground=this._getBackgroundColourOption(t.create.background)}else throw Error(`Expected valid noise or background to create a new input image`);delete r.buffer}else throw Error(`Expected valid width, height and channels to create a new input image`)}if(O.defined(t.text)){if(O.object(t.text)&&O.string(t.text.text)){if(r.textValue=t.text.text,O.defined(t.text.height)&&O.defined(t.text.dpi))throw Error(`Expected only one of dpi or height`);if(O.defined(t.text.font)){if(O.string(t.text.font))r.textFont=t.text.font;else throw O.invalidParameterError(`text.font`,`string`,t.text.font)}if(O.defined(t.text.fontfile)){if(O.string(t.text.fontfile))r.textFontfile=t.text.fontfile;else throw O.invalidParameterError(`text.fontfile`,`string`,t.text.fontfile)}if(O.defined(t.text.width)){if(O.integer(t.text.width)&&O.inRange(t.text.width,1,1e6))r.textWidth=t.text.width;else throw O.invalidParameterError(`text.width`,`integer between 1 and 1000000`,t.text.width)}if(O.defined(t.text.height)){if(O.integer(t.text.height)&&O.inRange(t.text.height,1,1e6))r.textHeight=t.text.height;else throw O.invalidParameterError(`text.height`,`integer between 1 and 1000000`,t.text.height)}if(O.defined(t.text.align)){if(O.string(t.text.align)&&O.string(this.constructor.align[t.text.align]))r.textAlign=this.constructor.align[t.text.align];else throw O.invalidParameterError(`text.align`,`valid alignment`,t.text.align)}if(O.defined(t.text.justify)){if(O.bool(t.text.justify))r.textJustify=t.text.justify;else throw O.invalidParameterError(`text.justify`,`boolean`,t.text.justify)}if(O.defined(t.text.dpi)){if(O.integer(t.text.dpi)&&O.inRange(t.text.dpi,1,1e6))r.textDpi=t.text.dpi;else throw O.invalidParameterError(`text.dpi`,`integer between 1 and 1000000`,t.text.dpi)}if(O.defined(t.text.rgba)){if(O.bool(t.text.rgba))r.textRgba=t.text.rgba;else throw O.invalidParameterError(`text.rgba`,`bool`,t.text.rgba)}if(O.defined(t.text.spacing)){if(O.integer(t.text.spacing)&&O.inRange(t.text.spacing,-1e6,1e6))r.textSpacing=t.text.spacing;else throw O.invalidParameterError(`text.spacing`,`integer between -1000000 and 1000000`,t.text.spacing)}if(O.defined(t.text.wrap)){if(O.string(t.text.wrap)&&O.inArray(t.text.wrap,[`word`,`char`,`word-char`,`none`]))r.textWrap=t.text.wrap;else throw O.invalidParameterError(`text.wrap`,`one of: word, char, word-char, none`,t.text.wrap)}delete r.buffer}else throw Error(`Expected a valid string to create an image with text.`)}if(O.defined(t.join)){if(O.defined(this.options.join)){if(O.defined(t.join.animated)){if(O.bool(t.join.animated))r.joinAnimated=t.join.animated;else throw O.invalidParameterError(`join.animated`,`boolean`,t.join.animated)}if(O.defined(t.join.across)){if(O.integer(t.join.across)&&O.inRange(t.join.across,1,1e6))r.joinAcross=t.join.across;else throw O.invalidParameterError(`join.across`,`integer between 1 and 100000`,t.join.across)}if(O.defined(t.join.shim)){if(O.integer(t.join.shim)&&O.inRange(t.join.shim,0,1e6))r.joinShim=t.join.shim;else throw O.invalidParameterError(`join.shim`,`integer between 0 and 100000`,t.join.shim)}if(O.defined(t.join.background)&&(r.joinBackground=this._getBackgroundColourOption(t.join.background)),O.defined(t.join.halign)){if(O.string(t.join.halign)&&O.string(this.constructor.align[t.join.halign]))r.joinHalign=this.constructor.align[t.join.halign];else throw O.invalidParameterError(`join.halign`,`valid alignment`,t.join.halign)}if(O.defined(t.join.valign)){if(O.string(t.join.valign)&&O.string(this.constructor.align[t.join.valign]))r.joinValign=this.constructor.align[t.join.valign];else throw O.invalidParameterError(`join.valign`,`valid alignment`,t.join.valign)}}else throw Error(`Expected input to be an array of images to join`)}}else if(O.defined(t))throw Error(`Invalid input options ${t}`);return r}function qt(e,t,n){Array.isArray(this.options.input.buffer)?O.buffer(e)?(this.options.input.buffer.push(e),n()):n(/* @__PURE__ */ Error(`Non-Buffer data on Writable Stream`)):n(/* @__PURE__ */ Error(`Unexpected data on Writable Stream`))}function Jt(){this._isStreamInput()&&(this.options.input.buffer=u.concat(this.options.input.buffer))}function Yt(){return Array.isArray(this.options.input.buffer)}function Xt(e){this.writableFinished?e():this.once(`finish`,e)}function Zt(e){let t=Error();return O.fn(e)?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.metadata(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)})}):k.metadata(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)}),this):this._isStreamInput()?new Promise((e,n)=>{this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.metadata(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}):new Promise((e,n)=>{k.metadata(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}function Qt(e){let t=Error();return O.fn(e)?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.stats(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)})}):k.stats(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)}),this):this._isStreamInput()?new Promise((e,n)=>{this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.stats(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}):new Promise((e,n)=>{k.stats(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}var $t=e=>{Object.assign(e.prototype,{_inputOptionsFromObject:Gt,_createInputDescriptor:Kt,_write:qt,_flattenBufferIn:Jt,_isStreamInput:Yt,_whenStreamInFinished:Xt,metadata:Zt,stats:Qt}),e.align=Ut};
38
+ const Ut={left:`low`,top:`low`,low:`low`,center:`centre`,centre:`centre`,right:`high`,bottom:`high`,high:`high`},Wt=[`failOn`,`limitInputPixels`,`limitInputChannels`,`unlimited`,`animated`,`autoOrient`,`density`,`ignoreIcc`,`page`,`pages`,`sequentialRead`,`jp2`,`openSlide`,`pdf`,`raw`,`svg`,`tiff`,`openSlideLevel`,`pdfBackground`,`tiffSubifd`];function Gt(e){let t=Wt.filter(t=>O.defined(e[t])).map(t=>[t,e[t]]);return t.length?Object.fromEntries(t):void 0}function Kt(e,t,n){let r={autoOrient:!1,failOn:`warning`,limitInputPixels:16383**2,limitInputChannels:5,ignoreIcc:!1,unlimited:!1,sequentialRead:!0};if(O.string(e))r.file=e;else if(O.buffer(e)){if(e.length===0)throw Error(`Input Buffer is empty`);r.buffer=e}else if(O.arrayBuffer(e)){if(e.byteLength===0)throw Error(`Input bit Array is empty`);r.buffer=d.from(e,0,e.byteLength)}else if(O.typedArray(e)){if(e.length===0)throw Error(`Input Bit Array is empty`);r.buffer=d.from(e.buffer,e.byteOffset,e.byteLength)}else if(O.plainObject(e)&&!O.defined(t))t=e,Gt(t)&&(r.buffer=[]);else if(!O.defined(e)&&!O.defined(t)&&O.object(n)&&n.allowStream)r.buffer=[];else if(Array.isArray(e)){if(e.length>1){if(!this.options.joining)this.options.joining=!0,this.options.join=e.map(e=>this._createInputDescriptor(e));else throw Error(`Recursive join is unsupported`)}else throw Error(`Expected at least two images to join`)}else throw Error(`Unsupported input '${e}' of type ${typeof e}${O.defined(t)?` when also providing options of type ${typeof t}`:``}`);if(O.object(t)){if(O.defined(t.failOn)){if(O.string(t.failOn)&&O.inArray(t.failOn,[`none`,`truncated`,`error`,`warning`]))r.failOn=t.failOn;else throw O.invalidParameterError(`failOn`,`one of: none, truncated, error, warning`,t.failOn)}if(O.defined(t.autoOrient)){if(O.bool(t.autoOrient))r.autoOrient=t.autoOrient;else throw O.invalidParameterError(`autoOrient`,`boolean`,t.autoOrient)}if(O.defined(t.density)){if(O.number(t.density)&&O.inRange(t.density,1,1e5))r.density=t.density;else throw O.invalidParameterError(`density`,`number between 1 and 100000`,t.density)}if(O.defined(t.ignoreIcc)){if(O.bool(t.ignoreIcc))r.ignoreIcc=t.ignoreIcc;else throw O.invalidParameterError(`ignoreIcc`,`boolean`,t.ignoreIcc)}if(O.defined(t.limitInputPixels)){if(O.bool(t.limitInputPixels))r.limitInputPixels=t.limitInputPixels?16383**2:0;else if(O.integer(t.limitInputPixels)&&O.inRange(t.limitInputPixels,0,2**53-1))r.limitInputPixels=t.limitInputPixels;else throw O.invalidParameterError(`limitInputPixels`,`positive integer`,t.limitInputPixels)}if(O.defined(t.limitInputChannels)){if(O.bool(t.limitInputChannels))r.limitInputChannels=t.limitInputChannels?5:0;else if(O.integer(t.limitInputChannels)&&O.inRange(t.limitInputChannels,0,2**53-1))r.limitInputChannels=t.limitInputChannels;else throw O.invalidParameterError(`limitInputChannels`,`positive integer`,t.limitInputChannels)}if(O.defined(t.unlimited)){if(O.bool(t.unlimited))r.unlimited=t.unlimited;else throw O.invalidParameterError(`unlimited`,`boolean`,t.unlimited)}if(O.defined(t.sequentialRead)){if(O.bool(t.sequentialRead))r.sequentialRead=t.sequentialRead;else throw O.invalidParameterError(`sequentialRead`,`boolean`,t.sequentialRead)}if(O.defined(t.raw)){if(O.object(t.raw)&&O.integer(t.raw.width)&&O.inRange(t.raw.width,1,1e8)&&O.integer(t.raw.height)&&O.inRange(t.raw.height,1,1e8)&&O.integer(t.raw.channels)&&O.inRange(t.raw.channels,1,4))switch(r.rawWidth=t.raw.width,r.rawHeight=t.raw.height,r.rawChannels=t.raw.channels,e.constructor){case Uint8Array:case Uint8ClampedArray:r.rawDepth=`uchar`;break;case Int8Array:r.rawDepth=`char`;break;case Uint16Array:r.rawDepth=`ushort`;break;case Int16Array:r.rawDepth=`short`;break;case Uint32Array:r.rawDepth=`uint`;break;case Int32Array:r.rawDepth=`int`;break;case Float32Array:r.rawDepth=`float`;break;case Float64Array:r.rawDepth=`double`;break;default:r.rawDepth=`uchar`}else throw Error(`Expected width, height and channels for raw pixel input`);if(r.rawPremultiplied=!1,O.defined(t.raw.premultiplied)){if(O.bool(t.raw.premultiplied))r.rawPremultiplied=t.raw.premultiplied;else throw O.invalidParameterError(`raw.premultiplied`,`boolean`,t.raw.premultiplied)}if(r.rawPageHeight=0,O.defined(t.raw.pageHeight)){if(O.integer(t.raw.pageHeight)&&t.raw.pageHeight>0&&t.raw.pageHeight<=t.raw.height){if(t.raw.height%t.raw.pageHeight!==0)throw Error(`Expected raw.height ${t.raw.height} to be a multiple of raw.pageHeight ${t.raw.pageHeight}`);r.rawPageHeight=t.raw.pageHeight}else throw O.invalidParameterError(`raw.pageHeight`,`positive integer`,t.raw.pageHeight)}}if(O.defined(t.animated)){if(O.bool(t.animated))r.pages=t.animated?-1:1;else throw O.invalidParameterError(`animated`,`boolean`,t.animated)}if(O.defined(t.pages)){if(O.integer(t.pages)&&O.inRange(t.pages,-1,1e5))r.pages=t.pages;else throw O.invalidParameterError(`pages`,`integer between -1 and 100000`,t.pages)}if(O.defined(t.page)){if(O.integer(t.page)&&O.inRange(t.page,0,1e5))r.page=t.page;else throw O.invalidParameterError(`page`,`integer between 0 and 100000`,t.page)}if(O.object(t.openSlide)&&O.defined(t.openSlide.level)){if(O.integer(t.openSlide.level)&&O.inRange(t.openSlide.level,0,256))r.openSlideLevel=t.openSlide.level;else throw O.invalidParameterError(`openSlide.level`,`integer between 0 and 256`,t.openSlide.level)}else if(O.defined(t.level)){if(O.integer(t.level)&&O.inRange(t.level,0,256))r.openSlideLevel=t.level;else throw O.invalidParameterError(`level`,`integer between 0 and 256`,t.level)}if(O.object(t.tiff)&&O.defined(t.tiff.subifd)){if(O.integer(t.tiff.subifd)&&O.inRange(t.tiff.subifd,-1,1e5))r.tiffSubifd=t.tiff.subifd;else throw O.invalidParameterError(`tiff.subifd`,`integer between -1 and 100000`,t.tiff.subifd)}else if(O.defined(t.subifd)){if(O.integer(t.subifd)&&O.inRange(t.subifd,-1,1e5))r.tiffSubifd=t.subifd;else throw O.invalidParameterError(`subifd`,`integer between -1 and 100000`,t.subifd)}if(O.object(t.svg)){if(O.defined(t.svg.stylesheet)){if(O.string(t.svg.stylesheet))r.svgStylesheet=t.svg.stylesheet;else throw O.invalidParameterError(`svg.stylesheet`,`string`,t.svg.stylesheet)}if(O.defined(t.svg.highBitdepth)){if(O.bool(t.svg.highBitdepth))r.svgHighBitdepth=t.svg.highBitdepth;else throw O.invalidParameterError(`svg.highBitdepth`,`boolean`,t.svg.highBitdepth)}}if(O.object(t.pdf)&&O.defined(t.pdf.background)?r.pdfBackground=this._getBackgroundColourOption(t.pdf.background):O.defined(t.pdfBackground)&&(r.pdfBackground=this._getBackgroundColourOption(t.pdfBackground)),O.object(t.jp2)&&O.defined(t.jp2.oneshot)){if(O.bool(t.jp2.oneshot))r.jp2Oneshot=t.jp2.oneshot;else throw O.invalidParameterError(`jp2.oneshot`,`boolean`,t.jp2.oneshot)}if(O.defined(t.create)){if(O.object(t.create)&&O.integer(t.create.width)&&O.inRange(t.create.width,1,1e8)&&O.integer(t.create.height)&&O.inRange(t.create.height,1,1e8)&&O.integer(t.create.channels)){if(r.createWidth=t.create.width,r.createHeight=t.create.height,r.createChannels=t.create.channels,r.createPageHeight=0,O.defined(t.create.pageHeight)){if(O.integer(t.create.pageHeight)&&t.create.pageHeight>0&&t.create.pageHeight<=t.create.height){if(t.create.height%t.create.pageHeight!==0)throw Error(`Expected create.height ${t.create.height} to be a multiple of create.pageHeight ${t.create.pageHeight}`);r.createPageHeight=t.create.pageHeight}else throw O.invalidParameterError(`create.pageHeight`,`positive integer`,t.create.pageHeight)}if(O.defined(t.create.noise)){if(!O.object(t.create.noise))throw Error(`Expected noise to be an object`);if(t.create.noise.type!==`gaussian`)throw Error(`Only gaussian noise is supported at the moment`);if(r.createNoiseType=t.create.noise.type,!O.inRange(t.create.channels,1,4))throw O.invalidParameterError(`create.channels`,`number between 1 and 4`,t.create.channels);if(r.createNoiseMean=128,O.defined(t.create.noise.mean)){if(O.number(t.create.noise.mean)&&O.inRange(t.create.noise.mean,0,1e4))r.createNoiseMean=t.create.noise.mean;else throw O.invalidParameterError(`create.noise.mean`,`number between 0 and 10000`,t.create.noise.mean)}if(r.createNoiseSigma=30,O.defined(t.create.noise.sigma)){if(O.number(t.create.noise.sigma)&&O.inRange(t.create.noise.sigma,0,1e4))r.createNoiseSigma=t.create.noise.sigma;else throw O.invalidParameterError(`create.noise.sigma`,`number between 0 and 10000`,t.create.noise.sigma)}}else if(O.defined(t.create.background)){if(!O.inRange(t.create.channels,3,4))throw O.invalidParameterError(`create.channels`,`number between 3 and 4`,t.create.channels);r.createBackground=this._getBackgroundColourOption(t.create.background)}else throw Error(`Expected valid noise or background to create a new input image`);delete r.buffer}else throw Error(`Expected valid width, height and channels to create a new input image`)}if(O.defined(t.text)){if(O.object(t.text)&&O.string(t.text.text)){if(r.textValue=t.text.text,O.defined(t.text.height)&&O.defined(t.text.dpi))throw Error(`Expected only one of dpi or height`);if(O.defined(t.text.font)){if(O.string(t.text.font))r.textFont=t.text.font;else throw O.invalidParameterError(`text.font`,`string`,t.text.font)}if(O.defined(t.text.fontfile)){if(O.string(t.text.fontfile))r.textFontfile=t.text.fontfile;else throw O.invalidParameterError(`text.fontfile`,`string`,t.text.fontfile)}if(O.defined(t.text.width)){if(O.integer(t.text.width)&&O.inRange(t.text.width,1,1e6))r.textWidth=t.text.width;else throw O.invalidParameterError(`text.width`,`integer between 1 and 1000000`,t.text.width)}if(O.defined(t.text.height)){if(O.integer(t.text.height)&&O.inRange(t.text.height,1,1e6))r.textHeight=t.text.height;else throw O.invalidParameterError(`text.height`,`integer between 1 and 1000000`,t.text.height)}if(O.defined(t.text.align)){if(O.string(t.text.align)&&O.string(this.constructor.align[t.text.align]))r.textAlign=this.constructor.align[t.text.align];else throw O.invalidParameterError(`text.align`,`valid alignment`,t.text.align)}if(O.defined(t.text.justify)){if(O.bool(t.text.justify))r.textJustify=t.text.justify;else throw O.invalidParameterError(`text.justify`,`boolean`,t.text.justify)}if(O.defined(t.text.dpi)){if(O.integer(t.text.dpi)&&O.inRange(t.text.dpi,1,1e6))r.textDpi=t.text.dpi;else throw O.invalidParameterError(`text.dpi`,`integer between 1 and 1000000`,t.text.dpi)}if(O.defined(t.text.rgba)){if(O.bool(t.text.rgba))r.textRgba=t.text.rgba;else throw O.invalidParameterError(`text.rgba`,`bool`,t.text.rgba)}if(O.defined(t.text.spacing)){if(O.integer(t.text.spacing)&&O.inRange(t.text.spacing,-1e6,1e6))r.textSpacing=t.text.spacing;else throw O.invalidParameterError(`text.spacing`,`integer between -1000000 and 1000000`,t.text.spacing)}if(O.defined(t.text.wrap)){if(O.string(t.text.wrap)&&O.inArray(t.text.wrap,[`word`,`char`,`word-char`,`none`]))r.textWrap=t.text.wrap;else throw O.invalidParameterError(`text.wrap`,`one of: word, char, word-char, none`,t.text.wrap)}delete r.buffer}else throw Error(`Expected a valid string to create an image with text.`)}if(O.defined(t.join)){if(O.defined(this.options.join)){if(O.defined(t.join.animated)){if(O.bool(t.join.animated))r.joinAnimated=t.join.animated;else throw O.invalidParameterError(`join.animated`,`boolean`,t.join.animated)}if(O.defined(t.join.across)){if(O.integer(t.join.across)&&O.inRange(t.join.across,1,1e6))r.joinAcross=t.join.across;else throw O.invalidParameterError(`join.across`,`integer between 1 and 100000`,t.join.across)}if(O.defined(t.join.shim)){if(O.integer(t.join.shim)&&O.inRange(t.join.shim,0,1e6))r.joinShim=t.join.shim;else throw O.invalidParameterError(`join.shim`,`integer between 0 and 100000`,t.join.shim)}if(O.defined(t.join.background)&&(r.joinBackground=this._getBackgroundColourOption(t.join.background)),O.defined(t.join.halign)){if(O.string(t.join.halign)&&O.string(this.constructor.align[t.join.halign]))r.joinHalign=this.constructor.align[t.join.halign];else throw O.invalidParameterError(`join.halign`,`valid alignment`,t.join.halign)}if(O.defined(t.join.valign)){if(O.string(t.join.valign)&&O.string(this.constructor.align[t.join.valign]))r.joinValign=this.constructor.align[t.join.valign];else throw O.invalidParameterError(`join.valign`,`valid alignment`,t.join.valign)}}else throw Error(`Expected input to be an array of images to join`)}}else if(O.defined(t))throw Error(`Invalid input options ${t}`);return r}function qt(e,t,n){Array.isArray(this.options.input.buffer)?O.buffer(e)?(this.options.input.buffer.push(e),n()):n(/* @__PURE__ */ Error(`Non-Buffer data on Writable Stream`)):n(/* @__PURE__ */ Error(`Unexpected data on Writable Stream`))}function Jt(){this._isStreamInput()&&(this.options.input.buffer=d.concat(this.options.input.buffer))}function Yt(){return Array.isArray(this.options.input.buffer)}function Xt(e){this.writableFinished?e():this.once(`finish`,e)}function Zt(e){let t=Error();return O.fn(e)?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.metadata(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)})}):k.metadata(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)}),this):this._isStreamInput()?new Promise((e,n)=>{this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.metadata(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}):new Promise((e,n)=>{k.metadata(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}function Qt(e){let t=Error();return O.fn(e)?(this._isStreamInput()?this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.stats(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)})}):k.stats(this.options,(n,r)=>{n?e(O.nativeError(n,t)):e(null,r)}),this):this._isStreamInput()?new Promise((e,n)=>{this._whenStreamInFinished(()=>{this._flattenBufferIn(),k.stats(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}):new Promise((e,n)=>{k.stats(this.options,(r,i)=>{r?n(O.nativeError(r,t)):e(i)})})}var $t=e=>{Object.assign(e.prototype,{_inputOptionsFromObject:Gt,_createInputDescriptor:Kt,_write:qt,_flattenBufferIn:Jt,_isStreamInput:Yt,_whenStreamInFinished:Xt,metadata:Zt,stats:Qt}),e.align=Ut};
39
39
  /*!
40
40
  Copyright 2013 Lovell Fuller and others.
41
41
  SPDX-License-Identifier: Apache-2.0
@@ -78,12 +78,12 @@ if(!Jr.isGlobal){if(Jr.isWasm)try{Zr=Kr(`@img/sharp-wasm32/versions`)}catch{}els
78
78
  /* node:coverage ignore next 5 */
79
79
  Zr.sharp=it.version,Zr.heif&&Yr.heif&&(Yr.heif.input.fileSuffix=[`.avif`],Yr.heif.output.alias=[`avif`]);function Qr(e){if(O.bool(e))return e?k.cache(50,20,100):k.cache(0,0,0);if(O.object(e)){for(let t of[`memory`,`files`,`items`]){let n=e[t];if(O.defined(n)&&!(O.integer(n)&&n>=0))throw O.invalidParameterError(t,`a positive integer`,n)}return k.cache(e.memory,e.files,e.items)}return k.cache()}Qr(!0);function $r(e){return k.concurrency(O.integer(e)?e:null)}
80
80
  /* node:coverage ignore next 7 */
81
- !l.env.MALLOC_ARENA_MAX&&ot.default.familySync()===ot.default.GLIBC&&!k._isUsingJemalloc()?k.concurrency(1):ot.default.familySync()===ot.default.MUSL&&k.concurrency()===1024&&k.concurrency(h());const ei=new f.EventEmitter;function ti(){return k.counters()}function ni(e){return k.simd(O.bool(e)?e:null)}function ri(e){if(O.object(e)){if(Array.isArray(e.operation)&&e.operation.every(O.string))k.block(e.operation,!0);else throw O.invalidParameterError(`operation`,`Array<string>`,e.operation)}else throw O.invalidParameterError(`options`,`object`,e)}function ii(e){if(O.object(e)){if(Array.isArray(e.operation)&&e.operation.every(O.string))k.block(e.operation,!1);else throw O.invalidParameterError(`operation`,`Array<string>`,e.operation)}else throw O.invalidParameterError(`options`,`object`,e)}
81
+ !l.env.MALLOC_ARENA_MAX&&ot.default.familySync()===ot.default.GLIBC&&!k._isUsingJemalloc()?k.concurrency(1):ot.default.familySync()===ot.default.MUSL&&k.concurrency()===1024&&k.concurrency(g());const ei=new p.EventEmitter;function ti(){return k.counters()}function ni(e){return k.simd(O.bool(e)?e:null)}function ri(e){if(O.object(e)){if(Array.isArray(e.operation)&&e.operation.every(O.string))k.block(e.operation,!0);else throw O.invalidParameterError(`operation`,`Array<string>`,e.operation)}else throw O.invalidParameterError(`options`,`object`,e)}function ii(e){if(O.object(e)){if(Array.isArray(e.operation)&&e.operation.every(O.string))k.block(e.operation,!1);else throw O.invalidParameterError(`operation`,`Array<string>`,e.operation)}else throw O.invalidParameterError(`options`,`object`,e)}
82
82
  /*!
83
83
  Copyright 2013 Lovell Fuller and others.
84
84
  SPDX-License-Identifier: Apache-2.0
85
85
  */
86
- $t(Vt),mn(Vt),_n(Vt),Hn(Vt),tr(Vt),cr(Vt),Gr(Vt),(e=>{e.cache=Qr,e.concurrency=$r,e.counters=ti,e.simd=ni,e.format=Yr,e.interpolators=Xr,e.versions=Zr,e.queue=ei,e.block=ri,e.unblock=ii})(Vt);var ai=Vt,oi=Object.defineProperty,si=/* @__PURE__ */ (t=>e===void 0?typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(e===void 0?t:e)[n]}):t:e)(function(t){if(e!==void 0)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),ci=(e,t)=>{for(var n in t)oi(e,n,{get:t[n],enumerable:!0})},li=`4.3.1`,ui=typeof self<`u`,di=!Fi(d),fi=!Fi(m),pi=ui&&`caches`in self,mi=globalThis.Deno!==void 0;globalThis.Bun;var hi=mi&&pi&&!di,gi=l!==void 0,_i=gi&&l?.release?.name===`node`&&!hi,vi=typeof window<`u`&&window.document!==void 0,yi=ui&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),bi=vi||yi||hi,xi=_i||typeof navigator<`u`&&`gpu`in navigator,Si=typeof navigator<`u`&&`ml`in navigator,Ci=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,wi=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,Ti=typeof ServiceWorkerGlobalScope<`u`&&ui&&self instanceof ServiceWorkerGlobalScope,Ei=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!((navigator.vendor||``).indexOf(`Apple`)>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`)))return!1;let t=e.match(/Version\/(\d+)/);return t?parseInt(t[1],10)<26:!1})(),j=Object.freeze({IS_BROWSER_ENV:vi,IS_WEBWORKER_ENV:yi,IS_WEB_ENV:bi,IS_SERVICE_WORKER_ENV:Ti,IS_DENO_WEB_RUNTIME:hi,IS_WEB_CACHE_AVAILABLE:pi,IS_WEBGPU_AVAILABLE:xi,IS_WEBNN_AVAILABLE:Si,IS_SAFARI_BELOW_26:Ei,IS_PROCESS_AVAILABLE:gi,IS_NODE_ENV:_i,IS_FS_AVAILABLE:di,IS_PATH_AVAILABLE:fi,IS_CRYPTO_AVAILABLE:Ci,IS_CHROME_AVAILABLE:wi}),Di=di&&fi,Oi=`./`;if(Di){let e=import.meta.url;e?Oi=m.dirname(m.dirname(_.fileURLToPath(e))):typeof __dirname<`u`&&(Oi=m.dirname(__dirname))}var ki=Di?m.join(Oi,`/.cache/`):null,Ai=`/models/`,ji=Di?m.join(Oi,Ai):Ai,Mi=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,Ni=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Pi=Ni.WARNING,M={version:li,backends:{onnx:{}},get logLevel(){return Pi},set logLevel(e){Pi=e,M.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(vi||yi||hi),localModelPath:ji,useFS:di,useBrowserCache:pi,useFSCache:di,cacheDir:ki,useCustomCache:!1,customCache:null,useWasmCache:pi||di,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Mi};function Fi(e){return Object.keys(e).length===0}var Ii=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function Li(e,t){e&&e(t)}var Ri=class extends Ii{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=/* @__PURE__ */ new Map}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function zi(e){return Number.isInteger(e)||typeof e==`bigint`}function Bi(e){return e==null||e===-1}function Vi(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function Hi(...e){return Array.prototype.concat.apply([],e)}function Ui(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function Wi(e,t){return Math.abs((e+t)%(2*t)-t)}function Gi(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function Ki(e,t){let n=0;for(let r of e)r===t&&++n;return n}var N={error(...e){M.logLevel<=Ni.ERROR&&console.error(...e)},warn(...e){M.logLevel<=Ni.WARNING&&console.warn(...e)},info(...e){M.logLevel<=Ni.INFO&&console.log(...e)},debug(...e){M.logLevel<=Ni.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},qi=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=/* @__PURE__ */ Object.create(null);for(let n of e){let e=t;for(let t=0;t<n.length;++t){let r=n[t];e=e[r]??=/* @__PURE__ */ Object.create(null)}e.end=n}return t}split(e){let t=[],n=e.length,r=0,i=0;for(;i<n;){let a=this.trie,o=null,s=i;for(;s<n&&(a=a[e[s]]);)a.end&&(o=a.end),++s;o?(i>r&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r<n&&t.push(e.slice(r)),t}},Ji=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},Yi=(e,t)=>{try{return new RegExp(e,t)}catch(n){if(!(n instanceof SyntaxError))throw n;let r=/* @__PURE__ */ new Map,i=e.replace(/(\\[pP])\{([^}=]+)\}/g,(t,n,i,a)=>{let o=0;for(let t=a-1;t>=0&&e[t]===`\\`;--t)++o;if(o%2==1)return t;let s=r.get(i);if(s===void 0){try{RegExp(`\\p{${i}}`,`u`),s=i}catch{s=`Script=${i}`}r.set(i,s)}return`${n}{${s}}`});if(i===e)throw n;try{return new RegExp(i,t)}catch{throw n}}},Xi=e=>e.replace(/ \./g,`.`).replace(/ \?/g,`?`).replace(/ \!/g,`!`).replace(/ ,/g,`,`).replace(/ \' /g,`'`).replace(/ n't/g,`n't`).replace(/ 'm/g,`'m`).replace(/ 's/g,`'s`).replace(/ 've/g,`'ve`).replace(/ 're/g,`'re`),Zi=(e,t=!0)=>{if(e.Regex!==void 0)return Yi(Ma(Sa(e.Regex)),`gu`);if(e.String!==void 0){let n=Na(e.String);return new RegExp(t?n:`(${n})`,`gu`)}return console.warn(`Unknown pattern type:`,e),null},Qi=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}`,$i=`${Qi}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,ea=`[${$i}]`,ta=`[^${$i}]`,na=`(?:(?<!${ea})(?=${ea})|(?<=${ea})(?!${ea}))`,ra=`(?:(?<!${ea})(?!${ea})|(?<=${ea})(?=${ea}))`,ia=`(?:(?<![\\s\\S])|(?<=\\n))`,aa=`(?:(?=\\n)|(?![\\s\\S]))`,oa=`0-9A-Fa-f`,sa=/* @__PURE__ */ new Map([[`A`,`(?<![\\s\\S])`],[`z`,`(?![\\s\\S])`],[`Z`,`(?=\\n?(?![\\s\\S]))`],[`h`,`[${oa}]`],[`H`,`[^${oa}]`],[`w`,ea],[`W`,ta],[`d`,`\\p{Nd}`],[`D`,`\\P{Nd}`],[`s`,`\\p{White_Space}`],[`S`,`\\P{White_Space}`],[`b`,na],[`B`,ra],[`a`,`\\x07`],[`e`,`\\x1B`]]),ca=/* @__PURE__ */ new Map([[`h`,oa],[`w`,Qi],[`d`,`\\p{Nd}`],[`D`,`\\P{Nd}`],[`s`,`\\p{White_Space}`],[`S`,`\\P{White_Space}`],[`a`,`\\x07`],[`e`,`\\x1B`]]),la=/* @__PURE__ */ new Map([[`W`,`[^${Qi}]`],[`H`,`[^${oa}]`]]),ua=/* @__PURE__ */ new Map([[`
86
+ $t(Vt),mn(Vt),_n(Vt),Hn(Vt),tr(Vt),cr(Vt),Gr(Vt),(e=>{e.cache=Qr,e.concurrency=$r,e.counters=ti,e.simd=ni,e.format=Yr,e.interpolators=Xr,e.versions=Zr,e.queue=ei,e.block=ri,e.unblock=ii})(Vt);var ai=Vt,oi=Object.defineProperty,si=/* @__PURE__ */ (t=>e===void 0?typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(e===void 0?t:e)[n]}):t:e)(function(t){if(e!==void 0)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),ci=(e,t)=>{for(var n in t)oi(e,n,{get:t[n],enumerable:!0})},li=`4.3.1`,ui=typeof self<`u`,di=!Fi(f),fi=!Fi(h),pi=ui&&`caches`in self,mi=globalThis.Deno!==void 0;globalThis.Bun;var hi=mi&&pi&&!di,gi=l!==void 0,_i=gi&&l?.release?.name===`node`&&!hi,vi=typeof window<`u`&&window.document!==void 0,yi=ui&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),bi=vi||yi||hi,xi=_i||typeof navigator<`u`&&`gpu`in navigator,Si=typeof navigator<`u`&&`ml`in navigator,Ci=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,wi=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,Ti=typeof ServiceWorkerGlobalScope<`u`&&ui&&self instanceof ServiceWorkerGlobalScope,Ei=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!((navigator.vendor||``).indexOf(`Apple`)>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`)))return!1;let t=e.match(/Version\/(\d+)/);return t?parseInt(t[1],10)<26:!1})(),j=Object.freeze({IS_BROWSER_ENV:vi,IS_WEBWORKER_ENV:yi,IS_WEB_ENV:bi,IS_SERVICE_WORKER_ENV:Ti,IS_DENO_WEB_RUNTIME:hi,IS_WEB_CACHE_AVAILABLE:pi,IS_WEBGPU_AVAILABLE:xi,IS_WEBNN_AVAILABLE:Si,IS_SAFARI_BELOW_26:Ei,IS_PROCESS_AVAILABLE:gi,IS_NODE_ENV:_i,IS_FS_AVAILABLE:di,IS_PATH_AVAILABLE:fi,IS_CRYPTO_AVAILABLE:Ci,IS_CHROME_AVAILABLE:wi}),Di=di&&fi,Oi=`./`;if(Di){let e=import.meta.url;e?Oi=h.dirname(h.dirname(_.fileURLToPath(e))):typeof __dirname<`u`&&(Oi=h.dirname(__dirname))}var ki=Di?h.join(Oi,`/.cache/`):null,Ai=`/models/`,ji=Di?h.join(Oi,Ai):Ai,Mi=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,Ni=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Pi=Ni.WARNING,M={version:li,backends:{onnx:{}},get logLevel(){return Pi},set logLevel(e){Pi=e,M.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(vi||yi||hi),localModelPath:ji,useFS:di,useBrowserCache:pi,useFSCache:di,cacheDir:ki,useCustomCache:!1,customCache:null,useWasmCache:pi||di,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Mi};function Fi(e){return Object.keys(e).length===0}var Ii=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function Li(e,t){e&&e(t)}var Ri=class extends Ii{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=/* @__PURE__ */ new Map}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function zi(e){return Number.isInteger(e)||typeof e==`bigint`}function Bi(e){return e==null||e===-1}function Vi(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function Hi(...e){return Array.prototype.concat.apply([],e)}function Ui(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function Wi(e,t){return Math.abs((e+t)%(2*t)-t)}function Gi(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function Ki(e,t){let n=0;for(let r of e)r===t&&++n;return n}var N={error(...e){M.logLevel<=Ni.ERROR&&console.error(...e)},warn(...e){M.logLevel<=Ni.WARNING&&console.warn(...e)},info(...e){M.logLevel<=Ni.INFO&&console.log(...e)},debug(...e){M.logLevel<=Ni.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},qi=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=/* @__PURE__ */ Object.create(null);for(let n of e){let e=t;for(let t=0;t<n.length;++t){let r=n[t];e=e[r]??=/* @__PURE__ */ Object.create(null)}e.end=n}return t}split(e){let t=[],n=e.length,r=0,i=0;for(;i<n;){let a=this.trie,o=null,s=i;for(;s<n&&(a=a[e[s]]);)a.end&&(o=a.end),++s;o?(i>r&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r<n&&t.push(e.slice(r)),t}},Ji=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},Yi=(e,t)=>{try{return new RegExp(e,t)}catch(n){if(!(n instanceof SyntaxError))throw n;let r=/* @__PURE__ */ new Map,i=e.replace(/(\\[pP])\{([^}=]+)\}/g,(t,n,i,a)=>{let o=0;for(let t=a-1;t>=0&&e[t]===`\\`;--t)++o;if(o%2==1)return t;let s=r.get(i);if(s===void 0){try{RegExp(`\\p{${i}}`,`u`),s=i}catch{s=`Script=${i}`}r.set(i,s)}return`${n}{${s}}`});if(i===e)throw n;try{return new RegExp(i,t)}catch{throw n}}},Xi=e=>e.replace(/ \./g,`.`).replace(/ \?/g,`?`).replace(/ \!/g,`!`).replace(/ ,/g,`,`).replace(/ \' /g,`'`).replace(/ n't/g,`n't`).replace(/ 'm/g,`'m`).replace(/ 's/g,`'s`).replace(/ 've/g,`'ve`).replace(/ 're/g,`'re`),Zi=(e,t=!0)=>{if(e.Regex!==void 0)return Yi(Ma(Sa(e.Regex)),`gu`);if(e.String!==void 0){let n=Na(e.String);return new RegExp(t?n:`(${n})`,`gu`)}return console.warn(`Unknown pattern type:`,e),null},Qi=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}`,$i=`${Qi}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,ea=`[${$i}]`,ta=`[^${$i}]`,na=`(?:(?<!${ea})(?=${ea})|(?<=${ea})(?!${ea}))`,ra=`(?:(?<!${ea})(?!${ea})|(?<=${ea})(?=${ea}))`,ia=`(?:(?<![\\s\\S])|(?<=\\n))`,aa=`(?:(?=\\n)|(?![\\s\\S]))`,oa=`0-9A-Fa-f`,sa=/* @__PURE__ */ new Map([[`A`,`(?<![\\s\\S])`],[`z`,`(?![\\s\\S])`],[`Z`,`(?=\\n?(?![\\s\\S]))`],[`h`,`[${oa}]`],[`H`,`[^${oa}]`],[`w`,ea],[`W`,ta],[`d`,`\\p{Nd}`],[`D`,`\\P{Nd}`],[`s`,`\\p{White_Space}`],[`S`,`\\P{White_Space}`],[`b`,na],[`B`,ra],[`a`,`\\x07`],[`e`,`\\x1B`]]),ca=/* @__PURE__ */ new Map([[`h`,oa],[`w`,Qi],[`d`,`\\p{Nd}`],[`D`,`\\P{Nd}`],[`s`,`\\p{White_Space}`],[`S`,`\\P{White_Space}`],[`a`,`\\x07`],[`e`,`\\x1B`]]),la=/* @__PURE__ */ new Map([[`W`,`[^${Qi}]`],[`H`,`[^${oa}]`]]),ua=/* @__PURE__ */ new Map([[`
87
87
  `,`\\n`],[`\r`,`\\r`],[` `,`\\t`],[`\f`,`\\f`],[`\v`,`\\v`]]),da=/* @__PURE__ */ new Map([[`alpha`,`\\p{Alphabetic}`],[`alnum`,`\\p{Alphabetic}\\p{Nd}`],[`digit`,`\\p{Nd}`],[`lower`,`\\p{Lowercase}`],[`upper`,`\\p{Uppercase}`],[`space`,`\\p{White_Space}`],[`blank`,`\\t\\p{Zs}`],[`punct`,`\\p{P}\\p{S}`],[`cntrl`,`\\p{Cc}`],[`word`,Qi],[`xdigit`,oa]]),fa=`^$\\.*+?()[]{}|/`,pa=/^\(\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/,ma=/^\\([pPxu])\{([^}]*)\}/,ha=/^\{(\d+(?:,\d*)?|,\d+)\}/,ga=/^\[:(\^?)(\p{Alphabetic}+):\]/u,_a=/^\[:\^:\]/,va=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,ya=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,ba=e=>e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`,xa=(e,t)=>String.fromCodePoint(e.codePointAt(t)),P=e=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;let t=Number.parseInt(e,16);if(t>127)return null;let n=String.fromCharCode(t);return ba(n)?`[${n.toLowerCase()}${n.toUpperCase()}]`:null},Sa=e=>e.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,`[^()|\\s$1]`),Ca=`[\\s\\S]`,F=256,wa=()=>({fragment:``,alternatives:[],tail:null,contains_complex_set:!1}),I=e=>{throw SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},Ta=(e,t,n,r=!0)=>{e.tail===`range`&&I(n),e.alternatives.push(t),e.tail=`set`,e.contains_complex_set=e.contains_complex_set||r},Ea=(e,t,n=!1,r=-1)=>{n&&e.tail===`range`&&I(r),e.tail===`range`?(e.fragment+=t,e.tail=`complete_range`):(e.fragment+=t,e.tail=n?`set`:`scalar`,e.contains_complex_set=e.contains_complex_set||n)},Da=(e,t,n)=>{let r=ma.exec(e.slice(t));if(r){let[e,i,a]=r;return i===`P`&&a===`Word`?Ta(n,`[^${Qi}]`,t):Ea(n,i===`x`?`\\u{${a}}`:i===`p`&&a===`Word`?Qi:e,i===`p`||i===`P`,t),t+e.length}let i=ya.exec(e.slice(t));if(i)return Ea(n,i[0]),t+i[0].length;if(t+1>=e.length)throw SyntaxError(`Unterminated escape in character class at index ${t}`);let a=xa(e,t+1),o=t+1+a.length,s=ua.get(a);if(s!==void 0)return Ea(n,s),o;let c=la.get(a);if(c!==void 0)return Ta(n,c,t),o;let l=ca.get(a),u,d=!1;return l===void 0?u=/[A-Za-z0-9]/.test(a)||fa.includes(a)||a===`-`?`\\${a}`:a:(u=l,d=a!==`a`&&a!==`e`),Ea(n,u,d,t),o},Oa=e=>e.length===1?e[0]:`(?:(?=(?:${e.join(`|`)}))${Ca})`,ka=e=>Oa(e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives]),Aa=e=>{let t=Yi(`^(?:${e})$`,`u`),n=``;for(let e=0;e<26;++e){let r=String.fromCharCode(65+e),i=String.fromCharCode(97+e),a=t.test(r);a!==t.test(i)&&(n+=a?i:r)}return n},ja=(e,t,n,r=!0,i=1)=>{if(i>F)throw SyntaxError(`Maximum character-class nesting depth of ${F} exceeded at index ${t}`);let a=t+1,o=e[a]===`^`;o&&++a;let s=a,c=[wa()],l=c[0],u=!1;for(;a<e.length;){let d=xa(e,a);if(d===`\\`)a=Da(e,a,l);else{if(d===`]`){if(a===s){Ea(l,`\\]`),++a;continue}if(l.tail===null)throw c.length>1?SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`):SyntaxError(`Empty character class at index ${t}`);let e=c.some(e=>e.contains_complex_set);if(o&&c.length>1&&u)throw SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);let i=ka(c[0]),d=i;if(c.length>1){let e=``;for(let t=1;t<c.length;++t)e+=`(?=${ka(c[t])})`;d=`(?:${e}${i})`}let f=c.length===1&&l.alternatives.length===0,p=l.fragment;if(n&&r){let e=Aa(d);e.length>0&&(f?(p+=e,d=`[${p}]`):d=Oa([d,`[${e}]`]))}return{atom:o?f?`[^${p}]`:`(?:(?!${d})${Ca})`:d,end:a+1,negated:o,contains_complex_set:e,contains_nested_negated_complex_set:u}}if(e.startsWith(`&&`,a)){if(l.tail===null)throw SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);l=wa(),c.push(l),a+=2}else if(d===`[`){let t=e.slice(a);if(_a.test(t))throw SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);let r=ga.exec(t);if(r){let[,e,t]=r,i=da.get(t);if(i===void 0)throw SyntaxError(`Unsupported POSIX character class "${t}" at index ${a}`);if(n&&e&&(t===`lower`||t===`upper`))throw SyntaxError(`Unsupported negated POSIX ${t} class inside an inline case-insensitive group`);e?Ta(l,`[^${i}]`,a):Ea(l,i,!0,a),a+=r[0].length;continue}if(va.test(t))throw SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);let o=ja(e,a,n,!1,i+1);Ta(l,o.atom,a,o.contains_complex_set),u||=o.contains_nested_negated_complex_set||o.negated&&o.contains_complex_set,a=o.end}else if(d===`-`){let t=e[a+1]===`]`||e.startsWith(`&&`,a+1);l.tail===`set`&&!t&&I(a),l.tail===null||l.tail===`range`||l.tail===`complete_range`||t?Ea(l,`\\-`):(l.fragment+=`-`,l.tail=`range`),++a}else Ea(l,d===`^`&&l.fragment.length===0?`\\^`:d),a+=d.length}}throw SyntaxError(`${c.length>1?`Unterminated character-class intersection`:`Unterminated character class`} at index ${t}`)},Ma=e=>{let t=``,n=-1,r=!1,i=!1,a=[],o=e=>{n=t.length,t+=e,r=!1};for(let s=0;s<e.length;){let c=xa(e,s);if(c===`\\`){let n=ma.exec(e.slice(s));if(n){let[e,t,r]=n,a=e;if(t===`x`){let e=`\\u{${r}}`;a=i?P(r)??e:e}else r===`Word`&&(a=t===`p`?ea:ta);o(a),s+=e.length;continue}let r=ya.exec(e.slice(s));if(r){let e=r[0];o(i&&e[1]!==`c`?P(e.slice(2))??e:e),s+=e.length;continue}if(s+1>=e.length){t+=c;break}let a=xa(e,s+1);if(s+=1+a.length,a===`G`)continue;let l=ua.get(a);if(l!==void 0){o(l);continue}let u=sa.get(a),d;d=u===void 0?/[A-Za-z0-9]/.test(a)||fa.includes(a)?`\\${a}`:a:u,o(d)}else switch(c){case`[`:{let t=ja(e,s,i);o(t.atom),s=t.end;continue}case`]`:o(`\\]`),++s;continue;case`.`:o(`[^\\n]`),++s;continue;case`^`:o(ia),++s;continue;case`$`:o(aa),++s;continue;case`(`:{let n=e.startsWith(`(?i:`,s),o=n?`(?i:`:pa.exec(e.slice(s))?.[0]??`(`,c=n||o===`(?>`?`(?:`:o;a.push([t.length,i]),n&&(i=!0),t+=c,r=!1,s+=o.length;continue}case`)`:t+=c,[n,i]=a.pop()??[-1,!1],r=!1,++s;continue;case`|`:t+=c,n=-1,r=!1,++s;continue;case`{`:{let i=ha.exec(e.slice(s));if(!i||n<0){o(`\\{`),++s;continue}let a=i[1].startsWith(`,`)?`0${i[1]}`:i[1];s+=i[0].length;let c=e[s];c===`+`||c===`*`?(t=`${t.slice(0,n)}(?:${t.slice(n)}{${a}})${c}`,++s):t+=`{${a}}`,r=!0;continue}case`}`:o(`\\}`),++s;continue;case`+`:if(r){++s;continue}t+=c,r=!0,++s;continue;case`*`:case`?`:t+=c,r=!0,++s;continue;default:o(i&&ba(c)?`[${c.toLowerCase()}${c.toUpperCase()}]`:c),s+=c.length;continue}}return t},Na=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Pa=(e,t,n)=>{let r=[],i=0;for(;i<e.length;)if(r.push(e[i]),(t.get(e[i])??n)!==n)++i;else for(;++i<e.length&&(t.get(e[i])??n)===n;)t.get(r.at(-1))!==n&&(r[r.length-1]+=e[i]);return r},Fa=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,Ia=e=>Number.isInteger(e)||typeof e==`bigint`,La=e=>{let t=0;for(let n of e)++t;return t},Ra=e=>Ha(e.toLowerCase()),za=(...e)=>Array.prototype.concat.apply([],e),Ba=e=>new Map(Object.entries(e)),Va=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r<i.index&&n.push(e.slice(r,i.index)),t.length>0&&n.push(t),r=i.index+t.length}return r<e.length&&n.push(e.slice(r)),n},Ha=e=>e.replace(/\p{M}/gu,``),Ua=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a "${r}" property`;return null},Wa=e=>e.match(/\S+/g)||[],Ga=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Ka=class extends Ga{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},qa=class extends Ka{tokenize_chinese_chars(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n];Fa(r.charCodeAt(0))?(t.push(` `),t.push(r),t.push(` `)):t.push(r)}return t.join(``)}strip_accents(e){return e.normalize(`NFD`).replace(/\p{Mn}/gu,``)}is_control(e){switch(e){case` `:case`
88
88
  `:case`\r`:return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let n of e){let e=n.charCodeAt(0);e===0||e===65533||this.is_control(n)||(/^\s$/.test(n)?t.push(` `):t.push(n))}return t.join(``)}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},Ja=class extends Ka{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,``),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm,` `),e=e.includes(`~`)?e.split(`~`).map(e=>e.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},Ya=class extends Ka{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>so(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},Xa=class extends Ka{constructor(e){super(e),this.pattern=Zi(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??``)}},Za=class extends Ka{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},Qa=class extends Za{constructor(){super(...arguments),this.form=`NFC`}},$a=class extends Za{constructor(){super(...arguments),this.form=`NFD`}},eo=class extends Za{constructor(){super(...arguments),this.form=`NFKC`}},to=class extends Za{constructor(){super(...arguments),this.form=`NFKD`}},no=class extends Ka{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},ro=class extends Ka{normalize(e){return Ha(e)}},io=class extends Ka{normalize(e){return e.toLowerCase()}},ao=class extends Ka{normalize(e){return e=this.config.prepend+e,e}};function oo(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new qa(e);case`Precompiled`:return new Ja(e);case`Sequence`:return new Ya(e);case`Replace`:return new Xa(e);case`NFC`:return new Qa(e);case`NFD`:return new $a(e);case`NFKC`:return new eo(e);case`NFKD`:return new to(e);case`Strip`:return new no(e);case`StripAccents`:return new ro(e);case`Lowercase`:return new io(e);case`Prepend`:return new ao(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var so=oo,co=class extends Ga{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},lo=(()=>{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),uo=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(lo),fo=`\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E`,po=class extends co{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=lo,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(` `)&&(e=` `+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},mo=class extends co{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},ho=class extends co{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},go=class extends co{constructor(e){super(),this.config=e,this.pattern=Zi(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?(e.match(this.pattern)||[]).filter(e=>e):this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):Va(e,this.pattern)}},_o=class extends co{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${fo}]+|[${fo}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},vo=class extends co{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?``:`+`}`;this.pattern=new RegExp(t,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},yo=class extends co{constructor(){super(),this.pattern=RegExp(`[^\\s${fo}]+|[${fo}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},bo=class extends co{constructor(e){super(),this.config=e,this.pattern=Zi(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},xo=class extends co{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>To(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},So=class extends co{pre_tokenize_text(e){return Wa(e)}},Co=class extends co{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;n<e.length;n+=this._length)t.push(e.slice(n,n+this._length));return t}};function wo(e){if(e===null)return null;switch(e.type){case`BertPreTokenizer`:return new yo;case`Sequence`:return new xo(e);case`Whitespace`:return new mo;case`WhitespaceSplit`:return new So;case`Metaspace`:return new ho(e);case`ByteLevel`:return new po(e);case`Split`:return new go(e);case`Punctuation`:return new _o(e);case`Digits`:return new vo(e);case`Replace`:return new bo(e);case`FixedLength`:return new Co(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}}var To=wo,Eo=class extends Ga{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=/* @__PURE__ */ new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=Pa(t,this.tokens_to_ids,this.unk_token_id)),t}},Do=class extends Eo{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Ba(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){let t=[];for(let n of e){let e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i<e.length;){let t=e.length,n=null;for(;i<t;){let r=e.slice(i,t).join(``);if(i>0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},Oo=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,/* @__PURE__ */ new Map)}},ko=class{constructor(){this.root=Oo.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=Oo.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e,t=0){let n=this.root;if(n===void 0)return;let r=``;for(let i=t;i<e.length;++i){let t=e[i];if(r+=t,n=n.children.get(t),n===void 0)return;n.is_leaf&&(yield r)}}},Ao=class e{constructor(e,t,n,r,i){this.token_id=e,this.node_id=t,this.pos=n,this.length=r,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},jo=class{constructor(e,t,n){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Ao(this.bos_token_id??0,0,0,0,0),i=new Ao(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=this.nodes.length,a=new Ao(r,i,e,t,n);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function Mo(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}var No=class extends Eo{constructor(e,t){super(e);let n=e.vocab.length;this.vocab=Array(n),this.scores=Array(n);for(let t=0;t<n;++t)[this.vocab[t],this.scores[t]]=e.vocab[t];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((e,t)=>[e,t])),this.bos_token=` `,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=Mo(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new ko,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;n<t.length;){let r=!1,i=this.trie.common_prefix_search(t,n);for(let t of i){let i=this.tokens_to_ids.get(t),a=this.scores[i],o=La(t);e.insert(n,o,a,i),!r&&o===1&&(r=!0)}r||e.insert(n,1,this.unk_score,this.unk_token_id),n+=1}}tokenize(e){let t=new jo(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let n of e){let e=this.tokenize(n);t.push(...e)}return t}},Po=class{constructor(e=(e,t)=>e>t,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._sift_up_from(e))}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},Fo=class{constructor(e){this.capacity=e,this.cache=/* @__PURE__ */ new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},Io=class extends Eo{constructor(e){super(e),this.tokens_to_ids=Ba(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new Fo(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new Po((e,t)=>e.score<t.score),t={token:n[0],bias:0,prev:null,next:null},i=t;for(let t=1;t<n.length;++t){let r={bias:t/n.length,token:n[t],prev:i,next:null};i.next=r,this.add_node(e,i),i=r}for(;!e.is_empty();){let n=e.pop();if(n.deleted||!n.next||n.next.deleted)continue;if(n.deleted=!0,n.next.deleted=!0,n.prev){let e={...n.prev};n.prev.deleted=!0,n.prev=e,e.prev?e.prev.next=e:t=e}let r={token:n.token+n.next.token,bias:n.bias,prev:n.prev,next:n.next.next};r.prev?(r.prev.next=r,this.add_node(e,r.prev)):t=r,r.next&&(r.next.prev=r,this.add_node(e,r))}for(let e=t;e!==null;e=e.next)r.push(e.token)}else r=n;if(this.continuing_subword_suffix)for(let e=0;e<r.length-1;++e)r[e]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,r),r}add_node(e,t){let n=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));n!==void 0&&(t.score=n+t.bias,e.push(t))}encode(e){let t=[];for(let n of e){if(this.ignore_merges&&this.tokens_to_ids.has(n)){t.push(n);continue}let e=this.bpe(n);for(let n of e)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){let e=Array.from(this.text_encoder.encode(n)).map(e=>`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},Lo=class extends Eo{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=Ba(t.target_lang?n[t.target_lang]:n),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function Ro(e,t){switch(e.type){case`WordPiece`:return new Do(e);case`Unigram`:return new No(e,t.eos_token);case`BPE`:return new Io(e);default:if(e.vocab)return Array.isArray(e.vocab)?new No(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new Io(e):new Do(e):new Lo(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var zo=Ro,Bo=class extends Ga{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},Vo=class extends Bo{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=za(i,e),a=za(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=za(i,t),a=za(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},Ho=class extends Bo{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},Uo=class extends Bo{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=za([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=za(e,i,t,a),r=za(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Wo=class extends Bo{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=za([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=za(e,i,t,a),r=za(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Go=class extends Bo{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>qo(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function Ko(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new Vo(e);case`ByteLevel`:return new Ho(e);case`BertProcessing`:return new Uo(e);case`RobertaProcessing`:return new Wo(e);case`Sequence`:return new Go(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var qo=Ko,Jo=class extends Ga{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=`trim_offsets`in e&&e.trim_offsets}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},Yo=class extends Jo{constructor(e){super(e),this.byte_decoder=uo,this.text_decoder=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},Xo=class extends Jo{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=Xi(e)),e})}},Zo=class extends Jo{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n].replaceAll(this.replacement,` `);n==0&&r.startsWith(` `)&&(r=r.substring(1)),t.push(r)}return t}},Qo=class extends Jo{constructor(e){super(e),this.suffix=e.suffix??``}decode_chain(e){return e.map((t,n)=>t.replaceAll(this.suffix,n===e.length-1?``:` `))}},$o=class extends Jo{constructor(e){super(e),this.pad_token=e.pad_token??``,this.word_delimiter_token=e.word_delimiter_token??``,this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return``;let t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let n=t.filter(e=>e!==this.pad_token).join(``);return this.cleanup&&(n=Xi(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},es=class extends Jo{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>os(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},ts=class extends Jo{constructor(e){super(e),this.pattern=Zi(this.config.pattern)}decode_chain(e){let t=this.config.content??``,n=this.pattern;return n===null?e:e.map(e=>e.replaceAll(n,t))}},ns=class extends Jo{decode_chain(e){return[e.join(``)]}},rs=class extends Jo{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n<this.start&&e[n]===this.content;++n)t=n+1;let n=e.length;for(let t=0;t<this.stop;++t){let r=e.length-t-1;if(e[r]===this.content)n=r;else break}return e.slice(t,n)})}},is=class extends Jo{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],n=[];for(let r of e){let e=null;if(r.length===6&&r.startsWith(`<0x`)&&r.endsWith(`>`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function as(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new Yo(e);case`WordPiece`:return new Xo(e);case`Metaspace`:return new Zo(e);case`BPEDecoder`:return new Qo(e);case`CTC`:return new $o(e);case`Sequence`:return new es(e);case`Replace`:return new ts(e);case`Fuse`:return new ns(e);case`Strip`:return new rs(e);case`ByteFallback`:return new is(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var os=as,ss=class{constructor(e,t){let n=Ua(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=Ua(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=so(this.tokenizer.normalizer),this.pre_tokenizer=To(this.tokenizer.pre_tokenizer),this.model=zo(this.tokenizer.model,this.config),this.post_processor=qo(this.tokenizer.post_processor),this.decoder=os(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=/* @__PURE__ */ new Map;for(let e of this.tokenizer.added_tokens){let t=new Ji(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new qi(i),this.splitter_normalized=new qi(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Ia(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Xi(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((e,t)=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=Ra(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t<n.length-1&&(n[t+1]=n[t+1].trimStart()))}),n.flatMap(e=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:za(r??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=/* @__PURE__ */ new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=/* @__PURE__ */ new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(e||!this.added_tokens_map.has(r))&&t.set(r,n)}return t}},cs=Object.defineProperty,ls=(e,t,n)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,us=(e,t,n)=>(ls(e,typeof t==`symbol`?t:t+``,n),n),L=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`}),ds=class{constructor(e,t){this.value=e,this.type=t}};function fs(e){return/\w/.test(e)}function ps(e){return/[0-9]/.test(e)}function ms(e){return/\s/.test(e)}var hs=[[`{%`,L.OpenStatement],[`%}`,L.CloseStatement],[`{{`,L.OpenExpression],[`}}`,L.CloseExpression],[`(`,L.OpenParen],[`)`,L.CloseParen],[`{`,L.OpenCurlyBracket],[`}`,L.CloseCurlyBracket],[`[`,L.OpenSquareBracket],[`]`,L.CloseSquareBracket],[`,`,L.Comma],[`.`,L.Dot],[`:`,L.Colon],[`|`,L.Pipe],[`<=`,L.ComparisonBinaryOperator],[`>=`,L.ComparisonBinaryOperator],[`==`,L.ComparisonBinaryOperator],[`!=`,L.ComparisonBinaryOperator],[`<`,L.ComparisonBinaryOperator],[`>`,L.ComparisonBinaryOperator],[`+`,L.AdditiveBinaryOperator],[`-`,L.AdditiveBinaryOperator],[`~`,L.AdditiveBinaryOperator],[`**`,L.ExponentiationBinaryOperator],[`*`,L.MultiplicativeBinaryOperator],[`//`,L.MultiplicativeBinaryOperator],[`/`,L.MultiplicativeBinaryOperator],[`%`,L.MultiplicativeBinaryOperator],[`=`,L.Equals]],gs=/* @__PURE__ */ new Map([[`n`,`
89
89
  `],[`t`,` `],[`r`,`\r`],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`'`,`'`],[`"`,`"`],[`\\`,`\\`]]);function _s(e,t={}){return e.endsWith(`
@@ -93,7 +93,7 @@ $t(Vt),mn(Vt),_n(Vt),Hn(Vt),tr(Vt),cr(Vt),Gr(Vt),(e=>{e.cache=Qr,e.concurrency=$
93
93
  `));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new R(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new z(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof R||e instanceof z)switch(r.value){case`abs`:return e instanceof R?new R(Math.abs(e.value)):new z(Math.abs(e.value));case`int`:return new R(Math.floor(e.value));case`float`:return new z(e.value);case`string`:return new B(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof fc)switch(r.value){case`items`:return new H(Array.from(e.value.entries()).map(([e,t])=>new H([new B(e),t])));case`length`:return new R(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof gc?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof V)switch(r.value){case`bool`:return new V(e.value);case`int`:return new R(+!!e.value);case`float`:return new z(+!!e.value);case`string`:return new B(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new _c;if(!(i instanceof R||i instanceof _c))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new V(!1);if(!(a instanceof V))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new V(!1);if(!(o instanceof V))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new _c,c=null;if(s instanceof H||s instanceof hc){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof B)||!(t instanceof B))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof _c))throw Error(`If set, separators must be a tuple of two strings`);return new B(dc(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}if(i===`join`){let t;if(e instanceof B)t=Array.from(e.value);else if(e instanceof H)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new B(``);if(!(s instanceof B))throw Error(`separator must be a string`);return new B(t.join(s.value))}if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new R(0):new z(0));if(e instanceof B){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new R(t):new z(t)}if(e instanceof R||e instanceof z)return e;if(e instanceof V)return i===`int`?new R(+!!e.value):new z(+!!e.value);throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}if(i==="default"){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new B(``),o=t[1]??i.get(`boolean`)??new V(!1);if(!(o instanceof V))throw Error("`default` filter flag must be a boolean");return e instanceof vc||o.value&&!e.__bool__().value?a:e}if(e instanceof H){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new V(!1);if(!(a instanceof V))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new V(!1);if(!(o instanceof V))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new _c;if(!(s instanceof B||s instanceof R||s instanceof _c))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof _c?e:Ec(e,s instanceof R?String(s.value):s.value);return new H(e.value.slice().sort((e,t)=>{let n=Dc(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!Cc(e)))throw Error(`\`${i}\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \`${i}\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new H(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof B))throw Error(`attribute must be a string`);let r=t.get(`default`);return new H(e.value.map(e=>{if(!Cc(e))throw Error(`items in map must be an object`);let t=Ec(e,n.value);return t instanceof vc?r??new vc:t}))}throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${i}`)}if(e instanceof B){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new R(4);if(!(a instanceof R))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new V(!1),s=t.at(2)??i.get(`blank`)??new V(!1),c=e.value.split(`
94
94
  `),l=` `.repeat(a.value);return new B(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(`
95
95
  `))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof gc))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new pc(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}if(e instanceof fc){let t=e.builtins.get(i);if(t&&t instanceof gc){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new pc(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new V(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new vc}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new V(!n.value);case`+`:case`-`:{let t=e.operator.value===`-`?-1:1;if(n instanceof R||n instanceof z||n instanceof V){let e=t*(n instanceof V?+!!n.value:n.value);return n instanceof z?new z(e):new R(e)}throw SyntaxError(`Unknown operator "${e.operator.value}" for ${n.type}`)}default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new B(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new pc(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof H||e instanceof B))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof R||r instanceof vc))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof R||i instanceof vc))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof R||a instanceof vc))throw Error(`Slice step must be numeric or undefined`);return e instanceof H?new H($s(e.value,r.value,i.value,a.value)):new B($s(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=e.property.type===`IntegerLiteral`?new R(e.property.value):new B(e.property.value);let i;if(Cc(n)){if(!(r instanceof B))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??(n instanceof fc?n.builtins.get(r.value):void 0)}else if(n instanceof H||n instanceof B){if(r instanceof R)i=n.value.at(r.value),n instanceof B&&(i=new B(n.value.at(r.value)));else if(r instanceof B)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`)}else{if(!(r instanceof B))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof cc?i:new vc}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof H))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;e<r.value.length;++e){let n=r.value[e];if(n.type!==`Identifier`)throw Error(`Cannot unpack to non-identifier in set: ${n.type}`);t.setVariable(n.value,i[e])}}else if(e.assignee.type===`MemberExpression`){let r=e.assignee,i=this.evaluate(r.object,t);if(!(i instanceof mc))throw Error(`cannot assign attribute on non-namespace object`);if(r.property.type!==`Identifier`)throw Error(`Cannot assign to member with non-identifier property`);i.value.set(r.property.value,n)}else throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new _c}evaluateIf(e,t){let n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let n=new xc(t),r,i;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=this.evaluate(t.lhs,n),r=t.test}else i=this.evaluate(e.iterable,n);if(!(i instanceof H||i instanceof fc))throw Error(`Expected iterable or object type in for loop: got ${i.type}`);i instanceof fc&&(i=i.keys());let a=[],o=[];for(let t=0;t<i.value.length;++t){let s=new xc(n),c=i.value[t],l;if(e.loopvar.type===`Identifier`)l=t=>t.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r<t.value.length;++r){if(t.value[r].type!==`Identifier`)throw Error(`Cannot unpack non-identifier type: ${t.value[r].type}`);e.setVariable(t.value[r].value,n.value[r])}}}else throw Error(`Invalid loop variable(s): ${e.loopvar.type}`);r&&(l(s),!this.evaluate(r,s).__bool__().value)||(a.push(c),o.push(l))}let s=``,c=!0;for(let t=0;t<a.length;++t){let r=/* @__PURE__ */ new Map([[`index`,new R(t+1)],[`index0`,new R(t)],[`revindex`,new R(a.length-t)],[`revindex0`,new R(a.length-t-1)],[`first`,new V(t===0)],[`last`,new V(t===a.length-1)],[`length`,new R(a.length)],[`previtem`,t>0?a[t-1]:new vc],[`nextitem`,t<a.length-1?a[t+1]:new vc]]);n.setVariable(`loop`,new fc(r)),o[t](n);try{let t=this.evaluateBlock(e.body,n);s+=t.value}catch(e){if(e instanceof oc)continue;if(e instanceof ac)break;throw e}c=!1}if(c){let t=this.evaluateBlock(e.defaultBlock,n);s+=t.value}return new B(s)}bindMacroArguments(e,t,n,r,i){let a=r.slice(),o=/* @__PURE__ */ new Map;a.at(-1)instanceof pc&&(o=new Map(a.pop().value));let s=[];for(let e=0;e<t.length;++e){let{name:n,defaultValue:r}=Oc(t[e]),c=a[e];c===void 0&&o.has(n)&&(c=o.get(n),o.delete(n)),c===void 0&&r!==void 0&&s.push([n,r]),i.setVariable(n,c??new vc)}if(n.has(`kwargs`))i.setVariable(`kwargs`,new fc(o));else if(o.size>0)throw Error(`macro ${e} takes no keyword argument '${o.keys().next().value}'`);if(n.has(`varargs`))i.setVariable(`varargs`,new H(a.slice(t.length)));else if(a.length>t.length)throw Error(`macro ${e} takes not more than ${t.length} argument(s)`);for(let[e,t]of s)i.setVariable(e,this.evaluate(t,i))}evaluateMacro(e,t){let n=Ac(e.args,e.body);return t.setVariable(e.name.value,new gc((t,r)=>{let i=new xc(r);return this.bindMacroArguments(`'${e.name.value}'`,e.args,n,t,i),this.evaluateBlock(e.body,i)})),new _c}evaluateCallStatement(e,t){let n=e.callerArgs??[],r=Ac(n,e.body),i=new gc(i=>{let a=new xc(t);return this.bindMacroArguments(`None`,n,r,i,a),this.evaluateBlock(e.body,a)}),[a,o]=this.evaluateArguments(e.call.args,t);a.push(new pc(o));let s=this.evaluate(e.call.callee,t);if(s.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${s.type}`);let c=new xc(t);return c.setVariable(`caller`,i),s.value(a,c)}evaluateFilterStatement(e,t){let n=this.evaluateBlock(e.body,t);return this.applyFilter(n,e.filter,t)}evaluate(e,t){if(!e)return new vc;switch(e.type){case`Program`:return this.evalProgram(e,t);case`Set`:return this.evaluateSet(e,t);case`If`:return this.evaluateIf(e,t);case`For`:return this.evaluateFor(e,t);case`Macro`:return this.evaluateMacro(e,t);case`CallStatement`:return this.evaluateCallStatement(e,t);case`Break`:throw new ac;case`Continue`:throw new oc;case`IntegerLiteral`:return new R(e.value);case`FloatLiteral`:return new z(e.value);case`StringLiteral`:return new B(e.value);case`ArrayLiteral`:return new H(e.value.map(e=>this.evaluate(e,t)));case`TupleLiteral`:return new hc(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=/* @__PURE__ */ new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof B))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new fc(n)}case`Identifier`:return this.evaluateIdentifier(e,t);case`CallExpression`:return this.evaluateCallExpression(e,t);case`MemberExpression`:return this.evaluateMemberExpression(e,t);case`UnaryExpression`:return this.evaluateUnaryExpression(e,t);case`BinaryExpression`:return this.evaluateBinaryExpression(e,t);case`FilterExpression`:return this.evaluateFilterExpression(e,t);case`FilterStatement`:return this.evaluateFilterStatement(e,t);case`TestExpression`:return this.evaluateTestExpression(e,t);case`SelectExpression`:return this.evaluateSelectExpression(e,t);case`Ternary`:return this.evaluateTernaryExpression(e,t);case`Comment`:return new _c;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function Mc(e){switch(typeof e){case`number`:return Number.isInteger(e)?new R(e):new z(e);case`string`:return new B(e);case`boolean`:return new V(e);case`undefined`:return new vc;case`object`:return e===null?new _c:Array.isArray(e)?new H(e.map(Mc)):new fc(new Map(Object.entries(e).map(([e,t])=>[e,Mc(t)])));case`function`:return new gc((t,n)=>Mc(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var Nc=`
96
- `,Pc=`{%- `,Fc=` -%}`,Ic=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function Lc(e){switch(e.operator.type){case`ExponentiationBinaryOperator`:return Ic.EXPONENTIATION;case`MultiplicativeBinaryOperator`:return Ic.MULTIPLICATIVE;case`AdditiveBinaryOperator`:return Ic.ADDITIVE;case`ComparisonBinaryOperator`:return Ic.COMPARISON;case`Identifier`:return e.operator.value===`and`?Ic.LOGICAL_AND:e.operator.value===`in`||e.operator.value===`not in`?Ic.COMPARISON:Ic.LOGICAL_OR}return Ic.LOGICAL_OR}function Rc(e){switch(e.type){case`SelectExpression`:case`Ternary`:return Ic.CONDITIONAL;case`BinaryExpression`:return Lc(e);case`UnaryExpression`:return e.operator.value===`not`?Ic.LOGICAL_NOT:Ic.UNARY_SIGN;case`TestExpression`:return Ic.TEST;case`FilterExpression`:return Ic.FILTER;default:return Ic.ATOM}}function zc(e,t){let n=Zc(e);return Rc(e)<t?`(${n})`:n}function Bc(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return Hc(e.body,0,n).replace(/\n$/,``)}function Vc(...e){return Pc+e.join(` `)+Fc}function Hc(e,t,n){return e.map(e=>Wc(e,t,n)).join(Nc)}function Uc(e){return e.map(e=>Zc(e)).join(`, `)}function Wc(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return Hc(e.body,t,n);case`If`:return Gc(e,t,n);case`For`:return Kc(e,t,n);case`Set`:return qc(e,t,n);case`Macro`:return Jc(e,t,n);case`Break`:return r+Vc(`break`);case`Continue`:return r+Vc(`continue`);case`CallStatement`:return Yc(e,t,n);case`FilterStatement`:return Xc(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+Zc(e)+` -}}`}}function Gc(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+Vc(`if`,Zc(i[0].test))+Nc+Hc(i[0].body,t+1,n);for(let e=1;e<i.length;++e)o+=Nc+r+Vc(`elif`,Zc(i[e].test))+Nc+Hc(i[e].body,t+1,n);return a&&a.alternate.length>0&&(o+=Nc+r+Vc(`else`)+Nc+Hc(a.alternate,t+1,n)),o+=Nc+r+Vc(`endif`),o}function Kc(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${Zc(t.lhs)} if ${Zc(t.test)}`}else i=Zc(e.iterable);let a=r+Vc(`for`,Zc(e.loopvar),`in`,i)+Nc+Hc(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=Nc+r+Vc(`else`)+Nc+Hc(e.defaultBlock,t+1,n)),a+=Nc+r+Vc(`endfor`),a}function qc(e,t,n){let r=n.repeat(t),i=Zc(e.assignee),a=e.value?Zc(e.value):``,o=r+Vc(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+Nc+Hc(e.body,t+1,n)+Nc+r+Vc(`endset`)}function Jc(e,t,n){let r=n.repeat(t),i=Uc(e.args);return r+Vc(`macro`,`${e.name.value}(${i})`)+Nc+Hc(e.body,t+1,n)+Nc+r+Vc(`endmacro`)}function Yc(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${Uc(e.callerArgs)})`:``,a=Zc(e.call),o=r+Vc(`call${i}`,a)+Nc;return o+=Hc(e.body,t+1,n)+Nc,o+=r+Vc(`endcall`),o}function Xc(e,t,n){let r=n.repeat(t),i=r+Vc(`filter`,e.filter.type===`Identifier`?e.filter.value:Zc(e.filter))+Nc;return i+=Hc(e.body,t+1,n)+Nc,i+=r+Vc(`endfilter`),i}function Zc(e){switch(e.type){case`SpreadExpression`:return`*${Zc(e.argument)}`;case`KeywordSpreadExpression`:return`**${Zc(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:{let t=e.value;return Object.is(t,-0)?`-0.0`:t%1==0?t.toFixed(1):t.toString()}case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let t=e,n=Lc(t),r=zc(t.left,n),i=zc(t.right,n+1);return`${r} ${t.operator.value} ${i}`}case`UnaryExpression`:{let t=e,n=t.argument.type===`UnaryExpression`?Rc(t):Ic.ATOM;return t.operator.value+(t.operator.value===`not`?` `:``)+zc(t.argument,n)}case`CallExpression`:{let t=e,n=Uc(t.args);return`${Zc(t.callee)}(${n})`}case`MemberExpression`:{let t=e,n=zc(t.object,Ic.ATOM),r=Zc(t.property);return!t.computed&&t.property.type!==`Identifier`&&t.property.type!==`IntegerLiteral`&&(r=`(${r})`),t.computed?`${n}[${r}]`:`${n}.${r}`}case`FilterExpression`:{let t=e,n=zc(t.operand,Ic.FILTER);return t.filter.type===`CallExpression`?`${n} | ${Zc(t.filter)}`:`${n} | ${t.filter.value}`}case`SelectExpression`:{let t=e;return`${zc(t.lhs,Ic.LOGICAL_OR)} if ${zc(t.test,Ic.LOGICAL_OR)}`}case`TestExpression`:{let t=e;return`${zc(t.operand,Ic.TEST)} is${t.negate?` not`:``} ${t.test.value}`}case`ArrayLiteral`:case`TupleLiteral`:{let t=Uc(e.value),n=e.type===`ArrayLiteral`?`[]`:`()`;return`${n[0]}${t}${n[1]}`}case`ObjectLiteral`:return`{${Array.from(e.value.entries()).map(([e,t])=>`${Zc(e)}: ${Zc(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?Zc(t.start):``}:${t.stop?Zc(t.stop):``}${t.step?`:${Zc(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${Zc(t.value)}`}case`Ternary`:{let t=e;return`${zc(t.trueExpr,Ic.LOGICAL_OR)} if ${zc(t.condition,Ic.LOGICAL_OR)} else ${zc(t.falseExpr,Ic.CONDITIONAL)}`}default:throw Error(`Unknown expression type: ${e.type}`)}}var Qc=class{parsed;constructor(e){let t=vs(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Zs(t)}render(e){let t=new xc;if(Sc(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new jc(t).run(this.parsed).value}format(e){return Bc(this.parsed,e?.indent||` `)}},$c={txt:`text/plain`,html:`text/html`,css:`text/css`,js:`text/javascript`,json:`application/json`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`},el=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=d.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=d.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=d.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,$c[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await d.promises.readFile(this.filePath)).buffer}async blob(){let e=await d.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await d.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},tl=class{constructor(e){this._mt=/* @__PURE__ */ new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null){if(j.IS_CRYPTO_AVAILABLE){let t=/* @__PURE__ */ new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0}let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t|0);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(1812433253,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1566083941))-i>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&2147483648|e[(t+1)%624]&2147483647;e[t]=(e[(t+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[nl(this._random_fn,t)]}};function nl(e,t){let n=0;for(let e=0;e<t.length;++e)n+=t[e];let r=e()*n;for(let e=0;e<t.length;++e)if(r-=t[e],r<0)return e;return t.length-1}var rl=new tl,il=Object.freeze({Random:tl,seed:rl.seed.bind(rl),random:rl.random.bind(rl),gauss:rl.gauss.bind(rl),shuffle:rl.shuffle.bind(rl),choices:rl.choices.bind(rl)}),al=e=>nl(il.random,e),ol=new tl,sl=class{constructor(e){this.path=e}async match(e){let t=new el(m.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=m.join(this.path,e),i=r+`.tmp.${j.IS_PROCESS_AVAILABLE?l.pid:Date.now()}.${ol._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await d.promises.mkdir(m.dirname(r),{recursive:!0});let s=d.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{t?n(t):e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await d.promises.rename(i,r)}catch(e){try{await d.promises.unlink(i)}catch{}throw e}}async delete(e){let t=m.join(this.path,e);try{return await d.promises.unlink(t),!0}catch{return!1}}},cl={400:`Bad request error occurred while trying to load file`,401:`Unauthorized access to file`,403:`Forbidden access to file`,404:`Could not locate file`,408:`Request timeout error occurred while trying to load file`,500:`Internal server error error occurred while trying to load file`,502:`Bad gateway error occurred while trying to load file`,503:`Service unavailable error occurred while trying to load file`,504:`Gateway timeout error occurred while trying to load file`},ll=100,ul=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function dl(...e){return e=e.map((t,n)=>(n&&(t=t.replace(/* @__PURE__ */ RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(/* @__PURE__ */ RegExp(`/$`),``)),t)),e.join(`/`)}function fl(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function pl(e){return!(!ul.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function ml(e,t={},...n){return JSON.stringify([e,t.revision??`main`,t.cache_dir??null,t.local_files_only??!1,...n])}var hl=class extends Error{constructor(e,{status:t=null}={}){super(e),this.name=`ModelFileNotFoundError`,this.status=t}},gl=/* @__PURE__ */ new Set([401,403,404]);function _l(e,t,n){if(!n)return null;let r=`${cl[e]??`Error (${e}) occurred while trying to load file`}: "${t}".`;throw gl.has(e)?new hl(r,{status:e}):Error(r)}async function vl(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&N.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function yl(e){return fl(e,[`blob:`])}function bl(e,{allowUnresolved:t=!1}={}){let n;if(typeof location<`u`&&location.href)n=location.href;else if(import.meta.url)n=import.meta.url;else return e;try{return new URL(e,n).href}catch(n){if(!t)throw n;return e}}var xl=`SHA-256`,Sl=`experimental_transformers-hash-cache`,Cl=e=>({algorithm:xl,value:e}),wl=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Sl),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let e=await(await navigator.crossOriginStorage.requestFileHandle(Cl(t))).getFile();return new Response(e,{headers:{"Content-Length":String(e.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(Cl(t),{create:!0,origins:`*`})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(xl,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function Tl(e=null){let t=null;if(M.useCustomCache){if(!M.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!M.customCache.match||!M.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=M.customCache}if(!t&&M.experimental_useCrossOriginStorage&&wl.isAvailable()&&(t=new wl),!t&&M.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(M.cacheKey)}catch(e){N.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&M.useFSCache){if(!j.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new sl(e??M.cacheDir)}return t}async function El(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var Dl=new class{#e;#t;constructor(e){this.#e=e,this.#t=/* @__PURE__ */ new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function Ol(e,t){let n=Dl.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(Dl.delete(e),Promise.reject(t)));return Dl.put(e,r),r}async function kl(e){if(!fl(e,[`http:`,`https:`]))return null;let t=Nl(e);return t.set(`Range`,`bytes=0-0`),M.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function Al(e,t,n={}){return Ol(ml(e,n,t),()=>jl(e,t,n))}async function jl(e,t,n){let r=await Tl(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=Pl(e,t,n,r),c=await Fl(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(M.allowLocalModels&&!fl(i,[`http:`,`https:`]))try{let e=await Ml(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(M.allowRemoteModels&&!n.local_files_only&&s){let e=await kl(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \d+-\d+\/(\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}e&&e.status!==404&&e.status!==416&&_l(e.status,a,!0)}return{exists:!1,fromCache:!1}}async function Ml(e){return M.useFS&&!fl(e,[`http:`,`https:`,`blob:`])?new el(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):M.fetch(e,{headers:Nl(e)})}function Nl(e){let t=l!==void 0&&l?.release?.name===`node`,n=new Headers;if(t){let t=!!l.env?.TESTING_REMOTELY,r=M.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),fl(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e=l.env?.HF_TOKEN??l.env?.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function Pl(e,t,n={},r=null){let i=n.revision??`main`,a=dl(e,t),o=pl(e),s=o?dl(M.localModelPath,a):a,c=dl(M.remoteHost,M.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof sl?i===`main`?a:dl(e,i,t):c,validModelId:o}}async function Fl(e,t,n){if(e)return await El(e,t,n)}async function Il(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0&&!(typeof Cache<`u`&&n instanceof Cache&&!fl(bl(r,{allowUnresolved:!0}),[`http:`,`https:`]))){if(!a){let a=o.progress_callback?n=>Li(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}else if(typeof i!=`string`){let e=new Headers(i.headers);e.set(`content-length`,a.byteLength.toString()),await n.put(r,new Response(a,{headers:e})).catch(e=>{N.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function Ll(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=Pl(e,t,r,a),d,f=!1,p;p=await Fl(a,s,l);let m=p!==void 0;if(m)d=l;else{if(M.allowLocalModels){if(!fl(o,[`http:`,`https:`]))try{p=await Ml(s),d=s}catch(e){N.warn(`Unable to load from local path "${s}": "${e}"`)}else if(r.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);else if(!M.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!M.allowRemoteModels){if(n)throw new hl(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${s}".`);return null}if(!u)throw new hl(`Local file missing at "${s}" and download aborted due to invalid model ID "${e}".`);if(p=await Ml(c),p.status!==200)return _l(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}Li(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(j.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`){if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),Li(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await Al(e,t,r);n.size&&(i=n.size)}catch{}n=await vl(p,n=>{Li(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}}h=n}if(f&&d&&typeof p!=`string`&&await Il(e,t,a,d,p,h,r),j.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;Li(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(Li(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!j.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof el)return p.filePath;let g=await a?.match(d);if(g instanceof el)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}var Rl=/* @__PURE__ */ new Map;async function zl(e,t,n=!0,r={},i=!1){if(!M.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!M.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let a=ml(e,r,t,n,i),{progress_callback:o}=r,s=o instanceof Ri?o.loads:Rl,c=s.get(a);return c||(Li(o,{status:`initiate`,name:e,file:t}),c=Tl(r.cache_dir).then(a=>Ll(e,t,n,r,i,a)),s===Rl&&(c=c.finally(()=>Rl.delete(a))),s.set(a,c)),await c}async function Bl(e,t,n=!0,r={}){let i=await zl(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function Vl(e,t,n=!0,r={}){let i=await Bl(e,t,n,r);return i===null?{}:JSON.parse(i)}function Hl(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o<i;++o)for(let i=0;i<a;++i){let s=o*a+i,p=(i+.5)/c-.5,m=(o+.5)/l-.5,h=Math.floor(p),g=Math.floor(m),_=Math.min(h+1,r-1),v=Math.min(g+1,n-1);h=Math.max(h,0),g=Math.max(g,0);let y=p-h,b=m-g,x=(1-y)*(1-b),S=y*(1-b),C=(1-y)*b,ee=y*b,w=g*r,T=v*r,te=w+h,ne=w+_,E=T+h,D=T+_;for(let n=0;n<t;++n){let t=n*d;u[n*f+s]=x*e[t+te]+S*e[t+ne]+C*e[t+E]+ee*e[t+D]}}return u}function Ul(e,t,n){let r=Array(n.length),i=Array(n.length);for(let e=n.length-1,a=1;e>=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n<e.length;++n){let r=0;for(let e=t.length-1,i=n;e>=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function Wl(e){let t=ql(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function Gl(e){let t=ql(e)[0],n=0;for(let r=0;r<e.length;++r)n+=Math.exp(e[r]-t);let r=Math.log(n);return e.map(e=>e-t-r)}function Kl(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}function ql(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],n=r);return[t,n]}function Jl(e){return e>0&&!(e&e-1)}var Yl=class{constructor(e){if(this.size=e|0,this.size<=1||!Jl(this.size))throw Error(`FFT size must be a power of two larger than 1`);this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let e=0;e<this.table.length;e+=2){let t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){let n=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let n=t||Array(e.length>>>1);for(let t=0;t<e.length;t+=2)n[t>>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t<n.length;t+=2)n[t]=e[t>>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleTransform2(t,e,o,n,i)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleTransform4(t,e,o,r,i,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o<r;o+=a){let r=o+t-1;for(let a=o,s=0;a<r;a+=2,s+=i){let r=a,i=r+t,o=i+t,c=o+t,u=e[r],d=e[r+1],f=e[i],p=e[i+1],m=e[o],h=e[o+1],g=e[c],_=e[c+1],v=l[s],y=n*l[s+1],b=f*v-p*y,x=f*y+p*v,S=l[2*s],C=n*l[2*s+1],ee=m*S-h*C,w=m*C+h*S,T=l[3*s],te=n*l[3*s+1],ne=g*T-_*te,E=g*te+_*T,D=u+ee,re=d+w,ie=u-ee,ae=d-w,oe=b+ne,se=x+E,ce=n*(b-ne),le=n*(x-E);e[r]=D+oe,e[r+1]=re+se,e[i]=ie+le,e[i+1]=ae-ce,e[o]=D-oe,e[o+1]=re-se,e[c]=ie-le,e[c+1]=ae+ce}}}}_singleTransform2(e,t,n,r,i){let a=e[r],o=e[r+1],s=e[r+i],c=e[r+i+1];t[n]=a+s,t[n+1]=o+c,t[n+2]=a-s,t[n+3]=o-c}_singleTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+1],u=e[r+i],d=e[r+i+1],f=e[r+o],p=e[r+o+1],m=e[r+s],h=e[r+s+1],g=c+f,_=l+p,v=c-f,y=l-p,b=u+m,x=d+h,S=a*(u-m),C=a*(d-h);t[n]=g+b,t[n+1]=_+x,t[n+2]=v+C,t[n+3]=y-S,t[n+4]=g-b,t[n+5]=_-x,t[n+6]=v-C,t[n+7]=y+S}_realTransform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleRealTransform2(t,e,o,n>>>1,i>>>1)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleRealTransform4(t,e,o,r>>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o<r;o+=a)for(let r=0,a=0;r<=c;r+=2,a+=i){let i=o+r,u=i+s,d=u+s,f=d+s,p=e[i],m=e[i+1],h=e[u],g=e[u+1],_=e[d],v=e[d+1],y=e[f],b=e[f+1],x=p,S=m,C=l[a],ee=n*l[a+1],w=h*C-g*ee,T=h*ee+g*C,te=l[2*a],ne=n*l[2*a+1],E=_*te-v*ne,D=_*ne+v*te,re=l[3*a],ie=n*l[3*a+1],ae=y*re-b*ie,oe=y*ie+b*re,se=x+E,ce=S+D,le=x-E,ue=S-D,de=w+ae,O=T+oe,fe=n*(w-ae),pe=n*(T-oe);if(e[i]=se+de,e[i+1]=ce+O,e[u]=le+pe,e[u+1]=ue-fe,r===0){e[d]=se-de,e[d+1]=ce-O;continue}if(r===c)continue;let me=o+s-r,he=o+t-r;e[me]=le-n*pe,e[me+1]=-ue-n*fe,e[he]=se-n*de,e[he+1]=-ce+n*O}}let u=r>>>1;for(let t=2;t<u;t+=2)e[r-t]=e[t],e[r-t+1]=-e[t+1]}_singleRealTransform2(e,t,n,r,i){let a=e[r],o=e[r+i];t[n]=a+o,t[n+1]=0,t[n+2]=a-o,t[n+3]=0}_singleRealTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+i],u=e[r+o],d=e[r+s],f=c+u,p=c-u,m=l+d,h=a*(l-d);t[n]=f+m,t[n+1]=0,t[n+2]=p,t[n+3]=-h,t[n+4]=f-m,t[n+5]=0,t[n+6]=p,t[n+7]=h}},Xl=class{constructor(e){let t=2*(e-1),n=2*(2*e-1),r=2**Math.ceil(Math.log2(n));this.bufferSize=r,this._a=t;let i=new Float64Array(n),a=new Float64Array(r);this._chirpBuffer=new Float64Array(r),this._buffer1=new Float64Array(r),this._buffer2=new Float64Array(r),this._outBuffer1=new Float64Array(r),this._outBuffer2=new Float64Array(r);let o=-2*Math.PI/e,s=Math.cos(o),c=Math.sin(o);for(let t=0;t<n>>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new Yl(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e<c.length;e+=2){let n=e+1,i=t[e>>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e<c.length;e+=2){let n=e+1;r[e]=t[e]*c[e]-t[n]*c[n],r[n]=t[e]*c[n]+t[n]*c[e]}this._f.transform(a,r);for(let e=0;e<s.length;e+=2){let t=e+1;i[e]=a[e]*s[e]-a[t]*s[t],i[t]=a[e]*s[t]+a[t]*s[e]}this._f.inverseTransform(o,i);for(let t=0;t<o.length;t+=2){let n=o[t+l],r=o[t+l+1],i=c[t],a=c[t+1];e[t]=n*i-r*a,e[t+1]=n*a+r*i}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},Zl=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Jl(e),this.isPowerOfTwo?(this.fft=new Yl(e),this.outputBufferSize=2*e):(this.fft=new Xl(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function Ql(e,t){if(t%2==0||t<=0)throw Error(`Window size must be a positive odd number`);let n=new e.constructor(e.length),r=new e.constructor(t),i=Math.floor(t/2);for(let t=0;t<e.length;++t){let a=0;for(let n=-i;n<=i;++n){let i=t+n;i<0?i=Math.abs(i):i>=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function $l(e,t){let n=10**t;return Math.round(e*n)/n}function eu(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function tu(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t<r[1];++t)for(let n=1;n<r[0];++n){let r=i[n-1][t-1],o=i[n-1][t],s=i[n][t-1],c,l;r<o&&r<s?(c=r,l=0):o<r&&o<s?(c=o,l=1):(c=s,l=2),i[n][t]=e[n-1][t-1]+c,a[n][t]=l}for(let e=0;e<r[1];++e)a[0][e]=2;for(let e=0;e<r[0];++e)a[e][0]=1;let o=t,s=n,c=[],l=[];for(;o>0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var nu=/* @__PURE__ */ (function(){let e=null;return function(t){if(!e){e=/* @__PURE__ */ new Float32Array(65536);let t=/* @__PURE__ */ new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;++t){let i=0,a=(t&32768)<<16,o=(t&31744)>>10,s=t&1023;if(o===31)i=a|2139095040|s<<13;else if(o===0){if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;e<n;++e)i[e]=r[t[e]];return i}})(),ru=b(import.meta.url??__filename);l.env.ORT_DISABLE_TELEMETRY=`1`;var iu=ru(`onnxruntime-node`),au={};ci(au,{InferenceSession:()=>ad,TRACE:()=>Xu,TRACE_EVENT_BEGIN:()=>ed,TRACE_EVENT_END:()=>td,TRACE_FUNC_BEGIN:()=>Qu,TRACE_FUNC_END:()=>$u,Tensor:()=>Ju,default:()=>Ip,env:()=>Eu,registerBackend:()=>gu});var ou=Object.defineProperty,su=Object.getOwnPropertyDescriptor,cu=Object.getOwnPropertyNames,lu=Object.prototype.hasOwnProperty,uu=(e=>typeof si<`u`?si:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof si<`u`?si:e)[t]}):e)(function(e){if(typeof si<`u`)return si.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),U=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},du=(e,t)=>{for(var n in t)ou(e,n,{get:t[n],enumerable:!0})},fu=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of cu(t))!lu.call(e,i)&&i!==n&&ou(e,i,{get:()=>t[i],enumerable:!(r=su(t,i))||r.enumerable});return e},pu=e=>fu(ou({},`__esModule`,{value:!0}),e),mu,hu,gu,_u,vu,yu=U(()=>{mu=/* @__PURE__ */ new Map,hu=[],gu=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=mu.get(e);if(r===void 0)mu.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=hu.indexOf(e);t!==-1&&hu.splice(t,1);for(let t=0;t<hu.length;t++)if(mu.get(hu[t]).priority<=n){hu.splice(t,0,e);return}hu.push(e)}}else throw TypeError(`not a valid backend`)},_u=async e=>{let t=mu.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},vu=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?hu:n,i,a=[],o=/* @__PURE__ */ new Set;for(let e of r){let t=await _u(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),bu=U(()=>{yu()}),xu,Su=U(()=>{xu=`1.31.0-dev.20260911-2a43ec07e`}),Cu,wu,Tu=U(()=>{Su(),Cu=`warning`,wu={wasm:{},webgl:{},webgpu:{},versions:{common:xu},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Cu=e}},get logLevel(){return Cu}},Object.defineProperty(wu,"logLevel",{enumerable:!0})}),Eu,Du=U(()=>{Tu(),Eu=wu}),Ou,ku,Au=U(()=>{Ou=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},ku=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),ju,Mu,Nu,Pu,Fu,Iu,Lu=U(()=>{qu(),ju=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new Ku(`float32`,u,[1,4,n,r]):new Ku(`float32`,u,[1,3,n,r])},Mu=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,ju(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(ju(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return ju(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},Nu=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new Ku({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},Pu=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Ku({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},Fu=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Ku({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},Iu=(e,t,n)=>new Ku({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),Ru,zu,Bu,Vu,Hu=U(()=>{Ru=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),zu=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),Bu=!1,Vu=()=>{if(!Bu){Bu=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(Ru.set(`int64`,BigInt64Array),zu.set(BigInt64Array,`int64`)),t&&(Ru.set(`uint64`,BigUint64Array),zu.set(BigUint64Array,`uint64`)),r?(Ru.set(`float16`,n),zu.set(n,`float16`)):Ru.set(`float16`,Uint16Array)}}}),Uu,Wu,Gu=U(()=>{qu(),Uu=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},Wu=(e,t)=>{switch(e.location){case`cpu`:return new Ku(e.type,e.data,t);case`cpu-pinned`:return new Ku({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new Ku({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new Ku({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new Ku({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ku,qu=U(()=>{Au(),Lu(),Hu(),Gu(),Ku=class{constructor(e,t,n){Vu();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=Ru.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=Ru.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=zu.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=Uu(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return Mu(e,t)}static fromTexture(e,t){return Nu(e,t)}static fromGpuBuffer(e,t){return Pu(e,t)}static fromMLTensor(e,t){return Fu(e,t)}static fromPinnedBuffer(e,t,n){return Iu(e,t,n)}toDataURL(e){return Ou(this,e)}toImageData(e){return ku(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return Wu(this,e)}}}),Ju,Yu=U(()=>{qu(),Ju=Ku}),Xu,Zu,Qu,$u,ed,td,nd=U(()=>{Tu(),Xu=(e,t)=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||console.timeStamp(`${e}::ORT::${t}`)},Zu=(e,t)=>{let n=(/* @__PURE__ */ Error()).stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),Xu(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},Qu=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||Zu(`BEGIN`,e)},$u=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||Zu(`END`,e)},ed=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||console.time(`ORT::${e}`)},td=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||console.timeEnd(`ORT::${e}`)}}),rd,id=U(()=>{yu(),Yu(),nd(),rd=class e{constructor(e){this.handler=e}async run(e,t,n){Qu(),ed(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof Ju||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof Ju)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof Ju)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof Ju?t:new Ju(t.type,t.data,t.dims)}return td(`InferenceSession.run`),$u(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){Qu(),ed(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await vu(o),l=await s.createInferenceSessionHandler(a,c);return td(`InferenceSession.create`),$u(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),ad,od=U(()=>{id(),ad=rd}),sd=U(()=>{}),cd=U(()=>{}),ld=U(()=>{}),ud=U(()=>{}),dd={};du(dd,{InferenceSession:()=>ad,TRACE:()=>Xu,TRACE_EVENT_BEGIN:()=>ed,TRACE_EVENT_END:()=>td,TRACE_FUNC_BEGIN:()=>Qu,TRACE_FUNC_END:()=>$u,Tensor:()=>Ju,env:()=>Eu,registerBackend:()=>gu});var fd=U(()=>{bu(),Du(),od(),Yu(),sd(),cd(),nd(),ld(),ud()}),pd=U(()=>{}),md={};du(md,{default:()=>_d});var hd,gd,_d,vd=U(()=>{op(),Jd(),Rd(),hd=`ort-wasm-proxy-worker`,gd=globalThis.self?.name===hd,gd&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:Kd(n.wasm).then(()=>{Jf(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;Yf(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=$f(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;ep(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:tp(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;rp(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},ap([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:ip(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),_d=gd?null:e=>new Worker(e??Dd,{type:`module`,name:hd})}),yd={};du(yd,{default:()=>xd});async function bd(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.ed||=/* @__PURE__ */ new Map).set(e,n)},t.unmountExternalData=()=>{delete t.ed,delete t.Te,delete t.Se,delete t.Ue},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=un;return t=e(...t),un==n?t:new Promise((e,t)=>{_n={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=import.meta.url,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(S(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,x=!1,S=e=>e.startsWith(`file://`);function C(){Me.buffer!=w.buffer&&le()}if(i){let e=function(n){try{var r=n.data,i=r.$c;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({$c:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.ue)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({$c:`callHandler`,te:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));Me=r.Me,le(),f=r.Ne,fe(),cs()}else if(i===`run`){(function(e){var t=(C(),D)[e+52>>>2>>>0];e=(C(),D)[e+56>>>2>>>0],Ca(t,t-e),F(t)})(r.Xc),ma(r.Xc,0,0,1,0,0),ke(),Qt(r.Xc),ee||=(Gi(),!0);try{Ne(r.ze,r.kd)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?ee&&$t():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw ha(),e}};var ee=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var w,T,te,ne,E,D,re,ie,ae,oe,se,ce=!1;function le(){var e=Me.buffer;t.HEAP8=w=new Int8Array(e),te=new Int16Array(e),t.HEAPU8=T=new Uint8Array(e),ne=new Uint16Array(e),t.HEAP32=E=new Int32Array(e),t.HEAPU32=D=new Uint32Array(e),re=new Float32Array(e),ie=new Float64Array(e),ae=new BigInt64Array(e),oe=new BigUint64Array(e)}function ue(){ce=!0,i?g():yo.hc()}function de(e){throw b(e=`Aborted(`+e+`)`),x=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function O(){return{a:{qa:So,f:Le,K:ze,k:We,p:Ge,l:Ke,fa:qe,b:Je,da:Ye,gc:Ze,q:Qe,ea:rt,Ua:it,cc:at,ec:ot,Va:st,Sa:ct,La:lt,Ra:ut,oa:dt,dc:ft,ac:pt,Ta:mt,bc:ht,_a:gt,Ba:wt,Xb:Tt,Vb:Nt,Aa:Ft,O:It,J:Lt,Wb:zt,ka:qt,Yb:Jt,Oa:Yt,_b:en,Ea:nn,Tb:rn,Ca:an,Na:Qt,Xa:on,U:bn,n:Dn,c:Ot,qb:On,w:kn,N:An,A:jn,j:Mn,o:Nn,rb:Pn,H:Fn,T:In,g:Ln,u:Rn,m:zn,i:Bn,Ia:Vn,Ja:Gn,Ka:Kn,Ga:qn,Ha:Jn,Ub:Zn,ab:Qn,Za:tr,Z:ir,pb:ar,Da:or,Ya:$n,X:sr,Wa:cr,$b:lr,G:Xn,db:ur,_:dr,pa:_r,Zb:vr,cb:gr,bb:yr,lb:qr,z:Jr,sa:Yr,ra:Xr,nb:Zr,Y:Qr,v:$r,kb:ei,jb:ti,ib:ni,mb:ri,gb:ii,fb:ai,eb:oi,Pa:ui,Qa:di,fc:Ce,W:fi,Fa:pi,ma:mi,Ma:hi,la:_i,Fb:os,va:es,Gb:as,wa:$o,E:Bo,e:Eo,r:wo,x:Co,C:Io,Ib:Xo,ca:Yo,D:ko,xa:Zo,aa:ts,ha:Jo,Jb:qo,Kb:Ko,za:Ho,Lb:Wo,ya:Go,Mb:Uo,ua:is,ba:Qo,d:To,B:Oo,s:Do,Eb:ss,t:jo,y:Ro,F:Ao,I:Mo,L:zo,Nb:Vo,R:ns,ia:Fo,$:rs,Pb:Po,Rb:No,Ob:Lo,h:vi,a:Me,$a:xe,Hb:yi,V:bi,M:xi,na:Si,Db:Ci,ja:wi,S:Ti,Ab:Ei,Bb:j,vb:Di,wb:Oi,P:ki,xb:Ai,yb:ji,ta:Mi,Sb:Ni,ob:Pi,Q:M,hb:Fi,Cb:Ii,sb:Li,tb:zi,ub:Bi,ga:Vi,zb:Hi,Qb:Ui}}}async function fe(){function e(e,n){var r=yo=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=cn(n),e[t]=r):e[t]=n;return yo=e,yo=(function(){var e=yo,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).ic=t(e.ic),e.Nc=n(e.Nc),e.Pc=t(e.Pc),e.Bd=/* @__PURE__ */ (e=>(t,n)=>e(t,n)>>>0)(e.Bd),e.Gd=t(e.Gd),e.Hd=n(e.Hd),e.Ld=t(e.Ld),e})(),Ee.push(yo.sd),Wi=(e=yo).ic,Gi=e.jc,t._OrtInit=e.kc,t._OrtGetLastError=e.lc,t._OrtCreateSessionOptions=e.mc,t._OrtAppendExecutionProvider=e.nc,t._OrtAddFreeDimensionOverride=e.oc,t._OrtAddSessionConfigEntry=e.pc,t._OrtReleaseSessionOptions=e.qc,t._OrtCreateSession=e.rc,t._OrtReleaseSession=e.sc,t._OrtGetInputOutputCount=e.tc,t._OrtGetInputOutputMetadata=e.uc,t._OrtFree=e.vc,t._OrtCreateTensor=e.wc,t._OrtGetTensorData=e.xc,t._OrtReleaseTensor=e.yc,t._OrtCreateRunOptions=e.zc,t._OrtAddRunConfigEntry=e.Ac,t._OrtReleaseRunOptions=e.Bc,t._OrtCreateBinding=e.Cc,t._OrtBindInput=e.Dc,t._OrtBindOutput=e.Ec,t._OrtClearBoundOutputs=e.Fc,t._OrtReleaseBinding=e.Gc,t._OrtRunWithBinding=e.Hc,t._OrtRun=e.Ic,t._OrtEndProfiling=e.Jc,Ki=t._OrtCreateWebGpuInstance=e.Kc,t._wgpuCreateInstance=e.Lc,N=t._OrtGetWebGpuDevice=e.Mc,qi=e.Nc,Ji=t._free=e.Oc,Yi=t._malloc=e.Pc,Xi=t._wgpuBufferRelease=e.Qc,Zi=e.Rc,Qi=e.Sc,$i=e.Tc,ea=e.Uc,ta=e.Vc,na=e.Yc,ra=e.Zc,ia=e.hd,aa=e.id,oa=e.jd,sa=e.ld,ca=e.md,la=e.nd,ua=e.od,da=e.pd,fa=e.qd,pa=e.rd,ma=e.ud,ha=e.vd,ga=e.wd,_a=e.xd,va=e.yd,ya=e.zd,ba=e.Ad,xa=e.Bd,P=e.Cd,Sa=e.Dd,Ca=e.Ed,F=e.Fd,wa=e.Gd,I=e.Hd,Ta=e.Id,Ea=e.Jd,Da=e.Kd,Oa=e.Ld,ka=e.Md,Aa=e.Nd,ja=e.Od,Ma=e.Pd,Na=e.Qd,Pa=e.Rd,Fa=e.Sd,Ia=e.Td,La=e.Ud,Ra=e.Vd,za=e.Wd,Ba=e.Xd,Va=e.Yd,Ha=e.Zd,Ua=e._d,Wa=e.$d,Ga=e.ae,Ka=e.be,qa=e.ce,Ja=e.de,Ya=e.fe,Xa=e.ge,Za=e.he,Qa=e.ie,$a=e.je,eo=e.ke,to=e.le,no=e.me,ro=e.Ae,io=e.Be,ao=e.Ce,oo=e.De,so=e.Ee,co=e.Fe,lo=e.Ge,uo=e.He,fo=e.Ie,po=e.Je,mo=e.Ke,ho=e.nf,go=e.of,_o=e.pf,vo=e.qf,f=n,yo}var n,r=O();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,O()),f):(se??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(`ort-wasm-simd-threaded.asyncify.wasm`,import.meta.url).href,n=await(async function(e){var t=se;if(!d&&!S(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return(async function(e,t){try{var n=await(async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==se&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e})(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),de(e)}})(t,e)})(r),e(n.instance,n.module))}class pe{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var me=e=>{e.terminate(),e.onmessage=()=>{}},he=[],ge=0,_e=null,ve=e=>{we.length==0&&(je(),Ae(we[0]));var t=we.pop();if(!t)return 6;Te.push(t),De[e.Xc]=t,t.Xc=e.Xc;var n={$c:`run`,ze:e.ye,kd:e.kd,Xc:e.Xc};return t.postMessage(n,e.oe),0},ye=0,be=(e,t,...n)=>{var r,i=16*n.length,a=I(),o=wa(i),s=o>>>3;for(r of n)typeof r==`bigint`?((C(),ae)[s++>>>0]=1n,(C(),ae)[s++>>>0]=r):((C(),ae)[s++>>>0]=0n,(C(),ie)[s++>>>0]=r);return e=ga(e,0,i,o,t),F(a),e};function xe(e){if(i)return be(0,1,e);if(p=e,!(0<ye)){for(var t of Te)me(t);for(t of we)me(t);we=[],Te=[],De={},x=!0}c(0,new pe(e))}function Se(e){if(i)return be(1,0,e);Ce(e)}var Ce=e=>{if(p=e,i)throw Se(e),`unwind`;xe(e)},we=[],Te=[],Ee=[],De={},Oe=e=>{var t=e.Xc;delete De[t],we.push(e),Te.splice(Te.indexOf(e),1),e.Xc=0,_a(t)};function ke(){Ee.forEach(e=>e())}var Ae=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.$c,i.gd&&i.gd!=qi()){var a=De[i.gd];a?a.postMessage(i,i.oe):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.gd}, but that thread no longer exists!`)}else r===`checkMailbox`?$t():r===`spawnThread`?ve(i):r===`cleanupThread`?Xt(()=>{Oe(De[i.Le])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.te](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({$c:`load`,ue:i,Me,Ne:f})});function je(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.webgpu.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});we.push(e)}var Me,Ne=(e,t)=>{ye=0,e=Aa(e,t),0<ye?p=e:va(e)},Pe=[],Fe=0,Ie=e=>-9007199254740992>e||9007199254740992<e?NaN:Number(e);function Le(e){var t=new He(e>>>=0);return(C(),w)[t.ad+12>>>0]==0&&(Be(t,!0),Fe--),Ve(t,!1),Pe.push(t),Oa(e)}var Re=0,ze=()=>{P(0,0);var e=Pe.pop();Ta(e.td),Re=0};function Be(e,t){t=+!!t,(C(),w)[e.ad+12>>>0]=t}function Ve(e,t){t=+!!t,(C(),w)[e.ad+13>>>0]=t}class He{constructor(e){this.td=e,this.ad=e-24}}var Ue=e=>{var t=Re;if(!t)return Sa(0),0;var n=new He(t);(C(),D)[n.ad+16>>>2>>>0]=t;var r=(C(),D)[n.ad+4>>>2>>>0];if(!r)return Sa(0),t;for(var i of e){if(i===0||i===r)break;if(Da(i,r,n.ad+16))return Sa(i),t}return Sa(r),t};function We(){return Ue([])}function Ge(e){return Ue([e>>>0])}function Ke(e,t,n,r){return Ue([e>>>0,t>>>0,n>>>0,r>>>0])}var qe=()=>{var e=Pe.pop();e||de(`no exception to throw`);var t=e.td;throw(C(),w)[e.ad+13>>>0]==0&&(Pe.push(e),Ve(e,!0),Be(e,!1),Fe++),Ea(t),Re=t};function Je(e,t,n){var r=new He(e>>>=0);throw t>>>=0,n>>>=0,(C(),D)[r.ad+16>>>2>>>0]=0,(C(),D)[r.ad+4>>>2>>>0]=t,(C(),D)[r.ad+8>>>2>>>0]=n,Ea(e),Fe++,Re=e}var Ye=()=>Fe;function Xe(e,t,n,r){return i?be(2,1,e,t,n,r):Ze(e,t,n,r)}function Ze(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?Xe(e,t,n,r):(e={ye:n,Xc:e,kd:r,oe:a},i?(e.$c=`spawnThread`,postMessage(e,a),0):ve(e))}function Qe(e){throw Re||=e>>>0,Re}var $e=globalThis.TextDecoder&&new TextDecoder,et=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},tt=(e,t=0,n,r)=>{if(16<(n=et(e,t>>>=0,n,r))-t&&e.buffer&&$e)return $e.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t<n;){var i=e[t++];if(128&i){var a=63&e[t++];if((224&i)==192)r+=String.fromCharCode((31&i)<<6|a);else{var o=63&e[t++];65536>(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},nt=(e,t,n)=>(e>>>=0)?tt((C(),T),e,t,n):``;function rt(e,t,n){return i?be(3,1,e,t,n):0}function it(e,t){if(i)return be(4,1,e,t)}function at(e,t){if(i)return be(5,1,e,t)}function ot(e,t,n){if(i)return be(6,1,e,t,n)}function st(e,t,n){return i?be(7,1,e,t,n):0}function ct(e,t){if(i)return be(8,1,e,t)}function lt(e,t,n){if(i)return be(9,1,e,t,n)}function ut(e,t,n,r){if(i)return be(10,1,e,t,n,r)}function dt(e,t,n,r){if(i)return be(11,1,e,t,n,r)}function ft(e,t,n,r){if(i)return be(12,1,e,t,n,r)}function pt(e){if(i)return be(13,1,e)}function mt(e,t){if(i)return be(14,1,e,t)}function ht(e,t,n){if(i)return be(15,1,e,t,n)}var gt=()=>de(``),_t=e=>{e>>>=0;for(var t=``;;){var n=(C(),T)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},vt={},yt={},bt={},xt=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function St(e,t,n={}){return(function(e,t,n={}){var r=t.name;if(!e)throw new xt(`type "${r}" must have a positive integer typeid pointer`);if(yt.hasOwnProperty(e)){if(n.ve)return;throw new xt(`Cannot register type '${r}' twice`)}yt[e]=t,delete bt[e],vt.hasOwnProperty(e)&&(t=vt[e],delete vt[e],t.forEach(e=>e()))})(e,t,n)}var Ct=(e,t,n)=>{switch(t){case 1:return n?e=>(C(),w)[e>>>0]:e=>(C(),T)[e>>>0];case 2:return n?e=>(C(),te)[e>>>1>>>0]:e=>(C(),ne)[e>>>1>>>0];case 4:return n?e=>(C(),E)[e>>>2>>>0]:e=>(C(),D)[e>>>2>>>0];case 8:return n?e=>(C(),ae)[e>>>3>>>0]:e=>(C(),oe)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function wt(e,t,n,r,i){e>>>=0,n>>>=0,t=_t(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}St(e,{name:t,Wc:a,cd:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),bd:Ct(t,n,!r),dd:null})}function Tt(e,t,n,r){St(e>>>=0,{name:t=_t(t>>>0),Wc:function(e){return!!e},cd:function(e,t){return t?n:r},bd:function(e){return this.Wc((C(),T)[e>>>0])},dd:null})}var Et=[],Dt=[0,1,,1,null,1,!0,1,!1,1];function Ot(e){9<(e>>>=0)&&--Dt[e+1]===0&&(Dt[e]=void 0,Et.push(e))}var kt=e=>{if(!e)throw new xt(`Cannot use deleted val. handle = ${e}`);return Dt[e]},At=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=Et.pop()||Dt.length;return Dt[t]=e,Dt[t+1]=1,t}};function jt(e){return this.Wc((C(),D)[e>>>2>>>0])}var Mt={name:`emscripten::val`,Wc:e=>{var t=kt(e);return Ot(e),t},cd:(e,t)=>At(t),bd:jt,dd:null};function Nt(e){return St(e>>>0,Mt)}var Pt=(e,t)=>{switch(t){case 4:return function(e){return this.Wc((C(),re)[e>>>2>>>0])};case 8:return function(e){return this.Wc((C(),ie)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function Ft(e,t,n){n>>>=0,St(e>>>=0,{name:t=_t(t>>>0),Wc:e=>e,cd:(e,t)=>t,bd:Pt(t,n),dd:null})}function It(e,t,n,r,i){e>>>=0,n>>>=0,t=_t(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<<o>>>o,i=a(i)}St(e,{name:t,Wc:a,cd:(e,t)=>t,bd:Ct(t,n,r!==0),dd:null})}function Lt(e,t,n){function r(e){var t=(C(),D)[e>>>2>>>0];return e=(C(),D)[e+4>>>2>>>0],new i((C(),w).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];St(e>>>=0,{name:n=_t(n>>>0),Wc:r,bd:r},{ve:!0})}var Rt=(e,t,n)=>{var r=(C(),T);if(t>>>=0,0<n){var i=t;n=t+n-1;for(var a=0;a<e.length;++a){var o=e.codePointAt(a);if(127>=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},k=e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function zt(e,t){St(e>>>=0,{name:t=_t(t>>>0),Wc(e){var t=(C(),D)[e>>>2>>>0];return t=nt(e+4,t,!0),Ji(e),t},cd(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new xt(`Cannot pass non-string to std::string`);var r=n?k(t):t.length,i=Yi(4+r+1),a=i+4;return(C(),D)[i>>>2>>>0]=r,n?Rt(t,a,r+1):(C(),T).set(t,a>>>0),e!==null&&e.push(Ji,i),i},bd:jt,dd(e){Ji(e)}})}var Bt=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,Vt=(e,t,n)=>{if(e>>>=1,16<(t=et((C(),ne),e,t/2,n))-e&&Bt)return Bt.decode((C(),ne).slice(e,t));for(n=``;e<t;++e){var r=(C(),ne)[e>>>0];n+=String.fromCharCode(r)}return n},Ht=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i<n;++i){var a=e.charCodeAt(i);(C(),te)[t>>>1>>>0]=a,t+=2}return(C(),te)[t>>>1>>>0]=0,t-r},Ut=e=>2*e.length,Wt=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(C(),D)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},Gt=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i<e.length;++i){var a=e.codePointAt(i);if(65535<a&&i++,(C(),E)[t>>>2>>>0]=a,(t+=4)+4>n)break}return(C(),E)[t>>>2>>>0]=0,t-r},Kt=e=>{for(var t=0,n=0;n<e.length;++n)65535<e.codePointAt(n)&&n++,t+=4;return t};function qt(e,t,n){if(e>>>=0,t>>>=0,n=_t(n>>>=0),t===2)var r=Vt,i=Ht,a=Ut;else r=Wt,i=Gt,a=Kt;St(e,{name:n,Wc:e=>{var n=(C(),D)[e>>>2>>>0];return n=r(e+4,n*t,!0),Ji(e),n},cd:(e,r)=>{if(typeof r!=`string`)throw new xt(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=Yi(4+o+t);return(C(),D)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(Ji,s),s},bd:jt,dd(e){Ji(e)}})}function Jt(e,t){St(e>>>=0,{we:!0,name:t=_t(t>>>0),Wc:()=>{},cd:()=>{}})}function Yt(e){ma(e>>>0,!r,1,!n,131072,!1),ke()}var Xt=e=>{if(!x)try{if(e(),!(0<ye))try{i?qi()&&va(p):Ce(p)}catch(e){e instanceof pe||e==`unwind`||c(0,e)}}catch(e){e instanceof pe||e==`unwind`||c(0,e)}},Zt=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Qt(e){e>>>=0,Zt||(Atomics.waitAsync((C(),E),e>>>2,e).value.then($t),e+=128,Atomics.store((C(),E),e>>>2,1))}var $t=()=>Xt(()=>{var e=qi();e&&(Qt(e),ba())});function en(e,t){(e>>>=0)==t>>>0?setTimeout($t):i?postMessage({gd:e,$c:`checkMailbox`}):(e=De[e])&&e.postMessage({$c:`checkMailbox`})}var tn=[];function nn(e,t,n,r,i){for(t>>>=0,i>>>=0,tn.length=0,n=i>>>3,r=i+r>>>3;n<r;){var a=(C(),ae)[n++>>>0]?(C(),ae)[n++>>>0]:(C(),ie)[n++>>>0];tn.push(a)}return(t?xo[t]:bo[e])(...tn)}var rn=()=>{ye=0};function an(e){e>>>=0,i?postMessage({$c:`cleanupThread`,Le:e}):Oe(De[e])}function on(e){}var sn=e=>{try{e()}catch(e){de(e)}};function cn(e){var t=(...t)=>{fn.push(e);try{return e(...t)}finally{x||(fn.pop(),un&&ln===1&&fn.length===0&&(ln=0,ye+=1,sn(go),typeof Fibers<`u`&&Fibers.We()))}};return hn.set(e,t),t}var ln=0,un=null,dn=0,fn=[],pn=/* @__PURE__ */ new Map,mn=/* @__PURE__ */ new Map,hn=/* @__PURE__ */ new Map,gn=0,_n=null,vn=[],yn=e=>(function(e){if(!x){if(ln===0){var t=!1,n=!1;e((e=0)=>{if(!x&&(dn=e,t=!0,n)){ln=2,sn(()=>_o(un)),typeof MainLoop<`u`&&MainLoop.se&&MainLoop.resume(),e=!1;try{var r=(function(){var e=(C(),E)[un+8>>>2>>>0];return e=mn.get(e),e=hn.get(e),--ye,e()})()}catch(t){r=t,e=!0}var i=!1;if(!un){var a=_n;a&&(_n=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(ln=1,un=(function(){var e=Yi(65548),t=e+12;if((C(),D)[e>>>2>>>0]=t,(C(),D)[e+4>>>2>>>0]=t+65536,t=fn[0],!pn.has(t)){var n=gn++;pn.set(t,n),mn.set(n,t)}return t=pn.get(t),(C(),E)[e+8>>>2>>>0]=t,e})(),typeof MainLoop<`u`&&MainLoop.se&&MainLoop.pause(),sn(()=>ho(un)))}else ln===2?(ln=0,sn(vo),Ji(un),un=null,vn.forEach(Xt)):de(`invalid state: ${ln}`);return dn}})(t=>{e().then(t)});function bn(e){return e>>>=0,yn(async()=>At(await kt(e)))}var xn=[],Sn=e=>{var t=xn.length;return xn.push(e),t},Cn=(e,t)=>{for(var n=Array(e),r=0;r<e;++r){var i=r,a=(C(),D)[t+4*r>>>2>>>0],o=yt[a];if(o===void 0)throw e=`parameter ${r}`,a=Wi(a),t=_t(a),Ji(a),new xt(`${e} has unknown type ${t}`);n[i]=o}return n},wn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((C(),D)[t>>>2>>>0]=At(r)),e},Tn={},En=e=>{var t=Tn[e];return t===void 0?_t(e):t};function Dn(e,t,n){var[r,...i]=Cn(e,t>>>0);t=r.cd.bind(r);var a=i.map(e=>e.bd.bind(e));e--;var o={toValue:kt};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=En,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.we||(o.toReturnWire=t,o.emval_returnValue=wn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) {
96
+ `,Pc=`{%- `,Fc=` -%}`,Ic=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function Lc(e){switch(e.operator.type){case`ExponentiationBinaryOperator`:return Ic.EXPONENTIATION;case`MultiplicativeBinaryOperator`:return Ic.MULTIPLICATIVE;case`AdditiveBinaryOperator`:return Ic.ADDITIVE;case`ComparisonBinaryOperator`:return Ic.COMPARISON;case`Identifier`:return e.operator.value===`and`?Ic.LOGICAL_AND:e.operator.value===`in`||e.operator.value===`not in`?Ic.COMPARISON:Ic.LOGICAL_OR}return Ic.LOGICAL_OR}function Rc(e){switch(e.type){case`SelectExpression`:case`Ternary`:return Ic.CONDITIONAL;case`BinaryExpression`:return Lc(e);case`UnaryExpression`:return e.operator.value===`not`?Ic.LOGICAL_NOT:Ic.UNARY_SIGN;case`TestExpression`:return Ic.TEST;case`FilterExpression`:return Ic.FILTER;default:return Ic.ATOM}}function zc(e,t){let n=Zc(e);return Rc(e)<t?`(${n})`:n}function Bc(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return Hc(e.body,0,n).replace(/\n$/,``)}function Vc(...e){return Pc+e.join(` `)+Fc}function Hc(e,t,n){return e.map(e=>Wc(e,t,n)).join(Nc)}function Uc(e){return e.map(e=>Zc(e)).join(`, `)}function Wc(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return Hc(e.body,t,n);case`If`:return Gc(e,t,n);case`For`:return Kc(e,t,n);case`Set`:return qc(e,t,n);case`Macro`:return Jc(e,t,n);case`Break`:return r+Vc(`break`);case`Continue`:return r+Vc(`continue`);case`CallStatement`:return Yc(e,t,n);case`FilterStatement`:return Xc(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+Zc(e)+` -}}`}}function Gc(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+Vc(`if`,Zc(i[0].test))+Nc+Hc(i[0].body,t+1,n);for(let e=1;e<i.length;++e)o+=Nc+r+Vc(`elif`,Zc(i[e].test))+Nc+Hc(i[e].body,t+1,n);return a&&a.alternate.length>0&&(o+=Nc+r+Vc(`else`)+Nc+Hc(a.alternate,t+1,n)),o+=Nc+r+Vc(`endif`),o}function Kc(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${Zc(t.lhs)} if ${Zc(t.test)}`}else i=Zc(e.iterable);let a=r+Vc(`for`,Zc(e.loopvar),`in`,i)+Nc+Hc(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=Nc+r+Vc(`else`)+Nc+Hc(e.defaultBlock,t+1,n)),a+=Nc+r+Vc(`endfor`),a}function qc(e,t,n){let r=n.repeat(t),i=Zc(e.assignee),a=e.value?Zc(e.value):``,o=r+Vc(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+Nc+Hc(e.body,t+1,n)+Nc+r+Vc(`endset`)}function Jc(e,t,n){let r=n.repeat(t),i=Uc(e.args);return r+Vc(`macro`,`${e.name.value}(${i})`)+Nc+Hc(e.body,t+1,n)+Nc+r+Vc(`endmacro`)}function Yc(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${Uc(e.callerArgs)})`:``,a=Zc(e.call),o=r+Vc(`call${i}`,a)+Nc;return o+=Hc(e.body,t+1,n)+Nc,o+=r+Vc(`endcall`),o}function Xc(e,t,n){let r=n.repeat(t),i=r+Vc(`filter`,e.filter.type===`Identifier`?e.filter.value:Zc(e.filter))+Nc;return i+=Hc(e.body,t+1,n)+Nc,i+=r+Vc(`endfilter`),i}function Zc(e){switch(e.type){case`SpreadExpression`:return`*${Zc(e.argument)}`;case`KeywordSpreadExpression`:return`**${Zc(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:{let t=e.value;return Object.is(t,-0)?`-0.0`:t%1==0?t.toFixed(1):t.toString()}case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let t=e,n=Lc(t),r=zc(t.left,n),i=zc(t.right,n+1);return`${r} ${t.operator.value} ${i}`}case`UnaryExpression`:{let t=e,n=t.argument.type===`UnaryExpression`?Rc(t):Ic.ATOM;return t.operator.value+(t.operator.value===`not`?` `:``)+zc(t.argument,n)}case`CallExpression`:{let t=e,n=Uc(t.args);return`${Zc(t.callee)}(${n})`}case`MemberExpression`:{let t=e,n=zc(t.object,Ic.ATOM),r=Zc(t.property);return!t.computed&&t.property.type!==`Identifier`&&t.property.type!==`IntegerLiteral`&&(r=`(${r})`),t.computed?`${n}[${r}]`:`${n}.${r}`}case`FilterExpression`:{let t=e,n=zc(t.operand,Ic.FILTER);return t.filter.type===`CallExpression`?`${n} | ${Zc(t.filter)}`:`${n} | ${t.filter.value}`}case`SelectExpression`:{let t=e;return`${zc(t.lhs,Ic.LOGICAL_OR)} if ${zc(t.test,Ic.LOGICAL_OR)}`}case`TestExpression`:{let t=e;return`${zc(t.operand,Ic.TEST)} is${t.negate?` not`:``} ${t.test.value}`}case`ArrayLiteral`:case`TupleLiteral`:{let t=Uc(e.value),n=e.type===`ArrayLiteral`?`[]`:`()`;return`${n[0]}${t}${n[1]}`}case`ObjectLiteral`:return`{${Array.from(e.value.entries()).map(([e,t])=>`${Zc(e)}: ${Zc(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?Zc(t.start):``}:${t.stop?Zc(t.stop):``}${t.step?`:${Zc(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${Zc(t.value)}`}case`Ternary`:{let t=e;return`${zc(t.trueExpr,Ic.LOGICAL_OR)} if ${zc(t.condition,Ic.LOGICAL_OR)} else ${zc(t.falseExpr,Ic.CONDITIONAL)}`}default:throw Error(`Unknown expression type: ${e.type}`)}}var Qc=class{parsed;constructor(e){let t=vs(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Zs(t)}render(e){let t=new xc;if(Sc(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new jc(t).run(this.parsed).value}format(e){return Bc(this.parsed,e?.indent||` `)}},$c={txt:`text/plain`,html:`text/html`,css:`text/css`,js:`text/javascript`,json:`application/json`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`},el=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=f.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=f.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=f.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,$c[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await f.promises.readFile(this.filePath)).buffer}async blob(){let e=await f.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await f.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},tl=class{constructor(e){this._mt=/* @__PURE__ */ new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null){if(j.IS_CRYPTO_AVAILABLE){let t=/* @__PURE__ */ new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0}let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t|0);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(1812433253,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1566083941))-i>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&2147483648|e[(t+1)%624]&2147483647;e[t]=(e[(t+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[nl(this._random_fn,t)]}};function nl(e,t){let n=0;for(let e=0;e<t.length;++e)n+=t[e];let r=e()*n;for(let e=0;e<t.length;++e)if(r-=t[e],r<0)return e;return t.length-1}var rl=new tl,il=Object.freeze({Random:tl,seed:rl.seed.bind(rl),random:rl.random.bind(rl),gauss:rl.gauss.bind(rl),shuffle:rl.shuffle.bind(rl),choices:rl.choices.bind(rl)}),al=e=>nl(il.random,e),ol=new tl,sl=class{constructor(e){this.path=e}async match(e){let t=new el(h.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=h.join(this.path,e),i=r+`.tmp.${j.IS_PROCESS_AVAILABLE?l.pid:Date.now()}.${ol._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await f.promises.mkdir(h.dirname(r),{recursive:!0});let s=f.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{t?n(t):e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await f.promises.rename(i,r)}catch(e){try{await f.promises.unlink(i)}catch{}throw e}}async delete(e){let t=h.join(this.path,e);try{return await f.promises.unlink(t),!0}catch{return!1}}},cl={400:`Bad request error occurred while trying to load file`,401:`Unauthorized access to file`,403:`Forbidden access to file`,404:`Could not locate file`,408:`Request timeout error occurred while trying to load file`,500:`Internal server error error occurred while trying to load file`,502:`Bad gateway error occurred while trying to load file`,503:`Service unavailable error occurred while trying to load file`,504:`Gateway timeout error occurred while trying to load file`},ll=100,ul=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function dl(...e){return e=e.map((t,n)=>(n&&(t=t.replace(/* @__PURE__ */ RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(/* @__PURE__ */ RegExp(`/$`),``)),t)),e.join(`/`)}function fl(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function pl(e){return!(!ul.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function ml(e,t={},...n){return JSON.stringify([e,t.revision??`main`,t.cache_dir??null,t.local_files_only??!1,...n])}var hl=class extends Error{constructor(e,{status:t=null}={}){super(e),this.name=`ModelFileNotFoundError`,this.status=t}},gl=/* @__PURE__ */ new Set([401,403,404]);function _l(e,t,n){if(!n)return null;let r=`${cl[e]??`Error (${e}) occurred while trying to load file`}: "${t}".`;throw gl.has(e)?new hl(r,{status:e}):Error(r)}async function vl(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&N.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function yl(e){return fl(e,[`blob:`])}function bl(e,{allowUnresolved:t=!1}={}){let n;if(typeof location<`u`&&location.href)n=location.href;else if(import.meta.url)n=import.meta.url;else return e;try{return new URL(e,n).href}catch(n){if(!t)throw n;return e}}var xl=`SHA-256`,Sl=`experimental_transformers-hash-cache`,Cl=e=>({algorithm:xl,value:e}),wl=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Sl),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let e=await(await navigator.crossOriginStorage.requestFileHandle(Cl(t))).getFile();return new Response(e,{headers:{"Content-Length":String(e.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(Cl(t),{create:!0,origins:`*`})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(xl,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function Tl(e=null){let t=null;if(M.useCustomCache){if(!M.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!M.customCache.match||!M.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=M.customCache}if(!t&&M.experimental_useCrossOriginStorage&&wl.isAvailable()&&(t=new wl),!t&&M.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(M.cacheKey)}catch(e){N.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&M.useFSCache){if(!j.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new sl(e??M.cacheDir)}return t}async function El(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var Dl=new class{#e;#t;constructor(e){this.#e=e,this.#t=/* @__PURE__ */ new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function Ol(e,t){let n=Dl.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(Dl.delete(e),Promise.reject(t)));return Dl.put(e,r),r}async function kl(e){if(!fl(e,[`http:`,`https:`]))return null;let t=Nl(e);return t.set(`Range`,`bytes=0-0`),M.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function Al(e,t,n={}){return Ol(ml(e,n,t),()=>jl(e,t,n))}async function jl(e,t,n){let r=await Tl(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=Pl(e,t,n,r),c=await Fl(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(M.allowLocalModels&&!fl(i,[`http:`,`https:`]))try{let e=await Ml(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(M.allowRemoteModels&&!n.local_files_only&&s){let e=await kl(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \d+-\d+\/(\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}e&&e.status!==404&&e.status!==416&&_l(e.status,a,!0)}return{exists:!1,fromCache:!1}}async function Ml(e){return M.useFS&&!fl(e,[`http:`,`https:`,`blob:`])?new el(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):M.fetch(e,{headers:Nl(e)})}function Nl(e){let t=l!==void 0&&l?.release?.name===`node`,n=new Headers;if(t){let t=!!l.env?.TESTING_REMOTELY,r=M.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),fl(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e=l.env?.HF_TOKEN??l.env?.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function Pl(e,t,n={},r=null){let i=n.revision??`main`,a=dl(e,t),o=pl(e),s=o?dl(M.localModelPath,a):a,c=dl(M.remoteHost,M.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof sl?i===`main`?a:dl(e,i,t):c,validModelId:o}}async function Fl(e,t,n){if(e)return await El(e,t,n)}async function Il(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0&&!(typeof Cache<`u`&&n instanceof Cache&&!fl(bl(r,{allowUnresolved:!0}),[`http:`,`https:`]))){if(!a){let a=o.progress_callback?n=>Li(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}else if(typeof i!=`string`){let e=new Headers(i.headers);e.set(`content-length`,a.byteLength.toString()),await n.put(r,new Response(a,{headers:e})).catch(e=>{N.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function Ll(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=Pl(e,t,r,a),d,f=!1,p;p=await Fl(a,s,l);let m=p!==void 0;if(m)d=l;else{if(M.allowLocalModels){if(!fl(o,[`http:`,`https:`]))try{p=await Ml(s),d=s}catch(e){N.warn(`Unable to load from local path "${s}": "${e}"`)}else if(r.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);else if(!M.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!M.allowRemoteModels){if(n)throw new hl(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${s}".`);return null}if(!u)throw new hl(`Local file missing at "${s}" and download aborted due to invalid model ID "${e}".`);if(p=await Ml(c),p.status!==200)return _l(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}Li(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(j.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`){if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),Li(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await Al(e,t,r);n.size&&(i=n.size)}catch{}n=await vl(p,n=>{Li(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}}h=n}if(f&&d&&typeof p!=`string`&&await Il(e,t,a,d,p,h,r),j.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;Li(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(Li(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!j.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof el)return p.filePath;let g=await a?.match(d);if(g instanceof el)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}var Rl=/* @__PURE__ */ new Map;async function zl(e,t,n=!0,r={},i=!1){if(!M.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!M.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let a=ml(e,r,t,n,i),{progress_callback:o}=r,s=o instanceof Ri?o.loads:Rl,c=s.get(a);return c||(Li(o,{status:`initiate`,name:e,file:t}),c=Tl(r.cache_dir).then(a=>Ll(e,t,n,r,i,a)),s===Rl&&(c=c.finally(()=>Rl.delete(a))),s.set(a,c)),await c}async function Bl(e,t,n=!0,r={}){let i=await zl(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function Vl(e,t,n=!0,r={}){let i=await Bl(e,t,n,r);return i===null?{}:JSON.parse(i)}function Hl(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o<i;++o)for(let i=0;i<a;++i){let s=o*a+i,p=(i+.5)/c-.5,m=(o+.5)/l-.5,h=Math.floor(p),g=Math.floor(m),_=Math.min(h+1,r-1),v=Math.min(g+1,n-1);h=Math.max(h,0),g=Math.max(g,0);let y=p-h,b=m-g,x=(1-y)*(1-b),S=y*(1-b),C=(1-y)*b,ee=y*b,w=g*r,T=v*r,te=w+h,ne=w+_,E=T+h,D=T+_;for(let n=0;n<t;++n){let t=n*d;u[n*f+s]=x*e[t+te]+S*e[t+ne]+C*e[t+E]+ee*e[t+D]}}return u}function Ul(e,t,n){let r=Array(n.length),i=Array(n.length);for(let e=n.length-1,a=1;e>=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n<e.length;++n){let r=0;for(let e=t.length-1,i=n;e>=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function Wl(e){let t=ql(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function Gl(e){let t=ql(e)[0],n=0;for(let r=0;r<e.length;++r)n+=Math.exp(e[r]-t);let r=Math.log(n);return e.map(e=>e-t-r)}function Kl(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}function ql(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],n=r);return[t,n]}function Jl(e){return e>0&&!(e&e-1)}var Yl=class{constructor(e){if(this.size=e|0,this.size<=1||!Jl(this.size))throw Error(`FFT size must be a power of two larger than 1`);this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let e=0;e<this.table.length;e+=2){let t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){let n=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let n=t||Array(e.length>>>1);for(let t=0;t<e.length;t+=2)n[t>>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t<n.length;t+=2)n[t]=e[t>>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleTransform2(t,e,o,n,i)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleTransform4(t,e,o,r,i,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o<r;o+=a){let r=o+t-1;for(let a=o,s=0;a<r;a+=2,s+=i){let r=a,i=r+t,o=i+t,c=o+t,u=e[r],d=e[r+1],f=e[i],p=e[i+1],m=e[o],h=e[o+1],g=e[c],_=e[c+1],v=l[s],y=n*l[s+1],b=f*v-p*y,x=f*y+p*v,S=l[2*s],C=n*l[2*s+1],ee=m*S-h*C,w=m*C+h*S,T=l[3*s],te=n*l[3*s+1],ne=g*T-_*te,E=g*te+_*T,D=u+ee,re=d+w,ie=u-ee,ae=d-w,oe=b+ne,se=x+E,ce=n*(b-ne),le=n*(x-E);e[r]=D+oe,e[r+1]=re+se,e[i]=ie+le,e[i+1]=ae-ce,e[o]=D-oe,e[o+1]=re-se,e[c]=ie-le,e[c+1]=ae+ce}}}}_singleTransform2(e,t,n,r,i){let a=e[r],o=e[r+1],s=e[r+i],c=e[r+i+1];t[n]=a+s,t[n+1]=o+c,t[n+2]=a-s,t[n+3]=o-c}_singleTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+1],u=e[r+i],d=e[r+i+1],f=e[r+o],p=e[r+o+1],m=e[r+s],h=e[r+s+1],g=c+f,_=l+p,v=c-f,y=l-p,b=u+m,x=d+h,S=a*(u-m),C=a*(d-h);t[n]=g+b,t[n+1]=_+x,t[n+2]=v+C,t[n+3]=y-S,t[n+4]=g-b,t[n+5]=_-x,t[n+6]=v-C,t[n+7]=y+S}_realTransform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleRealTransform2(t,e,o,n>>>1,i>>>1)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleRealTransform4(t,e,o,r>>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o<r;o+=a)for(let r=0,a=0;r<=c;r+=2,a+=i){let i=o+r,u=i+s,d=u+s,f=d+s,p=e[i],m=e[i+1],h=e[u],g=e[u+1],_=e[d],v=e[d+1],y=e[f],b=e[f+1],x=p,S=m,C=l[a],ee=n*l[a+1],w=h*C-g*ee,T=h*ee+g*C,te=l[2*a],ne=n*l[2*a+1],E=_*te-v*ne,D=_*ne+v*te,re=l[3*a],ie=n*l[3*a+1],ae=y*re-b*ie,oe=y*ie+b*re,se=x+E,ce=S+D,le=x-E,ue=S-D,de=w+ae,O=T+oe,fe=n*(w-ae),pe=n*(T-oe);if(e[i]=se+de,e[i+1]=ce+O,e[u]=le+pe,e[u+1]=ue-fe,r===0){e[d]=se-de,e[d+1]=ce-O;continue}if(r===c)continue;let me=o+s-r,he=o+t-r;e[me]=le-n*pe,e[me+1]=-ue-n*fe,e[he]=se-n*de,e[he+1]=-ce+n*O}}let u=r>>>1;for(let t=2;t<u;t+=2)e[r-t]=e[t],e[r-t+1]=-e[t+1]}_singleRealTransform2(e,t,n,r,i){let a=e[r],o=e[r+i];t[n]=a+o,t[n+1]=0,t[n+2]=a-o,t[n+3]=0}_singleRealTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+i],u=e[r+o],d=e[r+s],f=c+u,p=c-u,m=l+d,h=a*(l-d);t[n]=f+m,t[n+1]=0,t[n+2]=p,t[n+3]=-h,t[n+4]=f-m,t[n+5]=0,t[n+6]=p,t[n+7]=h}},Xl=class{constructor(e){let t=2*(e-1),n=2*(2*e-1),r=2**Math.ceil(Math.log2(n));this.bufferSize=r,this._a=t;let i=new Float64Array(n),a=new Float64Array(r);this._chirpBuffer=new Float64Array(r),this._buffer1=new Float64Array(r),this._buffer2=new Float64Array(r),this._outBuffer1=new Float64Array(r),this._outBuffer2=new Float64Array(r);let o=-2*Math.PI/e,s=Math.cos(o),c=Math.sin(o);for(let t=0;t<n>>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new Yl(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e<c.length;e+=2){let n=e+1,i=t[e>>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e<c.length;e+=2){let n=e+1;r[e]=t[e]*c[e]-t[n]*c[n],r[n]=t[e]*c[n]+t[n]*c[e]}this._f.transform(a,r);for(let e=0;e<s.length;e+=2){let t=e+1;i[e]=a[e]*s[e]-a[t]*s[t],i[t]=a[e]*s[t]+a[t]*s[e]}this._f.inverseTransform(o,i);for(let t=0;t<o.length;t+=2){let n=o[t+l],r=o[t+l+1],i=c[t],a=c[t+1];e[t]=n*i-r*a,e[t+1]=n*a+r*i}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},Zl=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Jl(e),this.isPowerOfTwo?(this.fft=new Yl(e),this.outputBufferSize=2*e):(this.fft=new Xl(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function Ql(e,t){if(t%2==0||t<=0)throw Error(`Window size must be a positive odd number`);let n=new e.constructor(e.length),r=new e.constructor(t),i=Math.floor(t/2);for(let t=0;t<e.length;++t){let a=0;for(let n=-i;n<=i;++n){let i=t+n;i<0?i=Math.abs(i):i>=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function $l(e,t){let n=10**t;return Math.round(e*n)/n}function eu(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function tu(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t<r[1];++t)for(let n=1;n<r[0];++n){let r=i[n-1][t-1],o=i[n-1][t],s=i[n][t-1],c,l;r<o&&r<s?(c=r,l=0):o<r&&o<s?(c=o,l=1):(c=s,l=2),i[n][t]=e[n-1][t-1]+c,a[n][t]=l}for(let e=0;e<r[1];++e)a[0][e]=2;for(let e=0;e<r[0];++e)a[e][0]=1;let o=t,s=n,c=[],l=[];for(;o>0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var nu=/* @__PURE__ */ (function(){let e=null;return function(t){if(!e){e=/* @__PURE__ */ new Float32Array(65536);let t=/* @__PURE__ */ new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;++t){let i=0,a=(t&32768)<<16,o=(t&31744)>>10,s=t&1023;if(o===31)i=a|2139095040|s<<13;else if(o===0){if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;e<n;++e)i[e]=r[t[e]];return i}})(),ru=b(import.meta.url??__filename);l.env.ORT_DISABLE_TELEMETRY=`1`;var iu=ru(`onnxruntime-node`),au={};ci(au,{InferenceSession:()=>ad,TRACE:()=>Xu,TRACE_EVENT_BEGIN:()=>ed,TRACE_EVENT_END:()=>td,TRACE_FUNC_BEGIN:()=>Qu,TRACE_FUNC_END:()=>$u,Tensor:()=>Ju,default:()=>Ip,env:()=>Eu,registerBackend:()=>gu});var ou=Object.defineProperty,su=Object.getOwnPropertyDescriptor,cu=Object.getOwnPropertyNames,lu=Object.prototype.hasOwnProperty,uu=(e=>typeof si<`u`?si:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof si<`u`?si:e)[t]}):e)(function(e){if(typeof si<`u`)return si.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),U=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},du=(e,t)=>{for(var n in t)ou(e,n,{get:t[n],enumerable:!0})},fu=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of cu(t))!lu.call(e,i)&&i!==n&&ou(e,i,{get:()=>t[i],enumerable:!(r=su(t,i))||r.enumerable});return e},pu=e=>fu(ou({},`__esModule`,{value:!0}),e),mu,hu,gu,_u,vu,yu=U(()=>{mu=/* @__PURE__ */ new Map,hu=[],gu=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=mu.get(e);if(r===void 0)mu.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=hu.indexOf(e);t!==-1&&hu.splice(t,1);for(let t=0;t<hu.length;t++)if(mu.get(hu[t]).priority<=n){hu.splice(t,0,e);return}hu.push(e)}}else throw TypeError(`not a valid backend`)},_u=async e=>{let t=mu.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},vu=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?hu:n,i,a=[],o=/* @__PURE__ */ new Set;for(let e of r){let t=await _u(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),bu=U(()=>{yu()}),xu,Su=U(()=>{xu=`1.31.0-dev.20260911-2a43ec07e`}),Cu,wu,Tu=U(()=>{Su(),Cu=`warning`,wu={wasm:{},webgl:{},webgpu:{},versions:{common:xu},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Cu=e}},get logLevel(){return Cu}},Object.defineProperty(wu,"logLevel",{enumerable:!0})}),Eu,Du=U(()=>{Tu(),Eu=wu}),Ou,ku,Au=U(()=>{Ou=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},ku=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),ju,Mu,Nu,Pu,Fu,Iu,Lu=U(()=>{qu(),ju=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new Ku(`float32`,u,[1,4,n,r]):new Ku(`float32`,u,[1,3,n,r])},Mu=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,ju(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(ju(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return ju(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},Nu=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new Ku({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},Pu=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Ku({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},Fu=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Ku({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},Iu=(e,t,n)=>new Ku({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),Ru,zu,Bu,Vu,Hu=U(()=>{Ru=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),zu=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),Bu=!1,Vu=()=>{if(!Bu){Bu=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(Ru.set(`int64`,BigInt64Array),zu.set(BigInt64Array,`int64`)),t&&(Ru.set(`uint64`,BigUint64Array),zu.set(BigUint64Array,`uint64`)),r?(Ru.set(`float16`,n),zu.set(n,`float16`)):Ru.set(`float16`,Uint16Array)}}}),Uu,Wu,Gu=U(()=>{qu(),Uu=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},Wu=(e,t)=>{switch(e.location){case`cpu`:return new Ku(e.type,e.data,t);case`cpu-pinned`:return new Ku({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new Ku({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new Ku({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new Ku({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ku,qu=U(()=>{Au(),Lu(),Hu(),Gu(),Ku=class{constructor(e,t,n){Vu();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=Ru.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=Ru.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=zu.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=Uu(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return Mu(e,t)}static fromTexture(e,t){return Nu(e,t)}static fromGpuBuffer(e,t){return Pu(e,t)}static fromMLTensor(e,t){return Fu(e,t)}static fromPinnedBuffer(e,t,n){return Iu(e,t,n)}toDataURL(e){return Ou(this,e)}toImageData(e){return ku(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return Wu(this,e)}}}),Ju,Yu=U(()=>{qu(),Ju=Ku}),Xu,Zu,Qu,$u,ed,td,nd=U(()=>{Tu(),Xu=(e,t)=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||console.timeStamp(`${e}::ORT::${t}`)},Zu=(e,t)=>{let n=(/* @__PURE__ */ Error()).stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),Xu(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},Qu=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||Zu(`BEGIN`,e)},$u=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||Zu(`END`,e)},ed=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||console.time(`ORT::${e}`)},td=e=>{(typeof wu.trace>`u`?!wu.wasm.trace:!wu.trace)||console.timeEnd(`ORT::${e}`)}}),rd,id=U(()=>{yu(),Yu(),nd(),rd=class e{constructor(e){this.handler=e}async run(e,t,n){Qu(),ed(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof Ju||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof Ju)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof Ju)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof Ju?t:new Ju(t.type,t.data,t.dims)}return td(`InferenceSession.run`),$u(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){Qu(),ed(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await vu(o),l=await s.createInferenceSessionHandler(a,c);return td(`InferenceSession.create`),$u(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),ad,od=U(()=>{id(),ad=rd}),sd=U(()=>{}),cd=U(()=>{}),ld=U(()=>{}),ud=U(()=>{}),dd={};du(dd,{InferenceSession:()=>ad,TRACE:()=>Xu,TRACE_EVENT_BEGIN:()=>ed,TRACE_EVENT_END:()=>td,TRACE_FUNC_BEGIN:()=>Qu,TRACE_FUNC_END:()=>$u,Tensor:()=>Ju,env:()=>Eu,registerBackend:()=>gu});var fd=U(()=>{bu(),Du(),od(),Yu(),sd(),cd(),nd(),ld(),ud()}),pd=U(()=>{}),md={};du(md,{default:()=>_d});var hd,gd,_d,vd=U(()=>{op(),Jd(),Rd(),hd=`ort-wasm-proxy-worker`,gd=globalThis.self?.name===hd,gd&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:Kd(n.wasm).then(()=>{Jf(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;Yf(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=$f(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;ep(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:tp(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;rp(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},ap([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:ip(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),_d=gd?null:e=>new Worker(e??Dd,{type:`module`,name:hd})}),yd={};du(yd,{default:()=>xd});async function bd(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.ed||=/* @__PURE__ */ new Map).set(e,n)},t.unmountExternalData=()=>{delete t.ed,delete t.Te,delete t.Se,delete t.Ue},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=un;return t=e(...t),un==n?t:new Promise((e,t)=>{_n={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=import.meta.url,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(S(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,x=!1,S=e=>e.startsWith(`file://`);function C(){Me.buffer!=w.buffer&&le()}if(i){let e=function(n){try{var r=n.data,i=r.$c;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({$c:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.ue)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({$c:`callHandler`,te:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));Me=r.Me,le(),f=r.Ne,fe(),cs()}else if(i===`run`){(function(e){var t=(C(),D)[e+52>>>2>>>0];e=(C(),D)[e+56>>>2>>>0],Ca(t,t-e),F(t)})(r.Xc),ma(r.Xc,0,0,1,0,0),ke(),Qt(r.Xc),ee||=(Gi(),!0);try{Ne(r.ze,r.kd)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?ee&&$t():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw ha(),e}};var ee=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var w,T,te,ne,E,D,re,ie,ae,oe,se,ce=!1;function le(){var e=Me.buffer;t.HEAP8=w=new Int8Array(e),te=new Int16Array(e),t.HEAPU8=T=new Uint8Array(e),ne=new Uint16Array(e),t.HEAP32=E=new Int32Array(e),t.HEAPU32=D=new Uint32Array(e),re=new Float32Array(e),ie=new Float64Array(e),ae=new BigInt64Array(e),oe=new BigUint64Array(e)}function ue(){ce=!0,i?g():yo.hc()}function de(e){throw b(e=`Aborted(`+e+`)`),x=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function O(){return{a:{qa:So,f:Le,K:ze,k:We,p:Ge,l:Ke,fa:qe,b:Je,da:Ye,gc:Ze,q:Qe,ea:rt,Ua:it,cc:at,ec:ot,Va:st,Sa:ct,La:lt,Ra:ut,oa:dt,dc:ft,ac:pt,Ta:mt,bc:ht,_a:gt,Ba:wt,Xb:Tt,Vb:Nt,Aa:Ft,O:It,J:Lt,Wb:zt,ka:qt,Yb:Jt,Oa:Yt,_b:en,Ea:nn,Tb:rn,Ca:an,Na:Qt,Xa:on,U:bn,n:Dn,c:Ot,qb:On,w:kn,N:An,A:jn,j:Mn,o:Nn,rb:Pn,H:Fn,T:In,g:Ln,u:Rn,m:zn,i:Bn,Ia:Vn,Ja:Gn,Ka:Kn,Ga:qn,Ha:Jn,Ub:Zn,ab:Qn,Za:tr,Z:ir,pb:ar,Da:or,Ya:$n,X:sr,Wa:cr,$b:lr,G:Xn,db:ur,_:dr,pa:_r,Zb:vr,cb:gr,bb:yr,lb:qr,z:Jr,sa:Yr,ra:Xr,nb:Zr,Y:Qr,v:$r,kb:ei,jb:ti,ib:ni,mb:ri,gb:ii,fb:ai,eb:oi,Pa:ui,Qa:di,fc:Ce,W:fi,Fa:pi,ma:mi,Ma:hi,la:_i,Fb:os,va:es,Gb:as,wa:$o,E:Bo,e:Eo,r:wo,x:Co,C:Io,Ib:Xo,ca:Yo,D:ko,xa:Zo,aa:ts,ha:Jo,Jb:qo,Kb:Ko,za:Ho,Lb:Wo,ya:Go,Mb:Uo,ua:is,ba:Qo,d:To,B:Oo,s:Do,Eb:ss,t:jo,y:Ro,F:Ao,I:Mo,L:zo,Nb:Vo,R:ns,ia:Fo,$:rs,Pb:Po,Rb:No,Ob:Lo,h:vi,a:Me,$a:xe,Hb:yi,V:bi,M:xi,na:Si,Db:Ci,ja:wi,S:Ti,Ab:Ei,Bb:j,vb:Di,wb:Oi,P:ki,xb:Ai,yb:ji,ta:Mi,Sb:Ni,ob:Pi,Q:M,hb:Fi,Cb:Ii,sb:Li,tb:zi,ub:Bi,ga:Vi,zb:Hi,Qb:Ui}}}async function fe(){function e(e,n){var r=yo=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=cn(n),e[t]=r):e[t]=n;return yo=e,yo=(function(){var e=yo,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).ic=t(e.ic),e.Nc=n(e.Nc),e.Pc=t(e.Pc),e.Bd=/* @__PURE__ */ (e=>(t,n)=>e(t,n)>>>0)(e.Bd),e.Gd=t(e.Gd),e.Hd=n(e.Hd),e.Ld=t(e.Ld),e})(),Ee.push(yo.sd),Wi=(e=yo).ic,Gi=e.jc,t._OrtInit=e.kc,t._OrtGetLastError=e.lc,t._OrtCreateSessionOptions=e.mc,t._OrtAppendExecutionProvider=e.nc,t._OrtAddFreeDimensionOverride=e.oc,t._OrtAddSessionConfigEntry=e.pc,t._OrtReleaseSessionOptions=e.qc,t._OrtCreateSession=e.rc,t._OrtReleaseSession=e.sc,t._OrtGetInputOutputCount=e.tc,t._OrtGetInputOutputMetadata=e.uc,t._OrtFree=e.vc,t._OrtCreateTensor=e.wc,t._OrtGetTensorData=e.xc,t._OrtReleaseTensor=e.yc,t._OrtCreateRunOptions=e.zc,t._OrtAddRunConfigEntry=e.Ac,t._OrtReleaseRunOptions=e.Bc,t._OrtCreateBinding=e.Cc,t._OrtBindInput=e.Dc,t._OrtBindOutput=e.Ec,t._OrtClearBoundOutputs=e.Fc,t._OrtReleaseBinding=e.Gc,t._OrtRunWithBinding=e.Hc,t._OrtRun=e.Ic,t._OrtEndProfiling=e.Jc,Ki=t._OrtCreateWebGpuInstance=e.Kc,t._wgpuCreateInstance=e.Lc,N=t._OrtGetWebGpuDevice=e.Mc,qi=e.Nc,Ji=t._free=e.Oc,Yi=t._malloc=e.Pc,Xi=t._wgpuBufferRelease=e.Qc,Zi=e.Rc,Qi=e.Sc,$i=e.Tc,ea=e.Uc,ta=e.Vc,na=e.Yc,ra=e.Zc,ia=e.hd,aa=e.id,oa=e.jd,sa=e.ld,ca=e.md,la=e.nd,ua=e.od,da=e.pd,fa=e.qd,pa=e.rd,ma=e.ud,ha=e.vd,ga=e.wd,_a=e.xd,va=e.yd,ya=e.zd,ba=e.Ad,xa=e.Bd,P=e.Cd,Sa=e.Dd,Ca=e.Ed,F=e.Fd,wa=e.Gd,I=e.Hd,Ta=e.Id,Ea=e.Jd,Da=e.Kd,Oa=e.Ld,ka=e.Md,Aa=e.Nd,ja=e.Od,Ma=e.Pd,Na=e.Qd,Pa=e.Rd,Fa=e.Sd,Ia=e.Td,La=e.Ud,Ra=e.Vd,za=e.Wd,Ba=e.Xd,Va=e.Yd,Ha=e.Zd,Ua=e._d,Wa=e.$d,Ga=e.ae,Ka=e.be,qa=e.ce,Ja=e.de,Ya=e.fe,Xa=e.ge,Za=e.he,Qa=e.ie,$a=e.je,eo=e.ke,to=e.le,no=e.me,ro=e.Ae,io=e.Be,ao=e.Ce,oo=e.De,so=e.Ee,co=e.Fe,lo=e.Ge,uo=e.He,fo=e.Ie,po=e.Je,mo=e.Ke,ho=e.nf,go=e.of,_o=e.pf,vo=e.qf,f=n,yo}var n,r=O();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,O()),f):(se??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(`ort-wasm-simd-threaded.asyncify.wasm`,import.meta.url).href,n=await(async function(e){var t=se;if(!d&&!S(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return(async function(e,t){try{var n=await(async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==se&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e})(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),de(e)}})(t,e)})(r),e(n.instance,n.module))}class pe{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var me=e=>{e.terminate(),e.onmessage=()=>{}},he=[],ge=0,_e=null,ve=e=>{we.length==0&&(je(),Ae(we[0]));var t=we.pop();if(!t)return 6;Te.push(t),De[e.Xc]=t,t.Xc=e.Xc;var n={$c:`run`,ze:e.ye,kd:e.kd,Xc:e.Xc};return t.postMessage(n,e.oe),0},ye=0,be=(e,t,...n)=>{var r,i=16*n.length,a=I(),o=wa(i),s=o>>>3;for(r of n)typeof r==`bigint`?((C(),ae)[s++>>>0]=1n,(C(),ae)[s++>>>0]=r):((C(),ae)[s++>>>0]=0n,(C(),ie)[s++>>>0]=r);return e=ga(e,0,i,o,t),F(a),e};function xe(e){if(i)return be(0,1,e);if(p=e,!(0<ye)){for(var t of Te)me(t);for(t of we)me(t);we=[],Te=[],De={},x=!0}c(0,new pe(e))}function Se(e){if(i)return be(1,0,e);Ce(e)}var Ce=e=>{if(p=e,i)throw Se(e),`unwind`;xe(e)},we=[],Te=[],Ee=[],De={},Oe=e=>{var t=e.Xc;delete De[t],we.push(e),Te.splice(Te.indexOf(e),1),e.Xc=0,_a(t)};function ke(){Ee.forEach(e=>e())}var Ae=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.$c,i.gd&&i.gd!=qi()){var a=De[i.gd];a?a.postMessage(i,i.oe):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.gd}, but that thread no longer exists!`)}else r===`checkMailbox`?$t():r===`spawnThread`?ve(i):r===`cleanupThread`?Xt(()=>{Oe(De[i.Le])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.te](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({$c:`load`,ue:i,Me,Ne:f})});function je(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.webgpu.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});we.push(e)}var Me,Ne=(e,t)=>{ye=0,e=Aa(e,t),0<ye?p=e:va(e)},Pe=[],Fe=0,Ie=e=>-9007199254740992>e||9007199254740992<e?NaN:Number(e);function Le(e){var t=new He(e>>>=0);return(C(),w)[t.ad+12>>>0]==0&&(Be(t,!0),Fe--),Ve(t,!1),Pe.push(t),Oa(e)}var Re=0,ze=()=>{P(0,0);var e=Pe.pop();Ta(e.td),Re=0};function Be(e,t){t=+!!t,(C(),w)[e.ad+12>>>0]=t}function Ve(e,t){t=+!!t,(C(),w)[e.ad+13>>>0]=t}class He{constructor(e){this.td=e,this.ad=e-24}}var Ue=e=>{var t=Re;if(!t)return Sa(0),0;var n=new He(t);(C(),D)[n.ad+16>>>2>>>0]=t;var r=(C(),D)[n.ad+4>>>2>>>0];if(!r)return Sa(0),t;for(var i of e){if(i===0||i===r)break;if(Da(i,r,n.ad+16))return Sa(i),t}return Sa(r),t};function We(){return Ue([])}function Ge(e){return Ue([e>>>0])}function Ke(e,t,n,r){return Ue([e>>>0,t>>>0,n>>>0,r>>>0])}var qe=()=>{var e=Pe.pop();e||de(`no exception to throw`);var t=e.td;throw(C(),w)[e.ad+13>>>0]==0&&(Pe.push(e),Ve(e,!0),Be(e,!1),Fe++),Ea(t),Re=t};function Je(e,t,n){var r=new He(e>>>=0);throw t>>>=0,n>>>=0,(C(),D)[r.ad+16>>>2>>>0]=0,(C(),D)[r.ad+4>>>2>>>0]=t,(C(),D)[r.ad+8>>>2>>>0]=n,Ea(e),Fe++,Re=e}var Ye=()=>Fe;function Xe(e,t,n,r){return i?be(2,1,e,t,n,r):Ze(e,t,n,r)}function Ze(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?Xe(e,t,n,r):(e={ye:n,Xc:e,kd:r,oe:a},i?(e.$c=`spawnThread`,postMessage(e,a),0):ve(e))}function Qe(e){throw Re||=e>>>0,Re}var $e=globalThis.TextDecoder&&new TextDecoder,et=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},tt=(e,t=0,n,r)=>{if(16<(n=et(e,t>>>=0,n,r))-t&&e.buffer&&$e)return $e.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t<n;){var i=e[t++];if(128&i){var a=63&e[t++];if((224&i)==192)r+=String.fromCharCode((31&i)<<6|a);else{var o=63&e[t++];65536>(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},nt=(e,t,n)=>(e>>>=0)?tt((C(),T),e,t,n):``;function rt(e,t,n){return i?be(3,1,e,t,n):0}function it(e,t){if(i)return be(4,1,e,t)}function at(e,t){if(i)return be(5,1,e,t)}function ot(e,t,n){if(i)return be(6,1,e,t,n)}function st(e,t,n){return i?be(7,1,e,t,n):0}function ct(e,t){if(i)return be(8,1,e,t)}function lt(e,t,n){if(i)return be(9,1,e,t,n)}function ut(e,t,n,r){if(i)return be(10,1,e,t,n,r)}function dt(e,t,n,r){if(i)return be(11,1,e,t,n,r)}function ft(e,t,n,r){if(i)return be(12,1,e,t,n,r)}function pt(e){if(i)return be(13,1,e)}function mt(e,t){if(i)return be(14,1,e,t)}function ht(e,t,n){if(i)return be(15,1,e,t,n)}var gt=()=>de(``),_t=e=>{e>>>=0;for(var t=``;;){var n=(C(),T)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},vt={},yt={},bt={},xt=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function St(e,t,n={}){return(function(e,t,n={}){var r=t.name;if(!e)throw new xt(`type "${r}" must have a positive integer typeid pointer`);if(yt.hasOwnProperty(e)){if(n.ve)return;throw new xt(`Cannot register type '${r}' twice`)}yt[e]=t,delete bt[e],vt.hasOwnProperty(e)&&(t=vt[e],delete vt[e],t.forEach(e=>e()))})(e,t,n)}var Ct=(e,t,n)=>{switch(t){case 1:return n?e=>(C(),w)[e>>>0]:e=>(C(),T)[e>>>0];case 2:return n?e=>(C(),te)[e>>>1>>>0]:e=>(C(),ne)[e>>>1>>>0];case 4:return n?e=>(C(),E)[e>>>2>>>0]:e=>(C(),D)[e>>>2>>>0];case 8:return n?e=>(C(),ae)[e>>>3>>>0]:e=>(C(),oe)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function wt(e,t,n,r,i){e>>>=0,n>>>=0,t=_t(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}St(e,{name:t,Wc:a,cd:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),bd:Ct(t,n,!r),dd:null})}function Tt(e,t,n,r){St(e>>>=0,{name:t=_t(t>>>0),Wc:function(e){return!!e},cd:function(e,t){return t?n:r},bd:function(e){return this.Wc((C(),T)[e>>>0])},dd:null})}var Et=[],Dt=[0,1,,1,null,1,!0,1,!1,1];function Ot(e){9<(e>>>=0)&&--Dt[e+1]===0&&(Dt[e]=void 0,Et.push(e))}var kt=e=>{if(!e)throw new xt(`Cannot use deleted val. handle = ${e}`);return Dt[e]},At=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=Et.pop()||Dt.length;return Dt[t]=e,Dt[t+1]=1,t}};function jt(e){return this.Wc((C(),D)[e>>>2>>>0])}var Mt={name:`emscripten::val`,Wc:e=>{var t=kt(e);return Ot(e),t},cd:(e,t)=>At(t),bd:jt,dd:null};function Nt(e){return St(e>>>0,Mt)}var Pt=(e,t)=>{switch(t){case 4:return function(e){return this.Wc((C(),re)[e>>>2>>>0])};case 8:return function(e){return this.Wc((C(),ie)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function Ft(e,t,n){n>>>=0,St(e>>>=0,{name:t=_t(t>>>0),Wc:e=>e,cd:(e,t)=>t,bd:Pt(t,n),dd:null})}function It(e,t,n,r,i){e>>>=0,n>>>=0,t=_t(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<<o>>>o,i=a(i)}St(e,{name:t,Wc:a,cd:(e,t)=>t,bd:Ct(t,n,r!==0),dd:null})}function Lt(e,t,n){function r(e){var t=(C(),D)[e>>>2>>>0];return e=(C(),D)[e+4>>>2>>>0],new i((C(),w).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];St(e>>>=0,{name:n=_t(n>>>0),Wc:r,bd:r},{ve:!0})}var Rt=(e,t,n)=>{var r=(C(),T);if(t>>>=0,0<n){var i=t;n=t+n-1;for(var a=0;a<e.length;++a){var o=e.codePointAt(a);if(127>=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},k=e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function zt(e,t){St(e>>>=0,{name:t=_t(t>>>0),Wc(e){var t=(C(),D)[e>>>2>>>0];return t=nt(e+4,t,!0),Ji(e),t},cd(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new xt(`Cannot pass non-string to std::string`);var r=n?k(t):t.length,i=Yi(4+r+1),a=i+4;return(C(),D)[i>>>2>>>0]=r,n?Rt(t,a,r+1):(C(),T).set(t,a>>>0),e!==null&&e.push(Ji,i),i},bd:jt,dd(e){Ji(e)}})}var Bt=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,Vt=(e,t,n)=>{if(e>>>=1,16<(t=et((C(),ne),e,t/2,n))-e&&Bt)return Bt.decode((C(),ne).slice(e,t));for(n=``;e<t;++e){var r=(C(),ne)[e>>>0];n+=String.fromCharCode(r)}return n},Ht=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i<n;++i){var a=e.charCodeAt(i);(C(),te)[t>>>1>>>0]=a,t+=2}return(C(),te)[t>>>1>>>0]=0,t-r},Ut=e=>2*e.length,Wt=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(C(),D)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},Gt=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i<e.length;++i){var a=e.codePointAt(i);if(65535<a&&i++,(C(),E)[t>>>2>>>0]=a,(t+=4)+4>n)break}return(C(),E)[t>>>2>>>0]=0,t-r},Kt=e=>{for(var t=0,n=0;n<e.length;++n)65535<e.codePointAt(n)&&n++,t+=4;return t};function qt(e,t,n){if(e>>>=0,t>>>=0,n=_t(n>>>=0),t===2)var r=Vt,i=Ht,a=Ut;else r=Wt,i=Gt,a=Kt;St(e,{name:n,Wc:e=>{var n=(C(),D)[e>>>2>>>0];return n=r(e+4,n*t,!0),Ji(e),n},cd:(e,r)=>{if(typeof r!=`string`)throw new xt(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=Yi(4+o+t);return(C(),D)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(Ji,s),s},bd:jt,dd(e){Ji(e)}})}function Jt(e,t){St(e>>>=0,{we:!0,name:t=_t(t>>>0),Wc:()=>{},cd:()=>{}})}function Yt(e){ma(e>>>0,!r,1,!n,131072,!1),ke()}var Xt=e=>{if(!x)try{if(e(),!(0<ye))try{i?qi()&&va(p):Ce(p)}catch(e){e instanceof pe||e==`unwind`||c(0,e)}}catch(e){e instanceof pe||e==`unwind`||c(0,e)}},Zt=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Qt(e){e>>>=0,Zt||(Atomics.waitAsync((C(),E),e>>>2,e).value.then($t),e+=128,Atomics.store((C(),E),e>>>2,1))}var $t=()=>Xt(()=>{var e=qi();e&&(Qt(e),ba())});function en(e,t){(e>>>=0)==t>>>0?setTimeout($t):i?postMessage({gd:e,$c:`checkMailbox`}):(e=De[e])&&e.postMessage({$c:`checkMailbox`})}var tn=[];function nn(e,t,n,r,i){for(t>>>=0,i>>>=0,tn.length=0,n=i>>>3,r=i+r>>>3;n<r;){var a=(C(),ae)[n++>>>0]?(C(),ae)[n++>>>0]:(C(),ie)[n++>>>0];tn.push(a)}return(t?xo[t]:bo[e])(...tn)}var rn=()=>{ye=0};function an(e){e>>>=0,i?postMessage({$c:`cleanupThread`,Le:e}):Oe(De[e])}function on(e){}var sn=e=>{try{e()}catch(e){de(e)}};function cn(e){var t=(...t)=>{fn.push(e);try{return e(...t)}finally{x||(fn.pop(),un&&ln===1&&fn.length===0&&(ln=0,ye+=1,sn(go),typeof Fibers<`u`&&Fibers.We()))}};return hn.set(e,t),t}var ln=0,un=null,dn=0,fn=[],pn=/* @__PURE__ */ new Map,mn=/* @__PURE__ */ new Map,hn=/* @__PURE__ */ new Map,gn=0,_n=null,vn=[],yn=e=>(function(e){if(!x){if(ln===0){var t=!1,n=!1;e((e=0)=>{if(!x&&(dn=e,t=!0,n)){ln=2,sn(()=>_o(un)),typeof MainLoop<`u`&&MainLoop.se&&MainLoop.resume(),e=!1;try{var r=(function(){var e=(C(),E)[un+8>>>2>>>0];return e=mn.get(e),e=hn.get(e),--ye,e()})()}catch(t){r=t,e=!0}var i=!1;if(!un){var a=_n;a&&(_n=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(ln=1,un=(function(){var e=Yi(65548),t=e+12;if((C(),D)[e>>>2>>>0]=t,(C(),D)[e+4>>>2>>>0]=t+65536,t=fn[0],!pn.has(t)){var n=gn++;pn.set(t,n),mn.set(n,t)}return t=pn.get(t),(C(),E)[e+8>>>2>>>0]=t,e})(),typeof MainLoop<`u`&&MainLoop.se&&MainLoop.pause(),sn(()=>ho(un)))}else ln===2?(ln=0,sn(vo),Ji(un),un=null,vn.forEach(Xt)):de(`invalid state: ${ln}`);return dn}})(t=>{e().then(t)});function bn(e){return e>>>=0,yn(async()=>At(await kt(e)))}var xn=[],Sn=e=>{var t=xn.length;return xn.push(e),t},Cn=(e,t)=>{for(var n=Array(e),r=0;r<e;++r){var i=r,a=(C(),D)[t+4*r>>>2>>>0],o=yt[a];if(o===void 0)throw e=`parameter ${r}`,a=Wi(a),t=_t(a),Ji(a),new xt(`${e} has unknown type ${t}`);n[i]=o}return n},wn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((C(),D)[t>>>2>>>0]=At(r)),e},Tn={},En=e=>{var t=Tn[e];return t===void 0?_t(e):t};function Dn(e,t,n){var[r,...i]=Cn(e,t>>>0);t=r.cd.bind(r);var a=i.map(e=>e.bd.bind(e));e--;var o={toValue:kt};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=En,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.we||(o.toReturnWire=t,o.emval_returnValue=wn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) {
97
97
  ${s}
98
98
  }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,Sn(Object.defineProperty(n,"name",{value:s}))}function On(e,t){return t>>>=0,(e=kt(e>>>0))==kt(t)}function kn(e){return(e>>>=0)?(e=En(e),At(globalThis[e])):At(globalThis)}function An(e){return e=En(e>>>0),At(t[e])}function jn(e,t){return t>>>=0,e=kt(e>>>0),t=kt(t),At(e[t])}function Mn(e){9<(e>>>=0)&&(Dt[e+1]+=1)}function Nn(e,t,n,r,i){return xn[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function Pn(e,t,n,r,i){return Nn(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function Fn(){return At([])}function In(e){e=kt(e>>>0);for(var t=Array(e.length),n=0;n<e.length;n++)t[n]=e[n];return At(t)}function Ln(e){return At(En(e>>>0))}function Rn(){return At({})}function zn(e){for(var t=kt(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}Ot(e)}function Bn(e,t,n){t>>>=0,n>>>=0,e=kt(e>>>0),t=kt(t),n=kt(n),e[t]=n}function Vn(e,t){e=Ie(e),t>>>=0,e=/* @__PURE__ */ new Date(1e3*e),(C(),E)[t>>>2>>>0]=e.getUTCSeconds(),(C(),E)[t+4>>>2>>>0]=e.getUTCMinutes(),(C(),E)[t+8>>>2>>>0]=e.getUTCHours(),(C(),E)[t+12>>>2>>>0]=e.getUTCDate(),(C(),E)[t+16>>>2>>>0]=e.getUTCMonth(),(C(),E)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(C(),E)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(C(),E)[t+28>>>2>>>0]=e}var Hn=e=>e%4==0&&(e%100!=0||e%400==0),Un=[0,31,60,91,121,152,182,213,244,274,305,335],Wn=[0,31,59,90,120,151,181,212,243,273,304,334];function Gn(e,t){e=Ie(e),t>>>=0,e=/* @__PURE__ */ new Date(1e3*e),(C(),E)[t>>>2>>>0]=e.getSeconds(),(C(),E)[t+4>>>2>>>0]=e.getMinutes(),(C(),E)[t+8>>>2>>>0]=e.getHours(),(C(),E)[t+12>>>2>>>0]=e.getDate(),(C(),E)[t+16>>>2>>>0]=e.getMonth(),(C(),E)[t+20>>>2>>>0]=e.getFullYear()-1900,(C(),E)[t+24>>>2>>>0]=e.getDay();var n=(Hn(e.getFullYear())?Un:Wn)[e.getMonth()]+e.getDate()-1|0;(C(),E)[t+28>>>2>>>0]=n,(C(),E)[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),(C(),E)[t+32>>>2>>>0]=e}function Kn(e){e>>>=0;var t=new Date((C(),E)[e+20>>>2>>>0]+1900,(C(),E)[e+16>>>2>>>0],(C(),E)[e+12>>>2>>>0],(C(),E)[e+8>>>2>>>0],(C(),E)[e+4>>>2>>>0],(C(),E)[e>>>2>>>0],0),n=(C(),E)[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?(C(),E)[e+32>>>2>>>0]=+(i!=a&&o==r):0<n!=(o==r)&&(i=Math.max(a,i),t.setTime(t.getTime()+6e4*((0<n?o:i)-r))),(C(),E)[e+24>>>2>>>0]=t.getDay(),n=(Hn(t.getFullYear())?Un:Wn)[t.getMonth()]+t.getDate()-1|0,(C(),E)[e+28>>>2>>>0]=n,(C(),E)[e>>>2>>>0]=t.getSeconds(),(C(),E)[e+4>>>2>>>0]=t.getMinutes(),(C(),E)[e+8>>>2>>>0]=t.getHours(),(C(),E)[e+12>>>2>>>0]=t.getDate(),(C(),E)[e+16>>>2>>>0]=t.getMonth(),(C(),E)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function qn(e,t,n,r,a,o,s){return i?be(16,1,e,t,n,r,a,o,s):-52}function Jn(e,t,n,r,a,o){if(i)return be(17,1,e,t,n,r,a,o)}var Yn={},Xn=()=>performance.timeOrigin+performance.now();function Zn(e,t){return i?be(18,1,e,t):(Yn[e]&&(clearTimeout(Yn[e].id),delete Yn[e]),t&&(Yn[e]={id:setTimeout(()=>{delete Yn[e],Xt(()=>ya(e,performance.timeOrigin+performance.now()))},t),Ve:t}),0)}function Qn(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=(/* @__PURE__ */ new Date()).getFullYear(),a=new Date(i,0,1).getTimezoneOffset();i=new Date(i,6,1).getTimezoneOffset();var o=Math.max(a,i);(C(),D)[e>>>2>>>0]=60*o,(C(),E)[t>>>2>>>0]=+(a!=i),e=(t=e=>{var t=Math.abs(e);return`UTC${0<=e?`-`:`+`}${String(Math.floor(t/60)).padStart(2,`0`)}${String(t%60).padStart(2,`0`)}`})(a),t=t(i),i<a?(Rt(e,n,17),Rt(t,r,17)):(Rt(e,r,17),Rt(t,n,17))}var $n=()=>Date.now(),er=1;function tr(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!er)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(C(),ae)[n>>>3>>>0]=BigInt(e),0}var nr=[],rr=(e,t)=>{nr.length=0;for(var n;n=(C(),T)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,nr.push(n==112?(C(),D)[t>>>2>>>0]:n==106?(C(),ae)[t>>>3>>>0]:n==105?(C(),E)[t>>>2>>>0]:(C(),ie)[t>>>3>>>0]),t+=r?8:4}return nr};function ir(e,t,n){return e>>>=0,t=rr(t>>>0,n>>>0),xo[e](...t)}function ar(e,t,n){return e>>>=0,t=rr(t>>>0,n>>>0),xo[e](...t)}var or=()=>{};function sr(e,t){return b(nt(e>>>0,t>>>0))}var cr=()=>{throw ye+=1,`unwind`};function lr(){return 4294901760}var ur=()=>1,dr=()=>navigator.hardwareConcurrency,fr={},pr=e=>{var t=k(e)+1,n=Yi(t);return n&&Rt(e,n,t),n},mr=e=>{var t;return(t=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(e))?+t[1]:(t=/:(\d+):\d+(?:\)|$)/.exec(e))?2147483648|t[1]:0},hr=e=>{for(var t of e)(e=mr(t))&&(fr[e]=t)};function gr(){var e=Error().stack.toString().split(`
99
99
  `);return e[0]==`Error`&&e.shift(),hr(e),fr.ee=mr(e[3]),fr.xe=e,fr.ee}function _r(e){if(!(e=fr[e>>>0]))return 0;var t;if(t=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(e))e=t[1];else if(t=/^\s+at (.*) \(.*\)$/.exec(e))e=t[1];else{if(!(t=/^(.+?)@/.exec(e)))return 0;e=t[1]}return Ji(_r.ne??0),_r.ne=pr(e),_r.ne}function vr(e){e>>>=0;var t=(C(),T).length;if(e<=t||4294901760<e)return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);e:{r=(Math.min(4294901760,65536*Math.ceil(Math.max(e,r)/65536))-Me.buffer.byteLength+65535)/65536|0;try{Me.grow(r),le();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}function yr(e,t,n){if(e>>>=0,t>>>=0,fr.ee==e)var r=fr.xe;else(r=Error().stack.toString().split(`
@@ -101,7 +101,7 @@ $t(Vt),mn(Vt),_n(Vt),Hn(Vt),tr(Vt),cr(Vt),Gr(Vt),(e=>{e.cache=Qr,e.concurrency=$
101
101
  /*webpackIgnore:true*/
102
102
  /*@vite-ignore*/
103
103
  e)).default,Pd=(vd(),pu(md)).default,Fd=async()=>{if(!Dd)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(kd(Dd))return[void 0,Pd()];let e=await Md(Dd);return[e,Pd(e)]},Id=(Cd(),pu(yd)).default,Ld=async(e,t,n,r)=>{let i=Id&&!(e||t);if(i){if(Dd)i=kd(Dd)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,Id];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??Ad(r,t),a=n&&i&&!kd(i,t),o=a?await Md(i):i??jd(r,t);return[a?o:void 0,await Nd(o)]}}}),zd,Bd,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd=U(()=>{Rd(),Bd=!1,Vd=!1,Hd=!1,Ud=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Wd=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Gd=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Kd=async e=>{if(Bd)return Promise.resolve();if(Vd)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Hd)throw Error(`previous call to 'initializeWebAssembly()' failed.`);Vd=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!Gd())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!Wd())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=Ud();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await Ld(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Od();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{Vd=!1,Bd=!0,zd=t,e(),d&&URL.revokeObjectURL(d)},e=>{Vd=!1,Hd=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},qd=()=>{if(Bd&&zd)return zd;throw Error(`WebAssembly is not initialized yet.`)}}),Yd,Xd,W,Zd=U(()=>{Jd(),Yd=(e,t)=>{let n=qd(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},Xd=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)Xd(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},W=e=>{let t=qd(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),Qd,$d=U(()=>{Jd(),Zd(),Qd=e=>{let t=qd(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=Yd(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&W(`Can't create run options.`),e?.extra!==void 0&&Xd(e.extra,``,/* @__PURE__ */ new WeakSet,(e,i)=>{let a=Yd(e,r),o=Yd(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&W(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),ef,tf,nf,rf,af,of,sf,cf=U(()=>{Jd(),Zd(),ef=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},tf=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},nf=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},rf=(e,t,n,r)=>{let i=Yd(t,r),a=Yd(n,r);qd()._OrtAddSessionConfigEntry(e,i,a)!==0&&W(`Can't set a session config entry: ${t} - ${n}.`)},af=(e,t,n,r)=>{let i=Yd(t,r),a=Yd(n,r);e.push([i,a])},of=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,rf(e,`session.disable_quant_qdq`,`1`,n),rf(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&rf(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device){if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&af(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&af(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];af(a,`forceCpuNodeNames`,e.join(`
104
- `),n)}r.validationMode&&af(a,`validationMode`,r.validationMode,n),typeof r.enableMatmulFp32Accumulation==`boolean`&&af(a,`enableMatmulFp32Accumulation`,r.enableMatmulFp32Accumulation?`1`:`0`,n);for(let e of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let t=r[e];if(t){if(t!==`disabled`&&t!==`lazyRelease`&&t!==`simple`&&t!==`bucket`)throw Error(`${e} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${t}`);af(a,e,t,n)}}}let o=qd().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;af(a,`deviceId`,e.toString(),n),af(a,`webgpuInstance`,t.toString(),n),af(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=Yd(r,n),s=a.length,c=0,l=0;if(s>0){c=qd()._malloc(s*qd().PTR_SIZE),n.push(c),l=qd()._malloc(s*qd().PTR_SIZE),n.push(l);for(let e=0;e<s;e++)qd().setValue(c+e*qd().PTR_SIZE,a[e][0],`*`),qd().setValue(l+e*qd().PTR_SIZE,a[e][1],`*`)}await qd()._OrtAppendExecutionProvider(e,o,c,l,s)!==0&&W(`Can't append execution provider: ${r}.`)}},sf=async e=>{let t=qd(),n=0,r=[],i=e||{};nf(i);try{let e=ef(i.graphOptimizationLevel??`all`),a=tf(i.executionMode??`sequential`),o=typeof i.logId==`string`?Yd(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?Yd(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&W(`Can't create session options.`),i.executionProviders&&await of(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);rf(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=Yd(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&W(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&Xd(i.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{rf(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&W(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),lf,uf,df,ff,pf,mf,hf,gf,_f=U(()=>{lf=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},uf=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},df=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},ff=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},pf=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},mf=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,hf=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,gf=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),vf,yf=U(()=>{pd(),vf=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),bf,xf=U(()=>{_f(),bf=(e,t)=>new(ff(t))(e)}),Sf,Cf,wf,Tf,Ef,Df,Of,kf=U(()=>{_f(),Sf=[`V`,`I`,`W`,`E`,`F`],Cf=(e,t)=>{console.log(`[${Sf[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`)},Ef=(e,t)=>{wf=e,Tf=t},Df=(e,t)=>{let n=pf(e);n>=pf(wf)&&Cf(n,typeof t==`function`?t():t)},Of=(...e)=>{Tf&&Df(...e)}}),Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf=U(()=>{_f(),kf(),Af=/* @__PURE__ */ new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),jf=(e,t)=>{if(t===`int32`)return e;let n=Af.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(ff(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},Mf=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Nf=1,Pf=()=>Nf++,Ff=/* @__PURE__ */ new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),If=(e,t)=>{let n=Af.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},Lf=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return If(this.dataType,this.tensorShape)}destroy(){Of(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Mf(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},Rf=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Ff.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Of(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==If(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=jf(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}Of(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Mf(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},zf=class{constructor(e){this.backend=e,this.tensorTrackersById=/* @__PURE__ */ new Map,this.freeTensors=[],this.externalTensors=/* @__PURE__ */ new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Pf();return this.tensorTrackersById.set(e,new Rf(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){Of(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){Of(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=Pf(),o=new Lf({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new Rf(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){Of(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Of(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new Lf({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Bf=(...e)=>new zf(...e)}),Hf={};du(Hf,{WebNNBackend:()=>Gf});var Uf,Wf,Gf,Kf=U(()=>{_f(),Jd(),xf(),Vf(),kf(),Uf=/* @__PURE__ */ new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),Wf=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},Gf=class{constructor(e){this.tensorManager=Bf(this),this.mlContextBySessionId=/* @__PURE__ */ new Map,this.sessionIdsByMLContext=/* @__PURE__ */ new Map,this.mlContextCache=[],this.sessionGraphInputs=/* @__PURE__ */ new Map,this.sessionGraphOutputs=/* @__PURE__ */ new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=/* @__PURE__ */ new Map,this.mlOpSupportLimitsBySessionId=/* @__PURE__ */ new Map,Ef(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Of(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Of(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Of(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>Wf(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=/* @__PURE__ */ new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Of(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=Uf.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){Of(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=Uf.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!qd().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);Of(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return bf(n,t)}}registerMLTensor(e,t,n,r){let i=Uf.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Of(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=Uf.get(lf(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op=U(()=>{fd(),$d(),cf(),_f(),Jd(),Zd(),yf(),qf=(e,t)=>{qd()._OrtInit(e,t)!==0&&W(`Can't initialize onnxruntime.`)},Jf=async e=>{qf(e.wasm.numThreads,pf(e.logLevel))},Yf=async(e,t)=>{qd().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&qd().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(Kf(),pu(Hf)).WebNNBackend(e);qd().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},Xf=/* @__PURE__ */ new Map,Zf=e=>{let t=qd(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&W(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},Qf=(e,t)=>{let n=qd(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&W(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},$f=e=>{let t=qd(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},ep=async(e,t)=>{let n,r,i=qd();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=$f(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await sf(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(vf(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&W(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=Zf(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=Qf(a,t);e===0&&W(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:uf(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=Qf(a,n+e);r===0&&W(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:uf(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&W(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>gf(e))}),Xf.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&W(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&W(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&W(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},tp=e=>{let t=qd(),n=Xf.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&W(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&W(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&W(`Can't release session.`),Xf.delete(e)},np=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=qd(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=df(lf(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=df(lf(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,lf(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,Yd(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=lf(l);m=df(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(lf(l),p,m,g,u.length,gf(f));e===0&&W(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},rp=async(e,t,n,r,i,a)=>{let o=qd(),s=o.PTR_SIZE,c=Xf.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),ee=o.stackAlloc(h*s),w=o.stackAlloc(h*s),T=o.stackAlloc(g*s),te=o.stackAlloc(g*s);try{[_,v]=Qd(a),ed(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await np(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await np(i[t],b,x,e,d[r[t]],h+r[t],p);td(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(ee+e*s,y[e],`*`),o.setValue(w+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(T+e*s,b[e],`*`),o.setValue(te+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);ed(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&W(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&W(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&W(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}td(`wasm bindInputsOutputs`),Xf.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,T,_):await o._OrtRun(l,w,ee,h,te,g,T,_),c!==0&&W(`failed to call OrtRun().`);let C=[],ne=[];ed(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(T+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&W(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&W(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&W(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=uf(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=df(a,g);if(i===void 0||!mf(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(ff(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&W(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(df(a,g)===void 0||!hf(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,ne.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(ff(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&W(`Can't clear bound outputs.`),Xf.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(ne))C[e][2]=t;return td(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},ip=e=>{let t=qd(),n=Xf.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&W(`Can't get an profile file name.`),t._OrtFree(i)},ap=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp=U(()=>{fd(),op(),Jd(),Rd(),sp=()=>!!Eu.wasm.proxy&&typeof document<`u`,lp=!1,up=!1,dp=!1,mp=/* @__PURE__ */ new Map,hp=(e,t)=>{let n=mp.get(e);n?n.push(t):mp.set(e,[t])},gp=()=>{if(lp||!up||dp||!cp)throw Error(`worker not ready`)},_p=e=>{switch(e.data.type){case`init-wasm`:lp=!1,e.data.err?(dp=!0,pp[1](e.data.err)):(up=!0,pp[0]()),fp&&=(URL.revokeObjectURL(fp),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=mp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},vp=async()=>{if(!up){if(lp)throw Error(`multiple calls to 'initWasm()' detected.`);if(dp)throw Error(`previous call to 'initWasm()' failed.`);if(lp=!0,sp())return new Promise((e,t)=>{cp?.terminate(),Fd().then(([n,r])=>{try{cp=r,cp.onerror=e=>t(e),cp.onmessage=_p,pp=[e,t];let i={type:`init-wasm`,in:Eu};!i.in.wasm.wasmPaths&&(n||Td)&&(i.in.wasm.wasmPaths={wasm:new URL(`ort-wasm-simd-threaded.asyncify.wasm`,import.meta.url).href}),cp.postMessage(i),fp=n}catch(e){t(e)}},t)});try{await Kd(Eu.wasm),await Jf(Eu),up=!0}catch(e){throw dp=!0,e}finally{lp=!1}}},yp=async e=>{if(sp())return gp(),new Promise((t,n)=>{hp(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:Eu}};cp.postMessage(r)});await Yf(Eu,e)},bp=async e=>sp()?(gp(),new Promise((t,n)=>{hp(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};cp.postMessage(r,[e.buffer])})):$f(e),xp=async(e,t)=>{if(sp()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return gp(),new Promise((n,r)=>{hp(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),cp.postMessage(i,a)})}return ep(e,t)},Sp=async e=>{if(sp())return gp(),new Promise((t,n)=>{hp(`release`,[t,n]);let r={type:`release`,in:e};cp.postMessage(r)});tp(e)},Cp=async(e,t,n,r,i,a)=>{if(sp()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return gp(),new Promise((i,o)=>{hp(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};cp.postMessage(c,ap(s))})}return rp(e,t,n,r,i,a)},wp=async e=>{if(sp())return gp(),new Promise((t,n)=>{hp(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};cp.postMessage(r)});ip(e)}}),Ep,Dp,Op,kp=U(()=>{fd(),Tp(),_f(),pd(),yf(),Ep=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Dp=e=>{switch(e[3]){case`cpu`:return new Ju(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!mf(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return Ju.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!hf(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return Ju.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Op=class{async fetchModelAndCopyToWasmMemory(e){return bp(await vf(e))}async loadModel(e,t){Qu();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await xp(n,t),$u()}async dispose(){return Sp(this.sessionId)}async run(e,t,n){Qu();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Ep(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Ep(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Cp(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Dp(l[e]);return $u(),u}startProfiling(){}endProfiling(){wp(this.sessionId)}}}),Ap={};du(Ap,{OnnxruntimeWebAssemblyBackend:()=>Mp,initializeFlags:()=>jp,wasmBackend:()=>Np});var jp,Mp,Np,Pp=U(()=>{fd(),Tp(),kp(),jp=()=>{(typeof Eu.wasm.initTimeout!=`number`||Eu.wasm.initTimeout<0)&&(Eu.wasm.initTimeout=0);let e=Eu.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Eu.wasm.simd=!1),typeof Eu.wasm.proxy!=`boolean`&&(Eu.wasm.proxy=!1),typeof Eu.wasm.trace!=`boolean`&&(Eu.wasm.trace=!1),typeof Eu.wasm.numThreads!=`number`||!Number.isInteger(Eu.wasm.numThreads)||Eu.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)Eu.wasm.numThreads=1;else{let e=typeof navigator>`u`?uu(`node:os`).cpus().length:navigator.hardwareConcurrency;Eu.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},Mp=class{async init(e){jp(),await vp(),await yp(e)}async createInferenceSessionHandler(e,t){let n=new Op;return await n.loadModel(e,t),n}},Np=new Mp});fd(),fd(),fd();var Fp=`1.31.0-dev.20260914-8d85527a0`,Ip=dd;{let e=(Pp(),pu(Ap)).wasmBackend;gu(`webgpu`,e,5),gu(`webnn`,e,5),gu(`cpu`,e,10),gu(`wasm`,e,10)}Object.defineProperty(Eu.versions,"web",{value:Fp,enumerable:!0});async function Lp(e){let t=e.split(`/`).pop(),n;try{if(n=await Tl(),n){let t=await n.match(e);if(t)return t}}catch(e){N.warn(`Failed to load ${t} from cache:`,e)}let r=await M.fetch(e);if(!r.ok)throw Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(n)try{await n.put(e,r.clone())}catch(e){N.warn(`Failed to cache ${t}:`,e)}return r}async function Rp(e){let t=await Lp(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return N.warn(`Failed to read WASM binary:`,e),null}}async function zp(e){if(j.IS_SERVICE_WORKER_ENV||j.IS_CHROME_AVAILABLE)return e;let t=await Lp(e);if(!t||typeof t==`string`)return null;try{let e=await t.text();e=e.replaceAll(`globalThis.process?.versions?.node`,`false`);let n=new Blob([e],{type:`text/javascript`});return URL.createObjectURL(n)}catch(e){return N.warn(`Failed to read WASM factory:`,e),null}}var Bp=Object.freeze({auto:null,gpu:null,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:{name:`webnn`,deviceType:`cpu`},"webnn-npu":{name:`webnn`,deviceType:`npu`},"webnn-gpu":{name:`webnn`,deviceType:`gpu`},"webnn-cpu":{name:`webnn`,deviceType:`cpu`}});function Vp(e){return e<=Ni.DEBUG?0:e<=Ni.INFO?2:e<=Ni.WARNING||e<=Ni.ERROR?3:4}var Hp={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},Up=[],Wp,Gp,Kp=/* @__PURE__ */ Symbol.for(`onnxruntime`);if(Kp in globalThis)Gp=globalThis[Kp];else if(j.IS_NODE_ENV){switch(Gp=iu,l.platform){case`win32`:Up.push(`dml`);break;case`linux`:l.arch===`x64`&&Up.push(`cuda`);break;case`darwin`:Up.push(`coreml`)}Up.push(`webgpu`),Up.push(`cpu`),Wp=[`cpu`]}else Gp=au,j.IS_WEBNN_AVAILABLE&&Up.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),j.IS_WEBGPU_AVAILABLE&&Up.push(`webgpu`),Up.push(`wasm`),Wp=[`wasm`];var qp=Gp.InferenceSession;function Jp(e=null){if(!e)return Wp;switch(e){case`auto`:return Up;case`gpu`:return Up.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(Up.includes(e))return[Bp[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${Up.join(`, `)}.`)}var Yp=Promise.resolve(),Xp=null;async function Zp(){if(Xp)return Xp;if(!(M.useWasmCache&&typeof nm?.wasm?.wasmPaths==`object`&&nm?.wasm?.wasmPaths?.wasm&&nm?.wasm?.wasmPaths?.mjs)){if(j.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return Xp=Promise.resolve(),Xp}return Xp=(async()=>{let e=nm.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!yl(e.wasm)?(async()=>{try{let n=await Rp(bl(e.wasm));n&&(nm.wasm.wasmBinary=n,t=!0)}catch(e){N.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!yl(e.mjs)?(async()=>{try{let t=await zp(bl(e.mjs));t&&(nm.wasm.wasmPaths.mjs=t)}catch(e){N.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(nm.wasm.wasmPaths.mjs=e.mjs)})(),Xp}async function Qp(e,t,n){await Zp();let r=Vp(M.logLevel??Ni.WARNING),i=()=>qp.create(e,{logSeverityLevel:r,...t}),a=await(j.IS_WEB_ENV?Yp=Yp.then(i):i());return a.config=n,a}var $p=Promise.resolve();async function em(e,t){let n=()=>e.run(t);return j.IS_WEB_ENV?$p=$p.then(n):n()}function tm(e){return e instanceof Gp.Tensor}var nm=Gp?.env;function rm(){return nm?.wasm?.proxy}if(nm){let e=function(e){nm.logLevel=Hp[Vp(e)]};if(nm.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&nm.versions?.web&&!nm.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${nm.versions.web}/dist/`,t=`.asyncify`;j.IS_SAFARI_BELOW_26&&!j.IS_WEBGPU_AVAILABLE&&(t=``),nm.wasm.wasmPaths={mjs:`${e}ort-wasm-simd-threaded${t}.mjs`,wasm:`${e}ort-wasm-simd-threaded${t}.wasm`}}nm.wasm.proxy=!1}nm.webgpu&&(nm.webgpu.powerPreference=`high-performance`),e(M.logLevel??Ni.WARNING),M.backends.onnx={...nm,setLogLevel:e}}var im=async(e,t,n)=>{let r=await Qp(new Uint8Array(e),t);return(async e=>{let t=rm(),i=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])),a=await em(r,i);return Array.isArray(n)?n.map(e=>new G(a[e])):new G(a[n])})},am=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=im([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,`y`),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||=im([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||=im([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||=im([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,`c`),this._matmul}static get stft(){return this._stft||=im([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,`o`),this._stft}static get rfft(){return this._rfft||=im([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=im([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,[`v`,`i`]),this._top_k}static get slice(){return this._slice||=im([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,`y`),this._slice}},om=Object.freeze({auto:`auto`,gpu:`gpu`,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:`webnn`,"webnn-npu":`webnn-npu`,"webnn-gpu":`webnn-gpu`,"webnn-cpu":`webnn-cpu`}),sm=j.IS_NODE_ENV?`cpu`:`wasm`;function cm(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for "${t}". Using the default device (${sm}).`),sm):sm}var lm=/* @__PURE__ */ (function(){let e;return async function(){if(e===void 0){if(!j.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}}return e}})(),um=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`,q2:`q2`,q2f16:`q2f16`,q1:`q1`,q1f16:`q1f16`}),dm=um.fp32,fm=Object.freeze({[om.wasm]:um.q8}),pm=Object.freeze({[um.fp32]:``,[um.fp16]:`_fp16`,[um.int8]:`_int8`,[um.uint8]:`_uint8`,[um.q8]:`_quantized`,[um.q4]:`_q4`,[um.q2]:`_q2`,[um.q1]:`_q1`,[um.q4f16]:`_q4f16`,[um.q2f16]:`_q2f16`,[um.q1f16]:`_q1f16`,[um.bnb4]:`_bnb4`});function mm(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===um.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==um.auto&&um.hasOwnProperty(e))return e}s=fm[n]??dm}else s=a&&um.hasOwnProperty(a)?a:fm[n]??dm;return o&&i&&i(`dtype not specified for "${t}". Using the default dtype (${s}) for this device (${n}).`),s}var hm=Object.freeze({float32:Float32Array,float16:typeof Float16Array<`u`?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),G=class e{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return this.ort_tensor=tm(e[0])?e[0]:new ue(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r<e;++r)yield this._subarray(r,n,t)}else yield*this.data}_getitem(t){let[n,...r]=this.dims;if(t=Dm(t,n),r.length>0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}return new e(this.type,[this.data[t]],r)}_subarray(t,n,r){let i=t*n,a=(t+1)*n,o=`subarray`in this.data?this.data.subarray(i,a):this.data.slice(i,a);return new e(this.type,o,r)}item(){let e=this.data;if(e.length!==1)throw Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return gm(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]=e(t[n],n,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]-=e;return this}remainder(e){return this.clone().remainder_(e)}remainder_(e){let t=this.data,n=t instanceof BigInt64Array||t instanceof BigUint64Array?BigInt(e):Number(e);if((n===0||n===0n)&&(this.type.includes(`int`)||this.type===`bool`))throw RangeError(`Division by zero`);if(n<0&&(this.type.startsWith(`uint`)||this.type===`bool`))throw RangeError(`Negative divisors are not supported for unsigned or boolean tensors`);for(let e=0;e<t.length;++e){let r=t[e]%n;t[e]=r<0&&n>0||r>0&&n<0?r+n:r}return this}clone(){return new e(this.type,this.data.slice(),this.dims.slice())}slice(...t){let n=[],r=[];for(let e=0;e<this.dims.length;++e){let i=t[e];if(i==null)r.push([0,this.dims[e]]),n.push(this.dims[e]);else if(typeof i==`number`)i=Dm(i,this.dims[e],e),r.push([i,i+1]);else if(Array.isArray(i)&&i.length===2){let[t,a]=i;if(t=t===null?0:Dm(t,this.dims[e],e,!1),a=a===null?this.dims[e]:Dm(a,this.dims[e],e,!1),t>a)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e<i.length;++e)if(r[e][0]!==0||r[e][1]!==this.dims[e]){l=!1;break}if(l){let e=r[0][0]*c[0],t=r[0][1]*c[0];if(ArrayBuffer.isView(o))s.set(o.subarray(e,t));else if(Array.isArray(o)){let n=o.slice(e,t);for(let e=0;e<n.length;++e)s[e]=n[e]}else throw Error(`Unsupported data type for slicing`)}else for(let e=0;e<a;++e){let t=0;for(let n=i.length-1,a=e;n>=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return _m(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=Am(o,this,n,r);if(t!==1)for(let e=0;e<l.length;++e)l[e]=l[e]**(1/t);return new e(c,l,u)}normalize_(e=2,t=1){t=Dm(t,this.dims.length);let n=this.norm(e,t,!0),r=this.data,i=n.data;for(let e=0;e<r.length;++e){let n=0;for(let r=this.dims.length-1,i=e,a=1;r>=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return Nm(this.dims)}squeeze(t=null){return new e(this.type,this.data,Tm(this.dims,t))}squeeze_(e=null){return this.dims=Tm(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,Em(this.dims,t))}unsqueeze_(e){return this.dims=Em(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;e<t.length;++e)if(t[e]===-1){if(n!==-1)throw Error(`Only one dimension can be inferred`);n=e}let r=this.data;if(n!==-1){let e=t.reduce((e,t,r)=>r===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}gt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]>t);return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]<t);return new e(`bool`,n,this.dims)}clamp_(e,t){let n=this.data;for(let r=0;r<n.length;++r)n[r]=Math.min(Math.max(n[r],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return Mm(this,e,t)}min(t=null,n=!1){if(t===null){let t=Kl(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=Am((e,t)=>Math.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=ql(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=Am((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=Kl(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=ql(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.length<this.dims.length)throw Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(e=>e===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=Nm(r),l=Nm(i);for(let e=0;e<a;++e){let t=e,n=0;for(let e=0;e<i.length;++e){let i=Math.floor(t/l[e]);t%=l[e];let a=i%r[e];n+=a*c[e]}s[e]=o[n]}return new e(this.type,s,i)}tile(...e){if(e.length<this.dims.length){let t=this.dims.length-e.length;e=Array(t).fill(1).concat(e)}return this.repeat(...e)}to(t){if(this.type===t)return this;if(!hm.hasOwnProperty(t))throw Error(`Unsupported type: ${t}`);let n,r=[`int64`,`uint64`].includes(this.type),i=[`int64`,`uint64`].includes(t);if(r&&!i)n=Number;else if(!r&&i)n=[`float16`,`float32`,`float64`].includes(this.type)?e=>BigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,nu(this.data),this.dims);return new e(t,hm[t].from(this.data,n),this.dims)}};function gm(e,t){let n=e.length;if(n!==(t.length===0?1:t.reduce((e,t)=>e*t)))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.length<t[e]?i.push(r):n.push([r]),n},[[]]);return r[0]}function _m(e,t){let[n,r]=Ul(e.data,e.dims,t);return new G(e.type,n,r)}function vm(e,[t,n],r=`bilinear`,i=!1){let a=e.dims.at(-3)??1,o=e.dims.at(-2),s=e.dims.at(-1),c=Hl(e.data,[a,o,s],[t,n],r,i);return new G(e.type,c,[a,t,n])}async function ym(e,{size:t=null,mode:n=`bilinear`}={}){if(e.dims.length!==4)throw Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw Error("`interpolate_4d` requires a `size` argument.");let r;if(t.length===2)r=[...e.dims.slice(0,2),...t];else if(t.length===3)r=[e.dims[0],...t];else if(t.length===4)r=t;else throw Error("`size` must be of length 2, 3, or 4.");let i;if(n===`nearest`)i=await am.nearest_interpolate_4d;else if(n===`bilinear`)i=await am.bilinear_interpolate_4d;else if(n===`bicubic`)i=await am.bicubic_interpolate_4d;else throw Error(`Unsupported mode: ${n}`);let a=new G(`int64`,new BigInt64Array(r.map(BigInt)),[r.length]);return await i({x:e,s:a})}async function bm(e,t){return await(await am.matmul)({a:e,b:t})}async function xm(e,t){let n=await am.top_k;return t=t==null?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await n({x:e,k:new G(`int64`,[BigInt(t)],[1])})}var Sm=e=>new G(`int64`,e,[e.length]);async function Cm(e,t,n,r,i){return await(await am.slice)({x:e,s:Sm(t),e:Sm(n),a:Sm(r),t:Sm(i??Array(r.length).fill(1))})}function wm(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;e<o;++e){let t=e*c*s;for(let i=0;i<c;++i){let o=0,u=0,d=e*s,f=t+i;for(let e=0;e<s;++e){let t=Number(r[d+e]);u+=t,o+=n[f+e*c]*t}let p=o/u;a[l++]=p}}return new G(e.type,a,i)}function Tm(e,t){return e=e.slice(),t===null?e=e.filter(e=>e!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function Em(e,t){return t=Dm(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Dm(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Om(e,t=0){t=Dm(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a<e.length;++a){let{data:o,dims:s}=e[a];for(let e=0;e<o.length;++e){let a=0;for(let i=s.length-1,o=e,c=1;i>=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new G(a,i,n)}function km(e,t=0){return Om(e.map(e=>e.unsqueeze(t)),t)}function Am(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=Dm(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t<a.length;++t){let r=0;for(let e=o.length-1,i=t,a=1;e>=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function jm(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new G(e.type,[t],[]);return[new G(e.type,[r],[]),a]}t=Dm(t,a.length);let o=Mm(e,t,r),s=o.data,[c,l,u]=Am((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;e<l.length;++e)l[e]=Math.sqrt(l[e]/(a[t]-n));return[new G(c,l,u),o]}function Mm(e,t=null,n=!1){let r=e.dims,i=e.data;if(t===null){let t=i.reduce((e,t)=>e+t,0);return new G(e.type,[t/i.length],[])}t=Dm(t,r.length);let[a,o,s]=Am((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e<o.length;++e)o[e]/=r[t];return new G(a,o,s)}function Nm(e){let t=Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}function Pm(e,t,n,r){return new G(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function Fm(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return Pm(e,t,n,r)}function Im(e,t){return Fm(e.dims,t)}function Lm(e){return Pm(e,1n,`int64`,BigInt64Array)}function Rm(e){return Lm(e.dims)}function zm(e){return Pm(e,0n,`int64`,BigInt64Array)}function Bm(e){return zm(e.dims)}function Vm(e){let t=e.reduce((e,t)=>e*t,1);return new G(`float32`,Float32Array.from({length:t},()=>il.gauss()),e)}function Hm(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e<a.length;++e){let t=+(a[e]>0),r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new G(r,o,[e.dims[0],e.dims[1]/8])}async function Um(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await Al(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function Wm(e,t){let n=await Um(e);return await Promise.all(n.map(n=>Vl(e,n,!0,t)))}function Gm(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Km=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function qm(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?Hi(e[i],s):Hi(s,e[i])}}function Jm(e,t){for(let n of Object.keys(e))e[n].length=t}function Ym(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t){if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}return t}}return null}function Xm(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var K=class extends Ii{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new ss(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Ym(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ym(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ym(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ym(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ym(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ym(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=/* @__PURE__ */ Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with "name" and "template" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=/* @__PURE__ */ new Map;let n=Xm(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await Wm(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let{text_pair:n=null,add_special_tokens:r=!0,padding:i=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:s=null}=t,c=t.return_tensor??!0,l=Array.isArray(e),u;if(l){if(e.length===0)throw Error(`text array must be non-empty`);if(n!==null){if(!Array.isArray(n))throw Error(`text_pair must also be an array`);if(e.length!==n.length)throw Error(`text and text_pair must have the same length`);u=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:a}))}else u=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:a})]}if(s===null?s=this.model_max_length:o===null&&(i===!0?(N.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),s=this.model_max_length):i===!1&&(N.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),i===!0&&(s=Math.min(ql(u.map(e=>e.input_ids.length))[0],s??1/0)),s=Math.min(s,this.model_max_length??1/0),i||o)for(let e=0;e<u.length;++e)if(u[e].input_ids.length===s)continue;else u[e].input_ids.length>s?o&&Jm(u[e],s):i&&qm(u[e],s,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let d={};if(c){if(!(i&&o)&&u.some(e=>{for(let t of Object.keys(e))if(e[t].length!==u[0][t]?.length)return!0;return!1}))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.`);let e=[u.length,u[0].input_ids.length];for(let t of Object.keys(u[0]))d[t]=new G(`int64`,BigInt64Array.from(u.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(u[0]))d[e]=u.map(t=>t[e]);if(!l)for(let e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof G&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof G&&(e=Gm(e)),!Array.isArray(e)||e.length===0||!zi(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null){if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=n.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`)}}else if(e===null){if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`)}return e}apply_chat_template(e,t={}){let{tools:n=null,documents:r=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:s=!1,truncation:c=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!0,tokenizer_kwargs:f={},...p}=t;if(i=this.get_chat_template({chat_template:i,tools:n}),typeof i!=`string`)throw Error(`chat_template must be a string, but got ${typeof i}`);let m=this._compiled_template_cache.get(i);m===void 0&&(m=new Qc(i),this._compiled_template_cache.set(i,m));let h=/* @__PURE__ */ Object.create(null);for(let e of Km){let t=Ym(this.config,e);t&&(h[e]=t)}let g=m.render({messages:e,add_generation_prompt:a,tools:n,documents:r,...h,...p});if(o){let e=this._call(g,{add_special_tokens:!1,padding:s,truncation:c,max_length:l,return_tensor:u,...f});return d?e:e.input_ids}return g}};function Zm(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);let t=e._tokenizer.post_processor?.config;if(t&&`single`in t){for(let n of t.single)if(`SpecialToken`in n&&e.languageRegex.test(n.SpecialToken.id)){n.SpecialToken.id=e.lang_to_token(i);break}}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var Qm={};ci(Qm,{AlbertTokenizer:()=>$m,AutoTokenizer:()=>Zh,BartTokenizer:()=>eh,BertTokenizer:()=>th,BlenderbotSmallTokenizer:()=>nh,BlenderbotTokenizer:()=>rh,BloomTokenizer:()=>ih,CLIPTokenizer:()=>oh,CamembertTokenizer:()=>ah,CodeGenTokenizer:()=>ch,CodeLlamaTokenizer:()=>sh,CohereAsrTokenizer:()=>uh,CohereTokenizer:()=>lh,ConvBertTokenizer:()=>dh,DebertaTokenizer:()=>ph,DebertaV2Tokenizer:()=>fh,DistilBertTokenizer:()=>mh,ElectraTokenizer:()=>hh,EsmTokenizer:()=>gh,FalconTokenizer:()=>_h,GPT2Tokenizer:()=>bh,GPTNeoXTokenizer:()=>yh,GemmaTokenizer:()=>vh,HerbertTokenizer:()=>xh,LlamaTokenizer:()=>Sh,M2M100Tokenizer:()=>Ch,MBart50Tokenizer:()=>Eh,MBartTokenizer:()=>Th,MPNetTokenizer:()=>kh,MarianTokenizer:()=>wh,MgpstrTokenizer:()=>Dh,MobileBertTokenizer:()=>Oh,NllbTokenizer:()=>Ah,NougatTokenizer:()=>jh,PreTrainedTokenizer:()=>K,Qwen2Tokenizer:()=>Mh,RoFormerTokenizer:()=>Ph,RobertaTokenizer:()=>Nh,SiglipTokenizer:()=>Fh,SpeechT5Tokenizer:()=>Ih,SqueezeBertTokenizer:()=>Lh,T5Tokenizer:()=>Rh,TokenizersBackend:()=>K,VitsTokenizer:()=>Bh,Wav2Vec2CTCTokenizer:()=>Vh,WhisperTokenizer:()=>Jh,XLMRobertaTokenizer:()=>Yh,XLMTokenizer:()=>Xh});var $m=class extends K{return_token_type_ids=!0},eh=class extends K{},th=class extends K{return_token_type_ids=!0},nh=class extends K{},rh=class extends K{},ih=class extends K{},ah=class extends K{},oh=class extends K{},sh=class extends K{},ch=class extends K{},lh=class extends K{},uh=class extends K{},dh=class extends K{return_token_type_ids=!0},fh=class extends K{return_token_type_ids=!0},ph=class extends K{return_token_type_ids=!0},mh=class extends K{},hh=class extends K{return_token_type_ids=!0},gh=class extends K{},_h=class extends K{},vh=class extends K{},yh=class extends K{},bh=class extends K{},xh=class extends K{return_token_type_ids=!0},Sh=class extends K{padding_side=`left`},Ch=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Zm(this,e,t,n)}},wh=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),N.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[t,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||N.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Hi([e],super._encode_text(t))}}},Th=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Zm(this,e,t,n)}},Eh=class extends Th{},Dh=class extends K{},Oh=class extends K{return_token_type_ids=!0},kh=class extends K{},Ah=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Zm(this,e,t,n)}},jh=class extends K{},Mh=class extends K{},Nh=class extends K{},Ph=class extends K{return_token_type_ids=!0},Fh=class extends K{},Ih=class extends K{},Lh=class extends K{return_token_type_ids=!0},Rh=class extends K{},zh=class extends Jo{decode_chain(e){let t=``;for(let n=1;n<e.length;n+=2)t+=e[n];return[t]}},Bh=class extends K{constructor(e,t){super(e,t),this._tokenizer.decoder=new zh({type:`VitsDecoder`})}},Vh=class extends K{},Hh=[[`en`,`english`],[`zh`,`chinese`],[`de`,`german`],[`es`,`spanish`],[`ru`,`russian`],[`ko`,`korean`],[`fr`,`french`],[`ja`,`japanese`],[`pt`,`portuguese`],[`tr`,`turkish`],[`pl`,`polish`],[`ca`,`catalan`],[`nl`,`dutch`],[`ar`,`arabic`],[`sv`,`swedish`],[`it`,`italian`],[`id`,`indonesian`],[`hi`,`hindi`],[`fi`,`finnish`],[`vi`,`vietnamese`],[`he`,`hebrew`],[`uk`,`ukrainian`],[`el`,`greek`],[`ms`,`malay`],[`cs`,`czech`],[`ro`,`romanian`],[`da`,`danish`],[`hu`,`hungarian`],[`ta`,`tamil`],[`no`,`norwegian`],[`th`,`thai`],[`ur`,`urdu`],[`hr`,`croatian`],[`bg`,`bulgarian`],[`lt`,`lithuanian`],[`la`,`latin`],[`mi`,`maori`],[`ml`,`malayalam`],[`cy`,`welsh`],[`sk`,`slovak`],[`te`,`telugu`],[`fa`,`persian`],[`lv`,`latvian`],[`bn`,`bengali`],[`sr`,`serbian`],[`az`,`azerbaijani`],[`sl`,`slovenian`],[`kn`,`kannada`],[`et`,`estonian`],[`mk`,`macedonian`],[`br`,`breton`],[`eu`,`basque`],[`is`,`icelandic`],[`hy`,`armenian`],[`ne`,`nepali`],[`mn`,`mongolian`],[`bs`,`bosnian`],[`kk`,`kazakh`],[`sq`,`albanian`],[`sw`,`swahili`],[`gl`,`galician`],[`mr`,`marathi`],[`pa`,`punjabi`],[`si`,`sinhala`],[`km`,`khmer`],[`sn`,`shona`],[`yo`,`yoruba`],[`so`,`somali`],[`af`,`afrikaans`],[`oc`,`occitan`],[`ka`,`georgian`],[`be`,`belarusian`],[`tg`,`tajik`],[`sd`,`sindhi`],[`gu`,`gujarati`],[`am`,`amharic`],[`yi`,`yiddish`],[`lo`,`lao`],[`uz`,`uzbek`],[`fo`,`faroese`],[`ht`,`haitian creole`],[`ps`,`pashto`],[`tk`,`turkmen`],[`nn`,`nynorsk`],[`mt`,`maltese`],[`sa`,`sanskrit`],[`lb`,`luxembourgish`],[`my`,`myanmar`],[`bo`,`tibetan`],[`tl`,`tagalog`],[`mg`,`malagasy`],[`as`,`assamese`],[`tt`,`tatar`],[`haw`,`hawaiian`],[`ln`,`lingala`],[`ha`,`hausa`],[`ba`,`bashkir`],[`jw`,`javanese`],[`su`,`sundanese`]],Uh=new Map(Hh),Wh=new Map([...Hh.map(([e,t])=>[t,e]),[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]);function Gh(e){e=e.toLowerCase();let t=Wh.get(e);if(t===void 0){let n=e.match(/^<\|([a-z]{2})\|>$/);if(n&&(e=n[1]),Uh.has(e))t=e;else{let t=e.length===2?Uh.keys():Uh.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var Kh=/* @__PURE__ */ RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,`gu`),qh=.1,Jh=class extends K{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r<g)break;v=n}}}let b=[],x=[];for(let n=0;n<e.length;++n){let g=Number(e[n]);if(_.has(g)){let e=this.decode([g]),n=Uh.get(e.slice(2,-2));if(n!==void 0){if(a!==null&&n!==a&&!t){p.push(b);let e=this.findLongestCommonSequence(p)[0],t=this.decode(e);l.text=t,c.push(l),p=[],b=[],l=s()}a=l.language=n}}else if(g>=d&&g<=f){let e=$l((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g<y)h=!1;else if(l.timestamp[0]===null)l.timestamp[0]=e;else if(e!==l.timestamp[0]){l.timestamp[1]=e,p.push(b),o&&m.push(x);let[t,n]=this.findLongestCommonSequence(p,m),r=this.decode(t);if(l.text=r,o&&(l.words=this.collateWordTimestamps(t,n,a),l.words.length>0&&l.timestamp[1]!==null))for(let e of l.words)e.timestamp[1]>l.timestamp[1]&&l.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=l.timestamp[1]);c.push(l),p=[],b=[],m=[],x=[],l=s()}}else if(b.push(g),o){let e=$l(i[n]+u,2),t;if(n+1<i.length){t=$l(i[n+1]+u,2);let a=this.decode([g]);Kh.test(a)&&(t=$l(Math.min(e+r,t),2))}else t=null;x.push([e,t])}}if(`stride`in n){let[e,t,r]=n.stride;u+=e-r}b.length>0?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw Error(`Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=/* @__PURE__ */ Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e<c.length;++e){let r=c[e];t||delete r.timestamp,n||delete r.language}if(o){let e=[];for(let t of c)for(let n of t.words)e.push(n);v={chunks:e}}else v={chunks:c}}return[y,v]}findLongestCommonSequence(e,t=null){let n=e[0],r=n.length,i=[],a=Array.isArray(t)&&t.length>0,o=a?[]:null,s=a?t[0]:null;for(let c=1;c<e.length;++c){let l=e[c],u=0,d=[r,r,0,0],f=l.length;for(let e=1;e<r+f;++e){let i=Math.max(0,r-e),o=Math.min(r,r+f-e),p=n.slice(i,o),m=Math.max(0,e-r),h=Math.min(f,e),g=l.slice(m,h);if(p.length!==g.length)throw Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let _;_=a?p.filter((e,n)=>e===g[n]&&s[i+n][0]-qh<=t[c][m+n][0]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);if(a&&u===0&&r>0){let e=s[r-1][0],n=t[c].findIndex(t=>t[0]>=e);v=n===-1?l.length:n}i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e<r.length;++e){let n=a[e];o.push({text:r[e],timestamp:[t[n.at(0)][0],t[n.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,n=`"'“¡¿([{-`,r=`"'.。,,!!??::”)]}、`){t??=`english`;let i,a,o;return[`chinese`,`japanese`,`thai`,`lao`,`myanmar`].includes(t)?[i,a,o]=this.splitTokensOnUnicode(e):[i,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(i,a,o,n,r)}decode(e,t){let n;return t?.decode_with_timestamps?(e instanceof G&&(e=Gm(e)),n=this.decodeWithTimestamps(e,t)):n=super.decode(e,t),n}decodeWithTimestamps(e,t){let n=t?.time_precision??.02,r=this.all_special_ids.at(-1)+1,i=[[]];for(let t of e)if(t=Number(t),t>=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c<e.length;++c){let l=e[c];a.push(l),o.push(c);let u=this.decode(a,{decode_with_timestamps:!0});(!u.includes(`�`)||t[s+u.indexOf(`�`)]===`�`)&&(n.push(u),r.push(a),i.push(o),a=[],o=[],s+=u.length)}return[n,r,i]}splitTokensOnSpaces(e){let[t,n,r]=this.splitTokensOnUnicode(e),i=[],a=[],o=[];for(let e=0;e<t.length;++e){let s=t[e],c=n[e],l=r[e],u=c[0]>=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=Kh.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=Hi(o[c],o[l]),s[l]=Hi(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;l<a.length;)!a[c].endsWith(` `)&&i.includes(a[l])?(a[c]+=a[l],o[c]=Hi(o[c],o[l]),s[c]=Hi(s[c],s[l]),a[l]=``,o[l]=[],s[l]=[]):c=l,++l;return[a.filter(e=>e),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},Yh=class extends K{},Xh=class extends K{return_token_type_ids=!0;constructor(e,t){super(e,t),N.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Zh=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await Wm(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=Qm[c];return l||=(N.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),K),new l(o,s)}},Qh=`https://github.com/huggingface/transformers.js/issues/new/choose`,$h=`preprocessor_config.json`,eg=`preprocessor_config.json`,tg=`processor_config.json`,ng=`chat_template.jinja`,rg=class extends Ii{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?Vl(e,tg,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?Bl(e,ng,!0,t):null]);return new this(n,r,i)}},ig={};ci(ig,{ChatterboxProcessor:()=>Zg,CohereAsrProcessor:()=>$g,EmbeddingGemma2Processor:()=>p_,EmbeddingGemma2VideoProcessor:()=>u_,Florence2Processor:()=>Gv,Gemma3Processor:()=>Kv,Gemma3nProcessor:()=>qv,Gemma4Processor:()=>l_,Glm46VProcessor:()=>Yv,GraniteSpeechProcessor:()=>Xv,GroundingDinoProcessor:()=>Qv,Idefics3Processor:()=>ny,JinaCLIPProcessor:()=>iy,Lfm2VlProcessor:()=>ay,LlavaProcessor:()=>oy,MgpstrProcessor:()=>cy,MoonshineProcessor:()=>ly,OwlViTProcessor:()=>uy,PaliGemmaProcessor:()=>py,Phi3VProcessor:()=>gy,PixtralProcessor:()=>_y,Processor:()=>rg,PyAnnoteProcessor:()=>vy,Qwen2VLProcessor:()=>Jv,Qwen2_5_VLProcessor:()=>yy,Qwen3VLProcessor:()=>by,Sam2Processor:()=>Sy,Sam2VideoProcessor:()=>Cy,SamProcessor:()=>xy,SmolVLMProcessor:()=>ny,SpeechT5Processor:()=>wy,UltravoxProcessor:()=>Ty,VLChatProcessor:()=>ry,VoxtralProcessor:()=>Ay,VoxtralRealtimeProcessor:()=>Iy,Wav2Vec2Processor:()=>Ly,Wav2Vec2ProcessorWithLM:()=>Ry,WhisperProcessor:()=>zy});var ag=class extends Ii{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await Vl(e,$h,!0,t);return new this(n)}};function og(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var sg={};ci(sg,{ASTFeatureExtractor:()=>Ag,ChatterboxFeatureExtractor:()=>Mg,ClapFeatureExtractor:()=>Ng,CohereAsrFeatureExtractor:()=>Ig,DacFeatureExtractor:()=>Lg,EncodecFeatureExtractor:()=>jg,FeatureExtractor:()=>ag,Gemma3nAudioFeatureExtractor:()=>Rg,Gemma4AudioFeatureExtractor:()=>zg,GraniteSpeechFeatureExtractor:()=>Bg,MoonshineFeatureExtractor:()=>Vg,ParakeetFeatureExtractor:()=>Fg,PyAnnoteFeatureExtractor:()=>Hg,SeamlessM4TFeatureExtractor:()=>Ug,SnacFeatureExtractor:()=>Wg,SpeechT5FeatureExtractor:()=>Gg,VoxtralRealtimeFeatureExtractor:()=>Jg,Wav2Vec2FeatureExtractor:()=>Kg,WeSpeakerFeatureExtractor:()=>qg,WhisperFeatureExtractor:()=>Yg});async function cg(e,t){if(j.IS_BROWSER_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(j.IS_FS_AVAILABLE){let n=t.stream(),r=v.fromWeb(n),i=d.createWriteStream(e);await x(r,i)}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function lg(e,t){if(typeof AudioContext>`u`)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let n=await(await Ml(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&N.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r<i.length;++r)a[r]=e*(t[r]+n[r])/2}else a=i.getChannelData(0);return a}async function ug(e,t){return await lg(e,t)}function dg(e,t){if(e<1)return/* @__PURE__ */ new Float64Array;if(e===1)return new Float64Array([1]);let n=1-t,r=2*Math.PI/(e-1),i=new Float64Array(e);for(let a=0;a<e;++a)i[a]=t-n*Math.cos(a*r);return i}function fg(e){return dg(e,.5)}function pg(e){return dg(e,.54)}var mg={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function hg(e,t=`htk`){let n=mg[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var gg={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function _g(e,t=`htk`){let n=gg[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function vg(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;n<e.length;++n){let i=r[n];for(let r=0;r<t.length;++r)i[r]=t[r]-e[n]}let i=t.length-2,a=Array.from({length:i},()=>Array(e.length));for(let t=0;t<e.length;++t){let e=r[t];for(let r=0;r<i;++r){let i=-e[r]/n[r],o=e[r+2]/n[r+1];a[r][t]=Math.max(0,Math.min(i,o))}}return a}function yg(e,t,n){let r=(t-e)/(n-1);return Float64Array.from({length:n},(t,n)=>e+r*n)}function bg(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or "slaney"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=yg(hg(n,o),hg(r,o),t+2),l=_g(c,o),u;if(s){let t=i/((e-1)*2);u=hg(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=yg(0,Math.floor(i/2),e);let d=vg(u,l);if(a!==null&&a===`slaney`)for(let n=0;n<t;++n){let t=d[n],r=2/(l[n+2]-l[n]);for(let n=0;n<e;++n)t[n]*=r}return d}function xg(e,t,n){let r=new e.constructor(e.length+t+n),i=e.length-1;for(let n=0;n<e.length;++n)r[t+n]=e[n];for(let n=1;n<=t;++n)r[t-n]=e[Wi(n,i)];for(let a=1;a<=n;++a)r[i+t+a]=e[Wi(i-a,i)];return r}function Sg(e,t,n,r,i){if(n<=0)throw Error(`reference must be greater than zero`);if(r<=0)throw Error(`min_value must be greater than zero`);n=Math.max(r,n);let a=Math.log10(n);for(let n=0;n<e.length;++n)e[n]=t*Math.log10(Math.max(r,e[n])-a);if(i!==null){if(i<=0)throw Error(`db_range must be greater than zero`);let t=ql(e)[0]-i;for(let n=0;n<e.length;++n)e[n]=Math.max(e[n],t)}return e}function Cg(e,t=1,n=1e-5,r=null){return Sg(e,20,t,n,r)}function wg(e,t=1,n=1e-10,r=null){return Sg(e,10,t,n,r)}async function Tg(e,t,n,r,{fft_length:i=null,power:a=1,center:o=!0,pad_mode:s=`reflect`,onesided:c=!0,preemphasis:l=null,preemphasis_htk_flavor:u=!0,mel_filters:d=null,mel_floor:f=1e-10,log_mel:p=null,max_log_mel:m=null,reference:h=1,min_value:g=1e-10,db_range:_=null,remove_dc_offset:v=null,min_num_frames:y=null,max_num_frames:b=null,do_pad:x=!0,transpose:S=!1,mel_offset:C=0,mel_floor_mode:ee=`clamp`}={}){let w=t.length;if(i===null&&(i=n),n>i)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(w!==n)throw Error(`Length of the window (${w}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){let t=Math.floor(n/2);switch(s){case`reflect`:e=xg(e,t,t);break;case`constant`:{let n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}case`semicausal`:{let n=new e.constructor(e.length+t);n.set(e,t),e=n;break}default:throw Error(`pad_mode="${s}" not implemented yet.`)}}let T=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&T<y&&(T=y);let te=c?Math.floor(i/2)+1:i,ne=T,E=T;b!==null&&(b>T?x&&(E=b):E=ne=b);let D=new Zl(i),re=new Float64Array(i),ie=new Float64Array(D.outputBufferSize),ae=new Float32Array(te*E);for(let i=0;i<ne;++i){let a=i*r,o=Math.min(e.length-a,n);o!==n&&re.fill(0,0,n);for(let t=0;t<o;++t)re[t]=e[a+t];if(v){let e=0;for(let t=0;t<o;++t)e+=re[t];let t=e/o;for(let e=0;e<o;++e)re[e]-=t}if(l!==null){for(let e=o-1;e>=1;--e)re[e]-=l*re[e-1];re[0]*=1-l}for(let e=0;e<t.length;++e)re[e]*=t[e];D.realTransform(ie,re);for(let e=0;e<te;++e){let t=e<<1;ae[e*E+i]=ie[t]**2+ie[t+1]**2}}if(a!==null&&a!==2){let e=a/2;for(let t=0;t<ae.length;++t)ae[t]**=e}let oe=d.length,se=await bm(new G(`float32`,d.flat(),[oe,te]),new G(`float32`,ae,[te,E]));S&&(se=se.transpose(1,0));let ce=se.data;if(ee===`add`)for(let e=0;e<ce.length;++e)ce[e]=C+ce[e]+f;else for(let e=0;e<ce.length;++e)ce[e]=C+Math.max(f,ce[e]);if(a!==null&&p!==null){let e=Math.min(ce.length,ne*oe);switch(p){case`log`:for(let t=0;t<e;++t)ce[t]=Math.log(ce[t]);break;case`log10`:for(let t=0;t<e;++t)ce[t]=Math.log10(ce[t]);break;case`log10_max_norm`:{for(let t=0;t<e;++t)ce[t]=Math.log10(ce[t]);let t=(m??ql(ce)[0])-8;for(let n=0;n<e;++n)ce[n]=(Math.max(ce[n],t)+4)/4;break}case`dB`:if(a===1)Cg(ce,h,g,_);else if(a===2)wg(ce,h,g,_);else throw Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return se}function Eg(e,t,{periodic:n=!0,frame_length:r=null,center:i=!0}={}){let a=n?e+1:e,o;switch(t){case`boxcar`:o=new Float64Array(a).fill(1);break;case`hann`:case`hann_window`:o=fg(a);break;case`hamming`:o=pg(a);break;case`povey`:o=fg(a).map(e=>e**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);let s=new Float64Array(r),c=i?Math.floor((r-e)/2):0;return s.set(o,c),s}function Dg(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=/* @__PURE__ */ new ArrayBuffer(44),i=new DataView(r);return Og(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),Og(i,8,`WAVE`),Og(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),Og(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice())],{type:`audio/wav`})}function Og(e,t,n){for(let r=0;r<n.length;++r)e.setUint8(t+r,n.charCodeAt(r))}var kg=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return/* @__PURE__ */ new Float32Array;if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((e,t)=>e+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),Dg(e,this.sampling_rate)}async save(e){return cg(e,this.toBlob())}},Ag=class extends ag{constructor(e){super(e);let t=this.config.sampling_rate,n=bg(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Eg(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Tg(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){og(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t<n.length;++t)n[t]=(n[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}},jg=class extends ag{async _call(e){og(e,`EncodecFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=this.config.feature_size;if(e.length%t!==0)throw Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let n=[1,t,e.length/t];return{input_values:new G(`float32`,e,n)}}},Mg=class extends ag{async _call(e){og(e,`ChatterboxFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new G(`float32`,e,t)}}},Ng=class extends ag{constructor(e){super(e),this.mel_filters=bg(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,`htk`),this.mel_filters_slaney=bg(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,`slaney`,`slaney`),this.window=Eg(this.config.fft_window_size,`hann`)}async _get_input_mel(e,t,n,r){let i,a=e.length-t;if(a>0){if(n===`rand_trunc`){let n=Math.floor(il.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${n}" not implemented`)}else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;r<t;r+=e.length)n.set(e.subarray(0,Math.min(e.length,t-r)),r);else if(r===`repeatpad`)for(let t=e.length;t<-a;t+=e.length)n.set(e,t);e=n}if(n===`fusion`)throw Error(`Truncation strategy "${n}" not implemented`);i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return i.unsqueeze_(0)}async _extract_fbank_features(e,t,n=null){return Tg(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:`dB`,max_num_frames:n,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return og(e,`ClapFeatureExtractor`),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},Pg=1e-5,Fg=class extends ag{constructor(e){super(e),this.config.mel_filters??=bg(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,`slaney`,`slaney`);let t=Eg(this.config.win_length,`hann`,{periodic:!1});this.window=new Float64Array(this.config.n_fft);let n=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,n)}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await Tg(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:`log`,mel_floor:-1/0,pad_mode:`constant`,center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){og(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e<n;++e){let t=e*a;for(let e=0;e<a;++e){let n=r[t+e];o[e]+=n,s[e]+=n*n}}let c=n>1?n-1:1;for(let e=0;e<a;++e){let t=o[e]/n,i=(s[e]-n*t*t)/c,l=1/(Math.sqrt(i)+Pg);for(let i=0;i<n;++i){let n=i*a+e;r[n]=(r[n]-t)*l}}let l=new BigInt64Array(i);return l.fill(1n,0,n),{input_features:t.unsqueeze_(0),attention_mask:new G(`int64`,l,[1,i])}}},Ig=class extends Fg{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let n=new tl(e.length);for(let r=0;r<e.length;++r)e[r]+=t*n.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,n=this.config.overlap_chunk_second??5,r=this.config.min_energy_window_samples??1600,i=this.config.sampling_rate,a=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(n*i));if(e.length<=a)return[e];let s=[],c=0,l=e.length;for(;c<l;){if(c+a>=l){s.push(e.slice(c,l));break}let t=Math.max(c,c+a-o),n=Math.min(c+a,l),i;i=n<=t?c+a:this._find_split_point_energy(e,t,n,r),i=Math.max(c+1,Math.min(i,l)),s.push(e.slice(c,i)),c=i}return s}_find_split_point_energy(e,t,n,r){let i=n-t;if(i<=r)return Math.floor((t+n)/2);let a=1/0,o=t,s=i-r;for(let n=0;n<=s;n+=r){let i=0;for(let a=0;a<r;++a){let r=e[t+n+a];i+=r*r}i=Math.sqrt(i/r),i<a&&(a=i,o=t+n)}return o}async _call(e){og(e,`CohereAsrFeatureExtractor`);let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},Lg=class extends jg{},Rg=class extends ag{constructor(e){super(e);let{fft_length:t,feature_size:n,min_frequency:r,max_frequency:i,sampling_rate:a,frame_length:o}=this.config,s=bg(Math.floor(1+t/2),n,r,i,a,null,`htk`,!1);this.mel_filters=s,this.window=Eg(o,`hann`)}async _extract_fbank_features(e,t){return Tg(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:n=!0,padding:r=!0,pad_to_multiple_of:i=128}={}){if(og(e,`Gemma3nAudioFeatureExtractor`),n&&e.length>t&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=Fm([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},zg=class extends Rg{async _extract_fbank_features(e,t){let{frame_length:n,hop_length:r,fft_length:i}=this.config,a=Math.floor(n/2),o=Math.floor((e.length+a-(n+1))/r)+1;return Tg(e,this.window,n,r,{fft_length:i,center:!0,pad_mode:`semicausal`,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,mel_floor_mode:`add`,remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){og(e,`Gemma4AudioFeatureExtractor`);let n=e.length,r=await super._call(e,t),{input_features:i}=r,[,a,o]=i.dims,{frame_length:s,hop_length:c}=this.config,l=Math.floor(s/2),u=s+1,d=new Uint8Array(n+l+(t.pad_to_multiple_of??128));d.fill(1,l,l+n);let f=new Uint8Array(a);for(let e=0;e<a;++e)f[e]=+!!d[e*c+u-1];let p=i.data;for(let e=0;e<a;++e)f[e]||p.fill(0,e*o,(e+1)*o);return r.input_features_mask=new G(`bool`,f,[1,a]),r}},Bg=class extends ag{constructor(e){super(e);let{n_fft:t,win_length:n,n_mels:r,sample_rate:i}=e.melspec_kwargs;this.mel_filters=bg(Math.floor(1+t/2),r,0,i/2,i,null,`htk`);let a=Eg(n,`hann`);this.window=new Float64Array(t);let o=Math.floor((t-n)/2);this.window.set(a,o)}async _call(e){og(e,`GraniteSpeechFeatureExtractor`);let{n_fft:t,hop_length:n,n_mels:r}=this.config.melspec_kwargs,i=Math.floor(e.length/n)+1,a=i-i%2;return{input_features:(await Tg(e,this.window,t,n,{power:2,mel_filters:this.mel_filters,log_mel:`log10_max_norm`,transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*r).unsqueeze_(0)}}},Vg=class extends ag{async _call(e){og(e,`MoonshineFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new G(`float32`,e,t)}}},Hg=class extends ag{async _call(e){og(e,`PyAnnoteFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return{input_values:new G(`float32`,e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let n=t/this.samples_to_frames(t)/this.config.sampling_rate,r=[];for(let t of e.tolist()){let e=[],i=-1;for(let n=0;n<t.length;++n){let[r,a]=ql(Wl(t[n])),[o,s]=[n,n+1];a===i?(e.at(-1).end=s,e.at(-1).score+=r):(i=a,e.push({id:a,start:o,end:s,score:r}))}r.push(e.map(({id:e,start:t,end:r,score:i})=>({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},Ug=class extends ag{constructor(e){super(e);let t=this.config.sampling_rate,n=bg(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Eg(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),Tg(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){og(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r<t;++r){let i=0;for(let a=0;a<e;++a)i+=n[a*t+r];let a=i/e,o=0;for(let i=0;i<e;++i)o+=(n[i*t+r]-a)**2;o/=e-1;let s=Math.sqrt(o+1e-7);for(let i=0;i<e;++i){let e=i*t+r;n[e]=(n[e]-a)/s}}}let o;if(t){let[e,t]=a.dims,r=a.data,s=e%n;if(s>0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new G(a.type,n,[c,t]),i&&(o=new G(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;n<s;n+=l,++r)t[r]=e[n]}else t.fill(1n);d.attention_mask=new G(`int64`,t,[1,e])}return d}},Wg=class extends Lg{},Gg=class extends ag{},Kg=class extends ag{_zero_mean_unit_var_norm(e){let t=e.reduce((e,t)=>e+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){og(e,`Wav2Vec2FeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let n=[1,t.length];return{input_values:new G(`float32`,t,n),attention_mask:new G(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},qg=class extends ag{constructor(e){super(e);let t=this.config.sampling_rate,n=bg(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Eg(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),Tg(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){og(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;t<r;++t){let r=t*i*a,o=t*a;for(let t=0;t<i;++t){let i=r+t*a;for(let t=0;t<a;++t)n[i+t]-=e[o+t]}}}return{input_features:t}}},Jg=class extends ag{constructor(e){super(e),this.config.mel_filters??=bg(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Eg(this.config.n_fft,`hann`)}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:n,hop_length:r,mel_filters:i,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/r:(e.length-n)/r);return await Tg(e,this.window,n,r,{power:2,mel_filters:i,log_mel:`log10_max_norm`,max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return og(e,`VoxtralRealtimeFeatureExtractor`),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},Yg=class extends ag{constructor(e){super(e),this.config.mel_filters??=bg(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Eg(this.config.n_fft,`hann`)}async _extract_fbank_features(e){return await Tg(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:`log10_max_norm`,max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){og(e,`WhisperFeatureExtractor`);let n,r=t??this.config.n_samples;return e.length>r?(e.length>this.config.n_samples&&N.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},Xg=class{static async from_pretrained(e,t={}){let n=await Vl(e,$h,!0,t),r=n.feature_extractor_type,i=sg[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${Qh}.`);return new i(n)}},Zg=class extends rg{static tokenizer_class=Zh;static feature_extractor_class=Xg;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},Qg=/* @__PURE__ */ new Set([`ja`,`zh`]),$g=class extends rg{static tokenizer_class=Zh;static feature_extractor_class=Xg;static uses_processor_config=!0;get_decoder_prompt_ids(e=`en`){let t=[`▁`,`<|startofcontext|>`,`<|startoftranscript|>`,`<|emo:undefined|>`,`<|${e}|>`,`<|${e}|>`,`<|pnc|>`,`<|noitn|>`,`<|notimestamp|>`,`<|nodiarize|>`];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t=`en`){let n=e.filter(e=>e&&e.trim());if(n.length===0)return``;let r=Qg.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},e_,t_,n_;if(j.IS_WEB_ENV)e_=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},n_=self.createImageBitmap,t_=self.ImageData;else if(ai)n_=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new a_(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var r_={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},i_=/* @__PURE__ */ new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),a_=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;if(typeof t==`string`||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!j.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await Ml(e);if(t.status!==200)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(j.IS_WEB_ENV){let t=await n_(e),n=e_(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=ai(await e.arrayBuffer());return await n_(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.permute(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t<this.data.length;t+=this.channels){let r=this.data[t],i=this.data[t+1],a=this.data[t+2];e[n++]=Math.round(.2989*r+.587*i+.114*a)}break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t];break;case 4:for(let t=0,n=0;t<this.data.length;t+=4)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2];break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=255;break;case 3:for(let t=0,n=0;t<this.data.length;t+=3)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2],e[n++]=255;break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw Error(`Expected mask to have 1 channel, but got ${e.channels}`);let t=this.data,n=e.data,r=this.width*this.height;if(this.channels===3){let e=new Uint8ClampedArray(r*4);for(let i=0,a=0,o=0;i<r;++i)e[o++]=t[a++],e[o++]=t[a++],e[o++]=t[a++],e[o++]=n[i];return this._update(e,this.width,this.height,4)}if(this.channels===4){for(let e=0;e<r;++e)t[4*e+3]=n[e];return this}throw Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,n,{resample:r=2}={}){if(this.width===t&&this.height===n)return this;let i=r_[r]??r,a=Bi(t),o=Bi(n);if(a&&o)return this;if(a?t=n/this.height*this.width:o&&(n=t/this.width*this.height),j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),a=e_(t,n).getContext(`2d`);return a.drawImage(i,0,0,t,n),new e(a.getImageData(0,0,t,n).data,t,n,4).convert(r)}{let e=this.toSharp();switch(i){case`box`:case`hamming`:(i===`box`||i===`hamming`)&&(N.warn(`Resampling method ${i} is not yet supported. Using bilinear instead.`),i=`bilinear`);case`nearest`:case`bilinear`:case`bicubic`:e=e.affine([t/this.width,0,0,n/this.height],{interpolator:i});break;case`lanczos`:e=e.resize({width:t,height:n,fit:`fill`,kernel:`lanczos3`});break;default:throw Error(`Resampling method ${i} is not supported.`)}return await n_(e)}}async pad([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.max(r,0),i=Math.max(i,0),t===0&&n===0&&r===0&&i===0)return this;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=this.width+t+n,c=this.height+r+i,l=e_(s,c).getContext(`2d`);return l.drawImage(o,0,0,this.width,this.height,t,r,this.width,this.height),new e(l.getImageData(0,0,s,c).data,s,c,4).convert(a)}{let e=this.toSharp().extend({left:t,right:n,top:r,bottom:i});return await n_(e)}}async crop([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.min(r,this.width-1),i=Math.min(i,this.height-1),t===0&&n===0&&r===this.width-1&&i===this.height-1)return this;let a=r-t+1,o=i-n+1;if(j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),s=e_(a,o).getContext(`2d`);return s.drawImage(i,t,n,a,o,0,0,a,o),new e(s.getImageData(0,0,a,o).data,a,o,4).convert(r)}{let e=this.toSharp().extract({left:t,top:n,width:a,height:o});return await n_(e)}}async center_crop(t,n){if(this.width===t&&this.height===n)return this;let r=(this.width-t)/2,i=(this.height-n)/2;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=e_(t,n).getContext(`2d`),c=0,l=0,u=0,d=0;return r>=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await n_(e)}}async toBlob(e=`image/png`,t=1){if(!j.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new G(`uint8`,new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!==`HWC`){if(e===`CHW`)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`)}return t}toCanvas(){if(!j.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=e_(e.width,e.height),n=new t_(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;e<o;++e){let n=i*e;for(let r=0;r<i;++r)s[r][e]=t[n+r]}return s.map(t=>new e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(j.IS_WEB_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=i_.get(t)??`image/png`;return cg(e,await this.toBlob(n))}if(j.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(j.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return ai(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};a_.read.bind(a_);function o_(e,t,n,r,i){let a=r*n**2,o=Math.sqrt(a/(e*t)),s=i*n,c=Math.floor(o*e/s)*s,l=Math.floor(o*t/s)*s;if(c===0&&l===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${s}.`);let u=Math.floor(r/i**2)*s;return c===0?(c=s,l=Math.min(Math.floor(t/e)*s,u)):l===0&&(l=s,c=Math.min(Math.floor(e/t)*s,u)),[c,l]}function s_(e,t,n,r,i,a,o){let s=Math.floor(t/i),c=Math.floor(n/i),l=s*c,u=i*i*r,d=new Float32Array(a*u),f=0;for(let t=0;t<s;++t)for(let a=0;a<c;++a)for(let o=0;o<i;++o){let s=(t*i+o)*n*r+a*i*r;for(let t=0;t<i;++t){let n=s+t*r;for(let t=0;t<r;++t)d[f++]=e[n+t]}}let p=new BigInt64Array(a*2).fill(-1n),m=0;for(let e=0;e<s;++e)for(let t=0;t<c;++t)p[m++]=BigInt(t),p[m++]=BigInt(e);return{patches:new G(`float32`,d,[a,u]),positions:new G(`int64`,p,[a,2]),num_soft_tokens:Math.floor(l/o**2)}}var c_=class extends Ii{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);let{patch_size:t,pooling_kernel_size:n}=this,r=this.max_soft_tokens*n**2,i=[],a=[],o=[];for(let s of e){if(this.do_convert_rgb&&(s=s.rgb()),this.do_resize){let[e,i]=o_(s.height,s.width,t,r,n);(e!==s.height||i!==s.width)&&(s=await s.resize(i,e,{resample:this.resample}))}let e=Float32Array.from(s.data);if(this.do_rescale)for(let t=0;t<e.length;++t)e[t]*=this.rescale_factor;let{patches:c,positions:l,num_soft_tokens:u}=s_(e,s.height,s.width,s.channels,t,r,n);i.push(c),a.push(l),o.push(u)}return{pixel_values:km(i,0),image_position_ids:km(a,0),num_soft_tokens_per_image:o}}},l_=class extends rg{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:r,boa_token:i,eoa_token:a,image_token:o,boi_token:s,eoi_token:c}=this.tokenizer.config;this.audio_token=r,this.boa_token=i,this.eoa_token=a,this.image_token=o,this.boi_token=s,this.eoi_token=c}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([Vl(e,tg,!0,t),Zh.from_pretrained(e,t),Bl(e,ng,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new c_(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new zg(n.feature_extractor)),new this(n,a,i)}_compute_audio_num_tokens(e,t){let n=Math.round(t*20/1e3),r=Math.round(t*10/1e3),i=Math.floor(n/2),a=Math.floor((e+i-n-1)/r)+1;if(a<=0)return 0;for(let e=0;e<2;++e)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;if(t){i=await this.image_processor(t,r);let n=i.num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>`
104
+ `),n)}r.validationMode&&af(a,`validationMode`,r.validationMode,n),typeof r.enableMatmulFp32Accumulation==`boolean`&&af(a,`enableMatmulFp32Accumulation`,r.enableMatmulFp32Accumulation?`1`:`0`,n);for(let e of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let t=r[e];if(t){if(t!==`disabled`&&t!==`lazyRelease`&&t!==`simple`&&t!==`bucket`)throw Error(`${e} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${t}`);af(a,e,t,n)}}}let o=qd().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;af(a,`deviceId`,e.toString(),n),af(a,`webgpuInstance`,t.toString(),n),af(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=Yd(r,n),s=a.length,c=0,l=0;if(s>0){c=qd()._malloc(s*qd().PTR_SIZE),n.push(c),l=qd()._malloc(s*qd().PTR_SIZE),n.push(l);for(let e=0;e<s;e++)qd().setValue(c+e*qd().PTR_SIZE,a[e][0],`*`),qd().setValue(l+e*qd().PTR_SIZE,a[e][1],`*`)}await qd()._OrtAppendExecutionProvider(e,o,c,l,s)!==0&&W(`Can't append execution provider: ${r}.`)}},sf=async e=>{let t=qd(),n=0,r=[],i=e||{};nf(i);try{let e=ef(i.graphOptimizationLevel??`all`),a=tf(i.executionMode??`sequential`),o=typeof i.logId==`string`?Yd(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?Yd(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&W(`Can't create session options.`),i.executionProviders&&await of(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);rf(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=Yd(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&W(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&Xd(i.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{rf(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&W(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),lf,uf,df,ff,pf,mf,hf,gf,_f=U(()=>{lf=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},uf=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},df=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},ff=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},pf=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},mf=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,hf=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,gf=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),vf,yf=U(()=>{pd(),vf=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),bf,xf=U(()=>{_f(),bf=(e,t)=>new(ff(t))(e)}),Sf,Cf,wf,Tf,Ef,Df,Of,kf=U(()=>{_f(),Sf=[`V`,`I`,`W`,`E`,`F`],Cf=(e,t)=>{console.log(`[${Sf[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`)},Ef=(e,t)=>{wf=e,Tf=t},Df=(e,t)=>{let n=pf(e);n>=pf(wf)&&Cf(n,typeof t==`function`?t():t)},Of=(...e)=>{Tf&&Df(...e)}}),Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf=U(()=>{_f(),kf(),Af=/* @__PURE__ */ new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),jf=(e,t)=>{if(t===`int32`)return e;let n=Af.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(ff(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},Mf=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Nf=1,Pf=()=>Nf++,Ff=/* @__PURE__ */ new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),If=(e,t)=>{let n=Af.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},Lf=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return If(this.dataType,this.tensorShape)}destroy(){Of(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Mf(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},Rf=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Ff.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Of(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==If(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=jf(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}Of(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Mf(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},zf=class{constructor(e){this.backend=e,this.tensorTrackersById=/* @__PURE__ */ new Map,this.freeTensors=[],this.externalTensors=/* @__PURE__ */ new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Pf();return this.tensorTrackersById.set(e,new Rf(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){Of(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){Of(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=Pf(),o=new Lf({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new Rf(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){Of(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Of(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new Lf({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Bf=(...e)=>new zf(...e)}),Hf={};du(Hf,{WebNNBackend:()=>Gf});var Uf,Wf,Gf,Kf=U(()=>{_f(),Jd(),xf(),Vf(),kf(),Uf=/* @__PURE__ */ new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),Wf=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},Gf=class{constructor(e){this.tensorManager=Bf(this),this.mlContextBySessionId=/* @__PURE__ */ new Map,this.sessionIdsByMLContext=/* @__PURE__ */ new Map,this.mlContextCache=[],this.sessionGraphInputs=/* @__PURE__ */ new Map,this.sessionGraphOutputs=/* @__PURE__ */ new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=/* @__PURE__ */ new Map,this.mlOpSupportLimitsBySessionId=/* @__PURE__ */ new Map,Ef(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Of(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Of(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Of(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>Wf(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=/* @__PURE__ */ new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Of(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=Uf.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){Of(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=Uf.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!qd().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);Of(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return bf(n,t)}}registerMLTensor(e,t,n,r){let i=Uf.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Of(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=Uf.get(lf(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op=U(()=>{fd(),$d(),cf(),_f(),Jd(),Zd(),yf(),qf=(e,t)=>{qd()._OrtInit(e,t)!==0&&W(`Can't initialize onnxruntime.`)},Jf=async e=>{qf(e.wasm.numThreads,pf(e.logLevel))},Yf=async(e,t)=>{qd().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&qd().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(Kf(),pu(Hf)).WebNNBackend(e);qd().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},Xf=/* @__PURE__ */ new Map,Zf=e=>{let t=qd(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&W(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},Qf=(e,t)=>{let n=qd(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&W(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},$f=e=>{let t=qd(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},ep=async(e,t)=>{let n,r,i=qd();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=$f(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await sf(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(vf(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&W(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=Zf(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=Qf(a,t);e===0&&W(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:uf(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=Qf(a,n+e);r===0&&W(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:uf(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&W(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>gf(e))}),Xf.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&W(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&W(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&W(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},tp=e=>{let t=qd(),n=Xf.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&W(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&W(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&W(`Can't release session.`),Xf.delete(e)},np=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=qd(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=df(lf(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=df(lf(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,lf(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,Yd(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=lf(l);m=df(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(lf(l),p,m,g,u.length,gf(f));e===0&&W(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},rp=async(e,t,n,r,i,a)=>{let o=qd(),s=o.PTR_SIZE,c=Xf.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),ee=o.stackAlloc(h*s),w=o.stackAlloc(h*s),T=o.stackAlloc(g*s),te=o.stackAlloc(g*s);try{[_,v]=Qd(a),ed(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await np(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await np(i[t],b,x,e,d[r[t]],h+r[t],p);td(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(ee+e*s,y[e],`*`),o.setValue(w+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(T+e*s,b[e],`*`),o.setValue(te+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);ed(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&W(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&W(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&W(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}td(`wasm bindInputsOutputs`),Xf.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,T,_):await o._OrtRun(l,w,ee,h,te,g,T,_),c!==0&&W(`failed to call OrtRun().`);let C=[],ne=[];ed(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(T+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&W(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&W(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&W(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=uf(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=df(a,g);if(i===void 0||!mf(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(ff(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&W(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(df(a,g)===void 0||!hf(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,ne.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(ff(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&W(`Can't clear bound outputs.`),Xf.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(ne))C[e][2]=t;return td(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},ip=e=>{let t=qd(),n=Xf.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&W(`Can't get an profile file name.`),t._OrtFree(i)},ap=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp=U(()=>{fd(),op(),Jd(),Rd(),sp=()=>!!Eu.wasm.proxy&&typeof document<`u`,lp=!1,up=!1,dp=!1,mp=/* @__PURE__ */ new Map,hp=(e,t)=>{let n=mp.get(e);n?n.push(t):mp.set(e,[t])},gp=()=>{if(lp||!up||dp||!cp)throw Error(`worker not ready`)},_p=e=>{switch(e.data.type){case`init-wasm`:lp=!1,e.data.err?(dp=!0,pp[1](e.data.err)):(up=!0,pp[0]()),fp&&=(URL.revokeObjectURL(fp),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=mp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},vp=async()=>{if(!up){if(lp)throw Error(`multiple calls to 'initWasm()' detected.`);if(dp)throw Error(`previous call to 'initWasm()' failed.`);if(lp=!0,sp())return new Promise((e,t)=>{cp?.terminate(),Fd().then(([n,r])=>{try{cp=r,cp.onerror=e=>t(e),cp.onmessage=_p,pp=[e,t];let i={type:`init-wasm`,in:Eu};!i.in.wasm.wasmPaths&&(n||Td)&&(i.in.wasm.wasmPaths={wasm:new URL(`ort-wasm-simd-threaded.asyncify.wasm`,import.meta.url).href}),cp.postMessage(i),fp=n}catch(e){t(e)}},t)});try{await Kd(Eu.wasm),await Jf(Eu),up=!0}catch(e){throw dp=!0,e}finally{lp=!1}}},yp=async e=>{if(sp())return gp(),new Promise((t,n)=>{hp(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:Eu}};cp.postMessage(r)});await Yf(Eu,e)},bp=async e=>sp()?(gp(),new Promise((t,n)=>{hp(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};cp.postMessage(r,[e.buffer])})):$f(e),xp=async(e,t)=>{if(sp()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return gp(),new Promise((n,r)=>{hp(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),cp.postMessage(i,a)})}return ep(e,t)},Sp=async e=>{if(sp())return gp(),new Promise((t,n)=>{hp(`release`,[t,n]);let r={type:`release`,in:e};cp.postMessage(r)});tp(e)},Cp=async(e,t,n,r,i,a)=>{if(sp()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return gp(),new Promise((i,o)=>{hp(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};cp.postMessage(c,ap(s))})}return rp(e,t,n,r,i,a)},wp=async e=>{if(sp())return gp(),new Promise((t,n)=>{hp(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};cp.postMessage(r)});ip(e)}}),Ep,Dp,Op,kp=U(()=>{fd(),Tp(),_f(),pd(),yf(),Ep=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Dp=e=>{switch(e[3]){case`cpu`:return new Ju(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!mf(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return Ju.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!hf(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return Ju.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Op=class{async fetchModelAndCopyToWasmMemory(e){return bp(await vf(e))}async loadModel(e,t){Qu();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await xp(n,t),$u()}async dispose(){return Sp(this.sessionId)}async run(e,t,n){Qu();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Ep(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Ep(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Cp(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Dp(l[e]);return $u(),u}startProfiling(){}endProfiling(){wp(this.sessionId)}}}),Ap={};du(Ap,{OnnxruntimeWebAssemblyBackend:()=>Mp,initializeFlags:()=>jp,wasmBackend:()=>Np});var jp,Mp,Np,Pp=U(()=>{fd(),Tp(),kp(),jp=()=>{(typeof Eu.wasm.initTimeout!=`number`||Eu.wasm.initTimeout<0)&&(Eu.wasm.initTimeout=0);let e=Eu.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Eu.wasm.simd=!1),typeof Eu.wasm.proxy!=`boolean`&&(Eu.wasm.proxy=!1),typeof Eu.wasm.trace!=`boolean`&&(Eu.wasm.trace=!1),typeof Eu.wasm.numThreads!=`number`||!Number.isInteger(Eu.wasm.numThreads)||Eu.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)Eu.wasm.numThreads=1;else{let e=typeof navigator>`u`?uu(`node:os`).cpus().length:navigator.hardwareConcurrency;Eu.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},Mp=class{async init(e){jp(),await vp(),await yp(e)}async createInferenceSessionHandler(e,t){let n=new Op;return await n.loadModel(e,t),n}},Np=new Mp});fd(),fd(),fd();var Fp=`1.31.0-dev.20260914-8d85527a0`,Ip=dd;{let e=(Pp(),pu(Ap)).wasmBackend;gu(`webgpu`,e,5),gu(`webnn`,e,5),gu(`cpu`,e,10),gu(`wasm`,e,10)}Object.defineProperty(Eu.versions,"web",{value:Fp,enumerable:!0});async function Lp(e){let t=e.split(`/`).pop(),n;try{if(n=await Tl(),n){let t=await n.match(e);if(t)return t}}catch(e){N.warn(`Failed to load ${t} from cache:`,e)}let r=await M.fetch(e);if(!r.ok)throw Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(n)try{await n.put(e,r.clone())}catch(e){N.warn(`Failed to cache ${t}:`,e)}return r}async function Rp(e){let t=await Lp(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return N.warn(`Failed to read WASM binary:`,e),null}}async function zp(e){if(j.IS_SERVICE_WORKER_ENV||j.IS_CHROME_AVAILABLE)return e;let t=await Lp(e);if(!t||typeof t==`string`)return null;try{let e=await t.text();e=e.replaceAll(`globalThis.process?.versions?.node`,`false`);let n=new Blob([e],{type:`text/javascript`});return URL.createObjectURL(n)}catch(e){return N.warn(`Failed to read WASM factory:`,e),null}}var Bp=Object.freeze({auto:null,gpu:null,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:{name:`webnn`,deviceType:`cpu`},"webnn-npu":{name:`webnn`,deviceType:`npu`},"webnn-gpu":{name:`webnn`,deviceType:`gpu`},"webnn-cpu":{name:`webnn`,deviceType:`cpu`}});function Vp(e){return e<=Ni.DEBUG?0:e<=Ni.INFO?2:e<=Ni.WARNING||e<=Ni.ERROR?3:4}var Hp={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},Up=[],Wp,Gp,Kp=/* @__PURE__ */ Symbol.for(`onnxruntime`);if(Kp in globalThis)Gp=globalThis[Kp];else if(j.IS_NODE_ENV){switch(Gp=iu,l.platform){case`win32`:Up.push(`dml`);break;case`linux`:l.arch===`x64`&&Up.push(`cuda`);break;case`darwin`:Up.push(`coreml`)}Up.push(`webgpu`),Up.push(`cpu`),Wp=[`cpu`]}else Gp=au,j.IS_WEBNN_AVAILABLE&&Up.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),j.IS_WEBGPU_AVAILABLE&&Up.push(`webgpu`),Up.push(`wasm`),Wp=[`wasm`];var qp=Gp.InferenceSession;function Jp(e=null){if(!e)return Wp;switch(e){case`auto`:return Up;case`gpu`:return Up.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(Up.includes(e))return[Bp[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${Up.join(`, `)}.`)}var Yp=Promise.resolve(),Xp=null;async function Zp(){if(Xp)return Xp;if(!(M.useWasmCache&&typeof nm?.wasm?.wasmPaths==`object`&&nm?.wasm?.wasmPaths?.wasm&&nm?.wasm?.wasmPaths?.mjs)){if(j.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return Xp=Promise.resolve(),Xp}return Xp=(async()=>{let e=nm.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!yl(e.wasm)?(async()=>{try{let n=await Rp(bl(e.wasm));n&&(nm.wasm.wasmBinary=n,t=!0)}catch(e){N.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!yl(e.mjs)?(async()=>{try{let t=await zp(bl(e.mjs));t&&(nm.wasm.wasmPaths.mjs=t)}catch(e){N.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(nm.wasm.wasmPaths.mjs=e.mjs)})(),Xp}async function Qp(e,t,n){await Zp();let r=Vp(M.logLevel??Ni.WARNING),i=()=>qp.create(e,{logSeverityLevel:r,...t}),a=await(j.IS_WEB_ENV?Yp=Yp.then(i):i());return a.config=n,a}var $p=Promise.resolve();async function em(e,t){let n=()=>e.run(t);return j.IS_WEB_ENV?$p=$p.then(n):n()}function tm(e){return e instanceof Gp.Tensor}var nm=Gp?.env;function rm(){return nm?.wasm?.proxy}if(nm){let e=function(e){nm.logLevel=Hp[Vp(e)]};if(nm.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&nm.versions?.web&&!nm.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${nm.versions.web}/dist/`,t=`.asyncify`;j.IS_SAFARI_BELOW_26&&!j.IS_WEBGPU_AVAILABLE&&(t=``),nm.wasm.wasmPaths={mjs:`${e}ort-wasm-simd-threaded${t}.mjs`,wasm:`${e}ort-wasm-simd-threaded${t}.wasm`}}nm.wasm.proxy=!1}nm.webgpu&&(nm.webgpu.powerPreference=`high-performance`),e(M.logLevel??Ni.WARNING),M.backends.onnx={...nm,setLogLevel:e}}var im=async(e,t,n)=>{let r=await Qp(new Uint8Array(e),t);return(async e=>{let t=rm(),i=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])),a=await em(r,i);return Array.isArray(n)?n.map(e=>new G(a[e])):new G(a[n])})},am=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=im([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,`y`),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||=im([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||=im([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||=im([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,`c`),this._matmul}static get stft(){return this._stft||=im([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,`o`),this._stft}static get rfft(){return this._rfft||=im([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=im([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,[`v`,`i`]),this._top_k}static get slice(){return this._slice||=im([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,`y`),this._slice}},om=Object.freeze({auto:`auto`,gpu:`gpu`,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:`webnn`,"webnn-npu":`webnn-npu`,"webnn-gpu":`webnn-gpu`,"webnn-cpu":`webnn-cpu`}),sm=j.IS_NODE_ENV?`cpu`:`wasm`;function cm(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for "${t}". Using the default device (${sm}).`),sm):sm}var lm=/* @__PURE__ */ (function(){let e;return async function(){if(e===void 0){if(!j.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}}return e}})(),um=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`,q2:`q2`,q2f16:`q2f16`,q1:`q1`,q1f16:`q1f16`}),dm=um.fp32,fm=Object.freeze({[om.wasm]:um.q8}),pm=Object.freeze({[um.fp32]:``,[um.fp16]:`_fp16`,[um.int8]:`_int8`,[um.uint8]:`_uint8`,[um.q8]:`_quantized`,[um.q4]:`_q4`,[um.q2]:`_q2`,[um.q1]:`_q1`,[um.q4f16]:`_q4f16`,[um.q2f16]:`_q2f16`,[um.q1f16]:`_q1f16`,[um.bnb4]:`_bnb4`});function mm(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===um.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==um.auto&&um.hasOwnProperty(e))return e}s=fm[n]??dm}else s=a&&um.hasOwnProperty(a)?a:fm[n]??dm;return o&&i&&i(`dtype not specified for "${t}". Using the default dtype (${s}) for this device (${n}).`),s}var hm=Object.freeze({float32:Float32Array,float16:typeof Float16Array<`u`?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),G=class e{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return this.ort_tensor=tm(e[0])?e[0]:new ue(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r<e;++r)yield this._subarray(r,n,t)}else yield*this.data}_getitem(t){let[n,...r]=this.dims;if(t=Dm(t,n),r.length>0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}return new e(this.type,[this.data[t]],r)}_subarray(t,n,r){let i=t*n,a=(t+1)*n,o=`subarray`in this.data?this.data.subarray(i,a):this.data.slice(i,a);return new e(this.type,o,r)}item(){let e=this.data;if(e.length!==1)throw Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return gm(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]=e(t[n],n,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]-=e;return this}remainder(e){return this.clone().remainder_(e)}remainder_(e){let t=this.data,n=t instanceof BigInt64Array||t instanceof BigUint64Array?BigInt(e):Number(e);if((n===0||n===0n)&&(this.type.includes(`int`)||this.type===`bool`))throw RangeError(`Division by zero`);if(n<0&&(this.type.startsWith(`uint`)||this.type===`bool`))throw RangeError(`Negative divisors are not supported for unsigned or boolean tensors`);for(let e=0;e<t.length;++e){let r=t[e]%n;t[e]=r<0&&n>0||r>0&&n<0?r+n:r}return this}clone(){return new e(this.type,this.data.slice(),this.dims.slice())}slice(...t){let n=[],r=[];for(let e=0;e<this.dims.length;++e){let i=t[e];if(i==null)r.push([0,this.dims[e]]),n.push(this.dims[e]);else if(typeof i==`number`)i=Dm(i,this.dims[e],e),r.push([i,i+1]);else if(Array.isArray(i)&&i.length===2){let[t,a]=i;if(t=t===null?0:Dm(t,this.dims[e],e,!1),a=a===null?this.dims[e]:Dm(a,this.dims[e],e,!1),t>a)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e<i.length;++e)if(r[e][0]!==0||r[e][1]!==this.dims[e]){l=!1;break}if(l){let e=r[0][0]*c[0],t=r[0][1]*c[0];if(ArrayBuffer.isView(o))s.set(o.subarray(e,t));else if(Array.isArray(o)){let n=o.slice(e,t);for(let e=0;e<n.length;++e)s[e]=n[e]}else throw Error(`Unsupported data type for slicing`)}else for(let e=0;e<a;++e){let t=0;for(let n=i.length-1,a=e;n>=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return _m(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=Am(o,this,n,r);if(t!==1)for(let e=0;e<l.length;++e)l[e]=l[e]**(1/t);return new e(c,l,u)}normalize_(e=2,t=1){t=Dm(t,this.dims.length);let n=this.norm(e,t,!0),r=this.data,i=n.data;for(let e=0;e<r.length;++e){let n=0;for(let r=this.dims.length-1,i=e,a=1;r>=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return Nm(this.dims)}squeeze(t=null){return new e(this.type,this.data,Tm(this.dims,t))}squeeze_(e=null){return this.dims=Tm(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,Em(this.dims,t))}unsqueeze_(e){return this.dims=Em(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;e<t.length;++e)if(t[e]===-1){if(n!==-1)throw Error(`Only one dimension can be inferred`);n=e}let r=this.data;if(n!==-1){let e=t.reduce((e,t,r)=>r===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}gt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]>t);return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]<t);return new e(`bool`,n,this.dims)}clamp_(e,t){let n=this.data;for(let r=0;r<n.length;++r)n[r]=Math.min(Math.max(n[r],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return Mm(this,e,t)}min(t=null,n=!1){if(t===null){let t=Kl(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=Am((e,t)=>Math.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=ql(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=Am((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=Kl(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=ql(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.length<this.dims.length)throw Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(e=>e===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=Nm(r),l=Nm(i);for(let e=0;e<a;++e){let t=e,n=0;for(let e=0;e<i.length;++e){let i=Math.floor(t/l[e]);t%=l[e];let a=i%r[e];n+=a*c[e]}s[e]=o[n]}return new e(this.type,s,i)}tile(...e){if(e.length<this.dims.length){let t=this.dims.length-e.length;e=Array(t).fill(1).concat(e)}return this.repeat(...e)}to(t){if(this.type===t)return this;if(!hm.hasOwnProperty(t))throw Error(`Unsupported type: ${t}`);let n,r=[`int64`,`uint64`].includes(this.type),i=[`int64`,`uint64`].includes(t);if(r&&!i)n=Number;else if(!r&&i)n=[`float16`,`float32`,`float64`].includes(this.type)?e=>BigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,nu(this.data),this.dims);return new e(t,hm[t].from(this.data,n),this.dims)}};function gm(e,t){let n=e.length;if(n!==(t.length===0?1:t.reduce((e,t)=>e*t)))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.length<t[e]?i.push(r):n.push([r]),n},[[]]);return r[0]}function _m(e,t){let[n,r]=Ul(e.data,e.dims,t);return new G(e.type,n,r)}function vm(e,[t,n],r=`bilinear`,i=!1){let a=e.dims.at(-3)??1,o=e.dims.at(-2),s=e.dims.at(-1),c=Hl(e.data,[a,o,s],[t,n],r,i);return new G(e.type,c,[a,t,n])}async function ym(e,{size:t=null,mode:n=`bilinear`}={}){if(e.dims.length!==4)throw Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw Error("`interpolate_4d` requires a `size` argument.");let r;if(t.length===2)r=[...e.dims.slice(0,2),...t];else if(t.length===3)r=[e.dims[0],...t];else if(t.length===4)r=t;else throw Error("`size` must be of length 2, 3, or 4.");let i;if(n===`nearest`)i=await am.nearest_interpolate_4d;else if(n===`bilinear`)i=await am.bilinear_interpolate_4d;else if(n===`bicubic`)i=await am.bicubic_interpolate_4d;else throw Error(`Unsupported mode: ${n}`);let a=new G(`int64`,new BigInt64Array(r.map(BigInt)),[r.length]);return await i({x:e,s:a})}async function bm(e,t){return await(await am.matmul)({a:e,b:t})}async function xm(e,t){let n=await am.top_k;return t=t==null?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await n({x:e,k:new G(`int64`,[BigInt(t)],[1])})}var Sm=e=>new G(`int64`,e,[e.length]);async function Cm(e,t,n,r,i){return await(await am.slice)({x:e,s:Sm(t),e:Sm(n),a:Sm(r),t:Sm(i??Array(r.length).fill(1))})}function wm(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;e<o;++e){let t=e*c*s;for(let i=0;i<c;++i){let o=0,u=0,d=e*s,f=t+i;for(let e=0;e<s;++e){let t=Number(r[d+e]);u+=t,o+=n[f+e*c]*t}let p=o/u;a[l++]=p}}return new G(e.type,a,i)}function Tm(e,t){return e=e.slice(),t===null?e=e.filter(e=>e!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function Em(e,t){return t=Dm(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Dm(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Om(e,t=0){t=Dm(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a<e.length;++a){let{data:o,dims:s}=e[a];for(let e=0;e<o.length;++e){let a=0;for(let i=s.length-1,o=e,c=1;i>=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new G(a,i,n)}function km(e,t=0){return Om(e.map(e=>e.unsqueeze(t)),t)}function Am(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=Dm(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t<a.length;++t){let r=0;for(let e=o.length-1,i=t,a=1;e>=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function jm(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new G(e.type,[t],[]);return[new G(e.type,[r],[]),a]}t=Dm(t,a.length);let o=Mm(e,t,r),s=o.data,[c,l,u]=Am((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;e<l.length;++e)l[e]=Math.sqrt(l[e]/(a[t]-n));return[new G(c,l,u),o]}function Mm(e,t=null,n=!1){let r=e.dims,i=e.data;if(t===null){let t=i.reduce((e,t)=>e+t,0);return new G(e.type,[t/i.length],[])}t=Dm(t,r.length);let[a,o,s]=Am((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e<o.length;++e)o[e]/=r[t];return new G(a,o,s)}function Nm(e){let t=Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}function Pm(e,t,n,r){return new G(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function Fm(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return Pm(e,t,n,r)}function Im(e,t){return Fm(e.dims,t)}function Lm(e){return Pm(e,1n,`int64`,BigInt64Array)}function Rm(e){return Lm(e.dims)}function zm(e){return Pm(e,0n,`int64`,BigInt64Array)}function Bm(e){return zm(e.dims)}function Vm(e){let t=e.reduce((e,t)=>e*t,1);return new G(`float32`,Float32Array.from({length:t},()=>il.gauss()),e)}function Hm(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e<a.length;++e){let t=+(a[e]>0),r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new G(r,o,[e.dims[0],e.dims[1]/8])}async function Um(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await Al(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function Wm(e,t){let n=await Um(e);return await Promise.all(n.map(n=>Vl(e,n,!0,t)))}function Gm(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Km=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function qm(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?Hi(e[i],s):Hi(s,e[i])}}function Jm(e,t){for(let n of Object.keys(e))e[n].length=t}function Ym(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t){if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}return t}}return null}function Xm(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var K=class extends Ii{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new ss(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Ym(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ym(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ym(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ym(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ym(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ym(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=/* @__PURE__ */ Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with "name" and "template" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=/* @__PURE__ */ new Map;let n=Xm(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await Wm(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let{text_pair:n=null,add_special_tokens:r=!0,padding:i=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:s=null}=t,c=t.return_tensor??!0,l=Array.isArray(e),u;if(l){if(e.length===0)throw Error(`text array must be non-empty`);if(n!==null){if(!Array.isArray(n))throw Error(`text_pair must also be an array`);if(e.length!==n.length)throw Error(`text and text_pair must have the same length`);u=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:a}))}else u=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:a})]}if(s===null?s=this.model_max_length:o===null&&(i===!0?(N.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),s=this.model_max_length):i===!1&&(N.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),i===!0&&(s=Math.min(ql(u.map(e=>e.input_ids.length))[0],s??1/0)),s=Math.min(s,this.model_max_length??1/0),i||o)for(let e=0;e<u.length;++e)if(u[e].input_ids.length===s)continue;else u[e].input_ids.length>s?o&&Jm(u[e],s):i&&qm(u[e],s,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let d={};if(c){if(!(i&&o)&&u.some(e=>{for(let t of Object.keys(e))if(e[t].length!==u[0][t]?.length)return!0;return!1}))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.`);let e=[u.length,u[0].input_ids.length];for(let t of Object.keys(u[0]))d[t]=new G(`int64`,BigInt64Array.from(u.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(u[0]))d[e]=u.map(t=>t[e]);if(!l)for(let e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof G&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof G&&(e=Gm(e)),!Array.isArray(e)||e.length===0||!zi(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null){if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=n.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`)}}else if(e===null){if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`)}return e}apply_chat_template(e,t={}){let{tools:n=null,documents:r=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:s=!1,truncation:c=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!0,tokenizer_kwargs:f={},...p}=t;if(i=this.get_chat_template({chat_template:i,tools:n}),typeof i!=`string`)throw Error(`chat_template must be a string, but got ${typeof i}`);let m=this._compiled_template_cache.get(i);m===void 0&&(m=new Qc(i),this._compiled_template_cache.set(i,m));let h=/* @__PURE__ */ Object.create(null);for(let e of Km){let t=Ym(this.config,e);t&&(h[e]=t)}let g=m.render({messages:e,add_generation_prompt:a,tools:n,documents:r,...h,...p});if(o){let e=this._call(g,{add_special_tokens:!1,padding:s,truncation:c,max_length:l,return_tensor:u,...f});return d?e:e.input_ids}return g}};function Zm(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);let t=e._tokenizer.post_processor?.config;if(t&&`single`in t){for(let n of t.single)if(`SpecialToken`in n&&e.languageRegex.test(n.SpecialToken.id)){n.SpecialToken.id=e.lang_to_token(i);break}}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var Qm={};ci(Qm,{AlbertTokenizer:()=>$m,AutoTokenizer:()=>Zh,BartTokenizer:()=>eh,BertTokenizer:()=>th,BlenderbotSmallTokenizer:()=>nh,BlenderbotTokenizer:()=>rh,BloomTokenizer:()=>ih,CLIPTokenizer:()=>oh,CamembertTokenizer:()=>ah,CodeGenTokenizer:()=>ch,CodeLlamaTokenizer:()=>sh,CohereAsrTokenizer:()=>uh,CohereTokenizer:()=>lh,ConvBertTokenizer:()=>dh,DebertaTokenizer:()=>ph,DebertaV2Tokenizer:()=>fh,DistilBertTokenizer:()=>mh,ElectraTokenizer:()=>hh,EsmTokenizer:()=>gh,FalconTokenizer:()=>_h,GPT2Tokenizer:()=>bh,GPTNeoXTokenizer:()=>yh,GemmaTokenizer:()=>vh,HerbertTokenizer:()=>xh,LlamaTokenizer:()=>Sh,M2M100Tokenizer:()=>Ch,MBart50Tokenizer:()=>Eh,MBartTokenizer:()=>Th,MPNetTokenizer:()=>kh,MarianTokenizer:()=>wh,MgpstrTokenizer:()=>Dh,MobileBertTokenizer:()=>Oh,NllbTokenizer:()=>Ah,NougatTokenizer:()=>jh,PreTrainedTokenizer:()=>K,Qwen2Tokenizer:()=>Mh,RoFormerTokenizer:()=>Ph,RobertaTokenizer:()=>Nh,SiglipTokenizer:()=>Fh,SpeechT5Tokenizer:()=>Ih,SqueezeBertTokenizer:()=>Lh,T5Tokenizer:()=>Rh,TokenizersBackend:()=>K,VitsTokenizer:()=>Bh,Wav2Vec2CTCTokenizer:()=>Vh,WhisperTokenizer:()=>Jh,XLMRobertaTokenizer:()=>Yh,XLMTokenizer:()=>Xh});var $m=class extends K{return_token_type_ids=!0},eh=class extends K{},th=class extends K{return_token_type_ids=!0},nh=class extends K{},rh=class extends K{},ih=class extends K{},ah=class extends K{},oh=class extends K{},sh=class extends K{},ch=class extends K{},lh=class extends K{},uh=class extends K{},dh=class extends K{return_token_type_ids=!0},fh=class extends K{return_token_type_ids=!0},ph=class extends K{return_token_type_ids=!0},mh=class extends K{},hh=class extends K{return_token_type_ids=!0},gh=class extends K{},_h=class extends K{},vh=class extends K{},yh=class extends K{},bh=class extends K{},xh=class extends K{return_token_type_ids=!0},Sh=class extends K{padding_side=`left`},Ch=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Zm(this,e,t,n)}},wh=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),N.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[t,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||N.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Hi([e],super._encode_text(t))}}},Th=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Zm(this,e,t,n)}},Eh=class extends Th{},Dh=class extends K{},Oh=class extends K{return_token_type_ids=!0},kh=class extends K{},Ah=class extends K{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Zm(this,e,t,n)}},jh=class extends K{},Mh=class extends K{},Nh=class extends K{},Ph=class extends K{return_token_type_ids=!0},Fh=class extends K{},Ih=class extends K{},Lh=class extends K{return_token_type_ids=!0},Rh=class extends K{},zh=class extends Jo{decode_chain(e){let t=``;for(let n=1;n<e.length;n+=2)t+=e[n];return[t]}},Bh=class extends K{constructor(e,t){super(e,t),this._tokenizer.decoder=new zh({type:`VitsDecoder`})}},Vh=class extends K{},Hh=[[`en`,`english`],[`zh`,`chinese`],[`de`,`german`],[`es`,`spanish`],[`ru`,`russian`],[`ko`,`korean`],[`fr`,`french`],[`ja`,`japanese`],[`pt`,`portuguese`],[`tr`,`turkish`],[`pl`,`polish`],[`ca`,`catalan`],[`nl`,`dutch`],[`ar`,`arabic`],[`sv`,`swedish`],[`it`,`italian`],[`id`,`indonesian`],[`hi`,`hindi`],[`fi`,`finnish`],[`vi`,`vietnamese`],[`he`,`hebrew`],[`uk`,`ukrainian`],[`el`,`greek`],[`ms`,`malay`],[`cs`,`czech`],[`ro`,`romanian`],[`da`,`danish`],[`hu`,`hungarian`],[`ta`,`tamil`],[`no`,`norwegian`],[`th`,`thai`],[`ur`,`urdu`],[`hr`,`croatian`],[`bg`,`bulgarian`],[`lt`,`lithuanian`],[`la`,`latin`],[`mi`,`maori`],[`ml`,`malayalam`],[`cy`,`welsh`],[`sk`,`slovak`],[`te`,`telugu`],[`fa`,`persian`],[`lv`,`latvian`],[`bn`,`bengali`],[`sr`,`serbian`],[`az`,`azerbaijani`],[`sl`,`slovenian`],[`kn`,`kannada`],[`et`,`estonian`],[`mk`,`macedonian`],[`br`,`breton`],[`eu`,`basque`],[`is`,`icelandic`],[`hy`,`armenian`],[`ne`,`nepali`],[`mn`,`mongolian`],[`bs`,`bosnian`],[`kk`,`kazakh`],[`sq`,`albanian`],[`sw`,`swahili`],[`gl`,`galician`],[`mr`,`marathi`],[`pa`,`punjabi`],[`si`,`sinhala`],[`km`,`khmer`],[`sn`,`shona`],[`yo`,`yoruba`],[`so`,`somali`],[`af`,`afrikaans`],[`oc`,`occitan`],[`ka`,`georgian`],[`be`,`belarusian`],[`tg`,`tajik`],[`sd`,`sindhi`],[`gu`,`gujarati`],[`am`,`amharic`],[`yi`,`yiddish`],[`lo`,`lao`],[`uz`,`uzbek`],[`fo`,`faroese`],[`ht`,`haitian creole`],[`ps`,`pashto`],[`tk`,`turkmen`],[`nn`,`nynorsk`],[`mt`,`maltese`],[`sa`,`sanskrit`],[`lb`,`luxembourgish`],[`my`,`myanmar`],[`bo`,`tibetan`],[`tl`,`tagalog`],[`mg`,`malagasy`],[`as`,`assamese`],[`tt`,`tatar`],[`haw`,`hawaiian`],[`ln`,`lingala`],[`ha`,`hausa`],[`ba`,`bashkir`],[`jw`,`javanese`],[`su`,`sundanese`]],Uh=new Map(Hh),Wh=new Map([...Hh.map(([e,t])=>[t,e]),[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]);function Gh(e){e=e.toLowerCase();let t=Wh.get(e);if(t===void 0){let n=e.match(/^<\|([a-z]{2})\|>$/);if(n&&(e=n[1]),Uh.has(e))t=e;else{let t=e.length===2?Uh.keys():Uh.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var Kh=/* @__PURE__ */ RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,`gu`),qh=.1,Jh=class extends K{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r<g)break;v=n}}}let b=[],x=[];for(let n=0;n<e.length;++n){let g=Number(e[n]);if(_.has(g)){let e=this.decode([g]),n=Uh.get(e.slice(2,-2));if(n!==void 0){if(a!==null&&n!==a&&!t){p.push(b);let e=this.findLongestCommonSequence(p)[0],t=this.decode(e);l.text=t,c.push(l),p=[],b=[],l=s()}a=l.language=n}}else if(g>=d&&g<=f){let e=$l((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g<y)h=!1;else if(l.timestamp[0]===null)l.timestamp[0]=e;else if(e!==l.timestamp[0]){l.timestamp[1]=e,p.push(b),o&&m.push(x);let[t,n]=this.findLongestCommonSequence(p,m),r=this.decode(t);if(l.text=r,o&&(l.words=this.collateWordTimestamps(t,n,a),l.words.length>0&&l.timestamp[1]!==null))for(let e of l.words)e.timestamp[1]>l.timestamp[1]&&l.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=l.timestamp[1]);c.push(l),p=[],b=[],m=[],x=[],l=s()}}else if(b.push(g),o){let e=$l(i[n]+u,2),t;if(n+1<i.length){t=$l(i[n+1]+u,2);let a=this.decode([g]);Kh.test(a)&&(t=$l(Math.min(e+r,t),2))}else t=null;x.push([e,t])}}if(`stride`in n){let[e,t,r]=n.stride;u+=e-r}b.length>0?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw Error(`Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=/* @__PURE__ */ Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e<c.length;++e){let r=c[e];t||delete r.timestamp,n||delete r.language}if(o){let e=[];for(let t of c)for(let n of t.words)e.push(n);v={chunks:e}}else v={chunks:c}}return[y,v]}findLongestCommonSequence(e,t=null){let n=e[0],r=n.length,i=[],a=Array.isArray(t)&&t.length>0,o=a?[]:null,s=a?t[0]:null;for(let c=1;c<e.length;++c){let l=e[c],u=0,d=[r,r,0,0],f=l.length;for(let e=1;e<r+f;++e){let i=Math.max(0,r-e),o=Math.min(r,r+f-e),p=n.slice(i,o),m=Math.max(0,e-r),h=Math.min(f,e),g=l.slice(m,h);if(p.length!==g.length)throw Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let _;_=a?p.filter((e,n)=>e===g[n]&&s[i+n][0]-qh<=t[c][m+n][0]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);if(a&&u===0&&r>0){let e=s[r-1][0],n=t[c].findIndex(t=>t[0]>=e);v=n===-1?l.length:n}i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e<r.length;++e){let n=a[e];o.push({text:r[e],timestamp:[t[n.at(0)][0],t[n.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,n=`"'“¡¿([{-`,r=`"'.。,,!!??::”)]}、`){t??=`english`;let i,a,o;return[`chinese`,`japanese`,`thai`,`lao`,`myanmar`].includes(t)?[i,a,o]=this.splitTokensOnUnicode(e):[i,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(i,a,o,n,r)}decode(e,t){let n;return t?.decode_with_timestamps?(e instanceof G&&(e=Gm(e)),n=this.decodeWithTimestamps(e,t)):n=super.decode(e,t),n}decodeWithTimestamps(e,t){let n=t?.time_precision??.02,r=this.all_special_ids.at(-1)+1,i=[[]];for(let t of e)if(t=Number(t),t>=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c<e.length;++c){let l=e[c];a.push(l),o.push(c);let u=this.decode(a,{decode_with_timestamps:!0});(!u.includes(`�`)||t[s+u.indexOf(`�`)]===`�`)&&(n.push(u),r.push(a),i.push(o),a=[],o=[],s+=u.length)}return[n,r,i]}splitTokensOnSpaces(e){let[t,n,r]=this.splitTokensOnUnicode(e),i=[],a=[],o=[];for(let e=0;e<t.length;++e){let s=t[e],c=n[e],l=r[e],u=c[0]>=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=Kh.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=Hi(o[c],o[l]),s[l]=Hi(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;l<a.length;)!a[c].endsWith(` `)&&i.includes(a[l])?(a[c]+=a[l],o[c]=Hi(o[c],o[l]),s[c]=Hi(s[c],s[l]),a[l]=``,o[l]=[],s[l]=[]):c=l,++l;return[a.filter(e=>e),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},Yh=class extends K{},Xh=class extends K{return_token_type_ids=!0;constructor(e,t){super(e,t),N.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Zh=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await Wm(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=Qm[c];return l||=(N.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),K),new l(o,s)}},Qh=`https://github.com/huggingface/transformers.js/issues/new/choose`,$h=`preprocessor_config.json`,eg=`preprocessor_config.json`,tg=`processor_config.json`,ng=`chat_template.jinja`,rg=class extends Ii{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?Vl(e,tg,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?Bl(e,ng,!0,t):null]);return new this(n,r,i)}},ig={};ci(ig,{ChatterboxProcessor:()=>Zg,CohereAsrProcessor:()=>$g,EmbeddingGemma2Processor:()=>p_,EmbeddingGemma2VideoProcessor:()=>u_,Florence2Processor:()=>Gv,Gemma3Processor:()=>Kv,Gemma3nProcessor:()=>qv,Gemma4Processor:()=>l_,Glm46VProcessor:()=>Yv,GraniteSpeechProcessor:()=>Xv,GroundingDinoProcessor:()=>Qv,Idefics3Processor:()=>ny,JinaCLIPProcessor:()=>iy,Lfm2VlProcessor:()=>ay,LlavaProcessor:()=>oy,MgpstrProcessor:()=>cy,MoonshineProcessor:()=>ly,OwlViTProcessor:()=>uy,PaliGemmaProcessor:()=>py,Phi3VProcessor:()=>gy,PixtralProcessor:()=>_y,Processor:()=>rg,PyAnnoteProcessor:()=>vy,Qwen2VLProcessor:()=>Jv,Qwen2_5_VLProcessor:()=>yy,Qwen3VLProcessor:()=>by,Sam2Processor:()=>Sy,Sam2VideoProcessor:()=>Cy,SamProcessor:()=>xy,SmolVLMProcessor:()=>ny,SpeechT5Processor:()=>wy,UltravoxProcessor:()=>Ty,VLChatProcessor:()=>ry,VoxtralProcessor:()=>Ay,VoxtralRealtimeProcessor:()=>Iy,Wav2Vec2Processor:()=>Ly,Wav2Vec2ProcessorWithLM:()=>Ry,WhisperProcessor:()=>zy});var ag=class extends Ii{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await Vl(e,$h,!0,t);return new this(n)}};function og(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var sg={};ci(sg,{ASTFeatureExtractor:()=>Ag,ChatterboxFeatureExtractor:()=>Mg,ClapFeatureExtractor:()=>Ng,CohereAsrFeatureExtractor:()=>Ig,DacFeatureExtractor:()=>Lg,EncodecFeatureExtractor:()=>jg,FeatureExtractor:()=>ag,Gemma3nAudioFeatureExtractor:()=>Rg,Gemma4AudioFeatureExtractor:()=>zg,GraniteSpeechFeatureExtractor:()=>Bg,MoonshineFeatureExtractor:()=>Vg,ParakeetFeatureExtractor:()=>Fg,PyAnnoteFeatureExtractor:()=>Hg,SeamlessM4TFeatureExtractor:()=>Ug,SnacFeatureExtractor:()=>Wg,SpeechT5FeatureExtractor:()=>Gg,VoxtralRealtimeFeatureExtractor:()=>Jg,Wav2Vec2FeatureExtractor:()=>Kg,WeSpeakerFeatureExtractor:()=>qg,WhisperFeatureExtractor:()=>Yg});async function cg(e,t){if(j.IS_BROWSER_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(j.IS_FS_AVAILABLE){let n=t.stream(),r=v.fromWeb(n),i=f.createWriteStream(e);await x(r,i)}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function lg(e,t){if(typeof AudioContext>`u`)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let n=await(await Ml(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&N.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r<i.length;++r)a[r]=e*(t[r]+n[r])/2}else a=i.getChannelData(0);return a}async function ug(e,t){return await lg(e,t)}function dg(e,t){if(e<1)return/* @__PURE__ */ new Float64Array;if(e===1)return new Float64Array([1]);let n=1-t,r=2*Math.PI/(e-1),i=new Float64Array(e);for(let a=0;a<e;++a)i[a]=t-n*Math.cos(a*r);return i}function fg(e){return dg(e,.5)}function pg(e){return dg(e,.54)}var mg={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function hg(e,t=`htk`){let n=mg[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var gg={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function _g(e,t=`htk`){let n=gg[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function vg(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;n<e.length;++n){let i=r[n];for(let r=0;r<t.length;++r)i[r]=t[r]-e[n]}let i=t.length-2,a=Array.from({length:i},()=>Array(e.length));for(let t=0;t<e.length;++t){let e=r[t];for(let r=0;r<i;++r){let i=-e[r]/n[r],o=e[r+2]/n[r+1];a[r][t]=Math.max(0,Math.min(i,o))}}return a}function yg(e,t,n){let r=(t-e)/(n-1);return Float64Array.from({length:n},(t,n)=>e+r*n)}function bg(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or "slaney"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=yg(hg(n,o),hg(r,o),t+2),l=_g(c,o),u;if(s){let t=i/((e-1)*2);u=hg(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=yg(0,Math.floor(i/2),e);let d=vg(u,l);if(a!==null&&a===`slaney`)for(let n=0;n<t;++n){let t=d[n],r=2/(l[n+2]-l[n]);for(let n=0;n<e;++n)t[n]*=r}return d}function xg(e,t,n){let r=new e.constructor(e.length+t+n),i=e.length-1;for(let n=0;n<e.length;++n)r[t+n]=e[n];for(let n=1;n<=t;++n)r[t-n]=e[Wi(n,i)];for(let a=1;a<=n;++a)r[i+t+a]=e[Wi(i-a,i)];return r}function Sg(e,t,n,r,i){if(n<=0)throw Error(`reference must be greater than zero`);if(r<=0)throw Error(`min_value must be greater than zero`);n=Math.max(r,n);let a=Math.log10(n);for(let n=0;n<e.length;++n)e[n]=t*Math.log10(Math.max(r,e[n])-a);if(i!==null){if(i<=0)throw Error(`db_range must be greater than zero`);let t=ql(e)[0]-i;for(let n=0;n<e.length;++n)e[n]=Math.max(e[n],t)}return e}function Cg(e,t=1,n=1e-5,r=null){return Sg(e,20,t,n,r)}function wg(e,t=1,n=1e-10,r=null){return Sg(e,10,t,n,r)}async function Tg(e,t,n,r,{fft_length:i=null,power:a=1,center:o=!0,pad_mode:s=`reflect`,onesided:c=!0,preemphasis:l=null,preemphasis_htk_flavor:u=!0,mel_filters:d=null,mel_floor:f=1e-10,log_mel:p=null,max_log_mel:m=null,reference:h=1,min_value:g=1e-10,db_range:_=null,remove_dc_offset:v=null,min_num_frames:y=null,max_num_frames:b=null,do_pad:x=!0,transpose:S=!1,mel_offset:C=0,mel_floor_mode:ee=`clamp`}={}){let w=t.length;if(i===null&&(i=n),n>i)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(w!==n)throw Error(`Length of the window (${w}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){let t=Math.floor(n/2);switch(s){case`reflect`:e=xg(e,t,t);break;case`constant`:{let n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}case`semicausal`:{let n=new e.constructor(e.length+t);n.set(e,t),e=n;break}default:throw Error(`pad_mode="${s}" not implemented yet.`)}}let T=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&T<y&&(T=y);let te=c?Math.floor(i/2)+1:i,ne=T,E=T;b!==null&&(b>T?x&&(E=b):E=ne=b);let D=new Zl(i),re=new Float64Array(i),ie=new Float64Array(D.outputBufferSize),ae=new Float32Array(te*E);for(let i=0;i<ne;++i){let a=i*r,o=Math.min(e.length-a,n);o!==n&&re.fill(0,0,n);for(let t=0;t<o;++t)re[t]=e[a+t];if(v){let e=0;for(let t=0;t<o;++t)e+=re[t];let t=e/o;for(let e=0;e<o;++e)re[e]-=t}if(l!==null){for(let e=o-1;e>=1;--e)re[e]-=l*re[e-1];re[0]*=1-l}for(let e=0;e<t.length;++e)re[e]*=t[e];D.realTransform(ie,re);for(let e=0;e<te;++e){let t=e<<1;ae[e*E+i]=ie[t]**2+ie[t+1]**2}}if(a!==null&&a!==2){let e=a/2;for(let t=0;t<ae.length;++t)ae[t]**=e}let oe=d.length,se=await bm(new G(`float32`,d.flat(),[oe,te]),new G(`float32`,ae,[te,E]));S&&(se=se.transpose(1,0));let ce=se.data;if(ee===`add`)for(let e=0;e<ce.length;++e)ce[e]=C+ce[e]+f;else for(let e=0;e<ce.length;++e)ce[e]=C+Math.max(f,ce[e]);if(a!==null&&p!==null){let e=Math.min(ce.length,ne*oe);switch(p){case`log`:for(let t=0;t<e;++t)ce[t]=Math.log(ce[t]);break;case`log10`:for(let t=0;t<e;++t)ce[t]=Math.log10(ce[t]);break;case`log10_max_norm`:{for(let t=0;t<e;++t)ce[t]=Math.log10(ce[t]);let t=(m??ql(ce)[0])-8;for(let n=0;n<e;++n)ce[n]=(Math.max(ce[n],t)+4)/4;break}case`dB`:if(a===1)Cg(ce,h,g,_);else if(a===2)wg(ce,h,g,_);else throw Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return se}function Eg(e,t,{periodic:n=!0,frame_length:r=null,center:i=!0}={}){let a=n?e+1:e,o;switch(t){case`boxcar`:o=new Float64Array(a).fill(1);break;case`hann`:case`hann_window`:o=fg(a);break;case`hamming`:o=pg(a);break;case`povey`:o=fg(a).map(e=>e**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);let s=new Float64Array(r),c=i?Math.floor((r-e)/2):0;return s.set(o,c),s}function Dg(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=/* @__PURE__ */ new ArrayBuffer(44),i=new DataView(r);return Og(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),Og(i,8,`WAVE`),Og(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),Og(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice())],{type:`audio/wav`})}function Og(e,t,n){for(let r=0;r<n.length;++r)e.setUint8(t+r,n.charCodeAt(r))}var kg=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return/* @__PURE__ */ new Float32Array;if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((e,t)=>e+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),Dg(e,this.sampling_rate)}async save(e){return cg(e,this.toBlob())}},Ag=class extends ag{constructor(e){super(e);let t=this.config.sampling_rate,n=bg(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Eg(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Tg(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){og(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t<n.length;++t)n[t]=(n[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}},jg=class extends ag{async _call(e){og(e,`EncodecFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=this.config.feature_size;if(e.length%t!==0)throw Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let n=[1,t,e.length/t];return{input_values:new G(`float32`,e,n)}}},Mg=class extends ag{async _call(e){og(e,`ChatterboxFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new G(`float32`,e,t)}}},Ng=class extends ag{constructor(e){super(e),this.mel_filters=bg(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,`htk`),this.mel_filters_slaney=bg(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,`slaney`,`slaney`),this.window=Eg(this.config.fft_window_size,`hann`)}async _get_input_mel(e,t,n,r){let i,a=e.length-t;if(a>0){if(n===`rand_trunc`){let n=Math.floor(il.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${n}" not implemented`)}else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;r<t;r+=e.length)n.set(e.subarray(0,Math.min(e.length,t-r)),r);else if(r===`repeatpad`)for(let t=e.length;t<-a;t+=e.length)n.set(e,t);e=n}if(n===`fusion`)throw Error(`Truncation strategy "${n}" not implemented`);i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return i.unsqueeze_(0)}async _extract_fbank_features(e,t,n=null){return Tg(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:`dB`,max_num_frames:n,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return og(e,`ClapFeatureExtractor`),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},Pg=1e-5,Fg=class extends ag{constructor(e){super(e),this.config.mel_filters??=bg(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,`slaney`,`slaney`);let t=Eg(this.config.win_length,`hann`,{periodic:!1});this.window=new Float64Array(this.config.n_fft);let n=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,n)}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await Tg(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:`log`,mel_floor:-1/0,pad_mode:`constant`,center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){og(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e<n;++e){let t=e*a;for(let e=0;e<a;++e){let n=r[t+e];o[e]+=n,s[e]+=n*n}}let c=n>1?n-1:1;for(let e=0;e<a;++e){let t=o[e]/n,i=(s[e]-n*t*t)/c,l=1/(Math.sqrt(i)+Pg);for(let i=0;i<n;++i){let n=i*a+e;r[n]=(r[n]-t)*l}}let l=new BigInt64Array(i);return l.fill(1n,0,n),{input_features:t.unsqueeze_(0),attention_mask:new G(`int64`,l,[1,i])}}},Ig=class extends Fg{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let n=new tl(e.length);for(let r=0;r<e.length;++r)e[r]+=t*n.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,n=this.config.overlap_chunk_second??5,r=this.config.min_energy_window_samples??1600,i=this.config.sampling_rate,a=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(n*i));if(e.length<=a)return[e];let s=[],c=0,l=e.length;for(;c<l;){if(c+a>=l){s.push(e.slice(c,l));break}let t=Math.max(c,c+a-o),n=Math.min(c+a,l),i;i=n<=t?c+a:this._find_split_point_energy(e,t,n,r),i=Math.max(c+1,Math.min(i,l)),s.push(e.slice(c,i)),c=i}return s}_find_split_point_energy(e,t,n,r){let i=n-t;if(i<=r)return Math.floor((t+n)/2);let a=1/0,o=t,s=i-r;for(let n=0;n<=s;n+=r){let i=0;for(let a=0;a<r;++a){let r=e[t+n+a];i+=r*r}i=Math.sqrt(i/r),i<a&&(a=i,o=t+n)}return o}async _call(e){og(e,`CohereAsrFeatureExtractor`);let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},Lg=class extends jg{},Rg=class extends ag{constructor(e){super(e);let{fft_length:t,feature_size:n,min_frequency:r,max_frequency:i,sampling_rate:a,frame_length:o}=this.config,s=bg(Math.floor(1+t/2),n,r,i,a,null,`htk`,!1);this.mel_filters=s,this.window=Eg(o,`hann`)}async _extract_fbank_features(e,t){return Tg(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:n=!0,padding:r=!0,pad_to_multiple_of:i=128}={}){if(og(e,`Gemma3nAudioFeatureExtractor`),n&&e.length>t&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=Fm([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},zg=class extends Rg{async _extract_fbank_features(e,t){let{frame_length:n,hop_length:r,fft_length:i}=this.config,a=Math.floor(n/2),o=Math.floor((e.length+a-(n+1))/r)+1;return Tg(e,this.window,n,r,{fft_length:i,center:!0,pad_mode:`semicausal`,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,mel_floor_mode:`add`,remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){og(e,`Gemma4AudioFeatureExtractor`);let n=e.length,r=await super._call(e,t),{input_features:i}=r,[,a,o]=i.dims,{frame_length:s,hop_length:c}=this.config,l=Math.floor(s/2),u=s+1,d=new Uint8Array(n+l+(t.pad_to_multiple_of??128));d.fill(1,l,l+n);let f=new Uint8Array(a);for(let e=0;e<a;++e)f[e]=+!!d[e*c+u-1];let p=i.data;for(let e=0;e<a;++e)f[e]||p.fill(0,e*o,(e+1)*o);return r.input_features_mask=new G(`bool`,f,[1,a]),r}},Bg=class extends ag{constructor(e){super(e);let{n_fft:t,win_length:n,n_mels:r,sample_rate:i}=e.melspec_kwargs;this.mel_filters=bg(Math.floor(1+t/2),r,0,i/2,i,null,`htk`);let a=Eg(n,`hann`);this.window=new Float64Array(t);let o=Math.floor((t-n)/2);this.window.set(a,o)}async _call(e){og(e,`GraniteSpeechFeatureExtractor`);let{n_fft:t,hop_length:n,n_mels:r}=this.config.melspec_kwargs,i=Math.floor(e.length/n)+1,a=i-i%2;return{input_features:(await Tg(e,this.window,t,n,{power:2,mel_filters:this.mel_filters,log_mel:`log10_max_norm`,transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*r).unsqueeze_(0)}}},Vg=class extends ag{async _call(e){og(e,`MoonshineFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new G(`float32`,e,t)}}},Hg=class extends ag{async _call(e){og(e,`PyAnnoteFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return{input_values:new G(`float32`,e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let n=t/this.samples_to_frames(t)/this.config.sampling_rate,r=[];for(let t of e.tolist()){let e=[],i=-1;for(let n=0;n<t.length;++n){let[r,a]=ql(Wl(t[n])),[o,s]=[n,n+1];a===i?(e.at(-1).end=s,e.at(-1).score+=r):(i=a,e.push({id:a,start:o,end:s,score:r}))}r.push(e.map(({id:e,start:t,end:r,score:i})=>({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},Ug=class extends ag{constructor(e){super(e);let t=this.config.sampling_rate,n=bg(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Eg(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),Tg(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){og(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r<t;++r){let i=0;for(let a=0;a<e;++a)i+=n[a*t+r];let a=i/e,o=0;for(let i=0;i<e;++i)o+=(n[i*t+r]-a)**2;o/=e-1;let s=Math.sqrt(o+1e-7);for(let i=0;i<e;++i){let e=i*t+r;n[e]=(n[e]-a)/s}}}let o;if(t){let[e,t]=a.dims,r=a.data,s=e%n;if(s>0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new G(a.type,n,[c,t]),i&&(o=new G(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;n<s;n+=l,++r)t[r]=e[n]}else t.fill(1n);d.attention_mask=new G(`int64`,t,[1,e])}return d}},Wg=class extends Lg{},Gg=class extends ag{},Kg=class extends ag{_zero_mean_unit_var_norm(e){let t=e.reduce((e,t)=>e+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){og(e,`Wav2Vec2FeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let n=[1,t.length];return{input_values:new G(`float32`,t,n),attention_mask:new G(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},qg=class extends ag{constructor(e){super(e);let t=this.config.sampling_rate,n=bg(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Eg(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),Tg(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){og(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;t<r;++t){let r=t*i*a,o=t*a;for(let t=0;t<i;++t){let i=r+t*a;for(let t=0;t<a;++t)n[i+t]-=e[o+t]}}}return{input_features:t}}},Jg=class extends ag{constructor(e){super(e),this.config.mel_filters??=bg(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Eg(this.config.n_fft,`hann`)}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:n,hop_length:r,mel_filters:i,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/r:(e.length-n)/r);return await Tg(e,this.window,n,r,{power:2,mel_filters:i,log_mel:`log10_max_norm`,max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return og(e,`VoxtralRealtimeFeatureExtractor`),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},Yg=class extends ag{constructor(e){super(e),this.config.mel_filters??=bg(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Eg(this.config.n_fft,`hann`)}async _extract_fbank_features(e){return await Tg(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:`log10_max_norm`,max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){og(e,`WhisperFeatureExtractor`);let n,r=t??this.config.n_samples;return e.length>r?(e.length>this.config.n_samples&&N.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},Xg=class{static async from_pretrained(e,t={}){let n=await Vl(e,$h,!0,t),r=n.feature_extractor_type,i=sg[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${Qh}.`);return new i(n)}},Zg=class extends rg{static tokenizer_class=Zh;static feature_extractor_class=Xg;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},Qg=/* @__PURE__ */ new Set([`ja`,`zh`]),$g=class extends rg{static tokenizer_class=Zh;static feature_extractor_class=Xg;static uses_processor_config=!0;get_decoder_prompt_ids(e=`en`){let t=[`▁`,`<|startofcontext|>`,`<|startoftranscript|>`,`<|emo:undefined|>`,`<|${e}|>`,`<|${e}|>`,`<|pnc|>`,`<|noitn|>`,`<|notimestamp|>`,`<|nodiarize|>`];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t=`en`){let n=e.filter(e=>e&&e.trim());if(n.length===0)return``;let r=Qg.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},e_,t_,n_;if(j.IS_WEB_ENV)e_=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},n_=self.createImageBitmap,t_=self.ImageData;else if(ai)n_=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new a_(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var r_={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},i_=/* @__PURE__ */ new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),a_=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;if(typeof t==`string`||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!j.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await Ml(e);if(t.status!==200)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(j.IS_WEB_ENV){let t=await n_(e),n=e_(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=ai(await e.arrayBuffer());return await n_(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.permute(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t<this.data.length;t+=this.channels){let r=this.data[t],i=this.data[t+1],a=this.data[t+2];e[n++]=Math.round(.2989*r+.587*i+.114*a)}break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t];break;case 4:for(let t=0,n=0;t<this.data.length;t+=4)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2];break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=255;break;case 3:for(let t=0,n=0;t<this.data.length;t+=3)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2],e[n++]=255;break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw Error(`Expected mask to have 1 channel, but got ${e.channels}`);let t=this.data,n=e.data,r=this.width*this.height;if(this.channels===3){let e=new Uint8ClampedArray(r*4);for(let i=0,a=0,o=0;i<r;++i)e[o++]=t[a++],e[o++]=t[a++],e[o++]=t[a++],e[o++]=n[i];return this._update(e,this.width,this.height,4)}if(this.channels===4){for(let e=0;e<r;++e)t[4*e+3]=n[e];return this}throw Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,n,{resample:r=2}={}){if(this.width===t&&this.height===n)return this;let i=r_[r]??r,a=Bi(t),o=Bi(n);if(a&&o)return this;if(a?t=n/this.height*this.width:o&&(n=t/this.width*this.height),j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),a=e_(t,n).getContext(`2d`);return a.drawImage(i,0,0,t,n),new e(a.getImageData(0,0,t,n).data,t,n,4).convert(r)}{let e=this.toSharp();switch(i){case`box`:case`hamming`:(i===`box`||i===`hamming`)&&(N.warn(`Resampling method ${i} is not yet supported. Using bilinear instead.`),i=`bilinear`);case`nearest`:case`bilinear`:case`bicubic`:e=e.affine([t/this.width,0,0,n/this.height],{interpolator:i});break;case`lanczos`:e=e.resize({width:t,height:n,fit:`fill`,kernel:`lanczos3`});break;default:throw Error(`Resampling method ${i} is not supported.`)}return await n_(e)}}async pad([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.max(r,0),i=Math.max(i,0),t===0&&n===0&&r===0&&i===0)return this;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=this.width+t+n,c=this.height+r+i,l=e_(s,c).getContext(`2d`);return l.drawImage(o,0,0,this.width,this.height,t,r,this.width,this.height),new e(l.getImageData(0,0,s,c).data,s,c,4).convert(a)}{let e=this.toSharp().extend({left:t,right:n,top:r,bottom:i});return await n_(e)}}async crop([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.min(r,this.width-1),i=Math.min(i,this.height-1),t===0&&n===0&&r===this.width-1&&i===this.height-1)return this;let a=r-t+1,o=i-n+1;if(j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),s=e_(a,o).getContext(`2d`);return s.drawImage(i,t,n,a,o,0,0,a,o),new e(s.getImageData(0,0,a,o).data,a,o,4).convert(r)}{let e=this.toSharp().extract({left:t,top:n,width:a,height:o});return await n_(e)}}async center_crop(t,n){if(this.width===t&&this.height===n)return this;let r=(this.width-t)/2,i=(this.height-n)/2;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=e_(t,n).getContext(`2d`),c=0,l=0,u=0,d=0;return r>=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await n_(e)}}async toBlob(e=`image/png`,t=1){if(!j.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new G(`uint8`,new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!==`HWC`){if(e===`CHW`)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`)}return t}toCanvas(){if(!j.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=e_(e.width,e.height),n=new t_(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;e<o;++e){let n=i*e;for(let r=0;r<i;++r)s[r][e]=t[n+r]}return s.map(t=>new e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(j.IS_WEB_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=i_.get(t)??`image/png`;return cg(e,await this.toBlob(n))}if(j.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(j.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return ai(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};a_.read.bind(a_);function o_(e,t,n,r,i){let a=r*n**2,o=Math.sqrt(a/(e*t)),s=i*n,c=Math.floor(o*e/s)*s,l=Math.floor(o*t/s)*s;if(c===0&&l===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${s}.`);let u=Math.floor(r/i**2)*s;return c===0?(c=s,l=Math.min(Math.floor(t/e)*s,u)):l===0&&(l=s,c=Math.min(Math.floor(e/t)*s,u)),[c,l]}function s_(e,t,n,r,i,a,o){let s=Math.floor(t/i),c=Math.floor(n/i),l=s*c,u=i*i*r,d=new Float32Array(a*u),f=0;for(let t=0;t<s;++t)for(let a=0;a<c;++a)for(let o=0;o<i;++o){let s=(t*i+o)*n*r+a*i*r;for(let t=0;t<i;++t){let n=s+t*r;for(let t=0;t<r;++t)d[f++]=e[n+t]}}let p=new BigInt64Array(a*2).fill(-1n),m=0;for(let e=0;e<s;++e)for(let t=0;t<c;++t)p[m++]=BigInt(t),p[m++]=BigInt(e);return{patches:new G(`float32`,d,[a,u]),positions:new G(`int64`,p,[a,2]),num_soft_tokens:Math.floor(l/o**2)}}var c_=class extends Ii{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);let{patch_size:t,pooling_kernel_size:n}=this,r=this.max_soft_tokens*n**2,i=[],a=[],o=[];for(let s of e){if(this.do_convert_rgb&&(s=s.rgb()),this.do_resize){let[e,i]=o_(s.height,s.width,t,r,n);(e!==s.height||i!==s.width)&&(s=await s.resize(i,e,{resample:this.resample}))}let e=Float32Array.from(s.data);if(this.do_rescale)for(let t=0;t<e.length;++t)e[t]*=this.rescale_factor;let{patches:c,positions:l,num_soft_tokens:u}=s_(e,s.height,s.width,s.channels,t,r,n);i.push(c),a.push(l),o.push(u)}return{pixel_values:km(i,0),image_position_ids:km(a,0),num_soft_tokens_per_image:o}}},l_=class extends rg{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:r,boa_token:i,eoa_token:a,image_token:o,boi_token:s,eoi_token:c}=this.tokenizer.config;this.audio_token=r,this.boa_token=i,this.eoa_token=a,this.image_token=o,this.boi_token=s,this.eoi_token=c}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([Vl(e,tg,!0,t),Zh.from_pretrained(e,t),Bl(e,ng,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new c_(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new zg(n.feature_extractor)),new this(n,a,i)}_compute_audio_num_tokens(e,t){let n=Math.round(t*20/1e3),r=Math.round(t*10/1e3),i=Math.floor(n/2),a=Math.floor((e+i-n-1)/r)+1;if(a<=0)return 0;for(let e=0;e<2;++e)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;if(t){i=await this.image_processor(t,r);let n=i.num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>`
105
105
 
106
106
  ${this.boi_token}${this.image_token.repeat(n[a++])}${this.eoi_token}
107
107