@nocha/cli 4.13.0 → 4.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1200) hide show
  1. package/CHANGELOG.md +43 -124
  2. package/README.md +6 -1
  3. package/dist/NOCHA.schema.json +2117 -111
  4. package/dist/THIRD_PARTY_NOTICES.txt +2 -30
  5. package/dist/build-info.json +4 -4
  6. package/dist/dev-offline-compiler.js +11315 -25675
  7. package/dist/dev-offline-runner.js +2967 -1067
  8. package/dist/development-live-host.js +20932 -608
  9. package/dist/nocha.js +51294 -59984
  10. package/dist/reference-integrity.json +582 -735
  11. package/dist/references/README.md +2 -3
  12. package/dist/references/api/README.md +87 -148
  13. package/dist/references/api/SKILL.md +1 -1
  14. package/dist/references/api/experience-contract.md +36 -21
  15. package/dist/references/api/signatures/exports.md +997 -0
  16. package/dist/references/api/signatures/nocha.access.md +22 -0
  17. package/dist/references/api/signatures/nocha.ai.md +70 -0
  18. package/dist/references/api/signatures/nocha.assets.md +64 -0
  19. package/dist/references/api/signatures/nocha.assistant.md +46 -0
  20. package/dist/references/api/signatures/nocha.automations.md +94 -0
  21. package/dist/references/api/signatures/nocha.backend.md +22 -0
  22. package/dist/references/api/signatures/nocha.capabilities.md +16 -0
  23. package/dist/references/api/signatures/nocha.connectors.md +28 -0
  24. package/dist/references/api/signatures/nocha.context.md +16 -0
  25. package/dist/references/api/signatures/nocha.database.md +58 -0
  26. package/dist/references/api/signatures/nocha.device.md +118 -0
  27. package/dist/references/api/signatures/nocha.drive.md +16 -0
  28. package/dist/references/api/signatures/nocha.email.md +10 -0
  29. package/dist/references/api/signatures/nocha.excerpts.md +22 -0
  30. package/dist/references/api/signatures/nocha.experiences.md +34 -0
  31. package/dist/references/api/signatures/nocha.gamepad.md +28 -0
  32. package/dist/references/api/signatures/nocha.haptics.md +34 -0
  33. package/dist/references/api/signatures/nocha.hardware.md +88 -0
  34. package/dist/references/api/signatures/nocha.host.md +46 -0
  35. package/dist/references/api/signatures/nocha.inbox.md +22 -0
  36. package/dist/references/api/signatures/nocha.language.md +22 -0
  37. package/dist/references/api/signatures/nocha.library.md +112 -0
  38. package/dist/references/api/signatures/nocha.link.md +10 -0
  39. package/dist/references/api/signatures/nocha.machine.md +274 -0
  40. package/dist/references/api/signatures/nocha.memory.md +28 -0
  41. package/dist/references/api/signatures/nocha.module.md +10 -0
  42. package/dist/references/api/signatures/nocha.multiplayer.md +40 -0
  43. package/dist/references/api/signatures/nocha.navigation.md +46 -0
  44. package/dist/references/api/signatures/nocha.network.md +16 -0
  45. package/dist/references/api/signatures/nocha.notifications.md +28 -0
  46. package/dist/references/api/signatures/nocha.onEvent.md +10 -0
  47. package/dist/references/api/signatures/nocha.places.md +22 -0
  48. package/dist/references/api/signatures/nocha.player.md +10 -0
  49. package/dist/references/api/signatures/nocha.profiles.md +16 -0
  50. package/dist/references/api/signatures/nocha.ready.md +22 -0
  51. package/dist/references/api/signatures/nocha.screens.md +17 -0
  52. package/dist/references/api/signatures/nocha.search.md +10 -0
  53. package/dist/references/api/signatures/nocha.spaces.md +40 -0
  54. package/dist/references/api/signatures/nocha.state.md +22 -0
  55. package/dist/references/api/signatures/nocha.transfer.md +28 -0
  56. package/dist/references/api/signatures/nocha.use.md +10 -0
  57. package/dist/references/api/signatures/nocha.video.md +244 -0
  58. package/dist/references/api/signatures/nocha.viewport.md +34 -0
  59. package/dist/references/api/signatures/nocha.voice.md +28 -0
  60. package/dist/references/api/signatures/nocha.workspace.md +16 -0
  61. package/dist/references/api/signatures/registry.md +309 -0
  62. package/dist/references/api/signatures/server-exports.md +92 -0
  63. package/dist/references/api/signatures/watchirl.md +280 -0
  64. package/dist/references/api/signatures.md +58 -1312
  65. package/dist/references/base/NOCHA.json +42 -1
  66. package/dist/references/base/README.md +8 -7
  67. package/dist/references/base/SKILL.md +5 -5
  68. package/dist/references/base/index.html +2 -0
  69. package/dist/references/base/package-lock.json +427 -651
  70. package/dist/references/base/package.json +1 -1
  71. package/dist/references/base/server/tooling/sdk-plugin.ts +15 -5
  72. package/dist/references/base/server/tooling/sdk-sources.ts +3 -3
  73. package/dist/references/base/src/features/experience/application/start.ts +2 -2
  74. package/dist/references/base/src/features/experience/ui/components.ts +174 -12
  75. package/dist/references/base/src/features/experience/ui/home.ts +8 -7
  76. package/dist/references/base/src/features/experience/ui/mount.ts +30 -7
  77. package/dist/references/base/src/features/experience/ui/routes.ts +14 -3
  78. package/dist/references/base/src/locales/en.ts +7 -0
  79. package/dist/references/base/src/locales/fr.ts +8 -0
  80. package/dist/references/base/src/locales/index.ts +12 -0
  81. package/dist/references/base/src/main.ts +9 -2
  82. package/dist/references/base/src/platform/failure.ts +3 -97
  83. package/dist/references/base/src/platform/i18n.ts +83 -0
  84. package/dist/references/base/src/platform/nocha.ts +47 -4
  85. package/dist/references/base/src/platform/paging.ts +111 -0
  86. package/dist/references/base/src/platform/router.ts +235 -21
  87. package/dist/references/base/src/style.css +378 -51
  88. package/dist/references/base/src/types/nocha/index.d.ts +19392 -72
  89. package/dist/references/duel/NOCHA.json +6 -2
  90. package/dist/references/duel/README.md +2 -1
  91. package/dist/references/duel/index.html +1 -1
  92. package/dist/references/duel/package-lock.json +439 -621
  93. package/dist/references/duel/package.json +2 -2
  94. package/dist/references/duel/server/tooling/sdk-plugin.ts +15 -5
  95. package/dist/references/duel/server/tooling/sdk-sources.ts +3 -3
  96. package/dist/references/duel/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/README.md +31 -0
  97. package/dist/references/duel/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.d.ts +81 -0
  98. package/dist/references/duel/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.js +407 -0
  99. package/dist/references/duel/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/style.css +81 -0
  100. package/dist/references/duel/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/nocha-vendor.json +17 -0
  101. package/dist/references/duel/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/package.json +21 -0
  102. package/dist/references/duel/src/features/duel/api.ts +12 -11
  103. package/dist/references/duel/src/features/duel/model.ts +2 -1
  104. package/dist/references/duel/src/features/duel/renderer.ts +2 -1
  105. package/dist/references/duel/src/features/duel/ui.ts +17 -13
  106. package/dist/references/duel/src/locales/en.ts +43 -0
  107. package/dist/references/duel/src/locales/fr.ts +44 -0
  108. package/dist/references/duel/src/locales/index.ts +12 -0
  109. package/dist/references/duel/src/main.ts +9 -3
  110. package/dist/references/duel/src/platform/i18n.ts +83 -0
  111. package/dist/references/duel/src/types/nocha/index.d.ts +19392 -72
  112. package/dist/references/exploration/NOCHA.json +5 -1
  113. package/dist/references/exploration/README.md +2 -1
  114. package/dist/references/exploration/index.html +1 -1
  115. package/dist/references/exploration/package-lock.json +426 -650
  116. package/dist/references/exploration/package.json +2 -2
  117. package/dist/references/exploration/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/README.md +31 -0
  118. package/dist/references/exploration/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.d.ts +81 -0
  119. package/dist/references/exploration/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.js +407 -0
  120. package/dist/references/exploration/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/style.css +81 -0
  121. package/dist/references/exploration/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/nocha-vendor.json +17 -0
  122. package/dist/references/exploration/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/package.json +21 -0
  123. package/dist/references/exploration/src/features/exploration/model.ts +3 -1
  124. package/dist/references/exploration/src/features/exploration/renderer.ts +2 -1
  125. package/dist/references/exploration/src/features/exploration/ui.ts +8 -4
  126. package/dist/references/exploration/src/locales/en.ts +21 -0
  127. package/dist/references/exploration/src/locales/fr.ts +22 -0
  128. package/dist/references/exploration/src/locales/index.ts +12 -0
  129. package/dist/references/exploration/src/main.ts +9 -3
  130. package/dist/references/exploration/src/platform/i18n.ts +93 -0
  131. package/dist/references/guides/art-direction/SKILL.md +32 -42
  132. package/dist/references/packages/cli/README.md +6 -1
  133. package/dist/references/packages/experience-audio/README.md +68 -0
  134. package/dist/references/packages/experience-audio/SKILL.md +31 -0
  135. package/dist/references/packages/experience-input/README.md +4 -2
  136. package/dist/references/packages/experience-input/SKILL.md +1 -1
  137. package/dist/references/packages/experience-ui/README.md +79 -0
  138. package/dist/references/packages/experience-ui/SKILL.md +31 -0
  139. package/dist/references/packages/universe-foundation/README.md +63 -22
  140. package/dist/references/packages/universe-foundation/SKILL.md +4 -4
  141. package/dist/references/packages/world-ui/README.md +35 -1
  142. package/dist/references/platform/diagnostics.ts +66 -0
  143. package/dist/references/platform/failure.ts +6 -0
  144. package/dist/references/platform/lifecycle.ts +78 -0
  145. package/dist/references/platform/nocha.ts +103 -0
  146. package/dist/references/platform/paging.ts +112 -0
  147. package/dist/references/platform/router.ts +265 -0
  148. package/dist/references/platform/stored.ts +42 -0
  149. package/dist/references/racing/NOCHA.json +5 -1
  150. package/dist/references/racing/README.md +2 -1
  151. package/dist/references/racing/index.html +1 -1
  152. package/dist/references/racing/package-lock.json +426 -650
  153. package/dist/references/racing/package.json +2 -2
  154. package/dist/references/racing/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/README.md +31 -0
  155. package/dist/references/racing/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.d.ts +81 -0
  156. package/dist/references/racing/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.js +407 -0
  157. package/dist/references/racing/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/style.css +81 -0
  158. package/dist/references/racing/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/nocha-vendor.json +17 -0
  159. package/dist/references/racing/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/package.json +21 -0
  160. package/dist/references/racing/src/features/racing/model.ts +4 -1
  161. package/dist/references/racing/src/features/racing/renderer.ts +2 -1
  162. package/dist/references/racing/src/features/racing/ui.ts +8 -4
  163. package/dist/references/racing/src/locales/en.ts +21 -0
  164. package/dist/references/racing/src/locales/fr.ts +22 -0
  165. package/dist/references/racing/src/locales/index.ts +12 -0
  166. package/dist/references/racing/src/main.ts +9 -3
  167. package/dist/references/racing/src/platform/i18n.ts +93 -0
  168. package/dist/references/recipes/README.md +8 -3
  169. package/dist/references/recipes/ai-agent/NOCHA.json +94 -0
  170. package/dist/references/recipes/ai-agent/README.md +30 -0
  171. package/dist/references/recipes/ai-agent/SKILL.md +25 -0
  172. package/dist/references/recipes/ai-agent/recipe.ts +221 -0
  173. package/dist/references/recipes/ai-realtime-chat/NOCHA.json +3 -2
  174. package/dist/references/recipes/assistant-actions/README.md +34 -19
  175. package/dist/references/recipes/assistant-actions/SKILL.md +7 -9
  176. package/dist/references/recipes/assistant-actions/recipe.ts +61 -30
  177. package/dist/references/recipes/assistant-voice/NOCHA.json +1 -1
  178. package/dist/references/recipes/backend-transaction/NOCHA.json +6 -3
  179. package/dist/references/recipes/backend-transaction/README.md +22 -3
  180. package/dist/references/recipes/backend-transaction/SKILL.md +9 -4
  181. package/dist/references/recipes/backend-transaction/src/platform/failure.ts +3 -97
  182. package/dist/references/recipes/backend-transaction/src/platform/nocha.ts +47 -4
  183. package/dist/references/recipes/backend-transaction/src/platform/paging.ts +111 -0
  184. package/dist/references/recipes/backend-transaction/src/platform/router.ts +235 -21
  185. package/dist/references/recipes/database/NOCHA.json +71 -0
  186. package/dist/references/recipes/database/README.md +36 -0
  187. package/dist/references/recipes/database/SKILL.md +26 -0
  188. package/dist/references/recipes/database/recipe.ts +112 -0
  189. package/dist/references/recipes/device/NOCHA.json +2 -1
  190. package/dist/references/recipes/device/README.md +1 -1
  191. package/dist/references/recipes/device/SKILL.md +1 -1
  192. package/dist/references/recipes/device/recipe.ts +17 -1
  193. package/dist/references/recipes/drive/NOCHA.json +1 -1
  194. package/dist/references/recipes/email/NOCHA.json +1 -1
  195. package/dist/references/recipes/experience-calls/NOCHA.json +56 -0
  196. package/dist/references/recipes/experience-calls/README.md +16 -0
  197. package/dist/references/recipes/experience-calls/SKILL.md +24 -0
  198. package/dist/references/recipes/experience-calls/recipe.ts +44 -0
  199. package/dist/references/recipes/hardware/NOCHA.json +43 -0
  200. package/dist/references/recipes/hardware/README.md +15 -0
  201. package/dist/references/recipes/hardware/SKILL.md +24 -0
  202. package/dist/references/recipes/hardware/recipe.ts +33 -0
  203. package/dist/references/recipes/home-interface/NOCHA.json +54 -0
  204. package/dist/references/recipes/home-interface/SKILL.md +110 -0
  205. package/dist/references/recipes/home-interface/demo-data.ts +206 -0
  206. package/dist/references/recipes/home-interface/recipe.ts +588 -0
  207. package/dist/references/recipes/home-interface/scene/NOTICE +18 -0
  208. package/dist/references/recipes/home-interface/scene/boucle.ts +226 -0
  209. package/dist/references/recipes/home-interface/scene/fond.ts +220 -0
  210. package/dist/references/recipes/home-interface/scene/glsl.ts +95 -0
  211. package/dist/references/recipes/home-interface/scene/lieu.ts +93 -0
  212. package/dist/references/recipes/home-interface/scene/mouvement.ts +128 -0
  213. package/dist/references/recipes/home-interface/scene/profondeur.ts +60 -0
  214. package/dist/references/recipes/home-interface/scene/scene.css +51 -0
  215. package/dist/references/recipes/home-interface/scene/scene.ts +46 -0
  216. package/dist/references/recipes/home-interface/scene/teinte.ts +93 -0
  217. package/dist/references/recipes/i18n/README.md +26 -0
  218. package/dist/references/recipes/i18n/SKILL.md +22 -0
  219. package/dist/references/recipes/i18n/recipe.ts +86 -0
  220. package/dist/references/recipes/image-transformation/NOCHA.json +5 -3
  221. package/dist/references/recipes/image-transformation/README.md +1 -1
  222. package/dist/references/recipes/image-video-loop/NOCHA.json +7 -4
  223. package/dist/references/recipes/image-video-loop/src/features/video/api.ts +2 -2
  224. package/dist/references/recipes/image-video-loop/src/features/video/workflow.ts +6 -2
  225. package/dist/references/recipes/inbox/NOCHA.json +1 -1
  226. package/dist/references/recipes/multiplayer-canvas/NOCHA.json +3 -2
  227. package/dist/references/recipes/music/NOCHA.json +5 -4
  228. package/dist/references/recipes/navigation/README.md +28 -0
  229. package/dist/references/recipes/navigation/SKILL.md +22 -0
  230. package/dist/references/recipes/network/NOCHA.json +1 -1
  231. package/dist/references/recipes/network/README.md +1 -1
  232. package/dist/references/recipes/network/recipe.ts +4 -3
  233. package/dist/references/recipes/notifications/NOCHA.json +13 -2
  234. package/dist/references/recipes/notifications/README.md +12 -4
  235. package/dist/references/recipes/notifications/SKILL.md +5 -4
  236. package/dist/references/recipes/notifications/recipe.ts +35 -1
  237. package/dist/references/recipes/package.json +2 -2
  238. package/dist/references/recipes/search/NOCHA.json +90 -0
  239. package/dist/references/recipes/search/README.md +43 -0
  240. package/dist/references/recipes/search/SKILL.md +24 -0
  241. package/dist/references/recipes/search/recipe.ts +160 -0
  242. package/dist/references/recipes/spaces/NOCHA.json +88 -0
  243. package/dist/references/recipes/spaces/README.md +10 -0
  244. package/dist/references/recipes/spaces/SKILL.md +23 -0
  245. package/dist/references/recipes/spaces/recipe.ts +61 -0
  246. package/dist/references/recipes/state-memory/NOCHA.json +11 -19
  247. package/dist/references/recipes/state-memory/README.md +6 -4
  248. package/dist/references/recipes/state-memory/SKILL.md +4 -3
  249. package/dist/references/recipes/state-memory/recipe.ts +65 -30
  250. package/dist/references/recipes/text-research/NOCHA.json +1 -1
  251. package/dist/references/recipes/three-room/README.md +2 -2
  252. package/dist/references/recipes/three-room/src/features/room/index.ts +3 -2
  253. package/dist/references/recipes/three-stage/README.md +2 -2
  254. package/dist/references/recipes/three-stage/src/features/stage/model.ts +17 -15
  255. package/dist/references/recipes/three-stage/src/features/stage/scene.ts +3 -2
  256. package/dist/references/recipes/three-stage/src/locales/en.ts +24 -0
  257. package/dist/references/recipes/three-stage/src/locales/fr.ts +25 -0
  258. package/dist/references/recipes/three-stage/src/locales/index.ts +13 -0
  259. package/dist/references/recipes/three-stage/src/platform/i18n.ts +84 -0
  260. package/dist/references/recipes/types/nocha/ai-operations.d.ts +81 -0
  261. package/dist/references/recipes/types/nocha/ai-voice-catalogue.d.ts +19 -0
  262. package/dist/references/recipes/types/nocha/ai.d.ts +2 -1
  263. package/dist/references/recipes/types/nocha/assets-media.d.ts +9 -4
  264. package/dist/references/recipes/types/nocha/assets-operations.d.ts +106 -0
  265. package/dist/references/recipes/types/nocha/assistant-open.d.ts +21 -0
  266. package/dist/references/recipes/types/nocha/assistant-paid.d.ts +18 -0
  267. package/dist/references/recipes/types/nocha/assistant.d.ts +44 -0
  268. package/dist/references/recipes/types/nocha/attachments.d.ts +1 -1
  269. package/dist/references/recipes/types/nocha/audio-media.d.ts +19 -0
  270. package/dist/references/recipes/types/nocha/backend-database.d.ts +15 -5
  271. package/dist/references/recipes/types/nocha/backend-media.d.ts +43 -0
  272. package/dist/references/recipes/types/nocha/backend-runtime.d.ts +36 -0
  273. package/dist/references/recipes/types/nocha/backend-search.d.ts +33 -0
  274. package/dist/references/recipes/types/nocha/backend-server-query.d.ts +26 -0
  275. package/dist/references/recipes/types/nocha/backend-server.d.ts +48 -2
  276. package/dist/references/recipes/types/nocha/backend-transactions.d.ts +32 -1
  277. package/dist/references/recipes/types/nocha/capabilities.d.ts +2 -2
  278. package/dist/references/recipes/types/nocha/capability-deadlines.d.ts +60 -1
  279. package/dist/references/recipes/types/nocha/capability-needs.d.ts +7 -0
  280. package/dist/references/recipes/types/nocha/capability-operations.d.ts +41 -9
  281. package/dist/references/recipes/types/nocha/capability-registry.d.ts +18 -0
  282. package/dist/references/recipes/types/nocha/character-package-types.d.ts +108 -0
  283. package/dist/references/recipes/types/nocha/clipping-types.d.ts +2 -0
  284. package/dist/references/recipes/types/nocha/content-refusal.d.ts +11 -0
  285. package/dist/references/recipes/types/nocha/context.d.ts +4 -0
  286. package/dist/references/recipes/types/nocha/database-watch.d.ts +13 -0
  287. package/dist/references/recipes/types/nocha/device-operations.d.ts +6 -0
  288. package/dist/references/recipes/types/nocha/device-types.d.ts +31 -1
  289. package/dist/references/recipes/types/nocha/error-codes.d.ts +231 -34
  290. package/dist/references/recipes/types/nocha/excerpts-operations.d.ts +79 -0
  291. package/dist/references/recipes/types/nocha/excerpts-types.d.ts +43 -0
  292. package/dist/references/recipes/types/nocha/excerpts.d.ts +17 -0
  293. package/dist/references/recipes/types/nocha/execution.d.ts +5 -4
  294. package/dist/references/recipes/types/nocha/experience-context-types.d.ts +17 -0
  295. package/dist/references/recipes/types/nocha/experience-context.d.ts +5 -1
  296. package/dist/references/recipes/types/nocha/experiences-operations.d.ts +218 -0
  297. package/dist/references/recipes/types/nocha/experiences-types.d.ts +93 -0
  298. package/dist/references/recipes/types/nocha/experiences.d.ts +47 -0
  299. package/dist/references/recipes/types/nocha/external-protocol.d.ts +76 -0
  300. package/dist/references/recipes/types/nocha/failure.d.ts +58 -0
  301. package/dist/references/recipes/types/nocha/fault.d.ts +6 -0
  302. package/dist/references/recipes/types/nocha/gamepad-target.d.ts +5 -0
  303. package/dist/references/recipes/types/nocha/gamepad-types.d.ts +63 -0
  304. package/dist/references/recipes/types/nocha/gamepad.d.ts +21 -0
  305. package/dist/references/recipes/types/nocha/generation-input.d.ts +7 -3
  306. package/dist/references/recipes/types/nocha/guards.d.ts +8 -0
  307. package/dist/references/recipes/types/nocha/haptics-types.d.ts +31 -0
  308. package/dist/references/recipes/types/nocha/haptics.d.ts +8 -0
  309. package/dist/references/recipes/types/nocha/hardware-operations.d.ts +353 -0
  310. package/dist/references/recipes/types/nocha/hardware.d.ts +32 -0
  311. package/dist/references/recipes/types/nocha/host-channels.d.ts +11 -0
  312. package/dist/references/recipes/types/nocha/host-feed.d.ts +27 -0
  313. package/dist/references/recipes/types/nocha/host-operations.d.ts +89 -0
  314. package/dist/references/recipes/types/nocha/host-types.d.ts +106 -0
  315. package/dist/references/recipes/types/nocha/host-upload.d.ts +35 -0
  316. package/dist/references/recipes/types/nocha/hosting.d.ts +17 -0
  317. package/dist/references/recipes/types/nocha/index.d.ts +149 -7
  318. package/dist/references/recipes/types/nocha/language-match.d.ts +8 -0
  319. package/dist/references/recipes/types/nocha/language.d.ts +18 -0
  320. package/dist/references/recipes/types/nocha/library-operations.d.ts +430 -0
  321. package/dist/references/recipes/types/nocha/library-types.d.ts +325 -0
  322. package/dist/references/recipes/types/nocha/library.d.ts +58 -0
  323. package/dist/references/recipes/types/nocha/link-operations.d.ts +32 -0
  324. package/dist/references/recipes/types/nocha/link-types.d.ts +17 -0
  325. package/dist/references/recipes/types/nocha/link.d.ts +21 -0
  326. package/dist/references/recipes/types/nocha/live-media-failure.d.ts +40 -0
  327. package/dist/references/recipes/types/nocha/live-media-status.d.ts +7 -0
  328. package/dist/references/recipes/types/nocha/live-media.d.ts +9 -1
  329. package/dist/references/recipes/types/nocha/machine-operations.d.ts +1135 -0
  330. package/dist/references/recipes/types/nocha/machine-streams.d.ts +4 -0
  331. package/dist/references/recipes/types/nocha/machine.d.ts +77 -0
  332. package/dist/references/recipes/types/nocha/media-read.d.ts +9 -1
  333. package/dist/references/recipes/types/nocha/module-types.d.ts +53 -0
  334. package/dist/references/recipes/types/nocha/module.d.ts +7 -0
  335. package/dist/references/recipes/types/nocha/navigation-capture.d.ts +32 -0
  336. package/dist/references/recipes/types/nocha/navigation.d.ts +11 -0
  337. package/dist/references/recipes/types/nocha/notifications-operations.d.ts +78 -1
  338. package/dist/references/recipes/types/nocha/notifications.d.ts +11 -1
  339. package/dist/references/recipes/types/nocha/operation-metadata.d.ts +3 -2
  340. package/dist/references/recipes/types/nocha/operation-waiting.d.ts +47 -1
  341. package/dist/references/recipes/types/nocha/operation-wire-types.d.ts +191 -16
  342. package/dist/references/recipes/types/nocha/places-operations.d.ts +79 -0
  343. package/dist/references/recipes/types/nocha/places-types.d.ts +40 -0
  344. package/dist/references/recipes/types/nocha/places.d.ts +13 -0
  345. package/dist/references/recipes/types/nocha/player.d.ts +9 -0
  346. package/dist/references/recipes/types/nocha/profiles-operations.d.ts +55 -0
  347. package/dist/references/recipes/types/nocha/profiles-types.d.ts +33 -0
  348. package/dist/references/recipes/types/nocha/profiles.d.ts +18 -0
  349. package/dist/references/recipes/types/nocha/protocol.d.ts +140 -14
  350. package/dist/references/recipes/types/nocha/screens-operations.d.ts +21 -0
  351. package/dist/references/recipes/types/nocha/screens-types.d.ts +60 -0
  352. package/dist/references/recipes/types/nocha/screens.d.ts +17 -0
  353. package/dist/references/recipes/types/nocha/search-operations.d.ts +435 -0
  354. package/dist/references/recipes/types/nocha/search-results.d.ts +12 -0
  355. package/dist/references/recipes/types/nocha/search-types.d.ts +249 -0
  356. package/dist/references/recipes/types/nocha/search.d.ts +41 -0
  357. package/dist/references/recipes/types/nocha/shared-usage.d.ts +5 -0
  358. package/dist/references/recipes/types/nocha/shortcut-keys.d.ts +49 -0
  359. package/dist/references/recipes/types/nocha/spaces-types.d.ts +37 -0
  360. package/dist/references/recipes/types/nocha/spaces.d.ts +34 -0
  361. package/dist/references/recipes/types/nocha/speech-rules.d.ts +66 -0
  362. package/dist/references/recipes/types/nocha/speech-voices.d.ts +88 -0
  363. package/dist/references/recipes/types/nocha/storage-operation-types.d.ts +11 -3
  364. package/dist/references/recipes/types/nocha/storage-operations.d.ts +71 -1
  365. package/dist/references/recipes/types/nocha/storage.d.ts +25 -3
  366. package/dist/references/recipes/types/nocha/transfer-payload.d.ts +15 -0
  367. package/dist/references/recipes/types/nocha/transfer-preview.d.ts +4 -0
  368. package/dist/references/recipes/types/nocha/transfer-runtime.d.ts +23 -0
  369. package/dist/references/recipes/types/nocha/transfer-source.d.ts +30 -0
  370. package/dist/references/recipes/types/nocha/transfer-types.d.ts +221 -0
  371. package/dist/references/recipes/types/nocha/transfer-zones.d.ts +26 -0
  372. package/dist/references/recipes/types/nocha/transfer.d.ts +148 -0
  373. package/dist/references/recipes/types/nocha/transport.d.ts +7 -6
  374. package/dist/references/recipes/types/nocha/types/ai-wire.d.ts +342 -15
  375. package/dist/references/recipes/types/nocha/types/ai.d.ts +13 -3
  376. package/dist/references/recipes/types/nocha/types/assets-wire.d.ts +48 -2
  377. package/dist/references/recipes/types/nocha/types/assets.d.ts +34 -14
  378. package/dist/references/recipes/types/nocha/types/hardware.d.ts +327 -0
  379. package/dist/references/recipes/types/nocha/types/machine-workspace.d.ts +684 -0
  380. package/dist/references/recipes/types/nocha/types/machine.d.ts +279 -0
  381. package/dist/references/recipes/types/nocha/types/storage.d.ts +72 -2
  382. package/dist/references/recipes/types/nocha/types/video-projects-wire.d.ts +203 -0
  383. package/dist/references/recipes/types/nocha/types/video-sdk-wire.d.ts +18 -0
  384. package/dist/references/recipes/types/nocha/types/video-wire.d.ts +7 -0
  385. package/dist/references/recipes/types/nocha/types/video.d.ts +74 -1
  386. package/dist/references/recipes/types/nocha/types/voice-wire.d.ts +42 -6
  387. package/dist/references/recipes/types/nocha/ui-host.d.ts +44 -0
  388. package/dist/references/recipes/types/nocha/ui-text.d.ts +20 -0
  389. package/dist/references/recipes/types/nocha/ui-theme.d.ts +12 -0
  390. package/dist/references/recipes/types/nocha/validate.d.ts +51 -0
  391. package/dist/references/recipes/types/nocha/video-analysis.d.ts +3 -1
  392. package/dist/references/recipes/types/nocha/video-operations.d.ts +282 -1
  393. package/dist/references/recipes/types/nocha/video-playback.d.ts +14 -0
  394. package/dist/references/recipes/types/nocha/video-presentation.d.ts +55 -0
  395. package/dist/references/recipes/types/nocha/video-projects.d.ts +5 -0
  396. package/dist/references/recipes/types/nocha/video-settings-bridge.d.ts +22 -0
  397. package/dist/references/recipes/types/nocha/video-settings-controls.d.ts +42 -0
  398. package/dist/references/recipes/types/nocha/video-settings-css.d.ts +5 -0
  399. package/dist/references/recipes/types/nocha/video-settings-media.d.ts +16 -0
  400. package/dist/references/recipes/types/nocha/video-settings-state.d.ts +60 -0
  401. package/dist/references/recipes/types/nocha/video-settings-types.d.ts +296 -0
  402. package/dist/references/recipes/types/nocha/video-settings.d.ts +28 -0
  403. package/dist/references/recipes/types/nocha/video-workflow-picker.d.ts +25 -0
  404. package/dist/references/recipes/types/nocha/video-workflow-rules.d.ts +112 -0
  405. package/dist/references/recipes/types/nocha/viewport-types.d.ts +15 -0
  406. package/dist/references/recipes/types/nocha/viewport.d.ts +11 -1
  407. package/dist/references/recipes/types/nocha/voice-audition.d.ts +38 -0
  408. package/dist/references/recipes/types/nocha/voice-browser-categories.d.ts +38 -0
  409. package/dist/references/recipes/types/nocha/voice-browser-core.d.ts +32 -0
  410. package/dist/references/recipes/types/nocha/voice-browser.d.ts +12 -0
  411. package/dist/references/recipes/types/nocha/voice-favorites-account.d.ts +29 -0
  412. package/dist/references/recipes/types/nocha/voice-field.d.ts +11 -0
  413. package/dist/references/recipes/types/nocha/voice-imagine-toggle.d.ts +30 -0
  414. package/dist/references/recipes/types/nocha/voice-listing.d.ts +66 -0
  415. package/dist/references/recipes/types/nocha/voice-memory.d.ts +32 -0
  416. package/dist/references/recipes/types/nocha/voice-picker-bar.d.ts +31 -0
  417. package/dist/references/recipes/types/nocha/voice-picker-css.d.ts +4 -0
  418. package/dist/references/recipes/types/nocha/voice-picker-data.d.ts +92 -0
  419. package/dist/references/recipes/types/nocha/voice-picker-facets.d.ts +50 -0
  420. package/dist/references/recipes/types/nocha/voice-picker-list.d.ts +39 -0
  421. package/dist/references/recipes/types/nocha/voice-picker-models.d.ts +44 -0
  422. package/dist/references/recipes/types/nocha/voice-picker-row.d.ts +56 -0
  423. package/dist/references/recipes/types/nocha/voice-picker-state.d.ts +54 -0
  424. package/dist/references/recipes/types/nocha/voice-picker-types.d.ts +246 -0
  425. package/dist/references/recipes/types/nocha/voice-picker.d.ts +18 -0
  426. package/dist/references/recipes/types/nocha/voice-random.d.ts +52 -0
  427. package/dist/references/recipes/types/nocha/voice-recovery.d.ts +10 -0
  428. package/dist/references/recipes/types/nocha/voice-system-picker.d.ts +12 -0
  429. package/dist/references/recipes/types/nocha/voice.d.ts +5 -2
  430. package/dist/references/recipes/types/nocha/workspace.d.ts +3 -0
  431. package/dist/references/shooter/NOCHA.json +5 -1
  432. package/dist/references/shooter/README.md +2 -1
  433. package/dist/references/shooter/index.html +1 -1
  434. package/dist/references/shooter/package-lock.json +426 -650
  435. package/dist/references/shooter/package.json +2 -2
  436. package/dist/references/shooter/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/README.md +31 -0
  437. package/dist/references/shooter/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.d.ts +81 -0
  438. package/dist/references/shooter/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/index.js +407 -0
  439. package/dist/references/shooter/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/lib/style.css +81 -0
  440. package/dist/references/shooter/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/nocha-vendor.json +17 -0
  441. package/dist/references/shooter/server/vendor/experience-input/0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c/package.json +21 -0
  442. package/dist/references/shooter/src/features/shooter/model.ts +3 -1
  443. package/dist/references/shooter/src/features/shooter/renderer.ts +2 -1
  444. package/dist/references/shooter/src/features/shooter/ui.ts +8 -4
  445. package/dist/references/shooter/src/locales/en.ts +24 -0
  446. package/dist/references/shooter/src/locales/fr.ts +25 -0
  447. package/dist/references/shooter/src/locales/index.ts +12 -0
  448. package/dist/references/shooter/src/main.ts +9 -3
  449. package/dist/references/shooter/src/platform/i18n.ts +93 -0
  450. package/dist/references/stage/NOCHA.json +5 -1
  451. package/dist/references/stage/README.md +4 -4
  452. package/dist/references/stage/SKILL.md +1 -1
  453. package/dist/references/stage/index.html +2 -0
  454. package/dist/references/stage/package-lock.json +521 -740
  455. package/dist/references/stage/package.json +2 -2
  456. package/dist/references/stage/server/tooling/sdk-plugin.ts +15 -5
  457. package/dist/references/stage/server/tooling/sdk-sources.ts +3 -3
  458. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/README.md +71 -0
  459. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/pointer.d.ts +82 -0
  460. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/pointer.js +273 -0
  461. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/types.d.ts +337 -0
  462. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/universe.css +14 -0
  463. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/universe.d.ts +57 -0
  464. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/universe.js +205 -0
  465. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/viewport.d.ts +17 -0
  466. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/widget-types.js +1 -0
  467. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/nocha-vendor.json +108 -0
  468. package/dist/references/stage/server/vendor/world-ui/0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/package.json +34 -0
  469. package/dist/references/stage/src/features/stage/model.ts +17 -15
  470. package/dist/references/stage/src/features/stage/scene.ts +3 -2
  471. package/dist/references/stage/src/locales/en.ts +23 -0
  472. package/dist/references/stage/src/locales/fr.ts +24 -0
  473. package/dist/references/stage/src/locales/index.ts +12 -0
  474. package/dist/references/stage/src/main.ts +9 -3
  475. package/dist/references/stage/src/platform/i18n.ts +83 -0
  476. package/dist/references/stage/src/types/nocha/index.d.ts +19392 -72
  477. package/dist/references/stage/vite.config.ts +1 -1
  478. package/dist/references/workshop/NOCHA.json +23 -10
  479. package/dist/references/workshop/README.md +4 -2
  480. package/dist/references/workshop/index.html +1 -0
  481. package/dist/references/workshop/package-lock.json +515 -739
  482. package/dist/references/workshop/package.json +1 -1
  483. package/dist/references/workshop/server/app/domain/schemas.ts +2 -1
  484. package/dist/references/workshop/server/app/domain/workshop.ts +6 -3
  485. package/dist/references/workshop/server/tooling/sdk-plugin.ts +15 -5
  486. package/dist/references/workshop/server/tooling/sdk-sources.ts +3 -3
  487. package/dist/references/workshop/src/features/proposals/api.ts +17 -16
  488. package/dist/references/workshop/src/features/proposals/controller.ts +18 -18
  489. package/dist/references/workshop/src/features/proposals/index.ts +4 -3
  490. package/dist/references/workshop/src/features/proposals/view.ts +16 -13
  491. package/dist/references/workshop/src/locales/en.ts +75 -0
  492. package/dist/references/workshop/src/locales/fr.ts +76 -0
  493. package/dist/references/workshop/src/locales/index.ts +12 -0
  494. package/dist/references/workshop/src/main.ts +6 -2
  495. package/dist/references/workshop/src/platform/failure.ts +3 -97
  496. package/dist/references/workshop/src/platform/i18n.ts +83 -0
  497. package/dist/references/workshop/src/platform/nocha.ts +4 -3
  498. package/dist/references/workshop/src/styles.css +1 -1
  499. package/dist/references/workshop/src/types/nocha/backend-server.d.ts +14601 -11
  500. package/dist/references/workshop/src/types/nocha/index.d.ts +4754 -72
  501. package/dist/sdk-versions.json +2 -2
  502. package/dist/sdks/@nocha/sdk/dist/ai-operations.d.ts +81 -0
  503. package/dist/sdks/@nocha/sdk/dist/assets-operations.d.ts +106 -0
  504. package/dist/sdks/@nocha/sdk/dist/assistant-open.d.ts +20 -0
  505. package/dist/sdks/@nocha/sdk/dist/assistant-paid.d.ts +17 -0
  506. package/dist/sdks/@nocha/sdk/dist/assistant.d.ts +44 -0
  507. package/dist/sdks/@nocha/sdk/dist/audio-media.d.ts +18 -0
  508. package/dist/sdks/@nocha/sdk/dist/backend-database.d.ts +15 -5
  509. package/dist/sdks/@nocha/sdk/dist/backend-media.d.ts +42 -0
  510. package/dist/sdks/@nocha/sdk/dist/backend-runtime.d.ts +36 -0
  511. package/dist/sdks/@nocha/sdk/dist/backend-search.d.ts +32 -0
  512. package/dist/sdks/@nocha/sdk/dist/backend-server-host-core.d.ts +26 -3
  513. package/dist/sdks/@nocha/sdk/dist/backend-server-host.d.ts +1 -1
  514. package/dist/sdks/@nocha/sdk/dist/backend-server-host.js +261 -26
  515. package/dist/sdks/@nocha/sdk/dist/backend-server-query.d.ts +25 -0
  516. package/dist/sdks/@nocha/sdk/dist/backend-server.d.ts +48 -2
  517. package/dist/sdks/@nocha/sdk/dist/backend-server.js +36 -2
  518. package/dist/sdks/@nocha/sdk/dist/backend-transactions.d.ts +32 -1
  519. package/dist/sdks/@nocha/sdk/dist/bridge.js +3 -3
  520. package/dist/sdks/@nocha/sdk/dist/capabilities.d.ts +2 -2
  521. package/dist/sdks/@nocha/sdk/dist/capabilities.js +12 -2
  522. package/dist/sdks/@nocha/sdk/dist/capability-deadlines.d.ts +60 -1
  523. package/dist/sdks/@nocha/sdk/dist/capability-needs.d.ts +7 -0
  524. package/dist/sdks/@nocha/sdk/dist/capability-operations.d.ts +41 -9
  525. package/dist/sdks/@nocha/sdk/dist/capability-registry.d.ts +17 -0
  526. package/dist/sdks/@nocha/sdk/dist/character-package-types.d.ts +107 -0
  527. package/dist/sdks/@nocha/sdk/dist/chunk-AJF3E3TH.js +26 -0
  528. package/dist/sdks/@nocha/sdk/dist/chunk-DGHVP7N5.js +3835 -0
  529. package/dist/sdks/@nocha/sdk/dist/chunk-EIYOBJTN.js +330 -0
  530. package/dist/sdks/@nocha/sdk/dist/chunk-Z4YFZ7FO.js +108 -0
  531. package/dist/sdks/@nocha/sdk/dist/clipping-types.d.ts +2 -0
  532. package/dist/sdks/@nocha/sdk/dist/content-refusal.d.ts +10 -0
  533. package/dist/sdks/@nocha/sdk/dist/context.d.ts +4 -0
  534. package/dist/sdks/@nocha/sdk/dist/database-watch.d.ts +12 -0
  535. package/dist/sdks/@nocha/sdk/dist/device-operations.d.ts +6 -0
  536. package/dist/sdks/@nocha/sdk/dist/device-types.d.ts +31 -1
  537. package/dist/sdks/@nocha/sdk/dist/error-codes.d.ts +231 -34
  538. package/dist/sdks/@nocha/sdk/dist/excerpts-operations.d.ts +78 -0
  539. package/dist/sdks/@nocha/sdk/dist/excerpts-types.d.ts +42 -0
  540. package/dist/sdks/@nocha/sdk/dist/excerpts.d.ts +16 -0
  541. package/dist/sdks/@nocha/sdk/dist/execution.d.ts +5 -4
  542. package/dist/sdks/@nocha/sdk/dist/experience-context-host.d.ts +9 -6
  543. package/dist/sdks/@nocha/sdk/dist/experience-context-types.d.ts +17 -0
  544. package/dist/sdks/@nocha/sdk/dist/experience-context.d.ts +5 -1
  545. package/dist/sdks/@nocha/sdk/dist/experiences-operations.d.ts +217 -0
  546. package/dist/sdks/@nocha/sdk/dist/experiences-types.d.ts +92 -0
  547. package/dist/sdks/@nocha/sdk/dist/experiences.d.ts +46 -0
  548. package/dist/sdks/@nocha/sdk/dist/external-protocol.d.ts +75 -0
  549. package/dist/sdks/@nocha/sdk/dist/failure.d.ts +57 -0
  550. package/dist/sdks/@nocha/sdk/dist/gamepad-types.d.ts +62 -0
  551. package/dist/sdks/@nocha/sdk/dist/gamepad.d.ts +20 -0
  552. package/dist/sdks/@nocha/sdk/dist/guards.d.ts +20 -0
  553. package/dist/sdks/@nocha/sdk/dist/haptics-types.d.ts +30 -0
  554. package/dist/sdks/@nocha/sdk/dist/hardware-operations.d.ts +352 -0
  555. package/dist/sdks/@nocha/sdk/dist/hardware.d.ts +31 -0
  556. package/dist/sdks/@nocha/sdk/dist/host-channels.d.ts +10 -0
  557. package/dist/sdks/@nocha/sdk/dist/host-feed.d.ts +26 -0
  558. package/dist/sdks/@nocha/sdk/dist/host-operations.d.ts +88 -0
  559. package/dist/sdks/@nocha/sdk/dist/host-types.d.ts +105 -0
  560. package/dist/sdks/@nocha/sdk/dist/host.d.ts +3 -1
  561. package/dist/sdks/@nocha/sdk/dist/host.js +691 -12
  562. package/dist/sdks/@nocha/sdk/dist/hosting.d.ts +16 -0
  563. package/dist/sdks/@nocha/sdk/dist/index.d.ts +149 -7
  564. package/dist/sdks/@nocha/sdk/dist/index.js +12605 -1575
  565. package/dist/sdks/@nocha/sdk/dist/language-match.d.ts +7 -0
  566. package/dist/sdks/@nocha/sdk/dist/language.d.ts +17 -0
  567. package/dist/sdks/@nocha/sdk/dist/library-operations.d.ts +429 -0
  568. package/dist/sdks/@nocha/sdk/dist/library-types.d.ts +324 -0
  569. package/dist/sdks/@nocha/sdk/dist/library.d.ts +57 -0
  570. package/dist/sdks/@nocha/sdk/dist/link-operations.d.ts +31 -0
  571. package/dist/sdks/@nocha/sdk/dist/link-types.d.ts +16 -0
  572. package/dist/sdks/@nocha/sdk/dist/link.d.ts +20 -0
  573. package/dist/sdks/@nocha/sdk/dist/live-media-failure.d.ts +39 -0
  574. package/dist/sdks/@nocha/sdk/dist/machine-operations.d.ts +1134 -0
  575. package/dist/sdks/@nocha/sdk/dist/machine-stream-host.d.ts +16 -0
  576. package/dist/sdks/@nocha/sdk/dist/machine-stream-types.d.ts +168 -0
  577. package/dist/sdks/@nocha/sdk/dist/machine.d.ts +76 -0
  578. package/dist/sdks/@nocha/sdk/dist/module-types.d.ts +52 -0
  579. package/dist/sdks/@nocha/sdk/dist/navigation-capture.d.ts +31 -0
  580. package/dist/sdks/@nocha/sdk/dist/navigation-host.d.ts +6 -0
  581. package/dist/sdks/@nocha/sdk/dist/navigation.d.ts +11 -0
  582. package/dist/sdks/@nocha/sdk/dist/notifications-operations.d.ts +78 -1
  583. package/dist/sdks/@nocha/sdk/dist/notifications.d.ts +11 -1
  584. package/dist/sdks/@nocha/sdk/dist/operation-metadata.d.ts +3 -2
  585. package/dist/sdks/@nocha/sdk/dist/operation-wire-types.d.ts +191 -16
  586. package/dist/sdks/@nocha/sdk/dist/places-operations.d.ts +78 -0
  587. package/dist/sdks/@nocha/sdk/dist/places-types.d.ts +39 -0
  588. package/dist/sdks/@nocha/sdk/dist/places.d.ts +12 -0
  589. package/dist/sdks/@nocha/sdk/dist/player.d.ts +8 -0
  590. package/dist/sdks/@nocha/sdk/dist/profiles-operations.d.ts +54 -0
  591. package/dist/sdks/@nocha/sdk/dist/profiles-types.d.ts +32 -0
  592. package/dist/sdks/@nocha/sdk/dist/profiles.d.ts +17 -0
  593. package/dist/sdks/@nocha/sdk/dist/protocol.d.ts +140 -14
  594. package/dist/sdks/@nocha/sdk/dist/protocol.js +389 -11
  595. package/dist/sdks/@nocha/sdk/dist/screens-operations.d.ts +20 -0
  596. package/dist/sdks/@nocha/sdk/dist/screens-types.d.ts +59 -0
  597. package/dist/sdks/@nocha/sdk/dist/screens.d.ts +16 -0
  598. package/dist/sdks/@nocha/sdk/dist/search-operations.d.ts +434 -0
  599. package/dist/sdks/@nocha/sdk/dist/search-types.d.ts +248 -0
  600. package/dist/sdks/@nocha/sdk/dist/search.d.ts +40 -0
  601. package/dist/sdks/@nocha/sdk/dist/self-hosted.d.ts +66 -0
  602. package/dist/sdks/@nocha/sdk/dist/self-hosted.js +4117 -0
  603. package/dist/sdks/@nocha/sdk/dist/server-chunk-EFI5ST2P.js +134 -0
  604. package/dist/sdks/@nocha/sdk/dist/shared-usage.d.ts +4 -0
  605. package/dist/sdks/@nocha/sdk/dist/shortcut-keys.d.ts +48 -0
  606. package/dist/sdks/@nocha/sdk/dist/spaces-types.d.ts +36 -0
  607. package/dist/sdks/@nocha/sdk/dist/spaces.d.ts +33 -0
  608. package/dist/sdks/@nocha/sdk/dist/speech-rules.d.ts +65 -0
  609. package/dist/sdks/@nocha/sdk/dist/speech-voices.d.ts +87 -0
  610. package/dist/sdks/@nocha/sdk/dist/storage-operation-types.d.ts +11 -3
  611. package/dist/sdks/@nocha/sdk/dist/storage-operations.d.ts +71 -1
  612. package/dist/sdks/@nocha/sdk/dist/storage.d.ts +25 -3
  613. package/dist/sdks/@nocha/sdk/dist/transfer-types.d.ts +220 -0
  614. package/dist/sdks/@nocha/sdk/dist/transfer.d.ts +147 -0
  615. package/dist/sdks/@nocha/sdk/dist/transport.d.ts +7 -6
  616. package/dist/sdks/@nocha/sdk/dist/types/ai-wire.d.ts +342 -15
  617. package/dist/sdks/@nocha/sdk/dist/types/ai.d.ts +13 -3
  618. package/dist/sdks/@nocha/sdk/dist/types/assets-wire.d.ts +48 -2
  619. package/dist/sdks/@nocha/sdk/dist/types/assets.d.ts +34 -14
  620. package/dist/sdks/@nocha/sdk/dist/types/hardware.d.ts +326 -0
  621. package/dist/sdks/@nocha/sdk/dist/types/machine-workspace.d.ts +683 -0
  622. package/dist/sdks/@nocha/sdk/dist/types/machine.d.ts +278 -0
  623. package/dist/sdks/@nocha/sdk/dist/types/storage.d.ts +72 -2
  624. package/dist/sdks/@nocha/sdk/dist/types/video-projects-wire.d.ts +202 -0
  625. package/dist/sdks/@nocha/sdk/dist/types/video-sdk-wire.d.ts +18 -0
  626. package/dist/sdks/@nocha/sdk/dist/types/video-wire.d.ts +7 -0
  627. package/dist/sdks/@nocha/sdk/dist/types/video.d.ts +74 -1
  628. package/dist/sdks/@nocha/sdk/dist/types/voice-wire.d.ts +42 -6
  629. package/dist/sdks/@nocha/sdk/dist/ui-text.d.ts +19 -0
  630. package/dist/sdks/@nocha/sdk/dist/usage-facade.d.ts +2 -1
  631. package/dist/sdks/@nocha/sdk/dist/validate.d.ts +50 -0
  632. package/dist/sdks/@nocha/sdk/dist/video-analysis.d.ts +3 -1
  633. package/dist/sdks/@nocha/sdk/dist/video-operations.d.ts +282 -1
  634. package/dist/sdks/@nocha/sdk/dist/video-presentation.d.ts +54 -0
  635. package/dist/sdks/@nocha/sdk/dist/video-settings-bridge.d.ts +21 -0
  636. package/dist/sdks/@nocha/sdk/dist/video-settings-state.d.ts +59 -0
  637. package/dist/sdks/@nocha/sdk/dist/video-settings-types.d.ts +295 -0
  638. package/dist/sdks/@nocha/sdk/dist/video-settings.d.ts +27 -0
  639. package/dist/sdks/@nocha/sdk/dist/video-workflow-picker.d.ts +24 -0
  640. package/dist/sdks/@nocha/sdk/dist/video-workflow-rules.d.ts +111 -0
  641. package/dist/sdks/@nocha/sdk/dist/viewport-types.d.ts +15 -0
  642. package/dist/sdks/@nocha/sdk/dist/viewport.d.ts +11 -1
  643. package/dist/sdks/@nocha/sdk/dist/vite.js +22 -2
  644. package/dist/sdks/@nocha/sdk/dist/voice-audition.d.ts +37 -0
  645. package/dist/sdks/@nocha/sdk/dist/voice-browser.d.ts +11 -0
  646. package/dist/sdks/@nocha/sdk/dist/voice-favorites-account.d.ts +28 -0
  647. package/dist/sdks/@nocha/sdk/dist/voice-field.d.ts +10 -0
  648. package/dist/sdks/@nocha/sdk/dist/voice-imagine-toggle.d.ts +29 -0
  649. package/dist/sdks/@nocha/sdk/dist/voice-picker-types.d.ts +245 -0
  650. package/dist/sdks/@nocha/sdk/dist/voice-picker.d.ts +17 -0
  651. package/dist/sdks/@nocha/sdk/dist/voice-random.d.ts +51 -0
  652. package/dist/sdks/@nocha/sdk/dist/voice-recovery.d.ts +9 -0
  653. package/dist/sdks/@nocha/sdk/dist/voice.d.ts +5 -2
  654. package/dist/sdks/@nocha/sdk/dist/workspace.d.ts +3 -0
  655. package/dist/sdks/@nocha/sdk/package.json +5 -1
  656. package/dist/sdks/@watchirl/experience-sdk/dist/index.js +1196 -192
  657. package/dist/sdks/@watchirl/experience-sdk/package.json +1 -1
  658. package/dist/watchirl-sdk.js +1193 -189
  659. package/package.json +1 -1
  660. package/dist/references/base/src/types/nocha/access.d.ts +0 -24
  661. package/dist/references/base/src/types/nocha/ai-operations.d.ts +0 -253
  662. package/dist/references/base/src/types/nocha/ai.d.ts +0 -5
  663. package/dist/references/base/src/types/nocha/assets-media.d.ts +0 -8
  664. package/dist/references/base/src/types/nocha/assets-operations.d.ts +0 -106
  665. package/dist/references/base/src/types/nocha/assets.d.ts +0 -5
  666. package/dist/references/base/src/types/nocha/assistant-contract.d.ts +0 -30
  667. package/dist/references/base/src/types/nocha/assistant-controls.d.ts +0 -12
  668. package/dist/references/base/src/types/nocha/assistant.d.ts +0 -58
  669. package/dist/references/base/src/types/nocha/attachments.d.ts +0 -6
  670. package/dist/references/base/src/types/nocha/automations-operations.d.ts +0 -378
  671. package/dist/references/base/src/types/nocha/automations-types.d.ts +0 -157
  672. package/dist/references/base/src/types/nocha/automations.d.ts +0 -28
  673. package/dist/references/base/src/types/nocha/backend-database.d.ts +0 -18
  674. package/dist/references/base/src/types/nocha/backend-operations.d.ts +0 -72
  675. package/dist/references/base/src/types/nocha/backend-requests.d.ts +0 -58
  676. package/dist/references/base/src/types/nocha/backend-runtime.d.ts +0 -107
  677. package/dist/references/base/src/types/nocha/backend-server-error.d.ts +0 -8
  678. package/dist/references/base/src/types/nocha/backend-server-json.d.ts +0 -20
  679. package/dist/references/base/src/types/nocha/backend-server.d.ts +0 -49
  680. package/dist/references/base/src/types/nocha/backend-transactions.d.ts +0 -54
  681. package/dist/references/base/src/types/nocha/backend.d.ts +0 -5
  682. package/dist/references/base/src/types/nocha/bridge.d.ts +0 -7
  683. package/dist/references/base/src/types/nocha/capabilities.d.ts +0 -5
  684. package/dist/references/base/src/types/nocha/capability-deadlines.d.ts +0 -70
  685. package/dist/references/base/src/types/nocha/capability-needs.d.ts +0 -162
  686. package/dist/references/base/src/types/nocha/capability-operations.d.ts +0 -76
  687. package/dist/references/base/src/types/nocha/clipping-types.d.ts +0 -135
  688. package/dist/references/base/src/types/nocha/clipping.d.ts +0 -4
  689. package/dist/references/base/src/types/nocha/connectors-operations.d.ts +0 -104
  690. package/dist/references/base/src/types/nocha/connectors-types.d.ts +0 -11
  691. package/dist/references/base/src/types/nocha/connectors.d.ts +0 -15
  692. package/dist/references/base/src/types/nocha/context.d.ts +0 -19
  693. package/dist/references/base/src/types/nocha/device-operations.d.ts +0 -453
  694. package/dist/references/base/src/types/nocha/device-types.d.ts +0 -54
  695. package/dist/references/base/src/types/nocha/device.d.ts +0 -5
  696. package/dist/references/base/src/types/nocha/drive-operations.d.ts +0 -56
  697. package/dist/references/base/src/types/nocha/drive-types.d.ts +0 -77
  698. package/dist/references/base/src/types/nocha/drive.d.ts +0 -54
  699. package/dist/references/base/src/types/nocha/email-operations.d.ts +0 -31
  700. package/dist/references/base/src/types/nocha/email.d.ts +0 -10
  701. package/dist/references/base/src/types/nocha/error-codes.d.ts +0 -309
  702. package/dist/references/base/src/types/nocha/errors.d.ts +0 -37
  703. package/dist/references/base/src/types/nocha/execution.d.ts +0 -16
  704. package/dist/references/base/src/types/nocha/experience-context-types.d.ts +0 -13
  705. package/dist/references/base/src/types/nocha/experience-context.d.ts +0 -9
  706. package/dist/references/base/src/types/nocha/generation-input.d.ts +0 -16
  707. package/dist/references/base/src/types/nocha/guards.d.ts +0 -13
  708. package/dist/references/base/src/types/nocha/inbox-operations.d.ts +0 -59
  709. package/dist/references/base/src/types/nocha/inbox.d.ts +0 -24
  710. package/dist/references/base/src/types/nocha/listeners.d.ts +0 -5
  711. package/dist/references/base/src/types/nocha/live-media.d.ts +0 -7
  712. package/dist/references/base/src/types/nocha/media-read.d.ts +0 -29
  713. package/dist/references/base/src/types/nocha/multiplayer-facade.d.ts +0 -45
  714. package/dist/references/base/src/types/nocha/multiplayer-operations.d.ts +0 -81
  715. package/dist/references/base/src/types/nocha/multiplayer-subscriptions.d.ts +0 -11
  716. package/dist/references/base/src/types/nocha/multiplayer.d.ts +0 -17
  717. package/dist/references/base/src/types/nocha/navigation.d.ts +0 -17
  718. package/dist/references/base/src/types/nocha/network-operations.d.ts +0 -53
  719. package/dist/references/base/src/types/nocha/network.d.ts +0 -14
  720. package/dist/references/base/src/types/nocha/notifications-operations.d.ts +0 -30
  721. package/dist/references/base/src/types/nocha/notifications.d.ts +0 -10
  722. package/dist/references/base/src/types/nocha/operation-metadata.d.ts +0 -68
  723. package/dist/references/base/src/types/nocha/operation-waiting.d.ts +0 -70
  724. package/dist/references/base/src/types/nocha/operation-wire-types.d.ts +0 -348
  725. package/dist/references/base/src/types/nocha/outirl-operations.d.ts +0 -353
  726. package/dist/references/base/src/types/nocha/outirl.d.ts +0 -32
  727. package/dist/references/base/src/types/nocha/presence-operations.d.ts +0 -25
  728. package/dist/references/base/src/types/nocha/protocol.d.ts +0 -383
  729. package/dist/references/base/src/types/nocha/retry.d.ts +0 -6
  730. package/dist/references/base/src/types/nocha/state.d.ts +0 -14
  731. package/dist/references/base/src/types/nocha/storage-operation-types.d.ts +0 -50
  732. package/dist/references/base/src/types/nocha/storage-operations.d.ts +0 -230
  733. package/dist/references/base/src/types/nocha/storage.d.ts +0 -33
  734. package/dist/references/base/src/types/nocha/transport.d.ts +0 -37
  735. package/dist/references/base/src/types/nocha/types/ai-wire.d.ts +0 -377
  736. package/dist/references/base/src/types/nocha/types/ai.d.ts +0 -21
  737. package/dist/references/base/src/types/nocha/types/assets-wire.d.ts +0 -36
  738. package/dist/references/base/src/types/nocha/types/assets.d.ts +0 -58
  739. package/dist/references/base/src/types/nocha/types/json.d.ts +0 -9
  740. package/dist/references/base/src/types/nocha/types/network.d.ts +0 -17
  741. package/dist/references/base/src/types/nocha/types/outirl.d.ts +0 -327
  742. package/dist/references/base/src/types/nocha/types/storage.d.ts +0 -75
  743. package/dist/references/base/src/types/nocha/types/video-sdk-wire.d.ts +0 -622
  744. package/dist/references/base/src/types/nocha/types/video-wire.d.ts +0 -554
  745. package/dist/references/base/src/types/nocha/types/video.d.ts +0 -168
  746. package/dist/references/base/src/types/nocha/types/voice-wire.d.ts +0 -18
  747. package/dist/references/base/src/types/nocha/video-analysis.d.ts +0 -10
  748. package/dist/references/base/src/types/nocha/video-input.d.ts +0 -16
  749. package/dist/references/base/src/types/nocha/video-media.d.ts +0 -7
  750. package/dist/references/base/src/types/nocha/video-operations.d.ts +0 -647
  751. package/dist/references/base/src/types/nocha/video-playback.d.ts +0 -7
  752. package/dist/references/base/src/types/nocha/video-properties.d.ts +0 -7
  753. package/dist/references/base/src/types/nocha/video-resource.d.ts +0 -6
  754. package/dist/references/base/src/types/nocha/video.d.ts +0 -5
  755. package/dist/references/base/src/types/nocha/viewport-types.d.ts +0 -15
  756. package/dist/references/base/src/types/nocha/viewport.d.ts +0 -8
  757. package/dist/references/base/src/types/nocha/voice.d.ts +0 -14
  758. package/dist/references/base/src/types/nocha/workspace.d.ts +0 -8
  759. package/dist/references/duel/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/README.md +0 -29
  760. package/dist/references/duel/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.d.ts +0 -58
  761. package/dist/references/duel/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.js +0 -332
  762. package/dist/references/duel/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/style.css +0 -80
  763. package/dist/references/duel/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/nocha-vendor.json +0 -17
  764. package/dist/references/duel/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/package.json +0 -21
  765. package/dist/references/duel/src/types/nocha/access.d.ts +0 -24
  766. package/dist/references/duel/src/types/nocha/ai-operations.d.ts +0 -253
  767. package/dist/references/duel/src/types/nocha/ai.d.ts +0 -5
  768. package/dist/references/duel/src/types/nocha/assets-media.d.ts +0 -8
  769. package/dist/references/duel/src/types/nocha/assets-operations.d.ts +0 -106
  770. package/dist/references/duel/src/types/nocha/assets.d.ts +0 -5
  771. package/dist/references/duel/src/types/nocha/assistant-contract.d.ts +0 -30
  772. package/dist/references/duel/src/types/nocha/assistant-controls.d.ts +0 -12
  773. package/dist/references/duel/src/types/nocha/assistant.d.ts +0 -58
  774. package/dist/references/duel/src/types/nocha/attachments.d.ts +0 -6
  775. package/dist/references/duel/src/types/nocha/automations-operations.d.ts +0 -378
  776. package/dist/references/duel/src/types/nocha/automations-types.d.ts +0 -157
  777. package/dist/references/duel/src/types/nocha/automations.d.ts +0 -28
  778. package/dist/references/duel/src/types/nocha/backend-database.d.ts +0 -18
  779. package/dist/references/duel/src/types/nocha/backend-operations.d.ts +0 -72
  780. package/dist/references/duel/src/types/nocha/backend-requests.d.ts +0 -58
  781. package/dist/references/duel/src/types/nocha/backend-runtime.d.ts +0 -107
  782. package/dist/references/duel/src/types/nocha/backend-server-error.d.ts +0 -8
  783. package/dist/references/duel/src/types/nocha/backend-server-json.d.ts +0 -20
  784. package/dist/references/duel/src/types/nocha/backend-server.d.ts +0 -49
  785. package/dist/references/duel/src/types/nocha/backend-transactions.d.ts +0 -54
  786. package/dist/references/duel/src/types/nocha/backend.d.ts +0 -5
  787. package/dist/references/duel/src/types/nocha/bridge.d.ts +0 -7
  788. package/dist/references/duel/src/types/nocha/capabilities.d.ts +0 -5
  789. package/dist/references/duel/src/types/nocha/capability-deadlines.d.ts +0 -70
  790. package/dist/references/duel/src/types/nocha/capability-needs.d.ts +0 -162
  791. package/dist/references/duel/src/types/nocha/capability-operations.d.ts +0 -76
  792. package/dist/references/duel/src/types/nocha/clipping-types.d.ts +0 -135
  793. package/dist/references/duel/src/types/nocha/clipping.d.ts +0 -4
  794. package/dist/references/duel/src/types/nocha/connectors-operations.d.ts +0 -104
  795. package/dist/references/duel/src/types/nocha/connectors-types.d.ts +0 -11
  796. package/dist/references/duel/src/types/nocha/connectors.d.ts +0 -15
  797. package/dist/references/duel/src/types/nocha/context.d.ts +0 -19
  798. package/dist/references/duel/src/types/nocha/device-operations.d.ts +0 -453
  799. package/dist/references/duel/src/types/nocha/device-types.d.ts +0 -54
  800. package/dist/references/duel/src/types/nocha/device.d.ts +0 -5
  801. package/dist/references/duel/src/types/nocha/drive-operations.d.ts +0 -56
  802. package/dist/references/duel/src/types/nocha/drive-types.d.ts +0 -77
  803. package/dist/references/duel/src/types/nocha/drive.d.ts +0 -54
  804. package/dist/references/duel/src/types/nocha/email-operations.d.ts +0 -31
  805. package/dist/references/duel/src/types/nocha/email.d.ts +0 -10
  806. package/dist/references/duel/src/types/nocha/error-codes.d.ts +0 -309
  807. package/dist/references/duel/src/types/nocha/errors.d.ts +0 -37
  808. package/dist/references/duel/src/types/nocha/execution.d.ts +0 -16
  809. package/dist/references/duel/src/types/nocha/experience-context-types.d.ts +0 -13
  810. package/dist/references/duel/src/types/nocha/experience-context.d.ts +0 -9
  811. package/dist/references/duel/src/types/nocha/generation-input.d.ts +0 -16
  812. package/dist/references/duel/src/types/nocha/guards.d.ts +0 -13
  813. package/dist/references/duel/src/types/nocha/inbox-operations.d.ts +0 -59
  814. package/dist/references/duel/src/types/nocha/inbox.d.ts +0 -24
  815. package/dist/references/duel/src/types/nocha/listeners.d.ts +0 -5
  816. package/dist/references/duel/src/types/nocha/live-media.d.ts +0 -7
  817. package/dist/references/duel/src/types/nocha/media-read.d.ts +0 -29
  818. package/dist/references/duel/src/types/nocha/multiplayer-facade.d.ts +0 -45
  819. package/dist/references/duel/src/types/nocha/multiplayer-operations.d.ts +0 -81
  820. package/dist/references/duel/src/types/nocha/multiplayer-subscriptions.d.ts +0 -11
  821. package/dist/references/duel/src/types/nocha/multiplayer.d.ts +0 -17
  822. package/dist/references/duel/src/types/nocha/navigation.d.ts +0 -17
  823. package/dist/references/duel/src/types/nocha/network-operations.d.ts +0 -53
  824. package/dist/references/duel/src/types/nocha/network.d.ts +0 -14
  825. package/dist/references/duel/src/types/nocha/notifications-operations.d.ts +0 -30
  826. package/dist/references/duel/src/types/nocha/notifications.d.ts +0 -10
  827. package/dist/references/duel/src/types/nocha/operation-metadata.d.ts +0 -68
  828. package/dist/references/duel/src/types/nocha/operation-waiting.d.ts +0 -70
  829. package/dist/references/duel/src/types/nocha/operation-wire-types.d.ts +0 -348
  830. package/dist/references/duel/src/types/nocha/outirl-operations.d.ts +0 -353
  831. package/dist/references/duel/src/types/nocha/outirl.d.ts +0 -32
  832. package/dist/references/duel/src/types/nocha/presence-operations.d.ts +0 -25
  833. package/dist/references/duel/src/types/nocha/protocol.d.ts +0 -383
  834. package/dist/references/duel/src/types/nocha/retry.d.ts +0 -6
  835. package/dist/references/duel/src/types/nocha/state.d.ts +0 -14
  836. package/dist/references/duel/src/types/nocha/storage-operation-types.d.ts +0 -50
  837. package/dist/references/duel/src/types/nocha/storage-operations.d.ts +0 -230
  838. package/dist/references/duel/src/types/nocha/storage.d.ts +0 -33
  839. package/dist/references/duel/src/types/nocha/transport.d.ts +0 -37
  840. package/dist/references/duel/src/types/nocha/types/ai-wire.d.ts +0 -377
  841. package/dist/references/duel/src/types/nocha/types/ai.d.ts +0 -21
  842. package/dist/references/duel/src/types/nocha/types/assets-wire.d.ts +0 -36
  843. package/dist/references/duel/src/types/nocha/types/assets.d.ts +0 -58
  844. package/dist/references/duel/src/types/nocha/types/json.d.ts +0 -9
  845. package/dist/references/duel/src/types/nocha/types/network.d.ts +0 -17
  846. package/dist/references/duel/src/types/nocha/types/outirl.d.ts +0 -327
  847. package/dist/references/duel/src/types/nocha/types/storage.d.ts +0 -75
  848. package/dist/references/duel/src/types/nocha/types/video-sdk-wire.d.ts +0 -622
  849. package/dist/references/duel/src/types/nocha/types/video-wire.d.ts +0 -554
  850. package/dist/references/duel/src/types/nocha/types/video.d.ts +0 -168
  851. package/dist/references/duel/src/types/nocha/types/voice-wire.d.ts +0 -18
  852. package/dist/references/duel/src/types/nocha/video-analysis.d.ts +0 -10
  853. package/dist/references/duel/src/types/nocha/video-input.d.ts +0 -16
  854. package/dist/references/duel/src/types/nocha/video-media.d.ts +0 -7
  855. package/dist/references/duel/src/types/nocha/video-operations.d.ts +0 -647
  856. package/dist/references/duel/src/types/nocha/video-playback.d.ts +0 -7
  857. package/dist/references/duel/src/types/nocha/video-properties.d.ts +0 -7
  858. package/dist/references/duel/src/types/nocha/video-resource.d.ts +0 -6
  859. package/dist/references/duel/src/types/nocha/video.d.ts +0 -5
  860. package/dist/references/duel/src/types/nocha/viewport-types.d.ts +0 -15
  861. package/dist/references/duel/src/types/nocha/viewport.d.ts +0 -8
  862. package/dist/references/duel/src/types/nocha/voice.d.ts +0 -14
  863. package/dist/references/duel/src/types/nocha/workspace.d.ts +0 -8
  864. package/dist/references/exploration/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/README.md +0 -29
  865. package/dist/references/exploration/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.d.ts +0 -58
  866. package/dist/references/exploration/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.js +0 -332
  867. package/dist/references/exploration/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/style.css +0 -80
  868. package/dist/references/exploration/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/nocha-vendor.json +0 -17
  869. package/dist/references/exploration/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/package.json +0 -21
  870. package/dist/references/racing/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/README.md +0 -29
  871. package/dist/references/racing/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.d.ts +0 -58
  872. package/dist/references/racing/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.js +0 -332
  873. package/dist/references/racing/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/style.css +0 -80
  874. package/dist/references/racing/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/nocha-vendor.json +0 -17
  875. package/dist/references/racing/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/package.json +0 -21
  876. package/dist/references/recipes/outirl/NOCHA.json +0 -43
  877. package/dist/references/recipes/outirl/README.md +0 -15
  878. package/dist/references/recipes/outirl/SKILL.md +0 -24
  879. package/dist/references/recipes/outirl/recipe.ts +0 -33
  880. package/dist/references/recipes/three-room/src/features/universe-foundation/index.d.ts +0 -30
  881. package/dist/references/recipes/three-room/src/features/universe-foundation/index.js +0 -226
  882. package/dist/references/recipes/three-room/src/features/universe-foundation/style.css +0 -14
  883. package/dist/references/recipes/three-stage/src/features/universe-foundation/index.d.ts +0 -30
  884. package/dist/references/recipes/three-stage/src/features/universe-foundation/index.js +0 -226
  885. package/dist/references/recipes/three-stage/src/features/universe-foundation/style.css +0 -14
  886. package/dist/references/recipes/types/nocha/outirl-operations.d.ts +0 -353
  887. package/dist/references/recipes/types/nocha/outirl.d.ts +0 -32
  888. package/dist/references/recipes/types/nocha/types/outirl.d.ts +0 -327
  889. package/dist/references/shooter/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/README.md +0 -29
  890. package/dist/references/shooter/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.d.ts +0 -58
  891. package/dist/references/shooter/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/index.js +0 -332
  892. package/dist/references/shooter/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/lib/style.css +0 -80
  893. package/dist/references/shooter/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/nocha-vendor.json +0 -17
  894. package/dist/references/shooter/server/vendor/experience-input/0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087/package.json +0 -21
  895. package/dist/references/stage/server/vendor/world-ui/0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b/README.md +0 -37
  896. package/dist/references/stage/server/vendor/world-ui/0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b/lib/pointer.d.ts +0 -82
  897. package/dist/references/stage/server/vendor/world-ui/0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b/lib/pointer.js +0 -273
  898. package/dist/references/stage/server/vendor/world-ui/0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b/lib/types.d.ts +0 -352
  899. package/dist/references/stage/server/vendor/world-ui/0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b/nocha-vendor.json +0 -103
  900. package/dist/references/stage/server/vendor/world-ui/0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b/package.json +0 -24
  901. package/dist/references/stage/src/features/universe-foundation/index.d.ts +0 -30
  902. package/dist/references/stage/src/features/universe-foundation/index.js +0 -226
  903. package/dist/references/stage/src/features/universe-foundation/style.css +0 -14
  904. package/dist/references/stage/src/types/nocha/access.d.ts +0 -24
  905. package/dist/references/stage/src/types/nocha/ai-operations.d.ts +0 -253
  906. package/dist/references/stage/src/types/nocha/ai.d.ts +0 -5
  907. package/dist/references/stage/src/types/nocha/assets-media.d.ts +0 -8
  908. package/dist/references/stage/src/types/nocha/assets-operations.d.ts +0 -106
  909. package/dist/references/stage/src/types/nocha/assets.d.ts +0 -5
  910. package/dist/references/stage/src/types/nocha/assistant-contract.d.ts +0 -30
  911. package/dist/references/stage/src/types/nocha/assistant-controls.d.ts +0 -12
  912. package/dist/references/stage/src/types/nocha/assistant.d.ts +0 -58
  913. package/dist/references/stage/src/types/nocha/attachments.d.ts +0 -6
  914. package/dist/references/stage/src/types/nocha/automations-operations.d.ts +0 -378
  915. package/dist/references/stage/src/types/nocha/automations-types.d.ts +0 -157
  916. package/dist/references/stage/src/types/nocha/automations.d.ts +0 -28
  917. package/dist/references/stage/src/types/nocha/backend-database.d.ts +0 -18
  918. package/dist/references/stage/src/types/nocha/backend-operations.d.ts +0 -72
  919. package/dist/references/stage/src/types/nocha/backend-requests.d.ts +0 -58
  920. package/dist/references/stage/src/types/nocha/backend-runtime.d.ts +0 -107
  921. package/dist/references/stage/src/types/nocha/backend-server-error.d.ts +0 -8
  922. package/dist/references/stage/src/types/nocha/backend-server-json.d.ts +0 -20
  923. package/dist/references/stage/src/types/nocha/backend-server.d.ts +0 -49
  924. package/dist/references/stage/src/types/nocha/backend-transactions.d.ts +0 -54
  925. package/dist/references/stage/src/types/nocha/backend.d.ts +0 -5
  926. package/dist/references/stage/src/types/nocha/bridge.d.ts +0 -7
  927. package/dist/references/stage/src/types/nocha/capabilities.d.ts +0 -5
  928. package/dist/references/stage/src/types/nocha/capability-deadlines.d.ts +0 -70
  929. package/dist/references/stage/src/types/nocha/capability-needs.d.ts +0 -162
  930. package/dist/references/stage/src/types/nocha/capability-operations.d.ts +0 -76
  931. package/dist/references/stage/src/types/nocha/clipping-types.d.ts +0 -135
  932. package/dist/references/stage/src/types/nocha/clipping.d.ts +0 -4
  933. package/dist/references/stage/src/types/nocha/connectors-operations.d.ts +0 -104
  934. package/dist/references/stage/src/types/nocha/connectors-types.d.ts +0 -11
  935. package/dist/references/stage/src/types/nocha/connectors.d.ts +0 -15
  936. package/dist/references/stage/src/types/nocha/context.d.ts +0 -19
  937. package/dist/references/stage/src/types/nocha/device-operations.d.ts +0 -453
  938. package/dist/references/stage/src/types/nocha/device-types.d.ts +0 -54
  939. package/dist/references/stage/src/types/nocha/device.d.ts +0 -5
  940. package/dist/references/stage/src/types/nocha/drive-operations.d.ts +0 -56
  941. package/dist/references/stage/src/types/nocha/drive-types.d.ts +0 -77
  942. package/dist/references/stage/src/types/nocha/drive.d.ts +0 -54
  943. package/dist/references/stage/src/types/nocha/email-operations.d.ts +0 -31
  944. package/dist/references/stage/src/types/nocha/email.d.ts +0 -10
  945. package/dist/references/stage/src/types/nocha/error-codes.d.ts +0 -309
  946. package/dist/references/stage/src/types/nocha/errors.d.ts +0 -37
  947. package/dist/references/stage/src/types/nocha/execution.d.ts +0 -16
  948. package/dist/references/stage/src/types/nocha/experience-context-types.d.ts +0 -13
  949. package/dist/references/stage/src/types/nocha/experience-context.d.ts +0 -9
  950. package/dist/references/stage/src/types/nocha/generation-input.d.ts +0 -16
  951. package/dist/references/stage/src/types/nocha/guards.d.ts +0 -13
  952. package/dist/references/stage/src/types/nocha/inbox-operations.d.ts +0 -59
  953. package/dist/references/stage/src/types/nocha/inbox.d.ts +0 -24
  954. package/dist/references/stage/src/types/nocha/listeners.d.ts +0 -5
  955. package/dist/references/stage/src/types/nocha/live-media.d.ts +0 -7
  956. package/dist/references/stage/src/types/nocha/media-read.d.ts +0 -29
  957. package/dist/references/stage/src/types/nocha/multiplayer-facade.d.ts +0 -45
  958. package/dist/references/stage/src/types/nocha/multiplayer-operations.d.ts +0 -81
  959. package/dist/references/stage/src/types/nocha/multiplayer-subscriptions.d.ts +0 -11
  960. package/dist/references/stage/src/types/nocha/multiplayer.d.ts +0 -17
  961. package/dist/references/stage/src/types/nocha/navigation.d.ts +0 -17
  962. package/dist/references/stage/src/types/nocha/network-operations.d.ts +0 -53
  963. package/dist/references/stage/src/types/nocha/network.d.ts +0 -14
  964. package/dist/references/stage/src/types/nocha/notifications-operations.d.ts +0 -30
  965. package/dist/references/stage/src/types/nocha/notifications.d.ts +0 -10
  966. package/dist/references/stage/src/types/nocha/operation-metadata.d.ts +0 -68
  967. package/dist/references/stage/src/types/nocha/operation-waiting.d.ts +0 -70
  968. package/dist/references/stage/src/types/nocha/operation-wire-types.d.ts +0 -348
  969. package/dist/references/stage/src/types/nocha/outirl-operations.d.ts +0 -353
  970. package/dist/references/stage/src/types/nocha/outirl.d.ts +0 -32
  971. package/dist/references/stage/src/types/nocha/presence-operations.d.ts +0 -25
  972. package/dist/references/stage/src/types/nocha/protocol.d.ts +0 -383
  973. package/dist/references/stage/src/types/nocha/retry.d.ts +0 -6
  974. package/dist/references/stage/src/types/nocha/state.d.ts +0 -14
  975. package/dist/references/stage/src/types/nocha/storage-operation-types.d.ts +0 -50
  976. package/dist/references/stage/src/types/nocha/storage-operations.d.ts +0 -230
  977. package/dist/references/stage/src/types/nocha/storage.d.ts +0 -33
  978. package/dist/references/stage/src/types/nocha/transport.d.ts +0 -37
  979. package/dist/references/stage/src/types/nocha/types/ai-wire.d.ts +0 -377
  980. package/dist/references/stage/src/types/nocha/types/ai.d.ts +0 -21
  981. package/dist/references/stage/src/types/nocha/types/assets-wire.d.ts +0 -36
  982. package/dist/references/stage/src/types/nocha/types/assets.d.ts +0 -58
  983. package/dist/references/stage/src/types/nocha/types/json.d.ts +0 -9
  984. package/dist/references/stage/src/types/nocha/types/network.d.ts +0 -17
  985. package/dist/references/stage/src/types/nocha/types/outirl.d.ts +0 -327
  986. package/dist/references/stage/src/types/nocha/types/storage.d.ts +0 -75
  987. package/dist/references/stage/src/types/nocha/types/video-sdk-wire.d.ts +0 -622
  988. package/dist/references/stage/src/types/nocha/types/video-wire.d.ts +0 -554
  989. package/dist/references/stage/src/types/nocha/types/video.d.ts +0 -168
  990. package/dist/references/stage/src/types/nocha/types/voice-wire.d.ts +0 -18
  991. package/dist/references/stage/src/types/nocha/video-analysis.d.ts +0 -10
  992. package/dist/references/stage/src/types/nocha/video-input.d.ts +0 -16
  993. package/dist/references/stage/src/types/nocha/video-media.d.ts +0 -7
  994. package/dist/references/stage/src/types/nocha/video-operations.d.ts +0 -647
  995. package/dist/references/stage/src/types/nocha/video-playback.d.ts +0 -7
  996. package/dist/references/stage/src/types/nocha/video-properties.d.ts +0 -7
  997. package/dist/references/stage/src/types/nocha/video-resource.d.ts +0 -6
  998. package/dist/references/stage/src/types/nocha/video.d.ts +0 -5
  999. package/dist/references/stage/src/types/nocha/viewport-types.d.ts +0 -15
  1000. package/dist/references/stage/src/types/nocha/viewport.d.ts +0 -8
  1001. package/dist/references/stage/src/types/nocha/voice.d.ts +0 -14
  1002. package/dist/references/stage/src/types/nocha/workspace.d.ts +0 -8
  1003. package/dist/references/workshop/AGENTS.md +0 -40
  1004. package/dist/references/workshop/src/types/nocha/access.d.ts +0 -24
  1005. package/dist/references/workshop/src/types/nocha/ai-operations.d.ts +0 -253
  1006. package/dist/references/workshop/src/types/nocha/ai.d.ts +0 -5
  1007. package/dist/references/workshop/src/types/nocha/assets-media.d.ts +0 -8
  1008. package/dist/references/workshop/src/types/nocha/assets-operations.d.ts +0 -106
  1009. package/dist/references/workshop/src/types/nocha/assets.d.ts +0 -5
  1010. package/dist/references/workshop/src/types/nocha/assistant-contract.d.ts +0 -30
  1011. package/dist/references/workshop/src/types/nocha/assistant-controls.d.ts +0 -12
  1012. package/dist/references/workshop/src/types/nocha/assistant.d.ts +0 -58
  1013. package/dist/references/workshop/src/types/nocha/attachments.d.ts +0 -6
  1014. package/dist/references/workshop/src/types/nocha/automations-operations.d.ts +0 -378
  1015. package/dist/references/workshop/src/types/nocha/automations-types.d.ts +0 -157
  1016. package/dist/references/workshop/src/types/nocha/automations.d.ts +0 -28
  1017. package/dist/references/workshop/src/types/nocha/backend-database.d.ts +0 -18
  1018. package/dist/references/workshop/src/types/nocha/backend-operations.d.ts +0 -72
  1019. package/dist/references/workshop/src/types/nocha/backend-requests.d.ts +0 -58
  1020. package/dist/references/workshop/src/types/nocha/backend-runtime.d.ts +0 -107
  1021. package/dist/references/workshop/src/types/nocha/backend-server-error.d.ts +0 -8
  1022. package/dist/references/workshop/src/types/nocha/backend-server-json.d.ts +0 -20
  1023. package/dist/references/workshop/src/types/nocha/backend-transactions.d.ts +0 -54
  1024. package/dist/references/workshop/src/types/nocha/backend.d.ts +0 -5
  1025. package/dist/references/workshop/src/types/nocha/bridge.d.ts +0 -7
  1026. package/dist/references/workshop/src/types/nocha/capabilities.d.ts +0 -5
  1027. package/dist/references/workshop/src/types/nocha/capability-deadlines.d.ts +0 -70
  1028. package/dist/references/workshop/src/types/nocha/capability-needs.d.ts +0 -162
  1029. package/dist/references/workshop/src/types/nocha/capability-operations.d.ts +0 -76
  1030. package/dist/references/workshop/src/types/nocha/clipping-types.d.ts +0 -135
  1031. package/dist/references/workshop/src/types/nocha/clipping.d.ts +0 -4
  1032. package/dist/references/workshop/src/types/nocha/connectors-operations.d.ts +0 -104
  1033. package/dist/references/workshop/src/types/nocha/connectors-types.d.ts +0 -11
  1034. package/dist/references/workshop/src/types/nocha/connectors.d.ts +0 -15
  1035. package/dist/references/workshop/src/types/nocha/context.d.ts +0 -19
  1036. package/dist/references/workshop/src/types/nocha/device-operations.d.ts +0 -453
  1037. package/dist/references/workshop/src/types/nocha/device-types.d.ts +0 -54
  1038. package/dist/references/workshop/src/types/nocha/device.d.ts +0 -5
  1039. package/dist/references/workshop/src/types/nocha/drive-operations.d.ts +0 -56
  1040. package/dist/references/workshop/src/types/nocha/drive-types.d.ts +0 -77
  1041. package/dist/references/workshop/src/types/nocha/drive.d.ts +0 -54
  1042. package/dist/references/workshop/src/types/nocha/email-operations.d.ts +0 -31
  1043. package/dist/references/workshop/src/types/nocha/email.d.ts +0 -10
  1044. package/dist/references/workshop/src/types/nocha/error-codes.d.ts +0 -309
  1045. package/dist/references/workshop/src/types/nocha/errors.d.ts +0 -37
  1046. package/dist/references/workshop/src/types/nocha/execution.d.ts +0 -16
  1047. package/dist/references/workshop/src/types/nocha/experience-context-types.d.ts +0 -13
  1048. package/dist/references/workshop/src/types/nocha/experience-context.d.ts +0 -9
  1049. package/dist/references/workshop/src/types/nocha/generation-input.d.ts +0 -16
  1050. package/dist/references/workshop/src/types/nocha/guards.d.ts +0 -13
  1051. package/dist/references/workshop/src/types/nocha/inbox-operations.d.ts +0 -59
  1052. package/dist/references/workshop/src/types/nocha/inbox.d.ts +0 -24
  1053. package/dist/references/workshop/src/types/nocha/listeners.d.ts +0 -5
  1054. package/dist/references/workshop/src/types/nocha/live-media.d.ts +0 -7
  1055. package/dist/references/workshop/src/types/nocha/media-read.d.ts +0 -29
  1056. package/dist/references/workshop/src/types/nocha/multiplayer-facade.d.ts +0 -45
  1057. package/dist/references/workshop/src/types/nocha/multiplayer-operations.d.ts +0 -81
  1058. package/dist/references/workshop/src/types/nocha/multiplayer-subscriptions.d.ts +0 -11
  1059. package/dist/references/workshop/src/types/nocha/multiplayer.d.ts +0 -17
  1060. package/dist/references/workshop/src/types/nocha/navigation.d.ts +0 -17
  1061. package/dist/references/workshop/src/types/nocha/network-operations.d.ts +0 -53
  1062. package/dist/references/workshop/src/types/nocha/network.d.ts +0 -14
  1063. package/dist/references/workshop/src/types/nocha/notifications-operations.d.ts +0 -30
  1064. package/dist/references/workshop/src/types/nocha/notifications.d.ts +0 -10
  1065. package/dist/references/workshop/src/types/nocha/operation-metadata.d.ts +0 -68
  1066. package/dist/references/workshop/src/types/nocha/operation-waiting.d.ts +0 -70
  1067. package/dist/references/workshop/src/types/nocha/operation-wire-types.d.ts +0 -348
  1068. package/dist/references/workshop/src/types/nocha/outirl-operations.d.ts +0 -353
  1069. package/dist/references/workshop/src/types/nocha/outirl.d.ts +0 -32
  1070. package/dist/references/workshop/src/types/nocha/presence-operations.d.ts +0 -25
  1071. package/dist/references/workshop/src/types/nocha/protocol.d.ts +0 -383
  1072. package/dist/references/workshop/src/types/nocha/retry.d.ts +0 -6
  1073. package/dist/references/workshop/src/types/nocha/state.d.ts +0 -14
  1074. package/dist/references/workshop/src/types/nocha/storage-operation-types.d.ts +0 -50
  1075. package/dist/references/workshop/src/types/nocha/storage-operations.d.ts +0 -230
  1076. package/dist/references/workshop/src/types/nocha/storage.d.ts +0 -33
  1077. package/dist/references/workshop/src/types/nocha/transport.d.ts +0 -37
  1078. package/dist/references/workshop/src/types/nocha/types/ai-wire.d.ts +0 -377
  1079. package/dist/references/workshop/src/types/nocha/types/ai.d.ts +0 -21
  1080. package/dist/references/workshop/src/types/nocha/types/assets-wire.d.ts +0 -36
  1081. package/dist/references/workshop/src/types/nocha/types/assets.d.ts +0 -58
  1082. package/dist/references/workshop/src/types/nocha/types/json.d.ts +0 -9
  1083. package/dist/references/workshop/src/types/nocha/types/network.d.ts +0 -17
  1084. package/dist/references/workshop/src/types/nocha/types/outirl.d.ts +0 -327
  1085. package/dist/references/workshop/src/types/nocha/types/storage.d.ts +0 -75
  1086. package/dist/references/workshop/src/types/nocha/types/video-sdk-wire.d.ts +0 -622
  1087. package/dist/references/workshop/src/types/nocha/types/video-wire.d.ts +0 -554
  1088. package/dist/references/workshop/src/types/nocha/types/video.d.ts +0 -168
  1089. package/dist/references/workshop/src/types/nocha/types/voice-wire.d.ts +0 -18
  1090. package/dist/references/workshop/src/types/nocha/video-analysis.d.ts +0 -10
  1091. package/dist/references/workshop/src/types/nocha/video-input.d.ts +0 -16
  1092. package/dist/references/workshop/src/types/nocha/video-media.d.ts +0 -7
  1093. package/dist/references/workshop/src/types/nocha/video-operations.d.ts +0 -647
  1094. package/dist/references/workshop/src/types/nocha/video-playback.d.ts +0 -7
  1095. package/dist/references/workshop/src/types/nocha/video-properties.d.ts +0 -7
  1096. package/dist/references/workshop/src/types/nocha/video-resource.d.ts +0 -6
  1097. package/dist/references/workshop/src/types/nocha/video.d.ts +0 -5
  1098. package/dist/references/workshop/src/types/nocha/viewport-types.d.ts +0 -15
  1099. package/dist/references/workshop/src/types/nocha/viewport.d.ts +0 -8
  1100. package/dist/references/workshop/src/types/nocha/voice.d.ts +0 -14
  1101. package/dist/references/workshop/src/types/nocha/workspace.d.ts +0 -8
  1102. package/dist/sdks/@nocha/sdk/dist/chunk-4AHRR2WX.js +0 -120
  1103. package/dist/sdks/@nocha/sdk/dist/chunk-7SH7NNX6.js +0 -231
  1104. package/dist/sdks/@nocha/sdk/dist/chunk-B34FPFNB.js +0 -26
  1105. package/dist/sdks/@nocha/sdk/dist/chunk-EAC27UOG.js +0 -2120
  1106. package/dist/sdks/@nocha/sdk/dist/outirl-operations.d.ts +0 -352
  1107. package/dist/sdks/@nocha/sdk/dist/outirl.d.ts +0 -31
  1108. package/dist/sdks/@nocha/sdk/dist/server-chunk-ZTA43KOG.js +0 -121
  1109. package/dist/sdks/@nocha/sdk/dist/types/outirl.d.ts +0 -326
  1110. /package/dist/references/duel/server/vendor/experience-input/{0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087 → 0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c}/LICENSE +0 -0
  1111. /package/dist/references/exploration/server/vendor/experience-input/{0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087 → 0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c}/LICENSE +0 -0
  1112. /package/dist/references/racing/server/vendor/experience-input/{0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087 → 0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c}/LICENSE +0 -0
  1113. /package/dist/references/shooter/server/vendor/experience-input/{0.2.2-2afef667ed23d6cdeb8dda34c3d2f183e54c4f4447ec960b624d7b5921c0c087 → 0.2.4-e760060497535b002d4934c04ec40e13bdcbe03f2d303932fa42a7b301d40b7c}/LICENSE +0 -0
  1114. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/LICENSE +0 -0
  1115. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/canvas2d.d.ts +0 -0
  1116. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/canvas2d.js +0 -0
  1117. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/context.d.ts +0 -0
  1118. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/context.js +0 -0
  1119. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/dialog.d.ts +0 -0
  1120. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/dialog.js +0 -0
  1121. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/edit-bar.d.ts +0 -0
  1122. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/edit-bar.js +0 -0
  1123. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/environment.d.ts +0 -0
  1124. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/environment.js +0 -0
  1125. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/fields.d.ts +0 -0
  1126. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/fields.js +0 -0
  1127. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/focus.d.ts +0 -0
  1128. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/focus.js +0 -0
  1129. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/index.d.ts +0 -0
  1130. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/index.js +0 -0
  1131. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/keys.d.ts +0 -0
  1132. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/keys.js +0 -0
  1133. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/layout.d.ts +0 -0
  1134. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/layout.js +0 -0
  1135. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/mirror.d.ts +0 -0
  1136. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/mirror.js +0 -0
  1137. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/motion.d.ts +0 -0
  1138. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/motion.js +0 -0
  1139. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/navigation.d.ts +0 -0
  1140. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/navigation.js +0 -0
  1141. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/options-diff.d.ts +0 -0
  1142. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/options-diff.js +0 -0
  1143. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-geometry.d.ts +0 -0
  1144. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-geometry.js +0 -0
  1145. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-layout.d.ts +0 -0
  1146. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-layout.js +0 -0
  1147. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-place.d.ts +0 -0
  1148. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-place.js +0 -0
  1149. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-scroll.d.ts +0 -0
  1150. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel-scroll.js +0 -0
  1151. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel.d.ts +0 -0
  1152. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/panel.js +0 -0
  1153. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/picker.d.ts +0 -0
  1154. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/picker.js +0 -0
  1155. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/picture.d.ts +0 -0
  1156. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/picture.js +0 -0
  1157. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/scroll-guard.d.ts +0 -0
  1158. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/scroll-guard.js +0 -0
  1159. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/stacking.d.ts +0 -0
  1160. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/stacking.js +0 -0
  1161. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/style.css +0 -0
  1162. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/surface.d.ts +0 -0
  1163. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/surface.js +0 -0
  1164. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/theme.d.ts +0 -0
  1165. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/theme.js +0 -0
  1166. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/types.js +0 -0
  1167. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b/lib/widget-types.js → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f/lib/viewport.js} +0 -0
  1168. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widget-types.d.ts +0 -0
  1169. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widget.d.ts +0 -0
  1170. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widget.js +0 -0
  1171. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/button-face.d.ts +0 -0
  1172. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/button-face.js +0 -0
  1173. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/button.d.ts +0 -0
  1174. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/button.js +0 -0
  1175. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/card-face.d.ts +0 -0
  1176. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/card-face.js +0 -0
  1177. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/choice.d.ts +0 -0
  1178. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/choice.js +0 -0
  1179. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/field-paint.d.ts +0 -0
  1180. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/field-paint.js +0 -0
  1181. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/file-button.d.ts +0 -0
  1182. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/file-button.js +0 -0
  1183. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/image.d.ts +0 -0
  1184. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/image.js +0 -0
  1185. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/label.d.ts +0 -0
  1186. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/label.js +0 -0
  1187. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/link.d.ts +0 -0
  1188. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/link.js +0 -0
  1189. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/progress.d.ts +0 -0
  1190. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/progress.js +0 -0
  1191. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/slider.d.ts +0 -0
  1192. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/slider.js +0 -0
  1193. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/text-field.d.ts +0 -0
  1194. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/text-field.js +0 -0
  1195. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/toggle.d.ts +0 -0
  1196. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/toggle.js +0 -0
  1197. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/video.d.ts +0 -0
  1198. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/widgets/video.js +0 -0
  1199. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/world-ui.d.ts +0 -0
  1200. /package/dist/references/stage/server/vendor/world-ui/{0.5.2-4a57a5904f77c0abfd1833815b3981b6385821c2a14039dc4acb3bf65599908b → 0.6.1-691896a7efb9060c8a26f17a92e146757e3f12b47dc8e36bf9bf0ae43184f58f}/lib/world-ui.js +0 -0
@@ -2,7 +2,7 @@
2
2
  import { join } from "node:path";
3
3
 
4
4
  // nocha:browser-source
5
- var nochaBrowserSdkSource = '// src/error-codes.ts\nvar D = "denied";\nvar B = "billing";\nvar T = "transient";\nvar A = "aborted";\nvar I = "invalid";\nvar U = "unknown";\nvar nochaErrorClasses = {\n // SDK\n bridge_unavailable: D,\n usage_required: I,\n invalid_request: I,\n invalid_result: U,\n invocation_timed_out: T,\n aborted: A,\n invocation_failed: U,\n unknown_error: U,\n navigation_unavailable: D,\n navigation_timed_out: T,\n user_action_required: D,\n upload_failed: U,\n upload_interrupted: T,\n source_too_large: I,\n // Web and native hosts\n client_update_required: D,\n capability_denied: D,\n request_cancelled: A,\n experience_inactive: T,\n public_control_consent_required: D,\n request_failed: U,\n invalid_response: U,\n multiplayer_unavailable: T,\n rate_limited: T,\n multiplayer_receipt_missing: T,\n multiplayer_receipt_unsupported: D,\n multiplayer_receipt_backlog: I,\n multiplayer_receipt_invalid: U,\n voice_host_unavailable: D,\n native_host_required: D,\n device_inactive: A,\n device_permission_denied: D,\n device_unavailable: D,\n device_busy: T,\n device_timeout: T,\n device_limit: I,\n device_limit_exceeded: I,\n device_media_size: I,\n device_operation_unknown: I,\n device_invalid_request: I,\n // Nocha API behind the reader\n unauthorized: D,\n identity_required: D,\n service_unavailable: T,\n internal_error: T,\n not_found: I,\n not_ready: D,\n playback_unavailable: D,\n experience_unpublished: T,\n playback_changed: D,\n playback_temporarily_unavailable: T,\n runtime_unavailable: T,\n authentication_required: D,\n public_read_denied: D,\n review_unavailable: D,\n workspace_access_denied: D,\n workspace_revoked: D,\n workspace_context_required: D,\n workspace_selection_invalid: I,\n data_contract_incompatible: D,\n public_control_denied: D,\n review_external_integration_unavailable: D,\n revision_schema_unsupported: D,\n usage_unknown: I,\n usage_operation_denied: I,\n usage_resource_denied: I,\n usage_scope_denied: I,\n usage_cap_exceeded: B,\n usage_public_read_denied: D,\n usage_public_control_denied: D,\n // Storage\n // `*_full`: the workspace budget is reached (free keys or records); `*_too_large`: one value exceeds its own limit.\n state_conflict: I,\n conflict: I,\n memory_conflict: I,\n database_conflict: I,\n idempotency_conflict: I,\n memory_full: I,\n database_full: I,\n memory_value_too_large: I,\n database_record_too_large: I,\n database_insert_limit: I,\n database_unavailable: T,\n // Backend pilot: an unknown outcome/deadline requires receipt reconciliation, never blind retry.\n backend_unavailable: T,\n backend_capacity_exceeded: T,\n backend_budget_exhausted: D,\n backend_route_unknown: I,\n backend_usage_denied: D,\n backend_resource_protected: D,\n backend_paid_capability_denied: D,\n backend_input_invalid: I,\n backend_output_invalid: U,\n backend_deadline_exceeded: U,\n backend_outcome_unknown: U,\n backend_revision_required: D,\n // Personal connected accounts\n connector_not_granted: D,\n connector_scope_missing: D,\n connector_reauthorization_required: D,\n connector_unavailable: T,\n connectors_unavailable: T,\n connector_failed: I,\n connector_uncertain: U,\n connector_confirmation_required: D,\n quota_exceeded: T,\n // Managed network\n network_unavailable: T,\n network_declaration_required: I,\n network_revision_required: D,\n network_method_denied: I,\n network_path_invalid: I,\n network_body_invalid: I,\n network_asset_integrity: U,\n network_outcome_unknown: U,\n network_access_denied: D,\n network_rate_limited: T,\n network_destination_invalid: I,\n network_destination_private: I,\n network_redirect_denied: I,\n network_response_too_large: I,\n network_timeout: U,\n network_transport_failed: U,\n // Notifications sent to a player\n notifications_unavailable: D,\n notifications_disabled: D,\n notifications_rate_limited: T,\n notifications_not_declared: I,\n // Triggers, automations and the experience inbox\n inbox_unavailable: D,\n inbox_full: I,\n inbox_event_not_found: I,\n trigger_not_found: I,\n trigger_disabled: D,\n trigger_limit_reached: I,\n trigger_managed_by_mail: I,\n trigger_slug_taken: I,\n workspace_unavailable: I,\n automation_schedule_invalid: I,\n automation_rate_limited: T,\n // The person\'s Drive, through the host dialog: `sign_in_required` asks a visitor to sign in first;\n // `drive_unavailable` names a host without the Drive (nocha dev, a standalone page).\n drive_unavailable: D,\n sign_in_required: D,\n drive_forbidden: D,\n drive_not_found: I,\n drive_name_conflict: I,\n drive_invalid_name: I,\n drive_unsupported_type: I,\n drive_upload_expired: T,\n drive_file_too_large: I,\n // Experience mail\n mail_unavailable: D,\n mail_disabled: D,\n mail_recipient_not_allowed: I,\n mail_reply_expired: I,\n mail_too_large: I,\n mail_rate_limited: T,\n mail_sender_not_allowed: D,\n mail_send_failed: U,\n mail_workspace_not_allowed: I,\n // Automation allowance and overage billing\n automation_allowance_exhausted: B,\n automation_billing_blocked: B,\n // Declarative workflows (`automations`): activation, effectful tests and publication need the host\'s confirmation\n automations_unavailable: T,\n workflow_host_confirmation_required: D,\n workflow_published_revision_required: D,\n workflow_account_required: D,\n workflow_limit_reached: B,\n workflow_version_conflict: I,\n workflow_consent_expired: I,\n workflow_invalid: I,\n // Developer API keys\n api_key_not_allowed: D,\n api_key_scope_denied: D,\n api_key_experience_denied: D,\n api_key_expired: D,\n api_key_revoked: D,\n api_key_watchirl_unavailable: D,\n api_key_limit_reached: I,\n // AI and spending\n experience_authorization_required: B,\n experience_cap_exhausted: B,\n credit_exhausted: B,\n review_budget_exhausted: B,\n review_spending_not_authorized: B,\n generation_quote_expired: B,\n generation_quote_conflict: B,\n spend_settlement_conflict: B,\n spend_reconciliation_required: B,\n spend_authorization_pending: B,\n participant_daily_cap_reached: B,\n paid_consent_required: B,\n spend_journal_failed: U,\n spend_busy: T,\n intelligence_unavailable: T,\n generation_paused: T,\n pricing_unavailable: T,\n generation_estimate_unavailable: T,\n generation_options_unavailable: T,\n data_consent_unavailable: T,\n generation_failed: U,\n generation_budget_exceeded: I,\n operation_retired: I,\n generation_effort_conflict: I,\n generation_effort_unavailable: I,\n generation_policy_required: I,\n // Speech model and voice selection: refused before any operation or charge\n model_unavailable: I,\n voice_unavailable: I,\n generation_model_conflict: I,\n generation_usage_unknown: I,\n generation_not_found: I,\n generation_request_conflict: I,\n spend_request_conflict: I,\n media_idempotency_conflict: I,\n realtime_in_progress: I,\n experience_revision_changed: D,\n // Media\n media_unavailable: T,\n media_usage_required: I,\n media_usage_denied: D,\n media_access_denied: D,\n media_retention_denied: D,\n media_reference_denied: D,\n media_not_found: I,\n media_recovery_required: D,\n media_too_large: I,\n media_reference_too_large: I,\n media_unsupported: I,\n media_reference_unsupported: I,\n media_invalid_resource: U,\n media_resource_conflict: I,\n erasure_changed: I,\n media_unsupported_host: D,\n playback_unsupported_host: D,\n video_recovery_unavailable: T,\n video_request_refused: D,\n video_recovery_required: D,\n // Video\n video_unavailable: T,\n video_connection_required: D,\n video_media_unauthorized: D,\n video_media_unavailable: T,\n video_invalid_response: U,\n video_generation_not_found: I,\n video_not_ready: T,\n video_request_failed: T,\n video_data_unavailable: T,\n video_connection_unavailable: T,\n clipping_unavailable: T,\n clipping_not_found: I,\n invalid_media_usage: I,\n provider_unavailable: T,\n studio_references_unavailable: T,\n media_reference_copy_unavailable: T,\n creator_attribution_unavailable: T,\n transfers_unavailable: T,\n video_consent_required: B,\n video_project_payer_unsupported: D,\n workflow_unknown: I,\n workflow_unsupported: I,\n // Outirl\n outirl_unavailable: T,\n outirl_invalid_response: U,\n outirl_owner_required: D,\n outirl_connection_required: D,\n outirl_hue_connection_required: D,\n outirl_leds_connection_required: D,\n outirl_audio_connection_required: D,\n outirl_connection_changed: D,\n outirl_access_revoked: D,\n outirl_access_denied: D,\n outirl_device_denied: D,\n outirl_host_unavailable: D,\n outirl_agent_incompatible: D,\n outirl_hue_setup_required: D,\n outirl_audio_setup_required: D,\n outirl_audio_transcription_denied: D,\n outirl_audio_quota_exceeded: B,\n outirl_invalid_request: I,\n outirl_audio_capture_not_found: I,\n outirl_audio_device_not_found: I,\n outirl_audio_busy: I,\n outirl_rate_limited: T,\n outirl_host_offline: T,\n outirl_leds_unreachable: T,\n outirl_hue_network: T,\n outirl_hue_unavailable: T,\n outirl_device_service_unavailable: T,\n outirl_audio_unreachable: T,\n outirl_audio_unavailable: T,\n outirl_audio_transcription_unavailable: T,\n outirl_audio_source_missing: D,\n outirl_audio_format_unsupported: D,\n outirl_desktop_connection_required: D,\n DESKTOP_DISABLED: D,\n DESKTOP_UNSUPPORTED_PLATFORM: D,\n DESKTOP_AUTOMATION_DENIED: D,\n DESKTOP_TERMINAL_UNAVAILABLE: T,\n DESKTOP_AGENT_UNKNOWN: I,\n DESKTOP_DICTATION_UNAVAILABLE: T,\n DESKTOP_COMMAND_FAILED: U,\n // Local development (nocha dev)\n development_unavailable: T,\n development_expired: T,\n request_timeout: T,\n topic_limit: I\n};\nfunction isNochaErrorCode(value) {\n return typeof value === "string" && Object.hasOwn(nochaErrorClasses, value);\n}\nvar experienceBackendErrorCodes = [\n "invalid_request",\n "identity_required",\n "workspace_access_denied",\n "usage_unknown",\n "usage_operation_denied",\n "usage_resource_denied",\n "idempotency_conflict",\n "database_conflict",\n "backend_unavailable",\n "backend_capacity_exceeded",\n "backend_budget_exhausted",\n "backend_route_unknown",\n "backend_usage_denied",\n "backend_resource_protected",\n "backend_paid_capability_denied",\n "backend_input_invalid",\n "backend_output_invalid",\n "backend_deadline_exceeded",\n "backend_outcome_unknown",\n "backend_revision_required"\n];\n\n// src/errors.ts\nvar genericCodes = /* @__PURE__ */ new Set(["invocation_failed", "request_failed", "unknown_error"]);\nvar hostRetryable = /* @__PURE__ */ new WeakMap();\nvar NochaError = class extends Error {\n code;\n wireCode;\n trace_id;\n correlation_id;\n operation_id;\n idempotency_key;\n details;\n constructor(code, message, metadata = {}) {\n super(message);\n this.name = "NochaError";\n const known = isNochaErrorCode(code);\n this.code = known ? code : "unknown_error";\n const wireCode = metadata.wireCode ?? (known ? void 0 : String(code));\n if (wireCode !== void 0 && wireCode !== this.code) this.wireCode = wireCode;\n if (metadata.trace_id !== void 0) this.trace_id = metadata.trace_id;\n if (metadata.correlation_id !== void 0) this.correlation_id = metadata.correlation_id;\n if (metadata.operation_id !== void 0) this.operation_id = metadata.operation_id;\n if (metadata.idempotency_key !== void 0) this.idempotency_key = metadata.idempotency_key;\n if (metadata.details !== void 0) this.details = Object.freeze({ ...metadata.details });\n hostRetryable.set(this, metadata.retryable === true);\n }\n /** True when retrying later, with the same idempotency key, can succeed. */\n get retryable() {\n return classifyError(this) === "transient";\n }\n};\nfunction isNochaError(value) {\n return value instanceof NochaError || value instanceof Error && value.name === "NochaError" && typeof value.code === "string";\n}\nfunction classifyError(error) {\n if (!isNochaError(error)) {\n return error !== null && typeof error === "object" && error.name === "AbortError" ? "aborted" : "unknown";\n }\n const code = isNochaErrorCode(error.code) ? error.code : "unknown_error";\n if (genericCodes.has(code)) return hostRetryable.get(error) === true ? "transient" : "unknown";\n return nochaErrorClasses[code];\n}\nfunction wireError(value, fallback = { code: "invocation_failed", message: "Nocha invocation failed" }) {\n const error = value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};\n const raw = typeof error.code === "string" && error.code ? error.code : fallback.code;\n const known = isNochaErrorCode(raw);\n return new NochaError(known ? raw : "unknown_error", typeof error.message === "string" ? error.message : fallback.message, {\n retryable: error.retryable === true,\n ...known ? {} : { wireCode: raw },\n ...typeof error.trace_id === "string" ? { trace_id: error.trace_id } : {},\n ...typeof error.correlation_id === "string" ? { correlation_id: error.correlation_id } : {},\n ...error.details !== null && typeof error.details === "object" && !Array.isArray(error.details) ? { details: error.details } : {}\n });\n}\n\n// src/guards.ts\nvar isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);\nvar isString = (value) => typeof value === "string";\nvar isNonEmptyString = (value) => typeof value === "string" && value.length > 0;\nvar isBoolean = (value) => typeof value === "boolean";\nvar isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);\nvar isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\nvar isNullable = (value, check) => value === null || check(value);\nvar isUuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);\nvar isBase64 = (value) => typeof value === "string" && /^[A-Za-z0-9+/]*={0,2}$/.test(value);\nvar isArrayOf = (value, check) => Array.isArray(value) && value.every(check);\n\n// src/automations.ts\nfunction createAutomations(context) {\n const invoke = async (operation2, input3, list2, options) => {\n const value = await context.invoke("automations", operation2, input3, options);\n if (list2 ? !Array.isArray(value) : !isRecord(value)) throw new NochaError("invalid_result", "Nocha returned an invalid workflow result");\n return value;\n };\n return {\n catalog: (options) => invoke("catalog", {}, false, options),\n list: (options) => invoke("list", {}, true, options),\n get: (id, options) => invoke("get", { id }, false, options),\n create: (input3, options) => invoke("create", input3, false, options),\n save: (id, input3, options) => invoke("save", { id, ...input3 }, false, options),\n validate: (graph, options) => invoke("validate", { graph }, true, options),\n remove: (id, options) => invoke("remove", { id }, false, options),\n activate: (id, options) => invoke("activate", { id }, false, options),\n pause: (id, options) => invoke("pause", { id }, false, options),\n test: (id, input3, options) => invoke("test", { id, ...input3 }, false, options),\n runs: (id, input3 = {}, options) => invoke("runs", { id, ...input3 }, true, options),\n run: (runId, options) => invoke("run", { id: runId }, false, options),\n templates: {\n list: (options) => invoke("templates.list", {}, true, options),\n publish: (id, input3, options) => invoke("templates.publish", { id, ...input3 }, false, options),\n use: (templateId, input3, options) => invoke("templates.use", { id: templateId, ...input3 }, false, options)\n }\n };\n}\n\n// src/listeners.ts\nfunction notifyListener(listener, value) {\n try {\n listener(value);\n } catch (error) {\n console.error("Nocha listener failed", error);\n }\n}\nvar warned = /* @__PURE__ */ new Set();\nfunction warnOnce(kind, message) {\n if (warned.has(kind)) return;\n warned.add(kind);\n console.warn(`Nocha ignored ${kind}: ${message}`);\n}\n\n// src/experience-context-types.ts\nfunction isExperienceContext(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const device = value.device;\n if (!device || typeof device !== "object" || Array.isArray(device)) return false;\n const { type, platform, sessionId } = device;\n return typeof type === "string" && ["phone", "tablet", "desktop", "unknown"].includes(type) && typeof platform === "string" && ["ios", "android", "web"].includes(platform) && typeof sessionId === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(sessionId);\n}\n\n// src/operation-waiting.ts\nvar operationWaiting = {\n default: 15e3,\n access: { request: 3e5 },\n // One multiplayer call may refresh credentials, connect (20 s) then run a command (10 s).\n multiplayer: { default: 35e3 },\n // HTTPS transport 10 s plus two revision checks and the idempotency receipt.\n network: { default: 2e4 },\n // Attachment uploads stream up to 64 MiB through the host. assets.media is not an operation: its host acknowledges at\n // once, asks assets.read for a read grant, then reads at most 64 MiB and stops any read after 15 minutes.\n assets: { default: 6e4, uploadAttachment: 10 * 6e4, media: 10 * 6e4, "media.firstReply": 15e3 },\n // video.media is not an operation: its host acknowledges at once, calls video.get, then streams at most\n // 256 MiB and stops any read after 15 minutes.\n video: { default: 3e4, "clipping.uploadSource": 31 * 6e4, media: 10 * 6e4, "media.firstReply": 15e3 },\n // Outirl Host calls: 25 s, transcription 150 s.\n outirl: { default: 35e3, "audio.transcribe": 165e3 },\n // decide: 8 s provider deadline plus up to 5 s settlement; voice.start waits for host consent.\n ai: { default: 3e4, decide: 2e4, "voice.start": 12e4, "voice.state": 15e3 },\n // Device operations may wait for a consent sheet or a system picker.\n device: {\n default: 18e4,\n availability: 15e3,\n "haptics.trigger": 15e3,\n "haptics.pattern": 15e3,\n "haptics.stop": 15e3,\n "camera.stream": 3e5,\n "microphone.stream": 3e5,\n "motion.unsubscribe": 15e3,\n "notifications.list": 15e3,\n "notifications.cancel": 15e3,\n "alarms.list": 15e3,\n "alarms.cancel": 15e3\n },\n // Consent resolution and the queued request, without waiting for any device delivery.\n notifications: { default: 2e4 },\n // The person chooses in the host\'s Drive dialog (up to 3 minutes), then the host moves up to 64 MiB.\n drive: { default: 18e4, save: 13 * 6e4, pick: 13 * 6e4, "pick.firstReply": 15e3 },\n // One bounded page of the workspace inbox, or an acknowledgement.\n inbox: { default: 15e3 },\n // Recipient resolution, metering and the queued message, without waiting for delivery.\n email: { default: 2e4 },\n navigation: { connect: 15e3, command: 15e3 }\n};\n\n// src/storage-operations.ts\nvar common = { spend: "none", deadlineMs: null, sdkMarginMs: null, sdkTimeoutMs: operationWaiting.default, rateBucket: "public-playback" };\nvar read = { ...common, access: "read", observer: "declared-public-read", publicRead: "eligible", idempotency: "read" };\nvar write = { ...common, access: "contribute", observer: "denied", publicRead: "denied" };\nvar storageOperations = {\n state: {\n get: {\n ...read,\n capability: "state",\n operation: "get",\n input: "StateGetInput",\n output: "StateSnapshot",\n resource: null,\n facades: [{ path: "state.get", kind: "direct" }, { path: "state.watch", kind: "composite", live: "state" }]\n },\n set: {\n ...write,\n capability: "state",\n operation: "set",\n input: "StateSetInput",\n output: "StateSnapshot",\n resource: null,\n idempotency: "durable-receipt",\n facades: [{ path: "state.set", kind: "direct" }]\n }\n },\n memory: {\n get: {\n ...read,\n capability: "memory",\n operation: "get",\n input: "MemoryGetInput",\n output: "MemoryValue",\n resource: "key",\n facades: [{ path: "memory.get", kind: "direct" }]\n },\n set: {\n ...write,\n capability: "memory",\n operation: "set",\n input: "MemorySetInput",\n output: "MemoryValue",\n resource: "key",\n idempotency: "compare-and-set",\n facades: [{ path: "memory.set", kind: "direct" }]\n }\n },\n database: {\n insert: {\n ...write,\n capability: "database",\n operation: "insert",\n input: "DatabaseInsertInput",\n output: "DatabaseInsertOutput",\n resource: "collection",\n idempotency: "durable-receipt",\n facades: [{ path: "database.insert", kind: "direct" }]\n },\n get: {\n ...read,\n capability: "database",\n operation: "get",\n input: "DatabaseGetInput",\n output: "DatabaseGetOutput",\n resource: "collection",\n facades: [{ path: "database.get", kind: "direct" }]\n },\n query: {\n ...read,\n capability: "database",\n operation: "query",\n input: "DatabaseQueryInput",\n output: "DatabaseQueryOutput",\n resource: "collection",\n facades: [{ path: "database.query", kind: "direct" }]\n },\n update: {\n ...write,\n capability: "database",\n operation: "update",\n input: "DatabaseUpdateInput",\n output: "DatabaseUpdateOutput",\n resource: "collection",\n idempotency: "compare-and-set",\n facades: [{ path: "database.update", kind: "direct" }]\n },\n remove: {\n ...write,\n capability: "database",\n operation: "remove",\n input: "DatabaseRemoveInput",\n output: "DatabaseRemoveOutput",\n resource: "collection",\n idempotency: "compare-and-set",\n facades: [{ path: "database.remove", kind: "direct" }]\n },\n // Server-only final commit. There is no frontend facade or single top-level resource.\n transact: {\n ...write,\n capability: "database",\n operation: "transact",\n input: "BackendTransactionInput",\n output: "BackendTransactionCommitResult",\n resource: null,\n idempotency: "durable-receipt",\n facades: []\n }\n }\n};\nvar storageCapabilities = Object.keys(storageOperations);\nvar storageOperationList = Object.values(storageOperations).flatMap((group) => Object.values(group));\nvar storageReadOperations = storageOperationList.filter((item) => item.access === "read");\nvar databaseOperations = [\n storageOperations.database.insert.operation,\n storageOperations.database.get.operation,\n storageOperations.database.query.operation,\n storageOperations.database.update.operation,\n storageOperations.database.remove.operation,\n storageOperations.database.transact.operation\n];\nvar stateOperations = Object.values(storageOperations.state).map((item) => item.operation);\nvar memoryOperations = Object.values(storageOperations.memory).map((item) => item.operation);\n\n// src/types/video-wire.ts\nvar tripirlVideoLocales = ["fr-FR", "en-US", "es-ES", "de-DE", "it-IT", "pt-PT", "nl-NL", "pl-PL", "sv-SE", "da-DK", "nb-NO", "fi-FI", "cs-CZ", "sk-SK", "hr-HR", "bg-BG", "ro-RO", "hu-HU", "el-GR", "ru-RU", "uk-UA", "tr-TR", "ar-SA", "hi-IN", "ta-IN", "id-ID", "ms-MY", "vi-VN", "zh-CN", "ja-JP", "ko-KR", "th-TH"];\n\n// src/types/video-sdk-wire.ts\nvar videoLocales = tripirlVideoLocales;\n\n// src/video-properties.ts\nvar videoStepIdPattern = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\nvar finite = (value) => typeof value === "number" && Number.isFinite(value);\nfunction propertyValue(value, depth = 0) {\n if (depth > 32) return void 0;\n if (value === null || typeof value === "string" || typeof value === "boolean" || finite(value)) return value;\n if (Array.isArray(value)) {\n const parsed2 = value.map((item) => propertyValue(item, depth + 1));\n return parsed2.some((item) => item === void 0) ? void 0 : parsed2;\n }\n if (!isRecord(value)) return void 0;\n const parsed = Object.entries(value).map(([key, item]) => [key, propertyValue(item, depth + 1)]);\n return parsed.some(([, item]) => item === void 0) ? void 0 : Object.fromEntries(parsed);\n}\nfunction propertyMap(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => {\n const parsed = propertyValue(item);\n return parsed === void 0 ? [] : [[key, parsed]];\n }));\n}\nfunction readVideoProperties(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([step2, values]) => {\n const parsed = videoStepIdPattern.test(step2) ? propertyMap(values) : void 0;\n return parsed === void 0 ? [] : [[step2, parsed]];\n }));\n}\nfunction readEffectiveVideoProperties(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([step2, block]) => {\n if (!videoStepIdPattern.test(step2) || !isRecord(block) || !isRecord(block.module) || typeof block.module.id !== "string" || !Number.isSafeInteger(block.module.revision) || Number(block.module.revision) <= 0) return [];\n const values = propertyMap(block.values);\n return values === void 0 ? [] : [[step2, { module: { id: block.module.id, revision: block.module.revision }, values }]];\n }));\n}\nfunction readVideoPropertyDefinition(value, depth = 0) {\n if (depth > 32 || !isRecord(value) || typeof value.key !== "string") return null;\n const effect = value.cost_effect;\n if (effect !== "none" && effect !== "may_change_quantity" && effect !== "may_change_unit_price" && effect !== "may_change_route") return null;\n const defaultValue = propertyValue(value.default);\n if (defaultValue === void 0) return null;\n const base2 = { key: value.key, cost_effect: effect, default: defaultValue };\n if (value.type === "boolean" && value.constraints === null) return { ...base2, type: "boolean", constraints: null };\n if (!isRecord(value.constraints)) return null;\n const constraints = value.constraints;\n if (value.type === "integer" || value.type === "number") {\n return { ...base2, type: value.type, constraints: Object.fromEntries(["minimum", "maximum", "step"].flatMap((key) => finite(constraints[key]) ? [[key, constraints[key]]] : [])) };\n }\n if (value.type === "string") return { ...base2, type: "string", constraints: Number.isSafeInteger(constraints.max_length) && Number(constraints.max_length) > 0 ? { max_length: constraints.max_length } : {} };\n if (value.type === "enum" && Array.isArray(constraints.values)) {\n const values = constraints.values.filter((item) => typeof item === "string" || typeof item === "boolean" || finite(item));\n return { ...base2, type: "enum", constraints: { values } };\n }\n if (value.type === "route" && Array.isArray(constraints.routes)) {\n const routes = constraints.routes.filter(isRecord).flatMap((route) => typeof route.provider === "string" && typeof route.model === "string" ? [{ provider: route.provider, model: route.model }] : []);\n return { ...base2, type: "route", constraints: { ...typeof constraints.need === "string" ? { need: constraints.need } : {}, routes } };\n }\n if (value.type === "object" && Array.isArray(constraints.fields)) {\n const fields = constraints.fields.map((item) => readVideoPropertyDefinition(item, depth + 1)).filter((item) => item !== null);\n return { ...base2, type: "object", constraints: { fields } };\n }\n return null;\n}\n\n// src/video-analysis.ts\nvar string = (value) => typeof value === "string";\nvar words = (value) => string(value) ? value : "";\nvar textOrNull = (value) => string(value) && value.length > 0 ? value : null;\nvar ms = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\nvar records = (value) => Array.isArray(value) ? value.filter(isRecord) : [];\nvar ids = (value) => Array.isArray(value) ? value.filter((item) => string(item) && item.length > 0) : [];\nvar span = (value) => ms(value.start_ms) && ms(value.end_ms) && value.end_ms >= value.start_ms;\nvar subject = (value) => string(value.id) && value.id.length > 0 && string(value.label);\nfunction readVideoSourceAnalysis(value) {\n if (!isRecord(value) || !ms(value.duration_ms) || value.duration_ms === 0 || !string(value.summary) || !isRecord(value.source)) return null;\n const source2 = value.source, audio = isRecord(value.audio) ? value.audio : {};\n if (!string(source2.sha256) || !ms(source2.width) || !ms(source2.height)) return null;\n return {\n duration_ms: value.duration_ms,\n summary: value.summary,\n places: records(value.places).filter(subject).map((item) => ({ id: item.id, label: item.label, description: words(item.description) })),\n people: records(value.people).filter(subject).map((item) => ({\n id: item.id,\n label: item.label,\n description: words(item.description),\n appearance: words(item.appearance),\n appearances: records(item.appearances).filter(span).map(({ start_ms, end_ms }) => ({ start_ms, end_ms })),\n speaks: item.speaks === true\n })),\n objects: records(value.objects).filter(subject).map((item) => ({ id: item.id, label: item.label, description: words(item.description) })),\n shots: records(value.shots).filter(span).map((item) => ({\n start_ms: item.start_ms,\n end_ms: item.end_ms,\n camera: words(item.camera),\n action: words(item.action),\n people: ids(item.people)\n })),\n events: records(value.events).filter((item) => ms(item.start_ms) && (item.end_ms === null || ms(item.end_ms)) && string(item.description)).map((item) => ({\n start_ms: item.start_ms,\n end_ms: item.end_ms,\n kind: words(item.kind),\n description: item.description,\n people: ids(item.people)\n })),\n transcript: records(value.transcript).filter((item) => span(item) && string(item.text)).map((item) => ({\n start_ms: item.start_ms,\n end_ms: item.end_ms,\n speaker: textOrNull(item.speaker),\n text: item.text\n })),\n audio: { music: textOrNull(audio.music), ambience: textOrNull(audio.ambience), speech: textOrNull(audio.speech) },\n source: {\n sha256: source2.sha256,\n width: source2.width,\n height: source2.height,\n fps: typeof source2.fps === "number" && Number.isFinite(source2.fps) && source2.fps > 0 ? source2.fps : null\n }\n };\n}\nfunction readVideoAnalysisResult(value) {\n if (!isRecord(value) || value.kind !== "analysis") return null;\n const analysis = readVideoSourceAnalysis(value.analysis);\n return analysis ? { kind: "analysis", analysis } : null;\n}\nfunction readVideoReferenceReplaces(value) {\n if (!isRecord(value)) return void 0;\n const subjectId = textOrNull(value.subject_id), description = textOrNull(value.description);\n if (!subjectId && !description) return void 0;\n return { ...subjectId ? { subject_id: subjectId } : {}, ...description ? { description } : {} };\n}\nfunction readVideoEditPlan(value) {\n if (value === void 0) return void 0;\n if (!isRecord(value)) return null;\n const analysisId = value.source_analysis_id;\n return {\n source_analysis_id: string(analysisId) && analysisId ? analysisId : null,\n mappings: records(value.mappings).filter((item) => isRecord(item.reference) && string(item.reference.asset_id) && item.reference.asset_id).map((item) => {\n const reference2 = item.reference, replaces2 = isRecord(item.replaces) ? item.replaces : {};\n return {\n reference: { asset_id: reference2.asset_id, role: textOrNull(reference2.role), name: textOrNull(reference2.name) },\n replaces: { subject_id: textOrNull(replaces2.subject_id), description: textOrNull(replaces2.description) },\n source: item.source === "explicit" ? "explicit" : "inferred",\n image_index: ms(item.image_index) && item.image_index > 0 ? item.image_index : null,\n visual_sheet: item.visual_sheet === true\n };\n }),\n warnings: Array.isArray(value.warnings) ? value.warnings.filter((item) => string(item) && item.length > 0) : []\n };\n}\n\n// src/capability-needs.ts\nvar generate = { role: "generate", mediaUsage: false, storedMediaResult: false };\nvar capabilityNeeds = {\n "text.short": { ...generate, providerCapability: "text.generate", waitMs: 2e4 },\n "text.chat": { ...generate, providerCapability: "text.generate", waitMs: 2e4 },\n "text.long": { ...generate, providerCapability: "text.generate", waitMs: 9e4 },\n "text.structured": { ...generate, providerCapability: "text.generate_structured", waitMs: 6e4 },\n "web.research": { ...generate, providerCapability: "web.research", waitMs: 9e4 },\n "audio.synthesize": { ...generate, providerCapability: "audio.synthesize", waitMs: 2e4, mediaUsage: true },\n "audio.transcribe": { ...generate, providerCapability: "audio.transcribe", waitMs: 12e4 },\n "audio.generate": { ...generate, providerCapability: "audio.generate", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "image.generate": { ...generate, providerCapability: "image.generate", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "image.edit": { ...generate, providerCapability: "image.edit", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "video.generate": { ...generate, providerCapability: "video.generate", waitMs: 18e4, mediaUsage: true, storedMediaResult: true },\n "image.remove_background": { ...generate, providerCapability: "image.remove_background", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "image.upscale": { ...generate, providerCapability: "image.upscale", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "audio.sound_effect": { ...generate, providerCapability: "audio.sound_effect", waitMs: 3e5, mediaUsage: true, storedMediaResult: true },\n "video.extend": { ...generate, providerCapability: "video.extend", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "audio.voice_change": { ...generate, providerCapability: "audio.voice_change", waitMs: 3e5, mediaUsage: true, storedMediaResult: true },\n "text.decision": { role: "decide", providerCapability: "text.decide", waitMs: 8e3, mediaUsage: false, storedMediaResult: false },\n "voice.call": { role: "voice", providerCapability: "voice.call", waitMs: 2e4, mediaUsage: false, storedMediaResult: false }\n};\nvar allCapabilityNeeds = Object.keys(capabilityNeeds);\nvar aiGenerateNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].role === "generate");\nvar aiDecideNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].role === "decide");\nvar voiceCallNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].role === "voice");\nvar mediaResultNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].storedMediaResult);\nvar mediaUsageNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].mediaUsage);\nvar generationDeadlines = Object.fromEntries(aiGenerateNeeds.map((need) => [need, capabilityNeeds[need].waitMs]));\nvar capabilityNeedWaits = Object.fromEntries(allCapabilityNeeds.map((need) => [need, capabilityNeeds[need].waitMs]));\nvar needProviderCapabilities = Object.fromEntries(allCapabilityNeeds.map((need) => [need, capabilityNeeds[need].providerCapability]));\nvar generationWaiting = {\n fallbackMs: 2e4,\n visionTextMs: 3e5,\n sdkMarginMs: 6e4,\n negotiatedAdmissionMs: 25e3,\n pollIntervalMs: 2e3,\n pollMaxMs: 8e3\n};\n\n// src/operation-metadata.ts\nvar operationDefaults = {\n needs: [],\n transport: "invoke",\n access: "contribute",\n observer: "denied",\n publicRead: "denied",\n publicControl: null,\n mediaUsage: false,\n spend: "none",\n idempotency: "host-defined",\n waiting: "operation",\n deadlineMs: null,\n sdkMarginMs: null,\n rateBucket: "public-playback",\n compatibility: "current"\n};\nvar operationRead = { access: "read", idempotency: "read" };\nvar observerRead = { ...operationRead, observer: "declared-public-read" };\nvar publicRead = { ...observerRead, publicRead: "eligible" };\n\n// src/automations-operations.ts\nvar base = { ...operationDefaults, capability: "automations", sdkTimeoutMs: 12e4, rateBucket: "experience-automations" };\nvar automationsOperationDefinitions = {\n catalog: { ...base, ...operationRead, operation: "catalog", input: "automations.catalog", output: "automations.catalog", facades: [{ path: "automations.catalog", kind: "direct" }] },\n list: { ...base, ...operationRead, operation: "list", input: "automations.list", output: "automations.list", facades: [{ path: "automations.list", kind: "direct" }] },\n get: { ...base, ...operationRead, operation: "get", input: "automations.get", output: "automations.get", facades: [{ path: "automations.get", kind: "direct" }] },\n create: { ...base, operation: "create", input: "automations.create", output: "automations.create", facades: [{ path: "automations.create", kind: "direct" }] },\n save: { ...base, operation: "save", input: "automations.save", output: "automations.save", idempotency: "compare-and-set", facades: [{ path: "automations.save", kind: "direct" }] },\n validate: { ...base, ...operationRead, operation: "validate", input: "automations.validate", output: "automations.validate", facades: [{ path: "automations.validate", kind: "direct" }] },\n remove: { ...base, operation: "remove", input: "automations.remove", output: "automations.remove", facades: [{ path: "automations.remove", kind: "direct" }] },\n activate: { ...base, operation: "activate", input: "automations.activate", output: "automations.activate", facades: [{ path: "automations.activate", kind: "direct" }] },\n pause: { ...base, operation: "pause", input: "automations.pause", output: "automations.pause", facades: [{ path: "automations.pause", kind: "direct" }] },\n test: { ...base, operation: "test", input: "automations.test", output: "automations.test", spend: "may-spend", facades: [{ path: "automations.test", kind: "direct" }] },\n runs: { ...base, ...operationRead, operation: "runs", input: "automations.runs", output: "automations.runs", facades: [{ path: "automations.runs", kind: "direct" }] },\n run: { ...base, ...operationRead, operation: "run", input: "automations.run", output: "automations.run", facades: [{ path: "automations.run", kind: "direct" }] },\n "templates.list": { ...base, ...operationRead, operation: "templates.list", input: "automations.templates.list", output: "automations.templates.list", facades: [{ path: "automations.templates.list", kind: "direct" }] },\n "templates.publish": { ...base, operation: "templates.publish", input: "automations.templates.publish", output: "automations.templates.publish", facades: [{ path: "automations.templates.publish", kind: "direct" }] },\n "templates.use": { ...base, operation: "templates.use", input: "automations.templates.use", output: "automations.templates.use", facades: [{ path: "automations.templates.use", kind: "direct" }] }\n};\n\n// src/ai-operations.ts\nvar aiOperationDefinitions = {\n "generate": {\n ...operationDefaults,\n capability: "ai",\n operation: "generate",\n input: "ai.generate",\n output: "ai.generate",\n sdkTimeoutMs: null,\n needs: aiGenerateNeeds,\n spend: "may-spend",\n waiting: "generation-need",\n sdkMarginMs: generationWaiting.sdkMarginMs,\n idempotency: "durable-receipt",\n facades: [{ path: "ai.generate", kind: "composite" }]\n },\n "estimate": {\n ...operationDefaults,\n capability: "ai",\n operation: "estimate",\n input: "ai.estimate",\n output: "ai.estimate",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.estimate", kind: "direct" }]\n },\n "options": {\n ...operationDefaults,\n capability: "ai",\n operation: "options",\n input: "ai.options",\n output: "ai.options",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.options", kind: "direct" }]\n },\n "models": {\n ...operationDefaults,\n capability: "ai",\n operation: "models",\n input: "ai.models",\n output: "ai.models",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.models", kind: "direct" }]\n },\n "voices": {\n ...operationDefaults,\n capability: "ai",\n operation: "voices",\n input: "ai.voices",\n output: "ai.voices",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.voices", kind: "direct" }]\n },\n "get": {\n ...operationDefaults,\n capability: "ai",\n operation: "get",\n input: "ai.get",\n output: "ai.get",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.get", kind: "direct" }]\n },\n "decide": {\n ...operationDefaults,\n capability: "ai",\n operation: "decide",\n input: "ai.decide",\n output: "ai.decide",\n sdkTimeoutMs: operationWaiting.ai["decide"],\n needs: aiDecideNeeds,\n spend: "may-spend",\n facades: [{ path: "ai.decide", kind: "direct" }]\n },\n "voice.start": {\n ...operationDefaults,\n capability: "ai",\n operation: "voice.start",\n input: "ai.voice.start",\n output: "ai.voice.start",\n sdkTimeoutMs: operationWaiting.ai["voice.start"],\n needs: voiceCallNeeds,\n spend: "may-spend",\n transport: "voice-host",\n facades: [{ path: "voice.start", kind: "direct" }]\n },\n "voice.stop": {\n ...operationDefaults,\n capability: "ai",\n operation: "voice.stop",\n input: "ai.voice.stop",\n output: "ai.voice.stop",\n sdkTimeoutMs: operationWaiting.ai.default,\n needs: voiceCallNeeds,\n transport: "voice-host",\n facades: [{ path: "voice.stop", kind: "direct" }]\n },\n "voice.state": {\n ...operationDefaults,\n capability: "ai",\n operation: "voice.state",\n input: "ai.voice.state",\n output: "ai.voice.state",\n sdkTimeoutMs: operationWaiting.ai["voice.state"],\n ...operationRead,\n needs: voiceCallNeeds,\n transport: "voice-host",\n facades: [{ path: "voice.state", kind: "direct" }]\n }\n};\n\n// src/assets-operations.ts\nvar assetsOperationDefinitions = {\n "read": {\n ...operationDefaults,\n capability: "assets",\n operation: "read",\n input: "assets.read",\n output: "assets.read",\n sdkTimeoutMs: operationWaiting.assets.default,\n ...publicRead,\n facades: [{ path: "assets.read", kind: "direct" }, { path: "assets.media", kind: "composite" }]\n },\n "upload": {\n ...operationDefaults,\n capability: "assets",\n operation: "upload",\n input: "assets.upload",\n output: "assets.upload",\n sdkTimeoutMs: operationWaiting.assets.default,\n mediaUsage: true,\n facades: [{ path: "assets.upload", kind: "direct" }]\n },\n "uploadAttachment": {\n ...operationDefaults,\n capability: "assets",\n operation: "uploadAttachment",\n input: "assets.uploadAttachment",\n output: "assets.uploadAttachment",\n sdkTimeoutMs: operationWaiting.assets["uploadAttachment"],\n mediaUsage: true,\n transport: "binary-upload",\n idempotency: "durable-receipt",\n facades: [{ path: "assets.uploadAttachment", kind: "direct" }]\n },\n "attachmentUrl": {\n ...operationDefaults,\n capability: "assets",\n operation: "attachmentUrl",\n input: "assets.attachmentUrl",\n output: "assets.attachmentUrl",\n sdkTimeoutMs: operationWaiting.assets.default,\n mediaUsage: true,\n ...operationRead,\n facades: [{ path: "assets.attachmentUrl", kind: "direct" }]\n }\n};\n\n// src/video-operations.ts\nvar videoOperationDefinitions = {\n "connection": {\n ...operationDefaults,\n capability: "video",\n operation: "connection",\n input: "video.connection",\n output: "video.connection",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.connection", kind: "direct" }]\n },\n "workflows": {\n ...operationDefaults,\n capability: "video",\n operation: "workflows",\n input: "video.workflows",\n output: "video.workflows",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.workflows", kind: "direct" }]\n },\n "workflow": {\n ...operationDefaults,\n capability: "video",\n operation: "workflow",\n input: "video.workflow",\n output: "video.workflow",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.workflow", kind: "direct" }]\n },\n "estimate": {\n ...operationDefaults,\n capability: "video",\n operation: "estimate",\n input: "video.estimate",\n output: "video.estimate",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.estimate", kind: "direct" }]\n },\n "create": {\n ...operationDefaults,\n capability: "video",\n operation: "create",\n input: "video.create",\n output: "video.create",\n sdkTimeoutMs: operationWaiting.video.default,\n mediaUsage: true,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.create", kind: "direct" }]\n },\n "list": {\n ...operationDefaults,\n capability: "video",\n operation: "list",\n input: "video.list",\n output: "video.list",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.list", kind: "direct" }]\n },\n "get": {\n ...operationDefaults,\n capability: "video",\n operation: "get",\n input: "video.get",\n output: "video.get",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.get", kind: "direct" }, { path: "video.wait", kind: "composite" }, { path: "video.media", kind: "composite" }, { path: "video.playback", kind: "composite" }]\n },\n "retry": {\n ...operationDefaults,\n capability: "video",\n operation: "retry",\n input: "video.retry",\n output: "video.retry",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.retry", kind: "direct" }]\n },\n "cancel": {\n ...operationDefaults,\n capability: "video",\n operation: "cancel",\n input: "video.cancel",\n output: "video.cancel",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.cancel", kind: "direct" }]\n },\n "remove": {\n ...operationDefaults,\n capability: "video",\n operation: "remove",\n input: "video.remove",\n output: "video.remove",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.remove", kind: "direct" }]\n },\n "clipping.create": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.create",\n input: "video.clipping.create",\n output: "video.clipping.create",\n sdkTimeoutMs: operationWaiting.video.default,\n mediaUsage: true,\n facades: [{ path: "video.clipping.create", kind: "direct" }]\n },\n "clipping.list": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.list",\n input: "video.clipping.list",\n output: "video.clipping.list",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.clipping.list", kind: "direct" }]\n },\n "clipping.get": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.get",\n input: "video.clipping.get",\n output: "video.clipping.get",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.clipping.get", kind: "direct" }]\n },\n "clipping.remove": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.remove",\n input: "video.clipping.remove",\n output: "video.clipping.remove",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.clipping.remove", kind: "direct" }]\n },\n "clipping.uploadSource": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.uploadSource",\n input: "video.clipping.uploadSource",\n output: "video.clipping.uploadSource",\n sdkTimeoutMs: operationWaiting.video["clipping.uploadSource"],\n transport: "binary-upload",\n facades: [{ path: "video.clipping.uploadSource", kind: "direct" }]\n },\n "clipping.estimate": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.estimate",\n input: "video.clipping.estimate",\n output: "video.clipping.estimate",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.clipping.estimate", kind: "direct" }]\n },\n "clipping.propose": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.propose",\n input: "video.clipping.propose",\n output: "video.clipping.propose",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.clipping.propose", kind: "direct" }]\n },\n "clipping.updatePlan": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.updatePlan",\n input: "video.clipping.updatePlan",\n output: "video.clipping.updatePlan",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.clipping.updatePlan", kind: "direct" }]\n },\n "clipping.createExport": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.createExport",\n input: "video.clipping.createExport",\n output: "video.clipping.createExport",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.clipping.createExport", kind: "direct" }]\n },\n "clipping.getJob": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.getJob",\n input: "video.clipping.getJob",\n output: "video.clipping.getJob",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.clipping.getJob", kind: "direct" }]\n },\n "clipping.cancelJob": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.cancelJob",\n input: "video.clipping.cancelJob",\n output: "video.clipping.cancelJob",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.clipping.cancelJob", kind: "direct" }]\n },\n "clipping.resumeJob": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.resumeJob",\n input: "video.clipping.resumeJob",\n output: "video.clipping.resumeJob",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.clipping.resumeJob", kind: "direct" }]\n },\n "clipping.prepareMutation": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.prepareMutation",\n input: "video.clipping.prepareMutation",\n output: "video.clipping.prepareMutation",\n sdkTimeoutMs: operationWaiting.video.default,\n transport: "host-document",\n facades: [{ path: "video.clipping.prepareMutation", kind: "direct" }]\n },\n "clipping.readMutation": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.readMutation",\n input: "video.clipping.readMutation",\n output: "video.clipping.readMutation",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n transport: "host-document",\n facades: [{ path: "video.clipping.readMutation", kind: "direct" }]\n },\n "clipping.completeMutation": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.completeMutation",\n input: "video.clipping.completeMutation",\n output: "video.clipping.completeMutation",\n sdkTimeoutMs: operationWaiting.video.default,\n transport: "host-document",\n facades: [{ path: "video.clipping.completeMutation", kind: "direct" }]\n }\n};\nvar videoOperations = [\n videoOperationDefinitions["connection"].operation,\n videoOperationDefinitions["workflows"].operation,\n videoOperationDefinitions["workflow"].operation,\n videoOperationDefinitions["estimate"].operation,\n videoOperationDefinitions["create"].operation,\n videoOperationDefinitions["list"].operation,\n videoOperationDefinitions["get"].operation,\n videoOperationDefinitions["retry"].operation,\n videoOperationDefinitions["cancel"].operation,\n videoOperationDefinitions["remove"].operation,\n videoOperationDefinitions["clipping.create"].operation,\n videoOperationDefinitions["clipping.list"].operation,\n videoOperationDefinitions["clipping.get"].operation,\n videoOperationDefinitions["clipping.remove"].operation,\n videoOperationDefinitions["clipping.uploadSource"].operation,\n videoOperationDefinitions["clipping.estimate"].operation,\n videoOperationDefinitions["clipping.propose"].operation,\n videoOperationDefinitions["clipping.updatePlan"].operation,\n videoOperationDefinitions["clipping.createExport"].operation,\n videoOperationDefinitions["clipping.getJob"].operation,\n videoOperationDefinitions["clipping.cancelJob"].operation,\n videoOperationDefinitions["clipping.resumeJob"].operation,\n videoOperationDefinitions["clipping.prepareMutation"].operation,\n videoOperationDefinitions["clipping.readMutation"].operation,\n videoOperationDefinitions["clipping.completeMutation"].operation\n];\nvar videoWaitSchedule = { fastMs: 2e3, fastForMs: 2e4, steadyMs: 5e3, steadyForMs: 12e4, slowMs: 15e3, minimumIntervalMs: 2e3 };\n\n// src/outirl-operations.ts\nvar outirlOperationDefinitions = {\n "metrics.read": {\n ...operationDefaults,\n capability: "outirl",\n operation: "metrics.read",\n input: "outirl.metrics.read",\n output: "outirl.metrics.read",\n sdkTimeoutMs: operationWaiting.outirl.default,\n ...operationRead,\n facades: [{ path: "outirl.metrics", kind: "direct" }]\n },\n "hue.lights.read": {\n ...operationDefaults,\n capability: "outirl",\n operation: "hue.lights.read",\n input: "outirl.hue.lights.read",\n output: "outirl.hue.lights.read",\n sdkTimeoutMs: operationWaiting.outirl.default,\n ...operationRead,\n publicControl: "hue",\n rateBucket: "hardware-control",\n facades: [{ path: "outirl.hue.lights", kind: "direct" }]\n },\n "hue.lights.set": {\n ...operationDefaults,\n capability: "outirl",\n operation: "hue.lights.set",\n input: "outirl.hue.lights.set",\n output: "outirl.hue.lights.set",\n sdkTimeoutMs: operationWaiting.outirl.default,\n publicControl: "hue",\n rateBucket: "hardware-control",\n facades: [{ path: "outirl.hue.set", kind: "direct" }]\n },\n "leds.read": {\n ...operationDefaults,\n capability: "outirl",\n operation: "leds.read",\n input: "outirl.leds.read",\n output: "outirl.leds.read",\n sdkTimeoutMs: operationWaiting.outirl.default,\n ...operationRead,\n publicControl: "leds",\n rateBucket: "hardware-control",\n facades: [{ path: "outirl.leds.read", kind: "direct" }]\n },\n "leds.set": {\n ...operationDefaults,\n capability: "outirl",\n operation: "leds.set",\n input: "outirl.leds.set",\n output: "outirl.leds.set",\n sdkTimeoutMs: operationWaiting.outirl.default,\n publicControl: "leds",\n rateBucket: "hardware-control",\n facades: [{ path: "outirl.leds.set", kind: "direct" }]\n },\n "audio.devices": {\n ...operationDefaults,\n capability: "outirl",\n operation: "audio.devices",\n input: "outirl.audio.devices",\n output: "outirl.audio.devices",\n sdkTimeoutMs: operationWaiting.outirl.default,\n ...operationRead,\n rateBucket: "outirl-audio",\n facades: [{ path: "outirl.audio.devices", kind: "direct" }]\n },\n "audio.start": {\n ...operationDefaults,\n capability: "outirl",\n operation: "audio.start",\n input: "outirl.audio.start",\n output: "outirl.audio.start",\n sdkTimeoutMs: operationWaiting.outirl.default,\n rateBucket: "outirl-audio",\n facades: [{ path: "outirl.audio.start", kind: "direct" }]\n },\n "audio.read": {\n ...operationDefaults,\n capability: "outirl",\n operation: "audio.read",\n input: "outirl.audio.read",\n output: "outirl.audio.read",\n sdkTimeoutMs: operationWaiting.outirl.default,\n ...operationRead,\n rateBucket: "outirl-audio",\n facades: [{ path: "outirl.audio.read", kind: "direct" }]\n },\n "audio.stop": {\n ...operationDefaults,\n capability: "outirl",\n operation: "audio.stop",\n input: "outirl.audio.stop",\n output: "outirl.audio.stop",\n sdkTimeoutMs: operationWaiting.outirl.default,\n rateBucket: "outirl-audio",\n facades: [{ path: "outirl.audio.stop", kind: "direct" }]\n },\n "audio.transcribe": {\n ...operationDefaults,\n capability: "outirl",\n operation: "audio.transcribe",\n input: "outirl.audio.transcribe",\n output: "outirl.audio.transcribe",\n sdkTimeoutMs: operationWaiting.outirl["audio.transcribe"],\n rateBucket: "outirl-audio",\n spend: "may-spend",\n facades: [{ path: "outirl.audio.transcribe", kind: "direct" }]\n },\n "network.read": {\n ...operationDefaults,\n capability: "outirl",\n operation: "network.read",\n input: "outirl.network.read",\n output: "outirl.network.read",\n sdkTimeoutMs: operationWaiting.outirl.default,\n ...publicRead,\n rateBucket: "outirl-network",\n facades: [{ path: "outirl.network", kind: "direct" }]\n },\n "desktop.read": {\n ...operationDefaults,\n capability: "outirl",\n operation: "desktop.read",\n input: "outirl.desktop.read",\n output: "outirl.desktop.read",\n sdkTimeoutMs: operationWaiting.outirl.default,\n ...operationRead,\n rateBucket: "outirl-desktop",\n facades: [{ path: "outirl.desktop.read", kind: "direct" }]\n },\n "desktop.dictation": {\n ...operationDefaults,\n capability: "outirl",\n operation: "desktop.dictation",\n input: "outirl.desktop.dictation",\n output: "outirl.desktop.dictation",\n sdkTimeoutMs: operationWaiting.outirl.default,\n rateBucket: "outirl-desktop",\n facades: [{ path: "outirl.desktop.dictation", kind: "direct" }]\n },\n "desktop.terminal": {\n ...operationDefaults,\n capability: "outirl",\n operation: "desktop.terminal",\n input: "outirl.desktop.terminal",\n output: "outirl.desktop.terminal",\n sdkTimeoutMs: operationWaiting.outirl.default,\n rateBucket: "outirl-desktop",\n facades: [{ path: "outirl.desktop.terminal", kind: "direct" }]\n }\n};\n\n// src/network-operations.ts\nvar networkOperationDefinitions = {\n "request": {\n ...operationDefaults,\n capability: "network",\n operation: "request",\n input: "network.request",\n output: "network.request",\n sdkTimeoutMs: operationWaiting.network.default,\n idempotency: "durable-receipt",\n facades: [{ path: "network.request", kind: "direct" }]\n },\n "asset": {\n ...operationDefaults,\n capability: "network",\n operation: "asset",\n input: "network.asset",\n output: "network.asset",\n sdkTimeoutMs: operationWaiting.network.default,\n ...operationRead,\n facades: [{ path: "network.asset", kind: "direct" }]\n }\n};\n\n// src/multiplayer-operations.ts\nvar multiplayerOperationDefinitions = {\n "presence": {\n ...operationDefaults,\n capability: "multiplayer",\n operation: "presence",\n input: "multiplayer.presence",\n output: "multiplayer.presence",\n sdkTimeoutMs: operationWaiting.multiplayer.default,\n transport: "live-host",\n ...publicRead,\n facades: [{ path: "multiplayer.presence", kind: "direct" }, { path: "multiplayer.onPresence", kind: "composite" }]\n },\n "subscribe": {\n ...operationDefaults,\n capability: "multiplayer",\n operation: "subscribe",\n input: "multiplayer.subscribe",\n output: "multiplayer.subscribe",\n sdkTimeoutMs: operationWaiting.multiplayer.default,\n transport: "live-host",\n ...publicRead,\n facades: [{ path: "multiplayer.subscribe", kind: "composite" }]\n },\n "publish": {\n ...operationDefaults,\n capability: "multiplayer",\n operation: "publish",\n input: "multiplayer.publish",\n output: "multiplayer.publish",\n sdkTimeoutMs: operationWaiting.multiplayer.default,\n transport: "live-host",\n facades: [{ path: "multiplayer.publish", kind: "direct" }]\n }\n};\n\n// src/device-operations.ts\nvar deviceOperationDefinitions = {\n "availability": {\n ...operationDefaults,\n capability: "device",\n operation: "availability",\n input: "device.availability",\n output: "device.availability",\n sdkTimeoutMs: operationWaiting.device["availability"],\n transport: "native-host",\n ...operationRead,\n facades: [{ path: "device.availability", kind: "direct" }]\n },\n "camera.capture": {\n ...operationDefaults,\n capability: "device",\n operation: "camera.capture",\n input: "device.camera.capture",\n output: "device.camera.capture",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.camera.capture", kind: "direct" }]\n },\n "camera.stream": {\n ...operationDefaults,\n capability: "device",\n operation: "camera.stream",\n input: "device.camera.stream",\n output: "device.camera.stream",\n sdkTimeoutMs: operationWaiting.device["camera.stream"],\n transport: "native-host",\n facades: [{ path: "device.media.getUserMedia", kind: "composite" }]\n },\n "photos.pick": {\n ...operationDefaults,\n capability: "device",\n operation: "photos.pick",\n input: "device.photos.pick",\n output: "device.photos.pick",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.photos.pick", kind: "direct" }]\n },\n "microphone.stream": {\n ...operationDefaults,\n capability: "device",\n operation: "microphone.stream",\n input: "device.microphone.stream",\n output: "device.microphone.stream",\n sdkTimeoutMs: operationWaiting.device["microphone.stream"],\n transport: "native-host",\n facades: [{ path: "device.media.getUserMedia", kind: "composite" }]\n },\n "motion.subscribe": {\n ...operationDefaults,\n capability: "device",\n operation: "motion.subscribe",\n input: "device.motion.subscribe",\n output: "device.motion.subscribe",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.motion.subscribe", kind: "composite" }]\n },\n "motion.unsubscribe": {\n ...operationDefaults,\n capability: "device",\n operation: "motion.unsubscribe",\n input: "device.motion.unsubscribe",\n output: "device.motion.unsubscribe",\n sdkTimeoutMs: operationWaiting.device["motion.unsubscribe"],\n transport: "native-host",\n facades: [{ path: "device.motion.subscribe", kind: "composite" }]\n },\n "haptics.trigger": {\n ...operationDefaults,\n capability: "device",\n operation: "haptics.trigger",\n input: "device.haptics.trigger",\n output: "device.haptics.trigger",\n sdkTimeoutMs: operationWaiting.device["haptics.trigger"],\n transport: "native-host",\n facades: [{ path: "device.haptics.trigger", kind: "direct" }]\n },\n "haptics.pattern": {\n ...operationDefaults,\n capability: "device",\n operation: "haptics.pattern",\n input: "device.haptics.pattern",\n output: "device.haptics.pattern",\n sdkTimeoutMs: operationWaiting.device["haptics.pattern"],\n transport: "native-host",\n facades: [{ path: "device.haptics.pattern", kind: "direct" }]\n },\n "haptics.stop": {\n ...operationDefaults,\n capability: "device",\n operation: "haptics.stop",\n input: "device.haptics.stop",\n output: "device.haptics.stop",\n sdkTimeoutMs: operationWaiting.device["haptics.stop"],\n transport: "native-host",\n facades: [{ path: "device.haptics.stop", kind: "direct" }]\n },\n "location.current": {\n ...operationDefaults,\n capability: "device",\n operation: "location.current",\n input: "device.location.current",\n output: "device.location.current",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n ...operationRead,\n facades: [{ path: "device.location.current", kind: "direct" }]\n },\n "share.open": {\n ...operationDefaults,\n capability: "device",\n operation: "share.open",\n input: "device.share.open",\n output: "device.share.open",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.share.open", kind: "direct" }]\n },\n "notifications.schedule": {\n ...operationDefaults,\n capability: "device",\n operation: "notifications.schedule",\n input: "device.notifications.schedule",\n output: "device.notifications.schedule",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.notifications.schedule", kind: "direct" }]\n },\n "notifications.list": {\n ...operationDefaults,\n capability: "device",\n operation: "notifications.list",\n input: "device.notifications.list",\n output: "device.notifications.list",\n sdkTimeoutMs: operationWaiting.device["notifications.list"],\n transport: "native-host",\n ...operationRead,\n facades: [{ path: "device.notifications.list", kind: "direct" }]\n },\n "notifications.cancel": {\n ...operationDefaults,\n capability: "device",\n operation: "notifications.cancel",\n input: "device.notifications.cancel",\n output: "device.notifications.cancel",\n sdkTimeoutMs: operationWaiting.device["notifications.cancel"],\n transport: "native-host",\n facades: [{ path: "device.notifications.cancel", kind: "direct" }]\n },\n "alarms.schedule": {\n ...operationDefaults,\n capability: "device",\n operation: "alarms.schedule",\n input: "device.alarms.schedule",\n output: "device.alarms.schedule",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.alarms.schedule", kind: "direct" }]\n },\n "alarms.list": {\n ...operationDefaults,\n capability: "device",\n operation: "alarms.list",\n input: "device.alarms.list",\n output: "device.alarms.list",\n sdkTimeoutMs: operationWaiting.device["alarms.list"],\n transport: "native-host",\n ...operationRead,\n facades: [{ path: "device.alarms.list", kind: "direct" }]\n },\n "alarms.cancel": {\n ...operationDefaults,\n capability: "device",\n operation: "alarms.cancel",\n input: "device.alarms.cancel",\n output: "device.alarms.cancel",\n sdkTimeoutMs: operationWaiting.device["alarms.cancel"],\n transport: "native-host",\n facades: [{ path: "device.alarms.cancel", kind: "direct" }]\n }\n};\n\n// src/presence-operations.ts\nvar presenceOperationDefinitions = {\n "list": {\n ...operationDefaults,\n capability: "presence",\n operation: "list",\n input: "presence.list",\n output: "presence.list",\n sdkTimeoutMs: operationWaiting.default,\n ...publicRead,\n compatibility: "wire-alias",\n facades: []\n }\n};\n\n// src/notifications-operations.ts\nvar notificationsOperationDefinitions = {\n "send": {\n ...operationDefaults,\n capability: "notifications",\n operation: "send",\n input: "notifications.send",\n output: "notifications.send",\n sdkTimeoutMs: operationWaiting.notifications.default,\n idempotency: "durable-receipt",\n rateBucket: "experience-notifications",\n facades: [{ path: "notifications.send", kind: "direct" }]\n }\n};\n\n// src/inbox-operations.ts\nvar inboxOperationDefinitions = {\n "list": {\n ...operationDefaults,\n ...operationRead,\n capability: "inbox",\n operation: "list",\n input: "inbox.list",\n output: "inbox.list",\n sdkTimeoutMs: operationWaiting.inbox.default,\n rateBucket: "experience-inbox",\n facades: [{ path: "inbox.list", kind: "direct" }, { path: "inbox.watch", kind: "composite" }]\n },\n "ack": {\n ...operationDefaults,\n capability: "inbox",\n operation: "ack",\n input: "inbox.ack",\n output: "inbox.ack",\n sdkTimeoutMs: operationWaiting.inbox.default,\n rateBucket: "experience-inbox",\n facades: [{ path: "inbox.ack", kind: "direct" }]\n }\n};\n\n// src/email-operations.ts\nvar emailOperationDefinitions = {\n "send": {\n ...operationDefaults,\n capability: "email",\n operation: "send",\n input: "email.send",\n output: "email.send",\n sdkTimeoutMs: operationWaiting.email.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n rateBucket: "experience-email",\n facades: [{ path: "email.send", kind: "direct" }]\n }\n};\n\n// src/connectors-operations.ts\nvar connectorsOperationDefinitions = {\n status: { ...operationDefaults, capability: "connectors", operation: "status", input: "connectors.status", output: "connectors.status", sdkTimeoutMs: 3e4, idempotency: "read", rateBucket: "experience-connectors", facades: [{ path: "connectors.status", kind: "direct" }] },\n request: { ...operationDefaults, capability: "connectors", operation: "request", input: "connectors.request", output: "connectors.request", sdkTimeoutMs: null, rateBucket: "experience-connectors", facades: [{ path: "connectors.request", kind: "direct" }] },\n invoke: { ...operationDefaults, capability: "connectors", operation: "invoke", input: "connectors.invoke", output: "connectors.invoke", sdkTimeoutMs: 45e3, idempotency: "durable-receipt", rateBucket: "experience-connectors", facades: [{ path: "connectors.invoke", kind: "direct" }] },\n revoke: { ...operationDefaults, capability: "connectors", operation: "revoke", input: "connectors.revoke", output: "connectors.revoke", sdkTimeoutMs: 3e4, rateBucket: "experience-connectors", facades: [{ path: "connectors.revoke", kind: "direct" }] }\n};\n\n// src/backend-operations.ts\nvar backendOperationDefinitions = {\n request: {\n ...operationDefaults,\n capability: "backend",\n operation: "request",\n input: "backend.request",\n output: "backend.request",\n // Host waits at most 60 s for admission/execution; leave a margin for durable storage.\n idempotency: "durable-receipt",\n sdkTimeoutMs: 65e3,\n facades: []\n },\n get: {\n ...operationDefaults,\n ...operationRead,\n capability: "backend",\n operation: "get",\n input: "backend.get",\n output: "backend.get",\n sdkTimeoutMs: operationWaiting.default,\n facades: []\n },\n cancel: {\n ...operationDefaults,\n ...operationRead,\n capability: "backend",\n operation: "cancel",\n input: "backend.cancel",\n output: "backend.cancel",\n idempotency: "durable-receipt",\n sdkTimeoutMs: operationWaiting.default,\n facades: []\n }\n};\n\n// src/drive-operations.ts\nvar driveOperationDefinitions = {\n "save": {\n ...operationDefaults,\n capability: "drive",\n operation: "save",\n input: "drive.save",\n output: "drive.save",\n sdkTimeoutMs: operationWaiting.drive.save,\n transport: "binary-upload",\n facades: [{ path: "drive.save", kind: "direct" }]\n },\n "pick": {\n ...operationDefaults,\n capability: "drive",\n operation: "pick",\n input: "drive.pick",\n output: "drive.pick",\n sdkTimeoutMs: operationWaiting.drive.pick,\n transport: "host-document",\n ...operationRead,\n facades: [{ path: "drive.pick", kind: "direct" }]\n }\n};\n\n// src/capability-operations.ts\nvar capabilityOperations = {\n automations: automationsOperationDefinitions,\n connectors: connectorsOperationDefinitions,\n backend: backendOperationDefinitions,\n ai: aiOperationDefinitions,\n assets: assetsOperationDefinitions,\n video: videoOperationDefinitions,\n outirl: outirlOperationDefinitions,\n network: networkOperationDefinitions,\n multiplayer: multiplayerOperationDefinitions,\n device: deviceOperationDefinitions,\n presence: presenceOperationDefinitions,\n notifications: notificationsOperationDefinitions,\n inbox: inboxOperationDefinitions,\n email: emailOperationDefinitions,\n drive: driveOperationDefinitions\n};\nvar capabilityOperationList = Object.values(capabilityOperations).flatMap((group) => Object.values(group));\nvar storageEntries = storageOperationList.map((item) => ({ ...operationDefaults, ...item }));\nvar operationList = [...storageEntries, ...capabilityOperationList];\nfunction findOperation(capability, operation2) {\n return operationList.find((item) => item.capability === capability && item.operation === operation2);\n}\nvar mediaEntries = capabilityOperationList.filter((item) => item.mediaUsage);\nvar operationId = (item) => `${item.capability}.${item.operation}`;\nvar mediaUsageOperationIds = [...mediaUsageNeeds, ...mediaEntries.map(operationId)];\nvar mediaInvocationOperationIds = operationList.filter((item) => item.capability === "assets" || item.capability === "video" || item.capability === "ai" && item.needs === aiOperationDefinitions.generate.needs).map((item) => `${item.capability}.${item.operation}`);\nvar networkOperationIds = Object.values(networkOperationDefinitions).map((item) => `${item.capability}.${item.operation}`);\nvar audioEntries = Object.values(outirlOperationDefinitions).filter((item) => item.rateBucket === "outirl-audio");\nvar networkEntries = Object.values(outirlOperationDefinitions).filter((item) => item.rateBucket === "outirl-network");\nvar desktopEntries = Object.values(outirlOperationDefinitions).filter((item) => item.rateBucket === "outirl-desktop");\nvar suffix = (prefix, operation2) => operation2.slice(prefix.length);\nvar outirlAudioOperationNames = audioEntries.map((item) => suffix("audio.", item.operation));\nvar outirlNetworkOperationNames = networkEntries.map((item) => suffix("network.", item.operation));\nvar outirlDesktopOperationNames = desktopEntries.map((item) => suffix("desktop.", item.operation));\n\n// src/capability-deadlines.ts\nvar capabilityDeadlines = {\n default: operationWaiting.default,\n access: operationWaiting.access,\n multiplayer: operationWaiting.multiplayer,\n network: operationWaiting.network,\n assets: { default: operationWaiting.assets.default, uploadAttachment: assetsOperationDefinitions.uploadAttachment.sdkTimeoutMs, media: operationWaiting.assets.media },\n video: { default: operationWaiting.video.default, "clipping.uploadSource": videoOperationDefinitions["clipping.uploadSource"].sdkTimeoutMs, media: operationWaiting.video.media },\n outirl: { default: operationWaiting.outirl.default, "audio.transcribe": outirlOperationDefinitions["audio.transcribe"].sdkTimeoutMs },\n ai: { default: operationWaiting.ai.default, decide: aiOperationDefinitions.decide.sdkTimeoutMs, "voice.start": aiOperationDefinitions["voice.start"].sdkTimeoutMs, "voice.state": aiOperationDefinitions["voice.state"].sdkTimeoutMs },\n device: {\n default: operationWaiting.device.default,\n availability: deviceOperationDefinitions.availability.sdkTimeoutMs,\n "haptics.trigger": deviceOperationDefinitions["haptics.trigger"].sdkTimeoutMs,\n "haptics.pattern": deviceOperationDefinitions["haptics.pattern"].sdkTimeoutMs,\n "haptics.stop": deviceOperationDefinitions["haptics.stop"].sdkTimeoutMs,\n "motion.unsubscribe": deviceOperationDefinitions["motion.unsubscribe"].sdkTimeoutMs,\n "camera.stream": deviceOperationDefinitions["camera.stream"].sdkTimeoutMs,\n "microphone.stream": deviceOperationDefinitions["microphone.stream"].sdkTimeoutMs,\n "notifications.list": deviceOperationDefinitions["notifications.list"].sdkTimeoutMs,\n "notifications.cancel": deviceOperationDefinitions["notifications.cancel"].sdkTimeoutMs,\n "alarms.list": deviceOperationDefinitions["alarms.list"].sdkTimeoutMs,\n "alarms.cancel": deviceOperationDefinitions["alarms.cancel"].sdkTimeoutMs\n },\n notifications: { default: operationWaiting.notifications.default, send: notificationsOperationDefinitions.send.sdkTimeoutMs },\n inbox: { default: operationWaiting.inbox.default, list: inboxOperationDefinitions.list.sdkTimeoutMs, ack: inboxOperationDefinitions.ack.sdkTimeoutMs },\n email: { default: operationWaiting.email.default, send: emailOperationDefinitions.send.sdkTimeoutMs },\n drive: { default: operationWaiting.drive.default, save: driveOperationDefinitions.save.sdkTimeoutMs, pick: driveOperationDefinitions.pick.sdkTimeoutMs },\n navigation: operationWaiting.navigation\n};\n\n// src/drive-types.ts\nvar DRIVE_TRANSFER_MAX_BYTES = 64 * 1024 * 1024;\nvar DRIVE_FOLDER_MAX_DEPTH = 30;\n\n// src/types/assets-wire.ts\nvar assetMediaTypes = ["image/jpeg", "image/png", "image/webp", "audio/mpeg", "audio/wav", "audio/flac", "audio/ogg", "video/mp4", "video/quicktime"];\nvar ASSET_MEDIA_MAX_BYTES = 64 * 1024 * 1024;\n\n// src/protocol.ts\nvar NOCHA_BRIDGE_PROTOCOL = "nocha.bridge.v4";\nvar experienceCapabilities = ["presence", "multiplayer", "state", "ai", "assets", "video", "outirl", "memory", "database", "device", "network", "notifications", "inbox", "email", "backend", "automations", "connectors", "drive"];\nvar browserCapabilities = ["presence", "state", "ai", "assets", "video", "outirl", "memory", "database", "multiplayer", "device", "network", "notifications", "inbox", "email", "backend", "automations", "connectors", "drive"];\nvar imageSizeByAspectRatio = {\n "1:1": "1024x1024",\n "3:2": "1536x1024",\n "2:3": "1024x1536",\n "16:9": "1536x864",\n "9:16": "864x1536",\n "4:3": "1536x1152",\n "3:4": "1152x1536"\n};\nvar NOCHA_NAVIGATION_PROTOCOL = "nocha.navigation.v1";\nfunction unsafePathCharacters(value) {\n return [...value].some((character) => character === "\\\\" || character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);\n}\nfunction normalizeExperienceLocation(target, base2 = { pathname: "/", search: "", hash: "" }) {\n if (typeof target !== "string" && (target === null || typeof target !== "object" || typeof target.pathname !== "string" || typeof target.search !== "string" || typeof target.hash !== "string")) {\n throw new NochaError("invalid_request", "Expected an experience location");\n }\n const source2 = typeof target === "string" ? target : `${target.pathname}${target.search}${target.hash}`;\n if (!source2 || source2.trim() !== source2 || source2.length > 16384 || unsafePathCharacters(source2) || source2.startsWith("//") || /^[a-z][a-z\\d+.-]*:/i.test(source2)) throw new NochaError("invalid_request", "Expected an internal experience location");\n if (typeof target !== "string" && (!target.pathname.startsWith("/") || target.search !== "" && !target.search.startsWith("?") || target.hash !== "" && !target.hash.startsWith("#"))) throw new NochaError("invalid_request", "Invalid experience location");\n const url = new URL(source2, `https://experience.invalid${base2.pathname}${base2.search}${base2.hash}`);\n if (url.origin !== "https://experience.invalid" || url.username || url.password) throw new NochaError("invalid_request", "Expected an internal experience location");\n let path;\n try {\n path = decodeURIComponent(url.pathname);\n } catch {\n throw new NochaError("invalid_request", "Invalid experience pathname");\n }\n if (path === "/_nocha" || path.startsWith("/_nocha/") || unsafePathCharacters(path)) throw new NochaError("invalid_request", "Reserved experience pathname");\n for (const key of url.searchParams.keys()) if (key.startsWith("__nocha_")) throw new NochaError("invalid_request", "Reserved reader parameter");\n return { pathname: url.pathname, search: url.search, hash: url.hash };\n}\nfunction isExperienceLocation(value) {\n if (!value || typeof value !== "object") return false;\n const location2 = value;\n if (typeof location2.pathname !== "string" || typeof location2.search !== "string" || typeof location2.hash !== "string") return false;\n try {\n const normalized = normalizeExperienceLocation(location2);\n return normalized.pathname === location2.pathname && normalized.search === location2.search && normalized.hash === location2.hash;\n } catch {\n return false;\n }\n}\n\n// src/capabilities.ts\nfunction deadlineMs(capability, operation2, input3) {\n const record4 = input3 !== null && typeof input3 === "object" && !Array.isArray(input3) ? input3 : {};\n if (capability === "ai" && operation2 === "generate") {\n const need = typeof record4.need === "string" ? record4.need : "";\n const vision = Array.isArray(record4.input_asset_ids) && record4.input_asset_ids.length > 0;\n const base2 = Object.hasOwn(generationDeadlines, need) ? generationDeadlines[need] : generationWaiting.fallbackMs;\n return (vision && need.startsWith("text.") ? Math.max(base2, generationWaiting.visionTextMs) : base2) + generationWaiting.sdkMarginMs;\n }\n const registered = findOperation(capability, operation2);\n if (registered?.sdkTimeoutMs != null) return registered.sdkTimeoutMs;\n const table = Object.hasOwn(capabilityDeadlines, capability) ? capabilityDeadlines[capability] : void 0;\n if (typeof table !== "object") return capabilityDeadlines.default;\n return (Object.hasOwn(table, operation2) ? table[operation2] : table.default) ?? capabilityDeadlines.default;\n}\n\n// src/execution.ts\nvar runtimeCapabilities = [...browserCapabilities, "assistant", "voice", "access", "workspace", "context", "navigation"];\nfunction getNochaMode() {\n if (typeof window === "undefined") return "standalone";\n if (typeof document !== "undefined" && document.querySelector(\'meta[name="nocha-mode"]\')?.getAttribute("content") === "standalone") return "standalone";\n return window.parent && window.parent !== window ? "embedded" : "standalone";\n}\nvar experienceContextAvailable = false;\nfunction markExperienceContextAvailable() {\n experienceContextAvailable = true;\n}\nvar capabilities = Object.freeze({\n has(capability) {\n if (capability === "context") return getNochaMode() === "embedded" && experienceContextAvailable;\n return runtimeCapabilities.includes(capability) && (capability === "navigation" ? typeof window !== "undefined" : getNochaMode() === "embedded");\n },\n get() {\n return Object.freeze(Object.fromEntries(runtimeCapabilities.map((capability) => [capability, capabilities.has(capability)])));\n }\n});\n\n// src/transport.ts\nvar LATE_PORT_MS = 10 * 6e4;\nfunction assertHostCapability(capability) {\n if (getNochaMode() === "standalone") throw new NochaError("bridge_unavailable", `${capability} requires the embedded Nocha reader`);\n}\nfunction isFromHost(event) {\n return event.source == null || event.source === window.parent;\n}\nvar bridgeCapabilities = /* @__PURE__ */ new Set([...experienceCapabilities, "access", "workspace"]);\nvar usagePattern = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;\nvar maxTimerMs = 2147483647;\nvar maxInputDepth = 64;\nfunction isIdempotencyKey(value) {\n return typeof value === "string" && value.length >= 8 && value.length <= 200 && ![...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);\n}\nfunction isPlainObject(value) {\n if (value === null || typeof value !== "object" || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nfunction jsonProblem(value, depth, ancestors) {\n if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") return void 0;\n if (typeof value === "number") return Number.isFinite(value) ? void 0 : "numbers must be finite";\n if (typeof value !== "object") return `${typeof value} values are not JSON`;\n if (depth > maxInputDepth) return "values are nested too deeply";\n if (ancestors.has(value)) return "values contain a cycle";\n const items = Array.isArray(value) ? value : isPlainObject(value) ? Object.values(value) : void 0;\n if (!items) return "only plain objects and arrays are JSON";\n ancestors.add(value);\n try {\n for (const item of items) {\n const problem = jsonProblem(item, depth + 1, ancestors);\n if (problem) return problem;\n }\n return void 0;\n } finally {\n ancestors.delete(value);\n }\n}\nfunction requestProblem(capability, operation2, input3, options) {\n if (!bridgeCapabilities.has(capability)) return `Unknown capability ${String(capability)}`;\n if (typeof operation2 !== "string" || !operation2 || operation2.length > 100) return "The operation name must have 1 to 100 characters";\n if (!options || typeof options !== "object") return "Request options must be an object";\n if (options.usageId !== void 0 && (typeof options.usageId !== "string" || !usagePattern.test(options.usageId))) return "The usage id is not a valid NOCHA.json usage id";\n if (options.idempotencyKey !== void 0 && !isIdempotencyKey(options.idempotencyKey)) return "The idempotency key must have 8 to 200 characters without control characters";\n if (!isPlainObject(input3)) return "The input must be a JSON object";\n const problem = jsonProblem(input3, 0, /* @__PURE__ */ new Set());\n if (problem) return `The input is not JSON: ${problem}`;\n if (options.timeoutMs !== void 0 && (typeof options.timeoutMs !== "number" || !Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > maxTimerMs)) {\n return "timeoutMs must be a positive finite timer duration";\n }\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) return "signal must be an AbortSignal";\n return void 0;\n}\nfunction invokeBridgeResponse(capability, operation2, input3, options, withPort, lateResult) {\n try {\n assertHostCapability(capability);\n } catch (error) {\n return Promise.reject(error);\n }\n const problem = requestProblem(capability, operation2, input3, options);\n if (problem) return Promise.reject(new NochaError("invalid_request", problem));\n if (options.signal?.aborted) return Promise.reject(new NochaError("aborted", "Local bridge wait was aborted"));\n const timeoutMs = options.timeoutMs ?? deadlineMs(capability, operation2, input3);\n const host = window.parent;\n const requestId = crypto.randomUUID();\n const request = {\n protocol: NOCHA_BRIDGE_PROTOCOL,\n sdkVersion: 4,\n type: "invoke",\n requestId,\n capability,\n operation: operation2,\n ...options.usageId !== void 0 ? { usageId: options.usageId } : {},\n idempotencyKey: options.idempotencyKey ?? `${requestId.replaceAll("-", "")}:experience`,\n input: input3\n };\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n window.removeEventListener("message", onMessage);\n options.signal?.removeEventListener("abort", onAbort);\n };\n const fail = (error) => {\n cleanup();\n reject2(error);\n };\n const abandon = (error) => {\n fail(error);\n if (lateResult && !lateResult.signal.aborted) {\n const stopLate = () => {\n clearTimeout(lateTimer2);\n window.removeEventListener("message", onLate);\n lateResult.signal.removeEventListener("abort", stopLate);\n };\n const onLate = (event) => {\n if (!isFromHost(event) || !isRecord2(event.data) || event.data.protocol !== NOCHA_BRIDGE_PROTOCOL || event.data.requestId !== requestId || event.data.type !== "result" && event.data.type !== "error") return;\n stopLate();\n if (event.data.type === "result") lateResult.onResult();\n else lateResult.onError(wireError(event.data.error));\n };\n const lateTimer2 = setTimeout(() => {\n stopLate();\n lateResult.onExpired();\n }, deadlineMs(capability, operation2, input3));\n window.addEventListener("message", onLate);\n lateResult.signal.addEventListener("abort", stopLate, { once: true });\n }\n if (!withPort) return;\n const late = (event) => {\n if (!isFromHost(event) || !isRecord2(event.data) || event.data.requestId !== requestId) return;\n window.removeEventListener("message", late);\n clearTimeout(lateTimer);\n const port = event.ports[0];\n if (!port) return;\n try {\n port.postMessage({ type: "stop" });\n } catch {\n }\n port.close();\n };\n const lateTimer = setTimeout(() => window.removeEventListener("message", late), LATE_PORT_MS);\n window.addEventListener("message", late);\n };\n const onAbort = () => abandon(new NochaError("aborted", "Local bridge wait was aborted"));\n const onMessage = (event) => {\n if (!isFromHost(event)) return;\n const message = event.data;\n if (!isRecord2(message) || message.protocol !== NOCHA_BRIDGE_PROTOCOL || message.requestId !== requestId) return;\n if (message.type !== "result" && message.type !== "error") return;\n if (message.type === "result") {\n if (withPort) {\n const port = event.ports[0];\n if (!port) {\n fail(new NochaError("invalid_result", "Nocha returned live media without its message port"));\n return;\n }\n cleanup();\n resolve({ result: message.result, port });\n return;\n }\n cleanup();\n resolve(message.result);\n return;\n }\n fail(wireError(message.error));\n };\n const timer = setTimeout(() => abandon(new NochaError("invocation_timed_out", "Local bridge wait timed out")), timeoutMs);\n window.addEventListener("message", onMessage);\n options.signal?.addEventListener("abort", onAbort, { once: true });\n try {\n host.postMessage(request, "*");\n } catch (error) {\n fail(new NochaError("invalid_request", `The request cannot be sent to the Nocha host: ${error instanceof Error ? error.message : String(error)}`));\n }\n });\n}\nfunction invokeBridge(capability, operation2, input3 = {}, options = {}) {\n return invokeBridgeResponse(capability, operation2, input3, options, false);\n}\nfunction invokeBridgeWithLateResult(capability, operation2, input3, options, lateResult) {\n return invokeBridgeResponse(capability, operation2, input3, options, false, lateResult);\n}\nfunction invokeBridgeWithPort(capability, operation2, input3 = {}, options = {}) {\n return invokeBridgeResponse(capability, operation2, input3, options, true);\n}\nfunction subscribeBridgeEvents(listener) {\n if (getNochaMode() === "standalone") return () => {\n };\n const onMessage = (event) => {\n if (!isFromHost(event) || !isRecord2(event.data)) return;\n const message = event.data;\n if (message.protocol !== NOCHA_BRIDGE_PROTOCOL || message.type !== "event" || !isRecord2(message.event) || typeof message.event.type !== "string") return;\n const sequence = message.event.sequence;\n listener({\n type: message.event.type,\n payload: message.event.payload,\n ...typeof sequence === "number" && Number.isSafeInteger(sequence) && sequence >= 0 ? { sequence } : {}\n });\n };\n window.addEventListener("message", onMessage);\n return () => window.removeEventListener("message", onMessage);\n}\nfunction isRecord2(value) {\n return value !== null && typeof value === "object" && !Array.isArray(value);\n}\n\n// src/access.ts\nfunction parseDataSpace(value) {\n if (!isRecord(value)) return null;\n const { kind, id } = value;\n return (kind === "public" || kind === "personal" || kind === "team") && isUuid(id) ? { kind, id } : null;\n}\nfunction parseSnapshot(value) {\n if (!isRecord(value) || !isBoolean(value.authenticated) || value.role !== "observer" && value.role !== "participant" || !isBoolean(value.participate) || !isBoolean(value.save) || !isBoolean(value.paid) || !isBoolean(value.server)) return null;\n const dataSpace = value.dataSpace === void 0 ? void 0 : parseDataSpace(value.dataSpace);\n if (dataSpace === null) return null;\n return {\n authenticated: value.authenticated,\n role: value.role,\n participate: value.participate,\n save: value.save,\n paid: value.paid,\n server: value.server,\n ...dataSpace ? { dataSpace } : {}\n };\n}\nfunction snapshot(value) {\n const parsed = parseSnapshot(value);\n if (!parsed) throw new NochaError("invalid_result", "Nocha returned an invalid access snapshot");\n return parsed;\n}\nvar access = Object.freeze({\n get: async () => snapshot(await invokeBridge("access", "get")),\n request: async (input3) => {\n assertHostCapability("access");\n if (typeof navigator !== "undefined" && navigator.userActivation && !navigator.userActivation.isActive) {\n throw new NochaError("user_action_required", "Request access from a button or another deliberate user action");\n }\n return snapshot(await invokeBridge("access", "request", input3));\n },\n onChange: (listener) => {\n assertHostCapability("access");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "An access listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== "access.changed") return;\n const parsed = parseSnapshot(event.payload);\n if (parsed) notifyListener(listener, parsed);\n else warnOnce("access.changed", "the host sent an access snapshot this SDK does not understand");\n });\n }\n});\n\n// src/generation-input.ts\nvar supportedNeeds = new Set(aiGenerateNeeds);\nvar mediaNeeds = new Set(mediaResultNeeds);\nfunction invalid(message) {\n return new NochaError("invalid_request", message);\n}\nfunction isMicrocredits(value) {\n return typeof value === "string" && /^[1-9]\\d*$/.test(value);\n}\nfunction isMediaNeed(need) {\n return mediaNeeds.has(need);\n}\nfunction text(value, field3) {\n if (typeof value !== "string" || !value.trim()) throw invalid(`${field3} must be a non-empty string`);\n return value.trim();\n}\nfunction optionalString(value, field3) {\n if (value !== void 0 && typeof value !== "string") throw invalid(`${field3} must be a string`);\n}\nvar modelPattern = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,99}$/;\nvar voicePattern = /^[A-Za-z0-9_:.-]{1,160}$/;\nvar languagePattern = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;\nfunction matching(value, pattern, field3) {\n if (typeof value !== "string" || !pattern.test(value)) throw invalid(`${field3} is not a valid identifier`);\n return value;\n}\nfunction optionalNumber(value, field3) {\n if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value))) throw invalid(`${field3} must be a finite number`);\n}\nfunction assetIds(value, field3, required) {\n if (value === void 0 && !required) return void 0;\n if (!Array.isArray(value) || !value.every(isUuid) || required && !value.length) throw invalid(`${field3} must list authorized asset ids`);\n return value;\n}\nfunction singleSource(value) {\n const ids2 = assetIds(value, "inputAssetIds", true);\n if (ids2.length !== 1) throw invalid("inputAssetIds must contain exactly one authorized source asset");\n return ids2;\n}\nvar voiceSettingBounds = {\n stability: ["stability", 0, 1],\n similarityBoost: ["similarity_boost", 0, 1],\n style: ["style", 0, 1],\n speed: ["speed", 0.7, 1.2]\n};\nfunction voiceSettings(value) {\n if (value === void 0) return {};\n if (!isRecord(value)) throw invalid("voiceSettings must be an object");\n const unknown = Object.entries(value).find(([key, setting]) => setting !== void 0 && key !== "useSpeakerBoost" && !Object.hasOwn(voiceSettingBounds, key));\n if (unknown) throw invalid(`voiceSettings.${unknown[0]} is not a voice setting`);\n const settings = {};\n for (const [key, [field3, min, max]] of Object.entries(voiceSettingBounds)) {\n const setting = value[key];\n if (setting === void 0) continue;\n if (typeof setting !== "number" || !Number.isFinite(setting) || setting < min || setting > max) throw invalid(`voiceSettings.${key} must be a number from ${min} to ${max}`);\n settings[field3] = setting;\n }\n if (value.useSpeakerBoost !== void 0) {\n if (typeof value.useSpeakerBoost !== "boolean") throw invalid("voiceSettings.useSpeakerBoost must be a boolean");\n settings.use_speaker_boost = value.useSpeakerBoost;\n }\n return Object.keys(settings).length ? { voice_settings: settings } : {};\n}\nfunction responseFormat(schema, schemaName, fallback) {\n if (!isRecord(schema)) throw invalid("schema must be a JSON schema object");\n optionalString(schemaName, "schemaName");\n return { type: "json_schema", name: schemaName ?? fallback, schema, strict: true };\n}\nfunction budget(input3) {\n if (input3.quoteId !== void 0 && !isUuid(input3.quoteId)) throw invalid("quoteId must be a generation quote id");\n if (input3.maximumCostMicrocredits !== void 0 && !isMicrocredits(input3.maximumCostMicrocredits)) throw invalid("maximumCostMicrocredits must be a positive integer string");\n return {\n ...input3.quoteId ? { quote_id: input3.quoteId } : {},\n ...input3.maximumCostMicrocredits !== void 0 ? { maximum_cost_microcredits: input3.maximumCostMicrocredits } : {}\n };\n}\nfunction policy(input3) {\n optionalString(input3.generationUsage, "generationUsage");\n return {\n ...input3.effort !== void 0 ? { effort: input3.effort } : {},\n ...input3.generationUsage ? { generation_usage: input3.generationUsage } : {},\n ...budget(input3)\n };\n}\nfunction aiGenerateWire(input3) {\n if (!isRecord(input3) || typeof input3.need !== "string" || !supportedNeeds.has(input3.need)) throw invalid("need must be a supported generation need");\n const value = input3;\n const need = value.need;\n switch (need) {\n case "text.short":\n case "text.chat":\n case "text.long":\n case "text.structured": {\n const ids2 = assetIds(value.inputAssetIds, "inputAssetIds", false);\n return {\n ...policy(value),\n ...value.desiredLength ? { desired_length: value.desiredLength } : {},\n prompt: text(value.prompt, "prompt"),\n need,\n ...need === "text.structured" ? { response_format: responseFormat(value.schema, value.schemaName, "experience_analysis") } : {},\n ...ids2 ? { input_asset_ids: ids2 } : {}\n };\n }\n case "web.research": {\n if (!Array.isArray(value.allowedDomains) || !value.allowedDomains.every((domain) => typeof domain === "string")) throw invalid("allowedDomains must list hostnames");\n if (typeof value.maxToolCalls !== "number" || !Number.isInteger(value.maxToolCalls)) throw invalid("maxToolCalls must be an integer");\n return {\n ...policy(value),\n prompt: text(value.prompt, "prompt"),\n need,\n response_format: responseFormat(value.schema, value.schemaName, "web_research"),\n allowed_domains: value.allowedDomains.map((domain) => domain.trim().toLowerCase()),\n max_tool_calls: value.maxToolCalls\n };\n }\n case "audio.synthesize":\n return {\n ...policy(value),\n prompt: text(value.prompt, "prompt"),\n need,\n ...value.language ? { language: matching(value.language, languagePattern, "language") } : {},\n ...value.voice ? { voice_id: matching(value.voice, voicePattern, "voice") } : {},\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...voiceSettings(value.voiceSettings)\n };\n case "audio.transcribe":\n if (value.audioDataUrl === void 0 && value.durationSeconds === void 0 && value.inputAssetIds === void 0) throw invalid("audioDataUrl must be an audio data URL");\n if (value.audioDataUrl !== void 0 && (typeof value.audioDataUrl !== "string" || !value.audioDataUrl.startsWith("data:"))) throw invalid("audioDataUrl must be an audio data URL");\n optionalNumber(value.durationSeconds, "durationSeconds");\n optionalString(value.language, "language");\n optionalString(value.prompt, "prompt");\n return {\n ...policy(value),\n need,\n ...value.audioDataUrl !== void 0 ? { audio_data_url: value.audioDataUrl } : {},\n ...value.inputAssetIds !== void 0 ? { input_asset_ids: singleSource(value.inputAssetIds) } : {},\n ...value.durationSeconds !== void 0 ? { duration_seconds: value.durationSeconds } : {},\n ...value.language ? { language: value.language } : {},\n ...value.prompt ? { prompt: value.prompt } : {}\n };\n case "audio.generate":\n optionalNumber(value.durationSeconds, "durationSeconds");\n if (value.instrumental !== void 0 && typeof value.instrumental !== "boolean") throw invalid("instrumental must be a boolean");\n if (value.instrumental && value.lyrics != null) throw invalid("An instrumental track takes no lyrics");\n return {\n ...policy(value),\n need,\n prompt: text(value.prompt, "prompt"),\n duration_seconds: value.durationSeconds ?? 60,\n output_format: value.outputFormat ?? "mp3",\n ...value.instrumental !== void 0 ? { instrumental: value.instrumental } : {},\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...value.inputAssetIds !== void 0 ? { input_asset_ids: singleSource(value.inputAssetIds) } : {},\n ...value.lyrics != null ? { lyrics: value.lyrics } : {},\n ...value.seed != null ? { seed: value.seed } : {},\n ...value.bpm != null ? { bpm: value.bpm } : {},\n ...value.vocalLanguage != null ? { vocal_language: value.vocalLanguage } : {},\n ...value.keyScale != null ? { key_scale: value.keyScale } : {},\n ...value.timeSignature != null ? { time_signature: value.timeSignature } : {}\n };\n case "image.generate":\n case "image.edit": {\n const ids2 = assetIds(value.inputAssetIds, "inputAssetIds", need === "image.edit");\n if (value.size !== void 0 && value.aspectRatio !== void 0 && imageSizeByAspectRatio[value.aspectRatio] !== value.size) throw invalid("size conflicts with aspectRatio");\n if (value.background === "transparent" && value.outputFormat === "jpeg") throw invalid("JPEG does not support a transparent background");\n return {\n ...policy(value),\n prompt: text(value.prompt, "prompt"),\n need,\n ...ids2 ? { input_asset_ids: ids2 } : {},\n ...value.size ? { size: value.size } : {},\n ...value.aspectRatio ? { aspect_ratio: value.aspectRatio } : {},\n ...value.quality ? { quality: value.quality } : {},\n ...value.outputFormat ? { output_format: value.outputFormat } : {},\n ...value.background ? { background: value.background } : {}\n };\n }\n case "video.generate": {\n if (value.provider !== void 0 || value.model !== void 0) {\n throw invalid("video.generate does not accept provider or model");\n }\n optionalNumber(value.durationSeconds, "durationSeconds");\n const durationSeconds = value.durationSeconds ?? 6;\n if (durationSeconds < 4 || durationSeconds > 30) throw invalid("durationSeconds must be between 4 and 30 for video.generate");\n return { ...policy(value), prompt: text(value.prompt, "prompt"), need, duration_seconds: durationSeconds };\n }\n case "image.remove_background":\n return { ...budget(value), input_asset_ids: singleSource(value.inputAssetIds), need, ...value.outputFormat ? { output_format: value.outputFormat } : {} };\n case "image.upscale":\n return {\n ...budget(value),\n input_asset_ids: singleSource(value.inputAssetIds),\n need,\n ...value.scale !== void 0 ? { scale: value.scale } : {},\n ...value.outputFormat ? { output_format: value.outputFormat } : {}\n };\n case "audio.sound_effect":\n optionalNumber(value.durationSeconds, "durationSeconds");\n if (value.loop !== void 0 && typeof value.loop !== "boolean") throw invalid("loop must be a boolean");\n return { ...budget(value), need, prompt: text(value.prompt, "prompt"), duration_seconds: value.durationSeconds ?? 5, loop: value.loop ?? false };\n case "video.extend":\n optionalString(value.prompt, "prompt");\n optionalNumber(value.durationSeconds, "durationSeconds");\n return {\n ...budget(value),\n input_asset_ids: singleSource(value.inputAssetIds),\n need,\n duration_seconds: value.durationSeconds ?? 5,\n ...value.prompt !== void 0 ? { prompt: value.prompt } : {},\n ...value.mode !== void 0 ? { mode: value.mode } : {}\n };\n case "audio.voice_change":\n if (value.audioDataUrl === void 0 === (value.inputAssetIds === void 0)) throw invalid("Provide one recording: audioDataUrl or inputAssetIds");\n if (value.audioDataUrl !== void 0 && (typeof value.audioDataUrl !== "string" || !value.audioDataUrl.startsWith("data:"))) throw invalid("audioDataUrl must be an audio data URL");\n if (value.durationSeconds !== void 0) throw invalid("durationSeconds is not accepted by audio.voice_change");\n if (value.voice === void 0) throw invalid("voice is required by audio.voice_change");\n if (value.removeBackgroundNoise !== void 0 && typeof value.removeBackgroundNoise !== "boolean") throw invalid("removeBackgroundNoise must be a boolean");\n return {\n ...budget(value),\n need,\n ...value.audioDataUrl !== void 0 ? { audio_data_url: value.audioDataUrl } : { input_asset_ids: singleSource(value.inputAssetIds) },\n voice_id: matching(value.voice, voicePattern, "voice"),\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...voiceSettings(value.voiceSettings),\n ...value.removeBackgroundNoise !== void 0 ? { remove_background_noise: value.removeBackgroundNoise } : {}\n };\n }\n}\nvar decisionTypes = /* @__PURE__ */ new Set(["choice", "score", "noul"]);\nfunction aiDecideWire(input3) {\n if (!isRecord(input3) || !isRecord(input3.questions) || !Object.keys(input3.questions).length) throw invalid("A decision needs at least one question");\n for (const [id, question] of Object.entries(input3.questions)) {\n if (!isRecord(question) || !decisionTypes.has(question.type) || typeof question.instructions !== "string" || !question.instructions.trim()) {\n throw invalid(`Decision question ${id} needs a type and instructions`);\n }\n }\n if (input3.maximumCostMicrocredits !== void 0 && !isMicrocredits(input3.maximumCostMicrocredits)) throw invalid("maximumCostMicrocredits must be a positive integer string");\n return {\n state: input3.state,\n questions: input3.questions,\n ...input3.maximumCostMicrocredits !== void 0 ? { maximum_cost_microcredits: input3.maximumCostMicrocredits } : {}\n };\n}\nfunction aiOptionsWire(input3) {\n if (!isRecord(input3) || typeof input3.need !== "string" || !supportedNeeds.has(input3.need)) throw invalid("need must be a supported generation need");\n const ids2 = assetIds(input3.inputAssetIds, "inputAssetIds", false);\n optionalString(input3.generationUsage, "generationUsage");\n return { need: input3.need, ...ids2 ? { input_asset_ids: ids2 } : {}, ...input3.generationUsage ? { generation_usage: input3.generationUsage } : {} };\n}\nfunction aiModelsWire(input3) {\n if (!isRecord(input3) || input3.need !== "audio.synthesize") throw invalid("need must be audio.synthesize");\n return { need: input3.need };\n}\nfunction aiVoicesWire(input3) {\n const value = isRecord(input3) ? input3 : {};\n if (value.collection !== void 0 && value.collection !== "standard" && value.collection !== "library") throw invalid("collection must be standard or library");\n optionalString(value.query, "query");\n optionalString(value.cursor, "cursor");\n if (value.limit !== void 0 && (!Number.isInteger(value.limit) || value.limit < 1 || value.limit > 50)) throw invalid("limit must be an integer from 1 to 50");\n return {\n need: "audio.synthesize",\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...value.language !== void 0 ? { language: matching(value.language, languagePattern, "language") } : {},\n ...value.collection !== void 0 ? { collection: value.collection } : {},\n ...value.query?.trim() ? { query: value.query.trim() } : {},\n ...value.cursor ? { cursor: value.cursor } : {},\n ...value.limit !== void 0 ? { limit: value.limit } : {}\n };\n}\nfunction aiGetWire(input3) {\n const value = isRecord(input3) ? input3 : {};\n const operationId2 = value.operationId, idempotencyKey = value.idempotencyKey;\n if (operationId2 === void 0 === (idempotencyKey === void 0)) throw invalid("Provide one operationId or the original idempotencyKey");\n const key = operationId2 ?? idempotencyKey;\n if (typeof key !== "string" || !key) throw invalid("operationId or idempotencyKey must be a non-empty string");\n return operationId2 !== void 0 ? { operation_id: key } : { idempotency_key: key };\n}\n\n// src/ai.ts\nvar credits = (value) => typeof value === "string" && /^\\d+$/.test(value);\nvar isSource = (value) => isRecord(value) && isString(value.url) && (value.title === void 0 || isString(value.title));\nvar reject = (message) => new NochaError("invalid_result", message);\nfunction generationResult(need, value) {\n if (!isRecord(value) || value.need !== need || !isNonEmptyString(value.operation_id) || !isRecord(value.billing) || value.billing.participant_captured_microcredits !== void 0 && !credits(value.billing.participant_captured_microcredits)) {\n throw reject("Nocha returned an invalid generation result");\n }\n const media = !Array.isArray(value.asset_ids) || !value.asset_ids.length || !isArrayOf(value.asset_ids, isString) || !isArrayOf(value.assets, (asset) => isRecord(asset) && isString(asset.id)) || value.asset_ids.some((id) => !value.assets.some((asset) => asset.id === id));\n const invalid2 = need === "text.structured" ? !isString(value.text) || value.structured === void 0 : need.startsWith("text.") ? !isString(value.text) : need === "web.research" ? value.structured === void 0 || !isArrayOf(value.sources, isSource) || !Number.isInteger(value.search_call_count) || Number(value.search_call_count) < 1 : need === "audio.synthesize" ? !isNonEmptyString(value.audio_base64) || !isString(value.mime_type) || !value.mime_type.startsWith("audio/") : need === "audio.transcribe" ? !isString(value.text) || value.duration_seconds !== void 0 && !isFiniteNumber(value.duration_seconds) : isMediaNeed(need) ? media || value.duration_seconds !== void 0 && !isFiniteNumber(value.duration_seconds) : true;\n if (invalid2) throw reject(`Nocha returned an invalid ${need} result`);\n return value;\n}\nvar assetShape = (asset) => isRecord(asset) && isString(asset.id);\nfunction pendingReceipt(value) {\n if (!isRecord(value) || value.status !== "pending" || !isNonEmptyString(value.operation_id) || !isString(value.need)) return void 0;\n if ("billing" in value || "text" in value || "audio_base64" in value || "asset_ids" in value || "structured" in value) return void 0;\n const poll = value.poll_after_ms;\n const interval = isFiniteNumber(poll) && poll >= generationWaiting.pollIntervalMs ? poll : generationWaiting.pollIntervalMs;\n return { operation_id: value.operation_id, need: value.need, poll_after_ms: Math.min(interval, generationWaiting.pollMaxMs) };\n}\nfunction withRecovery(error, operationId2, idempotencyKey) {\n return new NochaError(error.code, error.message, {\n ...error.wireCode ? { wireCode: error.wireCode } : {},\n ...error.trace_id ? { trace_id: error.trace_id } : {},\n ...error.correlation_id ? { correlation_id: error.correlation_id } : {},\n retryable: error.retryable,\n ...operationId2 ? { operation_id: operationId2 } : {},\n ...idempotencyKey ? { idempotency_key: idempotencyKey } : {}\n });\n}\nfunction waitRemaining(ms2, signal) {\n if (signal?.aborted) return Promise.reject(new NochaError("aborted", "Generation wait was aborted"));\n if (ms2 <= 0) return Promise.resolve();\n return new Promise((resolve, reject2) => {\n const timer = setTimeout(finish, ms2);\n const onAbort = () => {\n clearTimeout(timer);\n signal?.removeEventListener("abort", onAbort);\n reject2(new NochaError("aborted", "Generation wait was aborted"));\n };\n function finish() {\n signal?.removeEventListener("abort", onAbort);\n resolve();\n }\n signal?.addEventListener("abort", onAbort, { once: true });\n });\n}\nfunction decoded(value, options) {\n return options?.decode && "structured" in value ? { ...value, structured: options.decode(value.structured) } : value;\n}\nasync function generate2(context, input3, options) {\n const paid = aiGenerateWire(input3);\n const wire = { ...paid, response_mode: "pending" };\n const started = Date.now();\n const total = options?.timeoutMs ?? deadlineMs("ai", "generate", paid);\n const key = options?.idempotencyKey;\n const signal = options?.signal;\n const admission = Math.min(total, generationWaiting.negotiatedAdmissionMs + generationWaiting.sdkMarginMs);\n let value;\n try {\n value = await context.invoke(aiOperationDefinitions["generate"].capability, aiOperationDefinitions["generate"].operation, wire, {\n ...options,\n timeoutMs: Math.max(1, admission)\n });\n } catch (error) {\n if (isNochaError(error) && (error.code === "aborted" || error.code === "invocation_timed_out")) throw withRecovery(error, void 0, key);\n throw error;\n }\n const pending2 = pendingReceipt(value);\n if (!pending2) return decoded(generationResult(input3.need, value), options);\n let pause2 = pending2.poll_after_ms;\n const operationId2 = pending2.operation_id;\n while (Date.now() - started < total) {\n const remaining = total - (Date.now() - started);\n try {\n await waitRemaining(Math.min(pause2, remaining), signal);\n } catch (error) {\n if (isNochaError(error)) throw withRecovery(error, operationId2, key);\n throw error;\n }\n if (Date.now() - started >= total) break;\n const budget2 = Math.max(1, Math.min(operationWaiting.ai.default, total - (Date.now() - started)));\n let status2;\n try {\n status2 = await get(context, { operationId: operationId2 }, { signal, timeoutMs: budget2 });\n } catch (error) {\n if (classifyError(error) !== "transient") throw isNochaError(error) ? withRecovery(error, operationId2, key) : error;\n pause2 = Math.min(generationWaiting.pollMaxMs, Math.max(pause2 * 2, generationWaiting.pollIntervalMs));\n continue;\n }\n if (status2.status === "succeeded") {\n const final = Object.fromEntries(Object.entries(status2).filter(([key2]) => !["status", "poll_after_ms", "failure"].includes(key2)));\n return decoded(generationResult(input3.need, final), options);\n }\n if (status2.status === "failed" || status2.status === "cancelled") {\n throw new NochaError("generation_failed", status2.failure?.message ?? "Generation could not be completed", { operation_id: operationId2, idempotency_key: key });\n }\n pause2 = Math.min(generationWaiting.pollMaxMs, Math.max(pause2 * 2, generationWaiting.pollIntervalMs));\n }\n throw new NochaError("invocation_timed_out", "Generation is still running", { operation_id: operationId2, idempotency_key: key });\n}\nasync function estimate(context, input3, options) {\n const wire = aiGenerateWire(input3);\n const value = await context.invoke(aiOperationDefinitions["estimate"].capability, aiOperationDefinitions["estimate"].operation, wire, options);\n if (!isRecord(value) || !isUuid(value.quote_id) || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at)) || !credits(value.estimated_cost_micro_usd) || !isRecord(value.estimated_usage) || !Object.values(value.estimated_usage).every(credits) || value.estimated_charge_microcredits !== void 0 && !credits(value.estimated_charge_microcredits) || value.creator_fee_microcredits !== void 0 && !credits(value.creator_fee_microcredits) || value.base_charge_microcredits !== void 0 && !credits(value.base_charge_microcredits) || typeof value.rate_card_id !== "string") throw reject("Nocha returned an invalid generation quote");\n return value;\n}\nvar decisionAnswerTypes = ["choice", "score", "noul"];\nasync function decide(context, input3, options) {\n const wire = aiDecideWire(input3);\n const value = await context.invoke(aiOperationDefinitions["decide"].capability, aiOperationDefinitions["decide"].operation, wire, options);\n if (!isRecord(value) || typeof value.operation_id !== "string" || typeof value.model !== "string" || value.capability !== "text.decide" || value.need !== "text.decision" || !isRecord(value.answers) || !Object.values(value.answers).every((answer) => isRecord(answer) && decisionAnswerTypes.includes(String(answer.type))) || !isRecord(value.billing) || !["participants", "project"].includes(String(value.billing.payer_mode)) || !["initiator", "project"].includes(String(value.billing.capability_calls)) || !credits(value.billing.participant_captured_microcredits)) {\n throw reject("Nocha returned an invalid decision");\n }\n return options?.decode ? { ...value, answers: options.decode(value.answers) } : value;\n}\nasync function get(context, input3, options) {\n const wire = aiGetWire(input3);\n const value = await context.invoke(aiOperationDefinitions["get"].capability, aiOperationDefinitions["get"].operation, wire, options);\n if (!isRecord(value) || typeof value.operation_id !== "string" || typeof value.need !== "string" || !["queued", "running", "succeeded", "failed", "cancelled"].includes(String(value.status)) || !isArrayOf(value.asset_ids, isString) || value.text !== void 0 && typeof value.text !== "string" || value.sources !== void 0 && !isArrayOf(value.sources, isSource) || value.search_call_count !== void 0 && (!Number.isSafeInteger(value.search_call_count) || Number(value.search_call_count) < 1) || value.audio_base64 !== void 0 && !isString(value.audio_base64) || value.mime_type !== void 0 && !isString(value.mime_type) || value.model !== void 0 && !isString(value.model) || value.seed !== void 0 && !Number.isInteger(value.seed) || value.assets !== void 0 && !isArrayOf(value.assets, assetShape) || value.billing !== void 0 && !isRecord(value.billing) || value.poll_after_ms !== void 0 && (!isFiniteNumber(value.poll_after_ms) || value.poll_after_ms < 0) || value.failure !== void 0 && (!isRecord(value.failure) || typeof value.failure.code !== "string" || typeof value.failure.message !== "string" || typeof value.failure.retryable !== "boolean")) {\n throw reject("Nocha returned an invalid generation operation");\n }\n return value;\n}\nasync function generationOptions(context, input3, options) {\n const wire = aiOptionsWire(input3);\n const value = await context.invoke(aiOperationDefinitions["options"].capability, aiOperationDefinitions["options"].operation, wire, options);\n if (!isRecord(value) || value.version !== 1 || typeof value.usage !== "string" || !["text", "image", "video", "voice", "music", "sound", "research", "import"].includes(String(value.family)) || !Array.isArray(value.efforts) || !value.efforts.every((effort) => ["low", "medium", "high"].includes(String(effort)))) {\n throw reject("Nocha returned invalid generation options");\n }\n return value;\n}\nvar isOptionalString = (value) => value === void 0 || isString(value);\nvar isStringList = (value) => isArrayOf(value, isString);\nasync function models(context, input3, options) {\n const wire = aiModelsWire(input3);\n const value = await context.invoke(aiOperationDefinitions["models"].capability, aiOperationDefinitions["models"].operation, wire, options);\n if (!isRecord(value) || value.need !== "audio.synthesize" || !isNonEmptyString(value.default_model) || !isArrayOf(value.models, (model) => isRecord(model) && isNonEmptyString(model.model) && isString(model.label) && typeof model.default === "boolean" && (model.languages === void 0 || isStringList(model.languages)))) {\n throw reject("Nocha returned invalid speech models");\n }\n return value;\n}\nasync function voices(context, input3, options) {\n const wire = aiVoicesWire(input3);\n const value = await context.invoke(aiOperationDefinitions["voices"].capability, aiOperationDefinitions["voices"].operation, wire, options);\n if (!isRecord(value) || !isNonEmptyString(value.model) || !isNonEmptyString(value.default_voice) || value.next_cursor !== null && !isNonEmptyString(value.next_cursor) || !isArrayOf(value.voices, (voice) => isRecord(voice) && isNonEmptyString(voice.id) && isString(voice.name) && isStringList(voice.languages) && (voice.collection === "standard" || voice.collection === "library") && [voice.description, voice.gender, voice.age, voice.accent, voice.alias].every(isOptionalString) && (voice.price_multiplier === void 0 || isFiniteNumber(voice.price_multiplier) && voice.price_multiplier > 0))) {\n throw reject("Nocha returned invalid speech voices");\n }\n return value;\n}\nfunction createAi(context) {\n return Object.freeze({\n generate: (input3, options) => generate2(context, input3, options),\n estimate: (input3, options) => estimate(context, input3, options),\n decide: (input3, options) => decide(context, input3, options),\n options: (input3, options) => generationOptions(context, input3, options),\n get: (input3, options) => get(context, input3, options),\n models: (input3, options) => models(context, input3, options),\n voices: (input3, options) => voices(context, input3, options)\n });\n}\n\n// src/media-read.ts\nfunction mediaReadTimeout(options, fallback) {\n if (!isRecord(options)) throw invalid("Request options must be an object");\n if (options.onProgress !== void 0 && typeof options.onProgress !== "function") throw invalid("onProgress must be a function");\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalid("signal must be an AbortSignal");\n const timeout = options.timeoutMs ?? fallback;\n if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid("timeoutMs must be a positive finite timer duration");\n return timeout;\n}\nfunction readHostMedia(read3) {\n const { noun, options } = read3;\n const subject2 = noun.charAt(0).toUpperCase() + noun.slice(1);\n const unsupported = () => new NochaError("media_unsupported_host", `This Nocha host cannot read ${noun} media`);\n const host = window.parent;\n const requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n let acknowledged = false;\n const cleanup = () => {\n clearTimeout(unanswered);\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const stop = (error) => {\n cleanup();\n try {\n host.postMessage({ protocol: "nocha.media.v1", type: "abort", requestId }, "*");\n } catch {\n }\n reject2(error);\n };\n const abort = () => stop(new NochaError("aborted", `${subject2} read aborted`));\n const receive = (event) => {\n const message = event.data;\n if (!isFromHost(event) || !isRecord(message) || message.protocol !== "nocha.media.v1" || message.requestId !== requestId) return;\n clearTimeout(unanswered);\n if (message.type === "progress") {\n acknowledged = true;\n if (options.onProgress && isCount(message.loaded) && (message.total === null || isCount(message.total))) {\n notifyListener(options.onProgress, { loaded: message.loaded, total: message.total });\n }\n return;\n }\n if (message.type !== "result" && message.type !== "error") return;\n cleanup();\n const value = message.type === "result" ? read3.accept(message.result) : void 0;\n if (message.type === "error" && read3.unknownReadRefused && !acknowledged && isRecord(message.error) && message.error.code === "invalid_request") reject2(unsupported());\n else if (message.type === "error") reject2(wireError(message.error, { code: "media_unavailable", message: `${subject2} media is unavailable` }));\n else if (value !== void 0) resolve(value);\n else reject2(new NochaError("invalid_result", `Nocha returned an invalid ${noun} file`));\n };\n const unanswered = read3.timeoutMs > read3.firstReplyMs ? setTimeout(() => stop(unsupported()), read3.firstReplyMs) : void 0;\n const timer = setTimeout(() => stop(new NochaError("invocation_timed_out", `Local ${noun} read timed out`)), read3.timeoutMs);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n read3.send(host, requestId);\n } catch (error) {\n cleanup();\n reject2(new NochaError("invalid_request", `The request cannot be sent to the Nocha host: ${error instanceof Error ? error.message : String(error)}`));\n }\n });\n}\n\n// src/assets-media.ts\nvar mediaTypes = new Set(assetMediaTypes);\nfunction isAssetMedia(value, id) {\n return isRecord(value) && value.id === id && mediaTypes.has(value.mime_type) && value.blob instanceof Blob && value.blob.type === value.mime_type && value.blob.size > 0 && value.blob.size <= ASSET_MEDIA_MAX_BYTES && value.size_bytes === value.blob.size;\n}\nasync function readAssetMedia(context, input3, options = {}) {\n if (!isRecord(input3) || !isUuid(input3.assetId)) throw new NochaError("invalid_request", "assetId must be an asset id");\n const assetId = input3.assetId;\n const timeout = mediaReadTimeout(options, operationWaiting.assets.media);\n assertHostCapability("assets");\n const usageId = context.usageId;\n if (usageId === void 0) throw new NochaError("usage_required", "assets.media requires nocha.use(<declared usage id>)");\n if (options.signal?.aborted) throw new NochaError("aborted", "Asset read aborted");\n return readHostMedia({\n noun: "asset",\n timeoutMs: timeout,\n firstReplyMs: operationWaiting.assets["media.firstReply"],\n options,\n unknownReadRefused: true,\n accept: (result2) => isAssetMedia(result2, assetId) ? result2.blob : void 0,\n send: (host, requestId) => host.postMessage({\n protocol: "nocha.media.v1",\n type: "read",\n requestId,\n capability: assetsOperationDefinitions["read"].capability,\n operation: assetsOperationDefinitions["read"].operation,\n usageId,\n input: { asset_id: assetId }\n }, "*")\n });\n}\n\n// src/attachments.ts\nvar maxBytes = 64 * 1024 * 1024;\nvar attachmentTypes = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp", "video/mp4", "audio/wav", "audio/mp4"]);\nasync function uploadAttachment(context, request, options = {}) {\n if (!isRecord(request)) throw invalid("An attachment request object is required");\n const file = request.file;\n if (!(file instanceof Blob) || file.size < 1 || file.size > maxBytes) throw invalid("The attachment must be between 1 byte and 64 MiB");\n if (!attachmentTypes.has(file.type)) throw invalid("Select a JPEG, PNG, WebP, MP4 or WAV file");\n if (file.type.startsWith("audio/") && file.size > 4 * 1024 * 1024) throw invalid("Audio attachments are limited to 4 MiB");\n if (request.filename !== void 0 && typeof request.filename !== "string") throw invalid("filename must be a string");\n assertHostCapability("assets");\n if (context.usageId === void 0) throw new NochaError("usage_required", "assets.uploadAttachment requires nocha.use(<declared usage id>)");\n if (options.idempotencyKey !== void 0 && !isIdempotencyKey(options.idempotencyKey)) throw invalid("idempotencyKey must contain 8 to 200 characters");\n if (options.signal?.aborted) throw new NochaError("aborted", "Attachment upload aborted");\n const filename = (request.filename ?? ("name" in file ? String(file.name) : "attachment")).replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 120);\n const upload2 = { filename, mime_type: file.type, size_bytes: file.size };\n const timeout = options.timeoutMs ?? deadlineMs(assetsOperationDefinitions.uploadAttachment.capability, assetsOperationDefinitions.uploadAttachment.operation, upload2);\n if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid("timeoutMs must be a positive finite timer duration");\n const host = window.parent;\n const requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const abort = () => {\n host.postMessage({ protocol: "nocha.upload.v1", type: "abort", requestId }, "*");\n cleanup();\n reject2(new NochaError("aborted", "Attachment upload aborted"));\n };\n const expire = () => {\n cleanup();\n reject2(new NochaError("invocation_timed_out", "Local upload wait timed out; the upload may still complete"));\n };\n const receive = (event) => {\n const message = event.data;\n if (!isFromHost(event) || !isRecord(message) || message.protocol !== "nocha.upload.v1" || message.requestId !== requestId) return;\n if (message.type === "progress") {\n if (options.onProgress) notifyListener(options.onProgress, { loaded: Number(message.loaded), total: file.size });\n return;\n }\n cleanup();\n const result2 = message.result;\n if (message.type === "result" && isRecord(result2) && isNonEmptyString(result2.id) && isString(result2.mime_type) && typeof result2.size_bytes === "string") resolve(result2);\n else reject2(wireError(message.error, { code: "upload_failed", message: "Attachment upload failed" }));\n };\n const timer = setTimeout(expire, timeout);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n host.postMessage({ protocol: "nocha.upload.v1", type: "upload", requestId, capability: assetsOperationDefinitions.uploadAttachment.capability, operation: assetsOperationDefinitions.uploadAttachment.operation, usageId: context.usageId, idempotencyKey: options.idempotencyKey ?? `${requestId}:attachment`, input: upload2, file }, "*");\n } catch (error) {\n cleanup();\n reject2(error);\n }\n });\n}\nasync function attachmentUrl(context, input3, options) {\n if (!isRecord(input3) || !isUuid(input3.postId) || !isUuid(input3.assetId)) throw invalid("postId and assetId must be record and asset ids");\n const value = await context.invoke(assetsOperationDefinitions["attachmentUrl"].capability, assetsOperationDefinitions["attachmentUrl"].operation, { post_id: input3.postId, asset_id: input3.assetId, ...input3.collection === void 0 ? {} : { collection: input3.collection } }, options);\n if (!isRecord(value) || !isNonEmptyString(value.url) || !attachmentTypes.has(value.mime_type)) throw new NochaError("invalid_result", "Nocha returned no attachment URL");\n return value;\n}\n\n// src/assets.ts\nvar readableTypes = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp", "audio/mpeg", "audio/wav", "audio/flac", "audio/ogg"]);\nvar uploadableTypes = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);\nvar videoTypes = /* @__PURE__ */ new Set(["video/mp4", "video/quicktime"]);\nvar audioTypes = /* @__PURE__ */ new Set(["audio/mpeg", "audio/wav"]);\nvar audioAliases = { "audio/mp3": "audio/mpeg", "audio/x-wav": "audio/wav", "audio/wave": "audio/wav", "audio/vnd.wave": "audio/wav" };\nvar maxMediaBytes = 64 * 1024 * 1024;\nasync function read2(context, input3, options) {\n if (!isRecord(input3) || !isUuid(input3.assetId)) throw new NochaError("invalid_request", "assetId must be an asset id");\n const value = await context.invoke(assetsOperationDefinitions["read"].capability, assetsOperationDefinitions["read"].operation, { asset_id: input3.assetId }, options);\n if (!isRecord(value) || value.id !== input3.assetId || !readableTypes.has(value.mime_type) || !isNonEmptyString(value.data_base64)) {\n throw new NochaError("invalid_result", "Nocha returned no readable asset");\n }\n return { ...value, data_url: `data:${String(value.mime_type)};base64,${value.data_base64}` };\n}\nfunction bytesToBase64(bytes) {\n let binary = "";\n for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));\n return btoa(binary);\n}\nfunction binaryType(file, filename) {\n if (file.type) {\n const type = file.type.toLowerCase();\n return videoTypes.has(type) || audioTypes.has(type) ? type : audioAliases[type];\n }\n const name = filename ?? ("name" in file ? String(file.name) : "");\n return /\\.(mp4|m4v)$/i.test(name) ? "video/mp4" : /\\.mov$/i.test(name) ? "video/quicktime" : /\\.mp3$/i.test(name) ? "audio/mpeg" : /\\.wav$/i.test(name) ? "audio/wav" : void 0;\n}\nasync function uploadBinary(context, file, mimeType, filename, options = {}) {\n const kind = mimeType.startsWith("audio/") ? "Audio" : "Video";\n if (file.size > maxMediaBytes) throw invalid(`The ${kind.toLowerCase()} file must be at most 64 MiB`);\n assertHostCapability("assets");\n if (context.usageId === void 0) throw new NochaError("usage_required", "assets.upload requires nocha.use(<declared usage id>)");\n if (options.idempotencyKey !== void 0 && !isIdempotencyKey(options.idempotencyKey)) throw invalid("idempotencyKey must contain 8 to 200 characters");\n if (options.signal?.aborted) throw new NochaError("aborted", `${kind} upload aborted`);\n const fallback = { "video/mp4": "source-video.mp4", "video/quicktime": "source-video.mov", "audio/mpeg": "soundtrack.mp3", "audio/wav": "soundtrack.wav" }[mimeType];\n const name = filename ?? ("name" in file ? String(file.name) : fallback);\n const input3 = { filename: name.replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 120), mime_type: mimeType, size_bytes: file.size };\n const timeout = options.timeoutMs ?? operationWaiting.assets.uploadAttachment;\n if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid("timeoutMs must be a positive finite timer duration");\n const host = window.parent;\n const requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const abort = () => {\n host.postMessage({ protocol: "nocha.upload.v1", type: "abort", requestId }, "*");\n cleanup();\n reject2(new NochaError("aborted", `${kind} upload aborted`));\n };\n const expire = () => {\n cleanup();\n reject2(new NochaError("invocation_timed_out", "Local upload wait timed out; the upload may still complete"));\n };\n const receive = (event) => {\n const message = event.data;\n if (!isFromHost(event) || !isRecord(message) || message.protocol !== "nocha.upload.v1" || message.requestId !== requestId) return;\n if (message.type === "progress") {\n if (options.onProgress) notifyListener(options.onProgress, { loaded: Number(message.loaded), total: file.size });\n return;\n }\n cleanup();\n const result2 = message.result;\n if (message.type === "result" && isRecord(result2) && isNonEmptyString(result2.id) && isString(result2.mime_type) && typeof result2.size_bytes === "string" && /^\\d+$/.test(result2.size_bytes)) resolve(result2);\n else reject2(wireError(message.error, { code: "upload_failed", message: `${kind} upload failed` }));\n };\n const timer = setTimeout(expire, timeout);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n host.postMessage({ protocol: "nocha.upload.v1", type: "upload", requestId, capability: assetsOperationDefinitions.upload.capability, operation: assetsOperationDefinitions.upload.operation, usageId: context.usageId, idempotencyKey: options.idempotencyKey ?? `${requestId}:upload`, input: input3, file }, "*");\n } catch (error) {\n cleanup();\n reject2(error);\n }\n });\n}\nasync function upload(context, input3, options) {\n if (!isRecord(input3) || !(input3.file instanceof Blob) || !input3.file.size) throw new NochaError("invalid_request", "A non-empty image, video or audio file is required");\n if (input3.filename !== void 0 && typeof input3.filename !== "string") throw new NochaError("invalid_request", "filename must be a string");\n const file = input3.file, binary = binaryType(file, input3.filename);\n if (binary) return uploadBinary(context, file, binary, input3.filename, options);\n if (!uploadableTypes.has(file.type)) throw new NochaError("invalid_request", "Choose a JPEG, PNG or WebP image, an MP4 or QuickTime video, or an MP3 or WAV audio file of at most 64 MiB");\n const value = await context.invoke(assetsOperationDefinitions["upload"].capability, assetsOperationDefinitions["upload"].operation, {\n data_base64: bytesToBase64(new Uint8Array(await file.arrayBuffer())),\n mime_type: file.type,\n filename: input3.filename ?? ("name" in file ? String(file.name) : "reference-image")\n }, options);\n if (!isRecord(value) || !isNonEmptyString(value.id) || !isString(value.mime_type) || typeof value.size_bytes !== "string" || !/^\\d+$/.test(value.size_bytes)) {\n throw new NochaError("invalid_result", "Nocha returned no uploaded asset");\n }\n return value;\n}\nfunction createAssets(context) {\n return Object.freeze({\n read: (input3, options) => read2(context, input3, options),\n media: (input3, options) => readAssetMedia(context, input3, options),\n upload: (input3, options) => upload(context, input3, options),\n uploadAttachment: (input3, options) => uploadAttachment(context, input3, options),\n attachmentUrl: (input3, options) => attachmentUrl(context, input3, options)\n });\n}\n\n// src/backend-server-error.ts\nvar codes = {\n invalid_request: true,\n identity_required: true,\n workspace_access_denied: true,\n usage_unknown: true,\n usage_operation_denied: true,\n usage_resource_denied: true,\n idempotency_conflict: true,\n database_conflict: true,\n backend_unavailable: true,\n backend_capacity_exceeded: true,\n backend_budget_exhausted: true,\n backend_route_unknown: true,\n backend_usage_denied: true,\n backend_resource_protected: true,\n backend_paid_capability_denied: true,\n backend_input_invalid: true,\n backend_output_invalid: true,\n backend_deadline_exceeded: true,\n backend_outcome_unknown: true,\n backend_revision_required: true\n};\nfunction isBackendServerErrorCode(value) {\n return typeof value === "string" && Object.hasOwn(codes, value);\n}\nvar BackendServerError = class extends Error {\n code;\n constructor(code) {\n super("Nocha backend operation failed.");\n this.name = "BackendServerError";\n this.code = isBackendServerErrorCode(code) ? code : "backend_unavailable";\n }\n};\n\n// src/backend-server-json.ts\nvar backendServerLimits = Object.freeze({\n outputBytes: 256 * 1024,\n transactionBytes: 128 * 1024,\n recordBytes: 16 * 1024,\n jsonDepth: 16,\n jsonNodes: 16384,\n transactionRecords: 16,\n collectionReads: 8,\n queryRecords: 100\n});\nfunction utf8Bytes(text5) {\n let size = 0;\n for (let index = 0; index < text5.length; index++) {\n const code = text5.charCodeAt(index);\n if (code < 128) size++;\n else if (code < 2048) size += 2;\n else if (code >= 55296 && code <= 56319 && index + 1 < text5.length && text5.charCodeAt(index + 1) >= 56320 && text5.charCodeAt(index + 1) <= 57343) {\n size += 4;\n index++;\n } else size += 3;\n }\n return size;\n}\nfunction encodeBackendServerJson(value, maxBytes2) {\n const fail = () => {\n throw new BackendServerError("backend_input_invalid");\n };\n if (!Number.isSafeInteger(maxBytes2) || maxBytes2 < 1 || maxBytes2 > backendServerLimits.outputBytes) fail();\n let nodes = 0, bytes = 0;\n const seen = /* @__PURE__ */ new Set();\n const add = (text5) => {\n bytes += utf8Bytes(text5);\n if (bytes > maxBytes2) fail();\n return text5;\n };\n function encode(item, depth) {\n if (++nodes > backendServerLimits.jsonNodes || depth > backendServerLimits.jsonDepth) return fail();\n if (item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item))\n return add(JSON.stringify(item));\n if (typeof item === "string") {\n if (item.length > maxBytes2 - bytes) return fail();\n return add(JSON.stringify(item));\n }\n if (typeof item !== "object" || !item || seen.has(item)) return fail();\n const array = Array.isArray(item);\n if (!array && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) return fail();\n seen.add(item);\n const keys = Reflect.ownKeys(item);\n if (keys.length > backendServerLimits.jsonNodes - nodes + (array ? 1 : 0)) return fail();\n if (array && (keys.length !== item.length + 1 || keys[keys.length - 1] !== "length")) return fail();\n const parts = [add(array ? "[" : "{")];\n const children = array ? keys.slice(0, -1) : keys;\n for (const [index, key] of children.entries()) {\n if (typeof key !== "string" || ["__proto__", "constructor", "prototype"].includes(key)) return fail();\n if (array && key !== String(index)) return fail();\n const descriptor = Object.getOwnPropertyDescriptor(item, key);\n if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) return fail();\n if (index) parts.push(add(","));\n if (!array) {\n if (key.length > maxBytes2 - bytes) return fail();\n parts.push(add(JSON.stringify(key)), add(":"));\n }\n parts.push(encode(descriptor.value, depth + 1));\n }\n parts.push(add(array ? "]" : "}"));\n return parts.join("");\n }\n try {\n const text5 = encode(value, 0);\n return { text: text5, value: JSON.parse(text5) };\n } catch {\n return fail();\n }\n}\n\n// src/backend.ts\nvar routePattern = /^[a-z][a-z0-9_-]{0,79}$/;\nvar receiptPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;\nvar failure = (output = false) => new NochaError(output ? "backend_output_invalid" : "backend_input_invalid", "Invalid Nocha backend envelope.");\nvar uncertainErrors = /* @__PURE__ */ new Set([\n "invocation_timed_out",\n "aborted",\n "request_cancelled",\n "request_failed",\n "invalid_response",\n "invalid_result",\n "invocation_failed",\n "unknown_error"\n]);\nfunction record(value, keys, output = false) {\n try {\n if (!value || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw failure(output);\n const own = Reflect.ownKeys(value);\n if (own.length !== keys.length || !own.every((key) => typeof key === "string" && keys.includes(key))) throw failure(output);\n const copy = {};\n for (const key of keys) {\n const field3 = Object.getOwnPropertyDescriptor(value, key);\n if (!field3?.enumerable || !("value" in field3)) throw failure(output);\n copy[key] = field3.value;\n }\n return copy;\n } catch {\n throw failure(output);\n }\n}\nfunction json(value, bytes, output = false) {\n try {\n return encodeBackendServerJson(value, bytes).value;\n } catch {\n throw failure(output);\n }\n}\nfunction receipt(value) {\n if (typeof value !== "string" || !receiptPattern.test(value)) throw failure();\n return value;\n}\nfunction status(value) {\n let state;\n try {\n state = Object.getOwnPropertyDescriptor(value, "status")?.value;\n } catch {\n throw failure(true);\n }\n const extra = state === "succeeded" ? ["result"] : state === "failed" || state === "outcome_unknown" ? ["error"] : [];\n const item = record(value, ["receipt", "routeId", "status", ...extra], true);\n if (typeof item.receipt !== "string" || !receiptPattern.test(item.receipt) || typeof item.routeId !== "string" || !routePattern.test(item.routeId)) throw failure(true);\n const base2 = { receipt: item.receipt, routeId: item.routeId };\n switch (item.status) {\n case "admitted":\n case "waiting_capacity":\n case "running":\n case "cancelled":\n return { ...base2, status: item.status };\n case "succeeded":\n return { ...base2, status: "succeeded", result: json(item.result, 256 * 1024, true) };\n case "failed":\n case "outcome_unknown": {\n const error = record(item.error, ["code", "message"], true);\n const code = experienceBackendErrorCodes.find((code2) => code2 === error.code);\n if (!code || typeof error.message !== "string" || !error.message.length || error.message.length > 1e3) throw failure(true);\n return { ...base2, status: item.status, error: { code, message: "Nocha backend operation failed." } };\n }\n default:\n throw failure(true);\n }\n}\nfunction createBackend(context) {\n async function invoke(operation2, input3, idempotencyKey) {\n try {\n const result2 = status(await context.invoke("backend", operation2, input3, { idempotencyKey }));\n const expected = input3;\n if (expected.routeId !== void 0 && result2.routeId !== expected.routeId || expected.receipt !== void 0 && result2.receipt !== expected.receipt) throw failure(true);\n return result2;\n } catch (cause) {\n if (isNochaError(cause) && !uncertainErrors.has(cause.code)) {\n const message = cause.code === "bridge_unavailable" ? "Backend calls require the embedded Nocha host." : cause.code === "backend_unavailable" ? "Nocha backend requires available durable host storage and backend service." : cause.code === "backend_outcome_unknown" ? "Nocha backend outcome is unknown; reconcile the same intention." : "Nocha backend operation could not be completed.";\n throw new NochaError(cause.code, message);\n }\n throw new NochaError("backend_outcome_unknown", "Nocha backend outcome is unknown; reconcile the same intention.");\n }\n }\n return Object.freeze({\n async request(routeId, input3, options) {\n const parsed = record(options, ["idempotencyKey"]);\n if (typeof routeId !== "string" || !routePattern.test(routeId) || typeof parsed.idempotencyKey !== "string" || !/^[\\x21-\\x7e]{8,200}$/.test(parsed.idempotencyKey)) throw failure();\n return invoke("request", { routeId, input: json(input3, 64 * 1024) }, parsed.idempotencyKey);\n },\n async get(value) {\n const handle = receipt(value);\n return invoke("get", { receipt: handle }, handle);\n },\n async cancel(value) {\n const handle = receipt(value);\n return invoke("cancel", { receipt: handle }, handle);\n }\n });\n}\n\n// src/assistant-controls.ts\nvar PAGE_SIZE = 5;\nvar selector = \'button,a[href],[role="button"],[role="tab"],select,textarea,input:not([type]),input[type="text"],input[type="search"],input[type="button"],input[type="submit"]\';\nvar sensitive = /password|passwd|secret|token|credit.?card|card.?number|cvc|cvv|one.?time|email|e-mail|phone|telephone|address|billing/i;\nfunction registerAssistantControls(register, options) {\n const { root } = options;\n const ids2 = /* @__PURE__ */ new WeakMap();\n let nextId = 0, page = 0, stopped = false, timer;\n function controls() {\n const modal = root.querySelector(\'dialog[open],[role="dialog"][aria-modal="true"]\');\n const scope = modal ?? root;\n const result2 = [];\n for (const element of Array.from(scope.querySelectorAll(selector))) {\n if (result2.length >= 200) break;\n if (!element.isConnected || element.closest(\'[hidden],[inert],[aria-hidden="true"],[data-assistant-private]\') || element.matches(\':disabled,[aria-disabled="true"]\') || !element.getClientRects().length) continue;\n const style = getComputedStyle(element);\n if (style.visibility === "hidden" || style.display === "none") continue;\n const field3 = element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement;\n if (field3 && (element.readOnly || sensitive.test([element.name, element.id, element.autocomplete, element.getAttribute("aria-label")].join(" ")))) continue;\n if (field3 && element instanceof HTMLInputElement && !["text", "search", "button", "submit"].includes(element.type)) continue;\n const label = (element.getAttribute("aria-label") || (field3 ? element.labels?.[0]?.textContent || element.getAttribute("placeholder") : element.textContent) || element.getAttribute("title") || "").replace(/\\s+/g, " ").trim().slice(0, 64);\n if (!label) continue;\n const anchor = element instanceof HTMLAnchorElement ? new URL(element.href, location.href) : null;\n if (anchor && (anchor.origin !== location.origin || anchor.pathname !== location.pathname || anchor.search !== location.search || !anchor.hash || element.hasAttribute("download"))) continue;\n let id = ids2.get(element);\n if (!id) {\n id = `c${++nextId}`;\n ids2.set(element, id);\n }\n const editable2 = element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement && ["text", "search"].includes(element.type);\n result2.push({ id, label, kind: anchor || element.getAttribute("role") === "tab" ? "navigation" : editable2 ? "field" : element instanceof HTMLSelectElement ? "choice" : "action", element });\n }\n return result2;\n }\n function find(id, kind) {\n const control = controls().find((item) => item.id === id && (!kind || item.kind === kind));\n if (!control) throw new Error("Ce contr\\xF4le a chang\\xE9 ou n\\u2019est plus disponible. Relisez le contexte.");\n return control;\n }\n const done = () => ({ status: "completed" });\n function parse(value) {\n const data = JSON.parse(value);\n if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" || !("text" in data) || typeof data.text !== "string") throw new Error(\'Valeur attendue : {"id":"c1","text":"texte"}.\');\n return { id: data.id, text: data.text };\n }\n const binding = register({\n snapshot() {\n const list2 = controls();\n page = Math.min(page, Math.max(0, Math.ceil(list2.length / PAGE_SIZE) - 1));\n return {\n title: options.title.slice(0, 80),\n page: location.hash.slice(0, 100) || "/",\n controlsPage: page + 1,\n controlsPages: Math.max(1, Math.ceil(list2.length / PAGE_SIZE)),\n controls: list2.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE).map(({ id, label, kind, element }) => ({\n id,\n label,\n kind,\n ...element instanceof HTMLSelectElement ? { options: Array.from(element.options).filter((option) => !option.disabled).slice(0, 8).map((option) => ({ value: option.value.slice(0, 40), label: option.text.slice(0, 40) })) } : {}\n })),\n ...options.snapshot ? { context: options.snapshot() } : {}\n };\n },\n actions: {\n show_controls: { description: "Afficher une page de contr\\xF4les. Valeur : num\\xE9ro de page (1 \\xE0 controlsPages).", run(value) {\n const next = Number(value);\n if (!Number.isInteger(next) || next < 1 || next > Math.max(1, Math.ceil(controls().length / PAGE_SIZE))) throw new Error("Page de contr\\xF4les inconnue.");\n page = next - 1;\n return done();\n } },\n navigate_control: { description: "Apr\\xE8s confirmation Nocha, ouvrir un onglet ou lien interne de kind navigation. Valeur : id cN.", run(value) {\n find(value, "navigation").element.click();\n return done();\n } },\n set_field: { description: \'Apr\\xE8s confirmation Nocha, \\xE9crire dans un champ visible. Sa logique peut enregistrer automatiquement. JSON {"id":"cN","text":"texte"}.\', run(value) {\n const input3 = parse(value), field3 = find(input3.id, "field").element;\n const maximum = field3.maxLength >= 0 ? Math.min(1400, field3.maxLength) : 1400;\n if (input3.text.length > maximum) throw new Error(`Le champ accepte ${maximum} caract\\xE8res maximum.`);\n const prototype = field3 instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;\n Object.getOwnPropertyDescriptor(prototype, "value").set.call(field3, input3.text);\n field3.dispatchEvent(new Event("input", { bubbles: true }));\n field3.dispatchEvent(new Event("change", { bubbles: true }));\n return done();\n } },\n activate_control: { description: \'Apr\\xE8s confirmation explicite dans Nocha, activer un bouton d\\xE9clar\\xE9. Valeur : id cN. Pour une liste de choix : JSON {"id":"cN","text":"valeur"}. Ne pas annoncer un r\\xE9sultat final sur simple activation.\', run(value) {\n if (value.startsWith("{")) {\n const input3 = parse(value), field3 = find(input3.id, "choice").element;\n if (!Array.from(field3.options).some((option) => option.value === input3.text && !option.disabled)) throw new Error("Choix indisponible.");\n field3.value = input3.text;\n field3.dispatchEvent(new Event("change", { bubbles: true }));\n } else find(value, "action").element.click();\n return { status: "started", message: "Contr\\xF4le activ\\xE9. V\\xE9rifiez le nouvel \\xE9tat pour conna\\xEEtre le r\\xE9sultat." };\n } }\n }\n });\n const changed = () => {\n if (stopped || timer) return;\n timer = setTimeout(() => {\n timer = void 0;\n binding.changed();\n }, 100);\n };\n const observer = new MutationObserver(changed);\n observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["hidden", "disabled", "aria-hidden", "aria-disabled", "aria-label", "open"] });\n root.addEventListener("input", changed);\n root.addEventListener("change", changed);\n window.addEventListener("hashchange", changed);\n return { changed: binding.changed, dispose() {\n if (stopped) return;\n stopped = true;\n clearTimeout(timer);\n observer.disconnect();\n root.removeEventListener("input", changed);\n root.removeEventListener("change", changed);\n window.removeEventListener("hashchange", changed);\n binding.dispose();\n } };\n}\n\n// src/assistant-contract.ts\nvar ASSISTANT_CONTEXT_MAX_BYTES = 24 * 1024;\nvar ASSISTANT_ARGUMENTS_MAX_BYTES = 8 * 1024;\nvar ASSISTANT_DESCRIPTION_MAX_CHARS = 4e3;\nvar ASSISTANT_CONFIRMATION_ACTIONS = /* @__PURE__ */ new Set(["navigate_control", "set_field", "activate_control"]);\nvar object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);\nfunction assertAssistantJson(value, maxBytes2, maxDepth = 8) {\n let nodes = 0;\n function visit(item, depth) {\n if (++nodes > 2048 || depth > maxDepth) throw new TypeError("Assistant data is too complex.");\n if (item === null || typeof item === "boolean" || typeof item === "string" || typeof item === "number" && Number.isFinite(item)) return;\n if (Array.isArray(item)) {\n for (const child of item) visit(child, depth + 1);\n return;\n }\n if (object(item) && [Object.prototype, null].includes(Object.getPrototypeOf(item))) {\n for (const [key, child] of Object.entries(item)) {\n if (["__proto__", "constructor", "prototype"].includes(key)) throw new TypeError("Unsafe Assistant data key.");\n visit(child, depth + 1);\n }\n return;\n }\n throw new TypeError("Assistant data must contain JSON values only.");\n }\n visit(value, 0);\n if (new TextEncoder().encode(JSON.stringify(value)).length > maxBytes2) throw new TypeError("Assistant data exceeds its byte budget.");\n}\nfunction assertAssistantArgumentsSchema(value) {\n assertAssistantJson(value, 4096, 14);\n function visit(schema, depth) {\n if (!object(schema) || depth > 6 || !["object", "array", "string", "number", "integer", "boolean", "null"].includes(String(schema.type))) throw new TypeError("Assistant argument schemas require an explicit supported type.");\n const common2 = ["type", "title", "description", "enum", "const"];\n const typed = schema.type === "object" ? ["properties", "required", "additionalProperties"] : schema.type === "array" ? ["items", "minItems", "maxItems"] : schema.type === "string" ? ["minLength", "maxLength"] : ["number", "integer"].includes(String(schema.type)) ? ["minimum", "maximum"] : [];\n if (Object.keys(schema).some((key) => !common2.includes(key) && !typed.includes(key))) throw new TypeError("Unsupported Assistant JSON Schema keyword.");\n for (const key of ["title", "description"]) if (schema[key] !== void 0 && typeof schema[key] !== "string") throw new TypeError("Schema annotations must be text.");\n if (schema.enum !== void 0 && (!Array.isArray(schema.enum) || !schema.enum.length)) throw new TypeError("Schema enum must be a non-empty array.");\n if (schema.properties !== void 0) {\n if (!object(schema.properties)) throw new TypeError("Schema properties must be an object.");\n for (const child of Object.values(schema.properties)) visit(child, depth + 1);\n }\n if (schema.required !== void 0 && (!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string" || !object(schema.properties) || !Object.hasOwn(schema.properties, key)))) throw new TypeError("Schema required keys must have declared properties.");\n if (schema.additionalProperties !== void 0 && typeof schema.additionalProperties !== "boolean") throw new TypeError("Schema additionalProperties must be a boolean.");\n if (schema.items !== void 0) visit(schema.items, depth + 1);\n for (const key of ["minLength", "maxLength", "minItems", "maxItems"]) if (schema[key] !== void 0 && (!Number.isSafeInteger(schema[key]) || Number(schema[key]) < 0)) throw new TypeError("Schema limits must be positive integers.");\n for (const key of ["minimum", "maximum"]) if (schema[key] !== void 0 && (typeof schema[key] !== "number" || !Number.isFinite(schema[key]))) throw new TypeError("Schema limits must be finite numbers.");\n }\n visit(value, 0);\n if (!object(value) || value.type !== "object") throw new TypeError("Assistant arguments must use an object schema.");\n}\nfunction canonical(value) {\n if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;\n if (object(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;\n return JSON.stringify(value);\n}\nfunction assertAssistantArguments(value, schema) {\n assertAssistantArgumentsSchema(schema);\n assertAssistantJson(value, ASSISTANT_ARGUMENTS_MAX_BYTES);\n function visit(item, node, path) {\n const fail = () => {\n throw new TypeError(`Invalid Assistant argument at ${path}.`);\n };\n if (node.const !== void 0 && canonical(item) !== canonical(node.const)) fail();\n if (node.enum && !node.enum.some((candidate) => canonical(candidate) === canonical(item))) fail();\n if (node.type === "object") {\n if (!object(item)) {\n fail();\n return;\n }\n if (node.required?.some((key) => !Object.hasOwn(item, key))) fail();\n for (const [key, child] of Object.entries(item)) {\n const next = node.properties && Object.hasOwn(node.properties, key) ? node.properties[key] : void 0;\n if (next) visit(child, next, `${path}.${key}`);\n else if (node.additionalProperties === false) fail();\n }\n } else if (node.type === "array") {\n if (!Array.isArray(item)) {\n fail();\n return;\n }\n if (node.minItems !== void 0 && item.length < node.minItems || node.maxItems !== void 0 && item.length > node.maxItems) fail();\n if (node.items) item.forEach((child, index) => visit(child, node.items, `${path}[${index}]`));\n } else if (node.type === "string") {\n if (typeof item !== "string") {\n fail();\n return;\n }\n const length = Array.from(item).length;\n if (node.minLength !== void 0 && length < node.minLength || node.maxLength !== void 0 && length > node.maxLength) fail();\n } else if (node.type === "number" || node.type === "integer") {\n if (typeof item !== "number" || node.type === "integer" && !Number.isInteger(item)) {\n fail();\n return;\n }\n if (node.minimum !== void 0 && item < node.minimum || node.maximum !== void 0 && item > node.maximum) fail();\n } else if (node.type === "null" ? item !== null : typeof item !== "boolean") fail();\n }\n visit(value, schema, "arguments");\n}\n\n// src/assistant.ts\nvar record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;\nvar actionName = /^[a-z][a-z0-9_]{0,39}$/;\nvar release;\nvar assistant = Object.freeze({\n registerControls(options) {\n assertHostCapability("assistant");\n return registerAssistantControls(assistant.register, options);\n },\n register(registration) {\n assertHostCapability("assistant");\n if (!record2(registration) || typeof registration.snapshot !== "function" || !record2(registration.actions)) {\n throw new NochaError("invalid_request", "Assistant registration requires snapshot() and an actions object.");\n }\n const entries = Object.entries(registration.actions);\n if (entries.length > 24 || entries.some(([name, action]) => !actionName.test(name) || typeof action.description !== "string" || action.description.length > ASSISTANT_DESCRIPTION_MAX_CHARS || typeof action.run !== "function")) throw new NochaError("invalid_request", "Assistant actions require up to 24 names (40 characters), descriptions (4000 characters), and handlers.");\n for (const [, action] of entries) {\n if (action.argumentsSchema !== void 0) assertAssistantArgumentsSchema(action.argumentsSchema);\n if (action.confirmation !== void 0 && !["required", "none"].includes(action.confirmation)) throw new NochaError("invalid_request", "Invalid Assistant confirmation policy.");\n }\n const actions = new Map(entries), bridgeId = crypto.randomUUID();\n const calls = /* @__PURE__ */ new Map();\n let settled = 0;\n const host = typeof window !== "undefined" && window.parent !== window ? window.parent : void 0;\n const legacyCompatible = entries.every(([, action]) => !action.argumentsSchema && action.description.length <= 400 && action.availability === void 0 && action.confirmation !== "required");\n let disposed = false, version = 1, revision = 0, timer, negotiation, last = "";\n function send(event) {\n if (!disposed) host?.postMessage({ protocol: NOCHA_BRIDGE_PROTOCOL, type: "event", event: { ...event, bridgeId } }, "*");\n }\n function context() {\n const state = registration.snapshot();\n if (!record2(state)) throw new NochaError("invalid_request", "Assistant snapshot must be a JSON object.");\n assertAssistantJson(state, 12 * 1024, 6);\n const descriptions = entries.map(([name, action]) => {\n const availability = typeof action.availability === "function" ? action.availability() : action.availability ?? { available: true };\n if (typeof availability.available !== "boolean" || availability.reason !== void 0 && (typeof availability.reason !== "string" || availability.reason.length > 400)) throw new NochaError("invalid_request", "Invalid Assistant action availability.");\n return {\n name,\n description: action.description,\n ...action.argumentsSchema ? { argumentsSchema: action.argumentsSchema } : {},\n availability,\n confirmation: ASSISTANT_CONFIRMATION_ACTIONS.has(name) ? "required" : action.confirmation ?? "none"\n };\n });\n const value = { state, actions: descriptions };\n assertAssistantJson(value, ASSISTANT_CONTEXT_MAX_BYTES - 256, 18);\n const encoded = JSON.stringify(value);\n if (encoded !== last) {\n revision++;\n last = encoded;\n }\n return value;\n }\n function publish(force = false) {\n if (disposed) return;\n const previous = last, value = context();\n if (version === 1 && !legacyCompatible) return;\n if (!force && previous === last) return;\n const event = version === 2 ? { type: "experience.assistant.context", version, contextRevision: String(revision), ...value } : { type: "experience.assistant.context", version, state: value.state, actions: entries.map(([name, action]) => ({ name, description: action.description })) };\n assertAssistantJson({ ...event, bridgeId }, version === 2 ? ASSISTANT_CONTEXT_MAX_BYTES : 12 * 1024, 18);\n send(event);\n }\n function reportError(error) {\n if (typeof registration.onError === "function") notifyListener(registration.onError.bind(registration), error instanceof Error ? error : new Error(String(error)));\n }\n function safePublish(force = false) {\n try {\n publish(force);\n } catch (error) {\n last = "";\n send({ type: "experience.assistant.clear" });\n reportError(error);\n }\n }\n function observe(callId, result2) {\n const call2 = calls.get(callId);\n if (!call2 || call2.terminal || disposed) return;\n if (!result2 || !["completed", "started", "awaiting_user", "failed"].includes(result2.status)) throw new NochaError("invalid_request", "The action did not return a valid outcome.");\n assertAssistantJson(result2, 8192);\n if (result2.message !== void 0 && (typeof result2.message !== "string" || result2.message.length > 2e3)) throw new NochaError("invalid_request", "Assistant outcome messages have at most 2000 characters.");\n call2.terminal = result2.status === "completed" || result2.status === "failed";\n call2.latest = { ok: result2.status !== "failed", ...result2 };\n if (call2.terminal) {\n calls.delete(callId);\n calls.set(callId, call2);\n settled++;\n for (const [id, entry] of calls) {\n if (settled <= 200) break;\n if (entry.terminal) {\n calls.delete(id);\n settled--;\n }\n }\n }\n send({ type: "experience.assistant.result", callId, contextRevision: String(revision), result: call2.latest });\n safePublish();\n }\n function receive(event) {\n if (!host || !isFromHost(event)) return;\n const envelope = record2(event.data), message = record2(envelope?.event);\n if (envelope?.protocol !== NOCHA_BRIDGE_PROTOCOL || envelope.type !== "event" || !message) return;\n if (message.type === "experience.assistant.request") {\n if (Array.isArray(message.versions) && message.versions.includes(2)) {\n version = 2;\n clearTimeout(negotiation);\n }\n safePublish(true);\n return;\n }\n if (message.bridgeId !== bridgeId) return;\n if (message.type === "experience.assistant.accept" && message.version === 2) {\n version = 2;\n clearTimeout(negotiation);\n safePublish(true);\n return;\n }\n if (message.type !== "experience.assistant.action") return;\n const { callId, action: name } = message;\n if (typeof callId !== "string" || !callId.length || callId.length > 160 || typeof name !== "string") return;\n const previous = calls.get(callId);\n if (previous) {\n send({ type: "experience.assistant.result", callId, contextRevision: String(revision), result: previous.latest });\n return;\n }\n if (calls.size - settled >= 200) {\n send({ type: "experience.assistant.result", callId, result: { ok: false, status: "failed", message: "Too many assistant actions are in progress. Retry once one of them finishes." } });\n return;\n }\n calls.set(callId, { latest: { ok: true, status: "started" }, terminal: false });\n void Promise.resolve().then(() => {\n if (disposed) throw new Error("The experience was closed.");\n const latest = context(), action = actions.get(name), contract = latest.actions.find((item) => item.name === name);\n if (!action || !contract || !contract.availability.available) throw new Error(contract?.availability.reason || "This action is unavailable.");\n if (version === 2 && message.expectedContextRevision !== String(revision)) {\n safePublish(true);\n throw new Error("Experience context changed. Read the current revision before acting.");\n }\n if (version === 2 && contract.confirmation === "required" && message.confirmed !== true) throw new Error("This action requires host confirmation.");\n const execution = { callId, report: (result2) => observe(callId, result2) };\n if (action.argumentsSchema) {\n if (version !== 2) throw new Error("Structured arguments require Assistant bridge v2.");\n assertAssistantArguments(message.arguments, action.argumentsSchema);\n return action.run(message.arguments, execution);\n }\n const value = message.value ?? record2(message.arguments)?.value ?? "";\n if (typeof value !== "string" || value.length > 1600) throw new NochaError("invalid_request", "Legacy Assistant values are strings of at most 1600 characters.");\n return action.run(value, execution);\n }).then((result2) => observe(callId, result2)).catch((error) => observe(callId, { status: "failed", message: (error instanceof Error ? error.message : String(error)).slice(0, 2e3) }));\n }\n context();\n release?.();\n if (host) window.addEventListener("message", receive);\n send({ type: "experience.assistant.hello", versions: [2, 1] });\n safePublish(true);\n if (host && !legacyCompatible) negotiation = setTimeout(() => {\n if (version !== 2) reportError(new Error("This experience requires a Nocha host supporting Assistant bridge v2."));\n }, 2e3);\n const binding = {\n changed() {\n if (disposed) return;\n clearTimeout(timer);\n timer = setTimeout(() => safePublish(), 100);\n },\n dispose() {\n if (disposed) return;\n send({ type: "experience.assistant.clear" });\n disposed = true;\n clearTimeout(timer);\n clearTimeout(negotiation);\n if (host) window.removeEventListener("message", receive);\n if (release === binding.dispose) release = void 0;\n }\n };\n release = binding.dispose;\n return binding;\n }\n});\n\n// src/context.ts\nvar usagePattern2 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;\nvar hostCapabilities = /* @__PURE__ */ new Set(["access", "workspace"]);\nfunction createContext(usageId) {\n if (usageId !== void 0 && (typeof usageId !== "string" || !usagePattern2.test(usageId))) {\n throw new NochaError("invalid_request", "nocha.use() requires a usage id declared in NOCHA.json");\n }\n const optionsFor = (capability, operation2, options) => {\n assertHostCapability(capability);\n if (usageId === void 0 && !hostCapabilities.has(capability)) throw new NochaError("usage_required", `${capability}.${operation2} requires nocha.use(<declared usage id>)`);\n if (options === null || typeof options !== "object") throw new NochaError("invalid_request", "Request options must be an object");\n const { idempotencyKey, timeoutMs, signal } = options;\n return {\n ...idempotencyKey !== void 0 ? { idempotencyKey } : {},\n ...timeoutMs !== void 0 ? { timeoutMs } : {},\n ...signal !== void 0 ? { signal } : {},\n ...usageId !== void 0 ? { usageId } : {}\n };\n };\n const invoke = (capability, operation2, input3 = {}, options = {}) => {\n try {\n return invokeBridge(capability, operation2, input3, optionsFor(capability, operation2, options));\n } catch (error) {\n return Promise.reject(error);\n }\n };\n const invokeWithPort = (capability, operation2, input3 = {}, options = {}) => {\n try {\n return invokeBridgeWithPort(capability, operation2, input3, optionsFor(capability, operation2, options));\n } catch (error) {\n return Promise.reject(error);\n }\n };\n return Object.freeze({ usageId, invoke, invokeWithPort });\n}\n\n// src/live-media.ts\nvar installedMediaDevices = /* @__PURE__ */ new WeakSet();\nfunction domFailure(name, message, code) {\n const error = new DOMException(message, name);\n Object.defineProperty(error, "nochaCode", { configurable: true, enumerable: false, value: code });\n return error;\n}\nfunction bridgeFailure(error) {\n const code = isNochaError(error) ? error.wireCode ?? error.code : "unknown_error";\n const message = error instanceof Error && error.message ? error.message : "Live camera or microphone access failed";\n if (code === "media_permission_denied") return domFailure("NotAllowedError", message, code);\n if (code === "media_device_busy") return domFailure("NotReadableError", message, code);\n if (code === "media_device_missing") return domFailure("NotFoundError", message, code);\n if (code === "device_operation_unknown") return domFailure("NotSupportedError", `${message} \\u2014 Mets \\xE0 jour l\\u2019app Nocha.`, code);\n if (code === "media_requires_experience_host" || code === "media_sign_in_required" || code === "usage_unknown" || code === "usage_operation_denied" || code === "usage_resource_denied" || code === "usage_scope_denied" || code === "usage_required" || code === "capability_denied") {\n return domFailure("SecurityError", message, code);\n }\n if (error instanceof DOMException) return error;\n return domFailure("OperationError", message, code);\n}\nfunction exactOrIdeal(value) {\n if (!isRecord(value)) return value;\n return value.exact ?? value.ideal;\n}\nfunction boundedNumber(value, minimum, maximum, name) {\n const selected2 = exactOrIdeal(value);\n if (selected2 === void 0) return void 0;\n if (!isFiniteNumber(selected2)) throw domFailure("OverconstrainedError", `${name} must be a finite number`, "invalid_request");\n if (isRecord(value) && value.exact !== void 0 && (selected2 < minimum || selected2 > maximum)) {\n throw domFailure("OverconstrainedError", `${name} cannot be satisfied`, "invalid_request");\n }\n return Math.round(Math.min(maximum, Math.max(minimum, selected2)));\n}\nfunction facingMode(value) {\n const selected2 = exactOrIdeal(value);\n const candidate = Array.isArray(selected2) ? selected2.find((item) => item === "user" || item === "environment") : selected2;\n if (candidate === "user" || candidate === "environment") return candidate;\n if (isRecord(value) && value.exact !== void 0) throw domFailure("OverconstrainedError", "facingMode cannot be satisfied", "invalid_request");\n return void 0;\n}\nfunction booleanConstraint(value) {\n const selected2 = exactOrIdeal(value);\n return typeof selected2 === "boolean" ? selected2 : void 0;\n}\nfunction videoInput(value) {\n if (value === void 0 || value === false) return null;\n if (value === true) return {};\n if (!isRecord(value)) throw domFailure("TypeError", "Invalid video constraints", "invalid_request");\n return {\n ...facingMode(value.facingMode) ? { facingMode: facingMode(value.facingMode) } : {},\n ...boundedNumber(value.width, 160, 1280, "width") !== void 0 ? { width: boundedNumber(value.width, 160, 1280, "width") } : {},\n ...boundedNumber(value.height, 120, 720, "height") !== void 0 ? { height: boundedNumber(value.height, 120, 720, "height") } : {},\n ...boundedNumber(value.frameRate, 5, 30, "frameRate") !== void 0 ? { frameRate: boundedNumber(value.frameRate, 5, 30, "frameRate") } : {}\n };\n}\nfunction audioInput(value) {\n if (value === void 0 || value === false) return null;\n if (value === true) return {};\n if (!isRecord(value)) throw domFailure("TypeError", "Invalid audio constraints", "invalid_request");\n const echoCancellation = booleanConstraint(value.echoCancellation);\n const noiseSuppression = booleanConstraint(value.noiseSuppression);\n const autoGainControl = booleanConstraint(value.autoGainControl);\n return {\n ...echoCancellation !== void 0 ? { echoCancellation } : {},\n ...noiseSuppression !== void 0 ? { noiseSuppression } : {},\n ...autoGainControl !== void 0 ? { autoGainControl } : {}\n };\n}\nfunction isLiveResult(value) {\n const video = isRecord(value) ? value.video : void 0;\n const audio = isRecord(value) ? value.audio : void 0;\n return isRecord(value) && isString(value.session) && (video === null || isRecord(video) && ["width", "height", "frameRate"].every((key) => isFiniteNumber(video[key])) && (video.facingMode === "user" || video.facingMode === "environment")) && (audio === null || isRecord(audio) && isFiniteNumber(audio.sampleRate) && audio.channelCount === 1);\n}\nfunction patchTrack(track, settings, stopped) {\n const nativeStop = track.stop.bind(track);\n let closed = false;\n Object.defineProperty(track, "getSettings", {\n configurable: true,\n value: () => ({ ...MediaStreamTrack.prototype.getSettings.call(track), ...settings })\n });\n Object.defineProperty(track, "stop", {\n configurable: true,\n value: () => {\n if (closed) return;\n closed = true;\n nativeStop();\n stopped();\n }\n });\n return (ended) => {\n if (closed) return;\n closed = true;\n nativeStop();\n stopped();\n if (ended) track.dispatchEvent(new Event("ended"));\n };\n}\nfunction genericDevice(kind, deviceId, label) {\n const value = { deviceId, groupId: "nocha-live-media", kind, label };\n return { ...value, toJSON: () => ({ ...value }) };\n}\nfunction createLiveMedia(context) {\n const invokeBridge2 = (capability, operation2, input3, timeoutMs) => context.invokeWithPort(capability, operation2, input3, { timeoutMs });\n const getUserMedia = (constraints) => {\n let video;\n let audio;\n try {\n if (!isRecord(constraints)) throw domFailure("TypeError", "Media constraints are required", "invalid_request");\n const mediaConstraints = constraints;\n video = videoInput(mediaConstraints.video);\n audio = audioInput(mediaConstraints.audio);\n if (!video && !audio) throw domFailure("TypeError", "Camera or microphone constraints are required", "invalid_request");\n } catch (error) {\n return Promise.reject(bridgeFailure(error));\n }\n let eagerAudio = null;\n if (audio) {\n try {\n eagerAudio = new AudioContext();\n void eagerAudio.resume().catch(() => void 0);\n } catch {\n eagerAudio = null;\n }\n }\n const opened = video ? (() => {\n const input3 = { video, ...audio ? { audio } : { audio: false } };\n return invokeBridge2("device", "camera.stream", input3, deviceOperationDefinitions["camera.stream"].sdkTimeoutMs);\n })() : (() => {\n const input3 = { audio };\n return invokeBridge2("device", "microphone.stream", input3, deviceOperationDefinitions["microphone.stream"].sdkTimeoutMs);\n })();\n let pendingPort = null;\n let rebuiltAudio = null;\n return opened.then(async ({ result: raw, port }) => {\n pendingPort = port;\n if (!isLiveResult(raw)) throw new NochaError("invalid_result", "Nocha returned invalid live media settings");\n const result2 = raw;\n const tracks = [];\n const active2 = /* @__PURE__ */ new Set();\n const closeTracks = /* @__PURE__ */ new Map();\n const sources2 = /* @__PURE__ */ new Set();\n let hostEnded = false;\n let audioState = null;\n let requestFrame;\n let canvas = null;\n let gestureResume = null;\n let scheduledUntil = 0;\n const stopped = (track) => {\n active2.delete(track);\n if (hostEnded) return;\n try {\n port.postMessage({ type: "stop", kind: track.kind });\n } catch {\n }\n if (!active2.size) {\n port.close();\n if (audioState) void audioState.context.close().catch(() => void 0);\n if (gestureResume) {\n window.removeEventListener("pointerdown", gestureResume);\n window.removeEventListener("keydown", gestureResume);\n }\n }\n };\n if (result2.video) {\n canvas = document.createElement("canvas");\n canvas.width = result2.video.width;\n canvas.height = result2.video.height;\n let captured = null;\n try {\n captured = canvas.captureStream(0);\n } catch {\n }\n let track = captured?.getVideoTracks()[0];\n const framed = track;\n if (track && typeof framed?.requestFrame === "function") {\n requestFrame = () => framed.requestFrame();\n } else {\n for (const provisional of captured?.getTracks() ?? []) provisional.stop();\n captured = canvas.captureStream(result2.video.frameRate);\n track = captured.getVideoTracks()[0];\n }\n if (!track) throw new NochaError("invalid_result", "The browser cannot reconstruct a video track");\n tracks.push(track);\n active2.add(track);\n closeTracks.set(track, patchTrack(track, {\n width: result2.video.width,\n height: result2.video.height,\n frameRate: result2.video.frameRate,\n facingMode: result2.video.facingMode,\n deviceId: "nocha-camera"\n }, () => stopped(track)));\n }\n if (result2.audio) {\n let audioContext = eagerAudio;\n if (!audioContext || audioContext.sampleRate !== result2.audio.sampleRate) {\n if (audioContext) void audioContext.close().catch(() => void 0);\n audioContext = new AudioContext({ sampleRate: result2.audio.sampleRate });\n void audioContext.resume().catch(() => void 0);\n }\n rebuiltAudio = audioContext;\n const destination = audioContext.createMediaStreamDestination();\n const track = destination.stream.getAudioTracks()[0];\n if (!track) throw new NochaError("invalid_result", "The browser cannot reconstruct an audio track");\n audioState = { context: audioContext, destination };\n tracks.push(track);\n active2.add(track);\n closeTracks.set(track, patchTrack(track, {\n sampleRate: result2.audio.sampleRate,\n channelCount: 1,\n deviceId: "nocha-microphone"\n }, () => stopped(track)));\n gestureResume = () => {\n if (audioContext.state === "suspended") void audioContext.resume().catch(() => void 0);\n else {\n window.removeEventListener("pointerdown", gestureResume);\n window.removeEventListener("keydown", gestureResume);\n }\n };\n if (audioContext.state === "suspended") {\n window.addEventListener("pointerdown", gestureResume);\n window.addEventListener("keydown", gestureResume);\n }\n } else if (eagerAudio) void eagerAudio.close().catch(() => void 0);\n port.addEventListener("message", (event) => {\n const message = event.data;\n if (!isRecord(message) || !isString(message.type)) return;\n if (message.type === "frame") {\n const bitmap = message.bitmap;\n try {\n if (!canvas || !(bitmap instanceof ImageBitmap)) return;\n const drawing = canvas.getContext("2d", { alpha: false });\n if (!drawing) return;\n drawing.drawImage(bitmap, 0, 0, canvas.width, canvas.height);\n requestFrame?.();\n } finally {\n if (bitmap instanceof ImageBitmap) bitmap.close();\n try {\n port.postMessage({ type: "ack" });\n } catch {\n }\n }\n return;\n }\n if (message.type === "audio" && audioState && message.samples instanceof Float32Array && isFiniteNumber(message.sampleRate) && message.sampleRate === audioState.context.sampleRate) {\n if (audioState.context.state !== "running" || scheduledUntil - audioState.context.currentTime > 0.25) return;\n const buffer = audioState.context.createBuffer(1, message.samples.length, message.sampleRate);\n buffer.copyToChannel(new Float32Array(message.samples), 0);\n const source2 = audioState.context.createBufferSource();\n source2.buffer = buffer;\n source2.connect(audioState.destination);\n const earliest = audioState.context.currentTime + 0.06;\n if (scheduledUntil < audioState.context.currentTime) scheduledUntil = earliest;\n const at = Math.max(earliest, scheduledUntil);\n scheduledUntil = at + buffer.duration;\n sources2.add(source2);\n source2.addEventListener("ended", () => {\n sources2.delete(source2);\n source2.disconnect();\n }, { once: true });\n source2.start(at);\n return;\n }\n if (message.type === "ended") {\n hostEnded = true;\n for (const source2 of sources2) {\n try {\n source2.stop();\n } catch {\n }\n }\n sources2.clear();\n for (const close of closeTracks.values()) close(true);\n port.close();\n if (audioState) void audioState.context.close().catch(() => void 0);\n if (gestureResume) {\n window.removeEventListener("pointerdown", gestureResume);\n window.removeEventListener("keydown", gestureResume);\n }\n }\n });\n port.start();\n port.postMessage({ type: "start" });\n const stream = new MediaStream(tracks);\n pendingPort = null;\n return stream;\n }).catch((error) => {\n if (pendingPort) {\n try {\n pendingPort.postMessage({ type: "stop" });\n } catch {\n }\n pendingPort.close();\n pendingPort = null;\n }\n if (eagerAudio) void eagerAudio.close().catch(() => void 0);\n if (rebuiltAudio && rebuiltAudio !== eagerAudio) void rebuiltAudio.close().catch(() => void 0);\n throw bridgeFailure(error);\n });\n };\n const install = () => {\n if (typeof navigator === "undefined" || !navigator.mediaDevices || installedMediaDevices.has(navigator.mediaDevices)) return;\n const mediaDevices = navigator.mediaDevices;\n Object.defineProperty(mediaDevices, "getUserMedia", { configurable: true, value: getUserMedia });\n Object.defineProperty(mediaDevices, "enumerateDevices", {\n configurable: true,\n value: async () => [\n genericDevice("videoinput", "nocha-camera", "Nocha camera"),\n genericDevice("audioinput", "nocha-microphone", "Nocha microphone")\n ]\n });\n installedMediaDevices.add(mediaDevices);\n };\n return Object.freeze({ getUserMedia, install });\n}\n\n// src/device.ts\nvar features = ["camera", "photos", "audio", "motion", "haptics", "location", "share", "notifications", "alarms"];\nvar isAvailability = (value) => isRecord(value) && ["ios", "android", "web"].includes(String(value.platform)) && isRecord(value.capabilities) && features.every((feature) => {\n const entry = isRecord(value.capabilities) ? value.capabilities[feature] : void 0;\n return isRecord(entry) && isBoolean(entry.available) && (entry.reason === void 0 || isString(entry.reason)) && (entry.styles === void 0 || isArrayOf(entry.styles, isString)) && (entry.pattern === void 0 || isBoolean(entry.pattern));\n});\nvar isMedia = (value) => isRecord(value) && (value.cancelled === true || value.cancelled === false && isRecord(value.file) && isString(value.file.dataUrl) && value.file.dataUrl.startsWith("data:") && isString(value.file.mimeType) && isString(value.file.name));\nvar isScheduled = (kind, id) => (value) => isRecord(value) && isString(value.id) && (id === void 0 || value.id === id) && isString(value.title) && isString(value.at) && Number.isFinite(Date.parse(value.at)) && (value.body === void 0 || isString(value.body)) && value.kind === kind;\nvar isLocation = (value) => isRecord(value) && isFiniteNumber(value.latitude) && Math.abs(value.latitude) <= 90 && isFiniteNumber(value.longitude) && Math.abs(value.longitude) <= 180 && isNullable(value.accuracy, isFiniteNumber);\nvar completed = (value) => isRecord(value) && value.completed === true;\nfunction isMotion(value) {\n return isRecord(value) && isString(value.id) && (value.sensor === "accelerometer" || value.sensor === "gyroscope") && ["x", "y", "z", "timestamp"].every((key) => isFiniteNumber(value[key]));\n}\nvar field = (input3, key) => isRecord(input3) ? input3[key] : void 0;\nfunction createDevice(context, subscriptions) {\n const call2 = async (operation2, input3, check, options) => {\n const value = await context.invoke(deviceOperationDefinitions[operation2].capability, deviceOperationDefinitions[operation2].operation, input3, options);\n if (!check(value)) throw new NochaError("invalid_result", `Nocha returned an invalid device ${operation2} result`);\n return value;\n };\n const scheduling = (kind) => {\n const item = kind === "notifications" ? "notification" : "alarm";\n return {\n schedule: (input3, options) => call2(`${kind}.schedule`, input3, isScheduled(item, field(input3, "id")), options),\n list: (options) => call2(`${kind}.list`, {}, (value) => isRecord(value) && isArrayOf(value.items, isScheduled(item)), options),\n cancel: (input3, options) => call2(`${kind}.cancel`, input3, (value) => isRecord(value) && isBoolean(value.cancelled), options)\n };\n };\n return Object.freeze({\n availability: (options) => call2("availability", {}, isAvailability, options),\n camera: { capture: (options) => call2("camera.capture", {}, isMedia, options) },\n photos: { pick: (options) => call2("photos.pick", {}, isMedia, options) },\n media: createLiveMedia(context),\n motion: { async subscribe(input3, listener, options) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A motion listener is required");\n if (!isRecord(input3) || !isString(input3.id)) throw new NochaError("invalid_request", "A motion subscription id is required");\n if (subscriptions.has(input3.id)) throw new NochaError("invalid_request", "Motion subscription id is already active");\n subscriptions.add(input3.id);\n let closed = false;\n const stop = subscribeBridgeEvents((event) => {\n if (event.type === "device.motion.stopped" && isRecord(event.payload) && event.payload.id === input3.id) {\n closed = true;\n stop();\n subscriptions.delete(input3.id);\n return;\n }\n if (event.type === "device.motion" && isMotion(event.payload) && event.payload.id === input3.id && event.payload.sensor === input3.sensor) notifyListener(listener, event.payload);\n });\n try {\n await call2("motion.subscribe", input3, (value) => isRecord(value) && value.id === input3.id, options);\n } catch (error) {\n stop();\n subscriptions.delete(input3.id);\n void call2("motion.unsubscribe", { id: input3.id }, () => true, options).catch(() => {\n });\n throw error;\n }\n return async () => {\n if (closed) return;\n await call2("motion.unsubscribe", { id: input3.id }, (value) => isRecord(value) && isBoolean(value.removed), options);\n closed = true;\n stop();\n subscriptions.delete(input3.id);\n };\n } },\n haptics: {\n trigger: (input3 = {}, options) => call2("haptics.trigger", input3, completed, options),\n pattern: (input3, options) => call2("haptics.pattern", input3, (value) => isRecord(value) && isBoolean(value.completed), options),\n stop: (options) => call2("haptics.stop", {}, (value) => isRecord(value) && isBoolean(value.stopped), options)\n },\n location: { current: (options) => call2("location.current", {}, isLocation, options) },\n share: { open: (input3, options) => call2("share.open", input3, completed, options) },\n notifications: scheduling("notifications"),\n alarms: scheduling("alarms")\n });\n}\n\n// src/drive.ts\nvar forbiddenCharacter = (character) => character === "/" || character === "\\\\" || character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127;\nvar usagePattern3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;\nvar mimePattern = /^[a-z0-9][a-z0-9.+-]*\\/[a-z0-9][a-z0-9.+-]*$/;\nvar acceptPattern = /^[a-z0-9][a-z0-9.+-]*\\/(?:\\*|[a-z0-9][a-z0-9.+-]*)$/;\nfunction driveName(value, field3) {\n const name = typeof value === "string" ? value.trim() : "";\n if (!name || name.length > 255 || [...name].some(forbiddenCharacter) || name === "." || name === "..") throw invalid(`${field3} must be a Drive name: 1 to 255 characters, without / or \\\\`);\n return name;\n}\nfunction dialogHints(folder, title) {\n if (folder !== void 0 && (!Array.isArray(folder) || folder.length > DRIVE_FOLDER_MAX_DEPTH)) throw invalid(`folder must list at most ${DRIVE_FOLDER_MAX_DEPTH} folder names`);\n if (title !== void 0 && (typeof title !== "string" || !title.trim() || title.trim().length > 120)) throw invalid("title must have 1 to 120 characters");\n const names = Array.isArray(folder) ? folder.map((item) => driveName(item, "Each folder")) : void 0;\n return { ...names?.length ? { folder: names } : {}, ...typeof title === "string" ? { title: title.trim() } : {} };\n}\nfunction timeoutOf(value, fallback) {\n const timeout = value ?? fallback;\n if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid("timeoutMs must be a positive finite timer duration");\n return timeout;\n}\nfunction checkOptions(options) {\n if (!isRecord(options)) throw invalid("Request options must be an object");\n if (options.onProgress !== void 0 && typeof options.onProgress !== "function") throw invalid("onProgress must be a function");\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalid("signal must be an AbortSignal");\n}\nvar isSaveResult = (value) => isRecord(value) && (value.saved === false || value.saved === true && isRecord(value.file) && isNonEmptyString(value.file.id) && isNonEmptyString(value.file.name) && isArrayOf(value.file.path, isString) && isString(value.file.mimeType) && isCount(value.file.sizeBytes));\nfunction requireUsage(context, operation2) {\n assertHostCapability("drive");\n if (context.usageId === void 0) throw new NochaError("usage_required", `drive.${operation2} requires nocha.use(<declared usage id>)`);\n return context.usageId;\n}\nfunction saveFile(context, input3, options) {\n const { file } = input3;\n if (!file.size) throw invalid("A non-empty file is required");\n if (file.size > DRIVE_TRANSFER_MAX_BYTES) throw new NochaError("source_too_large", "A Drive file sent by an experience is at most 64 MiB");\n const fallbackName = "name" in file && typeof file.name === "string" && file.name.trim() ? file.name : "file";\n const name = driveName(input3.name ?? fallbackName, "name");\n const declared = (typeof input3.mimeType === "string" ? input3.mimeType : file.type).trim().toLowerCase().split(";", 1)[0] ?? "";\n if (input3.mimeType !== void 0 && !mimePattern.test(declared)) throw invalid("mimeType must be a MIME type such as audio/mpeg");\n const hints = dialogHints(options.folder, options.title);\n const usageId = requireUsage(context, "save");\n if (options.idempotencyKey !== void 0 && !isIdempotencyKey(options.idempotencyKey)) throw invalid("idempotencyKey must contain 8 to 200 characters");\n const timeout = timeoutOf(options.timeoutMs, operationWaiting.drive.save);\n if (options.signal?.aborted) throw new NochaError("aborted", "Drive save aborted");\n const wire = { name, mime_type: mimePattern.test(declared) ? declared : "application/octet-stream", size_bytes: file.size, ...hints };\n const host = window.parent;\n const requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const abort = () => {\n host.postMessage({ protocol: "nocha.upload.v1", type: "abort", requestId }, "*");\n cleanup();\n reject2(new NochaError("aborted", "Drive save aborted"));\n };\n const expire = () => {\n cleanup();\n reject2(new NochaError("invocation_timed_out", "Local Drive wait timed out; the file may still be saved"));\n };\n const receive = (event) => {\n const message = event.data;\n if (!isFromHost(event) || !isRecord(message) || message.protocol !== "nocha.upload.v1" || message.requestId !== requestId) return;\n if (message.type === "progress") {\n if (options.onProgress && isCount(message.loaded)) notifyListener(options.onProgress, { loaded: message.loaded, total: file.size });\n return;\n }\n cleanup();\n if (message.type === "result" && isSaveResult(message.result)) resolve(message.result);\n else if (message.type === "result") reject2(new NochaError("invalid_result", "Nocha returned an invalid Drive save result"));\n else reject2(wireError(message.error, { code: "upload_failed", message: "Drive save failed" }));\n };\n const timer = setTimeout(expire, timeout);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n host.postMessage({\n protocol: "nocha.upload.v1",\n type: "upload",\n requestId,\n capability: driveOperationDefinitions.save.capability,\n operation: driveOperationDefinitions.save.operation,\n usageId,\n idempotencyKey: options.idempotencyKey ?? `${requestId}:drive`,\n input: wire,\n file\n }, "*");\n } catch (error) {\n cleanup();\n reject2(error);\n }\n });\n}\nasync function saveVideo(context, input3, options) {\n const video = input3.video;\n if (!isRecord(video) || typeof video.usage !== "string" || !usagePattern3.test(video.usage) || !isNonEmptyString(video.id) || video.id.length > 200) {\n throw invalid("video must name the declared video usage and the generation id: { usage, id }");\n }\n const name = input3.name === void 0 ? void 0 : driveName(input3.name, "name");\n const hints = dialogHints(options.folder, options.title);\n requireUsage(context, "save");\n const value = await context.invoke(driveOperationDefinitions.save.capability, driveOperationDefinitions.save.operation, {\n video: { usage: video.usage, id: video.id },\n ...name ? { name } : {},\n ...hints\n }, {\n ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},\n timeoutMs: timeoutOf(options.timeoutMs, operationWaiting.drive.save),\n ...options.signal !== void 0 ? { signal: options.signal } : {}\n });\n if (!isSaveResult(value)) throw new NochaError("invalid_result", "Nocha returned an invalid Drive save result");\n return value;\n}\nasync function save(context, input3, options = {}) {\n checkOptions(options);\n if (!isRecord(input3)) throw invalid("Expected { file } or { video }");\n if ("file" in input3 && input3.file !== void 0) {\n if (!(input3.file instanceof Blob)) throw invalid("file must be a Blob or a File");\n return saveFile(context, input3, options);\n }\n if ("video" in input3 && input3.video !== void 0) return saveVideo(context, input3, options);\n throw invalid("Expected { file } or { video }");\n}\nfunction isPickTransfer(value, maxBytes2) {\n if (!isRecord(value)) return false;\n if (value.picked === false) return true;\n return value.picked === true && isRecord(value.drive) && isNonEmptyString(value.drive.id) && isArrayOf(value.drive.path, isString) && isCount(value.drive.sizeBytes) && isNonEmptyString(value.name) && isString(value.mime_type) && value.blob instanceof Blob && value.blob.size === value.drive.sizeBytes && value.blob.size <= maxBytes2;\n}\nasync function pick(context, input3 = {}, options = {}) {\n checkOptions(options);\n if (!isRecord(input3)) throw invalid("Expected { accept?, maxBytes?, title?, folder? }");\n const accept = input3.accept;\n if (accept !== void 0 && (!Array.isArray(accept) || !accept.length || accept.length > 16 || accept.some((pattern) => typeof pattern !== "string" || !acceptPattern.test(pattern.trim().toLowerCase())))) {\n throw invalid("accept must list 1 to 16 MIME patterns such as audio/* or audio/mpeg");\n }\n const maxBytes2 = input3.maxBytes ?? DRIVE_TRANSFER_MAX_BYTES;\n if (!isCount(maxBytes2) || maxBytes2 < 1 || maxBytes2 > DRIVE_TRANSFER_MAX_BYTES) throw invalid("maxBytes must be an integer from 1 to 64 MiB");\n const hints = dialogHints(input3.folder, input3.title);\n const usageId = requireUsage(context, "pick");\n const timeout = timeoutOf(options.timeoutMs, operationWaiting.drive.pick);\n if (options.signal?.aborted) throw new NochaError("aborted", "Drive pick aborted");\n const wire = { ...accept ? { accept: accept.map((pattern) => pattern.trim().toLowerCase()) } : {}, ...input3.maxBytes !== void 0 ? { max_bytes: maxBytes2 } : {}, ...hints };\n const firstReply = operationWaiting.drive["pick.firstReply"];\n const host = window.parent;\n const requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(unanswered);\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const stop = (error) => {\n cleanup();\n try {\n host.postMessage({ protocol: "nocha.media.v1", type: "abort", requestId }, "*");\n } catch {\n }\n reject2(error);\n };\n const abort = () => stop(new NochaError("aborted", "Drive pick aborted"));\n const receive = (event) => {\n const message = event.data;\n if (!isFromHost(event) || !isRecord(message) || message.protocol !== "nocha.media.v1" || message.requestId !== requestId) return;\n clearTimeout(unanswered);\n if (message.type === "progress") {\n if (options.onProgress && isCount(message.loaded) && (message.total === null || isCount(message.total))) {\n notifyListener(options.onProgress, { loaded: message.loaded, total: message.total });\n }\n return;\n }\n if (message.type !== "result" && message.type !== "error") return;\n cleanup();\n if (message.type === "error") {\n reject2(wireError(message.error, { code: "media_unavailable", message: "The Drive file is unavailable" }));\n return;\n }\n const result2 = message.result;\n if (!isPickTransfer(result2, maxBytes2)) {\n reject2(new NochaError("invalid_result", "Nocha returned an invalid Drive file"));\n return;\n }\n if (result2.picked === false) {\n resolve({ picked: false });\n return;\n }\n resolve({ picked: true, file: new File([result2.blob], result2.name, { type: result2.mime_type || result2.blob.type }), drive: { id: result2.drive.id, path: [...result2.drive.path], sizeBytes: result2.drive.sizeBytes } });\n };\n const unanswered = timeout > firstReply ? setTimeout(() => stop(new NochaError("client_update_required", "Update Nocha to choose a file from the Drive")), firstReply) : void 0;\n const timer = setTimeout(() => stop(new NochaError("invocation_timed_out", "Local Drive wait timed out")), timeout);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n host.postMessage({\n protocol: "nocha.media.v1",\n type: "read",\n requestId,\n capability: driveOperationDefinitions.pick.capability,\n operation: driveOperationDefinitions.pick.operation,\n usageId,\n input: wire\n }, "*");\n } catch (error) {\n cleanup();\n reject2(new NochaError("invalid_request", `The request cannot be sent to the Nocha host: ${error instanceof Error ? error.message : String(error)}`));\n }\n });\n}\nfunction createDrive(context) {\n return Object.freeze({\n save: (input3, options) => save(context, input3, options),\n pick: (input3, options) => pick(context, input3, options)\n });\n}\n\n// src/experience-context.ts\nvar current = null;\nvar pending = null;\nfunction snapshot2(value) {\n if (!isExperienceContext(value)) return null;\n const { type, platform, sessionId } = value.device;\n return Object.freeze({ device: Object.freeze({ type, platform, sessionId }) });\n}\nasync function get2() {\n assertHostCapability("context");\n if (current) return current;\n if (pending) return pending;\n const requestId = crypto.randomUUID();\n pending = new Promise((resolve, reject2) => {\n const finish = () => {\n clearTimeout(timer);\n unsubscribe();\n };\n const unsubscribe = subscribeBridgeEvents((event) => {\n if (event.type !== "context.snapshot" || !event.payload || typeof event.payload !== "object") return;\n const payload = event.payload;\n if (payload.requestId !== requestId) return;\n const value = snapshot2(payload.context);\n finish();\n if (!value) {\n reject2(new NochaError("invalid_result", "Nocha returned an invalid experience context"));\n return;\n }\n current = value;\n markExperienceContextAvailable();\n resolve(value);\n });\n const timer = setTimeout(() => {\n finish();\n reject2(new NochaError("bridge_unavailable", "This reader does not provide experience context"));\n }, 1500);\n try {\n window.parent.postMessage({\n protocol: NOCHA_BRIDGE_PROTOCOL,\n type: "event",\n event: { type: "context.request", payload: { requestId } }\n }, "*");\n } catch {\n finish();\n reject2(new NochaError("bridge_unavailable", "Experience context is unavailable"));\n }\n });\n try {\n return await pending;\n } finally {\n pending = null;\n }\n}\nvar experienceContext = Object.freeze({\n get: get2,\n onChange(listener) {\n assertHostCapability("context");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A context listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== "context.changed") return;\n const value = snapshot2(event.payload);\n if (value) {\n current = value;\n markExperienceContextAvailable();\n notifyListener(listener, value);\n } else warnOnce("context.changed", "the host sent an experience context this SDK does not understand");\n });\n }\n});\nif (getNochaMode() === "embedded") void get2().catch(() => void 0);\n\n// src/connectors.ts\nfunction createConnectors(context) {\n return Object.freeze({\n async status(options) {\n const value = await context.invoke("connectors", "status", {}, options);\n if (!isRecord(value) || typeof value.granted !== "boolean" || typeof value.ready !== "boolean" || !Array.isArray(value.operations) || !value.operations.every((item) => typeof item === "string") || !(value.account === null || isRecord(value.account) && typeof value.account.label === "string" && ["google", "github", "notion"].includes(String(value.account.provider)))) {\n throw new NochaError("invalid_result", "Nocha returned an invalid connector status");\n }\n return value;\n },\n async request(options) {\n const value = await context.invoke("connectors", "request", {}, options);\n if (!isRecord(value) || typeof value.granted !== "boolean") throw new NochaError("invalid_result", "Nocha returned an invalid connector authorization");\n return { granted: value.granted };\n },\n async invoke(operation2, input3, options) {\n if (typeof operation2 !== "string" || !operation2) throw new NochaError("invalid_request", "Expected a declared connector operation");\n return await context.invoke("connectors", "invoke", { operation: operation2, input: input3 }, options);\n },\n async revoke(options) {\n await context.invoke("connectors", "revoke", {}, options);\n }\n });\n}\n\n// src/email.ts\nvar isResult = (value) => isRecord(value) && isUuid(value.id) && (value.status === "queued" || value.status === "sent" || value.status === "duplicate");\nfunction createEmail(context) {\n return Object.freeze({\n async send(input3, options) {\n const operation2 = emailOperationDefinitions.send;\n const value = await context.invoke(operation2.capability, operation2.operation, input3, options);\n if (!isResult(value)) throw new NochaError("invalid_result", "Nocha returned an invalid email result");\n return value;\n }\n });\n}\n\n// src/retry.ts\nvar retryBaseMs = 500;\nvar retryMaxMs = 8e3;\nfunction retryDelayMs(error, attempt) {\n if (classifyError(error) !== "transient") return void 0;\n const ceiling2 = Math.min(retryMaxMs, retryBaseMs * 2 ** Math.min(Math.max(0, attempt), 4));\n return ceiling2 * (0.5 + Math.random() / 2);\n}\n\n// src/multiplayer-subscriptions.ts\nvar operation = multiplayerOperationDefinitions.subscribe;\nvar pendingEventLimit = 256;\nvar pendingEventByteLimit = 1048576;\nvar encoder = new TextEncoder();\nfunction subscriptionResult(value, topic, subscribed) {\n if (!isRecord(value) || value.topic !== topic || value.subscribed !== subscribed) {\n throw new NochaError("invalid_result", "Nocha returned an invalid multiplayer subscription result");\n }\n}\nvar definitiveRefusal = (error) => ["denied", "invalid", "billing"].includes(classifyError(error));\nfunction createMultiplayerSubscriptions(listeners, reconcile) {\n const topics = /* @__PURE__ */ new Map();\n const cleanupFailures = /* @__PURE__ */ new Map();\n const callers = /* @__PURE__ */ new Set();\n const scope = new AbortController();\n let closed;\n const retire = (topic) => {\n if (closed || topic.callers.size || topics.get(topic.name) !== topic) return Promise.resolve();\n if (topic.closing) return topic.closing;\n topic.controller.abort();\n topic.closing = (async () => {\n await Promise.all([...topic.authorizations.values()].map((pending2) => pending2.catch(() => {\n })));\n if (closed || !topic.mayExist) return;\n topic.lateResult = false;\n const value = await invokeBridge(operation.capability, operation.operation, { topic: topic.name, action: "unsubscribe" }, {\n usageId: topic.usageId,\n timeoutMs: operation.sdkTimeoutMs,\n signal: scope.signal\n });\n subscriptionResult(value, topic.name, false);\n })().catch((error) => {\n cleanupFailures.set(topic.name, error);\n throw error;\n }).finally(() => {\n if (topics.get(topic.name) !== topic) return;\n topics.delete(topic.name);\n topic.closing = void 0;\n if (!closed && topic.lateResult) {\n topic.lateResult = false;\n topics.set(topic.name, topic);\n void retire(topic).catch(() => {\n });\n }\n reconcile();\n });\n return topic.closing;\n };\n const reconcileAbandoned = (abandoned, usageId, confirmed = false) => {\n if (closed) return;\n if (cleanupFailures.has(abandoned.name) && definitiveRefusal(cleanupFailures.get(abandoned.name))) return;\n const current2 = topics.get(abandoned.name);\n if (current2?.callers.size) return;\n const topic = current2 ?? abandoned;\n if (!current2) topics.set(topic.name, topic);\n topic.mayExist = true;\n if (confirmed || !topic.authorized) topic.usageId = usageId;\n if (confirmed) topic.authorized = true;\n topic.lateResult = true;\n void retire(topic).catch(() => {\n });\n };\n const authorize = (topic, options) => {\n const key = options.usageId ?? "";\n let pending2 = topic.authorizations.get(key);\n if (pending2) return pending2;\n pending2 = invokeBridgeWithLateResult(operation.capability, operation.operation, { topic: topic.name }, {\n ...options,\n timeoutMs: operation.sdkTimeoutMs,\n signal: topic.controller.signal\n }, {\n signal: scope.signal,\n onResult: () => reconcileAbandoned(topic, options.usageId, true),\n onError: (error) => {\n if (!definitiveRefusal(error)) reconcileAbandoned(topic, options.usageId);\n },\n // Even a completely lost reply cannot hide setup that finished after the first\n // deletion. Reconcile once at the host operation\'s normal waiting ceiling.\n onExpired: () => reconcileAbandoned(topic, options.usageId)\n }).then((value) => {\n topic.mayExist = true;\n subscriptionResult(value, topic.name, true);\n topic.authorized = true;\n topic.usageId = options.usageId;\n }).catch((error) => {\n if (!definitiveRefusal(error)) {\n topic.mayExist = true;\n if (!topic.authorized) topic.usageId = options.usageId;\n }\n if (topic.authorizations.get(key) === pending2) topic.authorizations.delete(key);\n throw error;\n });\n topic.authorizations.set(key, pending2);\n return pending2;\n };\n const subscribe = async (name, listener, options = {}) => {\n if (closed) throw closed;\n const { signal, timeoutMs, idempotencyKey } = options;\n if (signal !== void 0 && !(signal instanceof AbortSignal)) throw new NochaError("invalid_request", "signal must be an AbortSignal");\n if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647)) {\n throw new NochaError("invalid_request", "timeoutMs must be a positive finite timer duration");\n }\n if (idempotencyKey !== void 0 && !isIdempotencyKey(idempotencyKey)) throw new NochaError("invalid_request", "The idempotency key must have 8 to 200 characters without control characters");\n const aborted = () => new NochaError("aborted", "Local multiplayer subscription was aborted");\n if (signal?.aborted) throw aborted();\n let active2 = true;\n let ready = false;\n let stopped;\n const buffered = [];\n let bufferedBytes = 0;\n let topic;\n let closing;\n let timer;\n let rejectWait;\n const cancelled = new Promise((_resolve, reject2) => {\n rejectWait = reject2;\n });\n const clearBuffer = () => {\n buffered.length = 0;\n bufferedBytes = 0;\n };\n const guarded = (event) => {\n if (!active2 || signal?.aborted) return;\n if (ready) {\n listener(event);\n return;\n }\n try {\n const serialized = JSON.stringify(event);\n if (serialized === void 0) throw new Error("The event is not serializable");\n const remaining = pendingEventByteLimit - bufferedBytes;\n const bytes = serialized.length > remaining ? serialized.length : encoder.encode(serialized).byteLength;\n if (buffered.length >= pendingEventLimit || bytes > remaining) {\n void cancel(new NochaError("multiplayer_unavailable", "Too many multiplayer events arrived before subscription authorization; reload the authoritative snapshot", {\n details: { topic: name, reason: "subscription_buffer_overflow", maximumEvents: pendingEventLimit, maximumBytes: pendingEventByteLimit }\n })).catch(() => {\n });\n return;\n }\n buffered.push(structuredClone(event));\n bufferedBytes += bytes;\n } catch {\n void cancel(new NochaError("invalid_result", "A multiplayer event could not be buffered before authorization")).catch(() => {\n });\n }\n };\n const stopWaiting = () => {\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n };\n const cancel = (error) => {\n if (!active2) return closing ?? Promise.resolve();\n active2 = false;\n stopped = error;\n clearBuffer();\n stopWaiting();\n signal?.removeEventListener("abort", onAbort);\n callers.delete(cancel);\n if (topic) {\n topic.callers.delete(cancel);\n const callbacks = listeners.get(name);\n callbacks?.delete(guarded);\n if (!callbacks?.size) listeners.delete(name);\n }\n rejectWait(error);\n closing = topic ? retire(topic) : Promise.resolve();\n reconcile();\n return closing;\n };\n const onAbort = () => {\n void cancel(aborted()).catch(() => {\n });\n };\n callers.add(cancel);\n signal?.addEventListener("abort", onAbort, { once: true });\n timer = setTimeout(() => {\n void cancel(new NochaError("invocation_timed_out", "Local multiplayer subscription timed out")).catch(() => {\n });\n }, timeoutMs ?? operation.sdkTimeoutMs);\n const setup = async () => {\n while (active2 && !closed) {\n if (cleanupFailures.has(name)) throw cleanupFailures.get(name);\n const current2 = topics.get(name);\n if (current2?.closing) {\n await current2.closing;\n continue;\n }\n topic = current2 ?? {\n name,\n usageId: options.usageId,\n callers: /* @__PURE__ */ new Set(),\n authorizations: /* @__PURE__ */ new Map(),\n controller: new AbortController(),\n authorized: false,\n mayExist: false,\n lateResult: false\n };\n topics.set(name, topic);\n topic.callers.add(cancel);\n let callbacks = listeners.get(name);\n if (!callbacks) {\n callbacks = /* @__PURE__ */ new Set();\n listeners.set(name, callbacks);\n }\n callbacks.add(guarded);\n await authorize(topic, options);\n if (!active2 || closed) throw closed ?? stopped ?? aborted();\n stopWaiting();\n for (let index = 0; active2 && index < buffered.length; index++) notifyListener(listener, buffered[index]);\n clearBuffer();\n if (!active2 || closed) throw closed ?? stopped ?? aborted();\n ready = true;\n return () => cancel(new NochaError("request_cancelled", "Multiplayer listener was disposed"));\n }\n throw closed ?? aborted();\n };\n try {\n return await Promise.race([setup(), cancelled]);\n } catch (error) {\n void cancel(isNochaError(error) ? error : new NochaError("invocation_failed", String(error))).catch(() => {\n });\n throw error;\n }\n };\n return {\n subscribe,\n /** The host owns socket teardown on revocation, scope replacement or document exit.\n * Cancel our callbacks, waits and late observers without invoking a successor scope. */\n close(error = new NochaError("request_cancelled", "The multiplayer host scope closed")) {\n if (closed) return;\n closed = error;\n scope.abort();\n for (const cancel of callers) void cancel(error).catch(() => {\n });\n for (const topic of topics.values()) topic.controller.abort();\n topics.clear();\n cleanupFailures.clear();\n listeners.clear();\n reconcile();\n }\n };\n}\n\n// src/multiplayer.ts\nfunction record3(value) {\n return value !== null && typeof value === "object" && !Array.isArray(value);\n}\nfunction identity(value) {\n return record3(value) && typeof value.user === "string" && typeof value.display_name === "string" && (value.role === "participant" || value.role === "observer");\n}\nfunction isPresenceSnapshot(value) {\n return record3(value) && identity(value.self) && Array.isArray(value.members) && value.members.every(identity) && typeof value.count === "number" && Number.isInteger(value.count) && value.count >= 0;\n}\nfunction isPresenceEvent(value) {\n return record3(value) && isPresenceSnapshot(value.snapshot) && (value.type === "reconcile" || (value.type === "join" || value.type === "leave") && identity(value.member));\n}\nfunction isLiveSender(value) {\n return identity(value) || record3(value) && value.user === "system" && value.role === "system" && value.display_name === "Nocha";\n}\nfunction parseLiveEvent(value) {\n if (!record3(value) || typeof value.topic !== "string" || typeof value.eventId !== "string" || !value.eventId || typeof value.publishedAt !== "string" || !value.publishedAt || value.delivery !== "ephemeral" && value.delivery !== "durable" || value.recovered !== void 0 && typeof value.recovered !== "boolean" || !isLiveSender(value.sender)) return null;\n return { topic: value.topic, data: value.data, sender: value.sender, delivery: value.delivery, eventId: value.eventId, publishedAt: value.publishedAt, recovered: value.recovered === true };\n}\nfunction isLiveConnection(value) {\n return record3(value) && ["connecting", "connected", "recovering", "unavailable", "closed"].includes(String(value.status)) && (value.reason === void 0 || typeof value.reason === "string") && (value.attempt === void 0 || typeof value.attempt === "number" && Number.isInteger(value.attempt) && value.attempt >= 0);\n}\nfunction isLiveRecoveryRequired(value) {\n return record3(value) && typeof value.topic === "string" && value.reason === "history_lost";\n}\n\n// src/multiplayer-facade.ts\nfunction createLiveHub() {\n const connections = /* @__PURE__ */ new Set();\n const recoveries = /* @__PURE__ */ new Set();\n const events = /* @__PURE__ */ new Set();\n const presence = /* @__PURE__ */ new Set();\n const topics = /* @__PURE__ */ new Map();\n let lastConnection;\n let lastPresence;\n let presenceRevision = 0;\n let stop;\n const reconcile = () => {\n if (!events.size && !presence.size && !topics.size && !connections.size && !recoveries.size) {\n stop?.();\n stop = void 0;\n }\n };\n const subscriptions = createMultiplayerSubscriptions(topics, reconcile);\n let tracking = false;\n let workspaceKey;\n const track = () => {\n if (tracking) return;\n tracking = true;\n subscribeBridgeEvents((event) => {\n if (event.type === "workspace.changed" && isRecord(event.payload)) {\n const { id, environment, revisionId, participantId, permissions } = event.payload;\n if (isNonEmptyString(id) && isNonEmptyString(revisionId) && (environment === "play" || environment === "development") && (participantId === null || typeof participantId === "string")) {\n const next = JSON.stringify([id, environment, revisionId, participantId]);\n if (workspaceKey !== void 0 && workspaceKey !== next || isRecord(permissions) && permissions.read === false) subscriptions.close();\n workspaceKey = next;\n }\n return;\n }\n if (event.type !== "multiplayer.connection" || !isLiveConnection(event.payload)) return;\n if (event.payload.status === "closed") subscriptions.close();\n if (lastConnection?.status === event.payload.status && lastConnection.reason === event.payload.reason && lastConnection.attempt === event.payload.attempt) return;\n lastConnection = event.payload;\n for (const listener of connections) notifyListener(listener, event.payload);\n });\n window.addEventListener("pagehide", (event) => {\n if (!event.persisted) subscriptions.close();\n });\n };\n const listen = () => {\n track();\n stop ??= subscribeBridgeEvents((event) => {\n if (event.type === "multiplayer.recovery.required" && isLiveRecoveryRequired(event.payload)) {\n for (const listener of recoveries) notifyListener(listener, event.payload);\n }\n if (event.type === "multiplayer.presence" && isPresenceEvent(event.payload)) {\n const payload = event.payload;\n lastPresence = payload;\n presenceRevision += 1;\n for (const listener of presence) notifyListener(listener, payload);\n }\n if (event.type === "multiplayer.event") {\n const payload = parseLiveEvent(event.payload);\n if (payload) for (const listener of topics.get(payload.topic) ?? []) notifyListener(listener, payload);\n }\n for (const listener of events) notifyListener(listener, event);\n });\n };\n const onConnection = (listener) => {\n assertHostCapability("multiplayer");\n connections.add(listener);\n listen();\n const initial = lastConnection;\n if (initial) queueMicrotask(() => {\n if (connections.has(listener) && lastConnection === initial) notifyListener(listener, initial);\n });\n return () => {\n connections.delete(listener);\n reconcile();\n };\n };\n return {\n connections,\n recoveries,\n events,\n presence,\n topics,\n track,\n listen,\n reconcile,\n onConnection,\n get lastConnection() {\n return lastConnection;\n },\n get lastPresence() {\n return lastPresence;\n },\n get presenceRevision() {\n return presenceRevision;\n },\n subscribe: subscriptions.subscribe,\n onEvent(listener) {\n assertHostCapability("events");\n events.add(listener);\n listen();\n return () => {\n events.delete(listener);\n reconcile();\n };\n }\n };\n}\nvar durableKey = /^[A-Za-z0-9._:-]{8,200}$/;\nfunction presenceSnapshot(value) {\n if (!isPresenceSnapshot(value)) throw new NochaError("invalid_result", "Nocha returned an invalid presence snapshot");\n return value;\n}\nfunction createMultiplayer(context, hub) {\n return Object.freeze({\n onConnection: hub.onConnection,\n onRecoveryRequired(listener) {\n assertHostCapability("multiplayer");\n hub.recoveries.add(listener);\n hub.listen();\n return () => {\n hub.recoveries.delete(listener);\n hub.reconcile();\n };\n },\n async presence(options) {\n hub.track();\n return presenceSnapshot(await context.invoke(multiplayerOperationDefinitions["presence"].capability, multiplayerOperationDefinitions["presence"].operation, {}, options));\n },\n onPresence(listener, options) {\n assertHostCapability("multiplayer");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A presence listener is required");\n const { onError, ...request } = options ?? {};\n const fail = (error) => {\n if (typeof onError === "function") notifyListener(onError, error);\n };\n if (context.usageId === void 0) {\n fail(new NochaError("usage_required", "multiplayer.onPresence requires nocha.use(<declared usage id>)"));\n return () => {\n };\n }\n let active2 = true;\n const controller = new AbortController();\n let attempt = 0;\n let pending2 = false;\n let timer;\n const cancelRetry = () => {\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n hub.connections.delete(onConnection);\n };\n const dispose = () => {\n active2 = false;\n controller.abort();\n cancelRetry();\n hub.presence.delete(listener);\n request.signal?.removeEventListener("abort", dispose);\n hub.reconcile();\n };\n const initialize = () => {\n if (!active2 || pending2 || hub.presence.has(listener)) return;\n if (hub.lastConnection?.status === "closed") {\n dispose();\n return;\n }\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n pending2 = true;\n const startedRevision = hub.presenceRevision;\n void context.invoke(multiplayerOperationDefinitions["presence"].capability, multiplayerOperationDefinitions["presence"].operation, {}, { ...request, signal: controller.signal }).then((value) => {\n if (!active2) return;\n const snapshot3 = presenceSnapshot(value);\n const last = hub.lastPresence;\n const current2 = hub.presenceRevision !== startedRevision && last?.snapshot.self.user === snapshot3.self.user ? last.snapshot : snapshot3;\n attempt = 0;\n cancelRetry();\n hub.presence.add(listener);\n hub.listen();\n notifyListener(listener, { type: "reconcile", snapshot: current2 });\n }).catch((cause) => {\n if (!active2) return;\n const error = isNochaError(cause) ? cause : new NochaError("invocation_failed", String(cause));\n const delay = retryDelayMs(error, attempt);\n if (delay === void 0) {\n dispose();\n if (error.code !== "aborted") fail(error);\n return;\n }\n attempt += 1;\n timer = setTimeout(initialize, delay);\n }).finally(() => {\n pending2 = false;\n });\n };\n const onConnection = (event) => {\n if (event.status === "closed") dispose();\n else if (event.status === "connected") initialize();\n };\n if (request.signal?.aborted) return dispose;\n request.signal?.addEventListener("abort", dispose, { once: true });\n hub.connections.add(onConnection);\n hub.listen();\n initialize();\n return dispose;\n },\n async subscribe(topic, listener, options) {\n assertHostCapability("multiplayer");\n if (context.usageId === void 0) throw new NochaError("usage_required", "multiplayer.subscribe requires nocha.use(<declared usage id>)");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A multiplayer listener is required");\n if (typeof topic !== "string" || !topic) throw new NochaError("invalid_request", "A multiplayer topic is required");\n hub.listen();\n try {\n const unsubscribe = await hub.subscribe(topic, listener, { ...options, usageId: context.usageId });\n return async () => {\n try {\n await unsubscribe();\n } finally {\n hub.reconcile();\n }\n };\n } catch (error) {\n hub.reconcile();\n throw error;\n }\n },\n async publish(topic, data, options = {}) {\n assertHostCapability("multiplayer");\n const { delivery, ...request } = options ?? {};\n if (delivery === "durable" && !(typeof request.idempotencyKey === "string" && durableKey.test(request.idempotencyKey))) {\n throw new NochaError("invalid_request", "A durable publication requires an idempotencyKey of 8 to 200 characters among A-Z a-z 0-9 . _ : -");\n }\n hub.track();\n const receipt2 = await context.invoke(multiplayerOperationDefinitions["publish"].capability, multiplayerOperationDefinitions["publish"].operation, { topic, data, delivery: delivery === "durable" ? "durable" : "ephemeral" }, request);\n if (!isRecord(receipt2) || receipt2.accepted !== true || !isNonEmptyString(receipt2.eventId)) throw new NochaError("invalid_result", "Nocha returned an invalid publication receipt");\n return { accepted: true, eventId: receipt2.eventId };\n }\n });\n}\n\n// src/navigation.ts\nvar sameLocation = (a, b) => a?.pathname === b.pathname && a.search === b.search && a.hash === b.hash;\nfunction reportNavigationError(cause, options) {\n const error = isNochaError(cause) ? cause : new NochaError("navigation_unavailable", String(cause));\n if (typeof options?.onError === "function") notifyListener(options.onError, error);\n else warnOnce("navigation", error.message);\n}\nvar connectCeilingMs = 6e4;\nfunction createEmbeddedNavigation() {\n let current2 = { pathname: "/", search: "", hash: "" };\n let documentId;\n let revision = -1;\n let connected = false;\n let listening = false;\n let restoring = false;\n const listeners = /* @__PURE__ */ new Set();\n const waiting = /* @__PURE__ */ new Map();\n let ready;\n let resolveReady;\n const connect = () => {\n if (ready) return ready;\n if (typeof window === "undefined" || window.parent === window) return Promise.reject(new NochaError("bridge_unavailable", "Navigation requires a Nocha experience frame"));\n const id = documentId ??= crypto.randomUUID();\n revision = -1;\n if (!listening) {\n window.addEventListener("message", onMessage);\n listening = true;\n }\n if (!restoring) {\n restoring = true;\n window.addEventListener("pageshow", (event) => {\n if (event.persisted) resynchronize();\n });\n }\n const announce = () => {\n if (!connected) window.parent.postMessage({ protocol: NOCHA_NAVIGATION_PROTOCOL, type: "ready", documentId: id }, "*");\n };\n const started = Date.now();\n let deadline = started + capabilityDeadlines.navigation.connect;\n let loaded = typeof document === "undefined" || document.readyState === "complete";\n const timers = /* @__PURE__ */ new Set();\n const later = (delay, run) => {\n const timer = setTimeout(() => {\n timers.delete(timer);\n run();\n }, delay);\n timers.add(timer);\n };\n const onLoad = () => {\n loaded = true;\n deadline = Math.min(Math.max(deadline, Date.now() + 2e3), started + connectCeilingMs);\n later(50, announce);\n later(250, announce);\n };\n const pending2 = new Promise((resolve, reject2) => {\n const finish = () => {\n for (const timer of timers) clearTimeout(timer);\n timers.clear();\n window.removeEventListener("load", onLoad);\n };\n const retry2 = (delay) => later(delay, () => {\n if (connected) return;\n const now = Date.now();\n if (loaded && now >= deadline || now >= started + connectCeilingMs) {\n finish();\n if (ready === pending2) ready = void 0;\n reject2(new NochaError("navigation_unavailable", "This host does not support experience navigation"));\n return;\n }\n announce();\n retry2(Math.min(2e3, delay * 2));\n });\n resolveReady = () => {\n finish();\n connected = true;\n resolve();\n };\n if (!loaded) window.addEventListener("load", onLoad, { once: true });\n retry2(100);\n });\n ready = pending2;\n announce();\n return pending2;\n };\n const resynchronize = () => {\n if (!ready || !connected) return;\n connected = false;\n ready = void 0;\n resolveReady = void 0;\n void connect().catch((error) => {\n for (const listener of errorListeners) reportNavigationError(error, listener);\n });\n };\n const errorListeners = /* @__PURE__ */ new Set();\n const onMessage = (event) => {\n if (!isFromHost(event)) return;\n const message = event.data;\n if (!message || message.protocol !== NOCHA_NAVIGATION_PROTOCOL || message.type !== "snapshot" || message.documentId !== documentId || !Number.isSafeInteger(message.revision) || message.revision <= revision || !isExperienceLocation(message.location) || typeof message.canGoBack !== "boolean") return;\n revision = message.revision;\n const changed = !sameLocation(current2, message.location);\n current2 = Object.freeze({ ...message.location });\n resolveReady?.();\n resolveReady = void 0;\n if (changed) for (const listener of listeners) listener(current2);\n if (message.requestId) {\n const pending2 = waiting.get(message.requestId);\n if (pending2) {\n waiting.delete(message.requestId);\n clearTimeout(pending2.timer);\n pending2.resolve(current2);\n }\n }\n };\n const command = async (action, target) => {\n await connect();\n const location2 = target === void 0 ? void 0 : normalizeExperienceLocation(target, current2);\n if (action === "navigate" && location2 && sameLocation(current2, location2)) return current2;\n const requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n const timer = setTimeout(() => {\n waiting.delete(requestId);\n resynchronize();\n reject2(new NochaError("navigation_timed_out", "Navigation was not acknowledged"));\n }, capabilityDeadlines.navigation.command);\n waiting.set(requestId, { resolve, reject: reject2, timer });\n window.parent.postMessage({ protocol: NOCHA_NAVIGATION_PROTOCOL, type: "intent", documentId, requestId, action, ...location2 ? { location: location2 } : {} }, "*");\n });\n };\n return Object.freeze({\n get: async () => {\n await connect();\n return current2;\n },\n navigate: (target) => command("navigate", target),\n replace: (target) => command("replace", target),\n back: () => command("back"),\n onChange(listener, options) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A navigation listener is required");\n let previous;\n const deliver = (location2) => {\n if (sameLocation(previous, location2)) return;\n previous = location2;\n notifyListener(listener, location2);\n };\n const errors = options ?? {};\n listeners.add(deliver);\n errorListeners.add(errors);\n void connect().then(\n () => {\n if (listeners.has(deliver)) deliver(current2);\n },\n (error) => {\n if (listeners.has(deliver)) reportNavigationError(error, errors);\n }\n );\n return () => {\n listeners.delete(deliver);\n errorListeners.delete(errors);\n };\n }\n });\n}\nfunction createStandaloneNavigation() {\n let current2 = Object.freeze({ pathname: "/", search: "", hash: "" });\n let connected = false;\n const listeners = /* @__PURE__ */ new Set();\n const traversals = /* @__PURE__ */ new Set();\n const read3 = () => {\n const url = new URL(window.location.href);\n for (const key of [...url.searchParams.keys()]) if (key.startsWith("__nocha_")) url.searchParams.delete(key);\n return normalizeExperienceLocation({ pathname: url.pathname, search: url.search, hash: url.hash });\n };\n const update = () => {\n const next = read3();\n if (next.pathname !== current2.pathname || next.search !== current2.search || next.hash !== current2.hash) {\n current2 = Object.freeze(next);\n for (const listener of listeners) notifyListener(listener, current2);\n }\n for (const complete of traversals) complete();\n };\n const connect = () => {\n if (typeof window === "undefined") throw new NochaError("navigation_unavailable", "Navigation requires a browser");\n if (connected) return;\n current2 = Object.freeze(read3());\n window.addEventListener("popstate", update);\n window.addEventListener("hashchange", update);\n connected = true;\n };\n const command = async (replace, target) => {\n connect();\n const next = normalizeExperienceLocation(target, current2);\n if (!replace && next.pathname === current2.pathname && next.search === current2.search && next.hash === current2.hash) return current2;\n const url = new URL(`${next.pathname}${next.search}${next.hash}`, window.location.origin);\n if (replace) window.history.replaceState(window.history.state, "", url.href);\n else window.history.pushState(null, "", url.href);\n update();\n return current2;\n };\n return Object.freeze({\n get: async () => {\n connect();\n return current2;\n },\n navigate: (target) => command(false, target),\n replace: (target) => command(true, target),\n back: async () => {\n connect();\n return new Promise((resolve) => {\n const complete = () => {\n clearTimeout(timer);\n traversals.delete(complete);\n resolve(current2);\n };\n const timer = setTimeout(complete, 1e3);\n traversals.add(complete);\n window.history.back();\n });\n },\n onChange(listener, options) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A navigation listener is required");\n try {\n connect();\n } catch (error) {\n reportNavigationError(error, options);\n return () => {\n };\n }\n listeners.add(listener);\n queueMicrotask(() => {\n if (listeners.has(listener)) notifyListener(listener, current2);\n });\n return () => {\n listeners.delete(listener);\n };\n }\n });\n}\nvar selected;\nvar source = () => selected ??= getNochaMode() === "standalone" ? createStandaloneNavigation() : createEmbeddedNavigation();\nvar navigation = Object.freeze({\n get: () => source().get(),\n navigate: (target) => source().navigate(target),\n replace: (target) => source().replace(target),\n back: () => source().back(),\n onChange: (listener, options) => source().onChange(listener, options)\n});\n\n// src/network.ts\nfunction isResponse(value) {\n return isRecord(value) && typeof value.status === "number" && Number.isInteger(value.status) && value.status >= 100 && value.status <= 599 && isString(value.contentType) && isString(value.body);\n}\nfunction isAsset(value) {\n return isRecord(value) && isString(value.mimeType) && isBase64(value.base64) && typeof value.sha256 === "string" && /^[0-9a-f]{64}$/.test(value.sha256);\n}\nfunction createNetwork(context) {\n return Object.freeze({\n async request(input3, options) {\n const value = await context.invoke(networkOperationDefinitions["request"].capability, networkOperationDefinitions["request"].operation, input3, options);\n if (!isResponse(value)) throw new NochaError("invalid_result", "Nocha returned an invalid network response");\n return value;\n },\n async asset(input3, options) {\n const value = await context.invoke(networkOperationDefinitions["asset"].capability, networkOperationDefinitions["asset"].operation, input3, options);\n if (!isAsset(value)) throw new NochaError("invalid_result", "Nocha returned an invalid network asset");\n return value;\n }\n });\n}\n\n// src/notifications.ts\nvar isResult2 = (value) => isRecord(value) && ["queued", "suppressed", "duplicate"].includes(String(value.status)) && (value.reason === void 0 || isString(value.reason));\nfunction createNotifications(context) {\n return Object.freeze({\n async send(input3, options) {\n const payload = input3?.destination === void 0 ? input3 : { ...input3, destination: normalizeExperienceLocation(input3.destination) };\n const value = await context.invoke(notificationsOperationDefinitions["send"].capability, notificationsOperationDefinitions["send"].operation, payload, options);\n if (!isResult2(value)) throw new NochaError("invalid_result", "Nocha returned an invalid notification result");\n return value;\n }\n });\n}\n\n// src/inbox.ts\nvar sources = /* @__PURE__ */ new Set(["api", "email", "schedule", "manual", "test"]);\nvar isTrigger = (value) => isRecord(value) && isNonEmptyString(value.id) && isString(value.slug) && isString(value.name);\nvar isEmail = (value) => isRecord(value) && isString(value.from) && isArrayOf(value.to, isString) && isArrayOf(value.cc, isString) && isString(value.subject) && Array.isArray(value.attachments) && isBoolean(value.authenticated);\nvar isEvent = (value) => isRecord(value) && isNonEmptyString(value.id) && sources.has(String(value.source)) && isNullable(value.trigger, isTrigger) && isNullable(value.task, isString) && Object.hasOwn(value, "payload") && isNullable(value.email, isEmail) && (value.status === "pending" || value.status === "acked") && isString(value.createdAt);\nvar isPage = (value) => isRecord(value) && isArrayOf(value.items, isEvent) && isNullable(value.next, isNonEmptyString);\nvar isAck = (value) => isRecord(value) && isCount(value.acked);\nvar minimumIntervalMs = 5e3;\nvar defaultIntervalMs = 15e3;\nvar pageSize = 50;\nvar rememberedIds = 1e3;\nfunction createInbox(context) {\n return Object.freeze({\n async list(input3, options) {\n const value = await context.invoke(inboxOperationDefinitions["list"].capability, inboxOperationDefinitions["list"].operation, input3 ?? {}, options);\n if (!isPage(value)) throw new NochaError("invalid_result", "Nocha returned an invalid inbox page");\n return value;\n },\n async ack(input3, options) {\n const value = await context.invoke(inboxOperationDefinitions["ack"].capability, inboxOperationDefinitions["ack"].operation, input3, options);\n if (!isAck(value)) throw new NochaError("invalid_result", "Nocha returned an invalid inbox acknowledgement");\n return value;\n },\n watch(listener, options) {\n assertHostCapability("inbox");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "An inbox listener is required");\n const { onError, intervalMs = defaultIntervalMs, signal } = options ?? {};\n if (typeof intervalMs !== "number" || !Number.isFinite(intervalMs) || intervalMs < minimumIntervalMs) {\n throw new NochaError("invalid_request", `inbox.watch polls every ${minimumIntervalMs} ms at least`);\n }\n const fail = (error) => {\n if (typeof onError === "function") notifyListener(onError, error);\n };\n if (context.usageId === void 0) {\n fail(new NochaError("usage_required", "inbox.watch requires nocha.use(<declared usage id>)"));\n return () => {\n };\n }\n let active2 = true;\n const controller = new AbortController();\n let timer;\n let after;\n let attempt = 0;\n const delivered = [];\n const seen = /* @__PURE__ */ new Set();\n const dispose = () => {\n active2 = false;\n controller.abort();\n if (timer !== void 0) clearTimeout(timer);\n signal?.removeEventListener("abort", dispose);\n };\n const later = (delayMs) => {\n if (active2) timer = setTimeout(() => {\n void poll();\n }, delayMs);\n };\n const poll = async () => {\n timer = void 0;\n try {\n const value = await context.invoke(\n inboxOperationDefinitions["list"].capability,\n inboxOperationDefinitions["list"].operation,\n { ...after === void 0 ? {} : { after }, limit: pageSize },\n { signal: controller.signal }\n );\n if (!active2) return;\n if (!isPage(value)) throw new NochaError("invalid_result", "Nocha returned an invalid inbox page");\n const fresh = value.items.filter((event) => !seen.has(event.id));\n for (const event of fresh) {\n seen.add(event.id);\n delivered.push(event.id);\n }\n while (delivered.length > rememberedIds) seen.delete(delivered.shift());\n after = value.items.at(-1)?.id ?? after;\n attempt = 0;\n if (fresh.length) notifyListener(listener, fresh);\n later(value.next ? minimumIntervalMs : intervalMs);\n } catch (cause) {\n if (!active2) return;\n const error = isNochaError(cause) ? cause : new NochaError("invocation_failed", String(cause));\n const delay = retryDelayMs(error, attempt);\n if (delay === void 0) {\n dispose();\n if (error.code !== "aborted") fail(error);\n return;\n }\n attempt += 1;\n later(Math.max(delay, minimumIntervalMs));\n }\n };\n if (signal?.aborted) {\n dispose();\n return dispose;\n }\n signal?.addEventListener("abort", dispose, { once: true });\n void poll();\n return dispose;\n }\n });\n}\n\n// src/outirl.ts\nvar captureStates = ["recording", "stopped", "expired", "failed"];\nvar isHostHeader = (value) => isRecord(value) && isNonEmptyString(value.hostId) && isString(value.hostName) && isString(value.collectedAt);\nvar isEvenCount = (value) => isCount(value) && value % 2 === 0;\nvar isMetrics = (value) => isHostHeader(value) && isString(value.context) && isBoolean(value.metricsAvailable) && Array.isArray(value.nodes) && Array.isArray(value.pods) && isArrayOf(value.warnings, isString);\nvar isHueLights = (value) => isHostHeader(value) && isArrayOf(value.lights, (light) => isRecord(light) && isString(light.id) && isString(light.name) && isBoolean(light.on) && isNullable(light.brightness, isFiniteNumber) && isBoolean(light.colorSupported)) && (value.groups === void 0 || Array.isArray(value.groups));\nvar isLedsSnapshot = (value) => isHostHeader(value) && isArrayOf(value.devices, (device) => isRecord(device) && isString(device.id) && isString(device.name) && isBoolean(device.online)) && Array.isArray(value.effects) && Array.isArray(value.scenes) && (value.commandId === void 0 || isString(value.commandId)) && (value.stateStatus === void 0 || value.stateStatus === "confirmed" || value.stateStatus === "optimistic");\nvar isAudioDevices = (value) => isHostHeader(value) && isArrayOf(value.devices, (device) => isRecord(device) && isString(device.id) && isBoolean(device.online) && isNullable(device.captureId, isString));\nvar isCapture = (deviceId) => (value) => isRecord(value) && isString(value.captureId) && value.deviceId === deviceId && value.state === "recording" && value.format === "s16le" && value.sampleRate === 16e3 && value.channels === 1;\nvar isChunk = (captureId) => (value) => isRecord(value) && value.captureId === captureId && captureStates.includes(String(value.state)) && isEvenCount(value.cursor) && isBase64(value.data) && isEvenCount(value.bytes) && isCount(value.totalBytes) && isCount(value.durationMs);\nvar isStopped = (captureId) => (value) => isRecord(value) && value.captureId === captureId && captureStates.includes(String(value.state)) && isCount(value.totalBytes) && isCount(value.durationMs);\nvar isTranscript = (captureId) => (value) => isRecord(value) && value.captureId === captureId && isString(value.text) && isCount(value.durationMs);\nvar isShare = (value) => isNullable(value, isFiniteNumber);\nvar isNetwork = (value) => isRecord(value) && isString(value.collectedAt) && isNullable(value.locksBusy, isCount) && isArrayOf(value.machines, (machine) => isRecord(machine) && isNonEmptyString(machine.id) && isBoolean(machine.reachable) && isShare(machine.cpuBusy) && isShare(machine.memoryUsed) && isArrayOf(machine.agents, (group) => isRecord(group) && isString(group.engine) && isString(group.surface) && isCount(group.count)) && isArrayOf(machine.jobs, (group) => isRecord(group) && isString(group.kind) && isString(group.status) && isCount(group.count)));\nvar isDesktopState = (value) => isRecord(value) && isRecord(value.terminal) && isString(value.terminal.app) && isBoolean(value.terminal.running) && isCount(value.terminal.windows) && isNullable(value.terminal.tabs, isCount) && isBoolean(value.terminal.frontmost) && isArrayOf(value.agents, (agent) => isRecord(agent) && isNonEmptyString(agent.id) && isString(agent.label)) && isRecord(value.dictation) && isBoolean(value.dictation.available);\nvar isDesktopDictation = (action) => (value) => isRecord(value) && value.action === action && value.delivered === true;\nvar isDesktopTerminal = (input3) => (value) => isRecord(value) && value.action === input3.action && isNullable(value.agentId, isString) && value.agentId === (input3.action === "tab.open" ? input3.agentId ?? null : null) && isCount(value.windows) && isNullable(value.tabs, isCount);\nvar field2 = (input3, key) => isRecord(input3) ? input3[key] : void 0;\nfunction createOutirl(context) {\n const call2 = async (operation2, input3, check, options) => {\n const value = await context.invoke(outirlOperationDefinitions[operation2].capability, outirlOperationDefinitions[operation2].operation, input3, options);\n if (!check(value)) throw new NochaError("invalid_result", `Nocha returned an invalid Outirl ${operation2} result`);\n return value;\n };\n return Object.freeze({\n metrics: (options) => call2("metrics.read", {}, isMetrics, options),\n hue: Object.freeze({\n lights: (options) => call2("hue.lights.read", {}, isHueLights, options),\n set: (input3, options) => call2("hue.lights.set", input3, isHueLights, options)\n }),\n leds: Object.freeze({\n read: (options) => call2("leds.read", {}, isLedsSnapshot, options),\n set: (input3, options) => call2("leds.set", input3, isLedsSnapshot, options)\n }),\n audio: Object.freeze({\n devices: (options) => call2("audio.devices", {}, isAudioDevices, options),\n start: (input3, options) => call2("audio.start", input3, isCapture(field2(input3, "deviceId")), options),\n read: (input3, options) => call2("audio.read", input3, isChunk(field2(input3, "captureId")), options),\n stop: (input3, options) => call2("audio.stop", input3, isStopped(field2(input3, "captureId")), options),\n transcribe: (input3, options) => call2("audio.transcribe", input3, isTranscript(field2(input3, "captureId")), options)\n }),\n network: (options) => call2("network.read", {}, isNetwork, options),\n desktop: Object.freeze({\n read: (options) => call2("desktop.read", {}, isDesktopState, options),\n dictation: (input3, options) => call2("desktop.dictation", input3, isDesktopDictation(field2(input3, "action")), options),\n terminal: (input3, options) => call2("desktop.terminal", input3, isDesktopTerminal(input3), options)\n })\n });\n}\n\n// src/state.ts\nfunction createStateWatch(invoke, subscribeEvents, subscribeConnection) {\n return (listener, options) => {\n assertHostCapability("state");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A state listener is required");\n let active2 = true;\n const controller = new AbortController();\n let authorized = false;\n let snapshot3 = null;\n let buffered = null;\n let connection2;\n let pending2 = false;\n let queued = false;\n let generation = 0;\n let attempt = 0;\n let timer;\n let stopEvents = () => {\n };\n let stopConnection = () => {\n };\n const emit = (status2, error) => {\n if (!active2) return;\n notifyListener(listener, { status: status2, snapshot: snapshot3, ...error ? { error } : {} });\n };\n const dispose = () => {\n active2 = false;\n controller.abort();\n if (timer !== void 0) clearTimeout(timer);\n stopEvents();\n stopConnection();\n options?.signal?.removeEventListener("abort", dispose);\n };\n const accept = (next) => {\n if (!snapshot3 || next.sequence > snapshot3.sequence) snapshot3 = next;\n };\n const currentStatus = () => connection2 === void 0 || connection2 === "connected" ? "synchronized" : "recovering";\n const refresh = () => {\n if (!active2) return;\n if (pending2) {\n queued = true;\n return;\n }\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n const startedGeneration = generation;\n pending2 = true;\n void invoke("state", "get", {}, { ...options, signal: controller.signal }).then((value) => {\n if (!active2 || startedGeneration !== generation) return;\n if (!isStateSnapshot(value)) throw new NochaError("invalid_result", "Nocha returned an invalid shared state snapshot");\n authorized = true;\n accept(value);\n if (buffered) {\n accept(buffered);\n buffered = null;\n }\n attempt = 0;\n emit(currentStatus());\n }).catch((cause) => {\n if (!active2 || startedGeneration !== generation) return;\n const error = isNochaError(cause) ? cause : new NochaError("invocation_failed", String(cause));\n const delay = retryDelayMs(error, attempt);\n if (delay === void 0) {\n emit("closed", error);\n dispose();\n return;\n }\n attempt += 1;\n emit("unavailable", error);\n timer = setTimeout(refresh, delay);\n }).finally(() => {\n pending2 = false;\n if (queued && active2) {\n queued = false;\n refresh();\n }\n });\n };\n if (options?.signal?.aborted) return dispose;\n stopEvents = subscribeEvents((event) => {\n if (!active2 || event.type !== "state.set") return;\n const value = { sequence: event.sequence, state: event.payload };\n if (!isStateSnapshot(value)) {\n refresh();\n return;\n }\n if (!authorized) {\n if (!buffered || value.sequence > buffered.sequence) buffered = value;\n return;\n }\n accept(value);\n emit(currentStatus());\n });\n stopConnection = subscribeConnection((event) => {\n if (!active2 || connection2 === event.status) return;\n connection2 = event.status;\n if (event.status === "closed") {\n emit("closed");\n dispose();\n return;\n }\n if (event.status === "connected") {\n refresh();\n return;\n }\n generation += 1;\n emit(event.status === "unavailable" ? "unavailable" : snapshot3 ? "recovering" : "loading");\n });\n options?.signal?.addEventListener("abort", dispose, { once: true });\n emit("loading");\n refresh();\n return dispose;\n };\n}\nfunction isStateSnapshot(value) {\n return isRecord(value) && isCount(value.sequence) && Object.hasOwn(value, "state");\n}\n\n// src/storage.ts\nfunction invalidResult(what) {\n throw new NochaError("invalid_result", `Nocha returned an invalid ${what}`);\n}\nasync function validated(request, check, what) {\n const value = await request;\n if (!check(value)) invalidResult(what);\n return value;\n}\nvar isAuthor = (value) => isNullable(value, isString);\nfunction isDatabaseRecord(value) {\n return isRecord(value) && isUuid(value.id) && isCount(value.revision) && value.revision >= 1 && isRecord(value.record) && isAuthor(value.author);\n}\nfunction input(value) {\n return isRecord(value) ? value : {};\n}\nfunction createState(context, watch) {\n return Object.freeze({\n get: (options) => validated(context.invoke(storageOperations.state.get.capability, storageOperations.state.get.operation, {}, options), isStateSnapshot, "shared state snapshot"),\n set: (value, options) => validated(context.invoke(storageOperations.state.set.capability, storageOperations.state.set.operation, {\n state: input(value).state,\n ...input(value).expectedSequence !== void 0 ? { expectedSequence: input(value).expectedSequence } : {}\n }, options), (next) => isStateSnapshot(next) && next.sequence >= 1, "shared state snapshot"),\n watch: (listener, options) => {\n if (context.usageId !== void 0) return watch(listener, options);\n assertHostCapability("state");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A state listener is required");\n notifyListener(listener, { status: "closed", snapshot: null, error: new NochaError("usage_required", "state.watch requires nocha.use(<declared usage id>)") });\n return () => {\n };\n }\n });\n}\nfunction createMemory(context) {\n const isMemory = (key) => (value) => isRecord(value) && value.key === key && isCount(value.sequence) && Object.hasOwn(value, "value");\n return Object.freeze({\n get: (value, options) => validated(context.invoke(storageOperations.memory.get.capability, storageOperations.memory.get.operation, value, options), isMemory(input(value).key), "memory value"),\n set: (value, options) => validated(context.invoke(storageOperations.memory.set.capability, storageOperations.memory.set.operation, value, options), isMemory(input(value).key), "memory value")\n });\n}\nfunction createDatabase(context) {\n return Object.freeze({\n insert: (value, options) => {\n if (!options?.idempotencyKey) return Promise.reject(new NochaError("invalid_request", "database.insert requires a persisted idempotencyKey"));\n return validated(\n context.invoke(storageOperations.database.insert.capability, storageOperations.database.insert.operation, value, options),\n (result2) => isRecord(result2) && isUuid(result2.id) && isCount(result2.revision) && result2.revision >= 1 && isAuthor(result2.author),\n "database insert receipt"\n );\n },\n get: (value, options) => validated(\n context.invoke(storageOperations.database.get.capability, storageOperations.database.get.operation, value, options),\n (result2) => result2 === null || isDatabaseRecord(result2) && result2.id === input(value).id,\n "database record"\n ),\n query: (value, options) => validated(\n context.invoke(storageOperations.database.query.capability, storageOperations.database.query.operation, value, options),\n (result2) => isRecord(result2) && Array.isArray(result2.records) && result2.records.every(isDatabaseRecord) && isNullable(result2.nextCursor, isString),\n "database page"\n ),\n update: (value, options) => validated(\n context.invoke(storageOperations.database.update.capability, storageOperations.database.update.operation, value, options),\n (result2) => isRecord(result2) && result2.id === input(value).id && isCount(result2.revision) && result2.revision >= 2 && isAuthor(result2.author),\n "database update receipt"\n ),\n remove: (value, options) => validated(\n context.invoke(storageOperations.database.remove.capability, storageOperations.database.remove.operation, value, options),\n (result2) => isRecord(result2) && result2.removed === true,\n "database removal receipt"\n )\n });\n}\n\n// src/clipping-types.ts\nvar CLIPPING_LIMITS = {\n source_maximum_bytes: 512 * 1024 * 1024,\n source_maximum_seconds: 30 * 60,\n target_minimum_seconds: 15,\n target_maximum_seconds: 120,\n instruction_maximum_characters: 2e3,\n accepted_mime_types: ["video/mp4", "video/quicktime", "video/webm"]\n};\n\n// src/clipping.ts\nfunction validJob(value) {\n return isRecord(value) && typeof value.id === "string" && ["proposal", "export"].includes(String(value.kind)) && ["queued", "running", "cancelling", "succeeded", "failed", "cancelled"].includes(String(value.status)) && Number.isFinite(value.progress) && Number(value.progress) >= 0 && Number(value.progress) <= 1 && typeof value.confirmed_maximum_microcredits === "string" && /^\\d+$/.test(value.confirmed_maximum_microcredits) && typeof value.spent_microcredits === "string" && /^\\d+$/.test(value.spent_microcredits);\n}\nfunction validExport(value) {\n return isRecord(value) && typeof value.id === "string" && Number.isInteger(value.plan_version) && typeof value.source_signature === "string" && validJob(value.job) && (value.result === null || isRecord(value.result) && typeof value.result.download_url === "string" && value.result.mime_type === "video/mp4" && Number.isFinite(value.result.duration_seconds) && Number.isFinite(value.result.size_bytes));\n}\nfunction validResource(value) {\n if (!isRecord(value) || typeof value.id !== "string" || value.project_id !== value.id || typeof value.title !== "string" || !isRecord(value.settings) || !Number.isFinite(value.settings.target_duration_seconds) || !["gentle", "balanced", "dynamic"].includes(String(value.settings.intensity)) || typeof value.settings.preserve_speech !== "boolean" || typeof value.settings.shorten_silences !== "boolean" || typeof value.settings.instruction !== "string" || !Array.isArray(value.exports) || !value.exports.every(validExport) || value.proposal_job !== null && !validJob(value.proposal_job)) return false;\n if (value.source !== null && (!isRecord(value.source) || typeof value.source.signature !== "string" || typeof value.source.name !== "string" || typeof value.source.has_audio !== "boolean" || !["duration_seconds", "size_bytes", "width", "height"].every((key) => Number.isFinite(value.source[key])) || !["preview_url", "thumbnail_url"].every((key) => value.source[key] === null || typeof value.source[key] === "string"))) return false;\n if (value.plan !== null && (!isRecord(value.plan) || !Number.isInteger(value.plan.version) || typeof value.plan.source_signature !== "string" || !Number.isFinite(value.plan.duration_seconds) || !Array.isArray(value.plan.evidence) || !value.plan.evidence.every((item) => isRecord(item) && typeof item.id === "string" && typeof item.description === "string" && ["visual", "speech", "audio"].includes(String(item.kind)) && Number.isFinite(item.start_seconds) && Number.isFinite(item.end_seconds)) || !Array.isArray(value.plan.segments) || !value.plan.segments.every((segment) => isRecord(segment) && typeof segment.id === "string" && typeof segment.explanation === "string" && Array.isArray(segment.evidence_ids) && segment.evidence_ids.every((id) => typeof id === "string") && Number.isFinite(segment.start_seconds) && Number.isFinite(segment.end_seconds) && Number(segment.end_seconds) > Number(segment.start_seconds)))) return false;\n return true;\n}\nvar validators = {\n prepareMutation: (result2) => isRecord(result2) && typeof result2.idempotency_key === "string" && "request" in result2,\n readMutation: (result2) => isRecord(result2) && (result2.pending === null || isRecord(result2.pending) && typeof result2.pending.idempotency_key === "string" && "request" in result2.pending),\n completeMutation: (result2) => isRecord(result2) && result2.completed === true,\n remove: (result2) => isRecord(result2) && result2.deleted === true,\n list: (result2) => isRecord(result2) && Array.isArray(result2.items) && result2.items.every(validResource),\n estimate: (result2) => isRecord(result2) && typeof result2.maximum_microcredits === "string" && /^\\d+$/.test(result2.maximum_microcredits) && typeof result2.valid_until === "string",\n createExport: validExport,\n getJob: validJob,\n cancelJob: validJob,\n resumeJob: validJob\n};\nasync function call(context, operation2, input3, options) {\n const result2 = await context.invoke(videoOperationDefinitions[operation2].capability, videoOperationDefinitions[operation2].operation, input3, options);\n if (!(validators[operation2.slice("clipping.".length)] ?? validResource)(result2)) throw new NochaError("invalid_result", "Nocha returned an invalid clipping result");\n return result2;\n}\nfunction text2(value, field3) {\n if (typeof value !== "string" || !value) throw invalid(`${field3} must be a non-empty string`);\n return value;\n}\nfunction integer(value, field3) {\n if (typeof value !== "number" || !Number.isInteger(value)) throw invalid(`${field3} must be an integer`);\n return value;\n}\nfunction ceiling(value) {\n if (typeof value !== "string" || !/^\\d+$/.test(value)) throw invalid("confirmedMaximumMicrocredits must be a decimal integer string");\n return value;\n}\nfunction document2(value, field3) {\n if (!isRecord(value)) throw invalid(`${field3} must be an object`);\n return value;\n}\nfunction input2(value) {\n if (!isRecord(value)) throw invalid("A clipping request object is required");\n return value;\n}\nasync function uploadSource(context, request, options = {}) {\n const value = input2(request);\n const id = text2(value.id, "id");\n const file = value.file;\n if (!(file instanceof Blob) || file.size <= 0) throw invalid("A non-empty video file is required");\n if (value.filename !== void 0 && typeof value.filename !== "string") throw invalid("filename must be a string");\n const filename = value.filename ?? ("name" in file ? String(file.name) : "source.mp4");\n const mimeType = file.type || (/\\.mov$/i.test(filename) ? "video/quicktime" : /\\.webm$/i.test(filename) ? "video/webm" : "video/mp4");\n if (!CLIPPING_LIMITS.accepted_mime_types.includes(mimeType)) throw invalid("Select an MP4, MOV or WebM video");\n assertHostCapability("video");\n if (context.usageId === void 0) throw new NochaError("usage_required", "video.clipping.uploadSource requires nocha.use(<declared usage id>)");\n if (options.idempotencyKey !== void 0 && !isIdempotencyKey(options.idempotencyKey)) throw invalid("idempotencyKey must contain 8 to 200 characters");\n if (options.signal?.aborted) throw new NochaError("aborted", "Video upload aborted");\n const upload2 = { id, filename, mime_type: mimeType, size_bytes: file.size };\n const timeout = options.timeoutMs ?? deadlineMs(videoOperationDefinitions["clipping.uploadSource"].capability, videoOperationDefinitions["clipping.uploadSource"].operation, upload2);\n if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid("timeoutMs must be a positive finite timer duration");\n const host = window.parent;\n const requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const abort = () => {\n host.postMessage({ protocol: "nocha.upload.v1", type: "abort", requestId }, "*");\n cleanup();\n reject2(new NochaError("aborted", "Video upload aborted"));\n };\n const expire = () => {\n cleanup();\n reject2(new NochaError("invocation_timed_out", "Local upload wait timed out; the upload may still complete"));\n };\n const receive = (event) => {\n const message = event.data;\n if (!isFromHost(event) || !isRecord(message) || message.protocol !== "nocha.upload.v1" || message.requestId !== requestId) return;\n if (message.type === "progress") {\n if (options.onProgress) notifyListener(options.onProgress, { loaded: Number(message.loaded), total: file.size });\n return;\n }\n cleanup();\n if (message.type === "result" && validResource(message.result)) resolve(message.result);\n else reject2(wireError(message.error, { code: "upload_failed", message: "Video upload failed" }));\n };\n const timer = setTimeout(expire, timeout);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n host.postMessage({ protocol: "nocha.upload.v1", type: "upload", requestId, usageId: context.usageId, idempotencyKey: options.idempotencyKey ?? `${requestId}:upload`, input: upload2, file }, "*");\n } catch (error) {\n cleanup();\n reject2(error);\n }\n });\n}\nfunction createClipping(context) {\n const run = (operation2, build, options) => {\n try {\n return call(context, operation2, build(), options);\n } catch (error) {\n return Promise.reject(error);\n }\n };\n return Object.freeze({\n prepareMutation: (request, options) => run("clipping.prepareMutation", () => {\n const value = input2(request);\n return { slot: text2(value.slot, "slot"), request: value.request };\n }, options),\n readMutation: (request, options) => run("clipping.readMutation", () => ({ slot: text2(input2(request).slot, "slot") }), options),\n completeMutation: (request, options) => run("clipping.completeMutation", () => {\n const value = input2(request);\n return { slot: text2(value.slot, "slot"), idempotency_key: text2(value.idempotencyKey, "idempotencyKey") };\n }, options),\n create: (request, options) => run("clipping.create", () => {\n const value = input2(request);\n return { title: text2(value.title, "title"), ...value.settings !== void 0 ? { settings: document2(value.settings, "settings") } : {} };\n }, options),\n list: (request = {}, options) => run("clipping.list", () => {\n const value = input2(request);\n return { ...value.limit !== void 0 ? { limit: integer(value.limit, "limit") } : {}, ...value.cursor !== void 0 ? { cursor: text2(value.cursor, "cursor") } : {} };\n }, options),\n get: (request, options) => run("clipping.get", () => ({ id: text2(input2(request).id, "id") }), options),\n remove: (request, options) => run("clipping.remove", () => ({ id: text2(input2(request).id, "id") }), options),\n uploadSource: (request, options) => uploadSource(context, request, options),\n estimate: (request, options) => run("clipping.estimate", () => {\n const value = input2(request);\n return { id: text2(value.id, "id"), settings: document2(value.settings, "settings"), ...value.kind !== void 0 ? { kind: value.kind } : {} };\n }, options),\n propose: (request, options) => run("clipping.propose", () => {\n const value = input2(request);\n return { id: text2(value.id, "id"), settings: document2(value.settings, "settings"), expected_version: integer(value.expectedVersion, "expectedVersion"), confirmed_maximum_microcredits: ceiling(value.confirmedMaximumMicrocredits) };\n }, options),\n updatePlan: (request, options) => run("clipping.updatePlan", () => {\n const value = input2(request);\n if (!Array.isArray(value.segments)) throw invalid("segments must be a list");\n return { id: text2(value.id, "id"), expected_version: integer(value.expectedVersion, "expectedVersion"), source_signature: text2(value.sourceSignature, "sourceSignature"), segments: value.segments };\n }, options),\n createExport: (request, options) => run("clipping.createExport", () => {\n const value = input2(request);\n return { id: text2(value.id, "id"), plan_version: integer(value.planVersion, "planVersion"), source_signature: text2(value.sourceSignature, "sourceSignature"), confirmed_maximum_microcredits: ceiling(value.confirmedMaximumMicrocredits) };\n }, options),\n getJob: (request, options) => run("clipping.getJob", () => {\n const value = input2(request);\n return { id: text2(value.id, "id"), job_id: text2(value.jobId, "jobId") };\n }, options),\n cancelJob: (request, options) => run("clipping.cancelJob", () => {\n const value = input2(request);\n return { id: text2(value.id, "id"), job_id: text2(value.jobId, "jobId") };\n }, options),\n resumeJob: (request, options) => run("clipping.resumeJob", () => {\n const value = input2(request);\n return { id: text2(value.id, "id"), job_id: text2(value.jobId, "jobId"), confirmed_maximum_microcredits: ceiling(value.confirmedMaximumMicrocredits) };\n }, options)\n });\n}\n\n// src/video-input.ts\nvar aspectRatios = /* @__PURE__ */ new Set(["9:16", "16:9", "1:1"]);\nvar locales = new Set(videoLocales);\nvar speechModes = /* @__PURE__ */ new Set(["none", "auto", "required"]);\nvar resolutions = /* @__PURE__ */ new Set(["720p", "1080p"]);\nvar efforts = /* @__PURE__ */ new Set(["auto", "low", "medium", "high"]);\nvar videoWorkflowFamilies = /* @__PURE__ */ new Set(["classic", "narrative", "image_loop", "analysis"]);\nvar videoStages = ["preparing", "planning", "generating_speech", "generating_media", "assembling"];\nvar workflowId = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/;\nvar analysisSubjectId = /^[plo][1-9]\\d{0,2}$/;\nfunction videoId(value) {\n if (typeof value !== "string" || !isUuid(value.trim())) throw invalid("A valid video generation id is required");\n return value.trim();\n}\nfunction positiveInteger(value, label) {\n if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw invalid(`${label} must be a positive integer`);\n return value;\n}\nfunction videoWorkflowRef(value, label = "workflow") {\n if (!isRecord(value) || typeof value.id !== "string" || !workflowId.test(value.id.trim())) throw invalid(`${label} needs an id such as film-classique or fmt_\\u2026`);\n return { id: value.id.trim(), ...value.revision === void 0 ? {} : { revision: positiveInteger(value.revision, `${label}.revision`) } };\n}\nfunction text3(value, label) {\n if (value === void 0) return void 0;\n if (typeof value !== "string" || !value.trim()) throw invalid(`${label} must be a non-empty string`);\n return value.trim();\n}\nfunction replaces(value, label) {\n if (value === void 0) return void 0;\n if (!isRecord(value)) throw invalid(`${label} must be an object`);\n const subject2 = text3(value.subjectId, `${label}.subjectId`), description = text3(value.description, `${label}.description`);\n if (subject2 !== void 0 && !analysisSubjectId.test(subject2)) throw invalid(`${label}.subjectId must be a subject of the analysis such as p1, l1 or o1`);\n if (!subject2 && !description) throw invalid(`${label} needs a subjectId, a description or both`);\n return { ...subject2 ? { subject_id: subject2 } : {}, ...description ? { description } : {} };\n}\nfunction reference(value, index) {\n const label = `references[${index}]`;\n if (!isRecord(value)) throw invalid(`${label} must be an object`);\n const role = text3(value.role, `${label}.role`), name = text3(value.name, `${label}.name`), description = text3(value.description, `${label}.description`);\n const replaced = replaces(value.replaces, `${label}.replaces`);\n const details = { ...role ? { role } : {}, ...name ? { name } : {}, ...description ? { description } : {}, ...replaced ? { replaces: replaced } : {} };\n if (value.assetId === void 0 === (value.studioReferenceId === void 0)) throw invalid(`${label} needs one assetId or one studioReferenceId`);\n const id = value.assetId ?? value.studioReferenceId;\n if (typeof id !== "string" || !isUuid(id.trim())) throw invalid(`${label} id must be a uuid`);\n return value.assetId !== void 0 ? { asset_id: id.trim().toLowerCase(), ...details } : { studio_reference_id: id.trim().toLowerCase(), ...details };\n}\nfunction member(value, values, label, fallback) {\n if (value === void 0 && fallback !== void 0) return fallback;\n if (!values.has(value)) throw invalid(`${label} must be one of ${[...values].join(", ")}`);\n return value;\n}\nfunction parameterValue(value, label) {\n if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return;\n if (!isRecord(value) || Object.keys(value).some((key) => key !== "provider" && key !== "model") || typeof value.provider !== "string" || !value.provider || typeof value.model !== "string" || !value.model) {\n throw invalid(`${label} must be a string, finite number, boolean or { provider, model } route`);\n }\n}\nfunction parameterMap(value, label) {\n if (!isRecord(value)) throw invalid(`${label} must be an object`);\n for (const [key, item] of Object.entries(value)) parameterValue(item, `${label}.${key}`);\n}\nfunction parameterValues(value) {\n if (value === void 0) return;\n if (!isRecord(value) || Object.keys(value).some((key) => key !== "workflow" && key !== "modules")) {\n throw invalid("parameters must contain only workflow and modules dictionaries");\n }\n if (value.workflow !== void 0) parameterMap(value.workflow, "parameters.workflow");\n if (value.modules !== void 0) {\n if (!isRecord(value.modules)) throw invalid("parameters.modules must be an object");\n for (const [instanceId, parameters] of Object.entries(value.modules)) parameterMap(parameters, `parameters.modules.${instanceId}`);\n }\n}\nfunction canonicalParameters(input3) {\n parameterValues(input3.parameters);\n const alias = input3.outputResolution === void 0 ? void 0 : member(input3.outputResolution, resolutions, "outputResolution");\n if (alias === void 0) return input3.parameters;\n const canonical2 = input3.parameters?.workflow?.output_resolution;\n if (canonical2 !== void 0 && canonical2 !== alias) {\n throw invalid("outputResolution conflicts with parameters.workflow.output_resolution");\n }\n return { ...input3.parameters, workflow: { ...input3.parameters?.workflow, output_resolution: alias } };\n}\nfunction propertyJson(value, label, parents) {\n if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return;\n if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n throw invalid(`${label} must be a JSON value`);\n }\n if (parents.has(value)) throw invalid(`${label} must not contain a cycle`);\n parents.add(value);\n for (const item of Array.isArray(value) ? value : Object.values(value)) propertyJson(item, label, parents);\n parents.delete(value);\n}\nfunction properties(value) {\n if (value === void 0) return;\n if (!isRecord(value)) throw invalid("properties must be an object keyed by workflow step");\n for (const [step2, values] of Object.entries(value)) {\n if (!videoStepIdPattern.test(step2)) throw invalid(`properties.${step2} is not a workflow step id`);\n if (!isRecord(values)) throw invalid(`properties.${step2} must be an object`);\n for (const [key, item] of Object.entries(values)) {\n if (!workflowId.test(key)) throw invalid(`properties.${step2} has an invalid property key`);\n propertyJson(item, `properties.${step2}.${key}`, /* @__PURE__ */ new Set());\n }\n }\n}\nfunction videoRequestWire(input3) {\n if (!isRecord(input3)) throw invalid("A video request is required");\n const legacy = ["profile", "contentLocale", "qualityProfile", "referenceAssetIds", "referenceMetadata", "studioReferenceIds", "imageAssetId", "circuitFormat", "generationUsage"].find((field3) => input3[field3] !== void 0);\n if (legacy) throw invalid(`${legacy} is not a video request field: choose a workflow and pass references (see the 6.0.0 migration guide)`);\n if (typeof input3.prompt !== "string" || !input3.prompt.trim()) throw invalid("prompt must be a non-empty string");\n if (input3.referencePreparation !== void 0 && input3.referencePreparation !== "auto") throw invalid("referencePreparation must be auto when provided");\n if (input3.references !== void 0 && !Array.isArray(input3.references)) throw invalid("references must be a list");\n if (input3.sourceAnalysisId !== void 0 && (typeof input3.sourceAnalysisId !== "string" || !isUuid(input3.sourceAnalysisId.trim()))) {\n throw invalid("sourceAnalysisId must be the id of an analyse-video generation");\n }\n const parameters = canonicalParameters(input3);\n properties(input3.properties);\n return {\n api: 2,\n workflow: videoWorkflowRef(input3.workflow),\n goal: input3.prompt.trim(),\n duration_seconds: positiveInteger(input3.durationSeconds, "durationSeconds"),\n speech: member(input3.speech, speechModes, "speech"),\n aspect_ratio: member(input3.aspectRatio, aspectRatios, "aspectRatio", "9:16"),\n locale: member(input3.locale, locales, "locale", "fr-FR"),\n ...parameters === void 0 ? {} : { parameters },\n ...input3.properties === void 0 ? {} : { properties: input3.properties },\n ...input3.references === void 0 ? {} : { references: input3.references.map(reference) },\n ...input3.referencePreparation ? { reference_preparation: "auto" } : {},\n ...input3.sourceAnalysisId === void 0 ? {} : { source_analysis_id: input3.sourceAnalysisId.trim().toLowerCase() },\n ...input3.effort === void 0 ? {} : { effort: member(input3.effort, efforts, "effort") }\n };\n}\nfunction videoCreateWire(input3) {\n const request = videoRequestWire(input3);\n return { ...request, ...videoNotifyWire(input3), confirmed_maximum_microcredits: confirmedMaximum(input3.confirmedMaximumMicrocredits) };\n}\nfunction videoNotifyWire(input3) {\n const notify = input3.notify;\n if (notify === void 0) return {};\n if (!isRecord(notify) || typeof notify.dedupeKey !== "string" || !/^[A-Za-z0-9_-]+$/.test(notify.dedupeKey)) {\n throw invalid("notify needs a dedupeKey made of letters, digits, - and _");\n }\n if (!isRecord(notify.messages)) throw invalid("notify needs messages for succeeded and failed");\n const { succeeded, failed, cancelled, stages: stages2 } = notify.messages;\n if (stages2 !== void 0 && (!isRecord(stages2) || Object.keys(stages2).some((stage) => !videoStages.includes(stage)))) {\n throw invalid(`notify messages stages are keyed by ${videoStages.join(", ")}`);\n }\n return { notify: {\n dedupe_key: notify.dedupeKey,\n ...notify.search === void 0 ? {} : { search: notifySearch(notify.search) },\n messages: {\n succeeded: notifyMessage(succeeded, "succeeded"),\n failed: notifyMessage(failed, "failed"),\n ...cancelled === void 0 ? {} : { cancelled: notifyMessage(cancelled, "cancelled") },\n ...stages2 === void 0 ? {} : { stages: Object.fromEntries(Object.entries(stages2).map(([stage, message]) => [stage, notifyMessage(message, stage)])) }\n }\n } };\n}\nfunction notifyMessage(value, label) {\n if (!isRecord(value) || typeof value.title !== "string" || !value.title.trim()) throw invalid(`notify message ${label} needs a title`);\n if (value.body !== void 0 && typeof value.body !== "string") throw invalid(`notify message ${label} body must be a string`);\n return { title: value.title, ...value.body === void 0 ? {} : { body: value.body } };\n}\nfunction notifySearch(value) {\n const location2 = typeof value === "string" && value.startsWith("?") ? normalizeExperienceLocation({ pathname: "/", search: value, hash: "" }) : null;\n if (!location2 || location2.pathname !== "/" || location2.hash || !location2.search) throw invalid("notify search must be a query such as ?film=<key>");\n return location2.search;\n}\nfunction confirmedMaximum(value) {\n if (!isMicrocredits(value)) throw invalid("confirmedMaximumMicrocredits must be a positive integer string");\n return value;\n}\nfunction videoWorkflowsWire(input3) {\n if (input3 === void 0) return {};\n if (!isRecord(input3)) throw invalid("workflows takes { durationSeconds?, family? }");\n return {\n ...input3.durationSeconds === void 0 ? {} : { duration_seconds: positiveInteger(input3.durationSeconds, "durationSeconds") },\n ...input3.family === void 0 ? {} : { family: member(input3.family, videoWorkflowFamilies, "family") }\n };\n}\n\n// src/video-media.ts\nfunction isMediaResult(value, id) {\n return isRecord(value) && value.id === id && value.mime_type === "video/mp4" && value.blob instanceof Blob && value.blob.type === "video/mp4" && value.blob.size > 0 && value.size_bytes === value.blob.size;\n}\nasync function readVideoMedia(context, input3, options = {}) {\n const id = videoId(isRecord(input3) ? input3.id : void 0);\n const timeout = mediaReadTimeout(options, operationWaiting.video.media);\n assertHostCapability("video");\n const usageId = context.usageId;\n if (usageId === void 0) throw new NochaError("usage_required", "video.media requires nocha.use(<declared usage id>)");\n if (options.signal?.aborted) throw new NochaError("aborted", "Video read aborted");\n return readHostMedia({\n noun: "video",\n timeoutMs: timeout,\n firstReplyMs: operationWaiting.video["media.firstReply"],\n options,\n accept: (result2) => isMediaResult(result2, id) ? result2.blob : void 0,\n send: (host, requestId) => host.postMessage({\n protocol: "nocha.media.v1",\n type: "read",\n requestId,\n capability: videoOperationDefinitions["get"].capability,\n operation: videoOperationDefinitions["get"].operation,\n usageId,\n input: { id }\n }, "*")\n });\n}\n\n// src/video-playback.ts\nasync function readVideoPlayback(context, input3, options = {}) {\n const id = videoId(isRecord(input3) ? input3.id : void 0);\n if (!isRecord(options)) throw invalid("Request options must be an object");\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalid("signal must be an AbortSignal");\n const timeout = options.timeoutMs ?? operationWaiting.video.default;\n if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid("timeoutMs must be a positive finite timer duration");\n assertHostCapability("video");\n if (context.usageId === void 0) throw new NochaError("usage_required", "video.playback requires nocha.use(<declared usage id>)");\n if (options.signal?.aborted) throw new NochaError("aborted", "Video playback aborted");\n const host = window.parent, requestId = crypto.randomUUID();\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n clearTimeout(unanswered);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const stop = (error) => {\n cleanup();\n try {\n host.postMessage({ protocol: "nocha.video-playback.v1", type: "abort", requestId }, "*");\n } catch {\n }\n reject2(error);\n };\n const abort = () => stop(new NochaError("aborted", "Video playback aborted"));\n const receive = (event) => {\n const message = event.data;\n if (!isFromHost(event) || !isRecord(message) || message.protocol !== "nocha.video-playback.v1" || message.requestId !== requestId) return;\n clearTimeout(unanswered);\n if (message.type === "accepted") return;\n if (message.type !== "result" && message.type !== "error") return;\n cleanup();\n if (message.type === "error") {\n reject2(wireError(message.error, { code: "media_unavailable", message: "Video playback is unavailable" }));\n return;\n }\n const result2 = message.result;\n if (isRecord(result2) && result2.id === id && result2.mimeType === "video/mp4" && typeof result2.url === "string" && typeof result2.expiresAt === "string" && Number.isFinite(Date.parse(result2.expiresAt)) && Date.parse(result2.expiresAt) > Date.now()) {\n try {\n const url = new URL(result2.url);\n if ((url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && !url.hash && /^\\/api\\/video\\/[0-9a-f-]{36}\\/media$/i.test(url.pathname) && url.searchParams.get("token") && [...url.searchParams.keys()].every((key) => key === "token")) {\n resolve({ url: url.href, expiresAt: result2.expiresAt, mimeType: "video/mp4" });\n return;\n }\n } catch {\n }\n }\n reject2(new NochaError("invalid_result", "Nocha returned an invalid video playback URL"));\n };\n const unanswered = setTimeout(() => stop(new NochaError("playback_unsupported_host", "Update the Nocha host to stream video playback")), Math.min(timeout, 15e3));\n const timer = setTimeout(() => stop(new NochaError("invocation_timed_out", "Local video playback authorization timed out")), timeout);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n host.postMessage({ protocol: "nocha.video-playback.v1", type: "open", requestId, capability: "video", operation: "get", usageId: context.usageId, input: { id } }, "*");\n } catch (cause) {\n cleanup();\n reject2(new NochaError("invalid_request", `The request cannot be sent to the Nocha host: ${String(cause)}`));\n }\n });\n}\n\n// src/video-resource.ts\nvar string2 = (value) => typeof value === "string";\nvar text4 = (value) => string2(value) ? value : null;\nvar count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\nvar measure = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;\nvar credits2 = (value) => string2(value) && /^\\d+$/.test(value);\nvar pick2 = (value, values) => string2(value) && values.includes(value) ? value : null;\nvar keep = (value, values) => Array.isArray(value) ? value.filter((item) => pick2(item, values) !== null) : [];\nvar counts = (value) => Array.isArray(value) ? value.filter(count) : [];\nvar records2 = (value) => Array.isArray(value) ? value.filter(isRecord) : [];\nvar optionalText = (value, key) => string2(value[key]) ? { [key]: value[key] } : {};\nvar families = ["classic", "narrative", "image_loop", "analysis"];\nvar kinds = ["film", "image_loop", "analysis"];\nvar speech = ["none", "auto", "required"];\nvar ratios = ["9:16", "16:9", "1:1"];\nvar locales2 = videoLocales;\nvar resolutions2 = ["720p", "1080p"];\nvar efforts2 = ["auto", "low", "medium", "high"];\nvar stages = ["preparing", "planning", "generating_speech", "generating_media", "assembling"];\nvar costEffects = ["none", "may_change_quantity", "may_change_unit_price", "may_change_route"];\nvar resumeReasons = [\n "interrupted",\n "inputs_changed",\n "provider_unavailable",\n "storage_full",\n "paid_work_retained",\n "retryable_failure",\n "final_failure",\n "budget_exhausted",\n "workflow_taken_over",\n "media_expired"\n];\nvar resumeActions = ["keep", "redo", "run"];\nfunction resume(value) {\n if (value === void 0) return void 0;\n if (!isRecord(value)) return null;\n const estimated = value.estimated_microcredits;\n if (typeof value.available !== "boolean" || !credits2(value.remaining_microcredits) || !(estimated === null || credits2(estimated))) return null;\n return {\n available: value.available,\n reason: pick2(value.reason, resumeReasons),\n steps: records2(value.steps).flatMap((step2) => {\n const action = pick2(step2.action, resumeActions);\n return string2(step2.id) && action && typeof step2.paid === "boolean" ? [{ id: step2.id, action, paid: step2.paid }] : [];\n }),\n estimated_microcredits: estimated,\n remaining_microcredits: value.remaining_microcredits\n };\n}\nvar scalar = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);\nfunction parameterValue2(value) {\n if (scalar(value)) return value;\n return isRecord(value) && string2(value.provider) && string2(value.model) ? { provider: value.provider, model: value.model } : void 0;\n}\nfunction parameterMap2(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => {\n const parsed = parameterValue2(item);\n return parsed === void 0 ? [] : [[key, parsed]];\n }));\n}\nfunction parameterValues2(value) {\n if (!isRecord(value)) return void 0;\n const workflow2 = parameterMap2(value.workflow);\n const modules = isRecord(value.modules) ? Object.fromEntries(Object.entries(value.modules).flatMap(([instanceId, item]) => {\n const parsed = parameterMap2(item);\n return parsed === void 0 ? [] : [[instanceId, parsed]];\n })) : void 0;\n return { ...workflow2 === void 0 ? {} : { workflow: workflow2 }, ...modules === void 0 ? {} : { modules } };\n}\nfunction parameterDefinition(value) {\n const scope = pick2(value.scope, ["workflow", "module"]);\n const costEffect = pick2(value.cost_effect, costEffects);\n const moduleId = value.module_id, instanceId = value.module_instance_id;\n const identity2 = scope === "workflow" ? moduleId === null && instanceId === null : scope === "module" && string2(moduleId) && string2(instanceId);\n const defaultValue = value.default === null ? null : parameterValue2(value.default);\n if (!string2(value.key) || !scope || !costEffect || !identity2 || defaultValue === void 0) return null;\n const base2 = {\n key: value.key,\n scope,\n module_id: moduleId,\n module_instance_id: instanceId,\n default: defaultValue,\n cost_effect: costEffect\n };\n const constraints = isRecord(value.constraints) ? value.constraints : null;\n if (value.type === "boolean" && value.constraints === null) return { ...base2, type: "boolean", constraints: null };\n if ((value.type === "integer" || value.type === "number") && constraints) {\n const values = Object.fromEntries(["minimum", "maximum", "step"].flatMap((key) => typeof constraints[key] === "number" && Number.isFinite(constraints[key]) ? [[key, constraints[key]]] : []));\n return { ...base2, type: value.type, constraints: values };\n }\n if (value.type === "string" && constraints) {\n return { ...base2, type: "string", constraints: count(constraints.max_length) ? { max_length: constraints.max_length } : {} };\n }\n if (value.type === "enum" && constraints && Array.isArray(constraints.values) && constraints.values.every(scalar)) {\n return { ...base2, type: "enum", constraints: { values: constraints.values } };\n }\n if (value.type === "route" && constraints?.need === "video.generate" && Array.isArray(constraints.routes)) {\n const routes = constraints.routes.map(parameterValue2).filter((route) => isRecord(route));\n if (routes.length === constraints.routes.length) return { ...base2, type: "route", constraints: { need: "video.generate", routes } };\n }\n return null;\n}\nfunction failure2(value) {\n return isRecord(value) && string2(value.code) && string2(value.message) ? { code: value.code, message: value.message, retryable: value.retryable === true } : null;\n}\nfunction result(value) {\n if (value === null) return null;\n if (isRecord(value) && value.kind !== void 0) return readVideoAnalysisResult(value);\n if (!isRecord(value) || measure(value.actual_duration_seconds) === null || !string2(value.download_url) || !string2(value.download_url_expires_at) || value.mime_type !== "video/mp4" || !string2(value.sha256) || !count(value.size_bytes)) return void 0;\n return {\n actual_duration_seconds: value.actual_duration_seconds,\n download_url: value.download_url,\n download_url_expires_at: value.download_url_expires_at,\n mime_type: "video/mp4",\n sha256: value.sha256,\n size_bytes: value.size_bytes,\n ...string2(value.filename) && value.filename.trim().length > 0 && value.filename.length <= 255 ? { filename: value.filename } : {},\n ...string2(value.asset_id) && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.asset_id) ? { asset_id: value.asset_id } : {},\n ...count(value.width) && value.width > 0 ? { width: value.width } : {},\n ...count(value.height) && value.height > 0 ? { height: value.height } : {},\n ...pick2(value.aspect_ratio, ratios) ? { aspect_ratio: pick2(value.aspect_ratio, ratios) } : {}\n };\n}\nfunction workflowRef(value) {\n if (!isRecord(value) || !string2(value.id) || !value.id) return null;\n return { id: value.id, family: pick2(value.family, families), revision: count(value.revision) ? value.revision : null, digest: text4(value.digest), ...optionalText(value, "name") };\n}\nfunction automation(value) {\n if (!isRecord(value) || !string2(value.id) || !string2(value.started_at) || !string2(value.updated_at)) return void 0;\n return {\n id: value.id,\n status: pick2(value.status, ["running", "stopping", "completed", "blocked", "cancelled"]),\n started_at: value.started_at,\n updated_at: value.updated_at,\n finished_at: text4(value.finished_at),\n error: failure2(value.error),\n steps: records2(value.steps).filter((step2) => string2(step2.id)).map((step2) => ({\n id: step2.id,\n operation: text4(step2.operation),\n status: pick2(step2.status, ["pending", "queued", "running", "retrying", "completed", "partial", "blocked", "cancelled", "skipped"]),\n freshness: pick2(step2.freshness, ["fresh", "outdated", "update_available", "missing"]),\n produced_by: isRecord(step2.produced_by) && string2(step2.produced_by.module_id) && count(step2.produced_by.revision) ? { module_id: step2.produced_by.module_id, revision: step2.produced_by.revision } : null,\n jobs_count: count(step2.jobs_count) ? step2.jobs_count : 0,\n error: failure2(step2.error)\n })),\n jobs: records2(value.jobs).filter((job) => string2(job.id) && string2(job.operation) && string2(job.created_at) && string2(job.updated_at)).map((job) => {\n const progress = isRecord(job.progress) ? job.progress : {};\n const module = isRecord(job.module) && string2(job.module.id) && string2(job.module.instance_id) && count(job.module.revision) ? { id: job.module.id, instance_id: job.module.instance_id, revision: job.module.revision } : null;\n return {\n id: job.id,\n step_id: text4(job.step_id),\n operation: job.operation,\n module,\n status: pick2(job.status, ["queued", "running", "retrying", "succeeded", "failed", "cancelled", "blocked"]),\n attempt: count(job.attempt) ? job.attempt : null,\n progress: { percent: measure(progress.percent), completed_units: measure(progress.completed_units), total_units: measure(progress.total_units) },\n created_at: job.created_at,\n started_at: text4(job.started_at),\n updated_at: job.updated_at,\n finished_at: text4(job.finished_at),\n error: failure2(job.error)\n };\n }),\n jobs_total: count(value.jobs_total) ? value.jobs_total : 0,\n jobs_truncated: value.jobs_truncated === true\n };\n}\nfunction readVideoGeneration(value) {\n if (!isRecord(value) || !string2(value.id) || !value.id || !string2(value.created_at) || !string2(value.updated_at)) return null;\n const output = result(value.result);\n if (output === void 0) return null;\n if (value.audience_view === "shared") {\n if (value.status !== "succeeded" || !output || !string2(value.collection_id)) return null;\n return {\n audience_view: "shared",\n id: value.id,\n collection_id: value.collection_id,\n kind: pick2(value.kind, kinds),\n status: "succeeded",\n created_at: value.created_at,\n updated_at: value.updated_at,\n result: output\n };\n }\n const workflow2 = workflowRef(value.workflow);\n const request = isRecord(value.request) ? value.request : null;\n const requested = request ? workflowRef({ ...isRecord(request.workflow) ? request.workflow : {}, family: null }) : null;\n const progress = isRecord(value.progress) ? value.progress : null;\n const cost = isRecord(value.cost) ? value.cost : null;\n if (!workflow2 || !request || !requested || !string2(request.goal) || !count(request.duration_seconds) || !progress || measure(progress.percent) === null || !credits2(value.estimated_maximum_microcredits) || !cost || !credits2(cost.total_microcredits)) return null;\n const parameters = isRecord(value.parameters) ? value.parameters : null;\n const generation = parameters && isRecord(parameters.generation) ? parameters.generation : null;\n const requestedParameters = parameterValues2(request.parameters);\n const requestedProperties = readVideoProperties(request.properties);\n const effectiveProperties = readEffectiveVideoProperties(value.properties);\n const effectiveWorkflow = parameters ? parameterMap2(parameters.workflow) : void 0;\n const effectiveModules = parameters && isRecord(parameters.modules) ? Object.fromEntries(Object.entries(parameters.modules).flatMap(([instanceId, item]) => {\n if (!isRecord(item) || !string2(item.module_id)) return [];\n const values = parameterMap2(item.values);\n return values === void 0 ? [] : [[instanceId, { module_id: item.module_id, values }]];\n })) : void 0;\n const origin = isRecord(value.origin) && value.origin.type === "nocha_experience" && ["experience_id", "experience_code", "experience_title", "revision_id"].every((key) => string2(value.origin[key])) ? value.origin : null;\n const access2 = isRecord(value.automation_access) ? value.automation_access : null;\n const automationValue = automation(value.automation);\n const resumeValue = resume(value.resume);\n const editPlan = readVideoEditPlan(value.edit_plan);\n const generationValue = {\n audience_view: "author",\n id: value.id,\n status: pick2(value.status, ["queued", "running", "cancelling", "succeeded", "failed", "cancelled"]),\n kind: pick2(value.kind, kinds),\n workflow: workflow2,\n request: {\n workflow: { id: requested.id, ...requested.revision === null ? {} : { revision: requested.revision } },\n goal: request.goal,\n duration_seconds: request.duration_seconds,\n aspect_ratio: pick2(request.aspect_ratio, ratios),\n locale: pick2(request.locale, locales2),\n speech: pick2(request.speech, speech),\n ...request.output_resolution === void 0 ? {} : { output_resolution: pick2(request.output_resolution, resolutions2) },\n ...request.parameters === void 0 ? {} : { parameters: requestedParameters ?? {} },\n ...requestedProperties === void 0 ? {} : { properties: requestedProperties },\n ...request.reference_preparation === "auto" ? { reference_preparation: "auto" } : {},\n ...string2(request.source_analysis_id) && request.source_analysis_id ? { source_analysis_id: request.source_analysis_id } : {},\n ...request.effort === void 0 ? {} : { effort: pick2(request.effort, efforts2) },\n collection_id: text4(request.collection_id),\n confirmed_maximum_microcredits: credits2(request.confirmed_maximum_microcredits) ? request.confirmed_maximum_microcredits : null\n },\n parameters: parameters && count(parameters.duration_seconds) ? {\n duration_seconds: parameters.duration_seconds,\n aspect_ratio: pick2(parameters.aspect_ratio, ratios),\n locale: pick2(parameters.locale, locales2),\n speech: pick2(parameters.speech, speech),\n output_resolution: pick2(parameters.output_resolution, resolutions2),\n reference_count: count(parameters.reference_count) ? parameters.reference_count : 0,\n ...parameters.reference_preparation === "auto" ? { reference_preparation: "auto" } : {},\n ...generation ? { generation: {\n intensity: pick2(generation.intensity, ["low", "medium", "high"]),\n ...count(generation.preference_revision) ? { preference_revision: generation.preference_revision } : {},\n ...string2(generation.policy_signature) ? { policy_signature: generation.policy_signature } : {}\n } } : {},\n ...effectiveWorkflow === void 0 ? {} : { workflow: effectiveWorkflow },\n ...effectiveModules === void 0 ? {} : { modules: effectiveModules }\n } : null,\n ...effectiveProperties === void 0 ? {} : { properties: effectiveProperties },\n references: records2(value.references).filter((item) => string2(item.asset_id)).map((item) => {\n const replaces2 = readVideoReferenceReplaces(item.replaces);\n return {\n asset_id: item.asset_id,\n ...optionalText(item, "role"),\n ...optionalText(item, "name"),\n ...optionalText(item, "description"),\n ...replaces2 ? { replaces: replaces2 } : {},\n availability: pick2(item.availability, ["available", "expired", "pending"])\n };\n }),\n origin: origin ? {\n type: "nocha_experience",\n experience_id: origin.experience_id,\n experience_code: origin.experience_code,\n experience_title: origin.experience_title,\n revision_id: origin.revision_id\n } : null,\n progress: {\n percent: Math.min(100, progress.percent),\n stage: pick2(progress.stage, stages),\n ...progress.step === null || string2(progress.step) ? { step: progress.step } : {}\n },\n ...automationValue ? { automation: automationValue } : {},\n automation_access: access2 && typeof access2.read_only === "boolean" ? { read_only: access2.read_only, taken_over_at: text4(access2.taken_over_at), media_expired_at: text4(access2.media_expired_at) } : null,\n collection_id: text4(value.collection_id),\n estimated_maximum_microcredits: value.estimated_maximum_microcredits,\n cost: {\n total_microcredits: cost.total_microcredits,\n ...credits2(cost.base_charge_microcredits) ? { base_charge_microcredits: cost.base_charge_microcredits } : {},\n ...credits2(cost.creator_fee_microcredits) ? { creator_fee_microcredits: cost.creator_fee_microcredits } : {}\n },\n actual_duration_seconds: measure(value.actual_duration_seconds),\n error: failure2(value.error),\n ...resumeValue === void 0 ? {} : { resume: resumeValue },\n result: output,\n ...editPlan === void 0 ? {} : { edit_plan: editPlan },\n created_at: value.created_at,\n updated_at: value.updated_at\n };\n return generationValue;\n}\nfunction readVideoEstimate(value) {\n if (!isRecord(value) || !string2(value.maximum_microcredits) || !/^[1-9]\\d*$/.test(value.maximum_microcredits) || !string2(value.valid_until)) return null;\n const workflow2 = workflowRef(value.workflow);\n return workflow2 ? { maximum_microcredits: value.maximum_microcredits, valid_until: value.valid_until, workflow: workflow2 } : null;\n}\nfunction step(value) {\n if (!string2(value.id)) return null;\n const module = isRecord(value.module) && string2(value.module.id) && string2(value.module.title) && count(value.module.revision) ? { id: value.module.id, title: value.module.title, revision: value.module.revision } : void 0;\n return {\n id: value.id,\n operation: text4(value.operation),\n lane: text4(value.lane),\n execution: pick2(value.execution, ["segment", "historical"]),\n ...module ? { module } : {},\n ...typeof value.restartable === "boolean" ? { restartable: value.restartable } : {},\n ...Array.isArray(value.properties) ? { properties: value.properties.flatMap((item) => {\n const definition = readVideoPropertyDefinition(item);\n return definition ? [definition] : [];\n }) } : {},\n modules: records2(value.modules).filter((item) => string2(item.id) && string2(item.instance_id) && string2(item.title) && count(item.revision)).map((item) => ({ id: item.id, instance_id: item.instance_id, title: item.title, revision: item.revision }))\n };\n}\nfunction referenceRole(value) {\n const media = pick2(value.media, ["image", "video", "audio"]);\n if (!string2(value.role) || !value.role || !media || !count(value.min) || !count(value.max) || value.max < 1) return null;\n return { role: value.role, media, min: value.min, max: value.max, gap_seconds: measure(value.gap_seconds), crossfade_seconds: measure(value.crossfade_seconds) };\n}\nfunction readVideoWorkflow(value) {\n if (!isRecord(value) || !string2(value.id) || !value.id || !string2(value.name) || !isRecord(value.duration_seconds) || !isRecord(value.references)) return null;\n const durations = value.duration_seconds, references = value.references, availability = isRecord(value.availability) ? value.availability : {};\n if (!count(durations.min) || !count(durations.max) || !count(references.min) || !count(references.max)) return null;\n return {\n id: value.id,\n origin: pick2(value.origin, ["builtin", "saved"]),\n revision: count(value.revision) ? value.revision : null,\n latest_revision: count(value.latest_revision) ? value.latest_revision : null,\n digest: text4(value.digest),\n base_id: text4(value.base_id),\n name: value.name,\n description: string2(value.description) ? value.description : "",\n kind: pick2(value.kind, kinds),\n family: pick2(value.family, families),\n variant: pick2(value.variant, ["native", "voix", "bande-son", "video-noire", "micro", "live"]),\n duration_seconds: { min: durations.min, max: durations.max, allowed: Array.isArray(durations.allowed) ? counts(durations.allowed) : null },\n default_for_durations_seconds: counts(value.default_for_durations_seconds),\n aspect_ratios: keep(value.aspect_ratios, ratios),\n output_resolutions: keep(value.output_resolutions, resolutions2),\n locales: keep(value.locales, locales2),\n speech_modes: records2(value.speech_modes).flatMap((item) => {\n const mode = pick2(item.mode, speech);\n return mode ? [{ mode, durations_seconds: Array.isArray(item.durations_seconds) ? counts(item.durations_seconds) : null }] : [];\n }),\n references: {\n min: references.min,\n max: references.max,\n mime_types: Array.isArray(references.mime_types) ? references.mime_types.filter(string2) : [],\n requires_non_character: references.requires_non_character === true,\n roles: records2(references.roles).map(referenceRole).filter((item) => item !== null)\n },\n reference_preparation: value.reference_preparation === true,\n restart_from: Array.isArray(value.restart_from) ? value.restart_from.filter(string2) : [],\n provider_needs: Array.isArray(value.provider_needs) ? value.provider_needs.filter(string2) : [],\n interaction: pick2(value.interaction, ["none", "recordings", "live"]),\n steps: records2(value.steps).map(step).filter((item) => item !== null),\n parameters: records2(value.parameters).map(parameterDefinition).filter((item) => item !== null),\n availability: availability.status === "available" ? { status: "available" } : {\n status: "unavailable",\n message: string2(availability.message) ? availability.message : "",\n reason: pick2(availability.reason, ["interactive", "providers", "modules", "render_target", "base", "unavailable"])\n }\n };\n}\n\n// src/video.ts\nvar connectionActions = /* @__PURE__ */ new Set(["status", "connect", "disconnect"]);\nvar active = /* @__PURE__ */ new Set(["queued", "running", "cancelling"]);\nvar invalidResult2 = (label) => new NochaError("invalid_result", `Nocha returned an invalid ${label}`);\nvar api = 2;\nfunction readable(value) {\n const generation = readVideoGeneration(value);\n if (!generation) throw invalidResult2("video generation");\n return generation;\n}\nfunction authored(value) {\n const generation = readable(value);\n if (generation.audience_view !== "author") throw invalidResult2("video generation");\n return generation;\n}\nasync function connection(context, input3 = {}, options) {\n const action = isRecord(input3) ? input3.action ?? "status" : void 0;\n if (!connectionActions.has(action)) throw invalid("action must be status, connect or disconnect");\n const value = await context.invoke(videoOperationDefinitions["connection"].capability, videoOperationDefinitions["connection"].operation, { action }, options);\n if (!isRecord(value) || !["connected", "disconnected", "authorization_required"].includes(String(value.status)) || value.status === "connected" && (!Array.isArray(value.scopes) || !value.scopes.every((scope) => typeof scope === "string") || typeof value.connected_at !== "string") || value.status === "authorization_required" && typeof value.authorization_url !== "string") throw invalidResult2("video connection");\n return value;\n}\nasync function workflows(context, input3, options) {\n const value = await context.invoke(videoOperationDefinitions["workflows"].capability, videoOperationDefinitions["workflows"].operation, videoWorkflowsWire(input3), options);\n if (!isRecord(value) || !Array.isArray(value.items)) throw invalidResult2("video workflow list");\n return { items: value.items.map(readVideoWorkflow).filter((item) => item !== null) };\n}\nasync function workflow(context, input3, options) {\n const value = readVideoWorkflow(await context.invoke(videoOperationDefinitions["workflow"].capability, videoOperationDefinitions["workflow"].operation, videoWorkflowRef(input3, "input"), options));\n if (!value) throw invalidResult2("video workflow");\n return value;\n}\nasync function estimate2(context, input3, options) {\n const value = readVideoEstimate(await context.invoke(videoOperationDefinitions["estimate"].capability, videoOperationDefinitions["estimate"].operation, videoRequestWire(input3), options));\n if (!value) throw invalidResult2("video estimate");\n return value;\n}\nfunction paidOptions(operation2, options) {\n if (!isRecord(options) || typeof options.idempotencyKey !== "string" || !options.idempotencyKey) {\n throw new NochaError("invalid_request", `video.${operation2} requires a persisted idempotencyKey`);\n }\n return options;\n}\nasync function create(context, input3, options) {\n const keyed = paidOptions("create", options);\n return authored(await context.invoke(videoOperationDefinitions["create"].capability, videoOperationDefinitions["create"].operation, videoCreateWire(input3), keyed));\n}\nasync function list(context, input3 = {}, options) {\n if (!isRecord(input3) || input3.limit !== void 0 && !Number.isInteger(input3.limit) || input3.cursor !== void 0 && typeof input3.cursor !== "string") {\n throw invalid("list takes an integer limit and a string cursor");\n }\n const workflow2 = input3.workflow === void 0 ? void 0 : videoWorkflowRef({ id: input3.workflow }, "list workflow").id;\n const value = await context.invoke(videoOperationDefinitions["list"].capability, videoOperationDefinitions["list"].operation, {\n api,\n ...input3.cursor ? { cursor: input3.cursor } : {},\n ...input3.limit === void 0 ? {} : { limit: input3.limit },\n ...workflow2 ? { workflow: workflow2 } : {}\n }, options);\n if (!isRecord(value) || !Array.isArray(value.items) || !isRecord(value.pagination) || typeof value.pagination.has_more !== "boolean" || !(value.pagination.next_cursor === null || typeof value.pagination.next_cursor === "string")) throw invalidResult2("video generation list");\n return { items: value.items.map(readable), pagination: { has_more: value.pagination.has_more, next_cursor: value.pagination.next_cursor } };\n}\nasync function get3(context, input3, options) {\n return readable(await context.invoke(videoOperationDefinitions["get"].capability, videoOperationDefinitions["get"].operation, { api, id: videoId(isRecord(input3) ? input3.id : void 0) }, options));\n}\nasync function retry(context, input3, options) {\n const keyed = paidOptions("retry", options);\n if (!isRecord(input3)) throw invalid("A retry request is required");\n if (input3.restartFrom !== void 0 && (typeof input3.restartFrom !== "string" || !input3.restartFrom.trim())) throw invalid("restartFrom must be a step of the workflow");\n return authored(await context.invoke(videoOperationDefinitions["retry"].capability, videoOperationDefinitions["retry"].operation, {\n api,\n id: videoId(input3.id),\n confirmed_maximum_microcredits: confirmedMaximum(input3.confirmedMaximumMicrocredits),\n ...input3.restartFrom ? { restart_from: input3.restartFrom.trim() } : {}\n }, keyed));\n}\nasync function mutate(context, operation2, input3, options) {\n return authored(await context.invoke(videoOperationDefinitions[operation2].capability, videoOperationDefinitions[operation2].operation, { api, id: videoId(isRecord(input3) ? input3.id : void 0) }, options));\n}\nfunction pause(ms2, signal) {\n if (signal?.aborted) return Promise.reject(new NochaError("aborted", "Video wait was aborted"));\n const page = typeof document === "undefined" ? void 0 : document;\n return new Promise((resolve, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n signal?.removeEventListener("abort", onAbort);\n page?.removeEventListener("visibilitychange", onVisibility);\n };\n const done = () => {\n cleanup();\n resolve();\n };\n const onAbort = () => {\n cleanup();\n reject2(new NochaError("aborted", "Video wait was aborted"));\n };\n const onVisibility = () => {\n if (!page?.hidden) done();\n };\n const timer = setTimeout(() => {\n if (!page?.hidden) done();\n }, ms2);\n signal?.addEventListener("abort", onAbort, { once: true });\n page?.addEventListener("visibilitychange", onVisibility);\n });\n}\nfunction nextInterval(startedAt, fixed) {\n if (fixed !== void 0) return fixed;\n const elapsed = Date.now() - startedAt;\n return elapsed < videoWaitSchedule.fastForMs ? videoWaitSchedule.fastMs : elapsed < videoWaitSchedule.steadyForMs ? videoWaitSchedule.steadyMs : videoWaitSchedule.slowMs;\n}\nasync function wait(context, input3, options = {}) {\n const id = videoId(isRecord(input3) ? input3.id : void 0);\n if (!isRecord(options)) throw invalid("Wait options must be an object");\n if (options.intervalMs !== void 0 && (typeof options.intervalMs !== "number" || !Number.isFinite(options.intervalMs))) throw invalid("intervalMs must be a number");\n const fixed = options.intervalMs === void 0 ? void 0 : Math.max(videoWaitSchedule.minimumIntervalMs, options.intervalMs);\n const startedAt = Date.now();\n let failures = 0;\n for (; ; ) {\n let current2;\n try {\n current2 = await get3(context, { id }, options.signal ? { signal: options.signal } : {});\n failures = 0;\n } catch (error) {\n if (!isNochaError(error) || !error.retryable || failures >= 3) throw error;\n failures += 1;\n if (options.onRetry) notifyListener((attempt) => options.onRetry(error, attempt), failures);\n await pause(nextInterval(startedAt, fixed), options.signal);\n continue;\n }\n if (options.onUpdate) notifyListener(options.onUpdate, current2);\n if (!active.has(current2.status)) return current2;\n await pause(nextInterval(startedAt, fixed), options.signal);\n }\n}\nfunction createVideo(context) {\n return Object.freeze({\n connection: (input3, options) => connection(context, input3, options),\n workflows: (input3, options) => workflows(context, input3, options),\n workflow: (input3, options) => workflow(context, input3, options),\n estimate: (input3, options) => estimate2(context, input3, options),\n create: (input3, options) => create(context, input3, options),\n list: (input3, options) => list(context, input3, options),\n get: (input3, options) => get3(context, input3, options),\n retry: (input3, options) => retry(context, input3, options),\n cancel: (input3, options) => mutate(context, "cancel", input3, options),\n remove: (input3, options) => mutate(context, "remove", input3, options),\n wait: (input3, options) => wait(context, input3, options),\n playback: (input3, options) => readVideoPlayback(context, input3, options),\n media: (input3, options) => readVideoMedia(context, input3, options),\n clipping: createClipping(context)\n });\n}\n\n// src/viewport-types.ts\nfunction isExperienceViewport(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const viewport = value;\n const positive = ["layoutWidth", "layoutHeight", "scale"];\n const nonnegative = ["visualWidth", "visualHeight", "offsetTop", "offsetLeft", "keyboardInset"];\n if (positive.some((key) => typeof viewport[key] !== "number" || !Number.isFinite(viewport[key]) || viewport[key] <= 0) || nonnegative.some((key) => typeof viewport[key] !== "number" || !Number.isFinite(viewport[key]) || viewport[key] < 0) || typeof viewport.keyboardVisible !== "boolean") return false;\n const v = value;\n return v.offsetLeft + v.visualWidth <= v.layoutWidth + 1 && v.offsetTop + v.visualHeight <= v.layoutHeight + 1 && v.keyboardInset <= v.layoutHeight && (v.keyboardVisible || v.keyboardInset === 0);\n}\n\n// src/viewport.ts\nvar edges = ["top", "right", "bottom", "left"];\nvar cssFields = {\n layoutWidth: "--nocha-layout-width",\n layoutHeight: "--nocha-layout-height",\n visualWidth: "--nocha-viewport-width",\n visualHeight: "--nocha-viewport-height",\n offsetTop: "--nocha-viewport-offset-top",\n offsetLeft: "--nocha-viewport-offset-left",\n keyboardInset: "--nocha-keyboard-inset"\n};\nfunction editable(element) {\n return element instanceof HTMLElement && (element.isContentEditable || element instanceof HTMLTextAreaElement && !element.disabled && !element.readOnly || element instanceof HTMLInputElement && !element.disabled && !element.readOnly && !["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "hidden"].includes(element.type));\n}\nfunction revealFocus(viewport) {\n if (Math.abs(viewport.scale - 1) >= 0.05) return;\n const input3 = document.activeElement;\n if (!editable(input3)) return;\n const style = getComputedStyle(document.documentElement);\n const inset = (edge) => Math.max(0, Number.parseFloat(style.getPropertyValue(`--nocha-safe-area-inset-${edge}`)) || 0);\n const top = Math.max(viewport.offsetTop, inset("top")) + 12;\n const bottom = Math.min(viewport.offsetTop + viewport.visualHeight, viewport.layoutHeight - inset("bottom")) - 12;\n if (bottom <= top) return;\n for (let parent = input3.parentElement; parent; parent = parent.parentElement) {\n const parentStyle = getComputedStyle(parent);\n if (!/(auto|scroll)/.test(parentStyle.overflowY) || parent.scrollHeight <= parent.clientHeight) continue;\n const box = parent.getBoundingClientRect();\n const visibleTop = Math.max(top, box.top + parent.clientTop);\n const visibleBottom = Math.min(bottom, box.top + parent.clientTop + parent.clientHeight);\n if (visibleBottom <= visibleTop) continue;\n const field3 = input3.getBoundingClientRect();\n const delta = field3.height > visibleBottom - visibleTop ? field3.top - visibleTop : field3.bottom > visibleBottom ? field3.bottom - visibleBottom : field3.top < visibleTop ? field3.top - visibleTop : 0;\n if (delta) parent.scrollTop += delta;\n }\n const scrolling = document.scrollingElement;\n if (scrolling && scrolling.scrollHeight > scrolling.clientHeight && ![document.documentElement, document.body].some((element) => element && /(hidden|clip)/.test(getComputedStyle(element).overflowY))) {\n const field3 = input3.getBoundingClientRect();\n const delta = field3.height > bottom - top ? field3.top - top : field3.bottom > bottom ? field3.bottom - bottom : field3.top < top ? field3.top - top : 0;\n if (delta) scrolling.scrollTop += delta;\n }\n}\nfunction createViewport() {\n let snapshot3 = null;\n const listeners = /* @__PURE__ */ new Set();\n if (typeof window !== "undefined" && typeof document !== "undefined") {\n let host = null;\n let frame = 0;\n let focusTimer = 0;\n let baselineHeight = document.documentElement.clientHeight || window.innerHeight;\n let baselineWidth = document.documentElement.clientWidth || window.innerWidth;\n let stop;\n let orientationChanged = false;\n const update = () => {\n frame = 0;\n const layoutWidth = Math.max(1, document.documentElement.clientWidth || window.innerWidth);\n const layoutHeight = Math.max(1, document.documentElement.clientHeight || window.innerHeight);\n const visual = window.visualViewport;\n const scale = visual?.scale || 1;\n if (orientationChanged || !editable(document.activeElement) || Math.abs(layoutWidth - baselineWidth) > 80) {\n orientationChanged = false;\n baselineHeight = layoutHeight;\n baselineWidth = layoutWidth;\n }\n const offsetTop = Math.max(0, Math.min(layoutHeight - 1, visual?.offsetTop || 0));\n const offsetLeft = Math.max(0, Math.min(layoutWidth - 1, visual?.offsetLeft || 0));\n const visualHeight = Math.max(1, Math.min(layoutHeight - offsetTop, visual?.height || layoutHeight));\n const visualWidth = Math.max(1, Math.min(layoutWidth - offsetLeft, visual?.width || layoutWidth));\n const keyboardVisible = editable(document.activeElement) && Math.abs(scale - 1) < 0.05 && baselineHeight - visualHeight > 100;\n const local = {\n layoutWidth,\n layoutHeight,\n visualWidth,\n visualHeight,\n offsetTop,\n offsetLeft,\n keyboardVisible,\n keyboardInset: keyboardVisible ? Math.max(0, layoutHeight - offsetTop - visualHeight) : 0,\n scale\n };\n const next = host ?? local;\n if (!snapshot3 || Object.keys(next).some((key) => next[key] !== snapshot3?.[key])) {\n snapshot3 = Object.freeze({ ...next });\n const cssViewport = Math.abs(next.scale - 1) < 0.05 ? next : {\n ...next,\n visualWidth: next.layoutWidth,\n visualHeight: next.layoutHeight,\n offsetTop: 0,\n offsetLeft: 0,\n keyboardInset: 0\n };\n for (const [key, property] of Object.entries(cssFields)) document.documentElement.style.setProperty(property, `${cssViewport[key]}px`);\n document.documentElement.toggleAttribute("data-nocha-keyboard-visible", next.keyboardVisible);\n for (const listener of listeners) notifyListener(listener, snapshot3);\n }\n revealFocus(next);\n };\n const schedule = () => {\n if (!frame) frame = window.requestAnimationFrame(update);\n };\n const start = () => {\n if (stop) return;\n const controller = new AbortController();\n const { signal } = controller;\n const unsubscribe = subscribeBridgeEvents((event) => {\n if (event.type === "experience.viewport" && isExperienceViewport(event.payload)) {\n host = Object.freeze({ ...event.payload });\n schedule();\n }\n if (event.type === "experience.safe-area" && event.payload && typeof event.payload === "object" && !Array.isArray(event.payload)) {\n const insets = event.payload;\n if (!edges.every((edge) => typeof insets[edge] === "number" && Number.isFinite(insets[edge]) && insets[edge] >= 0)) return;\n for (const edge of edges) document.documentElement.style.setProperty(`--nocha-safe-area-inset-${edge}`, `${insets[edge]}px`);\n schedule();\n }\n });\n window.addEventListener("resize", schedule, { signal });\n window.addEventListener("orientationchange", () => {\n orientationChanged = true;\n schedule();\n }, { signal });\n window.visualViewport?.addEventListener("resize", schedule, { signal });\n window.visualViewport?.addEventListener("scroll", schedule, { signal });\n document.addEventListener("focusin", () => {\n schedule();\n window.clearTimeout(focusTimer);\n focusTimer = window.setTimeout(schedule, 350);\n }, { signal });\n document.addEventListener("focusout", schedule, { signal });\n stop = () => {\n controller.abort();\n unsubscribe();\n window.cancelAnimationFrame(frame);\n window.clearTimeout(focusTimer);\n frame = 0;\n host = null;\n stop = void 0;\n };\n update();\n };\n window.addEventListener("pagehide", () => stop?.());\n window.addEventListener("pageshow", start);\n start();\n }\n return Object.freeze({\n get: () => snapshot3,\n subscribe(listener) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A viewport listener is required");\n listeners.add(listener);\n if (snapshot3) notifyListener(listener, snapshot3);\n return () => {\n listeners.delete(listener);\n };\n }\n });\n}\n\n// src/voice.ts\nfunction validState(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const v = value;\n return (v.callId === null || typeof v.callId === "string") && ["idle", "connecting", "connected", "reconnecting", "closing", "closed", "failed"].includes(String(v.connection)) && ["off", "on"].includes(String(v.microphone)) && ["idle", "playing"].includes(String(v.playback)) && ["idle", "running", "awaiting_confirmation"].includes(String(v.reasoning)) && ["pending", "settled", "incomplete"].includes(String(v.settlement));\n}\nfunction createVoice(context) {\n const invoke = async (operation2, input3, options) => {\n const result2 = await context.invoke(aiOperationDefinitions[operation2].capability, aiOperationDefinitions[operation2].operation, input3, options);\n if (!validState(result2)) throw new NochaError("invalid_result", "Nocha returned an invalid voice call state");\n return result2;\n };\n return Object.freeze({\n start: (input3, options) => invoke("voice.start", input3, options),\n stop: (input3, options) => invoke("voice.stop", input3, options),\n state: (input3 = {}, options) => invoke("voice.state", input3, options),\n onState: (listener) => {\n assertHostCapability("voice");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A voice state listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type === "voice.state" && validState(event.payload)) notifyListener(listener, event.payload);\n });\n }\n });\n}\n\n// src/workspace.ts\nfunction parseWorkspace(value) {\n if (!isRecord(value) || !isNonEmptyString(value.id) || !isNonEmptyString(value.revisionId)) return null;\n const { kind, environment, participantId, permissions } = value;\n if (kind !== "public" && kind !== "personal" && kind !== "team" || environment !== "play" && environment !== "development" || !(participantId === null || typeof participantId === "string") || !isRecord(permissions) || !isBoolean(permissions.read) || !isBoolean(permissions.contribute) || !isBoolean(permissions.manage)) return null;\n return {\n id: value.id,\n kind,\n environment,\n revisionId: value.revisionId,\n participantId,\n permissions: { read: permissions.read, contribute: permissions.contribute, manage: permissions.manage }\n };\n}\nvar workspace = Object.freeze({\n get: async () => {\n const parsed = parseWorkspace(await invokeBridge("workspace", "get"));\n if (!parsed) throw new NochaError("invalid_result", "Nocha returned an invalid workspace presentation");\n return parsed;\n },\n onChange: (listener) => {\n assertHostCapability("workspace");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A workspace listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== "workspace.changed") return;\n const parsed = parseWorkspace(event.payload);\n if (parsed) notifyListener(listener, parsed);\n else warnOnce("workspace.changed", "the host sent a workspace presentation this SDK does not understand");\n });\n }\n});\n\n// src/index.ts\nfunction createFacades(context, shared) {\n const multiplayer = createMultiplayer(context, shared.hub);\n return {\n automations: createAutomations(context),\n connectors: createConnectors(context),\n backend: createBackend(context),\n ai: createAi(context),\n assets: createAssets(context),\n video: createVideo(context),\n state: createState(context, createStateWatch(context.invoke, subscribeBridgeEvents, multiplayer.onConnection)),\n memory: createMemory(context),\n database: createDatabase(context),\n network: createNetwork(context),\n notifications: createNotifications(context),\n inbox: createInbox(context),\n email: createEmail(context),\n multiplayer,\n outirl: createOutirl(context),\n device: createDevice(context, shared.motion),\n drive: createDrive(context),\n voice: createVoice(context)\n };\n}\nfunction createSdk(context, shared) {\n return Object.freeze({\n ...createFacades(context, shared),\n get mode() {\n return getNochaMode();\n },\n capabilities,\n use(usageId) {\n const cached = shared.bound.get(usageId);\n if (cached) return cached;\n const bound = createSdk(createContext(usageId), shared);\n shared.bound.set(usageId, bound);\n return bound;\n },\n assistant,\n access,\n workspace,\n navigation,\n context: experienceContext,\n viewport: shared.viewport,\n onEvent: shared.hub.onEvent\n });\n}\nvar nocha = createSdk(createContext(), {\n hub: createLiveHub(),\n motion: /* @__PURE__ */ new Set(),\n viewport: createViewport(),\n bound: /* @__PURE__ */ new Map()\n});\nvar index_default = nocha;\nexport {\n NochaError,\n classifyError,\n index_default as default,\n isNochaError,\n isNochaErrorCode,\n nocha,\n videoLocales\n};\n';
5
+ var nochaBrowserSdkSource = 'var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/error-codes.ts\nvar D = "denied";\nvar B = "billing";\nvar T = "transient";\nvar A = "aborted";\nvar I = "invalid";\nvar U = "unknown";\nvar nochaErrorClasses = {\n // SDK\n bridge_unavailable: D,\n usage_required: I,\n invalid_request: I,\n invalid_result: U,\n invocation_timed_out: T,\n aborted: A,\n invocation_failed: U,\n unknown_error: U,\n navigation_unavailable: D,\n navigation_timed_out: T,\n user_action_required: D,\n upload_failed: U,\n upload_interrupted: T,\n source_too_large: I,\n transfer_unavailable: D,\n not_external: D,\n // Host uploads (`assets.upload`, attachments, `drive.save`): an expired or spent upload authorization, two uploads\n // already running for the account, an upload address the host does not send to; `payload_too_large` (HTTP 413): a\n // request or file beyond its route\'s bound, like the other `*_too_large`.\n upload_unavailable: T,\n upload_busy: T,\n invalid_upload: U,\n payload_too_large: I,\n // Web and native hosts\n client_update_required: D,\n capability_denied: D,\n request_cancelled: A,\n experience_inactive: T,\n public_control_consent_required: D,\n request_failed: U,\n invalid_response: U,\n multiplayer_unavailable: T,\n rate_limited: T,\n multiplayer_receipt_missing: T,\n multiplayer_receipt_unsupported: D,\n multiplayer_receipt_backlog: I,\n multiplayer_receipt_invalid: U,\n voice_host_unavailable: D,\n native_host_required: D,\n device_inactive: A,\n device_permission_denied: D,\n device_unavailable: D,\n device_busy: T,\n device_timeout: T,\n device_limit: I,\n device_limit_exceeded: I,\n device_media_size: I,\n device_operation_unknown: I,\n device_invalid_request: I,\n // Nocha API behind the reader\n unauthorized: D,\n identity_required: D,\n service_unavailable: T,\n internal_error: T,\n not_found: I,\n not_ready: D,\n playback_unavailable: D,\n experience_unpublished: T,\n playback_changed: D,\n playback_temporarily_unavailable: T,\n runtime_unavailable: T,\n authentication_required: D,\n public_read_denied: D,\n review_unavailable: D,\n workspace_access_denied: D,\n workspace_revoked: D,\n workspace_context_required: D,\n workspace_selection_invalid: I,\n // Spaces of an experience that declares them (`nocha.spaces`): `space_denied` this person may not enter it,\n // `space_not_declared` no data usage declares this kind, `team_required` no team chosen, `space_mismatch` an\n // operation sent to a space its usage does not declare, `space_not_attached` its space is not attached yet (ask\n // `nocha.spaces.<kind>()` first), `embedded_spaces` a creator setting the manifest now decides, `team_not_member` an\n // `asTeam` the person may not act for (not a current member of that team, or a reference `actAsTeam` never returned).\n space_denied: D,\n space_not_declared: I,\n team_required: I,\n space_mismatch: D,\n space_not_attached: I,\n embedded_spaces: I,\n team_not_member: D,\n data_contract_incompatible: D,\n public_control_denied: D,\n review_external_integration_unavailable: D,\n revision_schema_unsupported: D,\n usage_unknown: I,\n usage_operation_denied: I,\n usage_resource_denied: I,\n usage_scope_denied: I,\n usage_cap_exceeded: B,\n usage_public_read_denied: D,\n usage_public_control_denied: D,\n // Speech shared across the experience (`share: \'experience\'`): the media usage does not declare `share`, a shared\n // line names no explicit `model` and `voice`, the listener it waited on did not finish (call again with the same\n // request and key, possibly leading it with one\'s own consent), or the line left the cache since it was served.\n usage_share_denied: I,\n shared_speech_selection_required: I,\n shared_speech_retry: T,\n shared_speech_expired: I,\n // Storage\n // `*_full`: the workspace budget is reached (free keys or records); `*_too_large`: one value exceeds its own limit.\n state_conflict: I,\n conflict: I,\n memory_conflict: I,\n database_conflict: I,\n idempotency_conflict: I,\n memory_full: I,\n database_full: I,\n memory_value_too_large: I,\n database_record_too_large: I,\n database_insert_limit: I,\n database_unavailable: T,\n // Experience search indexes (`search`): `*_full` an index or mark budget, `search_adults_only` a `people` index\n // for a signed-in account not declared 18+, `search_asset_denied` an asset the writer did not upload in this experience.\n search_index_unknown: I,\n search_record_too_large: I,\n search_index_full: I,\n search_owner_limit: I,\n search_conflict: I,\n search_filter_invalid: I,\n search_cursor_expired: I,\n search_profile_required: I,\n search_location_required: I,\n search_location_rate_limited: T,\n search_marks_full: I,\n search_adults_only: D,\n search_unavailable: T,\n search_asset_denied: I,\n // Backend pilot: an unknown outcome/deadline requires receipt reconciliation, never blind retry.\n backend_unavailable: T,\n backend_capacity_exceeded: T,\n backend_budget_exhausted: D,\n backend_route_unknown: I,\n backend_route_owner_only: D,\n backend_usage_denied: D,\n backend_resource_protected: D,\n backend_paid_capability_denied: D,\n backend_input_invalid: I,\n backend_output_invalid: U,\n backend_deadline_exceeded: U,\n backend_outcome_unknown: U,\n backend_revision_required: D,\n // The person\'s own Mac (`machine`): the `denied` codes wait for an action (pairing, consent, the Mac\'s settings or\n // confirmation, an update, the operator right), never for a retry; `machine_offline` and `machine_unavailable` pass by\n // themselves; `machine_host_unsupported` names a host or SDK without the machine streams. End-to-end terminals:\n // `machine_device_untrusted` (the Mac has not authorized this device, revoked it, or its handshake failed: the host\n // offers pairing) and `machine_protocol_outdated` (the Mac or the host must be updated; never a plain terminal).\n machine_not_paired: D,\n machine_consent_required: D,\n machine_consent_denied: D,\n machine_operator_required: D,\n machine_offline: T,\n machine_agent_incompatible: D,\n machine_terminal_disabled: D,\n machine_paused: D,\n machine_confirmation_required: D,\n machine_locked: D,\n machine_tmux_missing: D,\n machine_session_not_found: I,\n machine_session_ended: I,\n machine_limit: I,\n machine_host_unsupported: D,\n machine_invalid_request: I,\n machine_unavailable: T,\n machine_device_untrusted: D,\n machine_protocol_outdated: D,\n // \xAB \xC9tabli \xBB, the Mac\'s projects (`workspace.*`, `files.*`, `git.*`, `agents.*`), worded in `machineWorkspaceErrorMessages`.\n machine_workspace_disabled: D,\n machine_root_not_found: I,\n machine_path_denied: D,\n machine_path_not_found: I,\n machine_path_exists: I,\n machine_too_large: I,\n machine_git_unavailable: D,\n machine_git_not_repository: I,\n machine_git_failed: I,\n machine_agent_unavailable: D,\n machine_conversation_not_found: I,\n machine_interaction_not_found: I,\n // Personal connected accounts\n connector_not_granted: D,\n connector_scope_missing: D,\n connector_reauthorization_required: D,\n connector_unavailable: T,\n connectors_unavailable: T,\n connector_failed: I,\n connector_uncertain: U,\n connector_confirmation_required: D,\n quota_exceeded: T,\n // Managed network\n network_unavailable: T,\n network_declaration_required: I,\n network_revision_required: D,\n network_method_denied: I,\n network_path_invalid: I,\n network_body_invalid: I,\n network_asset_integrity: U,\n network_outcome_unknown: U,\n network_access_denied: D,\n network_rate_limited: T,\n network_destination_invalid: I,\n network_destination_private: I,\n network_redirect_denied: I,\n network_response_too_large: I,\n network_timeout: U,\n network_transport_failed: U,\n // Owner-keyed recipients: no key the owner confirmed for this declaration (or a working revision outside the owner\'s\n // session), no secret key on this host, the owner\'s hourly quota or this account\'s share of it, a keyed response\n // that is not plain text; `network_asset_busy`: too many remote files downloading at once.\n network_secret_missing: D,\n network_secrets_unavailable: D,\n network_secret_quota: T,\n network_secret_unsafe_response: U,\n network_asset_busy: T,\n // Notifications sent to a player\n notifications_unavailable: D,\n notifications_disabled: D,\n notifications_rate_limited: T,\n notifications_not_declared: I,\n // Triggers, automations and the experience inbox\n inbox_unavailable: D,\n inbox_full: I,\n inbox_event_not_found: I,\n trigger_not_found: I,\n trigger_disabled: D,\n trigger_limit_reached: I,\n trigger_managed_by_mail: I,\n trigger_slug_taken: I,\n workspace_unavailable: I,\n automation_schedule_invalid: I,\n automation_rate_limited: T,\n // The person\'s Drive, through the host dialog: `sign_in_required` asks a visitor to sign in first;\n // `drive_unavailable` names a host without the Drive (nocha dev, a standalone page); `drive_read_only` a save to a\n // read-only library, refused like `drive_forbidden`; `drive_mount_unavailable` a library that does not answer.\n drive_unavailable: D,\n sign_in_required: D,\n drive_forbidden: D,\n drive_read_only: D,\n drive_not_found: I,\n drive_name_conflict: I,\n drive_invalid_name: I,\n drive_unsupported_type: I,\n drive_upload_expired: T,\n drive_file_too_large: I,\n drive_mount_unavailable: T,\n // Experience mail\n mail_unavailable: D,\n mail_disabled: D,\n mail_recipient_not_allowed: I,\n mail_reply_expired: I,\n mail_too_large: I,\n mail_rate_limited: T,\n mail_sender_not_allowed: D,\n mail_send_failed: U,\n mail_workspace_not_allowed: I,\n // Experience places: the capability is absent on this host (or this is not the published play); a refused point.\n places_unavailable: T,\n invalid_places: I,\n place_removed: I,\n place_limit: I,\n place_keyword_unknown: I,\n // Public profiles (`profiles`): the capability is absent on this host.\n profiles_unavailable: T,\n // Swipe excerpts: absent on this host (or not the published play); a player who is not the owner or an editor; a refused excerpt.\n excerpts_unavailable: D,\n excerpts_forbidden: D,\n invalid_excerpts: I,\n excerpt_removed: I,\n excerpt_limit: I,\n excerpt_keyword_unknown: I,\n // The person\'s library (`library`, served by the web host): `library_inactive` a frame the host did not mount as the\n // account\'s interface (an ordinary player, the app, offline, `nocha dev`: show a demo); `library_unavailable` a read\n // of the host that failed; `invalid_input` an input the host refuses; `activation_required` an `open` without a gesture.\n library_inactive: D,\n library_unavailable: T,\n invalid_input: I,\n activation_required: D,\n // Calls between experiences (`experiences`, relayed by the web host): `experience_call_unavailable` a host without the\n // relay or an experience that exposes nothing here (`available()` then answers false); `experience_call_denied` an\n // undeclared call or one the called experience does not admit; `experience_call_consent_refused` the person refused\n // (nothing is kept); `experience_call_quota` too many calls for now; `experience_call_failed` the called experience\n // failed, timed out or answered outside its schema; `experience_call_invalid` an input outside the declared schema.\n experience_call_unavailable: D,\n experience_call_denied: D,\n experience_call_consent_refused: D,\n experience_call_quota: T,\n experience_call_failed: T,\n experience_call_invalid: I,\n // A swipe experience (`nocha.host`, served by the host): `host_inactive` a frame the host did not mount as the swipe\n // experience (an ordinary player, `nocha dev`, an older host: show a demo); `hosting_restricted` a revision declaring\n // `hosts` that its owner may not publish yet (reserved to Nocha\'s main account until the operator opens it).\n host_inactive: D,\n hosting_restricted: D,\n // Workflow module calls (`nocha.module`, only inside a host\'s workflow run, never `nocha dev` nor `/playback/invoke`):\n // a host that delivers none, a call this host does not hold, a spend beyond what is left of the call\'s confirmed budget\n module_unavailable: D,\n module_call_unknown: I,\n module_budget_exhausted: B,\n // Automation allowance and overage billing\n automation_allowance_exhausted: B,\n automation_billing_blocked: B,\n // Declarative workflows (`automations`): activation, effectful tests and publication need the host\'s confirmation\n automations_unavailable: T,\n workflow_host_confirmation_required: D,\n workflow_published_revision_required: D,\n workflow_account_required: D,\n workflow_limit_reached: B,\n workflow_version_conflict: I,\n workflow_consent_expired: I,\n workflow_invalid: I,\n // Developer API keys\n api_key_not_allowed: D,\n api_key_scope_denied: D,\n api_key_experience_denied: D,\n api_key_expired: D,\n api_key_revoked: D,\n api_key_watchirl_unavailable: D,\n api_key_limit_reached: I,\n // Self-hosted experience server API: a browser caller, a token to ask the page again for (`revision_changed`: minted\n // for an older revision), a capability or usage the served revision does not allow, `frame.external` not granted\n browser_request_refused: D,\n player_token_invalid: D,\n revision_changed: D,\n capability_not_allowed: D,\n usage_not_declared: I,\n external_hosting_pending: D,\n rate_limit_unavailable: T,\n // AI and spending\n experience_authorization_required: B,\n experience_cap_exhausted: B,\n credit_exhausted: B,\n review_budget_exhausted: B,\n review_spending_not_authorized: B,\n generation_quote_expired: B,\n generation_quote_conflict: B,\n spend_settlement_conflict: B,\n spend_reconciliation_required: B,\n spend_authorization_pending: B,\n participant_daily_cap_reached: B,\n paid_consent_required: B,\n spend_journal_failed: U,\n spend_busy: T,\n intelligence_unavailable: T,\n generation_paused: T,\n pricing_unavailable: T,\n generation_estimate_unavailable: T,\n generation_options_unavailable: T,\n data_consent_unavailable: T,\n generation_failed: U,\n generation_budget_exceeded: I,\n operation_retired: I,\n generation_effort_conflict: I,\n generation_effort_unavailable: I,\n generation_policy_required: I,\n // Speech model and voice selection: refused before any operation or charge; `voice_preview_unavailable`: this voice\n // has no free sample here (auditioning it costs a synthesis); `voice_favorites_limit`: the participant\'s favourite\n // voices are full (`ai.voiceFavoritesUpdate`)\n model_unavailable: I,\n voice_unavailable: I,\n voice_preview_unavailable: I,\n generation_model_conflict: I,\n voice_favorites_limit: I,\n // Voice calls, refused by the host: an unknown or ended call, a previous call\'s settlement still open, another call\n // starting, an invalid start, consent or microphone refused, a call superseded by a newer start or a closing\n // document, an invalid answer from the call service, a session that must be started again.\n voice_call_not_found: I,\n voice_call_reconciliation_required: B,\n voice_call_busy: T,\n voice_call_input_invalid: I,\n voice_call_consent_required: D,\n voice_call_microphone_denied: D,\n voice_call_obsolete: A,\n voice_call_result_invalid: U,\n voice_call_restart_required: I,\n generation_usage_unknown: I,\n generation_not_found: I,\n generation_request_conflict: I,\n spend_request_conflict: I,\n media_idempotency_conflict: I,\n realtime_in_progress: I,\n experience_revision_changed: D,\n // Media\n media_unavailable: T,\n media_usage_required: I,\n media_usage_denied: D,\n media_access_denied: D,\n media_retention_denied: D,\n media_reference_denied: D,\n media_not_found: I,\n media_recovery_required: D,\n media_too_large: I,\n media_reference_too_large: I,\n media_unsupported: I,\n media_reference_unsupported: I,\n media_invalid_resource: U,\n media_resource_conflict: I,\n erasure_changed: I,\n media_unsupported_host: D,\n playback_unsupported_host: D,\n // A media a record or a film still cites, which removing it would break; the experience\'s media storage is full.\n media_cited: I,\n media_storage_full: I,\n // Live camera and microphone (`device.media`): outside the experience\'s own address, a visitor to sign in, a refused\n // permission, a device in use (or a hidden page), no device at all. `describeLiveMediaFailure` words each one.\n media_requires_experience_host: D,\n media_sign_in_required: D,\n media_permission_denied: D,\n media_device_busy: T,\n media_device_missing: D,\n video_recovery_unavailable: T,\n video_request_refused: D,\n video_recovery_required: D,\n // Video\n video_unavailable: T,\n video_connection_required: D,\n video_media_unauthorized: D,\n video_media_unavailable: T,\n video_invalid_response: U,\n video_generation_not_found: I,\n video_not_ready: T,\n video_request_failed: T,\n video_data_unavailable: T,\n video_connection_unavailable: T,\n clipping_unavailable: T,\n clipping_not_found: I,\n invalid_media_usage: I,\n provider_unavailable: T,\n studio_references_unavailable: T,\n media_reference_copy_unavailable: T,\n creator_attribution_unavailable: T,\n transfers_unavailable: T,\n video_consent_required: B,\n video_project_payer_unsupported: D,\n workflow_unknown: I,\n workflow_unsupported: I,\n // The participant\'s own Tripirl projects (`video.projects.*`): refused to this experience, gone, changed since the\n // revision shown, still running a film, or a setting that cannot change; an action the project\'s state refuses now\n // (`actions.*.reason`: work running, nothing to resume, already finished, nothing to cancel).\n video_projects_not_allowed: D,\n project_not_found: I,\n revision_conflict: I,\n generation_not_terminal: I,\n setting_not_editable: I,\n video_project_running: I,\n video_project_nothing_to_resume: I,\n video_project_already_finished: I,\n video_project_not_running: I,\n // `video.projects.addReference`: an asset that is not the participant\'s own, a file Tripirl cannot read as a video.\n video_reference_asset_not_found: I,\n video_reference_refused: I,\n // Mac hardware\n hardware_unavailable: T,\n hardware_invalid_response: U,\n hardware_owner_required: D,\n hardware_connection_required: D,\n hardware_hue_connection_required: D,\n hardware_leds_connection_required: D,\n hardware_audio_connection_required: D,\n hardware_connection_changed: D,\n hardware_access_revoked: D,\n hardware_access_denied: D,\n hardware_device_denied: D,\n hardware_host_unavailable: D,\n hardware_agent_incompatible: D,\n hardware_hue_setup_required: D,\n hardware_audio_setup_required: D,\n hardware_audio_transcription_denied: D,\n hardware_audio_quota_exceeded: B,\n hardware_invalid_request: I,\n hardware_audio_capture_not_found: I,\n hardware_audio_device_not_found: I,\n hardware_audio_busy: I,\n hardware_rate_limited: T,\n hardware_host_offline: T,\n hardware_leds_unreachable: T,\n hardware_hue_network: T,\n hardware_hue_unavailable: T,\n hardware_device_service_unavailable: T,\n hardware_audio_unreachable: T,\n hardware_audio_unavailable: T,\n hardware_audio_transcription_unavailable: T,\n hardware_audio_source_missing: D,\n hardware_audio_format_unsupported: D,\n hardware_desktop_connection_required: D,\n DESKTOP_DISABLED: D,\n DESKTOP_UNSUPPORTED_PLATFORM: D,\n DESKTOP_AUTOMATION_DENIED: D,\n DESKTOP_TERMINAL_UNAVAILABLE: T,\n DESKTOP_AGENT_UNKNOWN: I,\n DESKTOP_DICTATION_UNAVAILABLE: T,\n DESKTOP_COMMAND_FAILED: U,\n // Local development (nocha dev)\n development_unavailable: T,\n development_expired: T,\n request_timeout: T,\n topic_limit: I\n};\nfunction isNochaErrorCode(value) {\n return typeof value === "string" && Object.hasOwn(nochaErrorClasses, value);\n}\nvar hostUnavailableErrorCodes = [\n "bridge_unavailable",\n "native_host_required",\n "client_update_required",\n "navigation_unavailable",\n "voice_host_unavailable",\n "media_unsupported_host",\n "notifications_unavailable",\n "drive_unavailable",\n "media_requires_experience_host",\n "library_inactive",\n "experience_call_unavailable",\n "host_inactive"\n];\nvar unknownOutcomeErrorCodes = [\n "invocation_timed_out",\n "network_outcome_unknown",\n "network_timeout",\n "spend_journal_failed"\n];\nvar machineErrorCodes = [\n "machine_not_paired",\n "machine_consent_required",\n "machine_consent_denied",\n "machine_operator_required",\n "machine_offline",\n "machine_agent_incompatible",\n "machine_terminal_disabled",\n "machine_paused",\n "machine_confirmation_required",\n "machine_locked",\n "machine_tmux_missing",\n "machine_session_not_found",\n "machine_session_ended",\n "machine_limit",\n "machine_host_unsupported",\n "machine_invalid_request",\n "machine_unavailable",\n "machine_workspace_disabled",\n "machine_root_not_found",\n "machine_path_denied",\n "machine_path_not_found",\n "machine_path_exists",\n "machine_too_large",\n "machine_git_unavailable",\n "machine_git_not_repository",\n "machine_git_failed",\n "machine_agent_unavailable",\n "machine_conversation_not_found",\n "machine_interaction_not_found",\n "machine_device_untrusted",\n "machine_protocol_outdated"\n];\nvar machineStreamIdentityCodes = ["unauthorized", "identity_required", "sign_in_required"];\nvar experienceBackendErrorCodes = [\n "invalid_request",\n "identity_required",\n "workspace_access_denied",\n "usage_unknown",\n "usage_operation_denied",\n "usage_resource_denied",\n "idempotency_conflict",\n "database_conflict",\n "backend_unavailable",\n "backend_capacity_exceeded",\n "backend_budget_exhausted",\n "backend_route_unknown",\n "backend_route_owner_only",\n "backend_usage_denied",\n "backend_resource_protected",\n "backend_paid_capability_denied",\n "backend_input_invalid",\n "backend_output_invalid",\n "backend_deadline_exceeded",\n "backend_outcome_unknown",\n "backend_revision_required",\n "search_index_unknown",\n "search_record_too_large",\n "search_index_full",\n "search_owner_limit",\n "search_conflict",\n "search_filter_invalid",\n "search_cursor_expired",\n "search_profile_required",\n "search_location_required",\n "search_adults_only",\n "search_unavailable",\n "search_asset_denied"\n];\n\n// src/errors.ts\nvar genericCodes = /* @__PURE__ */ new Set(["invocation_failed", "request_failed", "unknown_error"]);\nvar hostRetryable = /* @__PURE__ */ new WeakMap();\nvar NochaError = class extends Error {\n code;\n wireCode;\n trace_id;\n correlation_id;\n operation_id;\n idempotency_key;\n details;\n constructor(code, message2, metadata = {}) {\n super(message2);\n this.name = "NochaError";\n const known = isNochaErrorCode(code);\n this.code = known ? code : "unknown_error";\n const wireCode = metadata.wireCode ?? (known ? void 0 : String(code));\n if (wireCode !== void 0 && wireCode !== this.code) this.wireCode = wireCode;\n if (metadata.trace_id !== void 0) this.trace_id = metadata.trace_id;\n if (metadata.correlation_id !== void 0) this.correlation_id = metadata.correlation_id;\n if (metadata.operation_id !== void 0) this.operation_id = metadata.operation_id;\n if (metadata.idempotency_key !== void 0) this.idempotency_key = metadata.idempotency_key;\n if (metadata.details !== void 0) this.details = Object.freeze({ ...metadata.details });\n hostRetryable.set(this, metadata.retryable === true);\n }\n /** True when retrying later, with the same idempotency key, can succeed. */\n get retryable() {\n return classifyError(this) === "transient";\n }\n};\nfunction isNochaError(value) {\n return value instanceof NochaError || value instanceof Error && value.name === "NochaError" && typeof value.code === "string";\n}\nfunction classifyError(error) {\n if (!isNochaError(error)) {\n return error !== null && typeof error === "object" && error.name === "AbortError" ? "aborted" : "unknown";\n }\n const code = isNochaErrorCode(error.code) ? error.code : "unknown_error";\n if (genericCodes.has(code)) return hostRetryable.get(error) === true ? "transient" : "unknown";\n return nochaErrorClasses[code];\n}\nfunction wireError(value, fallback = { code: "invocation_failed", message: "Nocha invocation failed" }) {\n const error = value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};\n const raw = typeof error.code === "string" && error.code ? error.code : fallback.code;\n const known = isNochaErrorCode(raw);\n return new NochaError(known ? raw : "unknown_error", typeof error.message === "string" ? error.message : fallback.message, {\n retryable: error.retryable === true,\n ...known ? {} : { wireCode: raw },\n ...typeof error.trace_id === "string" ? { trace_id: error.trace_id } : {},\n ...typeof error.correlation_id === "string" ? { correlation_id: error.correlation_id } : {},\n ...error.details !== null && typeof error.details === "object" && !Array.isArray(error.details) ? { details: error.details } : {}\n });\n}\n\n// src/guards.ts\nvar isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);\nvar isString = (value) => typeof value === "string";\nvar isNonEmptyString = (value) => typeof value === "string" && value.length > 0;\nvar isBoolean = (value) => typeof value === "boolean";\nvar isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);\nvar isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\nvar isNullable = (value, check2) => value === null || check2(value);\nvar isUuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);\nvar isBase64 = (value) => typeof value === "string" && /^[A-Za-z0-9+/]*={0,2}$/.test(value);\nvar CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;\nvar isArrayOf = (value, check2) => Array.isArray(value) && value.every(check2);\nvar maxJsonDepth = 64;\nfunction isIdempotencyKey(value) {\n return typeof value === "string" && value.length >= 8 && value.length <= 200 && ![...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);\n}\nfunction isPlainObject(value) {\n if (value === null || typeof value !== "object" || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nfunction jsonProblem(value, depth, ancestors, files = false) {\n if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") return void 0;\n if (typeof value === "number") return Number.isFinite(value) ? void 0 : "numbers must be finite";\n if (typeof value !== "object") return `${typeof value} values are not JSON`;\n if (files && typeof File !== "undefined" && value instanceof File) return void 0;\n if (depth > maxJsonDepth) return "values are nested too deeply";\n if (ancestors.has(value)) return "values contain a cycle";\n const items = Array.isArray(value) ? value : isPlainObject(value) ? Object.values(value) : void 0;\n if (!items) return "only plain objects and arrays are JSON";\n ancestors.add(value);\n try {\n for (const item of items) {\n const problem = jsonProblem(item, depth + 1, ancestors, files);\n if (problem) return problem;\n }\n return void 0;\n } finally {\n ancestors.delete(value);\n }\n}\n\n// src/automations.ts\nfunction createAutomations(context) {\n const invoke2 = async (operation2, input4, list5, options) => {\n const value = await context.invoke("automations", operation2, input4, options);\n if (list5 ? !Array.isArray(value) : !isRecord(value)) throw new NochaError("invalid_result", "Nocha returned an invalid workflow result");\n return value;\n };\n return {\n catalog: (options) => invoke2("catalog", {}, false, options),\n list: (options) => invoke2("list", {}, true, options),\n get: (id, options) => invoke2("get", { id }, false, options),\n create: (input4, options) => invoke2("create", input4, false, options),\n save: (id, input4, options) => invoke2("save", { id, ...input4 }, false, options),\n validate: (graph, options) => invoke2("validate", { graph }, true, options),\n remove: (id, options) => invoke2("remove", { id }, false, options),\n activate: (id, options) => invoke2("activate", { id }, false, options),\n pause: (id, options) => invoke2("pause", { id }, false, options),\n test: (id, input4, options) => invoke2("test", { id, ...input4 }, false, options),\n runs: (id, input4 = {}, options) => invoke2("runs", { id, ...input4 }, true, options),\n run: (runId, options) => invoke2("run", { id: runId }, false, options),\n templates: {\n list: (options) => invoke2("templates.list", {}, true, options),\n publish: (id, input4, options) => invoke2("templates.publish", { id, ...input4 }, false, options),\n use: (templateId, input4, options) => invoke2("templates.use", { id: templateId, ...input4 }, false, options)\n }\n };\n}\n\n// src/listeners.ts\nfunction notifyListener(listener, value) {\n try {\n listener(value);\n } catch (error) {\n console.error("Nocha listener failed", error);\n }\n}\nvar warned = /* @__PURE__ */ new Set();\nfunction warnOnce(kind, message2) {\n if (warned.has(kind)) return;\n warned.add(kind);\n console.warn(`Nocha ignored ${kind}: ${message2}`);\n}\n\n// src/experience-context-types.ts\nvar experienceHostKinds = ["web", "mac", "ios", "android"];\nfunction isExperienceHostKind(value) {\n return typeof value === "string" && experienceHostKinds.includes(value);\n}\nfunction isExperienceContext(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const device = value.device;\n if (!device || typeof device !== "object" || Array.isArray(device)) return false;\n const { type, platform, sessionId } = device;\n return typeof type === "string" && ["phone", "tablet", "desktop", "unknown"].includes(type) && typeof platform === "string" && ["ios", "android", "web"].includes(platform) && typeof sessionId === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(sessionId);\n}\n\n// src/language-match.ts\nvar EXPERIENCE_LANGUAGE_PATTERN = /^[a-z]{2,3}(?:-[A-Z]{2})?$/;\nfunction isExperienceLanguage(value) {\n return typeof value === "string" && EXPERIENCE_LANGUAGE_PATTERN.test(value);\n}\nvar tag = (value) => value.trim().replaceAll("_", "-").toLowerCase();\nvar primary = (value) => value.split("-")[0];\nfunction matchExperienceLanguage(preferences, available) {\n const offered = available.filter((language2) => typeof language2 === "string").map((language2) => ({ language: language2, tag: tag(language2) }));\n for (const preference of preferences) {\n if (typeof preference !== "string" || !preference.trim()) continue;\n const wanted = tag(preference), base2 = primary(wanted);\n const match = offered.find((item) => item.tag === wanted) ?? offered.find((item) => item.tag === base2) ?? offered.find((item) => primary(item.tag) === base2);\n if (match) return match.language;\n }\n return null;\n}\n\n// src/types/assets-wire.ts\nvar assetMediaTypes = ["image/jpeg", "image/png", "image/webp", "audio/mpeg", "audio/wav", "audio/flac", "audio/ogg", "video/mp4", "video/quicktime"];\nvar ASSET_MEDIA_MAX_BYTES = 64 * 1024 * 1024;\nvar ASSET_VIDEO_MAX_BYTES = 1024 * 1024 * 1024;\nvar GENERATED_VIDEO_MEDIA_MAX_BYTES = 256 * 1024 * 1024;\nvar assetMediaMaxBytes = (type) => type === "video/mp4" || type === "video/quicktime" ? ASSET_VIDEO_MAX_BYTES : ASSET_MEDIA_MAX_BYTES;\n\n// src/operation-waiting.ts\nvar operationWaiting = {\n default: 15e3,\n access: { request: 3e5 },\n // `attach` may wait for the host\'s sign-in proposal or its team choice.\n spaces: { default: 15e3, attach: 3e5 },\n // `open` waits for the person in the host\'s screen (a panel may stay open a while).\n screens: { default: 15e3, open: 18e5 },\n // One multiplayer call may refresh credentials, connect (20 s) then run a command (10 s).\n multiplayer: { default: 35e3 },\n // HTTPS transport 10 s plus two revision checks and the idempotency receipt.\n network: { default: 2e4 },\n // Attachment uploads stream up to 64 MiB through the host. assets.media is not an operation: its host acknowledges at\n // once, asks assets.read for a read grant, then reads at most 64 MiB (256 MiB for a generated MP4) and stops any read\n // after 15 minutes.\n assets: { default: 6e4, uploadAttachment: 10 * 6e4, media: 10 * 6e4, "media.firstReply": 15e3 },\n // video.media is not an operation: its host acknowledges at once, calls video.get, then streams at most\n // 256 MiB and stops any read after 15 minutes.\n video: { default: 3e4, "clipping.uploadSource": 31 * 6e4, media: 10 * 6e4, "media.firstReply": 15e3, "projects.addReference": 6 * 6e4 },\n // Mac calls: 25 s, transcription 150 s.\n hardware: { default: 35e3, "audio.transcribe": 165e3 },\n // decide: 8 s provider deadline plus up to 5 s settlement; voice.start waits for host consent.\n ai: { default: 3e4, decide: 2e4, "voice.start": 12e4, "voice.state": 15e3 },\n // Device operations may wait for a consent sheet or a system picker.\n device: {\n default: 18e4,\n availability: 15e3,\n "haptics.trigger": 15e3,\n "haptics.pattern": 15e3,\n "haptics.stop": 15e3,\n "camera.stream": 3e5,\n "microphone.stream": 3e5,\n "motion.unsubscribe": 15e3,\n "notifications.list": 15e3,\n "notifications.cancel": 15e3,\n "alarms.list": 15e3,\n "alarms.cancel": 15e3\n },\n // Consent resolution and the queued request, without waiting for any device delivery.\n notifications: { default: 2e4 },\n // The person chooses in the host\'s Drive dialog (up to 3 minutes), then the host moves up to 64 MiB.\n drive: { default: 18e4, save: 13 * 6e4, pick: 13 * 6e4, "pick.firstReply": 15e3 },\n // The person reads the address in the host\'s affordance and confirms, or closes it (up to 2 minutes).\n link: { default: 12e4, open: 12e4 },\n // One read of the person\'s library by the web host (a few API pages at most); icons and avatars fetch up to 24 images;\n // `open` may wait for the person\'s consent to another creator\'s interface; `prefetch` is a hint answered at once.\n library: { default: 2e4, icons: 3e4, avatars: 3e4, open: 12e4, prefetch: 5e3 },\n // Public profiles of the workspace: one directory read; `get` also reads up to 50 photos.\n profiles: { default: 15e3, get: 3e4 },\n // The person chooses in the provider\'s sheet (up to 15 minutes); `available` reads the designation, `handle` one relay.\n // `available` reads the called experience; `call` may wait for the person\'s consent and a sheet\'s gesture (up to 15\n // minutes); `handle` is one relay of the called document\'s answer; `open` hands a window to the host; `pick` waits while\n // the person chooses in the picker window; `host` one answer of the host composing a swipe experience\'s feed.\n experiences: { default: 2e4, call: 15 * 6e4, handle: 12e4, open: 15e3, pick: 30 * 6e4, host: 15e3 },\n // One bounded page of the workspace inbox, or an acknowledgement.\n inbox: { default: 15e3 },\n // Recipient resolution, metering and the queued message, without waiting for delivery.\n email: { default: 2e4 },\n // One call relayed to the Mac; connect waits for the host\'s consent dialog, attach and watch for the host\'s stream.\n // \xC9tabli: the Mac\'s picker (60 s), commit hooks and fetch (55 s), a checkout (30 s), the start of a conversation that\n // may ask the person (60 s), a long poll (15 s), a search and a project\'s structure (10 s), each plus the relay.\n machine: {\n default: 2e4,\n connect: 18e4,\n "terminal.attach": 3e4,\n "terminal.watch": 3e4,\n "workspace.requestRoot": 75e3,\n "files.search": 2e4,\n "files.tree": 2e4,\n "git.commit": 7e4,\n "git.fetch": 7e4,\n "git.checkout": 45e3,\n "agents.start": 75e3,\n "agents.events": 25e3\n },\n navigation: { connect: 15e3, command: 15e3 }\n // An import answers once Watchirl accepted it (consent, project, operation), never after its download: follow it with\n // `get` (one status read and signed addresses); `list` reads up to 20 imports.\n};\n\n// src/storage-operations.ts\nvar common = { spend: "none", deadlineMs: null, sdkMarginMs: null, sdkTimeoutMs: operationWaiting.default, rateBucket: "public-playback" };\nvar read = { ...common, access: "read", observer: "declared-public-read", publicRead: "eligible", idempotency: "read" };\nvar write = { ...common, access: "contribute", observer: "denied", publicRead: "denied" };\nvar storageOperations = {\n state: {\n get: {\n ...read,\n capability: "state",\n operation: "get",\n input: "StateGetInput",\n output: "StateSnapshot",\n resource: null,\n facades: [{ path: "state.get", kind: "direct" }, { path: "state.watch", kind: "composite", live: "state" }]\n },\n set: {\n ...write,\n capability: "state",\n operation: "set",\n input: "StateSetInput",\n output: "StateSnapshot",\n resource: null,\n idempotency: "durable-receipt",\n facades: [{ path: "state.set", kind: "direct" }]\n }\n },\n memory: {\n get: {\n ...read,\n capability: "memory",\n operation: "get",\n input: "MemoryGetInput",\n output: "MemoryValue",\n resource: "key",\n facades: [{ path: "memory.get", kind: "direct" }]\n },\n set: {\n ...write,\n capability: "memory",\n operation: "set",\n input: "MemorySetInput",\n output: "MemoryValue",\n resource: "key",\n idempotency: "compare-and-set",\n facades: [{ path: "memory.set", kind: "direct" }]\n },\n remove: {\n ...write,\n capability: "memory",\n operation: "remove",\n input: "MemoryRemoveInput",\n output: "MemoryRemoveOutput",\n resource: "key",\n idempotency: "compare-and-set",\n facades: [{ path: "memory.remove", kind: "direct" }]\n },\n // The keys of the usage, never one key: `prefix` narrows them and the server keeps them within the declaration.\n list: {\n ...read,\n capability: "memory",\n operation: "list",\n input: "MemoryListInput",\n output: "MemoryListOutput",\n resource: "key",\n facades: [{ path: "memory.list", kind: "direct" }]\n }\n },\n database: {\n insert: {\n ...write,\n capability: "database",\n operation: "insert",\n input: "DatabaseInsertInput",\n output: "DatabaseInsertOutput",\n resource: "collection",\n idempotency: "durable-receipt",\n facades: [{ path: "database.insert", kind: "direct" }]\n },\n get: {\n ...read,\n capability: "database",\n operation: "get",\n input: "DatabaseGetInput",\n output: "DatabaseGetOutput",\n resource: "collection",\n facades: [{ path: "database.get", kind: "direct" }]\n },\n // database.watch: the first page of query, which the host also subscribes to the collection\'s shared writes.\n query: {\n ...read,\n capability: "database",\n operation: "query",\n input: "DatabaseQueryInput",\n output: "DatabaseQueryOutput",\n resource: "collection",\n facades: [{ path: "database.query", kind: "direct" }, { path: "database.watch", kind: "composite", live: "database" }]\n },\n update: {\n ...write,\n capability: "database",\n operation: "update",\n input: "DatabaseUpdateInput",\n output: "DatabaseUpdateOutput",\n resource: "collection",\n idempotency: "compare-and-set",\n facades: [{ path: "database.update", kind: "direct" }]\n },\n remove: {\n ...write,\n capability: "database",\n operation: "remove",\n input: "DatabaseRemoveInput",\n output: "DatabaseRemoveOutput",\n resource: "collection",\n idempotency: "compare-and-set",\n facades: [{ path: "database.remove", kind: "direct" }]\n },\n // Server-only final commit. There is no frontend facade or single top-level resource.\n transact: {\n ...write,\n capability: "database",\n operation: "transact",\n input: "BackendTransactionInput",\n output: "BackendTransactionCommitResult",\n resource: null,\n idempotency: "durable-receipt",\n facades: []\n },\n // After transact, which keeps the public tuple\'s order. Only the record\'s author changes it, and only the\n // participant\'s own page makes a record shared.\n visibility: {\n ...write,\n capability: "database",\n operation: "visibility",\n input: "DatabaseVisibilityInput",\n output: "DatabaseVisibilityOutput",\n resource: "collection",\n idempotency: "host-defined",\n facades: [\n { path: "database.setVisibility", kind: "direct" },\n { path: "database.share", kind: "composite" },\n { path: "database.unshare", kind: "composite" }\n ]\n }\n }\n};\nvar storageCapabilities = Object.keys(storageOperations);\nvar storageOperationList = Object.values(storageOperations).flatMap((group) => Object.values(group));\nvar storageReadOperations = storageOperationList.filter((item) => item.access === "read");\nvar databaseOperations = [\n storageOperations.database.insert.operation,\n storageOperations.database.get.operation,\n storageOperations.database.query.operation,\n storageOperations.database.update.operation,\n storageOperations.database.remove.operation,\n storageOperations.database.transact.operation,\n storageOperations.database.visibility.operation\n];\nvar stateOperations = Object.values(storageOperations.state).map((item) => item.operation);\nvar memoryOperations = Object.values(storageOperations.memory).map((item) => item.operation);\n\n// src/types/video-wire.ts\nvar tripirlVideoLocales = ["fr-FR", "en-US", "es-ES", "de-DE", "it-IT", "pt-PT", "nl-NL", "pl-PL", "sv-SE", "da-DK", "nb-NO", "fi-FI", "cs-CZ", "sk-SK", "hr-HR", "bg-BG", "ro-RO", "hu-HU", "el-GR", "ru-RU", "uk-UA", "tr-TR", "ar-SA", "hi-IN", "ta-IN", "id-ID", "ms-MY", "vi-VN", "zh-CN", "ja-JP", "ko-KR", "th-TH"];\n\n// src/types/video-sdk-wire.ts\nvar videoLocales = tripirlVideoLocales;\n\n// src/video-properties.ts\nvar videoStepIdPattern = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\nvar finite = (value) => typeof value === "number" && Number.isFinite(value);\nfunction propertyValue(value, depth = 0) {\n if (depth > 32) return void 0;\n if (value === null || typeof value === "string" || typeof value === "boolean" || finite(value)) return value;\n if (Array.isArray(value)) {\n const parsed2 = value.map((item) => propertyValue(item, depth + 1));\n return parsed2.some((item) => item === void 0) ? void 0 : parsed2;\n }\n if (!isRecord(value)) return void 0;\n const parsed = Object.entries(value).map(([key2, item]) => [key2, propertyValue(item, depth + 1)]);\n return parsed.some(([, item]) => item === void 0) ? void 0 : Object.fromEntries(parsed);\n}\nfunction propertyMap(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([key2, item]) => {\n const parsed = propertyValue(item);\n return parsed === void 0 ? [] : [[key2, parsed]];\n }));\n}\nfunction readVideoProperties(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([step3, values]) => {\n const parsed = videoStepIdPattern.test(step3) ? propertyMap(values) : void 0;\n return parsed === void 0 ? [] : [[step3, parsed]];\n }));\n}\nfunction readEffectiveVideoProperties(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([step3, block]) => {\n if (!videoStepIdPattern.test(step3) || !isRecord(block) || !isRecord(block.module) || typeof block.module.id !== "string" || !Number.isSafeInteger(block.module.revision) || Number(block.module.revision) <= 0) return [];\n const values = propertyMap(block.values);\n return values === void 0 ? [] : [[step3, { module: { id: block.module.id, revision: block.module.revision }, values }]];\n }));\n}\nfunction readVideoPropertyDefinition(value, depth = 0) {\n if (depth > 32 || !isRecord(value) || typeof value.key !== "string") return null;\n const effect = value.cost_effect;\n if (effect !== "none" && effect !== "may_change_quantity" && effect !== "may_change_unit_price" && effect !== "may_change_route") return null;\n const defaultValue = propertyValue(value.default);\n if (defaultValue === void 0) return null;\n const base2 = { key: value.key, cost_effect: effect, default: defaultValue };\n if (value.type === "boolean" && value.constraints === null) return { ...base2, type: "boolean", constraints: null };\n if (!isRecord(value.constraints)) return null;\n const constraints = value.constraints;\n if (value.type === "integer" || value.type === "number") {\n return { ...base2, type: value.type, constraints: Object.fromEntries(["minimum", "maximum", "step"].flatMap((key2) => finite(constraints[key2]) ? [[key2, constraints[key2]]] : [])) };\n }\n if (value.type === "string") return { ...base2, type: "string", constraints: Number.isSafeInteger(constraints.max_length) && Number(constraints.max_length) > 0 ? { max_length: constraints.max_length } : {} };\n if (value.type === "enum" && Array.isArray(constraints.values)) {\n const values = constraints.values.filter((item) => typeof item === "string" || typeof item === "boolean" || finite(item));\n return { ...base2, type: "enum", constraints: { values } };\n }\n if (value.type === "route" && Array.isArray(constraints.routes)) {\n const routes = constraints.routes.filter(isRecord).flatMap((route) => typeof route.provider === "string" && typeof route.model === "string" ? [{ provider: route.provider, model: route.model }] : []);\n return { ...base2, type: "route", constraints: { ...typeof constraints.need === "string" ? { need: constraints.need } : {}, routes } };\n }\n if (value.type === "object" && Array.isArray(constraints.fields)) {\n const fields = constraints.fields.map((item) => readVideoPropertyDefinition(item, depth + 1)).filter((item) => item !== null);\n return { ...base2, type: "object", constraints: { fields } };\n }\n return null;\n}\n\n// src/video-analysis.ts\nvar string = (value) => typeof value === "string";\nvar words = (value) => string(value) ? value : "";\nvar textOrNull = (value) => string(value) && value.length > 0 ? value : null;\nvar ms = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\nvar records = (value) => Array.isArray(value) ? value.filter(isRecord) : [];\nvar ids = (value) => Array.isArray(value) ? value.filter((item) => string(item) && item.length > 0) : [];\nvar span = (value) => ms(value.start_ms) && ms(value.end_ms) && value.end_ms >= value.start_ms;\nvar subject = (value) => string(value.id) && value.id.length > 0 && string(value.label);\nfunction readVideoSourceAnalysis(value) {\n if (!isRecord(value) || !ms(value.duration_ms) || value.duration_ms === 0 || !string(value.summary) || !isRecord(value.source)) return null;\n const source2 = value.source, audio = isRecord(value.audio) ? value.audio : {};\n if (!string(source2.sha256) || !ms(source2.width) || !ms(source2.height)) return null;\n return {\n duration_ms: value.duration_ms,\n summary: value.summary,\n places: records(value.places).filter(subject).map((item) => ({ id: item.id, label: item.label, description: words(item.description) })),\n people: records(value.people).filter(subject).map((item) => ({\n id: item.id,\n label: item.label,\n description: words(item.description),\n appearance: words(item.appearance),\n appearances: records(item.appearances).filter(span).map(({ start_ms, end_ms }) => ({ start_ms, end_ms })),\n speaks: item.speaks === true\n })),\n objects: records(value.objects).filter(subject).map((item) => ({ id: item.id, label: item.label, description: words(item.description) })),\n shots: records(value.shots).filter(span).map((item) => ({\n start_ms: item.start_ms,\n end_ms: item.end_ms,\n camera: words(item.camera),\n action: words(item.action),\n people: ids(item.people)\n })),\n events: records(value.events).filter((item) => ms(item.start_ms) && (item.end_ms === null || ms(item.end_ms)) && string(item.description)).map((item) => ({\n start_ms: item.start_ms,\n end_ms: item.end_ms,\n kind: words(item.kind),\n description: item.description,\n people: ids(item.people)\n })),\n transcript: records(value.transcript).filter((item) => span(item) && string(item.text)).map((item) => ({\n start_ms: item.start_ms,\n end_ms: item.end_ms,\n speaker: textOrNull(item.speaker),\n text: item.text\n })),\n audio: { music: textOrNull(audio.music), ambience: textOrNull(audio.ambience), speech: textOrNull(audio.speech) },\n source: {\n sha256: source2.sha256,\n width: source2.width,\n height: source2.height,\n fps: typeof source2.fps === "number" && Number.isFinite(source2.fps) && source2.fps > 0 ? source2.fps : null\n }\n };\n}\nfunction readVideoAnalysisResult(value) {\n if (!isRecord(value) || value.kind !== "analysis") return null;\n const analysis = readVideoSourceAnalysis(value.analysis);\n return analysis ? { kind: "analysis", analysis } : null;\n}\nfunction readVideoReferenceReplaces(value) {\n if (!isRecord(value)) return void 0;\n const subjectId = textOrNull(value.subject_id), description = textOrNull(value.description);\n if (!subjectId && !description) return void 0;\n return { ...subjectId ? { subject_id: subjectId } : {}, ...description ? { description } : {} };\n}\nfunction readVideoEditPlan(value) {\n if (value === void 0) return void 0;\n if (!isRecord(value)) return null;\n const analysisId = value.source_analysis_id;\n return {\n source_analysis_id: string(analysisId) && analysisId ? analysisId : null,\n mappings: records(value.mappings).filter((item) => isRecord(item.reference) && string(item.reference.asset_id) && item.reference.asset_id).map((item) => {\n const reference2 = item.reference, replaces2 = isRecord(item.replaces) ? item.replaces : {};\n return {\n reference: { asset_id: reference2.asset_id, role: textOrNull(reference2.role), name: textOrNull(reference2.name) },\n replaces: { subject_id: textOrNull(replaces2.subject_id), description: textOrNull(replaces2.description) },\n source: item.source === "explicit" ? "explicit" : "inferred",\n image_index: ms(item.image_index) && item.image_index > 0 ? item.image_index : null,\n visual_sheet: item.visual_sheet === true\n };\n }),\n warnings: Array.isArray(value.warnings) ? value.warnings.filter((item) => string(item) && item.length > 0) : []\n };\n}\nfunction readVideoReviewWarnings(value) {\n if (!Array.isArray(value)) return void 0;\n return records(value).filter((item) => string(item.code) && item.code && string(item.message) && item.message).map((item) => ({\n code: item.code,\n clip: ms(item.clip) && Number.isInteger(item.clip) && item.clip > 0 ? item.clip : null,\n message: item.message\n }));\n}\n\n// src/gamepad-types.ts\nvar GAMEPAD_SUMMARY_EVENT = "experience.gamepad.summary";\nvar GAMEPAD_TARGET_ATTRIBUTE = "data-nocha-gamepad-target";\nvar GAMEPAD_MAX_SLOTS = 8;\nvar GAMEPAD_MAX_AXES = 4;\nvar GAMEPAD_MAX_BUTTONS = 17;\nvar GAMEPAD_ID_MAX_CHARS = 160;\nvar GAMEPAD_BUTTON = {\n cross: 0,\n circle: 1,\n square: 2,\n triangle: 3,\n l1: 4,\n r1: 5,\n l2: 6,\n r2: 7,\n share: 8,\n options: 9,\n l3: 10,\n r3: 11,\n up: 12,\n down: 13,\n left: 14,\n right: 15\n};\n\n// src/viewport-types.ts\nfunction isExperienceViewport(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const viewport = value;\n const positive = ["layoutWidth", "layoutHeight", "scale"];\n const nonnegative = ["visualWidth", "visualHeight", "offsetTop", "offsetLeft", "keyboardInset"];\n if (positive.some((key2) => typeof viewport[key2] !== "number" || !Number.isFinite(viewport[key2]) || viewport[key2] <= 0) || nonnegative.some((key2) => typeof viewport[key2] !== "number" || !Number.isFinite(viewport[key2]) || viewport[key2] < 0) || typeof viewport.keyboardVisible !== "boolean") return false;\n const v = value;\n return v.offsetLeft + v.visualWidth <= v.layoutWidth + 1 && v.offsetTop + v.visualHeight <= v.layoutHeight + 1 && v.keyboardInset <= v.layoutHeight && (v.keyboardVisible || v.keyboardInset === 0);\n}\nvar SAFE_AREA_DECLARATION_EVENT = "experience.safe-area.declare";\n\n// src/shortcut-keys.ts\nvar SHORTCUT_MODIFIERS = ["ctrl", "alt", "shift", "meta"];\nvar ASSISTANT_SHORTCUTS_EVENT = "experience.assistant.shortcuts";\nvar ASSISTANT_SHORTCUT_EVENT = "experience.assistant.shortcut";\nvar ASSISTANT_SHORTCUTS_MAX = 48;\nvar CODE = /^(Key[A-Z]|Digit[0-9]|F([1-9]|1[0-9]|2[0-4])|Arrow(Up|Down|Left|Right)|Space|Enter|Backspace|Delete|Tab|Escape|Home|End|PageUp|PageDown|Minus|Equal|BracketLeft|BracketRight|Backslash|Semicolon|Quote|Backquote|Comma|Period|Slash|Numpad[0-9]|NumpadAdd|NumpadSubtract|NumpadMultiply|NumpadDivide|NumpadDecimal|NumpadEnter)$/;\nvar FUNCTION_KEY = /^F([1-9]|1[0-9]|2[0-4])$/;\nfunction parseShortcutKeys(keys) {\n if (typeof keys !== "string" || keys.length > 48) return null;\n const parts = keys.split("+"), code = parts.pop() ?? "";\n const modifiers = parts;\n let last = -1;\n for (const modifier of modifiers) {\n const index = SHORTCUT_MODIFIERS.indexOf(modifier);\n if (index <= last) return null;\n last = index;\n }\n return CODE.test(code) ? { modifiers, code } : null;\n}\nfunction isShortcutKeys(keys, scope = "app") {\n const parts = parseShortcutKeys(keys);\n if (!parts) return false;\n if (FUNCTION_KEY.test(parts.code)) return true;\n const { modifiers } = parts;\n return scope === "global" ? modifiers.includes("ctrl") || modifiers.includes("meta") : modifiers.some((modifier) => modifier !== "shift");\n}\nfunction shortcutKeysFromEvent(event) {\n if (!CODE.test(event.code)) return null;\n const pressed2 = { ctrl: event.ctrlKey, alt: event.altKey, shift: event.shiftKey, meta: event.metaKey };\n return [...SHORTCUT_MODIFIERS.filter((modifier) => pressed2[modifier]), event.code].join("+");\n}\nfunction isAssistantShortcuts(value) {\n return Array.isArray(value) && value.length <= ASSISTANT_SHORTCUTS_MAX && value.every((item) => item !== null && typeof item === "object" && typeof item.action === "string" && /^[a-z][a-z0-9_]{0,39}$/.test(item.action) && isShortcutKeys(item.keys, item.scope) && typeof item.label === "string" && item.label.length >= 1 && item.label.length <= 32 && (item.scope === "app" || item.scope === "global"));\n}\n\n// src/assistant-open.ts\nvar ASSISTANT_OPEN_EVENT = "experience.assistant.open";\nvar ASSISTANT_OPENED_EVENT = "experience.assistant.opened";\nvar ASSISTANT_OPEN_REFUSALS = ["invalid_request", "user_action_required", "rate_limited", "capability_denied"];\nvar THREAD = /^[a-z][a-z0-9_-]{0,63}$/;\nvar isAssistantThread = (value) => typeof value === "string" && THREAD.test(value);\nvar ASSISTANT_OPEN_DRAFT_MAX = 2e3;\nvar isAssistantDraft = (value) => typeof value === "string" && value.trim().length > 0 && value.length <= ASSISTANT_OPEN_DRAFT_MAX;\n\n// src/capability-registry.ts\nvar experienceCapabilities = ["presence", "multiplayer", "state", "ai", "assets", "video", "hardware", "memory", "database", "device", "network", "notifications", "inbox", "email", "backend", "automations", "connectors", "drive", "transfer", "search", "machine", "places", "link", "library", "excerpts", "experiences", "profiles"];\nvar hostPseudoCapabilities = ["access", "workspace", "module", "spaces", "screens"];\nvar usageFreeCapabilities = new Set(hostPseudoCapabilities.filter((capability) => capability !== "module"));\nvar bridgeCapabilities = /* @__PURE__ */ new Set([...experienceCapabilities, ...hostPseudoCapabilities]);\n\n// src/speech-rules.ts\nvar SPEECH_MODEL_ID_MAX_LENGTH = 100;\nvar SPEECH_VOICE_ID_MAX_LENGTH = 160;\nvar SPEECH_MODEL_ID_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,${SPEECH_MODEL_ID_MAX_LENGTH - 1}}$`);\nvar SPEECH_VOICE_ID_PATTERN = new RegExp(`^[A-Za-z0-9_:.-]{1,${SPEECH_VOICE_ID_MAX_LENGTH}}$`);\nvar speechVoiceAliases = [\n "alloy",\n "ash",\n "ballad",\n "coral",\n "echo",\n "fable",\n "nova",\n "onyx",\n "sage",\n "shimmer",\n "verse",\n "marin",\n "cedar"\n];\nvar speechVoiceGenders = ["female", "male", "neutral"];\nvar speechVoiceAges = ["young", "middle", "old"];\nvar isSpeechModelId = (value) => typeof value === "string" && SPEECH_MODEL_ID_PATTERN.test(value);\nvar isSpeechVoiceId = (value) => typeof value === "string" && SPEECH_VOICE_ID_PATTERN.test(value);\nvar isSpeechVoiceAlias = (value) => typeof value === "string" && speechVoiceAliases.includes(value);\nvar speechSettingRanges = {\n stability: { min: 0, max: 1 },\n similarityBoost: { min: 0, max: 1 },\n style: { min: 0, max: 1 },\n speed: { min: 0.7, max: 1.2 }\n};\nvar aiModelNeeds = ["audio.synthesize", "audio.sound_effect", "audio.generate", "audio.transcribe"];\nvar voiceFacets = [\n "language",\n "locale",\n "collection",\n "query",\n "gender",\n "age",\n "accent",\n "category",\n "use_cases",\n "descriptives",\n "featured",\n "sort",\n "max_price_multiplier",\n "verified_for"\n];\nvar voiceSorts = ["created_date", "usage_character_count_1y", "trending", "cloned_by_count"];\nvar voiceCollections = ["standard", "library", "all"];\nvar voiceCatalogueCollections = ["standard", "library", "both", "all"];\nvar VOICE_FACET_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _-]{0,49}$/;\nvar VOICE_FACET_LIST_MAX = 5;\n\n// src/capability-needs.ts\nvar generate = { role: "generate", mediaUsage: false, storedMediaResult: false };\nvar capabilityNeeds = {\n "text.short": { ...generate, providerCapability: "text.generate", waitMs: 2e4 },\n "text.chat": { ...generate, providerCapability: "text.generate", waitMs: 2e4 },\n "text.long": { ...generate, providerCapability: "text.generate", waitMs: 9e4 },\n "text.structured": { ...generate, providerCapability: "text.generate_structured", waitMs: 6e4 },\n "web.research": { ...generate, providerCapability: "web.research", waitMs: 9e4 },\n "audio.synthesize": { ...generate, providerCapability: "audio.synthesize", waitMs: 2e4, mediaUsage: true },\n "audio.transcribe": { ...generate, providerCapability: "audio.transcribe", waitMs: 12e4 },\n "audio.generate": { ...generate, providerCapability: "audio.generate", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "image.generate": { ...generate, providerCapability: "image.generate", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "image.edit": { ...generate, providerCapability: "image.edit", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "video.generate": { ...generate, providerCapability: "video.generate", waitMs: 18e4, mediaUsage: true, storedMediaResult: true },\n "image.remove_background": { ...generate, providerCapability: "image.remove_background", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "image.upscale": { ...generate, providerCapability: "image.upscale", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "audio.sound_effect": { ...generate, providerCapability: "audio.sound_effect", waitMs: 3e5, mediaUsage: true, storedMediaResult: true },\n "video.extend": { ...generate, providerCapability: "video.extend", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "video.upscale": { ...generate, providerCapability: "video.upscale", waitMs: 6e5, mediaUsage: true, storedMediaResult: true },\n "audio.voice_change": { ...generate, providerCapability: "audio.voice_change", waitMs: 3e5, mediaUsage: true, storedMediaResult: true },\n "text.decision": { role: "decide", providerCapability: "text.decide", waitMs: 8e3, mediaUsage: false, storedMediaResult: false },\n "voice.call": { role: "voice", providerCapability: "voice.call", waitMs: 2e4, mediaUsage: false, storedMediaResult: false }\n};\nvar allCapabilityNeeds = Object.keys(capabilityNeeds);\nvar aiGenerateNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].role === "generate");\nvar aiDecideNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].role === "decide");\nvar voiceCallNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].role === "voice");\nvar mediaResultNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].storedMediaResult);\nvar mediaUsageNeeds = allCapabilityNeeds.filter((need) => capabilityNeeds[need].mediaUsage);\nvar generationDeadlines = Object.fromEntries(aiGenerateNeeds.map((need) => [need, capabilityNeeds[need].waitMs]));\nvar capabilityNeedWaits = Object.fromEntries(allCapabilityNeeds.map((need) => [need, capabilityNeeds[need].waitMs]));\nvar needProviderCapabilities = Object.fromEntries(allCapabilityNeeds.map((need) => [need, capabilityNeeds[need].providerCapability]));\nvar generationWaiting = {\n fallbackMs: 2e4,\n visionTextMs: 3e5,\n sdkMarginMs: 6e4,\n negotiatedAdmissionMs: 25e3,\n pollIntervalMs: 2e3,\n pollMaxMs: 8e3\n};\n\n// src/transfer-types.ts\nvar NOCHA_TRANSFER_PROTOCOL = "nocha.transfer.v1";\nvar TRANSFER_HELLO_EVENT = "transfer.hello";\nvar TRANSFER_MAX_ITEMS = 32;\nvar TRANSFER_MAX_BYTES = 512 * 1024 * 1024;\nvar TRANSFER_PREVIEW_MAX_BYTES = 256 * 1024;\nvar TRANSFER_PAYLOAD_TIMEOUT_MS = 12e4;\nvar TRANSFER_DROP_TIMEOUT_MS = 3e4;\nvar TRANSFER_DROP_ACTIVATION_MS = 5e3;\nvar TRANSFER_ROLE_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;\nvar TRANSFER_ITEM_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;\nvar TRANSFER_DRAG_ID_PATTERN = /^[A-Za-z0-9-]{8,64}$/;\nvar TRANSFER_LABEL_MAX = 60;\nvar transferMimeTypes = {\n image: ["image/jpeg", "image/png", "image/webp", "image/gif", "image/avif", "image/heic", "image/heif", "image/svg+xml"],\n video: ["video/mp4", "video/quicktime", "video/webm"],\n audio: ["audio/mpeg", "audio/mp4", "audio/aac", "audio/wav", "audio/ogg", "audio/webm", "audio/flac"],\n document: ["application/pdf", "text/plain", "text/markdown"]\n};\nvar transferTypeAliases = {\n "image/jpg": "image/jpeg",\n "image/pjpeg": "image/jpeg",\n "audio/mp3": "audio/mpeg",\n "audio/x-mp3": "audio/mpeg",\n "audio/mpeg3": "audio/mpeg",\n "audio/x-mpeg": "audio/mpeg",\n "audio/x-m4a": "audio/mp4",\n "audio/m4a": "audio/mp4",\n "audio/x-wav": "audio/wav",\n "audio/wave": "audio/wav",\n "audio/vnd.wave": "audio/wav",\n "audio/x-aac": "audio/aac",\n "audio/x-flac": "audio/flac",\n "video/x-m4v": "video/mp4",\n "text/x-markdown": "text/markdown"\n};\nvar familyOf = { image: "image", video: "video", audio: "audio" };\nvar kindByType = new Map(\n Object.entries(transferMimeTypes).flatMap(([kind, types]) => types.map((type) => [type, kind]))\n);\nfunction normalizeTransferType(value) {\n if (typeof value !== "string" || value.length > 255) return null;\n const type = (value.split(";", 1)[0] ?? "").trim().toLowerCase();\n const canonical2 = transferTypeAliases[type] ?? type;\n return kindByType.has(canonical2) ? canonical2 : null;\n}\nfunction isTransferTypePattern(value) {\n if (typeof value !== "string") return false;\n if (value.endsWith("/*")) return Object.hasOwn(familyOf, value.slice(0, -2));\n return normalizeTransferType(value) === value;\n}\nfunction matchesTransferType(pattern, type) {\n const normalized = normalizeTransferType(type);\n if (!normalized) return false;\n if (pattern.endsWith("/*")) return familyOf[pattern.slice(0, -2)] === kindByType.get(normalized);\n return pattern === normalized;\n}\nfunction matchesTransferTypes(patterns, type) {\n return patterns.some((pattern) => matchesTransferType(pattern, type));\n}\n\n// src/host-channels.ts\nvar NOCHA_UPLOAD_PROTOCOL = "nocha.upload.v1";\nvar NOCHA_MEDIA_PROTOCOL = "nocha.media.v1";\nvar NOCHA_VIDEO_PLAYBACK_PROTOCOL = "nocha.video-playback.v1";\nvar NOCHA_LINK_OPEN_EVENT = "nocha.link.open";\n\n// src/shared-usage.ts\nvar USAGE_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;\nvar isUsageId = (value) => typeof value === "string" && USAGE_ID_PATTERN.test(value);\n\n// src/external-protocol.ts\nvar NOCHA_EXTERNAL_PROTOCOL = "nocha.external.v1";\nvar NOCHA_EXTERNAL_DEFAULT_HOSTS = ["https://*.novelchallenge.com"];\nvar NOCHA_EXTERNAL_HOSTS_META = "nocha:hosts";\nvar NOCHA_EXTERNAL_HOSTING_META = "nocha:hosting";\nvar NOCHA_EXTERNAL_CODE_META = "nocha:code";\nvar NONCE = /^[A-Za-z0-9_-]{16,128}$/;\nvar REQUEST_ID = /^[A-Za-z0-9_-]{8,128}$/;\nvar CODE2 = /^[a-z0-9]{6,10}$/;\nvar PLAYER_TOKEN = /^npt_[A-Za-z0-9._-]{40,4096}$/;\nvar DATETIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?Z$/;\nvar LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";\nvar ORIGIN_HOST = new RegExp(`^${LABEL}(?:\\\\.${LABEL})*$`);\nvar PATTERN_HOST = new RegExp(`^(?:${LABEL}\\\\.)+[a-z]{2,63}$`);\nfunction exact(value, keys) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const own = Object.keys(value);\n return own.length === keys.length && keys.every((key2) => Object.hasOwn(value, key2));\n}\nfunction matches(pattern, value) {\n return typeof value === "string" && pattern.test(value);\n}\nfunction isDatetime(value) {\n return matches(DATETIME, value) && Number.isFinite(Date.parse(value));\n}\nfunction parseOrigin(origin) {\n if (typeof origin !== "string" || origin.length > 300) return null;\n try {\n const url = new URL(origin);\n return url.protocol === "https:" && url.origin === origin && ORIGIN_HOST.test(url.hostname) ? { host: url.hostname, port: url.port } : null;\n } catch {\n return null;\n }\n}\nfunction isPlayerToken(value) {\n return exact(value, ["token", "api", "environment", "participantId", "expiresAt"]) && matches(PLAYER_TOKEN, value.token) && parseOrigin(value.api) !== null && (value.environment === "play" || value.environment === "development") && typeof value.participantId === "string" && value.participantId.length > 0 && value.participantId.length <= 200 && isDatetime(value.expiresAt);\n}\nfunction isError(value) {\n return exact(value, ["code", "message"]) && matches(CODE_PATTERN, value.code) && typeof value.message === "string" && value.message.length <= 1e3;\n}\nfunction isExternalFrameMessage(value) {\n if (!value || typeof value !== "object" || value.protocol !== NOCHA_EXTERNAL_PROTOCOL) return false;\n const message2 = value;\n switch (message2.type) {\n case "hello":\n return exact(value, ["protocol", "type", "nonce", "code"]) && matches(NONCE, message2.nonce) && matches(CODE2, message2.code);\n case "hello.ack":\n return exact(value, ["protocol", "type", "nonce", "sdkVersion"]) && matches(NONCE, message2.nonce) && message2.sdkVersion === 4;\n case "player-token.request":\n return exact(value, ["protocol", "type", "requestId"]) && matches(REQUEST_ID, message2.requestId);\n case "player-token.result":\n return exact(value, ["protocol", "type", "requestId", "token"]) && matches(REQUEST_ID, message2.requestId) && (message2.token === null || isPlayerToken(message2.token));\n case "player-token.error":\n return exact(value, ["protocol", "type", "requestId", "error"]) && matches(REQUEST_ID, message2.requestId) && isError(message2.error);\n default:\n return false;\n }\n}\nfunction parseHostPattern(pattern) {\n const match = /^https:\\/\\/(\\*\\.)?([^/:]+)(?::(\\d{1,5}))?$/.exec(pattern.toLowerCase());\n if (!match || !PATTERN_HOST.test(match[2])) return null;\n const port = match[3] === void 0 ? 443 : Number(match[3]);\n if (port < 1 || port > 65535) return null;\n return { wildcard: match[1] !== void 0, host: match[2], port: port === 443 ? "" : String(port) };\n}\nfunction matchesExternalHostPattern(origin, pattern) {\n const target = parseOrigin(origin);\n const rule = parseHostPattern(pattern);\n if (!target || !rule || target.port !== rule.port) return false;\n return rule.wildcard ? target.host.endsWith(`.${rule.host}`) : target.host === rule.host;\n}\nfunction normalizeExternalHostPattern(pattern) {\n const rule = typeof pattern === "string" ? parseHostPattern(pattern) : null;\n return rule ? `https://${rule.wildcard ? "*." : ""}${rule.host}${rule.port ? `:${rule.port}` : ""}` : null;\n}\nfunction parseExternalCodes(content) {\n return typeof content === "string" ? [...new Set(content.split(/\\s+/).filter((code) => CODE2.test(code)))] : [];\n}\nfunction externalFrameOrigins(codes2, patterns) {\n const valid = codes2.filter((code) => typeof code === "string" && CODE2.test(code));\n return [...new Set(patterns.flatMap((pattern) => {\n const normalized = normalizeExternalHostPattern(pattern);\n return normalized?.startsWith("https://*.") ? valid.map((code) => normalized.replace("*", code)) : [];\n }))];\n}\nfunction parseExternalHostPatterns(content) {\n const declared = typeof content === "string" ? content.split(/\\s+/).flatMap((item) => normalizeExternalHostPattern(item) ?? []) : [];\n return [.../* @__PURE__ */ new Set([...NOCHA_EXTERNAL_DEFAULT_HOSTS, ...declared])];\n}\n\n// src/operation-metadata.ts\nvar operationDefaults = {\n needs: [],\n transport: "invoke",\n access: "contribute",\n observer: "denied",\n publicRead: "denied",\n publicControl: null,\n mediaUsage: false,\n spend: "none",\n idempotency: "host-defined",\n waiting: "operation",\n deadlineMs: null,\n sdkMarginMs: null,\n rateBucket: "public-playback",\n compatibility: "current"\n};\nvar operationRead = { access: "read", idempotency: "read" };\nvar observerRead = { ...operationRead, observer: "declared-public-read" };\nvar publicRead = { ...observerRead, publicRead: "eligible" };\n\n// src/automations-operations.ts\nvar base = { ...operationDefaults, capability: "automations", sdkTimeoutMs: 12e4, rateBucket: "experience-automations" };\nvar automationsOperationDefinitions = {\n catalog: { ...base, ...operationRead, operation: "catalog", input: "automations.catalog", output: "automations.catalog", facades: [{ path: "automations.catalog", kind: "direct" }] },\n list: { ...base, ...operationRead, operation: "list", input: "automations.list", output: "automations.list", facades: [{ path: "automations.list", kind: "direct" }] },\n get: { ...base, ...operationRead, operation: "get", input: "automations.get", output: "automations.get", facades: [{ path: "automations.get", kind: "direct" }] },\n create: { ...base, operation: "create", input: "automations.create", output: "automations.create", facades: [{ path: "automations.create", kind: "direct" }] },\n save: { ...base, operation: "save", input: "automations.save", output: "automations.save", idempotency: "compare-and-set", facades: [{ path: "automations.save", kind: "direct" }] },\n validate: { ...base, ...operationRead, operation: "validate", input: "automations.validate", output: "automations.validate", facades: [{ path: "automations.validate", kind: "direct" }] },\n remove: { ...base, operation: "remove", input: "automations.remove", output: "automations.remove", facades: [{ path: "automations.remove", kind: "direct" }] },\n activate: { ...base, operation: "activate", input: "automations.activate", output: "automations.activate", facades: [{ path: "automations.activate", kind: "direct" }] },\n pause: { ...base, operation: "pause", input: "automations.pause", output: "automations.pause", facades: [{ path: "automations.pause", kind: "direct" }] },\n test: { ...base, operation: "test", input: "automations.test", output: "automations.test", spend: "may-spend", facades: [{ path: "automations.test", kind: "direct" }] },\n runs: { ...base, ...operationRead, operation: "runs", input: "automations.runs", output: "automations.runs", facades: [{ path: "automations.runs", kind: "direct" }] },\n run: { ...base, ...operationRead, operation: "run", input: "automations.run", output: "automations.run", facades: [{ path: "automations.run", kind: "direct" }] },\n "templates.list": { ...base, ...operationRead, operation: "templates.list", input: "automations.templates.list", output: "automations.templates.list", facades: [{ path: "automations.templates.list", kind: "direct" }] },\n "templates.publish": { ...base, operation: "templates.publish", input: "automations.templates.publish", output: "automations.templates.publish", facades: [{ path: "automations.templates.publish", kind: "direct" }] },\n "templates.use": { ...base, operation: "templates.use", input: "automations.templates.use", output: "automations.templates.use", facades: [{ path: "automations.templates.use", kind: "direct" }] }\n};\n\n// src/ai-operations.ts\nvar aiOperationDefinitions = {\n "generate": {\n ...operationDefaults,\n capability: "ai",\n operation: "generate",\n input: "ai.generate",\n output: "ai.generate",\n sdkTimeoutMs: null,\n needs: aiGenerateNeeds,\n spend: "may-spend",\n waiting: "generation-need",\n sdkMarginMs: generationWaiting.sdkMarginMs,\n idempotency: "durable-receipt",\n facades: [{ path: "ai.generate", kind: "composite" }]\n },\n "estimate": {\n ...operationDefaults,\n capability: "ai",\n operation: "estimate",\n input: "ai.estimate",\n output: "ai.estimate",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.estimate", kind: "direct" }]\n },\n "options": {\n ...operationDefaults,\n capability: "ai",\n operation: "options",\n input: "ai.options",\n output: "ai.options",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.options", kind: "direct" }]\n },\n // `ai.voiceCatalogue` is a composite of these two reads, not an operation: it declares both.\n "models": {\n ...operationDefaults,\n capability: "ai",\n operation: "models",\n input: "ai.models",\n output: "ai.models",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.models", kind: "direct" }, { path: "ai.voiceCatalogue", kind: "composite" }]\n },\n "voices": {\n ...operationDefaults,\n capability: "ai",\n operation: "voices",\n input: "ai.voices",\n output: "ai.voices",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.voices", kind: "direct" }, { path: "ai.voiceCatalogue", kind: "composite" }]\n },\n // The provider\'s own sample of a listed voice: a read that synthesizes nothing, so it never spends.\n "voicePreview": {\n ...operationDefaults,\n capability: "ai",\n operation: "voicePreview",\n input: "ai.voicePreview",\n output: "ai.voicePreview",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n spend: "none",\n facades: [{ path: "ai.voicePreview", kind: "direct" }]\n },\n // The participant\'s favourite voices, kept by Nocha for every experience: free reads and writes.\n "voiceFavorites": {\n ...operationDefaults,\n capability: "ai",\n operation: "voiceFavorites",\n input: "ai.voiceFavorites",\n output: "ai.voiceFavorites",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n spend: "none",\n facades: [{ path: "ai.voiceFavorites", kind: "direct" }]\n },\n "voiceFavoritesUpdate": {\n ...operationDefaults,\n capability: "ai",\n operation: "voiceFavoritesUpdate",\n input: "ai.voiceFavoritesUpdate",\n output: "ai.voiceFavoritesUpdate",\n sdkTimeoutMs: operationWaiting.ai.default,\n needs: aiGenerateNeeds,\n spend: "none",\n facades: [{ path: "ai.voiceFavoritesUpdate", kind: "direct" }]\n },\n "get": {\n ...operationDefaults,\n capability: "ai",\n operation: "get",\n input: "ai.get",\n output: "ai.get",\n sdkTimeoutMs: operationWaiting.ai.default,\n ...operationRead,\n needs: aiGenerateNeeds,\n facades: [{ path: "ai.get", kind: "direct" }]\n },\n "decide": {\n ...operationDefaults,\n capability: "ai",\n operation: "decide",\n input: "ai.decide",\n output: "ai.decide",\n sdkTimeoutMs: operationWaiting.ai["decide"],\n needs: aiDecideNeeds,\n spend: "may-spend",\n facades: [{ path: "ai.decide", kind: "direct" }]\n },\n "voice.start": {\n ...operationDefaults,\n capability: "ai",\n operation: "voice.start",\n input: "ai.voice.start",\n output: "ai.voice.start",\n sdkTimeoutMs: operationWaiting.ai["voice.start"],\n needs: voiceCallNeeds,\n spend: "may-spend",\n transport: "voice-host",\n facades: [{ path: "voice.start", kind: "direct" }]\n },\n "voice.stop": {\n ...operationDefaults,\n capability: "ai",\n operation: "voice.stop",\n input: "ai.voice.stop",\n output: "ai.voice.stop",\n sdkTimeoutMs: operationWaiting.ai.default,\n needs: voiceCallNeeds,\n transport: "voice-host",\n facades: [{ path: "voice.stop", kind: "direct" }]\n },\n "voice.state": {\n ...operationDefaults,\n capability: "ai",\n operation: "voice.state",\n input: "ai.voice.state",\n output: "ai.voice.state",\n sdkTimeoutMs: operationWaiting.ai["voice.state"],\n ...operationRead,\n needs: voiceCallNeeds,\n transport: "voice-host",\n facades: [{ path: "voice.state", kind: "direct" }]\n }\n};\n\n// src/assets-operations.ts\nvar assetsOperationDefinitions = {\n "read": {\n ...operationDefaults,\n capability: "assets",\n operation: "read",\n input: "assets.read",\n output: "assets.read",\n sdkTimeoutMs: operationWaiting.assets.default,\n ...publicRead,\n facades: [{ path: "assets.read", kind: "direct" }, { path: "assets.media", kind: "composite" }]\n },\n "upload": {\n ...operationDefaults,\n capability: "assets",\n operation: "upload",\n input: "assets.upload",\n output: "assets.upload",\n sdkTimeoutMs: operationWaiting.assets.default,\n mediaUsage: true,\n facades: [{ path: "assets.upload", kind: "direct" }]\n },\n "uploadAttachment": {\n ...operationDefaults,\n capability: "assets",\n operation: "uploadAttachment",\n input: "assets.uploadAttachment",\n output: "assets.uploadAttachment",\n sdkTimeoutMs: operationWaiting.assets["uploadAttachment"],\n mediaUsage: true,\n transport: "binary-upload",\n idempotency: "durable-receipt",\n facades: [{ path: "assets.uploadAttachment", kind: "direct" }]\n },\n "attachmentUrl": {\n ...operationDefaults,\n capability: "assets",\n operation: "attachmentUrl",\n input: "assets.attachmentUrl",\n output: "assets.attachmentUrl",\n sdkTimeoutMs: operationWaiting.assets.default,\n mediaUsage: true,\n ...operationRead,\n facades: [{ path: "assets.attachmentUrl", kind: "direct" }]\n },\n // The caller\'s own media under the usage, with an account and contribute access: only its author lists, shares, hides or\n // removes one; sharing needs the participant\'s own page.\n "share": {\n ...operationDefaults,\n capability: "assets",\n operation: "share",\n input: "assets.share",\n output: "assets.share",\n sdkTimeoutMs: operationWaiting.assets.default,\n facades: [{ path: "assets.share", kind: "direct" }, { path: "assets.setVisibility", kind: "composite" }]\n },\n "unshare": {\n ...operationDefaults,\n capability: "assets",\n operation: "unshare",\n input: "assets.unshare",\n output: "assets.unshare",\n sdkTimeoutMs: operationWaiting.assets.default,\n facades: [{ path: "assets.unshare", kind: "direct" }, { path: "assets.setVisibility", kind: "composite" }]\n },\n "list": {\n ...operationDefaults,\n capability: "assets",\n operation: "list",\n input: "assets.list",\n output: "assets.list",\n sdkTimeoutMs: operationWaiting.assets.default,\n facades: [{ path: "assets.list", kind: "direct" }]\n },\n "remove": {\n ...operationDefaults,\n capability: "assets",\n operation: "remove",\n input: "assets.remove",\n output: "assets.remove",\n sdkTimeoutMs: operationWaiting.assets.default,\n facades: [{ path: "assets.remove", kind: "direct" }]\n }\n};\n\n// src/video-operations.ts\nvar videoOperationDefinitions = {\n "connection": {\n ...operationDefaults,\n capability: "video",\n operation: "connection",\n input: "video.connection",\n output: "video.connection",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.connection", kind: "direct" }]\n },\n "workflows": {\n ...operationDefaults,\n capability: "video",\n operation: "workflows",\n input: "video.workflows",\n output: "video.workflows",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.workflows", kind: "direct" }]\n },\n "workflow": {\n ...operationDefaults,\n capability: "video",\n operation: "workflow",\n input: "video.workflow",\n output: "video.workflow",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.workflow", kind: "direct" }]\n },\n "estimate": {\n ...operationDefaults,\n capability: "video",\n operation: "estimate",\n input: "video.estimate",\n output: "video.estimate",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.estimate", kind: "direct" }]\n },\n "create": {\n ...operationDefaults,\n capability: "video",\n operation: "create",\n input: "video.create",\n output: "video.create",\n sdkTimeoutMs: operationWaiting.video.default,\n mediaUsage: true,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.create", kind: "direct" }]\n },\n "list": {\n ...operationDefaults,\n capability: "video",\n operation: "list",\n input: "video.list",\n output: "video.list",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.list", kind: "direct" }]\n },\n "get": {\n ...operationDefaults,\n capability: "video",\n operation: "get",\n input: "video.get",\n output: "video.get",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.get", kind: "direct" }, { path: "video.wait", kind: "composite" }, { path: "video.media", kind: "composite" }, { path: "video.playback", kind: "composite" }]\n },\n "retry": {\n ...operationDefaults,\n capability: "video",\n operation: "retry",\n input: "video.retry",\n output: "video.retry",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.retry", kind: "direct" }]\n },\n "cancel": {\n ...operationDefaults,\n capability: "video",\n operation: "cancel",\n input: "video.cancel",\n output: "video.cancel",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.cancel", kind: "direct" }]\n },\n "remove": {\n ...operationDefaults,\n capability: "video",\n operation: "remove",\n input: "video.remove",\n output: "video.remove",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.remove", kind: "direct" }]\n },\n // By its author only; sharing needs the participant\'s own page.\n "share": {\n ...operationDefaults,\n capability: "video",\n operation: "share",\n input: "video.share",\n output: "video.share",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.share", kind: "direct" }, { path: "video.setVisibility", kind: "composite" }]\n },\n "unshare": {\n ...operationDefaults,\n capability: "video",\n operation: "unshare",\n input: "video.unshare",\n output: "video.unshare",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.unshare", kind: "direct" }, { path: "video.setVisibility", kind: "composite" }]\n },\n "clipping.create": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.create",\n input: "video.clipping.create",\n output: "video.clipping.create",\n sdkTimeoutMs: operationWaiting.video.default,\n mediaUsage: true,\n facades: [{ path: "video.clipping.create", kind: "direct" }]\n },\n "clipping.list": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.list",\n input: "video.clipping.list",\n output: "video.clipping.list",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.clipping.list", kind: "direct" }]\n },\n "clipping.get": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.get",\n input: "video.clipping.get",\n output: "video.clipping.get",\n sdkTimeoutMs: operationWaiting.video.default,\n ...observerRead,\n facades: [{ path: "video.clipping.get", kind: "direct" }]\n },\n "clipping.remove": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.remove",\n input: "video.clipping.remove",\n output: "video.clipping.remove",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.clipping.remove", kind: "direct" }]\n },\n "clipping.uploadSource": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.uploadSource",\n input: "video.clipping.uploadSource",\n output: "video.clipping.uploadSource",\n sdkTimeoutMs: operationWaiting.video["clipping.uploadSource"],\n transport: "binary-upload",\n facades: [{ path: "video.clipping.uploadSource", kind: "direct" }]\n },\n "clipping.estimate": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.estimate",\n input: "video.clipping.estimate",\n output: "video.clipping.estimate",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.clipping.estimate", kind: "direct" }]\n },\n "clipping.propose": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.propose",\n input: "video.clipping.propose",\n output: "video.clipping.propose",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.clipping.propose", kind: "direct" }]\n },\n "clipping.updatePlan": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.updatePlan",\n input: "video.clipping.updatePlan",\n output: "video.clipping.updatePlan",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.clipping.updatePlan", kind: "direct" }]\n },\n "clipping.createExport": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.createExport",\n input: "video.clipping.createExport",\n output: "video.clipping.createExport",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.clipping.createExport", kind: "direct" }]\n },\n "clipping.getJob": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.getJob",\n input: "video.clipping.getJob",\n output: "video.clipping.getJob",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n facades: [{ path: "video.clipping.getJob", kind: "direct" }]\n },\n "clipping.cancelJob": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.cancelJob",\n input: "video.clipping.cancelJob",\n output: "video.clipping.cancelJob",\n sdkTimeoutMs: operationWaiting.video.default,\n facades: [{ path: "video.clipping.cancelJob", kind: "direct" }]\n },\n "clipping.resumeJob": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.resumeJob",\n input: "video.clipping.resumeJob",\n output: "video.clipping.resumeJob",\n sdkTimeoutMs: operationWaiting.video.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n facades: [{ path: "video.clipping.resumeJob", kind: "direct" }]\n },\n "clipping.prepareMutation": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.prepareMutation",\n input: "video.clipping.prepareMutation",\n output: "video.clipping.prepareMutation",\n sdkTimeoutMs: operationWaiting.video.default,\n transport: "host-document",\n facades: [{ path: "video.clipping.prepareMutation", kind: "direct" }]\n },\n "clipping.readMutation": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.readMutation",\n input: "video.clipping.readMutation",\n output: "video.clipping.readMutation",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n transport: "host-document",\n facades: [{ path: "video.clipping.readMutation", kind: "direct" }]\n },\n "clipping.completeMutation": {\n ...operationDefaults,\n capability: "video",\n operation: "clipping.completeMutation",\n input: "video.clipping.completeMutation",\n output: "video.clipping.completeMutation",\n sdkTimeoutMs: operationWaiting.video.default,\n transport: "host-document",\n facades: [{ path: "video.clipping.completeMutation", kind: "direct" }]\n },\n // The participant\'s own Tripirl projects: signed-in only, never observed nor public; one per-account rate bucket.\n "projects.list": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.list",\n input: "video.projects.list",\n output: "video.projects.list",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.list", kind: "direct" }]\n },\n "projects.get": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.get",\n input: "video.projects.get",\n output: "video.projects.get",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.get", kind: "direct" }]\n },\n "projects.artifacts": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.artifacts",\n input: "video.projects.artifacts",\n output: "video.projects.artifacts",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.artifacts", kind: "direct" }]\n },\n "projects.media": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.media",\n input: "video.projects.media",\n output: "video.projects.media",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.media", kind: "composite" }]\n },\n "projects.cancel": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.cancel",\n input: "video.projects.cancel",\n output: "video.projects.cancel",\n sdkTimeoutMs: operationWaiting.video.default,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.cancel", kind: "direct" }]\n },\n "projects.previewSettings": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.previewSettings",\n input: "video.projects.previewSettings",\n output: "video.projects.previewSettings",\n sdkTimeoutMs: operationWaiting.video.default,\n ...operationRead,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.previewSettings", kind: "direct" }]\n },\n "projects.updateSettings": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.updateSettings",\n input: "video.projects.updateSettings",\n output: "video.projects.updateSettings",\n sdkTimeoutMs: operationWaiting.video.default,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.updateSettings", kind: "direct" }]\n },\n "projects.resume": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.resume",\n input: "video.projects.resume",\n output: "video.projects.resume",\n sdkTimeoutMs: operationWaiting.video.default,\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.resume", kind: "direct" }]\n },\n // Tripirl copies the video into the project before answering: up to a few minutes for a long one.\n "projects.addReference": {\n ...operationDefaults,\n capability: "video",\n operation: "projects.addReference",\n input: "video.projects.addReference",\n output: "video.projects.addReference",\n sdkTimeoutMs: operationWaiting.video["projects.addReference"],\n rateBucket: "experience-video-projects",\n facades: [{ path: "video.projects.addReference", kind: "direct" }]\n }\n};\nvar videoOperations = [\n videoOperationDefinitions["connection"].operation,\n videoOperationDefinitions["workflows"].operation,\n videoOperationDefinitions["workflow"].operation,\n videoOperationDefinitions["estimate"].operation,\n videoOperationDefinitions["create"].operation,\n videoOperationDefinitions["list"].operation,\n videoOperationDefinitions["get"].operation,\n videoOperationDefinitions["retry"].operation,\n videoOperationDefinitions["cancel"].operation,\n videoOperationDefinitions["remove"].operation,\n videoOperationDefinitions["share"].operation,\n videoOperationDefinitions["unshare"].operation,\n videoOperationDefinitions["clipping.create"].operation,\n videoOperationDefinitions["clipping.list"].operation,\n videoOperationDefinitions["clipping.get"].operation,\n videoOperationDefinitions["clipping.remove"].operation,\n videoOperationDefinitions["clipping.uploadSource"].operation,\n videoOperationDefinitions["clipping.estimate"].operation,\n videoOperationDefinitions["clipping.propose"].operation,\n videoOperationDefinitions["clipping.updatePlan"].operation,\n videoOperationDefinitions["clipping.createExport"].operation,\n videoOperationDefinitions["clipping.getJob"].operation,\n videoOperationDefinitions["clipping.cancelJob"].operation,\n videoOperationDefinitions["clipping.resumeJob"].operation,\n videoOperationDefinitions["clipping.prepareMutation"].operation,\n videoOperationDefinitions["clipping.readMutation"].operation,\n videoOperationDefinitions["clipping.completeMutation"].operation,\n videoOperationDefinitions["projects.list"].operation,\n videoOperationDefinitions["projects.get"].operation,\n videoOperationDefinitions["projects.artifacts"].operation,\n videoOperationDefinitions["projects.media"].operation,\n videoOperationDefinitions["projects.cancel"].operation,\n videoOperationDefinitions["projects.previewSettings"].operation,\n videoOperationDefinitions["projects.updateSettings"].operation,\n videoOperationDefinitions["projects.resume"].operation,\n videoOperationDefinitions["projects.addReference"].operation\n];\nvar videoWaitSchedule = { fastMs: 2e3, fastForMs: 2e4, steadyMs: 5e3, steadyForMs: 12e4, slowMs: 15e3, minimumIntervalMs: 2e3 };\n\n// src/hardware-operations.ts\nvar hardwareOperationDefinitions = {\n "metrics.read": {\n ...operationDefaults,\n capability: "hardware",\n operation: "metrics.read",\n input: "hardware.metrics.read",\n output: "hardware.metrics.read",\n sdkTimeoutMs: operationWaiting.hardware.default,\n ...operationRead,\n facades: [{ path: "hardware.metrics", kind: "direct" }]\n },\n "hue.lights.read": {\n ...operationDefaults,\n capability: "hardware",\n operation: "hue.lights.read",\n input: "hardware.hue.lights.read",\n output: "hardware.hue.lights.read",\n sdkTimeoutMs: operationWaiting.hardware.default,\n ...operationRead,\n publicControl: "hue",\n rateBucket: "hardware-control",\n facades: [{ path: "hardware.hue.lights", kind: "direct" }]\n },\n "hue.lights.set": {\n ...operationDefaults,\n capability: "hardware",\n operation: "hue.lights.set",\n input: "hardware.hue.lights.set",\n output: "hardware.hue.lights.set",\n sdkTimeoutMs: operationWaiting.hardware.default,\n publicControl: "hue",\n rateBucket: "hardware-control",\n facades: [{ path: "hardware.hue.set", kind: "direct" }]\n },\n "leds.read": {\n ...operationDefaults,\n capability: "hardware",\n operation: "leds.read",\n input: "hardware.leds.read",\n output: "hardware.leds.read",\n sdkTimeoutMs: operationWaiting.hardware.default,\n ...operationRead,\n publicControl: "leds",\n rateBucket: "hardware-control",\n facades: [{ path: "hardware.leds.read", kind: "direct" }]\n },\n "leds.set": {\n ...operationDefaults,\n capability: "hardware",\n operation: "leds.set",\n input: "hardware.leds.set",\n output: "hardware.leds.set",\n sdkTimeoutMs: operationWaiting.hardware.default,\n publicControl: "leds",\n rateBucket: "hardware-control",\n facades: [{ path: "hardware.leds.set", kind: "direct" }]\n },\n "audio.devices": {\n ...operationDefaults,\n capability: "hardware",\n operation: "audio.devices",\n input: "hardware.audio.devices",\n output: "hardware.audio.devices",\n sdkTimeoutMs: operationWaiting.hardware.default,\n ...operationRead,\n rateBucket: "hardware-audio",\n facades: [{ path: "hardware.audio.devices", kind: "direct" }]\n },\n "audio.start": {\n ...operationDefaults,\n capability: "hardware",\n operation: "audio.start",\n input: "hardware.audio.start",\n output: "hardware.audio.start",\n sdkTimeoutMs: operationWaiting.hardware.default,\n rateBucket: "hardware-audio",\n facades: [{ path: "hardware.audio.start", kind: "direct" }]\n },\n "audio.read": {\n ...operationDefaults,\n capability: "hardware",\n operation: "audio.read",\n input: "hardware.audio.read",\n output: "hardware.audio.read",\n sdkTimeoutMs: operationWaiting.hardware.default,\n ...operationRead,\n rateBucket: "hardware-audio",\n facades: [{ path: "hardware.audio.read", kind: "direct" }]\n },\n "audio.stop": {\n ...operationDefaults,\n capability: "hardware",\n operation: "audio.stop",\n input: "hardware.audio.stop",\n output: "hardware.audio.stop",\n sdkTimeoutMs: operationWaiting.hardware.default,\n rateBucket: "hardware-audio",\n facades: [{ path: "hardware.audio.stop", kind: "direct" }]\n },\n "audio.transcribe": {\n ...operationDefaults,\n capability: "hardware",\n operation: "audio.transcribe",\n input: "hardware.audio.transcribe",\n output: "hardware.audio.transcribe",\n sdkTimeoutMs: operationWaiting.hardware["audio.transcribe"],\n rateBucket: "hardware-audio",\n spend: "may-spend",\n facades: [{ path: "hardware.audio.transcribe", kind: "direct" }]\n },\n "network.read": {\n ...operationDefaults,\n capability: "hardware",\n operation: "network.read",\n input: "hardware.network.read",\n output: "hardware.network.read",\n sdkTimeoutMs: operationWaiting.hardware.default,\n ...publicRead,\n rateBucket: "hardware-network",\n facades: [{ path: "hardware.network", kind: "direct" }]\n },\n "desktop.read": {\n ...operationDefaults,\n capability: "hardware",\n operation: "desktop.read",\n input: "hardware.desktop.read",\n output: "hardware.desktop.read",\n sdkTimeoutMs: operationWaiting.hardware.default,\n ...operationRead,\n rateBucket: "hardware-desktop",\n facades: [{ path: "hardware.desktop.read", kind: "direct" }]\n },\n "desktop.dictation": {\n ...operationDefaults,\n capability: "hardware",\n operation: "desktop.dictation",\n input: "hardware.desktop.dictation",\n output: "hardware.desktop.dictation",\n sdkTimeoutMs: operationWaiting.hardware.default,\n rateBucket: "hardware-desktop",\n facades: [{ path: "hardware.desktop.dictation", kind: "direct" }]\n },\n "desktop.terminal": {\n ...operationDefaults,\n capability: "hardware",\n operation: "desktop.terminal",\n input: "hardware.desktop.terminal",\n output: "hardware.desktop.terminal",\n sdkTimeoutMs: operationWaiting.hardware.default,\n rateBucket: "hardware-desktop",\n facades: [{ path: "hardware.desktop.terminal", kind: "direct" }]\n }\n};\n\n// src/network-operations.ts\nvar networkOperationDefinitions = {\n "request": {\n ...operationDefaults,\n capability: "network",\n operation: "request",\n input: "network.request",\n output: "network.request",\n sdkTimeoutMs: operationWaiting.network.default,\n idempotency: "durable-receipt",\n facades: [{ path: "network.request", kind: "direct" }]\n },\n "asset": {\n ...operationDefaults,\n capability: "network",\n operation: "asset",\n input: "network.asset",\n output: "network.asset",\n sdkTimeoutMs: operationWaiting.network.default,\n ...operationRead,\n facades: [{ path: "network.asset", kind: "direct" }]\n }\n};\n\n// src/multiplayer-operations.ts\nvar multiplayerOperationDefinitions = {\n "presence": {\n ...operationDefaults,\n capability: "multiplayer",\n operation: "presence",\n input: "multiplayer.presence",\n output: "multiplayer.presence",\n sdkTimeoutMs: operationWaiting.multiplayer.default,\n transport: "live-host",\n ...publicRead,\n facades: [{ path: "multiplayer.presence", kind: "direct" }, { path: "multiplayer.onPresence", kind: "composite" }]\n },\n "subscribe": {\n ...operationDefaults,\n capability: "multiplayer",\n operation: "subscribe",\n input: "multiplayer.subscribe",\n output: "multiplayer.subscribe",\n sdkTimeoutMs: operationWaiting.multiplayer.default,\n transport: "live-host",\n ...publicRead,\n facades: [{ path: "multiplayer.subscribe", kind: "composite" }]\n },\n "publish": {\n ...operationDefaults,\n capability: "multiplayer",\n operation: "publish",\n input: "multiplayer.publish",\n output: "multiplayer.publish",\n sdkTimeoutMs: operationWaiting.multiplayer.default,\n transport: "live-host",\n facades: [{ path: "multiplayer.publish", kind: "direct" }]\n }\n};\n\n// src/device-operations.ts\nvar deviceOperationDefinitions = {\n "availability": {\n ...operationDefaults,\n capability: "device",\n operation: "availability",\n input: "device.availability",\n output: "device.availability",\n sdkTimeoutMs: operationWaiting.device["availability"],\n transport: "native-host",\n ...operationRead,\n facades: [\n { path: "device.availability", kind: "direct" },\n { path: "device.media.status", kind: "composite" },\n { path: "device.media.offerHost", kind: "composite" }\n ]\n },\n "camera.capture": {\n ...operationDefaults,\n capability: "device",\n operation: "camera.capture",\n input: "device.camera.capture",\n output: "device.camera.capture",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.camera.capture", kind: "direct" }]\n },\n "camera.stream": {\n ...operationDefaults,\n capability: "device",\n operation: "camera.stream",\n input: "device.camera.stream",\n output: "device.camera.stream",\n sdkTimeoutMs: operationWaiting.device["camera.stream"],\n transport: "native-host",\n facades: [{ path: "device.media.getUserMedia", kind: "composite" }]\n },\n "photos.pick": {\n ...operationDefaults,\n capability: "device",\n operation: "photos.pick",\n input: "device.photos.pick",\n output: "device.photos.pick",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.photos.pick", kind: "direct" }]\n },\n "microphone.stream": {\n ...operationDefaults,\n capability: "device",\n operation: "microphone.stream",\n input: "device.microphone.stream",\n output: "device.microphone.stream",\n sdkTimeoutMs: operationWaiting.device["microphone.stream"],\n transport: "native-host",\n facades: [{ path: "device.media.getUserMedia", kind: "composite" }]\n },\n "motion.subscribe": {\n ...operationDefaults,\n capability: "device",\n operation: "motion.subscribe",\n input: "device.motion.subscribe",\n output: "device.motion.subscribe",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.motion.subscribe", kind: "composite" }]\n },\n "motion.unsubscribe": {\n ...operationDefaults,\n capability: "device",\n operation: "motion.unsubscribe",\n input: "device.motion.unsubscribe",\n output: "device.motion.unsubscribe",\n sdkTimeoutMs: operationWaiting.device["motion.unsubscribe"],\n transport: "native-host",\n facades: [{ path: "device.motion.subscribe", kind: "composite" }]\n },\n "haptics.trigger": {\n ...operationDefaults,\n capability: "device",\n operation: "haptics.trigger",\n input: "device.haptics.trigger",\n output: "device.haptics.trigger",\n sdkTimeoutMs: operationWaiting.device["haptics.trigger"],\n transport: "native-host",\n facades: [{ path: "device.haptics.trigger", kind: "direct" }]\n },\n "haptics.pattern": {\n ...operationDefaults,\n capability: "device",\n operation: "haptics.pattern",\n input: "device.haptics.pattern",\n output: "device.haptics.pattern",\n sdkTimeoutMs: operationWaiting.device["haptics.pattern"],\n transport: "native-host",\n facades: [{ path: "device.haptics.pattern", kind: "direct" }]\n },\n "haptics.stop": {\n ...operationDefaults,\n capability: "device",\n operation: "haptics.stop",\n input: "device.haptics.stop",\n output: "device.haptics.stop",\n sdkTimeoutMs: operationWaiting.device["haptics.stop"],\n transport: "native-host",\n facades: [{ path: "device.haptics.stop", kind: "direct" }]\n },\n "location.current": {\n ...operationDefaults,\n capability: "device",\n operation: "location.current",\n input: "device.location.current",\n output: "device.location.current",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n ...operationRead,\n facades: [{ path: "device.location.current", kind: "direct" }]\n },\n "share.open": {\n ...operationDefaults,\n capability: "device",\n operation: "share.open",\n input: "device.share.open",\n output: "device.share.open",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.share.open", kind: "direct" }]\n },\n "notifications.schedule": {\n ...operationDefaults,\n capability: "device",\n operation: "notifications.schedule",\n input: "device.notifications.schedule",\n output: "device.notifications.schedule",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.notifications.schedule", kind: "direct" }]\n },\n "notifications.list": {\n ...operationDefaults,\n capability: "device",\n operation: "notifications.list",\n input: "device.notifications.list",\n output: "device.notifications.list",\n sdkTimeoutMs: operationWaiting.device["notifications.list"],\n transport: "native-host",\n ...operationRead,\n facades: [{ path: "device.notifications.list", kind: "direct" }]\n },\n "notifications.cancel": {\n ...operationDefaults,\n capability: "device",\n operation: "notifications.cancel",\n input: "device.notifications.cancel",\n output: "device.notifications.cancel",\n sdkTimeoutMs: operationWaiting.device["notifications.cancel"],\n transport: "native-host",\n facades: [{ path: "device.notifications.cancel", kind: "direct" }]\n },\n "alarms.schedule": {\n ...operationDefaults,\n capability: "device",\n operation: "alarms.schedule",\n input: "device.alarms.schedule",\n output: "device.alarms.schedule",\n sdkTimeoutMs: operationWaiting.device.default,\n transport: "native-host",\n facades: [{ path: "device.alarms.schedule", kind: "direct" }]\n },\n "alarms.list": {\n ...operationDefaults,\n capability: "device",\n operation: "alarms.list",\n input: "device.alarms.list",\n output: "device.alarms.list",\n sdkTimeoutMs: operationWaiting.device["alarms.list"],\n transport: "native-host",\n ...operationRead,\n facades: [{ path: "device.alarms.list", kind: "direct" }]\n },\n "alarms.cancel": {\n ...operationDefaults,\n capability: "device",\n operation: "alarms.cancel",\n input: "device.alarms.cancel",\n output: "device.alarms.cancel",\n sdkTimeoutMs: operationWaiting.device["alarms.cancel"],\n transport: "native-host",\n facades: [{ path: "device.alarms.cancel", kind: "direct" }]\n }\n};\n\n// src/presence-operations.ts\nvar presenceOperationDefinitions = {\n "list": {\n ...operationDefaults,\n capability: "presence",\n operation: "list",\n input: "presence.list",\n output: "presence.list",\n sdkTimeoutMs: operationWaiting.default,\n ...publicRead,\n compatibility: "wire-alias",\n facades: []\n }\n};\n\n// src/notifications-operations.ts\nvar notificationsOperationDefinitions = {\n "send": {\n ...operationDefaults,\n capability: "notifications",\n operation: "send",\n input: "notifications.send",\n output: "notifications.send",\n sdkTimeoutMs: operationWaiting.notifications.default,\n idempotency: "durable-receipt",\n rateBucket: "experience-notifications",\n facades: [{ path: "notifications.send", kind: "direct" }]\n },\n "schedule": {\n ...operationDefaults,\n capability: "notifications",\n operation: "schedule",\n input: "notifications.schedule",\n output: "notifications.schedule",\n sdkTimeoutMs: operationWaiting.notifications.default,\n rateBucket: "experience-notifications",\n facades: [{ path: "notifications.schedule", kind: "direct" }]\n },\n "cancel": {\n ...operationDefaults,\n capability: "notifications",\n operation: "cancel",\n input: "notifications.cancel",\n output: "notifications.cancel",\n sdkTimeoutMs: operationWaiting.notifications.default,\n rateBucket: "experience-notifications",\n facades: [{ path: "notifications.cancel", kind: "direct" }]\n },\n "list": {\n ...operationDefaults,\n ...operationRead,\n capability: "notifications",\n operation: "list",\n input: "notifications.list",\n output: "notifications.list",\n sdkTimeoutMs: operationWaiting.notifications.default,\n rateBucket: "experience-notifications",\n facades: [{ path: "notifications.scheduled", kind: "direct" }]\n }\n};\n\n// src/inbox-operations.ts\nvar inboxOperationDefinitions = {\n "list": {\n ...operationDefaults,\n ...operationRead,\n capability: "inbox",\n operation: "list",\n input: "inbox.list",\n output: "inbox.list",\n sdkTimeoutMs: operationWaiting.inbox.default,\n rateBucket: "experience-inbox",\n facades: [{ path: "inbox.list", kind: "direct" }, { path: "inbox.watch", kind: "composite" }]\n },\n "ack": {\n ...operationDefaults,\n capability: "inbox",\n operation: "ack",\n input: "inbox.ack",\n output: "inbox.ack",\n sdkTimeoutMs: operationWaiting.inbox.default,\n rateBucket: "experience-inbox",\n facades: [{ path: "inbox.ack", kind: "direct" }]\n }\n};\n\n// src/email-operations.ts\nvar emailOperationDefinitions = {\n "send": {\n ...operationDefaults,\n capability: "email",\n operation: "send",\n input: "email.send",\n output: "email.send",\n sdkTimeoutMs: operationWaiting.email.default,\n spend: "may-spend",\n idempotency: "durable-receipt",\n rateBucket: "experience-email",\n facades: [{ path: "email.send", kind: "direct" }]\n }\n};\n\n// src/connectors-operations.ts\nvar connectorsOperationDefinitions = {\n status: { ...operationDefaults, capability: "connectors", operation: "status", input: "connectors.status", output: "connectors.status", sdkTimeoutMs: 3e4, idempotency: "read", rateBucket: "experience-connectors", facades: [{ path: "connectors.status", kind: "direct" }] },\n request: { ...operationDefaults, capability: "connectors", operation: "request", input: "connectors.request", output: "connectors.request", sdkTimeoutMs: null, rateBucket: "experience-connectors", facades: [{ path: "connectors.request", kind: "direct" }] },\n invoke: { ...operationDefaults, capability: "connectors", operation: "invoke", input: "connectors.invoke", output: "connectors.invoke", sdkTimeoutMs: 45e3, idempotency: "durable-receipt", rateBucket: "experience-connectors", facades: [{ path: "connectors.invoke", kind: "direct" }] },\n revoke: { ...operationDefaults, capability: "connectors", operation: "revoke", input: "connectors.revoke", output: "connectors.revoke", sdkTimeoutMs: 3e4, rateBucket: "experience-connectors", facades: [{ path: "connectors.revoke", kind: "direct" }] }\n};\n\n// src/backend-operations.ts\nvar backendOperationDefinitions = {\n request: {\n ...operationDefaults,\n capability: "backend",\n operation: "request",\n input: "backend.request",\n output: "backend.request",\n // Host waits at most 60 s for admission/execution; leave a margin for durable storage.\n idempotency: "durable-receipt",\n sdkTimeoutMs: 65e3,\n facades: []\n },\n get: {\n ...operationDefaults,\n ...operationRead,\n capability: "backend",\n operation: "get",\n input: "backend.get",\n output: "backend.get",\n sdkTimeoutMs: operationWaiting.default,\n facades: []\n },\n cancel: {\n ...operationDefaults,\n ...operationRead,\n capability: "backend",\n operation: "cancel",\n input: "backend.cancel",\n output: "backend.cancel",\n idempotency: "durable-receipt",\n sdkTimeoutMs: operationWaiting.default,\n facades: []\n }\n};\n\n// src/drive-operations.ts\nvar driveOperationDefinitions = {\n "save": {\n ...operationDefaults,\n capability: "drive",\n operation: "save",\n input: "drive.save",\n output: "drive.save",\n sdkTimeoutMs: operationWaiting.drive.save,\n transport: "binary-upload",\n facades: [{ path: "drive.save", kind: "direct" }]\n },\n "pick": {\n ...operationDefaults,\n capability: "drive",\n operation: "pick",\n input: "drive.pick",\n output: "drive.pick",\n sdkTimeoutMs: operationWaiting.drive.pick,\n transport: "host-document",\n ...operationRead,\n facades: [{ path: "drive.pick", kind: "direct" }]\n }\n};\n\n// src/link-operations.ts\nvar linkOperationDefinitions = {\n "open": {\n ...operationDefaults,\n ...publicRead,\n capability: "link",\n operation: "open",\n input: "link.open",\n output: "link.open",\n sdkTimeoutMs: operationWaiting.link.open,\n transport: "host-document",\n facades: [{ path: "link.open", kind: "direct" }]\n }\n};\n\n// src/library-operations.ts\nvar library = { ...operationDefaults, ...operationRead, capability: "library", transport: "host-document", sdkTimeoutMs: operationWaiting.library.default };\nvar libraryOperationDefinitions = {\n "experiences": { ...library, operation: "experiences", input: "library.experiences", output: "library.experiences", facades: [{ path: "library.experiences", kind: "direct" }] },\n "catalogue": { ...library, operation: "catalogue", input: "library.catalogue", output: "library.catalogue", facades: [{ path: "library.catalogue", kind: "direct" }] },\n "search": { ...library, operation: "search", input: "library.search", output: "library.search", facades: [{ path: "library.search", kind: "direct" }] },\n "bookmarks": { ...library, operation: "bookmarks", input: "library.bookmarks", output: "library.bookmarks", facades: [{ path: "library.bookmarks", kind: "direct" }] },\n "teams": { ...library, operation: "teams", input: "library.teams", output: "library.teams", facades: [{ path: "library.teams", kind: "direct" }] },\n "teamExperiences": { ...library, operation: "teamExperiences", input: "library.teamExperiences", output: "library.teamExperiences", facades: [{ path: "library.teamExperiences", kind: "direct" }] },\n "journal": { ...library, operation: "journal", input: "library.journal", output: "library.journal", facades: [{ path: "library.journal", kind: "direct" }] },\n "facets": { ...library, operation: "facets", input: "library.facets", output: "library.facets", facades: [{ path: "library.facets", kind: "direct" }] },\n "account": { ...library, operation: "account", input: "library.account", output: "library.account", facades: [{ path: "library.account", kind: "direct" }] },\n "icons": { ...library, operation: "icons", input: "library.icons", output: "library.icons", sdkTimeoutMs: operationWaiting.library.icons, facades: [{ path: "library.icons", kind: "direct" }] },\n "avatars": { ...library, operation: "avatars", input: "library.avatars", output: "library.avatars", sdkTimeoutMs: operationWaiting.library.avatars, facades: [{ path: "library.avatars", kind: "direct" }] },\n "open": { ...library, operation: "open", input: "library.open", output: "library.open", sdkTimeoutMs: operationWaiting.library.open, facades: [{ path: "library.open", kind: "direct" }] },\n "interfaces": { ...library, operation: "interfaces", input: "library.interfaces", output: "library.interfaces", facades: [{ path: "library.interfaces", kind: "direct" }] },\n "collections": { ...library, operation: "collections", input: "library.collections", output: "library.collections", facades: [{ path: "library.collections", kind: "direct" }] },\n "bookmark": { ...library, access: "contribute", idempotency: "host-defined", operation: "bookmark", input: "library.bookmark", output: "library.bookmark", facades: [{ path: "library.bookmark", kind: "direct" }] },\n "bookmarked": { ...library, operation: "bookmarked", input: "library.bookmarked", output: "library.bookmarked", facades: [{ path: "library.bookmarked", kind: "direct" }] },\n "prefetch": { ...library, operation: "prefetch", input: "library.prefetch", output: "library.prefetch", sdkTimeoutMs: operationWaiting.library.prefetch, facades: [{ path: "library.prefetch", kind: "direct" }] }\n};\nvar libraryOperations = Object.keys(libraryOperationDefinitions);\n\n// src/host-operations.ts\nvar host = { ...operationDefaults, capability: "experiences", transport: "host-document", sdkTimeoutMs: operationWaiting.experiences.host };\nvar hostOperationDefinitions = {\n "host.configure": { ...host, operation: "host.configure", input: "experiences.host.configure", output: "experiences.host.configure", facades: [{ path: "host.configure", kind: "direct" }] },\n "host.navigate": {\n ...host,\n operation: "host.navigate",\n input: "experiences.host.navigate",\n output: "experiences.host.navigate",\n facades: [{ path: "host.next", kind: "composite" }, { path: "host.previous", kind: "composite" }, { path: "host.goTo", kind: "composite" }, { path: "host.reload", kind: "composite" }]\n },\n "host.items": { ...host, ...operationRead, operation: "host.items", input: "experiences.host.items", output: "experiences.host.items", facades: [{ path: "host.items", kind: "composite" }] }\n};\nvar experiencesHostOperations = Object.keys(hostOperationDefinitions);\n\n// src/experiences-operations.ts\nvar experiences = { ...operationDefaults, capability: "experiences", transport: "host-document" };\nvar experiencesOperationDefinitions = {\n "available": { ...experiences, ...operationRead, operation: "available", input: "experiences.available", output: "experiences.available", sdkTimeoutMs: operationWaiting.experiences.default, facades: [{ path: "experiences.available", kind: "composite" }] },\n "call": { ...experiences, operation: "call", input: "experiences.call", output: "experiences.call", sdkTimeoutMs: operationWaiting.experiences.call, facades: [{ path: "experiences.call", kind: "composite" }] },\n "open": { ...experiences, ...operationRead, operation: "open", input: "experiences.open", output: "experiences.open", sdkTimeoutMs: operationWaiting.experiences.open, facades: [{ path: "experiences.open", kind: "composite" }] },\n "handle": { ...experiences, operation: "handle", input: "experiences.handle", output: "experiences.handle", sdkTimeoutMs: operationWaiting.experiences.handle, facades: [{ path: "experiences.handle", kind: "composite" }] },\n "pick": { ...experiences, operation: "pick", input: "experiences.pick", output: "experiences.pick", sdkTimeoutMs: operationWaiting.experiences.pick, facades: [{ path: "experiences.pick", kind: "composite" }] },\n ...hostOperationDefinitions\n};\nvar experiencesOperations = Object.keys(experiencesOperationDefinitions);\n\n// src/search-operations.ts\nvar reads = { ...operationDefaults, sdkTimeoutMs: operationWaiting.default, rateBucket: "experience-search" };\nvar writes = { ...operationDefaults, sdkTimeoutMs: operationWaiting.default, rateBucket: "experience-search-writes" };\nvar facades = [{ path: "search.index", kind: "composite" }];\nvar searchOperationDefinitions = {\n "save": { ...writes, capability: "search", operation: "save", input: "search.save", output: "search.save", idempotency: "compare-and-set", facades },\n "patch": { ...writes, capability: "search", operation: "patch", input: "search.patch", output: "search.patch", idempotency: "compare-and-set", facades },\n "remove": { ...writes, capability: "search", operation: "remove", input: "search.remove", output: "search.remove", facades },\n "visibility": { ...writes, capability: "search", operation: "visibility", input: "search.visibility", output: "search.visibility", facades },\n "locate": { ...writes, capability: "search", operation: "locate", input: "search.locate", output: "search.locate", facades },\n "mine": { ...reads, ...operationRead, capability: "search", operation: "mine", input: "search.mine", output: "search.mine", facades },\n "query": { ...reads, ...publicRead, capability: "search", operation: "query", input: "search.query", output: "search.query", facades },\n "get": { ...reads, ...publicRead, capability: "search", operation: "get", input: "search.get", output: "search.get", facades },\n "similar": { ...reads, ...publicRead, capability: "search", operation: "similar", input: "search.similar", output: "search.similar", facades },\n "forMe": { ...reads, ...operationRead, capability: "search", operation: "forMe", input: "search.forMe", output: "search.forMe", facades },\n "mark": { ...writes, capability: "search", operation: "mark", input: "search.mark", output: "search.mark", facades },\n "unmark": { ...writes, capability: "search", operation: "unmark", input: "search.unmark", output: "search.unmark", facades },\n "marks": { ...reads, ...operationRead, capability: "search", operation: "marks", input: "search.marks", output: "search.marks", facades },\n "block": { ...writes, capability: "search", operation: "block", input: "search.block", output: "search.block", facades },\n "unblock": { ...writes, capability: "search", operation: "unblock", input: "search.unblock", output: "search.unblock", facades },\n "upsert": { ...writes, capability: "search", operation: "upsert", input: "search.upsert", output: "search.upsert", idempotency: "compare-and-set", facades: [] },\n "delete": { ...writes, capability: "search", operation: "delete", input: "search.delete", output: "search.delete", facades: [] }\n};\nvar searchOperations = Object.keys(searchOperationDefinitions);\nvar searchBackendOnlyOperations = ["upsert", "delete"];\nvar searchFrontendOperations = searchOperations.filter((operation2) => !searchBackendOnlyOperations.includes(operation2));\n\n// src/machine-operations.ts\nvar waits = operationWaiting.machine;\nvar machine = { ...operationDefaults, sdkTimeoutMs: waits.default, rateBucket: "experience-machine" };\nvar stream = { ...machine, transport: "machine-host" };\nvar workspace = { ...machine, rateBucket: "experience-machine-workspace" };\nvar machineOperationDefinitions = {\n "list": { ...machine, ...operationRead, capability: "machine", operation: "list", input: "machine.list", output: "machine.list", facades: [{ path: "machine.list", kind: "direct" }] },\n "connect": { ...machine, capability: "machine", operation: "connect", input: "machine.connect", output: "machine.connect", sdkTimeoutMs: waits.connect, facades: [{ path: "machine.connect", kind: "direct" }] },\n "revoke": { ...machine, capability: "machine", operation: "revoke", input: "machine.revoke", output: "machine.revoke", facades: [{ path: "machine.revoke", kind: "direct" }] },\n "terminal.sessions": { ...machine, ...operationRead, capability: "machine", operation: "terminal.sessions", input: "machine.terminal.sessions", output: "machine.terminal.sessions", facades: [{ path: "machine.terminal.sessions", kind: "direct" }] },\n "terminal.create": { ...machine, capability: "machine", operation: "terminal.create", input: "machine.terminal.create", output: "machine.terminal.create", facades: [{ path: "machine.terminal.create", kind: "direct" }] },\n "terminal.close": { ...machine, capability: "machine", operation: "terminal.close", input: "machine.terminal.close", output: "machine.terminal.close", facades: [{ path: "machine.terminal.close", kind: "direct" }] },\n "terminal.rename": { ...machine, capability: "machine", operation: "terminal.rename", input: "machine.terminal.rename", output: "machine.terminal.rename", facades: [{ path: "machine.terminal.rename", kind: "direct" }] },\n "terminal.attach": { ...stream, capability: "machine", operation: "terminal.attach", input: "machine.terminal.attach", output: "machine.terminal.attach", sdkTimeoutMs: waits["terminal.attach"], facades: [{ path: "machine.terminal.attach", kind: "composite" }] },\n "terminal.watch": { ...stream, capability: "machine", operation: "terminal.watch", input: "machine.terminal.watch", output: "machine.terminal.watch", sdkTimeoutMs: waits["terminal.watch"], facades: [{ path: "machine.terminal.watch", kind: "composite" }] },\n "workspace.roots": { ...workspace, ...operationRead, capability: "machine", operation: "workspace.roots", input: "machine.workspace.roots", output: "machine.workspace.roots", facades: [{ path: "machine.workspace.roots", kind: "direct" }] },\n "workspace.discover": { ...workspace, ...operationRead, capability: "machine", operation: "workspace.discover", input: "machine.workspace.discover", output: "machine.workspace.discover", facades: [{ path: "machine.workspace.discover", kind: "direct" }] },\n "workspace.requestRoot": { ...workspace, capability: "machine", operation: "workspace.requestRoot", input: "machine.workspace.requestRoot", output: "machine.workspace.requestRoot", sdkTimeoutMs: waits["workspace.requestRoot"], facades: [{ path: "machine.workspace.requestRoot", kind: "direct" }] },\n "files.list": { ...workspace, ...operationRead, capability: "machine", operation: "files.list", input: "machine.files.list", output: "machine.files.list", facades: [{ path: "machine.files.list", kind: "direct" }] },\n "files.stat": { ...workspace, ...operationRead, capability: "machine", operation: "files.stat", input: "machine.files.stat", output: "machine.files.stat", facades: [{ path: "machine.files.stat", kind: "direct" }] },\n "files.read": { ...workspace, ...operationRead, capability: "machine", operation: "files.read", input: "machine.files.read", output: "machine.files.read", facades: [{ path: "machine.files.read", kind: "direct" }] },\n "files.write": { ...workspace, capability: "machine", operation: "files.write", input: "machine.files.write", output: "machine.files.write", facades: [{ path: "machine.files.write", kind: "direct" }] },\n "files.mkdir": { ...workspace, capability: "machine", operation: "files.mkdir", input: "machine.files.mkdir", output: "machine.files.mkdir", facades: [{ path: "machine.files.mkdir", kind: "direct" }] },\n "files.move": { ...workspace, capability: "machine", operation: "files.move", input: "machine.files.move", output: "machine.files.move", facades: [{ path: "machine.files.move", kind: "direct" }] },\n "files.trash": { ...workspace, capability: "machine", operation: "files.trash", input: "machine.files.trash", output: "machine.files.trash", facades: [{ path: "machine.files.trash", kind: "direct" }] },\n "files.find": { ...workspace, ...operationRead, capability: "machine", operation: "files.find", input: "machine.files.find", output: "machine.files.find", facades: [{ path: "machine.files.find", kind: "direct" }] },\n "files.search": { ...workspace, ...operationRead, capability: "machine", operation: "files.search", input: "machine.files.search", output: "machine.files.search", sdkTimeoutMs: waits["files.search"], facades: [{ path: "machine.files.search", kind: "direct" }] },\n "files.tree": { ...workspace, ...operationRead, capability: "machine", operation: "files.tree", input: "machine.files.tree", output: "machine.files.tree", sdkTimeoutMs: waits["files.tree"], facades: [{ path: "machine.files.tree", kind: "direct" }] },\n "git.status": { ...workspace, ...operationRead, capability: "machine", operation: "git.status", input: "machine.git.status", output: "machine.git.status", facades: [{ path: "machine.git.status", kind: "direct" }] },\n "git.diff": { ...workspace, ...operationRead, capability: "machine", operation: "git.diff", input: "machine.git.diff", output: "machine.git.diff", facades: [{ path: "machine.git.diff", kind: "direct" }] },\n "git.log": { ...workspace, ...operationRead, capability: "machine", operation: "git.log", input: "machine.git.log", output: "machine.git.log", facades: [{ path: "machine.git.log", kind: "direct" }] },\n "git.show": { ...workspace, ...operationRead, capability: "machine", operation: "git.show", input: "machine.git.show", output: "machine.git.show", facades: [{ path: "machine.git.show", kind: "direct" }] },\n "git.branches": { ...workspace, ...operationRead, capability: "machine", operation: "git.branches", input: "machine.git.branches", output: "machine.git.branches", facades: [{ path: "machine.git.branches", kind: "direct" }] },\n "git.stage": { ...workspace, capability: "machine", operation: "git.stage", input: "machine.git.stage", output: "machine.git.stage", facades: [{ path: "machine.git.stage", kind: "direct" }] },\n "git.unstage": { ...workspace, capability: "machine", operation: "git.unstage", input: "machine.git.unstage", output: "machine.git.unstage", facades: [{ path: "machine.git.unstage", kind: "direct" }] },\n "git.discard": { ...workspace, capability: "machine", operation: "git.discard", input: "machine.git.discard", output: "machine.git.discard", facades: [{ path: "machine.git.discard", kind: "direct" }] },\n "git.commit": { ...workspace, capability: "machine", operation: "git.commit", input: "machine.git.commit", output: "machine.git.commit", sdkTimeoutMs: waits["git.commit"], facades: [{ path: "machine.git.commit", kind: "direct" }] },\n "git.checkout": { ...workspace, capability: "machine", operation: "git.checkout", input: "machine.git.checkout", output: "machine.git.checkout", sdkTimeoutMs: waits["git.checkout"], facades: [{ path: "machine.git.checkout", kind: "direct" }] },\n "git.fetch": { ...workspace, capability: "machine", operation: "git.fetch", input: "machine.git.fetch", output: "machine.git.fetch", sdkTimeoutMs: waits["git.fetch"], facades: [{ path: "machine.git.fetch", kind: "direct" }] },\n "agents.capabilities": { ...workspace, ...operationRead, capability: "machine", operation: "agents.capabilities", input: "machine.agents.capabilities", output: "machine.agents.capabilities", facades: [{ path: "machine.agents.capabilities", kind: "direct" }] },\n "agents.list": { ...workspace, ...operationRead, capability: "machine", operation: "agents.list", input: "machine.agents.list", output: "machine.agents.list", facades: [{ path: "machine.agents.list", kind: "direct" }] },\n "agents.read": { ...workspace, ...operationRead, capability: "machine", operation: "agents.read", input: "machine.agents.read", output: "machine.agents.read", facades: [{ path: "machine.agents.read", kind: "direct" }] },\n "agents.events": { ...workspace, ...operationRead, capability: "machine", operation: "agents.events", input: "machine.agents.events", output: "machine.agents.events", sdkTimeoutMs: waits["agents.events"], facades: [{ path: "machine.agents.events", kind: "direct" }] },\n "agents.item": { ...workspace, ...operationRead, capability: "machine", operation: "agents.item", input: "machine.agents.item", output: "machine.agents.item", facades: [{ path: "machine.agents.item", kind: "direct" }] },\n "agents.start": { ...workspace, capability: "machine", operation: "agents.start", input: "machine.agents.start", output: "machine.agents.start", sdkTimeoutMs: waits["agents.start"], facades: [{ path: "machine.agents.start", kind: "direct" }] },\n "agents.send": { ...workspace, capability: "machine", operation: "agents.send", input: "machine.agents.send", output: "machine.agents.send", facades: [{ path: "machine.agents.send", kind: "direct" }] },\n "agents.configure": { ...workspace, capability: "machine", operation: "agents.configure", input: "machine.agents.configure", output: "machine.agents.configure", facades: [{ path: "machine.agents.configure", kind: "direct" }] },\n "agents.interrupt": { ...workspace, capability: "machine", operation: "agents.interrupt", input: "machine.agents.interrupt", output: "machine.agents.interrupt", facades: [{ path: "machine.agents.interrupt", kind: "direct" }] },\n "agents.respond": { ...workspace, capability: "machine", operation: "agents.respond", input: "machine.agents.respond", output: "machine.agents.respond", facades: [{ path: "machine.agents.respond", kind: "direct" }] },\n "agents.rename": { ...workspace, capability: "machine", operation: "agents.rename", input: "machine.agents.rename", output: "machine.agents.rename", facades: [{ path: "machine.agents.rename", kind: "direct" }] },\n "agents.close": { ...workspace, capability: "machine", operation: "agents.close", input: "machine.agents.close", output: "machine.agents.close", facades: [{ path: "machine.agents.close", kind: "direct" }] }\n};\nvar machineOperations = Object.keys(machineOperationDefinitions);\n\n// src/places-operations.ts\nvar placesOperationDefinitions = {\n list: {\n ...operationDefaults,\n ...operationRead,\n capability: "places",\n operation: "list",\n input: "places.list",\n output: "places.list",\n sdkTimeoutMs: operationWaiting.default,\n facades: [{ path: "places.list", kind: "direct" }]\n },\n publish: {\n ...operationDefaults,\n capability: "places",\n operation: "publish",\n input: "places.publish",\n output: "places.publish",\n sdkTimeoutMs: operationWaiting.default,\n facades: [{ path: "places.publish", kind: "direct" }]\n },\n remove: {\n ...operationDefaults,\n capability: "places",\n operation: "remove",\n input: "places.remove",\n output: "places.remove",\n sdkTimeoutMs: operationWaiting.default,\n facades: [{ path: "places.remove", kind: "direct" }]\n }\n};\n\n// src/excerpts-operations.ts\nvar excerptsOperationDefinitions = {\n list: {\n ...operationDefaults,\n ...operationRead,\n capability: "excerpts",\n operation: "list",\n input: "excerpts.list",\n output: "excerpts.list",\n sdkTimeoutMs: operationWaiting.default,\n facades: [{ path: "excerpts.list", kind: "direct" }]\n },\n publish: {\n ...operationDefaults,\n capability: "excerpts",\n operation: "publish",\n input: "excerpts.publish",\n output: "excerpts.publish",\n sdkTimeoutMs: operationWaiting.default,\n facades: [{ path: "excerpts.publish", kind: "direct" }]\n },\n remove: {\n ...operationDefaults,\n capability: "excerpts",\n operation: "remove",\n input: "excerpts.remove",\n output: "excerpts.remove",\n sdkTimeoutMs: operationWaiting.default,\n facades: [{ path: "excerpts.remove", kind: "direct" }]\n }\n};\n\n// src/profiles-operations.ts\nvar profiles = { ...operationDefaults, ...publicRead, capability: "profiles" };\nvar profilesOperationDefinitions = {\n me: {\n ...profiles,\n operation: "me",\n input: "profiles.me",\n output: "profiles.me",\n sdkTimeoutMs: operationWaiting.profiles.default,\n facades: [{ path: "profiles.me", kind: "direct" }]\n },\n get: {\n ...profiles,\n operation: "get",\n input: "profiles.get",\n output: "profiles.get",\n sdkTimeoutMs: operationWaiting.profiles.get,\n facades: [{ path: "profiles.get", kind: "direct" }]\n }\n};\nvar profilesOperations = Object.keys(profilesOperationDefinitions);\n\n// src/capability-operations.ts\nvar capabilityOperations = {\n automations: automationsOperationDefinitions,\n connectors: connectorsOperationDefinitions,\n backend: backendOperationDefinitions,\n ai: aiOperationDefinitions,\n assets: assetsOperationDefinitions,\n video: videoOperationDefinitions,\n hardware: hardwareOperationDefinitions,\n network: networkOperationDefinitions,\n multiplayer: multiplayerOperationDefinitions,\n device: deviceOperationDefinitions,\n presence: presenceOperationDefinitions,\n notifications: notificationsOperationDefinitions,\n inbox: inboxOperationDefinitions,\n email: emailOperationDefinitions,\n drive: driveOperationDefinitions,\n link: linkOperationDefinitions,\n library: libraryOperationDefinitions,\n experiences: experiencesOperationDefinitions,\n search: searchOperationDefinitions,\n machine: machineOperationDefinitions,\n places: placesOperationDefinitions,\n excerpts: excerptsOperationDefinitions,\n profiles: profilesOperationDefinitions\n};\nvar capabilityOperationList = Object.values(capabilityOperations).flatMap((group) => Object.values(group));\nvar storageEntries = storageOperationList.map((item) => ({ ...operationDefaults, ...item }));\nvar operationList = [...storageEntries, ...capabilityOperationList];\nfunction findOperation(capability, operation2) {\n return operationList.find((item) => item.capability === capability && item.operation === operation2);\n}\nvar mediaEntries = capabilityOperationList.filter((item) => item.mediaUsage);\nvar operationId = (item) => `${item.capability}.${item.operation}`;\nvar mediaUsageOperationIds = [...mediaUsageNeeds, ...mediaEntries.map(operationId)];\nvar mediaInvocationOperationIds = operationList.filter((item) => item.capability === "assets" || item.capability === "video" || item.capability === "ai" && item.needs === aiOperationDefinitions.generate.needs).map((item) => `${item.capability}.${item.operation}`);\nvar networkOperationIds = Object.values(networkOperationDefinitions).map((item) => `${item.capability}.${item.operation}`);\nvar audioEntries = Object.values(hardwareOperationDefinitions).filter((item) => item.rateBucket === "hardware-audio");\nvar networkEntries = Object.values(hardwareOperationDefinitions).filter((item) => item.rateBucket === "hardware-network");\nvar desktopEntries = Object.values(hardwareOperationDefinitions).filter((item) => item.rateBucket === "hardware-desktop");\nvar suffix = (prefix, operation2) => operation2.slice(prefix.length);\nvar hardwareAudioOperationNames = audioEntries.map((item) => suffix("audio.", item.operation));\nvar hardwareNetworkOperationNames = networkEntries.map((item) => suffix("network.", item.operation));\nvar hardwareDesktopOperationNames = desktopEntries.map((item) => suffix("desktop.", item.operation));\n\n// src/capability-deadlines.ts\nvar capabilityDeadlines = {\n default: operationWaiting.default,\n access: operationWaiting.access,\n spaces: operationWaiting.spaces,\n screens: operationWaiting.screens,\n multiplayer: operationWaiting.multiplayer,\n network: operationWaiting.network,\n assets: { default: operationWaiting.assets.default, uploadAttachment: assetsOperationDefinitions.uploadAttachment.sdkTimeoutMs, media: operationWaiting.assets.media },\n video: { default: operationWaiting.video.default, "clipping.uploadSource": videoOperationDefinitions["clipping.uploadSource"].sdkTimeoutMs, media: operationWaiting.video.media },\n hardware: { default: operationWaiting.hardware.default, "audio.transcribe": hardwareOperationDefinitions["audio.transcribe"].sdkTimeoutMs },\n ai: { default: operationWaiting.ai.default, decide: aiOperationDefinitions.decide.sdkTimeoutMs, "voice.start": aiOperationDefinitions["voice.start"].sdkTimeoutMs, "voice.state": aiOperationDefinitions["voice.state"].sdkTimeoutMs },\n device: {\n default: operationWaiting.device.default,\n availability: deviceOperationDefinitions.availability.sdkTimeoutMs,\n "haptics.trigger": deviceOperationDefinitions["haptics.trigger"].sdkTimeoutMs,\n "haptics.pattern": deviceOperationDefinitions["haptics.pattern"].sdkTimeoutMs,\n "haptics.stop": deviceOperationDefinitions["haptics.stop"].sdkTimeoutMs,\n "motion.unsubscribe": deviceOperationDefinitions["motion.unsubscribe"].sdkTimeoutMs,\n "camera.stream": deviceOperationDefinitions["camera.stream"].sdkTimeoutMs,\n "microphone.stream": deviceOperationDefinitions["microphone.stream"].sdkTimeoutMs,\n "notifications.list": deviceOperationDefinitions["notifications.list"].sdkTimeoutMs,\n "notifications.cancel": deviceOperationDefinitions["notifications.cancel"].sdkTimeoutMs,\n "alarms.list": deviceOperationDefinitions["alarms.list"].sdkTimeoutMs,\n "alarms.cancel": deviceOperationDefinitions["alarms.cancel"].sdkTimeoutMs\n },\n notifications: {\n default: operationWaiting.notifications.default,\n send: notificationsOperationDefinitions.send.sdkTimeoutMs,\n schedule: notificationsOperationDefinitions.schedule.sdkTimeoutMs,\n cancel: notificationsOperationDefinitions.cancel.sdkTimeoutMs,\n list: notificationsOperationDefinitions.list.sdkTimeoutMs\n },\n inbox: { default: operationWaiting.inbox.default, list: inboxOperationDefinitions.list.sdkTimeoutMs, ack: inboxOperationDefinitions.ack.sdkTimeoutMs },\n email: { default: operationWaiting.email.default, send: emailOperationDefinitions.send.sdkTimeoutMs },\n drive: { default: operationWaiting.drive.default, save: driveOperationDefinitions.save.sdkTimeoutMs, pick: driveOperationDefinitions.pick.sdkTimeoutMs },\n machine: {\n default: operationWaiting.machine.default,\n connect: machineOperationDefinitions.connect.sdkTimeoutMs,\n "terminal.attach": machineOperationDefinitions["terminal.attach"].sdkTimeoutMs,\n "terminal.watch": machineOperationDefinitions["terminal.watch"].sdkTimeoutMs,\n "workspace.requestRoot": machineOperationDefinitions["workspace.requestRoot"].sdkTimeoutMs,\n "files.search": machineOperationDefinitions["files.search"].sdkTimeoutMs,\n "files.tree": machineOperationDefinitions["files.tree"].sdkTimeoutMs,\n "git.commit": machineOperationDefinitions["git.commit"].sdkTimeoutMs,\n "git.fetch": machineOperationDefinitions["git.fetch"].sdkTimeoutMs,\n "git.checkout": machineOperationDefinitions["git.checkout"].sdkTimeoutMs,\n "agents.start": machineOperationDefinitions["agents.start"].sdkTimeoutMs,\n "agents.events": machineOperationDefinitions["agents.events"].sdkTimeoutMs\n },\n navigation: operationWaiting.navigation,\n library: {\n default: operationWaiting.library.default,\n icons: libraryOperationDefinitions.icons.sdkTimeoutMs,\n avatars: libraryOperationDefinitions.avatars.sdkTimeoutMs,\n open: libraryOperationDefinitions.open.sdkTimeoutMs,\n prefetch: libraryOperationDefinitions.prefetch.sdkTimeoutMs\n },\n experiences: {\n default: operationWaiting.experiences.default,\n call: experiencesOperationDefinitions.call.sdkTimeoutMs,\n handle: experiencesOperationDefinitions.handle.sdkTimeoutMs,\n open: experiencesOperationDefinitions.open.sdkTimeoutMs,\n pick: experiencesOperationDefinitions.pick.sdkTimeoutMs,\n "host.configure": experiencesOperationDefinitions["host.configure"].sdkTimeoutMs,\n "host.navigate": experiencesOperationDefinitions["host.navigate"].sdkTimeoutMs,\n "host.items": experiencesOperationDefinitions["host.items"].sdkTimeoutMs\n },\n places: { default: operationWaiting.default, list: placesOperationDefinitions.list.sdkTimeoutMs, publish: placesOperationDefinitions.publish.sdkTimeoutMs, remove: placesOperationDefinitions.remove.sdkTimeoutMs },\n excerpts: { default: operationWaiting.default, list: excerptsOperationDefinitions.list.sdkTimeoutMs, publish: excerptsOperationDefinitions.publish.sdkTimeoutMs, remove: excerptsOperationDefinitions.remove.sdkTimeoutMs },\n profiles: { default: operationWaiting.profiles.default, me: profilesOperationDefinitions.me.sdkTimeoutMs, get: profilesOperationDefinitions.get.sdkTimeoutMs }\n};\n\n// src/spaces-types.ts\nvar SPACES_CHANGED_EVENT = "spaces.changed";\nvar SPACE_INPUT_KEY = "__nocha_space";\nvar SPACE_REF_PATTERN = /^(?:personal|public|team:[1-9]\\d{0,3})$/;\nvar TEAM_REF_PATTERN = /^t_[A-Za-z0-9_-]{43}$/;\nfunction isTeamRef(value) {\n return typeof value === "string" && TEAM_REF_PATTERN.test(value);\n}\nfunction isSpaceTeam(value) {\n return typeof value === "object" && value !== null && isTeamRef(value.ref) && typeof value.name === "string";\n}\nfunction isSpaceRef(value) {\n return typeof value === "string" && SPACE_REF_PATTERN.test(value);\n}\n\n// src/screens-types.ts\nvar SCREEN_ID_PATTERN = /^[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*$/;\nvar SCREEN_ID_MAX_LENGTH = 64;\nvar isScreenId = (value) => typeof value === "string" && value.length <= SCREEN_ID_MAX_LENGTH && SCREEN_ID_PATTERN.test(value);\nvar record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);\nfunction isScreenResult(value) {\n return record(value) && (value.status === "cancelled" || value.status === "done" && Object.hasOwn(value, "value"));\n}\n\n// src/screens-operations.ts\nvar screensOperations = {\n open: { capability: "screens", operation: "open", transport: "host-document", sdkTimeoutMs: operationWaiting.screens.open },\n available: { capability: "screens", operation: "available", transport: "host-document", sdkTimeoutMs: operationWaiting.screens.default }\n};\n\n// src/types/voice-wire.ts\nvar voiceCallConnections = ["idle", "connecting", "connected", "reconnecting", "closing", "closed", "failed"];\nvar voiceCallMicrophones = ["off", "on"];\nvar voiceCallPlaybacks = ["idle", "playing"];\nvar voiceCallReasonings = ["idle", "running", "awaiting_confirmation"];\nvar voiceCallSettlements = ["pending", "settled", "incomplete"];\nvar VOICE_CALL_PERSONA_LIMITS = Object.freeze({ fictionalRole: 240, objective: 600, tone: 240, opening: 500, boundaries: 8, boundary: 300 });\n\n// src/link-types.ts\nvar LINK_URL_MAX_LENGTH = 2048;\nvar LINK_LABEL_MAX_LENGTH = 80;\n\n// src/library-types.ts\nvar LIBRARY_SURFACES = ["home", "bookmarks", "team", "search", "teams", "experiences"];\nvar LIBRARY_SHELVES = ["board", "mine", "recent", "followed"];\nvar LIBRARY_PAGE_MAX = 60;\nvar LIBRARY_PAGE_DEFAULT = 24;\nvar LIBRARY_QUERY_MAX_LENGTH = 120;\nvar LIBRARY_ICON_CODES_MAX = 24;\nvar LIBRARY_ICON_SIZES = [64, 128, 256];\nvar LIBRARY_AVATAR_HANDLES_MAX = 24;\nvar LIBRARY_HANDLE_PATTERN = /^[a-z0-9_]{3,32}$/;\nvar LIBRARY_PREFETCH_CODES_MAX = 6;\nvar LIBRARY_BOOKMARKED_CODES_MAX = 30;\nvar LIBRARY_CATALOGUE_TAGS_MAX = 3;\nvar LIBRARY_RECT_OFFSET_MAX = 1e4;\nvar LIBRARY_RECT_SIZE_MAX = 1e4;\nvar LIBRARY_INTERFACE_SOURCES = ["mine", "collection", "favorite", "catalogue"];\n\n// src/profiles-types.ts\nvar PROFILES_PARTICIPANTS_MAX = 50;\nvar PROFILE_PARTICIPANT_PATTERN = /^p_[A-Za-z0-9_-]{43}$/;\nvar PROFILE_AVATAR_SIZES = ["small", "medium"];\n\n// src/character-package-types.ts\nvar CHARACTER_PACKAGE_FORMAT = "nocha:character-package@1";\nvar CHARACTER_PACKAGE_IMAGE_MAX_BYTES = 4 * 1024 * 1024;\nvar CHARACTER_PACKAGE_CARD_MAX_BYTES = 15 * 1024;\nvar CHARACTER_PACKAGE_RIG_FORMATS = ["plateau-live.look@1", "plateau-live.puppet@1"];\n\n// src/experiences-types.ts\nvar EXPOSED_NAME_PATTERN = /^[a-z][a-z0-9-]{1,39}$/;\nvar EXPOSED_OPERATION_PATTERN = /^[a-z][a-zA-Z0-9]{0,39}(?:\\.[a-z][a-zA-Z0-9]{0,39}){0,3}$/;\nvar EXPERIENCE_CALL_JSON_MAX_BYTES = 256 * 1024;\nvar EXPERIENCE_CALL_FILE_MAX_BYTES = 8 * 1024 * 1024;\nvar EXPERIENCE_CALL_FILES_MAX_BYTES = 32 * 1024 * 1024;\nvar EXPERIENCE_OPEN_CODE_PATTERN = /^[A-Za-z0-9_-]{1,200}$/;\nvar EXPERIENCE_OPEN_URL_MAX_LENGTH = 2048;\n\n// src/host-types.ts\nvar HOST_ITEMS_MAX = 20;\nvar HOST_STAGE_MARGIN_MAX = 96;\nvar HOST_KEYWORD_MAX_LENGTH = 64;\nvar HOST_SOURCE_KINDS = ["catalogue", "follows", "keyword"];\nvar HOST_RAIL_MODES = ["shown", "hidden", "device"];\nvar HOST_RAIL_SIDES = ["left", "right"];\nvar HOST_TRANSITIONS = ["slide", "fade"];\nvar HOST_ITEM_KINDS = ["experience", "excerpt"];\nvar HOST_CHANGE_PHASES = ["arriving", "active"];\nvar HOST_DIRECTIONS = ["forward", "backward", "none"];\nvar HOST_CHANGE_EVENT = "experiences.host.change";\n\n// src/drive-types.ts\nvar DRIVE_TRANSFER_MAX_BYTES = 64 * 1024 * 1024;\nvar DRIVE_FOLDER_MAX_DEPTH = 30;\n\n// src/protocol.ts\nvar NOCHA_BRIDGE_PROTOCOL = "nocha.bridge.v4";\nvar browserCapabilities = ["presence", "state", "ai", "assets", "video", "hardware", "memory", "database", "multiplayer", "device", "network", "notifications", "inbox", "email", "backend", "automations", "connectors", "drive", "transfer", "search", "machine", "places", "link", "library", "excerpts", "experiences", "profiles"];\nvar assistantVoices = [\n "brise",\n "sillage",\n "marin",\n "quartz",\n "ripple",\n "vesper",\n "willow",\n "stone",\n "gleam",\n "meridian",\n "bossa",\n "tempo",\n "beacon",\n "delta",\n "cinder",\n "nuri",\n "juni",\n "flitz",\n "nira",\n "harema",\n "shida",\n "noeul"\n];\nvar imageSizeByAspectRatio = {\n "1:1": "1024x1024",\n "3:2": "1536x1024",\n "2:3": "1024x1536",\n "16:9": "1536x864",\n "9:16": "864x1536",\n "4:3": "1536x1152",\n "3:4": "1152x1536"\n};\nvar NOCHA_NAVIGATION_PROTOCOL = "nocha.navigation.v1";\nfunction unsafePathCharacters(value) {\n return [...value].some((character) => character === "\\\\" || character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);\n}\nfunction normalizeExperienceLocation(target, base2 = { pathname: "/", search: "", hash: "" }) {\n if (typeof target !== "string" && (target === null || typeof target !== "object" || typeof target.pathname !== "string" || typeof target.search !== "string" || typeof target.hash !== "string")) {\n throw new NochaError("invalid_request", "Expected an experience location");\n }\n const source2 = typeof target === "string" ? target : `${target.pathname}${target.search}${target.hash}`;\n if (!source2 || source2.trim() !== source2 || source2.length > 16384 || unsafePathCharacters(source2) || source2.startsWith("//") || /^[a-z][a-z\\d+.-]*:/i.test(source2)) throw new NochaError("invalid_request", "Expected an internal experience location");\n if (typeof target !== "string" && (!target.pathname.startsWith("/") || target.search !== "" && !target.search.startsWith("?") || target.hash !== "" && !target.hash.startsWith("#"))) throw new NochaError("invalid_request", "Invalid experience location");\n const url = new URL(source2, `https://experience.invalid${base2.pathname}${base2.search}${base2.hash}`);\n if (url.origin !== "https://experience.invalid" || url.username || url.password) throw new NochaError("invalid_request", "Expected an internal experience location");\n let path;\n try {\n path = decodeURIComponent(url.pathname);\n } catch {\n throw new NochaError("invalid_request", "Invalid experience pathname");\n }\n if (path === "/_nocha" || path.startsWith("/_nocha/") || unsafePathCharacters(path)) throw new NochaError("invalid_request", "Reserved experience pathname");\n for (const key2 of url.searchParams.keys()) if (key2.startsWith("__nocha_")) throw new NochaError("invalid_request", "Reserved reader parameter");\n return { pathname: url.pathname, search: url.search, hash: url.hash };\n}\nfunction isExperienceLocation(value) {\n if (!value || typeof value !== "object") return false;\n const location2 = value;\n if (typeof location2.pathname !== "string" || typeof location2.search !== "string" || typeof location2.hash !== "string") return false;\n try {\n const normalized = normalizeExperienceLocation(location2);\n return normalized.pathname === location2.pathname && normalized.search === location2.search && normalized.hash === location2.hash;\n } catch {\n return false;\n }\n}\nvar NOTIFICATION_SCHEDULE_MIN_LEAD_MS = 6e4;\nvar NOTIFICATION_SCHEDULE_MAX_LEAD_MS = 12096e5;\nvar NOTIFICATION_SCHEDULE_MAX_PENDING = 16;\n\n// src/capabilities.ts\nfunction deadlineMs(capability, operation2, input4) {\n const record6 = input4 !== null && typeof input4 === "object" && !Array.isArray(input4) ? input4 : {};\n if (capability === "ai" && operation2 === "generate") {\n const need = typeof record6.need === "string" ? record6.need : "";\n const vision = Array.isArray(record6.input_asset_ids) && record6.input_asset_ids.length > 0;\n const base2 = Object.hasOwn(generationDeadlines, need) ? generationDeadlines[need] : generationWaiting.fallbackMs;\n return (vision && need.startsWith("text.") ? Math.max(base2, generationWaiting.visionTextMs) : base2) + generationWaiting.sdkMarginMs;\n }\n const registered = findOperation(capability, operation2);\n if (registered?.sdkTimeoutMs != null) return registered.sdkTimeoutMs;\n const table = Object.hasOwn(capabilityDeadlines, capability) ? capabilityDeadlines[capability] : void 0;\n if (typeof table !== "object") return capabilityDeadlines.default;\n return (Object.hasOwn(table, operation2) ? table[operation2] : table.default) ?? capabilityDeadlines.default;\n}\n\n// src/hosting.ts\nvar hostedPath = /^\\/v1\\/experience\\/[0-9a-f-]{36}\\/(?:_public|_private|_frame)\\//;\nvar helloWaitMs = 3e3;\nvar helloCeilingMs = 6e4;\nvar state;\nvar meta = (name) => typeof document === "undefined" ? null : document.querySelector(`meta[name="${name}"]`)?.getAttribute("content") ?? null;\nfunction fromParent(event) {\n if (event.source != null) return event.source === window.parent;\n const reported = window.location.ancestorOrigins?.[0];\n return !reported || reported === "null" || event.origin === reported;\n}\nfunction detect() {\n if (typeof window === "undefined" || !window.parent || window.parent === window || meta("nocha-mode") === "standalone") return "standalone";\n const declared = meta(NOCHA_EXTERNAL_HOSTING_META);\n if (declared === "hosted" || declared === "external") return declared;\n const { protocol, pathname } = window.location;\n if (window.origin === "null" || protocol === "http:" || hostedPath.test(pathname) || parseExternalHostPatterns(meta(NOCHA_EXTERNAL_HOSTS_META)).some((pattern) => matchesExternalHostPattern(window.origin, pattern))) return "hosted";\n return protocol === "https:" ? "external" : "hosted";\n}\nfunction current() {\n if (state) return state;\n const value = detect();\n if (value !== "external") return state = { value, external: false, origin: null, queue: null, ready: Promise.resolve(value) };\n let settle;\n const external = state = { value, external: true, origin: null, queue: [], ready: new Promise((resolve2) => {\n settle = resolve2;\n }) };\n const codes2 = parseExternalCodes(meta(NOCHA_EXTERNAL_CODE_META));\n const trusted = new Map(codes2.flatMap((code) => externalFrameOrigins([code], parseExternalHostPatterns(meta(NOCHA_EXTERNAL_HOSTS_META))).map((origin) => [origin, code])));\n const timers = [];\n const end = (value2) => {\n const queued = external.queue;\n if (!queued) return;\n external.queue = null;\n external.value = value2;\n for (const timer of timers) clearTimeout(timer);\n window.removeEventListener("load", loaded);\n if (value2 === "standalone") window.removeEventListener("message", hello2);\n for (const message2 of value2 === "external" ? queued : []) {\n try {\n window.parent.postMessage(message2, external.origin);\n } catch (error) {\n console.error("Nocha message failed", error);\n }\n }\n settle(value2);\n };\n const hello2 = (event) => {\n const message2 = event.data;\n if (!fromParent(event) || !isExternalFrameMessage(message2) || message2.type !== "hello") return;\n if (external.origin === null) {\n if (!external.queue || trusted.get(event.origin) !== message2.code) return;\n external.origin = event.origin;\n } else if (event.origin !== external.origin) return;\n window.parent.postMessage({ protocol: NOCHA_EXTERNAL_PROTOCOL, type: "hello.ack", nonce: message2.nonce, sdkVersion: 4 }, external.origin);\n end("external");\n };\n const loaded = () => {\n timers.push(setTimeout(() => end("standalone"), helloWaitMs));\n };\n if (!codes2.length) {\n console.error(`Nocha: this page runs standalone. A self-hosted page names its experience before the SDK\'s script: <meta name="${NOCHA_EXTERNAL_CODE_META}" content="<code>">, several codes separated by spaces (lab, production).`);\n end("standalone");\n return external;\n }\n window.addEventListener("message", hello2);\n if (document.readyState === "complete") loaded();\n else window.addEventListener("load", loaded, { once: true });\n timers.push(setTimeout(() => end("standalone"), helloCeilingMs));\n window.addEventListener("click", openOutside);\n window.addEventListener("auxclick", openOutside);\n return external;\n}\nfunction openOutside(event) {\n if (event.defaultPrevented || event.type === "auxclick" && event.button !== 1 || !state?.origin || state.value !== "external") return;\n const link = event.composedPath().find((node) => node instanceof Element && (node.localName === "a" || node.localName === "area") && node.hasAttribute("href"));\n if (!link) return;\n const target = link.getAttribute("target") ?? "";\n let url;\n try {\n url = new URL(link.getAttribute("href"), document.baseURI);\n } catch {\n return;\n }\n const web = url.protocol === "http:" || url.protocol === "https:";\n if (!web && url.protocol !== "mailto:" && url.protocol !== "tel:" || url.username || url.password || url.href.length > 2048) return;\n if (web && url.origin === window.origin && target !== "_blank") return;\n if (target && target[0] !== "_" && Array.from(document.getElementsByTagName("iframe")).some((frame) => frame.name === target)) return;\n event.preventDefault();\n postToHost({ type: NOCHA_LINK_OPEN_EVENT, url: url.href });\n}\nvar currentHosting = () => current().value;\nvar hostingReady = () => current().ready;\nvar hostingPending = () => current().queue !== null;\nvar externalStandalone = () => {\n const { external, value } = current();\n return external && value === "standalone";\n};\nfunction postToHost(message2) {\n const { external, origin, queue } = current();\n if (!external) window.parent.postMessage(message2, "*");\n else if (origin) window.parent.postMessage(message2, origin);\n else queue?.push(message2);\n}\nfunction isFromHost(event) {\n const { external, origin } = current();\n if (!external) return event.source == null || event.source === window.parent;\n return origin !== null && event.origin === origin && fromParent(event);\n}\n\n// src/execution.ts\nvar runtimeCapabilities = [...browserCapabilities, "assistant", "voice", "access", "workspace", "spaces", "context", "navigation"];\nfunction getNochaMode() {\n if (typeof window === "undefined") return "standalone";\n if (typeof document !== "undefined" && document.querySelector(\'meta[name="nocha-mode"]\')?.getAttribute("content") === "standalone") return "standalone";\n return window.parent && window.parent !== window && !externalStandalone() ? "embedded" : "standalone";\n}\nvar experienceContextAvailable = false;\nvar spacesAnnounced = false;\nfunction markExperienceContextAvailable(spaces2 = false) {\n experienceContextAvailable = true;\n spacesAnnounced = spaces2;\n}\nvar capabilities = Object.freeze({\n has(capability) {\n if (capability === "context") return getNochaMode() === "embedded" && experienceContextAvailable;\n if (capability === "spaces") return getNochaMode() === "embedded" && experienceContextAvailable && spacesAnnounced;\n return runtimeCapabilities.includes(capability) && (capability === "navigation" ? typeof window !== "undefined" : getNochaMode() === "embedded");\n },\n get() {\n return Object.freeze(Object.fromEntries(runtimeCapabilities.map((capability) => [capability, capabilities.has(capability)])));\n }\n});\n\n// src/transport.ts\nvar LATE_PORT_MS = 10 * 6e4;\nfunction assertHostCapability(capability) {\n if (getNochaMode() === "standalone") throw new NochaError("bridge_unavailable", `${capability} requires the embedded Nocha reader`);\n}\nvar maxTimerMs = 2147483647;\nfunction requestProblem(capability, operation2, input4, options, files) {\n if (!bridgeCapabilities.has(capability)) return `Unknown capability ${String(capability)}`;\n if (typeof operation2 !== "string" || !operation2 || operation2.length > 100) return "The operation name must have 1 to 100 characters";\n if (!options || typeof options !== "object") return "Request options must be an object";\n if (options.usageId !== void 0 && !isUsageId(options.usageId)) return "The usage id is not a valid NOCHA.json usage id";\n if (options.idempotencyKey !== void 0 && !isIdempotencyKey(options.idempotencyKey)) return "The idempotency key must have 8 to 200 characters without control characters";\n if (!isPlainObject(input4)) return "The input must be a JSON object";\n const problem = jsonProblem(input4, 0, /* @__PURE__ */ new Set(), files);\n if (problem) return `The input is not JSON: ${problem}`;\n if (options.timeoutMs !== void 0 && (typeof options.timeoutMs !== "number" || !Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > maxTimerMs)) {\n return "timeoutMs must be a positive finite timer duration";\n }\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) return "signal must be an AbortSignal";\n return void 0;\n}\nfunction invokeBridgeResponse(capability, operation2, input4, options, withPort, lateResult, files = false) {\n try {\n assertHostCapability(capability);\n } catch (error) {\n return Promise.reject(error);\n }\n const problem = requestProblem(capability, operation2, input4, options, files);\n if (problem) return Promise.reject(new NochaError("invalid_request", problem));\n if (options.signal?.aborted) return Promise.reject(new NochaError("aborted", "Local bridge wait was aborted"));\n if (hostingPending()) return hostingReady().then(() => invokeBridgeResponse(capability, operation2, input4, options, withPort, lateResult, files));\n const timeoutMs = options.timeoutMs ?? deadlineMs(capability, operation2, input4);\n const requestId = crypto.randomUUID();\n const request2 = {\n protocol: NOCHA_BRIDGE_PROTOCOL,\n sdkVersion: 4,\n type: "invoke",\n requestId,\n capability,\n operation: operation2,\n ...options.usageId !== void 0 ? { usageId: options.usageId } : {},\n idempotencyKey: options.idempotencyKey ?? `${requestId.replaceAll("-", "")}:experience`,\n input: input4\n };\n return new Promise((resolve2, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n window.removeEventListener("message", onMessage);\n options.signal?.removeEventListener("abort", onAbort);\n };\n const fail = (error) => {\n cleanup();\n reject2(error);\n };\n const abandon = (error) => {\n fail(error);\n if (lateResult && !lateResult.signal.aborted) {\n const stopLate = () => {\n clearTimeout(lateTimer2);\n window.removeEventListener("message", onLate);\n lateResult.signal.removeEventListener("abort", stopLate);\n };\n const onLate = (event) => {\n if (!isFromHost(event) || !isRecord(event.data) || event.data.protocol !== NOCHA_BRIDGE_PROTOCOL || event.data.requestId !== requestId || event.data.type !== "result" && event.data.type !== "error") return;\n stopLate();\n if (event.data.type === "result") lateResult.onResult();\n else lateResult.onError(wireError(event.data.error));\n };\n const lateTimer2 = setTimeout(() => {\n stopLate();\n lateResult.onExpired();\n }, deadlineMs(capability, operation2, input4));\n window.addEventListener("message", onLate);\n lateResult.signal.addEventListener("abort", stopLate, { once: true });\n }\n if (!withPort) return;\n const late = (event) => {\n if (!isFromHost(event) || !isRecord(event.data) || event.data.requestId !== requestId) return;\n window.removeEventListener("message", late);\n clearTimeout(lateTimer);\n const port = event.ports[0];\n if (!port) return;\n try {\n port.postMessage({ type: "stop" });\n } catch {\n }\n port.close();\n };\n const lateTimer = setTimeout(() => window.removeEventListener("message", late), LATE_PORT_MS);\n window.addEventListener("message", late);\n };\n const onAbort = () => abandon(new NochaError("aborted", "Local bridge wait was aborted"));\n const onMessage = (event) => {\n if (!isFromHost(event)) return;\n const message2 = event.data;\n if (!isRecord(message2) || message2.protocol !== NOCHA_BRIDGE_PROTOCOL || message2.requestId !== requestId) return;\n if (message2.type !== "result" && message2.type !== "error") return;\n if (message2.type === "result") {\n if (withPort) {\n const port = event.ports[0];\n if (!port) {\n fail(new NochaError("invalid_result", "Nocha returned live media without its message port"));\n return;\n }\n cleanup();\n resolve2({ result: message2.result, port });\n return;\n }\n cleanup();\n resolve2(message2.result);\n return;\n }\n fail(wireError(message2.error));\n };\n const timer = setTimeout(() => abandon(new NochaError("invocation_timed_out", "Local bridge wait timed out")), timeoutMs);\n window.addEventListener("message", onMessage);\n options.signal?.addEventListener("abort", onAbort, { once: true });\n try {\n postToHost(request2);\n } catch (error) {\n fail(new NochaError("invalid_request", `The request cannot be sent to the Nocha host: ${error instanceof Error ? error.message : String(error)}`));\n }\n });\n}\nfunction invokeBridge(capability, operation2, input4 = {}, options = {}) {\n return invokeBridgeResponse(capability, operation2, input4, options, false);\n}\nfunction invokeBridgeWithLateResult(capability, operation2, input4, options, lateResult) {\n return invokeBridgeResponse(capability, operation2, input4, options, false, lateResult);\n}\nfunction invokeBridgeWithFiles(capability, operation2, input4, options = {}) {\n return invokeBridgeResponse(capability, operation2, input4, options, false, void 0, true);\n}\nfunction invokeBridgeWithPort(capability, operation2, input4 = {}, options = {}) {\n return invokeBridgeResponse(capability, operation2, input4, options, true);\n}\nfunction subscribeBridgeEvents(listener) {\n if (getNochaMode() === "standalone") return () => {\n };\n const onMessage = (event) => {\n if (!isFromHost(event) || !isRecord(event.data)) return;\n const message2 = event.data;\n if (message2.protocol !== NOCHA_BRIDGE_PROTOCOL || message2.type !== "event" || !isRecord(message2.event) || typeof message2.event.type !== "string") return;\n const sequence = message2.event.sequence;\n listener({\n type: message2.event.type,\n payload: message2.event.payload,\n ...typeof sequence === "number" && Number.isSafeInteger(sequence) && sequence >= 0 ? { sequence } : {}\n });\n };\n window.addEventListener("message", onMessage);\n return () => window.removeEventListener("message", onMessage);\n}\n\n// src/transfer-runtime.ts\nvar activated = false;\nvar enabled = false;\nvar lastDropAt = -Infinity;\nvar availabilityListeners = /* @__PURE__ */ new Set();\nvar hostListeners = /* @__PURE__ */ new Set();\nvar closeListeners = /* @__PURE__ */ new Set();\nvar hello = () => {\n try {\n postToHost({ protocol: NOCHA_BRIDGE_PROTOCOL, type: "event", event: { type: TRANSFER_HELLO_EVENT, payload: {} } });\n } catch {\n }\n};\nfunction activateTransfer() {\n if (activated || getNochaMode() === "standalone") return;\n activated = true;\n window.addEventListener("message", (event) => {\n if (!isFromHost(event)) return;\n const message2 = parseHostMessage(event.data);\n if (!message2) return;\n if (message2.type === "state") {\n setEnabled(message2.enabled);\n return;\n }\n for (const listener of [...hostListeners]) notifyListener(listener, message2);\n });\n window.addEventListener("pageshow", hello);\n window.addEventListener("pagehide", () => {\n for (const listener of [...closeListeners]) notifyListener(listener, void 0);\n });\n hello();\n}\nfunction setEnabled(value) {\n if (value === enabled) return;\n enabled = value;\n if (!value) for (const listener of [...closeListeners]) notifyListener(listener, void 0);\n for (const listener of [...availabilityListeners]) notifyListener(listener, value);\n}\nvar transferAvailable = () => enabled && getNochaMode() !== "standalone";\nfunction onTransferAvailability(listener) {\n availabilityListeners.add(listener);\n return () => {\n availabilityListeners.delete(listener);\n };\n}\nfunction onTransferHostMessage(listener) {\n hostListeners.add(listener);\n return () => {\n hostListeners.delete(listener);\n };\n}\nfunction onTransferClose(listener) {\n closeListeners.add(listener);\n return () => {\n closeListeners.delete(listener);\n };\n}\nfunction postTransfer(message2) {\n if (!transferAvailable()) return;\n try {\n postToHost(message2);\n } catch (error) {\n console.error("Nocha transfer message failed", error);\n }\n}\nfunction markTransferDrop() {\n lastDropAt = performance.now();\n}\nfunction consumeTransferDrop() {\n const recent = performance.now() - lastDropAt < TRANSFER_DROP_ACTIVATION_MS;\n lastDropAt = -Infinity;\n return recent;\n}\nvar isControl = (character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127;\nvar isOneLine = (value) => ![...value].some(isControl);\nvar toOneLine = (value) => [...value].map((character) => isControl(character) ? " " : character).join("");\nvar clampCoordinate = (value) => Math.max(-1e5, Math.min(1e5, Number.isFinite(value) ? value : 0));\nvar outcomes = /* @__PURE__ */ new Set(["dropped", "returned", "cancelled", "refused"]);\nvar targets = /* @__PURE__ */ new Set(["experience", "drive", "desktop"]);\nvar sourceKinds = /* @__PURE__ */ new Set(["experience", "drive", "device"]);\nvar isDragId = (value) => isString(value) && TRANSFER_DRAG_ID_PATTERN.test(value);\nvar isOptional = (value, check2) => value === void 0 || check2(value);\nvar isDimension = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\nfunction parseItem(value) {\n if (!isRecord(value) || !isString(value.id) || !TRANSFER_ITEM_ID_PATTERN.test(value.id) || !isString(value.name) || !value.name) return null;\n const type = normalizeTransferType(value.type);\n if (!type || !isOptional(value.size, isDimension) || !isOptional(value.durationMs, isDimension) || !isOptional(value.width, isDimension) || !isOptional(value.height, isDimension)) return null;\n const { size, durationMs, width, height } = value;\n return {\n id: value.id,\n name: value.name,\n type,\n ...size !== void 0 ? { size } : {},\n ...durationMs !== void 0 ? { durationMs } : {},\n ...width !== void 0 ? { width } : {},\n ...height !== void 0 ? { height } : {}\n };\n}\nfunction parseItems(value) {\n if (!Array.isArray(value) || value.length < 1 || value.length > TRANSFER_MAX_ITEMS) return null;\n const items = value.map(parseItem);\n return items.every((item) => item !== null) ? items : null;\n}\nfunction parseSource(value) {\n if (!isRecord(value) || !isString(value.kind) || !sourceKinds.has(value.kind) || !isString(value.title) || !isOptional(value.self, isBoolean)) return null;\n return { kind: value.kind, title: value.title, ...value.self === true ? { self: true } : {} };\n}\nfunction parseHostMessage(data) {\n if (!isRecord(data) || data.protocol !== NOCHA_TRANSFER_PROTOCOL || !isString(data.type)) return null;\n const protocol = NOCHA_TRANSFER_PROTOCOL;\n if (data.type === "state") return isBoolean(data.enabled) ? { protocol, type: "state", enabled: data.enabled } : null;\n const { dragId } = data;\n if (!isDragId(dragId)) return null;\n switch (data.type) {\n case "payload-request": {\n const { requestId, itemIds } = data;\n if (!isString(requestId) || requestId.length < 8 || requestId.length > 200 || !isArrayOf(itemIds, isString) || itemIds.length < 1 || itemIds.length > TRANSFER_MAX_ITEMS) return null;\n return { protocol, type: "payload-request", dragId, requestId, itemIds };\n }\n case "drag-result": {\n const { outcome, target, x, y, code } = data;\n if (!isString(outcome) || !outcomes.has(outcome) || !isOptional(x, isFiniteNumber) || !isOptional(y, isFiniteNumber) || !isOptional(code, isString) || target !== void 0 && !(isString(target) && targets.has(target))) return null;\n return {\n protocol,\n type: "drag-result",\n dragId,\n outcome,\n ...target !== void 0 ? { target } : {},\n ...x !== void 0 ? { x } : {},\n ...y !== void 0 ? { y } : {},\n ...code !== void 0 ? { code } : {}\n };\n }\n case "drag-over": {\n const items = parseItems(data.items);\n const source2 = parseSource(data.source);\n if (!isFiniteNumber(data.x) || !isFiniteNumber(data.y) || !isBoolean(data.own) || !items || !source2) return null;\n return { protocol, type: "drag-over", dragId, x: data.x, y: data.y, own: data.own, items, source: source2 };\n }\n case "drag-leave":\n return { protocol, type: "drag-leave", dragId };\n case "drop": {\n const source2 = parseSource(data.source);\n if (!(data.zone === null || isString(data.zone)) || !isString(data.role) || !isFiniteNumber(data.x) || !isFiniteNumber(data.y) || !source2 || !Array.isArray(data.items) || data.items.length < 1 || data.items.length > TRANSFER_MAX_ITEMS) return null;\n const items = [];\n for (const value of data.items) {\n const item = parseItem(value);\n if (!item || !isRecord(value) || !(value.blob instanceof Blob)) return null;\n const { drive } = value;\n if (drive !== void 0 && !(isRecord(drive) && isString(drive.id) && isArrayOf(drive.path, isString))) return null;\n items.push({ ...item, blob: value.blob, ...drive !== void 0 ? { drive: { id: drive.id, path: [...drive.path] } } : {} });\n }\n return { protocol, type: "drop", dragId, zone: data.zone, role: data.role, x: data.x, y: data.y, source: source2, items };\n }\n default:\n return null;\n }\n}\n\n// src/module.ts\nvar CALL_EVENT = "module.call";\nvar CANCEL_EVENT = "module.cancel";\nvar ANNOUNCE_EVENT = "module.announce";\nvar identifier = /^[a-z][a-z0-9_]{0,31}$/;\nvar uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nvar textMaxLength = 2e3;\nvar outputsMax = 8;\nvar hostTimeoutMs = 3e4;\nvar relayTimeoutMs = 12e4;\nvar progressIntervalMs = 1e3;\nvar handlers = /* @__PURE__ */ new Map();\nvar running = /* @__PURE__ */ new Map();\nvar unsubscribe = null;\nvar readyTimer = null;\nvar announced = "";\nvar solicited = false;\nvar readyInFlight = false;\nvar readyAgain = false;\nfunction moduleCallActive() {\n return running.size > 0;\n}\nfunction key(prefix, callId) {\n return `module-${prefix}:${callId}:${crypto.randomUUID().slice(0, 8)}`;\n}\nfunction send(operation2, input4, callId, timeoutMs = hostTimeoutMs) {\n return invokeBridge("module", operation2, input4, { idempotencyKey: key(operation2, callId ?? "ready"), timeoutMs });\n}\nfunction announce() {\n if (!solicited || readyTimer) return;\n readyTimer = setTimeout(() => {\n readyTimer = null;\n if (readyInFlight) {\n readyAgain = true;\n return;\n }\n const actions = [...handlers.keys()].sort();\n const set = actions.join(",");\n if (!actions.length || set === announced) return;\n readyInFlight = true;\n send("ready", { actions }).then(() => {\n announced = set;\n }, (error) => {\n warnOnce("module.ready", `the host did not take the announced actions (${isNochaError(error) ? error.code : "unknown_error"})`);\n }).finally(() => {\n readyInFlight = false;\n if (readyAgain) {\n readyAgain = false;\n announce();\n }\n });\n }, 0);\n}\nfunction scalarOrFile(value) {\n return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || typeof File !== "undefined" && value instanceof File;\n}\nfunction readCall(payload) {\n if (!isRecord(payload)) return null;\n const { callId, action, attempt, budgetMicrocredits, input: input4 } = payload;\n if (typeof callId !== "string" || !uuidPattern.test(callId) || typeof action !== "string" || !identifier.test(action)) return null;\n if (typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 0) return null;\n if (typeof budgetMicrocredits !== "string" || !/^(?:0|[1-9]\\d{0,17})$/.test(budgetMicrocredits)) return null;\n if (!isRecord(input4)) return null;\n const values = /* @__PURE__ */ Object.create(null);\n for (const [name, value] of Object.entries(input4)) {\n if (!identifier.test(name) || !scalarOrFile(value)) return null;\n values[name] = value;\n }\n return { callId, action, attempt, budgetMicrocredits, input: Object.freeze(values) };\n}\nfunction mediaHandle(kind, usage, id) {\n if (!isUsageId(usage)) throw new NochaError("invalid_request", "A module media output names a NOCHA.json usage");\n if (kind === "film") {\n if (typeof id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id)) throw new NochaError("invalid_request", "A film output needs its generation id");\n return Object.freeze({ kind, usage, generationId: id });\n }\n if (typeof id !== "string" || !uuidPattern.test(id)) throw new NochaError("invalid_request", "An asset output needs its asset id");\n return Object.freeze({ kind, usage, assetId: id });\n}\nfunction isMediaHandle(value) {\n if (!isUsageId(value.usage)) return false;\n return value.kind === "film" ? Object.keys(value).length === 3 && typeof value.generationId === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(value.generationId) : value.kind === "asset" && Object.keys(value).length === 3 && typeof value.assetId === "string" && uuidPattern.test(value.assetId);\n}\nfunction readOutput(output) {\n if (!isRecord(output)) throw new NochaError("invalid_result", "A module handler returns an object of declared outputs");\n if (Object.keys(output).length > outputsMax) throw new NochaError("invalid_result", `A module result holds at most ${outputsMax} outputs`);\n const values = {};\n for (const [name, value] of Object.entries(output)) {\n if (!identifier.test(name)) throw new NochaError("invalid_result", `Output ${name} is not a declared field name`);\n const valid = typeof value === "string" && value.length <= textMaxLength || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || isRecord(value) && isMediaHandle(value);\n if (!valid) throw new NochaError("invalid_result", `Output ${name} is not text, a number, a boolean or a media handle (call.film, call.asset)`);\n values[name] = isRecord(value) ? { ...value } : value;\n }\n return values;\n}\nfunction failure(error) {\n const record6 = isRecord(error) ? error : {};\n const wire3 = isNochaError(error) ? error.wireCode ?? error.code : record6.code;\n const code = typeof wire3 === "string" && CODE_PATTERN.test(wire3) ? wire3 : "module_failed";\n const text6 = error instanceof Error ? error.message : typeof error === "string" ? error : "";\n const retryable = Object.hasOwn(record6, "retryable") && record6.retryable === true;\n return { code, message: text6.trim().slice(0, 300).trim() || "The experience could not finish this call.", retryable };\n}\nfunction progressReporter(callId, signal) {\n let last = -Infinity;\n let pending3 = null;\n let timer = null;\n const flush = () => {\n timer = null;\n if (!pending3 || signal.aborted) return;\n const input4 = pending3;\n pending3 = null;\n last = Date.now();\n send("progress", { callId, ...input4 }, callId).catch(() => void 0);\n };\n return {\n report(message2, ratio) {\n if (signal.aborted) return;\n const text6 = String(message2 ?? "").trim().slice(0, 160).trim();\n const value = typeof ratio === "number" && Number.isFinite(ratio) ? Math.min(1, Math.max(0, ratio)) : void 0;\n pending3 = { ...text6 ? { message: text6 } : {}, ...value === void 0 ? {} : { ratio: value } };\n if (timer) return;\n const wait2 = last + progressIntervalMs - Date.now();\n if (wait2 <= 0) flush();\n else timer = setTimeout(flush, wait2);\n },\n stop() {\n if (timer) clearTimeout(timer);\n timer = null;\n pending3 = null;\n }\n };\n}\nasync function run({ callId, action, attempt, budgetMicrocredits, input: input4 }) {\n const handler = handlers.get(action);\n if (!handler) {\n await send("fail", { callId, code: "action_not_served", message: `This document does not serve ${action}`, retryable: true }, callId, relayTimeoutMs).catch(() => void 0);\n return;\n }\n const controller = new AbortController();\n running.set(callId, controller);\n const progress = progressReporter(callId, controller.signal);\n const call2 = Object.freeze({\n id: callId,\n action,\n attempt,\n budgetMicrocredits,\n input: input4,\n signal: controller.signal,\n progress: (message2, ratio) => progress.report(message2, ratio),\n film: (usage, generationId) => mediaHandle("film", usage, generationId),\n asset: (usage, assetId2) => mediaHandle("asset", usage, assetId2)\n });\n const report = (error) => send("fail", { callId, ...failure(error) }, callId, relayTimeoutMs).catch((sent) => console.warn("Nocha module: the failure was not delivered", sent));\n try {\n let output;\n try {\n output = readOutput(await handler(call2));\n } catch (error) {\n if (!controller.signal.aborted) await report(error);\n return;\n }\n if (controller.signal.aborted) return;\n progress.stop();\n try {\n await send("complete", { callId, output }, callId, relayTimeoutMs);\n } catch (error) {\n if (controller.signal.aborted || isNochaError(error) && error.code === "invocation_timed_out") {\n console.warn("Nocha module: the host did not confirm the result in time", error);\n return;\n }\n await report(error);\n }\n } finally {\n progress.stop();\n running.delete(callId);\n }\n}\nfunction subscribe() {\n if (unsubscribe) return;\n unsubscribe = subscribeBridgeEvents((event) => {\n if (event.type === ANNOUNCE_EVENT) {\n solicited = true;\n announced = "";\n announce();\n return;\n }\n if (event.type === CANCEL_EVENT) {\n const callId = isRecord(event.payload) ? event.payload.callId : void 0;\n if (typeof callId === "string") running.get(callId)?.abort(new NochaError("aborted", "The workflow run stopped this call"));\n return;\n }\n if (event.type !== CALL_EVENT) return;\n const call2 = readCall(event.payload);\n if (!call2) {\n warnOnce(CALL_EVENT, "the host sent a module call this SDK does not understand");\n return;\n }\n if (running.has(call2.callId)) return;\n void run(call2);\n });\n}\nvar moduleFacade = Object.freeze({\n handle(action, handler) {\n assertHostCapability("module");\n if (typeof action !== "string" || !identifier.test(action)) throw new NochaError("invalid_request", "An action id is lowercase letters, digits and _");\n if (typeof handler !== "function") throw new NochaError("invalid_request", "A module handler is a function");\n if (handlers.has(action)) throw new NochaError("invalid_request", `Another handler already serves ${action}`);\n handlers.set(action, handler);\n subscribe();\n announce();\n return () => {\n if (handlers.get(action) !== handler) return;\n handlers.delete(action);\n announce();\n };\n },\n get busy() {\n return running.size > 0;\n }\n});\n\n// src/access.ts\nfunction parseDataSpace(value) {\n if (!isRecord(value)) return null;\n const { kind, id } = value;\n return (kind === "public" || kind === "personal" || kind === "team") && isUuid(id) ? { kind, id } : null;\n}\nfunction parseSnapshot(value) {\n if (!isRecord(value) || !isBoolean(value.authenticated) || value.role !== "observer" && value.role !== "participant" || !isBoolean(value.participate) || !isBoolean(value.save) || !isBoolean(value.paid) || !isBoolean(value.server)) return null;\n const dataSpace = value.dataSpace === void 0 ? void 0 : parseDataSpace(value.dataSpace);\n if (dataSpace === null) return null;\n return {\n authenticated: value.authenticated,\n role: value.role,\n participate: value.participate,\n save: value.save,\n paid: value.paid,\n server: value.server,\n ...dataSpace ? { dataSpace } : {}\n };\n}\nfunction snapshot(value) {\n const parsed = parseSnapshot(value);\n if (!parsed) throw new NochaError("invalid_result", "Nocha returned an invalid access snapshot");\n return parsed;\n}\nvar access = Object.freeze({\n get: async () => snapshot(await invokeBridge("access", "get")),\n request: async (input4) => {\n assertHostCapability("access");\n if (typeof navigator !== "undefined" && navigator.userActivation && !navigator.userActivation.isActive && !moduleCallActive() && !consumeTransferDrop()) {\n throw new NochaError("user_action_required", "Request access from a button or another deliberate user action");\n }\n return snapshot(await invokeBridge("access", "request", input4));\n },\n onChange: (listener) => {\n assertHostCapability("access");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "An access listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== "access.changed") return;\n const parsed = parseSnapshot(event.payload);\n if (parsed) notifyListener(listener, parsed);\n else warnOnce("access.changed", "the host sent an access snapshot this SDK does not understand");\n });\n }\n});\n\n// src/speech-voices.ts\nvar legacySpeechHostCodes = /* @__PURE__ */ new Set(["client_update_required", "capability_denied"]);\nvar isLegacySpeechHost = (error) => isNochaError(error) && error.code === "client_update_required";\nvar voicePreviewMissingCodes = /* @__PURE__ */ new Set(["voice_preview_unavailable", "voice_unavailable", "generation_options_unavailable"]);\nvar stability = { key: "stability", kind: "number", ...speechSettingRanges.stability };\nvar steppedStability = { ...stability, values: [0, 0.5, 1] };\nvar similarityBoost = { key: "similarityBoost", kind: "number", ...speechSettingRanges.similarityBoost };\nvar style = { key: "style", kind: "number", ...speechSettingRanges.style };\nvar speed = { key: "speed", kind: "number", ...speechSettingRanges.speed };\nvar speakerBoost = { key: "useSpeakerBoost", kind: "switch" };\nvar speechModels = {\n eleven_v4: { bounds: [stability, similarityBoost], tags: true },\n eleven_v3: { bounds: [steppedStability], tags: true },\n eleven_multilingual_v2: { bounds: [stability, similarityBoost, style, speed, speakerBoost], tags: false }\n};\nvar unknownSpeechModel = { bounds: [stability, similarityBoost], tags: false };\nvar settingKeys = {\n stability: "stability",\n similarity_boost: "similarityBoost",\n style: "style",\n speed: "speed",\n use_speaker_boost: "useSpeakerBoost"\n};\nvar finite2 = (value) => typeof value === "number" && Number.isFinite(value);\nfunction declaredBound(key2, setting) {\n const range2 = speechSettingRanges[key2];\n const min = Math.max(range2.min, finite2(setting.min) ? setting.min : range2.min);\n const max = Math.min(range2.max, finite2(setting.max) ? setting.max : range2.max);\n if (min > max) return null;\n const steps = Array.isArray(setting.values) ? setting.values.filter(finite2) : [];\n const values = [...new Set(steps.filter((value) => value >= min && value <= max))].sort((a, b) => a - b);\n if (steps.length && !values.length) return null;\n return { key: key2, kind: "number", min, max, ...values.length ? { values } : {} };\n}\nfunction speechModelSpec(model) {\n const id = typeof model === "string" ? model : typeof model?.model === "string" ? model.model : "";\n const table = Object.hasOwn(speechModels, id) ? speechModels[id] : unknownSpeechModel;\n const declared = typeof model === "string" ? void 0 : model?.capabilities;\n if (!declared) return table;\n let bounds = table.bounds;\n if (Array.isArray(declared.voice_settings)) {\n const found = /* @__PURE__ */ new Map();\n for (const setting of declared.voice_settings) {\n const key2 = setting && Object.hasOwn(settingKeys, setting.key) ? settingKeys[setting.key] : void 0;\n if (!key2 || found.has(key2)) continue;\n const bound = key2 === "useSpeakerBoost" ? speakerBoost : declaredBound(key2, setting);\n if (bound) found.set(key2, bound);\n }\n bounds = Object.values(settingKeys).flatMap((key2) => found.get(key2) ?? []);\n }\n return { bounds, tags: typeof declared.speech_tags === "boolean" ? declared.speech_tags : table.tags };\n}\nvar speechModelSettings = (model) => [...speechModelSpec(model).bounds];\nvar speechModelSupportsTags = (model) => speechModelSpec(model).tags;\nvar SPEECH_TAG_MAX_LENGTH = 40;\nvar SPEECH_TAG_PATTERN = /\\[[^[\\]\\n]*\\]/gu;\nvar speechTagShape = /^\\[[a-z]+(?:[ ,\'-]+[a-z]+)*\\]$/u;\nvar tagRoots = (words2) => new Set(words2.split(" "));\nvar emotionTagRoots = tagRoots("afraid amuse angry annoy anxious appall bitter calm cold confident confuse cry curious delight determine disappoint disgust embarrass enthusiastic excite fearful frustrate happy hesitant hopeful impatient irritate joyful melancholy mischievous nervous playful relieve resign sad sarcastic startle surprise tease tense thoughtful uncertain worry bored dramatic proud smug");\nvar nonVerbalTagRoots = tagRoots("breath chuckle clear cry exhale gasp giggle gulp inhale laugh pause sigh snort sob swallow throat wheeze yawn");\nvar voiceQualityTagRoots = tagRoots("accent announcer build clear deadpan deep dry emotion energy gentle gradual gravelly high-pitched hurry light loud low lower mumble mutter narrator pace quick quiet robotic shout sing slow soft stammer stern tender tremble urgent voice warm whisper");\nvar vocalTagRoots = /* @__PURE__ */ new Set([...emotionTagRoots, ...nonVerbalTagRoots, ...voiceQualityTagRoots]);\nvar soundEffectTagRoots = tagRoots("alarm animal applause bark bell bird blast boing car cat clap crash crowd door dog engine explosion footstep glass gun gunshot horn knock lightning music phone rain ring room siren storm thunder traffic wave wind rumble whoosh");\nvar nonEnglishTagWords = tagRoots("chuchote colere crie doucement heureux lentement murmure pleure rapidement rit soupire triste enojado feliz grita lentamente llora rapido rie susurra tristeza");\nvar speechTags = (text6) => text6.match(SPEECH_TAG_PATTERN) ?? [];\nvar stripSpeechTags = (text6) => text6.normalize("NFC").replace(SPEECH_TAG_PATTERN, " ").replace(/\\s+/gu, " ").trim();\nvar tagWords = (tag2) => tag2.slice(1, -1).match(/[a-z]+(?:-[a-z]+)*/gu) ?? [];\nfunction wordForms(word2) {\n const forms = /* @__PURE__ */ new Set([word2, word2.replace(/s$/u, "")]);\n for (const suffix2 of ["ly", "ing", "ed", "es", "y"]) {\n if (!word2.endsWith(suffix2) || word2.length <= suffix2.length + 2) continue;\n const stem = word2.slice(0, -suffix2.length);\n forms.add(stem).add(`${stem}e`);\n if (stem.at(-1) === stem.at(-2)) forms.add(stem.slice(0, -1));\n }\n return forms;\n}\nvar tagHasRoot = (tag2, roots) => tagWords(tag2).some((word2) => [...wordForms(word2)].some((form) => roots.has(form)));\nvar isSpeechTag = (tag2) => tag2.length - 2 <= SPEECH_TAG_MAX_LENGTH && speechTagShape.test(tag2) && !tagWords(tag2).some((word2) => nonEnglishTagWords.has(word2));\nvar isEmotionSpeechTag = (tag2) => tagHasRoot(tag2, emotionTagRoots);\nvar isSoundEffectSpeechTag = (tag2) => tagHasRoot(tag2, soundEffectTagRoots);\nfunction isVocalSpeechTag(tag2) {\n const words2 = tagWords(tag2);\n const voice = (word2) => wordForms(word2).has("voice");\n if (!words2.some(voice)) return !isSoundEffectSpeechTag(tag2) && tagHasRoot(tag2, vocalTagRoots);\n const soundNoun = words2.some((word2) => soundEffectTagRoots.has(word2) || soundEffectTagRoots.has(word2.replace(/s$/u, "")));\n return !soundNoun || words2.some((word2) => !voice(word2) && tagHasRoot(`[${word2}]`, voiceQualityTagRoots));\n}\nfunction nearestValue(values, value) {\n let best = values[0];\n for (const candidate of values) if (Math.abs(candidate - value) < Math.abs(best - value)) best = candidate;\n return best;\n}\nfunction speechVoiceSettings(model, settings2) {\n const kept = {};\n for (const bound of speechModelSpec(model).bounds) {\n if (bound.kind === "switch") {\n if (typeof settings2.useSpeakerBoost === "boolean") kept.useSpeakerBoost = settings2.useSpeakerBoost;\n continue;\n }\n const value = settings2[bound.key];\n if (typeof value !== "number" || !Number.isFinite(value)) continue;\n const bounded2 = Math.min(bound.max, Math.max(bound.min, value));\n const admitted = bound.values?.length ? nearestValue(bound.values, bounded2) : bounded2;\n kept[bound.key] = Math.round(admitted * 1e3) / 1e3;\n }\n return kept;\n}\nfunction voiceFits(ref, model, models2 = []) {\n if (isSpeechVoiceAlias(ref.id)) return true;\n const id = typeof model === "string" ? model : typeof model?.model === "string" ? model.model : "";\n if (!ref.model || !id) return false;\n if (ref.model === id) return true;\n const groupOf2 = (wanted) => {\n const listed = typeof model !== "string" && model.model === wanted ? model : models2.find((item) => item.model === wanted);\n const group2 = listed?.capabilities?.voice_group;\n return typeof group2 === "string" && group2 ? group2 : void 0;\n };\n const group = groupOf2(id);\n return group !== void 0 && group === groupOf2(ref.model);\n}\nfunction voiceVerifiedFor(voice, model) {\n const models2 = Array.isArray(voice.models) ? voice.models : [];\n return voice.collection === "standard" || !models2.length || models2.includes(model);\n}\nfunction verifiedModels(listed) {\n const models2 = Array.isArray(listed) ? listed.filter(isSpeechModelId) : [];\n return [...new Set(models2)].sort().slice(0, 24);\n}\nvar line = (value, max) => (\n // eslint-disable-next-line no-control-regex -- a listed name drops C0 controls and DEL on purpose.\n [...value.replace(/[\\u0000-\\u001f\\u007f]+/gu, " ").replace(/\\s+/gu, " ").trim()].slice(0, max).join("").trim()\n);\nvar spokenSeparator = /\\s[-\u2013\u2014|]\\s|,|\\(/u;\nfunction spokenVoiceName(name) {\n const cleaned = typeof name === "string" ? line(name, 160) : "";\n const head = cleaned.split(spokenSeparator)[0]?.trim() ?? "";\n return [...head || cleaned].slice(0, 40).join("").trim();\n}\nvar unaccented = (value) => value.normalize("NFD").replace(/[\\u0300-\\u036f]/gu, "");\nvar traitWord = (value) => unaccented(line(typeof value === "string" ? value : "", 48)).toLowerCase().replace(/[_\\-/]/gu, " ").replace(/\\s+/gu, " ").trim();\nvar genders = {\n female: "female",\n femme: "female",\n feminin: "female",\n feminine: "female",\n woman: "female",\n girl: "female",\n f: "female",\n male: "male",\n homme: "male",\n masculin: "male",\n masculine: "male",\n man: "male",\n boy: "male",\n m: "male",\n neutral: "neutral",\n neutre: "neutral",\n "non binary": "neutral",\n nonbinary: "neutral",\n "non binaire": "neutral",\n androgynous: "neutral",\n androgyne: "neutral",\n unisex: "neutral",\n other: "neutral"\n};\nvar ages = {\n young: "young",\n jeune: "young",\n child: "young",\n enfant: "young",\n kid: "young",\n teen: "young",\n teenager: "young",\n adolescent: "young",\n youth: "young",\n "young adult": "young",\n "jeune adulte": "young",\n middle: "middle",\n "middle age": "middle",\n "middle aged": "middle",\n "age moyen": "middle",\n adult: "middle",\n adulte: "middle",\n mature: "middle",\n "age mur": "middle",\n old: "old",\n older: "old",\n age: "old",\n agee: "old",\n senior: "old",\n elder: "old",\n elderly: "old",\n vieux: "old",\n vieille: "old"\n};\nvar listedWord = (value) => line(typeof value === "string" ? value : "", 40).toLowerCase();\nfunction speechVoiceTraits(voice) {\n const gender = genders[traitWord(voice.gender)];\n const age = ages[traitWord(voice.age)];\n const accent = listedWord(voice.accent);\n const listedGender = gender ? "" : listedWord(voice.gender);\n const listedAge = age ? "" : listedWord(voice.age);\n const listed = { ...listedGender ? { gender: listedGender } : {}, ...listedAge ? { age: listedAge } : {} };\n return {\n ...gender ? { gender } : {},\n ...age ? { age } : {},\n ...accent ? { accent } : {},\n ...Object.keys(listed).length ? { listed } : {}\n };\n}\nvar languageTag = /^([a-z]{2,3})(?:[-_][a-z0-9]+)*$/u;\nfunction speechVoiceLanguages(listed) {\n const items = Array.isArray(listed) ? listed : [];\n const codes2 = [];\n for (const item of items) {\n const code = typeof item === "string" ? languageTag.exec(item.trim().toLowerCase())?.[1] : void 0;\n if (code && !codes2.includes(code)) codes2.push(code);\n if (codes2.length >= 12) break;\n }\n return codes2;\n}\nfunction speechVoiceDialects(listed) {\n const items = Array.isArray(listed) ? listed : [];\n const dialects = [];\n const seen = /* @__PURE__ */ new Set();\n for (const item of items) {\n if (dialects.length >= 24) break;\n if (item === null || typeof item !== "object") continue;\n const value = item;\n const language2 = typeof value.language === "string" ? languageTag.exec(value.language.trim().toLowerCase())?.[1] : void 0;\n if (!language2) continue;\n const accent = listedWord(value.accent);\n const key2 = `${language2}\\0${accent}`;\n if (seen.has(key2)) continue;\n seen.add(key2);\n const locale = typeof value.locale === "string" ? line(value.locale, 20) : "";\n const models2 = verifiedModels(value.models);\n dialects.push({\n language: language2,\n ...locale ? { locale } : {},\n ...accent ? { accent } : {},\n ...models2.length ? { models: models2 } : {},\n ...typeof value.preview === "boolean" ? { preview: value.preview } : {}\n });\n }\n return dialects;\n}\nvar listedText = (value, max) => typeof value === "string" ? line(value, max) : "";\nfunction speechVoiceEntry(voice, model) {\n if (!isSpeechVoiceId(voice.id)) return null;\n const name = line(typeof voice.name === "string" ? voice.name : "", 80) || voice.id;\n const description = line(typeof voice.description === "string" ? voice.description : "", 300);\n const multiplier = voice.price_multiplier;\n const models2 = verifiedModels(voice.models);\n const dialects = speechVoiceDialects(voice.dialects);\n const useCase = listedText(voice.use_case, 50), descriptive = listedText(voice.descriptive, 50);\n const category = listedText(voice.category, 50), locale = listedText(voice.locale, 20);\n const popularity = voice.popularity;\n const count2 = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;\n return {\n ref: { id: voice.id, model },\n name,\n spokenName: spokenVoiceName(name),\n collection: voice.collection === "library" ? "library" : "standard",\n ...isSpeechVoiceAlias(voice.alias) ? { alias: voice.alias } : {},\n languages: speechVoiceLanguages(voice.languages),\n traits: speechVoiceTraits(voice),\n ...description ? { description } : {},\n ...models2.length ? { models: models2 } : {},\n preview: voice.preview === true,\n premium: typeof multiplier === "number" && Number.isFinite(multiplier) && multiplier > 1 ? multiplier : null,\n ...useCase ? { useCase } : {},\n ...descriptive ? { descriptive } : {},\n ...category ? { category } : {},\n ...typeof voice.featured === "boolean" ? { featured: voice.featured } : {},\n ...count2(popularity) ? { popularity } : {},\n ...count2(voice.usage_characters_7d) ? { usage7d: voice.usage_characters_7d } : {},\n ...count2(voice.usage_characters_1y) ? { usage1y: voice.usage_characters_1y } : {},\n ...locale ? { locale } : {},\n ...dialects.length ? { dialects } : {}\n };\n}\nfunction voiceFavoriteEntry(favorite) {\n const collection = favorite.collection ?? (favorite.voice.startsWith("library:") ? "library" : "standard");\n return speechVoiceEntry({\n id: favorite.voice,\n name: favorite.name,\n languages: favorite.languages ?? [],\n collection,\n gender: favorite.gender,\n age: favorite.age,\n accent: favorite.accent,\n locale: favorite.locale,\n ...isSpeechVoiceAlias(favorite.voice) ? { alias: favorite.voice } : {},\n ...favorite.preview !== void 0 ? { preview: favorite.preview } : {},\n ...favorite.price_multiplier !== void 0 ? { price_multiplier: favorite.price_multiplier } : {}\n }, typeof favorite.model === "string" && isSpeechModelId(favorite.model) ? favorite.model : "");\n}\nfunction aliasVoiceEntries(model) {\n return speechVoiceAliases.map((alias) => ({\n ref: { id: alias, model },\n name: alias.charAt(0).toUpperCase() + alias.slice(1),\n spokenName: alias.charAt(0).toUpperCase() + alias.slice(1),\n collection: "standard",\n alias,\n languages: [],\n traits: {},\n // A historical name has no listed voice behind it, so no published sample: auditioning it costs a synthesis.\n preview: false,\n premium: null\n }));\n}\n\n// src/voice-listing.ts\nvar baseLanguage = (language2) => (language2 ?? "").trim().toLowerCase().split(/[-_]/u)[0];\nfunction rankVoiceEntries(entries, language2, defaultVoice, sort) {\n if (sort) return entries;\n const isDefault = (entry) => typeof defaultVoice === "string" ? entry.ref.id === defaultVoice : entry.ref.id === defaultVoice.id && entry.ref.model === defaultVoice.model;\n const score = (entry) => (language2 && entry.languages.includes(language2) ? 4 : 0) + (isDefault(entry) ? 2 : 0) + (entry.collection === "standard" ? 1 : 0);\n return entries.map((entry, index) => ({ entry, index, score: score(entry) })).sort((a, b) => b.score - a.score || a.index - b.index).map((item) => item.entry);\n}\nfunction chooseSpeechModel(models2, defaultModel, wanted) {\n if (wanted && (!models2.length || models2.some((model) => model.model === wanted))) return wanted;\n if (!models2.length || models2.some((model) => model.model === defaultModel)) return defaultModel;\n return models2[0].model;\n}\nvar facetFields = [\n ["language", "language"],\n ["locale", "locale"],\n ["query", "query"],\n ["gender", "gender"],\n ["age", "age"],\n ["accent", "accent"],\n ["category", "category"],\n ["useCases", "use_cases"],\n ["descriptives", "descriptives"],\n ["featured", "featured"],\n ["maxPriceMultiplier", "max_price_multiplier"],\n ["verifiedFor", "verified_for"]\n];\nfunction voiceFacetsInUse(input4) {\n const used = input4.collection === "library" ? ["collection"] : [];\n for (const [field3, facet2] of facetFields) {\n const value = input4[field3];\n if (Array.isArray(value) ? value.length : typeof value === "string" ? value.trim() : value !== void 0) used.push(facet2);\n }\n return used;\n}\nfunction modelAnswersFacets(model, used) {\n const declared = model?.capabilities?.voice_facets;\n if (!Array.isArray(declared)) return true;\n const multilingual = model?.capabilities?.multilingual === true;\n return used.every((facet2) => declared.includes(facet2) || multilingual && (facet2 === "language" || facet2 === "locale"));\n}\nfunction voicesInputFor(model, input4) {\n const capabilities2 = model?.capabilities;\n if (!capabilities2) return input4;\n const { collection, language: language2, locale, ...rest } = input4;\n const multilingual = capabilities2.multilingual === true;\n return {\n ...rest,\n ...collection !== void 0 && capabilities2.voice_catalogue !== "fixed" ? { collection } : {},\n ...language2 !== void 0 && !multilingual ? { language: language2 } : {},\n ...locale !== void 0 && !multilingual ? { locale } : {}\n };\n}\nvar modelAnswersInput = (model, input4) => !(input4.collection === "library" && model?.capabilities?.voice_catalogue === "fixed") && modelAnswersFacets(model, voiceFacetsInUse(voicesInputFor(model, input4)));\nvar isModelUnavailable = (model) => model?.availability === "unavailable";\nfunction aliasListingEntries(model, collection, query) {\n const wanted = (query ?? "").toLowerCase();\n const all = collection === "library" ? [] : aliasVoiceEntries(model);\n return wanted ? all.filter((entry) => entry.name.toLowerCase().includes(wanted)) : all;\n}\nvar verifiedPageLimit = 8;\nasync function readVoicePages(voices2, input4, walk) {\n const seen = new Set(walk.known);\n const entries = [];\n let model = walk.model;\n let defaultVoice = "";\n let cursor = walk.cursor;\n for (let pages = 1; ; pages += 1) {\n let page;\n try {\n page = await voices2({ ...input4, ...cursor ? { cursor } : {}, limit: walk.limit(entries.length) }, walk.options);\n } catch (error) {\n if (walk.legacyFallback && pages === 1 && isLegacySpeechHost(error)) return null;\n throw error;\n }\n model = page.model || model;\n defaultVoice ||= page.default_voice;\n const before = entries.length;\n for (const voice of page.voices) {\n const entry = speechVoiceEntry(voice, model);\n if (!entry || seen.has(entry.ref.id)) continue;\n seen.add(entry.ref.id);\n entries.push(entry);\n }\n cursor = page.next_cursor ?? void 0;\n if (!cursor || entries.length === before && !input4.verifiedFor) return { entries, model, defaultVoice, cursor: null };\n if (entries.length >= walk.until || input4.verifiedFor && pages >= verifiedPageLimit) {\n return { entries, model, defaultVoice, cursor };\n }\n }\n}\n\n// src/ai-voice-catalogue.ts\nvar pageLimit = 50;\nvar defaultVoiceCount = 60;\nvar voiceCeiling = 300;\nvar queryLimit = 200;\nvar cursorLimit = 256;\nvar bothCursor = /^(standard|library):(.*)$/su;\nvar modelsLimit = 16;\nvar familyLimit = 50;\nvar memoMs = 5 * 6e4;\nvar maxTimerMs2 = 2147483647;\nvar filterKeys = [\n "locale",\n "gender",\n "age",\n "accent",\n "category",\n "useCases",\n "descriptives",\n "featured",\n "sort",\n "maxPriceMultiplier"\n];\nvar invalid = (message2) => new NochaError("invalid_request", message2);\nfunction catalogueRequest(input4) {\n const value = input4 !== null && typeof input4 === "object" ? input4 : {};\n if (value.model !== void 0 && !isSpeechModelId(value.model)) throw invalid("model is not a valid identifier");\n const models2 = value.models;\n if (models2 !== void 0 && models2 !== "all" && !(Array.isArray(models2) && models2.length > 0 && models2.length <= modelsLimit && models2.every(isSpeechModelId))) {\n throw invalid(`models must be \'all\' or 1 to ${modelsLimit} model identifiers`);\n }\n if (value.family !== void 0 && (typeof value.family !== "string" || !value.family.trim() || value.family.length > familyLimit)) {\n throw invalid(`family must be a non-empty string of at most ${familyLimit} characters`);\n }\n const several = models2 !== void 0 || value.family !== void 0;\n if (several && value.model !== void 0) throw invalid("model reads one model: models and family read several, without it");\n if (several && value.cursor !== void 0) throw invalid("cursor resumes a single-model catalogue: models and family return no nextCursor");\n if (value.language !== void 0 && typeof value.language !== "string") throw invalid("language must be a string");\n if (value.collection !== void 0 && !voiceCatalogueCollections.includes(value.collection)) {\n throw invalid("collection must be standard, library, both or all");\n }\n if (value.query !== void 0 && typeof value.query !== "string") throw invalid("query must be a string");\n if (value.verifiedFor !== void 0 && !isSpeechModelId(value.verifiedFor)) throw invalid("verifiedFor is not a valid identifier");\n if (value.maxVoices !== void 0 && typeof value.maxVoices !== "number") throw invalid("maxVoices must be a number");\n if (value.cursor !== void 0 && (typeof value.cursor !== "string" || !value.cursor || value.cursor.length > cursorLimit)) {\n throw invalid("cursor must be a nextCursor this catalogue returned");\n }\n if (value.rankLanguage !== void 0 && typeof value.rankLanguage !== "string") throw invalid("rankLanguage must be a string");\n const filters = {};\n for (const key2 of filterKeys) {\n const filter = value[key2];\n if (filter !== void 0) filters[key2] = Array.isArray(filter) ? [...filter] : filter;\n }\n const query = [...(value.query ?? "").replace(/[\\u0000-\\u001f\\u007f]+/gu, " ").replace(/\\s+/gu, " ").trim()].slice(0, queryLimit).join("").trim();\n const wanted = value.maxVoices;\n const collection = value.collection === "all" ? "both" : value.collection;\n if (value.cursor && collection === "both" && !bothCursor.test(value.cursor)) throw invalid("cursor does not belong to a both catalogue");\n return {\n ...value.model !== void 0 ? { model: value.model } : {},\n ...value.models === "all" ? { models: "all" } : value.models ? { models: [...new Set(value.models)] } : {},\n ...value.family !== void 0 ? { family: value.family.trim().toLowerCase() } : {},\n ...value.language ? { language: value.language } : {},\n ...collection !== void 0 ? { collection } : {},\n ...query ? { query } : {},\n ...value.verifiedFor !== void 0 ? { verifiedFor: value.verifiedFor } : {},\n maxVoices: typeof wanted === "number" && Number.isFinite(wanted) ? Math.min(voiceCeiling, Math.max(1, Math.floor(wanted))) : defaultVoiceCount,\n ...value.cursor ? { cursor: value.cursor } : {},\n ...value.rankLanguage !== void 0 ? { rankLanguage: value.rankLanguage } : {},\n filters\n };\n}\nvar cacheKey = (request2) => JSON.stringify([\n request2.model ?? "",\n request2.language ?? "",\n request2.collection ?? "",\n request2.query ?? "",\n request2.verifiedFor ?? "",\n request2.maxVoices,\n request2.cursor ?? "",\n request2.rankLanguage ?? null,\n filterKeys.map((key2) => request2.filters[key2] ?? null),\n request2.models ?? null,\n request2.family ?? ""\n]);\nfunction catalogueCursor(collection, phase, cursor) {\n return collection === "both" ? `${phase}:${cursor}` : cursor;\n}\nfunction resumeAt(request2) {\n const given = request2.cursor;\n if (request2.collection !== "both") return { phase: request2.collection === "library" ? "library" : "standard", ...given ? { cursor: given } : {} };\n if (!given) return { phase: "standard" };\n const match = bothCursor.exec(given);\n return { phase: match?.[1] === "library" ? "library" : "standard", ...match?.[2] ? { cursor: match[2] } : {} };\n}\nfunction aliasCatalogue(model, listed, request2) {\n const kept = request2.cursor ? [] : aliasListingEntries(model, request2.collection, request2.query);\n const entries = kept.slice(0, request2.maxVoices);\n return {\n model,\n // No `default_voice` to read on such a host: the first historical name stands in, accepted by every model.\n defaultVoice: { id: entries[0]?.ref.id ?? speechVoiceAliases[0], model },\n models: listed?.models ?? [],\n entries,\n complete: entries.length === kept.length,\n source: "aliases",\n fallbackReason: "client_update_required"\n };\n}\nvar pagesInput = (request2, collection, model, spec) => voicesInputFor(spec, {\n ...model ? { model } : {},\n ...request2.language ? { language: request2.language } : {},\n ...collection ? { collection } : {},\n ...request2.query ? { query: request2.query } : {},\n ...request2.verifiedFor ? { verifiedFor: request2.verifiedFor } : {},\n ...request2.filters\n});\nasync function readModelVoices(readers, request2, model, budget2, spec, options) {\n const start = resumeAt(request2);\n const walk = (chosen2, cursor, gathered, known) => ({\n model: chosen2,\n ...cursor ? { cursor } : {},\n ...known ? { known } : {},\n until: budget2 - gathered,\n options,\n limit: (count2) => Math.min(pageLimit, Math.max(1, budget2 - gathered - count2))\n });\n const voices2 = (page, pageOptions) => readers.voices(page, pageOptions);\n const firstCollection = request2.collection === "both" ? start.phase : request2.collection;\n const first = await readVoicePages(voices2, pagesInput(request2, firstCollection, model, spec), { ...walk(model, start.cursor, 0), legacyFallback: true });\n if (!first) return null;\n const chosen = first.model || model;\n const entries = [...first.entries];\n let defaultVoice = first.defaultVoice;\n let nextCursor = first.cursor === null ? null : catalogueCursor(request2.collection, start.phase, first.cursor);\n const fixed = spec?.capabilities?.voice_catalogue === "fixed";\n if (request2.collection === "both" && start.phase === "standard" && first.cursor === null && !fixed) {\n if (entries.length < budget2) {\n const known = entries.map((entry) => entry.ref.id);\n const library2 = await readVoicePages(voices2, pagesInput(request2, "library", chosen, spec), walk(chosen, void 0, entries.length, known));\n entries.push(...library2.entries);\n defaultVoice ||= library2.defaultVoice;\n nextCursor = library2.cursor === null ? null : catalogueCursor(request2.collection, "library", library2.cursor);\n } else nextCursor = "library:";\n }\n return { model: chosen, defaultVoice, entries, nextCursor };\n}\nvar rankLanguageOf = (request2) => baseLanguage(request2.rankLanguage ?? request2.language);\nfunction chosenModels(listed, request2) {\n const all = listed?.models ?? [];\n const fallback = chooseSpeechModel(all, listed?.default_model ?? "", void 0);\n const named = request2.models === void 0 || request2.models === "all" ? null : request2.models;\n const offered = !all.length ? named ?? [fallback] : named ? named.filter((id) => all.some((model) => model.model === id)) : all.map((model) => model.model);\n const ids2 = [...new Set(offered.length ? offered : [fallback])].sort((a, b) => Number(b === fallback) - Number(a === fallback));\n const input4 = pagesInput(request2, request2.collection === "library" ? "library" : void 0, "");\n const modelOf = (id) => all.find((model) => model.model === id);\n return ids2.filter((id) => (!request2.family || modelOf(id)?.capabilities?.family?.toLowerCase() === request2.family) && !isModelUnavailable(modelOf(id)) && modelAnswersInput(modelOf(id), input4));\n}\nasync function readSeveral(readers, request2, listed, options) {\n const ids2 = chosenModels(listed, request2);\n const share = Math.ceil(request2.maxVoices / Math.max(1, ids2.length));\n const specOf = (id) => listed?.models.find((model2) => model2.model === id);\n const settled2 = await Promise.allSettled(ids2.map((id) => readModelVoices(readers, request2, id, share, specOf(id), options)));\n const failedModels = ids2.filter((_id, index) => settled2[index].status === "rejected");\n const firstFailure = settled2.find((read4) => read4.status === "rejected");\n if (firstFailure && failedModels.length === ids2.length) throw firstFailure.reason;\n const reads3 = settled2.flatMap((read4) => read4.status === "fulfilled" ? [read4.value] : []);\n const fallback = ids2[0] ?? chooseSpeechModel(listed?.models ?? [], listed?.default_model ?? "", void 0);\n const done = reads3.filter((read4) => read4 !== null);\n if (done.length < reads3.length) return { ...aliasCatalogue(fallback, listed, request2), ...failedModels.length ? { failedModels } : {} };\n const seen = /* @__PURE__ */ new Set();\n const merged = [];\n for (const entry of done.flatMap((read4) => read4.entries)) {\n const key2 = `${specOf(entry.ref.model)?.capabilities?.voice_group ?? entry.ref.model}\\0${entry.ref.id}`;\n if (seen.has(key2)) continue;\n seen.add(key2);\n merged.push(entry);\n }\n const model = done[0]?.model ?? fallback;\n const defaultVoice = { id: done[0]?.defaultVoice || speechVoiceAliases[0], model };\n const ranked = rankVoiceEntries(merged, rankLanguageOf(request2), defaultVoice, request2.filters.sort);\n const entries = ranked.slice(0, request2.maxVoices);\n return {\n model,\n defaultVoice,\n models: listed?.models ?? [],\n entries,\n complete: !failedModels.length && entries.length === ranked.length && done.every((read4) => read4.nextCursor === null),\n source: "listed",\n ...failedModels.length ? { failedModels } : {}\n };\n}\nasync function readCatalogue(readers, request2, options) {\n let listed = null;\n try {\n listed = await readers.models({ need: "audio.synthesize" }, options);\n } catch (error) {\n if (!isLegacySpeechHost(error)) throw error;\n }\n if (request2.models !== void 0 || request2.family !== void 0) return readSeveral(readers, request2, listed, options);\n const model = chooseSpeechModel(listed?.models ?? [], listed?.default_model ?? "", request2.model);\n const spec = listed?.models.find((item) => item.model === model);\n const read4 = await readModelVoices(readers, request2, model, request2.maxVoices, spec, options);\n if (!read4) return aliasCatalogue(model, listed, request2);\n return {\n model: read4.model,\n defaultVoice: { id: read4.defaultVoice, model: read4.model },\n models: listed?.models ?? [],\n entries: rankVoiceEntries(read4.entries, rankLanguageOf(request2), read4.defaultVoice, request2.filters.sort),\n complete: read4.nextCursor === null,\n ...read4.nextCursor !== null ? { nextCursor: read4.nextCursor } : {},\n source: "listed"\n };\n}\nfunction waitOptions(options) {\n const { signal, timeoutMs } = options ?? {};\n if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > maxTimerMs2)) {\n throw invalid("timeoutMs must be a positive finite timer duration");\n }\n if (signal !== void 0 && !(signal instanceof AbortSignal)) throw invalid("signal must be an AbortSignal");\n return { ...signal ? { signal } : {}, ...timeoutMs !== void 0 ? { timeoutMs } : {} };\n}\nfunction raceAbort(shared, { signal, timeoutMs }, leave) {\n if (signal?.aborted) {\n leave(true);\n return Promise.reject(new NochaError("aborted", "Local voice catalogue wait was aborted"));\n }\n return new Promise((resolve2, reject2) => {\n let done = false;\n let timer;\n const finish = (gaveUp, settle) => {\n if (done) return;\n done = true;\n signal?.removeEventListener("abort", onAbort);\n clearTimeout(timer);\n leave(gaveUp);\n settle();\n };\n const onAbort = () => finish(true, () => reject2(new NochaError("aborted", "Local voice catalogue wait was aborted")));\n if (timeoutMs !== void 0) {\n timer = setTimeout(() => finish(true, () => reject2(new NochaError("invocation_timed_out", "Local voice catalogue wait timed out"))), timeoutMs);\n }\n signal?.addEventListener("abort", onAbort, { once: true });\n shared.then((value) => finish(false, () => resolve2(value)), (error) => finish(false, () => reject2(error)));\n });\n}\nfunction createVoiceCatalogue(readers) {\n const memos = /* @__PURE__ */ new Map();\n const forget = (key2, memo) => {\n if (memos.get(key2) === memo) memos.delete(key2);\n };\n return async (input4, options) => {\n const request2 = catalogueRequest(input4);\n const wait2 = waitOptions(options);\n const key2 = cacheKey(request2);\n let memo = memos.get(key2);\n if (memo?.settledAt != null && (input4?.refresh === true || Date.now() - memo.settledAt >= memoMs)) {\n forget(key2, memo);\n memo = void 0;\n }\n if (!memo) {\n const stop = new AbortController();\n const created = { reading: readCatalogue(readers, request2, { signal: stop.signal }), settledAt: null, waiters: 0, stop };\n created.reading.then(() => {\n created.settledAt = Date.now();\n }, () => forget(key2, created));\n memos.set(key2, created);\n memo = created;\n }\n const joined = memo;\n joined.waiters += 1;\n return raceAbort(joined.reading, wait2, (gaveUp) => {\n joined.waiters -= 1;\n if (gaveUp && !joined.waiters && joined.settledAt === null) {\n forget(key2, joined);\n joined.stop.abort();\n }\n });\n };\n}\n\n// src/fault.ts\nfunction invalid2(message2) {\n return new NochaError("invalid_request", message2);\n}\nfunction invalidResult(message2) {\n return new NochaError("invalid_result", message2);\n}\n\n// src/generation-input.ts\nvar supportedNeeds = new Set(aiGenerateNeeds);\nvar mediaNeeds = new Set(mediaResultNeeds);\nfunction isMicrocredits(value) {\n return typeof value === "string" && /^[1-9]\\d*$/.test(value);\n}\nfunction isMediaNeed(need) {\n return mediaNeeds.has(need);\n}\nfunction text(value, field3) {\n if (typeof value !== "string" || !value.trim()) throw invalid2(`${field3} must be a non-empty string`);\n return value.trim();\n}\nfunction optionalString(value, field3) {\n if (value !== void 0 && typeof value !== "string") throw invalid2(`${field3} must be a string`);\n}\nvar modelPattern = SPEECH_MODEL_ID_PATTERN;\nvar voicePattern = SPEECH_VOICE_ID_PATTERN;\nvar languagePattern = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;\nfunction matching(value, pattern, field3) {\n if (typeof value !== "string" || !pattern.test(value)) throw invalid2(`${field3} is not a valid identifier`);\n return value;\n}\nfunction optionalNumber(value, field3) {\n if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value))) throw invalid2(`${field3} must be a finite number`);\n}\nfunction assetIds(value, field3, required) {\n if (value === void 0 && !required) return void 0;\n if (!Array.isArray(value) || !value.every(isUuid) || required && !value.length) throw invalid2(`${field3} must list authorized asset ids`);\n return value;\n}\nfunction singleSource(value) {\n const ids2 = assetIds(value, "inputAssetIds", true);\n if (ids2.length !== 1) throw invalid2("inputAssetIds must contain exactly one authorized source asset");\n return ids2;\n}\nvar voiceSettingFields = {\n stability: "stability",\n similarityBoost: "similarity_boost",\n style: "style",\n speed: "speed"\n};\nfunction voiceSettings(value) {\n if (value === void 0) return {};\n if (!isRecord(value)) throw invalid2("voiceSettings must be an object");\n const unknown = Object.entries(value).find(([key2, setting]) => setting !== void 0 && key2 !== "useSpeakerBoost" && !Object.hasOwn(speechSettingRanges, key2));\n if (unknown) throw invalid2(`voiceSettings.${unknown[0]} is not a voice setting`);\n const settings2 = {};\n for (const [key2, field3] of Object.entries(voiceSettingFields)) {\n const { min, max } = speechSettingRanges[key2];\n const setting = value[key2];\n if (setting === void 0) continue;\n if (typeof setting !== "number" || !Number.isFinite(setting) || setting < min || setting > max) throw invalid2(`voiceSettings.${key2} must be a number from ${min} to ${max}`);\n settings2[field3] = setting;\n }\n if (value.useSpeakerBoost !== void 0) {\n if (typeof value.useSpeakerBoost !== "boolean") throw invalid2("voiceSettings.useSpeakerBoost must be a boolean");\n settings2.use_speaker_boost = value.useSpeakerBoost;\n }\n return Object.keys(settings2).length ? { voice_settings: settings2 } : {};\n}\nfunction responseFormat(schema, schemaName, fallback) {\n if (!isRecord(schema)) throw invalid2("schema must be a JSON schema object");\n optionalString(schemaName, "schemaName");\n return { type: "json_schema", name: schemaName ?? fallback, schema, strict: true };\n}\nfunction budget(input4) {\n if (input4.quoteId !== void 0 && !isUuid(input4.quoteId)) throw invalid2("quoteId must be a generation quote id");\n if (input4.maximumCostMicrocredits !== void 0 && !isMicrocredits(input4.maximumCostMicrocredits)) throw invalid2("maximumCostMicrocredits must be a positive integer string");\n return {\n ...input4.quoteId ? { quote_id: input4.quoteId } : {},\n ...input4.maximumCostMicrocredits !== void 0 ? { maximum_cost_microcredits: input4.maximumCostMicrocredits } : {}\n };\n}\nfunction policy(input4) {\n optionalString(input4.generationUsage, "generationUsage");\n return {\n ...input4.effort !== void 0 ? { effort: input4.effort } : {},\n ...input4.generationUsage ? { generation_usage: input4.generationUsage } : {},\n ...budget(input4)\n };\n}\nfunction aiGenerateWire(input4) {\n if (!isRecord(input4) || typeof input4.need !== "string" || !supportedNeeds.has(input4.need)) throw invalid2("need must be a supported generation need");\n const value = input4;\n const need = value.need;\n switch (need) {\n case "text.short":\n case "text.chat":\n case "text.long":\n case "text.structured": {\n const ids2 = assetIds(value.inputAssetIds, "inputAssetIds", false);\n return {\n ...policy(value),\n ...value.desiredLength ? { desired_length: value.desiredLength } : {},\n prompt: text(value.prompt, "prompt"),\n need,\n ...need === "text.structured" ? { response_format: responseFormat(value.schema, value.schemaName, "experience_analysis") } : {},\n ...ids2 ? { input_asset_ids: ids2 } : {}\n };\n }\n case "web.research": {\n if (!Array.isArray(value.allowedDomains) || !value.allowedDomains.every((domain) => typeof domain === "string")) throw invalid2("allowedDomains must list hostnames");\n if (typeof value.maxToolCalls !== "number" || !Number.isInteger(value.maxToolCalls)) throw invalid2("maxToolCalls must be an integer");\n return {\n ...policy(value),\n prompt: text(value.prompt, "prompt"),\n need,\n response_format: responseFormat(value.schema, value.schemaName, "web_research"),\n allowed_domains: value.allowedDomains.map((domain) => domain.trim().toLowerCase()),\n max_tool_calls: value.maxToolCalls\n };\n }\n case "audio.synthesize":\n if (value.share !== void 0 && value.share !== "experience") throw invalid2("share must be \'experience\'");\n return {\n ...policy(value),\n prompt: text(value.prompt, "prompt"),\n need,\n ...value.language ? { language: matching(value.language, languagePattern, "language") } : {},\n ...value.voice ? { voice_id: matching(value.voice, voicePattern, "voice") } : {},\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...voiceSettings(value.voiceSettings),\n ...value.share !== void 0 ? { share: value.share } : {}\n };\n case "audio.transcribe":\n if (value.audioDataUrl === void 0 && value.durationSeconds === void 0 && value.inputAssetIds === void 0) throw invalid2("audioDataUrl must be an audio data URL");\n if (value.audioDataUrl !== void 0 && (typeof value.audioDataUrl !== "string" || !value.audioDataUrl.startsWith("data:"))) throw invalid2("audioDataUrl must be an audio data URL");\n optionalNumber(value.durationSeconds, "durationSeconds");\n optionalString(value.language, "language");\n optionalString(value.prompt, "prompt");\n return {\n ...policy(value),\n need,\n ...value.audioDataUrl !== void 0 ? { audio_data_url: value.audioDataUrl } : {},\n ...value.inputAssetIds !== void 0 ? { input_asset_ids: singleSource(value.inputAssetIds) } : {},\n ...value.durationSeconds !== void 0 ? { duration_seconds: value.durationSeconds } : {},\n ...value.language ? { language: value.language } : {},\n ...value.prompt ? { prompt: value.prompt } : {},\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {}\n };\n case "audio.generate":\n optionalNumber(value.durationSeconds, "durationSeconds");\n if (value.instrumental !== void 0 && typeof value.instrumental !== "boolean") throw invalid2("instrumental must be a boolean");\n if (value.instrumental && value.lyrics != null) throw invalid2("An instrumental track takes no lyrics");\n return {\n ...policy(value),\n need,\n prompt: text(value.prompt, "prompt"),\n duration_seconds: value.durationSeconds ?? 60,\n output_format: value.outputFormat ?? "mp3",\n ...value.instrumental !== void 0 ? { instrumental: value.instrumental } : {},\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...value.inputAssetIds !== void 0 ? { input_asset_ids: singleSource(value.inputAssetIds) } : {},\n ...value.lyrics != null ? { lyrics: value.lyrics } : {},\n ...value.seed != null ? { seed: value.seed } : {},\n ...value.bpm != null ? { bpm: value.bpm } : {},\n ...value.vocalLanguage != null ? { vocal_language: value.vocalLanguage } : {},\n ...value.keyScale != null ? { key_scale: value.keyScale } : {},\n ...value.timeSignature != null ? { time_signature: value.timeSignature } : {}\n };\n case "image.generate":\n case "image.edit": {\n const ids2 = assetIds(value.inputAssetIds, "inputAssetIds", need === "image.edit");\n if (value.size !== void 0 && value.aspectRatio !== void 0 && imageSizeByAspectRatio[value.aspectRatio] !== value.size) throw invalid2("size conflicts with aspectRatio");\n if (value.background === "transparent" && value.outputFormat === "jpeg") throw invalid2("JPEG does not support a transparent background");\n return {\n ...policy(value),\n prompt: text(value.prompt, "prompt"),\n need,\n ...ids2 ? { input_asset_ids: ids2 } : {},\n ...value.size ? { size: value.size } : {},\n ...value.aspectRatio ? { aspect_ratio: value.aspectRatio } : {},\n ...value.quality ? { quality: value.quality } : {},\n ...value.outputFormat ? { output_format: value.outputFormat } : {},\n ...value.background ? { background: value.background } : {}\n };\n }\n case "video.generate": {\n if (value.provider !== void 0) throw invalid2("video.generate does not accept provider");\n optionalNumber(value.durationSeconds, "durationSeconds");\n const durationSeconds = value.durationSeconds ?? 6;\n if (durationSeconds < 2 || durationSeconds > 30) throw invalid2("durationSeconds must be between 2 and 30 for video.generate");\n const frames = assetIds(value.inputAssetIds, "inputAssetIds", false);\n if (frames && (frames.length < 1 || frames.length > 2)) throw invalid2("inputAssetIds must list a first frame and at most a last frame");\n if (value.audio !== void 0 && typeof value.audio !== "boolean") throw invalid2("audio must be a boolean");\n return {\n ...policy(value),\n prompt: text(value.prompt, "prompt"),\n need,\n duration_seconds: durationSeconds,\n ...frames ? { input_asset_ids: frames } : {},\n ...value.aspectRatio !== void 0 ? { aspect_ratio: value.aspectRatio } : {},\n ...value.resolution !== void 0 ? { resolution: value.resolution } : {},\n ...value.audio !== void 0 ? { audio: value.audio } : {},\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {}\n };\n }\n case "image.remove_background":\n return { ...budget(value), input_asset_ids: singleSource(value.inputAssetIds), need, ...value.outputFormat ? { output_format: value.outputFormat } : {} };\n case "image.upscale":\n return {\n ...budget(value),\n input_asset_ids: singleSource(value.inputAssetIds),\n need,\n ...value.scale !== void 0 ? { scale: value.scale } : {},\n ...value.outputFormat ? { output_format: value.outputFormat } : {}\n };\n case "audio.sound_effect":\n optionalNumber(value.durationSeconds, "durationSeconds");\n if (value.loop !== void 0 && typeof value.loop !== "boolean") throw invalid2("loop must be a boolean");\n return {\n ...budget(value),\n need,\n prompt: text(value.prompt, "prompt"),\n duration_seconds: value.durationSeconds ?? 5,\n loop: value.loop ?? false,\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {}\n };\n case "video.extend":\n optionalString(value.prompt, "prompt");\n optionalNumber(value.durationSeconds, "durationSeconds");\n return {\n ...budget(value),\n input_asset_ids: singleSource(value.inputAssetIds),\n need,\n duration_seconds: value.durationSeconds ?? 5,\n ...value.prompt !== void 0 ? { prompt: value.prompt } : {},\n ...value.mode !== void 0 ? { mode: value.mode } : {}\n };\n case "video.upscale":\n return {\n ...budget(value),\n input_asset_ids: singleSource(value.inputAssetIds),\n need,\n ...value.resolution !== void 0 ? { resolution: value.resolution } : {},\n ...value.fps !== void 0 ? { fps: value.fps } : {}\n };\n case "audio.voice_change":\n if (value.audioDataUrl === void 0 === (value.inputAssetIds === void 0)) throw invalid2("Provide one recording: audioDataUrl or inputAssetIds");\n if (value.audioDataUrl !== void 0 && (typeof value.audioDataUrl !== "string" || !value.audioDataUrl.startsWith("data:"))) throw invalid2("audioDataUrl must be an audio data URL");\n if (value.durationSeconds !== void 0) throw invalid2("durationSeconds is not accepted by audio.voice_change");\n if (value.voice === void 0) throw invalid2("voice is required by audio.voice_change");\n if (value.removeBackgroundNoise !== void 0 && typeof value.removeBackgroundNoise !== "boolean") throw invalid2("removeBackgroundNoise must be a boolean");\n return {\n ...budget(value),\n need,\n ...value.audioDataUrl !== void 0 ? { audio_data_url: value.audioDataUrl } : { input_asset_ids: singleSource(value.inputAssetIds) },\n voice_id: matching(value.voice, voicePattern, "voice"),\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...voiceSettings(value.voiceSettings),\n ...value.removeBackgroundNoise !== void 0 ? { remove_background_noise: value.removeBackgroundNoise } : {}\n };\n }\n}\nvar decisionTypes = /* @__PURE__ */ new Set(["choice", "score", "noul"]);\nfunction aiDecideWire(input4) {\n if (!isRecord(input4) || !isRecord(input4.questions) || !Object.keys(input4.questions).length) throw invalid2("A decision needs at least one question");\n for (const [id, question] of Object.entries(input4.questions)) {\n if (!isRecord(question) || !decisionTypes.has(question.type) || typeof question.instructions !== "string" || !question.instructions.trim()) {\n throw invalid2(`Decision question ${id} needs a type and instructions`);\n }\n }\n if (input4.maximumCostMicrocredits !== void 0 && !isMicrocredits(input4.maximumCostMicrocredits)) throw invalid2("maximumCostMicrocredits must be a positive integer string");\n return {\n state: input4.state,\n questions: input4.questions,\n ...input4.maximumCostMicrocredits !== void 0 ? { maximum_cost_microcredits: input4.maximumCostMicrocredits } : {}\n };\n}\nfunction aiOptionsWire(input4) {\n if (!isRecord(input4) || typeof input4.need !== "string" || !supportedNeeds.has(input4.need)) throw invalid2("need must be a supported generation need");\n const ids2 = assetIds(input4.inputAssetIds, "inputAssetIds", false);\n optionalString(input4.generationUsage, "generationUsage");\n return { need: input4.need, ...ids2 ? { input_asset_ids: ids2 } : {}, ...input4.generationUsage ? { generation_usage: input4.generationUsage } : {} };\n}\nvar modelNeeds = new Set(aiModelNeeds);\nfunction aiModelsWire(input4) {\n if (!isRecord(input4) || !modelNeeds.has(input4.need)) throw invalid2(`need must be one of ${aiModelNeeds.join(", ")}`);\n return { need: input4.need };\n}\nfunction facet(value, field3) {\n return matching(value, VOICE_FACET_PATTERN, field3);\n}\nfunction facetList(value, field3) {\n if (!Array.isArray(value)) throw invalid2(`${field3} must be an array of strings`);\n if (value.length > VOICE_FACET_LIST_MAX) throw invalid2(`${field3} accepts at most ${VOICE_FACET_LIST_MAX} entries`);\n return value.map((entry, index) => facet(entry, `${field3}[${index}]`));\n}\nfunction aiVoicesWire(input4) {\n const value = isRecord(input4) ? input4 : {};\n if (value.collection !== void 0 && !voiceCollections.includes(value.collection)) throw invalid2("collection must be standard, library or all");\n if (value.sort !== void 0 && !voiceSorts.includes(value.sort)) throw invalid2(`sort must be one of ${voiceSorts.join(", ")}`);\n if (value.featured !== void 0 && typeof value.featured !== "boolean") throw invalid2("featured must be a boolean");\n optionalString(value.query, "query");\n optionalString(value.cursor, "cursor");\n if (value.limit !== void 0 && (!Number.isInteger(value.limit) || value.limit < 1 || value.limit > 100)) throw invalid2("limit must be an integer from 1 to 100");\n if (value.maxPriceMultiplier !== void 0 && (typeof value.maxPriceMultiplier !== "number" || !Number.isFinite(value.maxPriceMultiplier) || value.maxPriceMultiplier <= 0)) {\n throw invalid2("maxPriceMultiplier must be a positive number");\n }\n return {\n need: "audio.synthesize",\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...value.language !== void 0 ? { language: matching(value.language, languagePattern, "language") } : {},\n ...value.locale !== void 0 ? { locale: facet(value.locale, "locale") } : {},\n ...value.collection !== void 0 ? { collection: value.collection } : {},\n ...value.query?.trim() ? { query: value.query.trim() } : {},\n ...value.gender !== void 0 ? { gender: facet(value.gender, "gender") } : {},\n ...value.age !== void 0 ? { age: facet(value.age, "age") } : {},\n ...value.accent !== void 0 ? { accent: facet(value.accent, "accent") } : {},\n ...value.category !== void 0 ? { category: facet(value.category, "category") } : {},\n ...value.useCases !== void 0 ? { use_cases: facetList(value.useCases, "useCases") } : {},\n ...value.descriptives !== void 0 ? { descriptives: facetList(value.descriptives, "descriptives") } : {},\n ...value.featured !== void 0 ? { featured: value.featured } : {},\n ...value.sort !== void 0 ? { sort: value.sort } : {},\n ...value.maxPriceMultiplier !== void 0 ? { max_price_multiplier: value.maxPriceMultiplier } : {},\n ...value.verifiedFor !== void 0 ? { verified_for: matching(value.verifiedFor, modelPattern, "verifiedFor") } : {},\n ...value.cursor ? { cursor: value.cursor } : {},\n ...value.limit !== void 0 ? { limit: value.limit } : {}\n };\n}\nfunction aiVoicePreviewWire(input4) {\n const value = isRecord(input4) ? input4 : {};\n return {\n need: "audio.synthesize",\n voice: matching(value.voice, voicePattern, "voice"),\n ...value.model !== void 0 ? { model: matching(value.model, modelPattern, "model") } : {},\n ...value.language !== void 0 ? { language: matching(value.language, languagePattern, "language") } : {}\n };\n}\nfunction aiVoiceFavoritesWire() {\n return { need: "audio.synthesize" };\n}\nvar favoriteBatchMax = 100;\nvar favoriteText = (value, max) => typeof value === "string" ? Array.from(value.replace(/\\s+/gu, " ").trim()).slice(0, max).join("").trim() : "";\nfunction voiceFavoriteWire(item, field3) {\n if (!isRecord(item)) throw invalid2(`${field3} must be a voice entry or a voice ref`);\n const entry = "ref" in item && isRecord(item.ref) ? item : null;\n const ref = entry ? entry.ref : item;\n const voice = matching(ref.id, voicePattern, `${field3}.id`);\n const model = typeof ref.model === "string" && ref.model ? matching(ref.model, modelPattern, `${field3}.model`) : "";\n const name = favoriteText(entry ? entry.name : item.name, 80) || voice.slice(voice.lastIndexOf(":") + 1) || voice;\n if (!entry) return { voice, ...model ? { model } : {}, name, ...voice.startsWith("library:") ? { collection: "library" } : {} };\n const languages = Array.from(new Set((Array.isArray(entry.languages) ? entry.languages : []).map((code) => typeof code === "string" ? code.trim().toLowerCase().split(/[-_]/u)[0] : "").filter((code) => /^[a-z]{2,3}$/u.test(code)))).slice(0, 24);\n const traits = isRecord(entry.traits) ? entry.traits : {};\n const gender = favoriteText(traits.gender ?? traits.listed?.gender, 40), age = favoriteText(traits.age ?? traits.listed?.age, 40);\n const accent = favoriteText(traits.accent, 40), locale = favoriteText(entry.locale, 50);\n const premium = typeof entry.premium === "number" && Number.isFinite(entry.premium) && entry.premium > 0 ? Math.min(entry.premium, 3) : void 0;\n return {\n voice,\n ...model ? { model } : {},\n name,\n ...languages.length ? { languages } : {},\n ...gender ? { gender } : {},\n ...age ? { age } : {},\n ...accent ? { accent } : {},\n ...locale ? { locale } : {},\n ...entry.collection === "standard" || entry.collection === "library" ? { collection: entry.collection } : {},\n ...typeof entry.preview === "boolean" ? { preview: entry.preview } : {},\n ...premium !== void 0 ? { price_multiplier: premium } : {}\n };\n}\nfunction aiVoiceFavoritesUpdateWire(input4) {\n const value = isRecord(input4) ? input4 : {};\n if (value.add !== void 0 && (!Array.isArray(value.add) || value.add.length > favoriteBatchMax)) throw invalid2(`add must be an array of at most ${favoriteBatchMax} voices`);\n if (value.remove !== void 0 && (!Array.isArray(value.remove) || value.remove.length > favoriteBatchMax)) throw invalid2(`remove must be an array of at most ${favoriteBatchMax} voice ids`);\n if (value.imagineFromFavorites !== void 0 && typeof value.imagineFromFavorites !== "boolean") throw invalid2("imagineFromFavorites must be a boolean");\n const add = value.add?.map((item, index) => voiceFavoriteWire(item, `add[${index}]`));\n const remove2 = value.remove?.map((id, index) => matching(id, voicePattern, `remove[${index}]`));\n return {\n need: "audio.synthesize",\n ...add?.length ? { add } : {},\n ...remove2?.length ? { remove: remove2 } : {},\n ...value.imagineFromFavorites !== void 0 ? { imagine_from_favorites: value.imagineFromFavorites } : {}\n };\n}\nfunction aiGetWire(input4) {\n const value = isRecord(input4) ? input4 : {};\n const operationId2 = value.operationId, idempotencyKey = value.idempotencyKey;\n if (operationId2 === void 0 === (idempotencyKey === void 0)) throw invalid2("Provide one operationId or the original idempotencyKey");\n const key2 = operationId2 ?? idempotencyKey;\n if (typeof key2 !== "string" || !key2) throw invalid2("operationId or idempotencyKey must be a non-empty string");\n return operationId2 !== void 0 ? { operation_id: key2 } : { idempotency_key: key2 };\n}\n\n// src/ai.ts\nvar credits = (value) => typeof value === "string" && /^\\d+$/.test(value);\nvar isSource = (value) => isRecord(value) && isString(value.url) && (value.title === void 0 || isString(value.title));\nvar reject = (message2) => new NochaError("invalid_result", message2);\nfunction generationResult(need, value) {\n if (!isRecord(value) || value.need !== need || !isNonEmptyString(value.operation_id) || !isRecord(value.billing) || value.billing.participant_captured_microcredits !== void 0 && !credits(value.billing.participant_captured_microcredits)) {\n throw reject("Nocha returned an invalid generation result");\n }\n const media2 = !Array.isArray(value.asset_ids) || !value.asset_ids.length || !isArrayOf(value.asset_ids, isString) || !isArrayOf(value.assets, (asset) => isRecord(asset) && isString(asset.id)) || value.asset_ids.some((id) => !value.assets.some((asset) => asset.id === id));\n const invalid5 = need === "text.structured" ? !isString(value.text) || value.structured === void 0 : need.startsWith("text.") ? !isString(value.text) : need === "web.research" ? value.structured === void 0 || !isArrayOf(value.sources, isSource) || !Number.isInteger(value.search_call_count) || Number(value.search_call_count) < 1 : need === "audio.synthesize" ? !isNonEmptyString(value.audio_base64) || !isString(value.mime_type) || !value.mime_type.startsWith("audio/") || value.shared !== void 0 && value.shared !== "hit" && value.shared !== "miss" : need === "audio.transcribe" ? !isString(value.text) || value.duration_seconds !== void 0 && !isFiniteNumber(value.duration_seconds) : isMediaNeed(need) ? media2 || value.duration_seconds !== void 0 && !isFiniteNumber(value.duration_seconds) : true;\n if (invalid5) throw reject(`Nocha returned an invalid ${need} result`);\n return value;\n}\nvar assetShape = (asset) => isRecord(asset) && isString(asset.id);\nfunction pendingReceipt(value) {\n if (!isRecord(value) || value.status !== "pending" || !isNonEmptyString(value.operation_id) || !isString(value.need)) return void 0;\n if ("billing" in value || "text" in value || "audio_base64" in value || "asset_ids" in value || "structured" in value) return void 0;\n const poll = value.poll_after_ms;\n const interval = isFiniteNumber(poll) && poll >= generationWaiting.pollIntervalMs ? poll : generationWaiting.pollIntervalMs;\n return { operation_id: value.operation_id, need: value.need, poll_after_ms: Math.min(interval, generationWaiting.pollMaxMs) };\n}\nfunction withRecovery(error, operationId2, idempotencyKey) {\n return new NochaError(error.code, error.message, {\n ...error.wireCode ? { wireCode: error.wireCode } : {},\n ...error.trace_id ? { trace_id: error.trace_id } : {},\n ...error.correlation_id ? { correlation_id: error.correlation_id } : {},\n retryable: error.retryable,\n ...operationId2 ? { operation_id: operationId2 } : {},\n ...idempotencyKey ? { idempotency_key: idempotencyKey } : {}\n });\n}\nfunction waitRemaining(ms2, signal) {\n if (signal?.aborted) return Promise.reject(new NochaError("aborted", "Generation wait was aborted"));\n if (ms2 <= 0) return Promise.resolve();\n return new Promise((resolve2, reject2) => {\n const timer = setTimeout(finish, ms2);\n const onAbort = () => {\n clearTimeout(timer);\n signal?.removeEventListener("abort", onAbort);\n reject2(new NochaError("aborted", "Generation wait was aborted"));\n };\n function finish() {\n signal?.removeEventListener("abort", onAbort);\n resolve2();\n }\n signal?.addEventListener("abort", onAbort, { once: true });\n });\n}\nfunction decoded(value, options) {\n return options?.decode && "structured" in value ? { ...value, structured: options.decode(value.structured) } : value;\n}\nasync function generate2(context, input4, options) {\n const paid = aiGenerateWire(input4);\n const wire3 = { ...paid, response_mode: "pending" };\n const started = Date.now();\n const total = options?.timeoutMs ?? deadlineMs("ai", "generate", paid);\n const key2 = options?.idempotencyKey;\n const signal = options?.signal;\n const admission = Math.min(total, generationWaiting.negotiatedAdmissionMs + generationWaiting.sdkMarginMs);\n let value;\n try {\n value = await context.invoke(aiOperationDefinitions["generate"].capability, aiOperationDefinitions["generate"].operation, wire3, {\n ...options,\n timeoutMs: Math.max(1, admission)\n });\n } catch (error) {\n if (isNochaError(error) && (error.code === "aborted" || error.code === "invocation_timed_out")) throw withRecovery(error, void 0, key2);\n throw error;\n }\n const pending3 = pendingReceipt(value);\n if (!pending3) return decoded(generationResult(input4.need, value), options);\n let pause2 = pending3.poll_after_ms;\n const operationId2 = pending3.operation_id;\n while (Date.now() - started < total) {\n const remaining = total - (Date.now() - started);\n try {\n await waitRemaining(Math.min(pause2, remaining), signal);\n } catch (error) {\n if (isNochaError(error)) throw withRecovery(error, operationId2, key2);\n throw error;\n }\n if (Date.now() - started >= total) break;\n const budget2 = Math.max(1, Math.min(operationWaiting.ai.default, total - (Date.now() - started)));\n let status2;\n try {\n status2 = await get(context, { operationId: operationId2 }, { signal, timeoutMs: budget2 });\n } catch (error) {\n if (classifyError(error) !== "transient") throw isNochaError(error) ? withRecovery(error, operationId2, key2) : error;\n pause2 = Math.min(generationWaiting.pollMaxMs, Math.max(pause2 * 2, generationWaiting.pollIntervalMs));\n continue;\n }\n if (status2.status === "succeeded") {\n const final = Object.fromEntries(Object.entries(status2).filter(([key3]) => !["status", "poll_after_ms", "failure"].includes(key3)));\n return decoded(generationResult(input4.need, final), options);\n }\n if (status2.status === "failed" || status2.status === "cancelled") {\n const code = status2.failure?.code === "shared_speech_retry" ? "shared_speech_retry" : "generation_failed";\n throw new NochaError(code, status2.failure?.message ?? "Generation could not be completed", { operation_id: operationId2, idempotency_key: key2 });\n }\n pause2 = Math.min(generationWaiting.pollMaxMs, Math.max(pause2 * 2, generationWaiting.pollIntervalMs));\n }\n throw new NochaError("invocation_timed_out", "Generation is still running", { operation_id: operationId2, idempotency_key: key2 });\n}\nasync function estimate(context, input4, options) {\n const wire3 = aiGenerateWire(input4);\n const value = await context.invoke(aiOperationDefinitions["estimate"].capability, aiOperationDefinitions["estimate"].operation, wire3, options);\n if (!isRecord(value) || !isUuid(value.quote_id) || typeof value.expires_at !== "string" || !Number.isFinite(Date.parse(value.expires_at)) || !credits(value.estimated_cost_micro_usd) || !isRecord(value.estimated_usage) || !Object.values(value.estimated_usage).every(credits) || value.estimated_charge_microcredits !== void 0 && !credits(value.estimated_charge_microcredits) || value.creator_fee_microcredits !== void 0 && !credits(value.creator_fee_microcredits) || value.base_charge_microcredits !== void 0 && !credits(value.base_charge_microcredits) || value.shared !== void 0 && value.shared !== "ready" && value.shared !== "pending" || typeof value.rate_card_id !== "string") throw reject("Nocha returned an invalid generation quote");\n return value;\n}\nvar decisionAnswerTypes = ["choice", "score", "noul"];\nasync function decide(context, input4, options) {\n const wire3 = aiDecideWire(input4);\n const value = await context.invoke(aiOperationDefinitions["decide"].capability, aiOperationDefinitions["decide"].operation, wire3, options);\n if (!isRecord(value) || typeof value.operation_id !== "string" || typeof value.model !== "string" || value.capability !== "text.decide" || value.need !== "text.decision" || !isRecord(value.answers) || !Object.values(value.answers).every((answer) => isRecord(answer) && decisionAnswerTypes.includes(String(answer.type))) || !isRecord(value.billing) || !["participants", "project"].includes(String(value.billing.payer_mode)) || !["initiator", "project"].includes(String(value.billing.capability_calls)) || !credits(value.billing.participant_captured_microcredits)) {\n throw reject("Nocha returned an invalid decision");\n }\n return options?.decode ? { ...value, answers: options.decode(value.answers) } : value;\n}\nasync function get(context, input4, options) {\n const wire3 = aiGetWire(input4);\n const value = await context.invoke(aiOperationDefinitions["get"].capability, aiOperationDefinitions["get"].operation, wire3, options);\n if (!isRecord(value) || typeof value.operation_id !== "string" || typeof value.need !== "string" || !["queued", "running", "succeeded", "failed", "cancelled"].includes(String(value.status)) || !isArrayOf(value.asset_ids, isString) || value.text !== void 0 && typeof value.text !== "string" || value.sources !== void 0 && !isArrayOf(value.sources, isSource) || value.search_call_count !== void 0 && (!Number.isSafeInteger(value.search_call_count) || Number(value.search_call_count) < 1) || value.audio_base64 !== void 0 && !isString(value.audio_base64) || value.mime_type !== void 0 && !isString(value.mime_type) || value.model !== void 0 && !isString(value.model) || value.seed !== void 0 && !Number.isInteger(value.seed) || value.shared !== void 0 && value.shared !== "hit" && value.shared !== "miss" || value.assets !== void 0 && !isArrayOf(value.assets, assetShape) || value.billing !== void 0 && !isRecord(value.billing) || value.poll_after_ms !== void 0 && (!isFiniteNumber(value.poll_after_ms) || value.poll_after_ms < 0) || value.failure !== void 0 && (!isRecord(value.failure) || typeof value.failure.code !== "string" || typeof value.failure.message !== "string" || typeof value.failure.retryable !== "boolean")) {\n throw reject("Nocha returned an invalid generation operation");\n }\n return value;\n}\nasync function generationOptions(context, input4, options) {\n const wire3 = aiOptionsWire(input4);\n const value = await context.invoke(aiOperationDefinitions["options"].capability, aiOperationDefinitions["options"].operation, wire3, options);\n if (!isRecord(value) || value.version !== 1 || typeof value.usage !== "string" || !["text", "image", "video", "voice", "music", "sound", "research", "import"].includes(String(value.family)) || !Array.isArray(value.efforts) || !value.efforts.every((effort) => ["low", "medium", "high"].includes(String(effort)))) {\n throw reject("Nocha returned invalid generation options");\n }\n return value;\n}\nvar isOptionalString = (value) => value === void 0 || isString(value);\nvar isStringList = (value) => isArrayOf(value, isString);\nvar isOptionalBoolean = (value) => value === void 0 || typeof value === "boolean";\nvar isOptionalNumber = (value) => value === void 0 || isFiniteNumber(value);\nvar settingKeys2 = /* @__PURE__ */ new Set(["stability", "similarity_boost", "style", "speed", "use_speaker_boost"]);\nvar facetNames = new Set(voiceFacets);\nvar isVoiceSetting = (value) => isRecord(value) && settingKeys2.has(value.key) && isOptionalNumber(value.min) && isOptionalNumber(value.max) && (value.values === void 0 || isArrayOf(value.values, isFiniteNumber));\nvar oneOf = (value, values) => values.includes(value);\nfunction modelCapabilities(value) {\n return {\n ...isNonEmptyString(value.family) ? { family: value.family } : {},\n ...oneOf(value.latency, ["low", "standard", "slow"]) ? { latency: value.latency } : {},\n ...oneOf(value.price_unit, ["character", "audio_second"]) ? { price_unit: value.price_unit } : {},\n ...typeof value.speech_tags === "boolean" ? { speech_tags: value.speech_tags } : {},\n ...Array.isArray(value.voice_settings) ? { voice_settings: value.voice_settings.filter(isVoiceSetting) } : {},\n ...oneOf(value.voice_catalogue, ["library", "fixed"]) ? { voice_catalogue: value.voice_catalogue } : {},\n ...Array.isArray(value.voice_facets) ? { voice_facets: value.voice_facets.filter((facet2) => facetNames.has(facet2)) } : {},\n ...typeof value.voice_previews === "boolean" ? { voice_previews: value.voice_previews } : {},\n ...typeof value.multilingual === "boolean" ? { multilingual: value.multilingual } : {},\n ...isNonEmptyString(value.voice_group) ? { voice_group: value.voice_group } : {}\n };\n}\nfunction modelState(model) {\n const price = model.price;\n const tariff = isRecord(price) && price.unit === "character" && isFiniteNumber(price.micro_credits_per_1000) && price.micro_credits_per_1000 >= 0 && typeof price.ceiling === "boolean" ? { unit: "character", micro_credits_per_1000: price.micro_credits_per_1000, ceiling: price.ceiling } : void 0;\n return {\n ...oneOf(model.availability, ["available", "degraded", "unavailable"]) ? { availability: model.availability } : {},\n ...oneOf(model.access, ["relayed", "direct"]) ? { access: model.access } : {},\n ...tariff ? { price: tariff } : {}\n };\n}\nasync function models(context, input4, options) {\n const wire3 = aiModelsWire(input4);\n const value = await context.invoke(aiOperationDefinitions["models"].capability, aiOperationDefinitions["models"].operation, wire3, options);\n if (!isRecord(value) || value.need !== wire3.need || !isNonEmptyString(value.default_model) || !isArrayOf(value.models, (model) => isRecord(model) && isNonEmptyString(model.model) && isString(model.label) && typeof model.default === "boolean" && (model.languages === void 0 || isStringList(model.languages)))) {\n throw reject(`Nocha returned invalid ${wire3.need} models`);\n }\n return {\n ...value,\n need: wire3.need,\n default_model: value.default_model,\n models: value.models.map(({ capabilities: capabilities2, availability: _availability, access: _access, price: _price, ...model }) => ({\n ...model,\n ...modelState({ availability: _availability, access: _access, price: _price }),\n ...isRecord(capabilities2) ? { capabilities: modelCapabilities(capabilities2) } : {}\n }))\n };\n}\nvar isOptionalCount = (value) => value === void 0 || isFiniteNumber(value) && Number.isInteger(value) && value >= 0;\nvar isVoiceDialect = (value) => isRecord(value) && isNonEmptyString(value.language) && isOptionalString(value.locale) && isOptionalString(value.accent) && (value.models === void 0 || isStringList(value.models)) && isOptionalBoolean(value.preview);\nasync function voices(context, input4, options) {\n const wire3 = aiVoicesWire(input4);\n const value = await context.invoke(aiOperationDefinitions["voices"].capability, aiOperationDefinitions["voices"].operation, wire3, options);\n if (!isRecord(value) || !isNonEmptyString(value.model) || !isNonEmptyString(value.default_voice) || value.next_cursor !== null && !isNonEmptyString(value.next_cursor) || !isOptionalCount(value.total_count) || !isArrayOf(value.voices, (voice) => isRecord(voice) && isNonEmptyString(voice.id) && isString(voice.name) && isStringList(voice.languages) && (voice.models === void 0 || isStringList(voice.models)) && (voice.collection === "standard" || voice.collection === "library") && [voice.description, voice.gender, voice.age, voice.accent, voice.alias, voice.locale, voice.use_case, voice.descriptive, voice.category].every(isOptionalString) && [voice.featured, voice.free, voice.preview].every(isOptionalBoolean) && [voice.popularity, voice.usage_characters_7d, voice.usage_characters_1y].every(isOptionalCount) && (voice.price_multiplier === void 0 || isFiniteNumber(voice.price_multiplier) && voice.price_multiplier > 0) && (voice.dialects === void 0 || isArrayOf(voice.dialects, isVoiceDialect)))) {\n throw reject("Nocha returned invalid speech voices");\n }\n return value;\n}\nasync function voicePreview(context, input4, options) {\n const wire3 = aiVoicePreviewWire(input4);\n const value = await context.invoke(aiOperationDefinitions["voicePreview"].capability, aiOperationDefinitions["voicePreview"].operation, wire3, options);\n if (!isRecord(value) || !isNonEmptyString(value.mimeType) || !value.mimeType.startsWith("audio/") || !isNonEmptyString(value.dataUrl) || !value.dataUrl.startsWith("data:audio/")) {\n throw reject("Nocha returned an invalid voice preview");\n }\n return { dataUrl: value.dataUrl, mimeType: value.mimeType, ...isNonEmptyString(value.language) ? { language: value.language } : {} };\n}\nvar isFavorite = (value) => isRecord(value) && isNonEmptyString(value.voice) && isString(value.name) && isString(value.added_at) && [value.model, value.gender, value.age, value.accent, value.locale].every(isOptionalString) && (value.languages === void 0 || isStringList(value.languages)) && (value.collection === void 0 || value.collection === "standard" || value.collection === "library") && isOptionalBoolean(value.preview) && (value.price_multiplier === void 0 || isFiniteNumber(value.price_multiplier) && value.price_multiplier > 0);\nfunction favoritesResult(value) {\n if (!isRecord(value) || !isArrayOf(value.favorites, isFavorite) || typeof value.imagine_from_favorites !== "boolean" || !isFiniteNumber(value.limit) || !Number.isInteger(value.limit) || value.limit < 0) {\n throw reject("Nocha returned invalid favourite voices");\n }\n return {\n favorites: value.favorites.map(voiceFavoriteEntry).filter((entry) => entry !== null),\n imagineFromFavorites: value.imagine_from_favorites,\n limit: value.limit\n };\n}\nasync function voiceFavorites(context, options) {\n const definition = aiOperationDefinitions["voiceFavorites"];\n return favoritesResult(await context.invoke(definition.capability, definition.operation, aiVoiceFavoritesWire(), options));\n}\nasync function voiceFavoritesUpdate(context, input4, options) {\n const definition = aiOperationDefinitions["voiceFavoritesUpdate"];\n const wire3 = aiVoiceFavoritesUpdateWire(input4);\n return favoritesResult(await context.invoke(definition.capability, definition.operation, wire3, options));\n}\nfunction createAi(context) {\n return Object.freeze({\n generate: (input4, options) => generate2(context, input4, options),\n estimate: (input4, options) => estimate(context, input4, options),\n decide: (input4, options) => decide(context, input4, options),\n options: (input4, options) => generationOptions(context, input4, options),\n get: (input4, options) => get(context, input4, options),\n models: (input4, options) => models(context, input4, options),\n voices: (input4, options) => voices(context, input4, options),\n voicePreview: (input4, options) => voicePreview(context, input4, options),\n voiceFavorites: (options) => voiceFavorites(context, options),\n voiceFavoritesUpdate: (input4, options) => voiceFavoritesUpdate(context, input4, options),\n voiceCatalogue: createVoiceCatalogue({\n models: (input4, options) => models(context, input4, options),\n voices: (input4, options) => voices(context, input4, options)\n })\n });\n}\n\n// src/audio-media.ts\nvar RECORDED_AUDIO_MAX_BYTES = 4 * 1024 * 1024;\nvar TRANSCRIPTION_AUDIO_TYPES = ["audio/wav", "audio/mp4", "audio/webm", "audio/ogg", "audio/mpeg"];\nvar dataUrlPattern = /^data:([^,;]*)((?:;[^,;]*)*),(.*)$/s;\nfunction base64ToBytes(base64) {\n if (!isBase64(base64) || base64.length % 4 === 1) throw invalid2("Expected base64 data");\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\nfunction bytesToBase64(bytes) {\n let binary = "";\n for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));\n return btoa(binary);\n}\nfunction dataUrlToBlob(dataUrl) {\n const match = typeof dataUrl === "string" ? dataUrlPattern.exec(dataUrl) : null;\n if (!match) throw invalid2("Expected a data: URL");\n const parameters = match[2].split(";").slice(1);\n const base64 = parameters.at(-1)?.toLowerCase() === "base64";\n const type = [match[1].trim().toLowerCase() || "text/plain", ...base64 ? parameters.slice(0, -1) : parameters].join(";");\n let bytes;\n if (base64) bytes = base64ToBytes(match[3]);\n else {\n try {\n bytes = new TextEncoder().encode(decodeURIComponent(match[3]));\n } catch {\n throw invalid2("Expected a percent-encoded data: URL");\n }\n }\n return new Blob([bytes], { type });\n}\nasync function blobToDataUrl(blob) {\n if (!(blob instanceof Blob)) throw invalid2("Expected a Blob");\n return `data:${blob.type || "application/octet-stream"};base64,${bytesToBase64(new Uint8Array(await blob.arrayBuffer()))}`;\n}\nfunction speechAudioBlob(result2) {\n if (result2 === null || typeof result2 !== "object" || typeof result2.mime_type !== "string" || !result2.mime_type.startsWith("audio/")) {\n throw invalid2("Expected an audio.synthesize result with audio_base64 and an audio mime_type");\n }\n return new Blob([base64ToBytes(result2.audio_base64)], { type: result2.mime_type });\n}\n\n// src/media-read.ts\nfunction mediaReadTimeout(options, fallback) {\n if (!isRecord(options)) throw invalid2("Request options must be an object");\n if (options.onProgress !== void 0 && typeof options.onProgress !== "function") throw invalid2("onProgress must be a function");\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalid2("signal must be an AbortSignal");\n const timeout = options.timeoutMs ?? fallback;\n if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid2("timeoutMs must be a positive finite timer duration");\n return timeout;\n}\nfunction readHostMedia(read4) {\n const { noun, options, messages = {} } = read4;\n const subject2 = noun.charAt(0).toUpperCase() + noun.slice(1);\n const unsupported = () => new NochaError("media_unsupported_host", `This Nocha host cannot read ${noun} media`);\n const requestId = crypto.randomUUID();\n return new Promise((resolve2, reject2) => {\n let acknowledged = false;\n const cleanup = () => {\n clearTimeout(unanswered);\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const stop = (error) => {\n cleanup();\n try {\n postToHost({ protocol: NOCHA_MEDIA_PROTOCOL, type: "abort", requestId });\n } catch {\n }\n reject2(error);\n };\n const abort = () => stop(new NochaError("aborted", messages.aborted ?? `${subject2} read aborted`));\n const receive = (event) => {\n const message2 = event.data;\n if (!isFromHost(event) || !isRecord(message2) || message2.protocol !== NOCHA_MEDIA_PROTOCOL || message2.requestId !== requestId) return;\n clearTimeout(unanswered);\n if (message2.type === "progress") {\n acknowledged = true;\n if (options.onProgress && isCount(message2.loaded) && (message2.total === null || isCount(message2.total))) {\n notifyListener(options.onProgress, { loaded: message2.loaded, total: message2.total });\n }\n return;\n }\n if (message2.type !== "result" && message2.type !== "error") return;\n cleanup();\n const value = message2.type === "result" ? read4.accept(message2.result) : void 0;\n if (message2.type === "error" && read4.unknownReadRefused && !acknowledged && isRecord(message2.error) && message2.error.code === "invalid_request") reject2(unsupported());\n else if (message2.type === "error") reject2(wireError(message2.error, { code: "media_unavailable", message: messages.unavailable ?? `${subject2} media is unavailable` }));\n else if (value !== void 0) resolve2(value);\n else reject2(new NochaError("invalid_result", `Nocha returned an invalid ${noun} file`));\n };\n const unanswered = read4.timeoutMs > read4.firstReplyMs ? setTimeout(() => stop(messages.unanswered?.() ?? unsupported()), read4.firstReplyMs) : void 0;\n const timer = setTimeout(() => stop(new NochaError("invocation_timed_out", messages.timedOut ?? `Local ${noun} read timed out`)), read4.timeoutMs);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n read4.send(requestId);\n } catch (error) {\n cleanup();\n reject2(new NochaError("invalid_request", `The request cannot be sent to the Nocha host: ${error instanceof Error ? error.message : String(error)}`));\n }\n });\n}\n\n// src/assets-media.ts\nvar mediaTypes = new Set(assetMediaTypes);\nfunction isAssetMedia(value, id) {\n return isRecord(value) && value.id === id && mediaTypes.has(value.mime_type) && value.blob instanceof Blob && value.blob.type === value.mime_type && value.blob.size > 0 && value.blob.size <= assetMediaMaxBytes(value.blob.type) && value.size_bytes === value.blob.size;\n}\nasync function readAssetMedia(context, input4, options = {}, readAsset) {\n if (!isRecord(input4) || !isUuid(input4.assetId)) throw new NochaError("invalid_request", "assetId must be an asset id");\n const assetId2 = input4.assetId;\n const timeout = mediaReadTimeout(options, operationWaiting.assets.media);\n if (options.fallback !== void 0 && options.fallback !== "read") throw invalid2("fallback must be \'read\'");\n assertHostCapability("assets");\n const usageId = context.usageId;\n if (usageId === void 0) throw new NochaError("usage_required", "assets.media requires nocha.use(<declared usage id>)");\n if (options.signal?.aborted) throw new NochaError("aborted", "Asset read aborted");\n const media2 = readHostMedia({\n noun: "asset",\n timeoutMs: timeout,\n firstReplyMs: operationWaiting.assets["media.firstReply"],\n options,\n unknownReadRefused: true,\n accept: (result2) => isAssetMedia(result2, assetId2) ? result2.blob : void 0,\n send: (requestId) => postToHost({\n protocol: NOCHA_MEDIA_PROTOCOL,\n type: "read",\n requestId,\n capability: assetsOperationDefinitions["read"].capability,\n operation: assetsOperationDefinitions["read"].operation,\n usageId,\n input: { asset_id: assetId2 }\n })\n });\n if (options.fallback !== "read" || !readAsset) return media2;\n try {\n return await media2;\n } catch (error) {\n if (!isNochaError(error) || error.code !== "media_unsupported_host") throw error;\n }\n const asset = await readAsset({ assetId: assetId2 }, { ...options.signal ? { signal: options.signal } : {}, ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {} });\n let blob;\n try {\n blob = new Blob([base64ToBytes(asset.data_base64)], { type: asset.mime_type });\n } catch {\n throw invalidResult("Nocha returned an invalid asset file");\n }\n if (!isAssetMedia({ id: asset.id, mime_type: asset.mime_type, blob, size_bytes: blob.size }, assetId2)) throw invalidResult("Nocha returned an invalid asset file");\n return blob;\n}\n\n// src/host-upload.ts\nfunction uploadToHost(upload2) {\n const { file, onProgress, signal, validate } = upload2;\n if (upload2.idempotencyKey !== void 0 && !isIdempotencyKey(upload2.idempotencyKey)) throw invalid2("idempotencyKey must contain 8 to 200 characters");\n if (signal?.aborted) throw new NochaError("aborted", upload2.abortMessage);\n const timeout = upload2.timeoutMs;\n if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid2("timeoutMs must be a positive finite timer duration");\n const requestId = crypto.randomUUID();\n return new Promise((resolve2, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n signal?.removeEventListener("abort", abort);\n };\n const abort = () => {\n postToHost({ protocol: NOCHA_UPLOAD_PROTOCOL, type: "abort", requestId });\n cleanup();\n reject2(new NochaError("aborted", upload2.abortMessage));\n };\n const expire = () => {\n cleanup();\n reject2(new NochaError("invocation_timed_out", upload2.timeoutMessage ?? "Local upload wait timed out; the upload may still complete"));\n };\n const receive = (event) => {\n const message2 = event.data;\n if (!isFromHost(event) || !isRecord(message2) || message2.protocol !== NOCHA_UPLOAD_PROTOCOL || message2.requestId !== requestId) return;\n if (message2.type === "progress") {\n if (onProgress && (!upload2.countedProgress || isCount(message2.loaded))) notifyListener(onProgress, { loaded: Number(message2.loaded), total: file.size });\n return;\n }\n cleanup();\n const result2 = message2.result;\n if (message2.type === "result" && validate(result2)) resolve2(result2);\n else if (message2.type === "result" && upload2.invalidResultMessage !== void 0) reject2(invalidResult(upload2.invalidResultMessage));\n else reject2(wireError(message2.error, { code: "upload_failed", message: upload2.failureMessage }));\n };\n const timer = setTimeout(expire, timeout);\n window.addEventListener("message", receive);\n signal?.addEventListener("abort", abort, { once: true });\n const idempotencyKey = upload2.idempotencyKey ?? `${requestId}:${upload2.keySuffix}`;\n try {\n if (upload2.unnamed) postToHost({ protocol: NOCHA_UPLOAD_PROTOCOL, type: "upload", requestId, usageId: upload2.usageId, idempotencyKey, input: upload2.input, file });\n else postToHost({ protocol: NOCHA_UPLOAD_PROTOCOL, type: "upload", requestId, capability: upload2.capability, operation: upload2.operation, usageId: upload2.usageId, idempotencyKey, input: upload2.input, file });\n } catch (error) {\n cleanup();\n reject2(error);\n }\n });\n}\n\n// src/attachments.ts\nvar maxBytes = 64 * 1024 * 1024;\nvar attachmentTypes = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp", "video/mp4", "audio/wav", "audio/mp4"]);\nasync function uploadAttachment(context, request2, options = {}) {\n if (!isRecord(request2)) throw invalid2("An attachment request object is required");\n const file = request2.file;\n if (!(file instanceof Blob) || file.size < 1 || file.size > maxBytes) throw invalid2("The attachment must be between 1 byte and 64 MiB");\n if (!attachmentTypes.has(file.type)) throw invalid2("Select a JPEG, PNG, WebP, MP4 or WAV file");\n if (file.type.startsWith("audio/") && file.size > 4 * 1024 * 1024) throw invalid2("Audio attachments are limited to 4 MiB");\n if (request2.filename !== void 0 && typeof request2.filename !== "string") throw invalid2("filename must be a string");\n assertHostCapability("assets");\n const usageId = context.usageId;\n if (usageId === void 0) throw new NochaError("usage_required", "assets.uploadAttachment requires nocha.use(<declared usage id>)");\n const filename = (request2.filename ?? ("name" in file ? String(file.name) : "attachment")).replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 120);\n const upload2 = { filename, mime_type: file.type, size_bytes: file.size };\n const definition = assetsOperationDefinitions.uploadAttachment;\n return uploadToHost({\n capability: definition.capability,\n operation: definition.operation,\n usageId,\n idempotencyKey: options.idempotencyKey,\n keySuffix: "attachment",\n input: upload2,\n file,\n onProgress: options.onProgress,\n timeoutMs: options.timeoutMs ?? deadlineMs(definition.capability, definition.operation, upload2),\n signal: options.signal,\n validate: (result2) => isRecord(result2) && isNonEmptyString(result2.id) && isString(result2.mime_type) && typeof result2.size_bytes === "string",\n abortMessage: "Attachment upload aborted",\n failureMessage: "Attachment upload failed"\n });\n}\nasync function attachmentUrl(context, input4, options) {\n if (!isRecord(input4) || !isUuid(input4.postId) || !isUuid(input4.assetId)) throw invalid2("postId and assetId must be record and asset ids");\n const value = await context.invoke(assetsOperationDefinitions["attachmentUrl"].capability, assetsOperationDefinitions["attachmentUrl"].operation, { post_id: input4.postId, asset_id: input4.assetId, ...input4.collection === void 0 ? {} : { collection: input4.collection } }, options);\n if (!isRecord(value) || !isNonEmptyString(value.url) || !attachmentTypes.has(value.mime_type)) throw new NochaError("invalid_result", "Nocha returned no attachment URL");\n return value;\n}\n\n// src/assets.ts\nvar readableTypes = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp", "audio/mpeg", "audio/wav", "audio/flac", "audio/ogg"]);\nvar uploadableTypes = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);\nvar videoTypes = /* @__PURE__ */ new Set(["video/mp4", "video/quicktime"]);\nvar audioTypes = /* @__PURE__ */ new Set(["audio/mpeg", "audio/wav"]);\nvar audioAliases = { "audio/mp3": "audio/mpeg", "audio/x-wav": "audio/wav", "audio/wave": "audio/wav", "audio/vnd.wave": "audio/wav" };\nvar maxAudioBytes = 64 * 1024 * 1024;\nasync function read2(context, input4, options) {\n if (!isRecord(input4) || !isUuid(input4.assetId)) throw new NochaError("invalid_request", "assetId must be an asset id");\n const value = await context.invoke(assetsOperationDefinitions["read"].capability, assetsOperationDefinitions["read"].operation, { asset_id: input4.assetId }, options);\n if (!isRecord(value) || value.id !== input4.assetId || !readableTypes.has(value.mime_type) || !isNonEmptyString(value.data_base64)) {\n throw new NochaError("invalid_result", "Nocha returned no readable asset");\n }\n return { ...value, data_url: `data:${String(value.mime_type)};base64,${value.data_base64}` };\n}\nfunction binaryType(file, filename) {\n if (file.type) {\n const type = file.type.toLowerCase();\n return videoTypes.has(type) || audioTypes.has(type) ? type : audioAliases[type];\n }\n const name = filename ?? ("name" in file ? String(file.name) : "");\n return /\\.(mp4|m4v)$/i.test(name) ? "video/mp4" : /\\.mov$/i.test(name) ? "video/quicktime" : /\\.mp3$/i.test(name) ? "audio/mpeg" : /\\.wav$/i.test(name) ? "audio/wav" : void 0;\n}\nasync function uploadBinary(context, file, mimeType, filename, shared, options = {}) {\n const kind = mimeType.startsWith("audio/") ? "Audio" : "Video";\n if (kind === "Video" ? file.size > ASSET_VIDEO_MAX_BYTES : file.size > maxAudioBytes) throw invalid2(`The ${kind.toLowerCase()} file must be at most ${kind === "Video" ? "1 GiB" : "64 MiB"}`);\n assertHostCapability("assets");\n const usageId = context.usageId;\n if (usageId === void 0) throw new NochaError("usage_required", "assets.upload requires nocha.use(<declared usage id>)");\n const fallback = { "video/mp4": "source-video.mp4", "video/quicktime": "source-video.mov", "audio/mpeg": "soundtrack.mp3", "audio/wav": "soundtrack.wav" }[mimeType];\n const name = filename ?? ("name" in file ? String(file.name) : fallback);\n const input4 = { filename: name.replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 120), mime_type: mimeType, size_bytes: file.size, ...shared ? { visibility: "shared" } : {} };\n return uploadToHost({\n capability: assetsOperationDefinitions.upload.capability,\n operation: assetsOperationDefinitions.upload.operation,\n usageId,\n idempotencyKey: options.idempotencyKey,\n keySuffix: "upload",\n input: input4,\n file,\n onProgress: options.onProgress,\n // Not deadlineMs: the registered assets.upload wait is the inline image\'s; a video or audio file takes the attachment transport\'s.\n timeoutMs: options.timeoutMs ?? operationWaiting.assets.uploadAttachment,\n signal: options.signal,\n validate: (result2) => isUploaded(result2),\n abortMessage: `${kind} upload aborted`,\n failureMessage: `${kind} upload failed`\n });\n}\nvar isVisibility = (value) => value === "private" || value === "shared";\nfunction isUploaded(value) {\n return isRecord(value) && isNonEmptyString(value.id) && isString(value.mime_type) && typeof value.size_bytes === "string" && /^\\d+$/.test(value.size_bytes) && (value.visibility === void 0 || isVisibility(value.visibility));\n}\nasync function upload(context, input4, options) {\n if (!isRecord(input4) || !(input4.file instanceof Blob) || !input4.file.size) throw new NochaError("invalid_request", "A non-empty image, video or audio file is required");\n if (input4.filename !== void 0 && typeof input4.filename !== "string") throw new NochaError("invalid_request", "filename must be a string");\n if (input4.visibility !== void 0 && !isVisibility(input4.visibility)) throw invalid2("visibility must be \'private\' or \'shared\'");\n const file = input4.file, binary = binaryType(file, input4.filename), shared = input4.visibility === "shared";\n let uploaded;\n if (binary) uploaded = await uploadBinary(context, file, binary, input4.filename, shared, options);\n else {\n if (!uploadableTypes.has(file.type)) throw new NochaError("invalid_request", "Choose a JPEG, PNG or WebP image, an MP4 or QuickTime video of at most 1 GiB, or an MP3 or WAV audio file of at most 64 MiB");\n const value = await context.invoke(assetsOperationDefinitions["upload"].capability, assetsOperationDefinitions["upload"].operation, {\n data_base64: bytesToBase64(new Uint8Array(await file.arrayBuffer())),\n mime_type: file.type,\n filename: input4.filename ?? ("name" in file ? String(file.name) : "reference-image"),\n ...shared ? { visibility: "shared" } : {}\n }, options);\n if (!isUploaded(value)) throw new NochaError("invalid_result", "Nocha returned no uploaded asset");\n uploaded = value;\n }\n if (!shared || uploaded.visibility === "shared") return uploaded;\n const visibility = await setVisibility(context, "share", { assetId: uploaded.id }, options?.signal ? { signal: options.signal } : void 0);\n return { ...uploaded, visibility: visibility.visibility };\n}\nfunction assetId(input4) {\n if (!isRecord(input4) || !isUuid(input4.assetId)) throw invalid2("assetId must be an asset id");\n return input4.assetId;\n}\nfunction assetRef(input4) {\n const value = input4;\n if (isRecord(value) && value.assetId === void 0 && isUuid(value.id)) return { assetId: value.id };\n return input4;\n}\nasync function setVisibility(context, operation2, input4, options) {\n const id = assetId(input4);\n const value = await context.invoke(assetsOperationDefinitions[operation2].capability, assetsOperationDefinitions[operation2].operation, { asset_id: id }, options);\n if (!isRecord(value) || value.id !== id || !isVisibility(value.visibility)) throw new NochaError("invalid_result", "Nocha returned no asset visibility");\n return { id, visibility: value.visibility };\n}\nfunction isListItem(value) {\n return isRecord(value) && isUuid(value.id) && isNonEmptyString(value.usage_id) && isNonEmptyString(value.operation) && isVisibility(value.visibility) && (value.retention === "temporary" || value.retention === "durable") && isString(value.created_at) && isNullable(value.expires_at, isString);\n}\nasync function list(context, input4 = {}, options) {\n if (!isRecord(input4) || input4.limit !== void 0 && (!Number.isInteger(input4.limit) || input4.limit < 1 || input4.limit > 100) || input4.cursor !== void 0 && typeof input4.cursor !== "string") throw invalid2("list takes a limit from 1 to 100 and a string cursor");\n const value = await context.invoke(assetsOperationDefinitions["list"].capability, assetsOperationDefinitions["list"].operation, {\n ...input4.cursor ? { cursor: input4.cursor } : {},\n ...input4.limit === void 0 ? {} : { limit: input4.limit }\n }, options);\n if (!isRecord(value) || !Array.isArray(value.items) || !value.items.every(isListItem) || !isNullable(value.next_cursor, isString)) {\n throw new NochaError("invalid_result", "Nocha returned no asset list");\n }\n return { items: value.items, next_cursor: value.next_cursor, nextCursor: value.next_cursor };\n}\nasync function remove(context, input4, options) {\n const value = await context.invoke(assetsOperationDefinitions["remove"].capability, assetsOperationDefinitions["remove"].operation, { asset_id: assetId(input4) }, options);\n if (!isRecord(value) || value.removed !== true) throw new NochaError("invalid_result", "Nocha returned no asset removal");\n return { removed: true };\n}\nfunction createAssets(context) {\n return Object.freeze({\n read: (input4, options) => read2(context, assetRef(input4), options),\n media: (input4, options) => readAssetMedia(context, assetRef(input4), options, (asset, readOptions) => read2(context, asset, readOptions)),\n upload: (input4, options) => upload(context, input4, options),\n uploadAttachment: (input4, options) => uploadAttachment(context, input4, options),\n attachmentUrl: (input4, options) => attachmentUrl(context, input4, options),\n share: (input4, options) => setVisibility(context, "share", assetRef(input4), options),\n unshare: (input4, options) => setVisibility(context, "unshare", assetRef(input4), options),\n setVisibility: (input4, options) => {\n const visibility = isRecord(input4) ? input4.visibility : void 0;\n if (!isVisibility(visibility)) return Promise.reject(invalid2("visibility must be \'private\' or \'shared\'"));\n return visibility === "shared" ? setVisibility(context, "share", assetRef(input4), options) : setVisibility(context, "unshare", assetRef(input4), options);\n },\n list: (input4, options) => list(context, input4, options),\n remove: (input4, options) => remove(context, assetRef(input4), options)\n });\n}\n\n// src/backend-server-error.ts\nvar codes = {\n invalid_request: true,\n identity_required: true,\n workspace_access_denied: true,\n usage_unknown: true,\n usage_operation_denied: true,\n usage_resource_denied: true,\n idempotency_conflict: true,\n database_conflict: true,\n backend_unavailable: true,\n backend_capacity_exceeded: true,\n backend_budget_exhausted: true,\n backend_route_unknown: true,\n backend_route_owner_only: true,\n backend_usage_denied: true,\n backend_resource_protected: true,\n backend_paid_capability_denied: true,\n backend_input_invalid: true,\n backend_output_invalid: true,\n backend_deadline_exceeded: true,\n backend_outcome_unknown: true,\n backend_revision_required: true,\n search_index_unknown: true,\n search_record_too_large: true,\n search_index_full: true,\n search_owner_limit: true,\n search_conflict: true,\n search_filter_invalid: true,\n search_cursor_expired: true,\n search_profile_required: true,\n search_location_required: true,\n search_adults_only: true,\n search_unavailable: true,\n search_asset_denied: true\n};\nfunction isBackendServerErrorCode(value) {\n return typeof value === "string" && Object.hasOwn(codes, value);\n}\nvar BackendServerError = class extends Error {\n code;\n constructor(code) {\n super("Nocha backend operation failed.");\n this.name = "BackendServerError";\n this.code = isBackendServerErrorCode(code) ? code : "backend_unavailable";\n }\n};\n\n// src/backend-server-json.ts\nvar backendServerLimits = Object.freeze({\n outputBytes: 256 * 1024,\n transactionBytes: 128 * 1024,\n recordBytes: 16 * 1024,\n jsonDepth: 16,\n jsonNodes: 16384,\n transactionRecords: 16,\n collectionReads: 8,\n queryRecords: 100\n});\nfunction utf8Bytes(text6) {\n let size = 0;\n for (let index = 0; index < text6.length; index++) {\n const code = text6.charCodeAt(index);\n if (code < 128) size++;\n else if (code < 2048) size += 2;\n else if (code >= 55296 && code <= 56319 && index + 1 < text6.length && text6.charCodeAt(index + 1) >= 56320 && text6.charCodeAt(index + 1) <= 57343) {\n size += 4;\n index++;\n } else size += 3;\n }\n return size;\n}\nfunction encodeBackendServerJson(value, maxBytes2) {\n const fail = () => {\n throw new BackendServerError("backend_input_invalid");\n };\n if (!Number.isSafeInteger(maxBytes2) || maxBytes2 < 1 || maxBytes2 > backendServerLimits.outputBytes) fail();\n let nodes = 0, bytes = 0;\n const seen = /* @__PURE__ */ new Set();\n const add = (text6) => {\n bytes += utf8Bytes(text6);\n if (bytes > maxBytes2) fail();\n return text6;\n };\n function encode2(item, depth) {\n if (++nodes > backendServerLimits.jsonNodes || depth > backendServerLimits.jsonDepth) return fail();\n if (item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item))\n return add(JSON.stringify(item));\n if (typeof item === "string") {\n if (item.length > maxBytes2 - bytes) return fail();\n return add(JSON.stringify(item));\n }\n if (typeof item !== "object" || !item || seen.has(item)) return fail();\n const array = Array.isArray(item);\n if (!array && Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) return fail();\n seen.add(item);\n const keys = Reflect.ownKeys(item);\n if (keys.length > backendServerLimits.jsonNodes - nodes + (array ? 1 : 0)) return fail();\n if (array && (keys.length !== item.length + 1 || keys[keys.length - 1] !== "length")) return fail();\n const parts = [add(array ? "[" : "{")];\n const children = array ? keys.slice(0, -1) : keys;\n for (const [index, key2] of children.entries()) {\n if (typeof key2 !== "string" || ["__proto__", "constructor", "prototype"].includes(key2)) return fail();\n if (array && key2 !== String(index)) return fail();\n const descriptor = Object.getOwnPropertyDescriptor(item, key2);\n if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) return fail();\n if (index) parts.push(add(","));\n if (!array) {\n if (key2.length > maxBytes2 - bytes) return fail();\n parts.push(add(JSON.stringify(key2)), add(":"));\n }\n parts.push(encode2(descriptor.value, depth + 1));\n }\n parts.push(add(array ? "]" : "}"));\n return parts.join("");\n }\n try {\n const text6 = encode2(value, 0);\n return { text: text6, value: JSON.parse(text6) };\n } catch {\n return fail();\n }\n}\n\n// src/backend.ts\nvar routePattern = /^[a-z][a-z0-9_-]{0,79}$/;\nvar receiptPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;\nvar failure2 = (output = false) => new NochaError(output ? "backend_output_invalid" : "backend_input_invalid", "Invalid Nocha backend envelope.");\nvar uncertainErrors = /* @__PURE__ */ new Set([\n "invocation_timed_out",\n "aborted",\n "request_cancelled",\n "request_failed",\n "invalid_response",\n "invalid_result",\n "invocation_failed",\n "unknown_error"\n]);\nfunction record2(value, keys, output = false) {\n try {\n if (!value || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw failure2(output);\n const own = Reflect.ownKeys(value);\n if (own.length !== keys.length || !own.every((key2) => typeof key2 === "string" && keys.includes(key2))) throw failure2(output);\n const copy2 = {};\n for (const key2 of keys) {\n const field3 = Object.getOwnPropertyDescriptor(value, key2);\n if (!field3?.enumerable || !("value" in field3)) throw failure2(output);\n copy2[key2] = field3.value;\n }\n return copy2;\n } catch {\n throw failure2(output);\n }\n}\nfunction json(value, bytes, output = false) {\n try {\n return encodeBackendServerJson(value, bytes).value;\n } catch {\n throw failure2(output);\n }\n}\nfunction receipt(value) {\n if (typeof value !== "string" || !receiptPattern.test(value)) throw failure2();\n return value;\n}\nfunction status(value) {\n let state3;\n try {\n state3 = Object.getOwnPropertyDescriptor(value, "status")?.value;\n } catch {\n throw failure2(true);\n }\n const extra = state3 === "succeeded" ? ["result"] : state3 === "failed" || state3 === "outcome_unknown" ? ["error"] : [];\n const item = record2(value, ["receipt", "routeId", "status", ...extra], true);\n if (typeof item.receipt !== "string" || !receiptPattern.test(item.receipt) || typeof item.routeId !== "string" || !routePattern.test(item.routeId)) throw failure2(true);\n const base2 = { receipt: item.receipt, routeId: item.routeId };\n switch (item.status) {\n case "admitted":\n case "waiting_capacity":\n case "running":\n case "cancelled":\n return { ...base2, status: item.status };\n case "succeeded":\n return { ...base2, status: "succeeded", result: json(item.result, 256 * 1024, true) };\n case "failed":\n case "outcome_unknown": {\n const error = record2(item.error, ["code", "message"], true);\n const code = experienceBackendErrorCodes.find((code2) => code2 === error.code);\n if (!code || typeof error.message !== "string" || !error.message.length || error.message.length > 1e3) throw failure2(true);\n return { ...base2, status: item.status, error: { code, message: "Nocha backend operation failed." } };\n }\n default:\n throw failure2(true);\n }\n}\nfunction createBackend(context) {\n async function invoke2(operation2, input4, idempotencyKey) {\n try {\n const result2 = status(await context.invoke("backend", operation2, input4, { idempotencyKey }));\n const expected = input4;\n if (expected.routeId !== void 0 && result2.routeId !== expected.routeId || expected.receipt !== void 0 && result2.receipt !== expected.receipt) throw failure2(true);\n return result2;\n } catch (cause) {\n if (isNochaError(cause) && !uncertainErrors.has(cause.code)) {\n const message2 = cause.code === "bridge_unavailable" ? "Backend calls require the embedded Nocha host." : cause.code === "backend_unavailable" ? "Nocha backend requires available durable host storage and backend service." : cause.code === "backend_outcome_unknown" ? "Nocha backend outcome is unknown; reconcile the same intention." : "Nocha backend operation could not be completed.";\n throw new NochaError(cause.code, message2);\n }\n throw new NochaError("backend_outcome_unknown", "Nocha backend outcome is unknown; reconcile the same intention.");\n }\n }\n return Object.freeze({\n async request(routeId, input4, options) {\n const parsed = record2(options, ["idempotencyKey"]);\n if (typeof routeId !== "string" || !routePattern.test(routeId) || typeof parsed.idempotencyKey !== "string" || !/^[\\x21-\\x7e]{8,200}$/.test(parsed.idempotencyKey)) throw failure2();\n return invoke2("request", { routeId, input: json(input4, 64 * 1024) }, parsed.idempotencyKey);\n },\n async get(value) {\n const handle = receipt(value);\n return invoke2("get", { receipt: handle }, handle);\n },\n async cancel(value) {\n const handle = receipt(value);\n return invoke2("cancel", { receipt: handle }, handle);\n }\n });\n}\n\n// src/experience-context.ts\nvar current2 = null;\nvar pending = null;\nvar followers = /* @__PURE__ */ new Set();\nfunction snapshot2(value) {\n if (!isExperienceContext(value)) return null;\n const { type, platform, sessionId } = value.device;\n const { language: language2 } = value;\n const kind = value.host?.kind;\n return Object.freeze({\n device: Object.freeze({ type, platform, sessionId }),\n ...isExperienceLanguage(language2) ? { language: language2 } : {},\n ...isExperienceHostKind(kind) ? { host: Object.freeze({ kind }) } : {},\n ...value.spaces === true ? { spaces: true } : {}\n });\n}\nfunction knownExperienceContext() {\n return current2;\n}\nfunction followExperienceContext(listener) {\n followers.add(listener);\n return () => {\n followers.delete(listener);\n };\n}\nasync function get2() {\n assertHostCapability("context");\n if (current2) return current2;\n if (pending) return pending;\n if (hostingPending()) {\n await hostingReady();\n return get2();\n }\n const requestId = crypto.randomUUID();\n pending = new Promise((resolve2, reject2) => {\n const finish = () => {\n clearTimeout(timer);\n unsubscribe3();\n };\n const unsubscribe3 = subscribeBridgeEvents((event) => {\n if (event.type !== "context.snapshot" || !event.payload || typeof event.payload !== "object") return;\n const payload = event.payload;\n if (payload.requestId !== requestId) return;\n const value = snapshot2(payload.context);\n finish();\n if (!value) {\n reject2(new NochaError("invalid_result", "Nocha returned an invalid experience context"));\n return;\n }\n current2 = value;\n markExperienceContextAvailable(value.spaces === true);\n resolve2(value);\n });\n const timer = setTimeout(() => {\n finish();\n reject2(new NochaError("bridge_unavailable", "This reader does not provide experience context"));\n }, 1500);\n try {\n postToHost({\n protocol: NOCHA_BRIDGE_PROTOCOL,\n type: "event",\n event: { type: "context.request", payload: { requestId } }\n });\n } catch {\n finish();\n reject2(new NochaError("bridge_unavailable", "Experience context is unavailable"));\n }\n });\n try {\n return await pending;\n } finally {\n pending = null;\n }\n}\nvar experienceContext = Object.freeze({\n get: get2,\n onChange(listener) {\n assertHostCapability("context");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A context listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== "context.changed") return;\n const value = snapshot2(event.payload);\n if (value) {\n current2 = value;\n markExperienceContextAvailable(value.spaces === true);\n notifyListener(listener, value);\n } else warnOnce("context.changed", "the host sent an experience context this SDK does not understand");\n });\n }\n});\nif (getNochaMode() === "embedded") {\n void get2().catch(() => void 0);\n subscribeBridgeEvents((event) => {\n if (event.type !== "context.changed") return;\n const value = snapshot2(event.payload), previous = current2;\n if (!value) return;\n current2 = value;\n markExperienceContextAvailable(value.spaces === true);\n for (const follower of followers) notifyListener((context) => follower(context, previous), value);\n });\n}\n\n// src/language.ts\nfunction parameterLanguage() {\n if (typeof location === "undefined") return void 0;\n const [primary2, region, ...rest] = (new URLSearchParams(location.search).get("lang") ?? "").trim().replaceAll("_", "-").split("-");\n const value = rest.length ? "" : region === void 0 ? primary2.toLowerCase() : `${primary2.toLowerCase()}-${region.toUpperCase()}`;\n return isExperienceLanguage(value) ? value : void 0;\n}\nfunction hostAnswer(waitMs) {\n let timer;\n return Promise.race([\n experienceContext.get().then(() => void 0, () => void 0),\n new Promise((resolve2) => {\n timer = setTimeout(resolve2, waitMs);\n })\n ]).finally(() => clearTimeout(timer));\n}\nvar language = Object.freeze({\n get() {\n if (getNochaMode() === "embedded") return knownExperienceContext()?.language;\n return parameterLanguage();\n },\n async ready(options) {\n const available = options?.available, waitMs = options?.waitMs ?? 400;\n if (!Array.isArray(available) || !available.length || !available.every(isExperienceLanguage)) {\n throw new NochaError("invalid_request", `language.ready() requires the available languages, tags matching ${EXPERIENCE_LANGUAGE_PATTERN} (fr, en-GB, pt-BR).`);\n }\n if (typeof waitMs !== "number" || !Number.isFinite(waitMs) || waitMs < 0) throw new NochaError("invalid_request", "waitMs is a duration in milliseconds.");\n if (getNochaMode() === "embedded" && !knownExperienceContext()) await hostAnswer(waitMs);\n const browser = typeof navigator === "undefined" ? [] : navigator.languages?.length ? navigator.languages : [navigator.language];\n return matchExperienceLanguage([language.get(), ...browser], available) ?? available[0];\n },\n onChange(listener) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A language listener is required");\n return followExperienceContext((context, previous) => {\n if (context.language && context.language !== previous?.language) listener(context.language);\n });\n }\n});\n\n// src/assistant-controls.ts\nvar PAGE_SIZE = 5;\nvar selector = \'button,a[href],[role="button"],[role="tab"],select,textarea,input:not([type]),input[type="text"],input[type="search"],input[type="button"],input[type="submit"]\';\nvar sensitive = /password|passwd|secret|token|credit.?card|card.?number|cvc|cvv|one.?time|email|e-mail|phone|telephone|address|billing/i;\nvar copy = {\n fr: {\n changed: "Ce contr\\xF4le a chang\\xE9 ou n\\u2019est plus disponible. Relisez le contexte.",\n expected: \'Valeur attendue : {"id":"c1","text":"texte"}.\',\n showControls: "Afficher une page de contr\\xF4les. Valeur : num\\xE9ro de page (1 \\xE0 controlsPages).",\n unknownPage: "Page de contr\\xF4les inconnue.",\n navigateControl: "Apr\\xE8s confirmation Nocha, ouvrir un onglet ou lien interne de kind navigation. Valeur : id cN.",\n setField: \'Apr\\xE8s confirmation Nocha, \\xE9crire dans un champ visible. Sa logique peut enregistrer automatiquement. JSON {"id":"cN","text":"texte"}.\',\n fieldLimit: (maximum) => `Le champ accepte ${maximum} caract\\xE8res maximum.`,\n activateControl: \'Apr\\xE8s confirmation explicite dans Nocha, activer un bouton d\\xE9clar\\xE9. Valeur : id cN. Pour une liste de choix : JSON {"id":"cN","text":"valeur"}. Ne pas annoncer un r\\xE9sultat final sur simple activation.\',\n choiceUnavailable: "Choix indisponible.",\n activated: "Contr\\xF4le activ\\xE9. V\\xE9rifiez le nouvel \\xE9tat pour conna\\xEEtre le r\\xE9sultat."\n },\n en: {\n changed: "This control changed or is no longer available. Read the context again.",\n expected: \'Expected value: {"id":"c1","text":"text"}.\',\n showControls: "Show a page of controls. Value: page number (1 to controlsPages).",\n unknownPage: "Unknown page of controls.",\n navigateControl: "After Nocha confirmation, open a tab or internal link of kind navigation. Value: id cN.",\n setField: \'After Nocha confirmation, write into a visible field. Its logic may save automatically. JSON {"id":"cN","text":"text"}.\',\n fieldLimit: (maximum) => `The field accepts ${maximum} characters at most.`,\n activateControl: \'After explicit confirmation in Nocha, activate a declared button. Value: id cN. For a choice list: JSON {"id":"cN","text":"value"}. Do not announce a final result on mere activation.\',\n choiceUnavailable: "Choice unavailable.",\n activated: "Control activated. Check the new state to learn the result."\n }\n};\nfunction registerAssistantControls(register, options) {\n const { root } = options;\n const text6 = () => copy[matchExperienceLanguage([language.get(), typeof navigator === "undefined" ? void 0 : navigator.language], ["fr", "en"]) === "fr" ? "fr" : "en"];\n const ids2 = /* @__PURE__ */ new WeakMap();\n let nextId = 0, page = 0, stopped = false, timer;\n function controls() {\n const modal = root.querySelector(\'dialog[open],[role="dialog"][aria-modal="true"]\');\n const scope = modal ?? root;\n const result2 = [];\n for (const element2 of Array.from(scope.querySelectorAll(selector))) {\n if (result2.length >= 200) break;\n if (!element2.isConnected || element2.closest(\'[hidden],[inert],[aria-hidden="true"],[data-assistant-private]\') || element2.matches(\':disabled,[aria-disabled="true"]\') || !element2.getClientRects().length) continue;\n const style2 = getComputedStyle(element2);\n if (style2.visibility === "hidden" || style2.display === "none") continue;\n const field3 = element2 instanceof HTMLInputElement || element2 instanceof HTMLTextAreaElement;\n if (field3 && (element2.readOnly || sensitive.test([element2.name, element2.id, element2.autocomplete, element2.getAttribute("aria-label")].join(" ")))) continue;\n if (field3 && element2 instanceof HTMLInputElement && !["text", "search", "button", "submit"].includes(element2.type)) continue;\n const label = (element2.getAttribute("aria-label") || (field3 ? element2.labels?.[0]?.textContent || element2.getAttribute("placeholder") : element2.textContent) || element2.getAttribute("title") || "").replace(/\\s+/g, " ").trim().slice(0, 64);\n if (!label) continue;\n const anchor = element2 instanceof HTMLAnchorElement ? new URL(element2.href, location.href) : null;\n if (anchor && (anchor.origin !== location.origin || anchor.pathname !== location.pathname || anchor.search !== location.search || !anchor.hash || element2.hasAttribute("download"))) continue;\n let id = ids2.get(element2);\n if (!id) {\n id = `c${++nextId}`;\n ids2.set(element2, id);\n }\n const editable3 = element2 instanceof HTMLTextAreaElement || element2 instanceof HTMLInputElement && ["text", "search"].includes(element2.type);\n result2.push({ id, label, kind: anchor || element2.getAttribute("role") === "tab" ? "navigation" : editable3 ? "field" : element2 instanceof HTMLSelectElement ? "choice" : "action", element: element2 });\n }\n return result2;\n }\n function find2(id, kind) {\n const control = controls().find((item) => item.id === id && (!kind || item.kind === kind));\n if (!control) throw new Error(text6().changed);\n return control;\n }\n const done = () => ({ status: "completed" });\n function parse(value) {\n const data = JSON.parse(value);\n if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" || !("text" in data) || typeof data.text !== "string") throw new Error(text6().expected);\n return { id: data.id, text: data.text };\n }\n const binding = register({\n snapshot() {\n const list5 = controls();\n page = Math.min(page, Math.max(0, Math.ceil(list5.length / PAGE_SIZE) - 1));\n return {\n title: options.title.slice(0, 80),\n page: location.hash.slice(0, 100) || "/",\n controlsPage: page + 1,\n controlsPages: Math.max(1, Math.ceil(list5.length / PAGE_SIZE)),\n controls: list5.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE).map(({ id, label, kind, element: element2 }) => ({\n id,\n label,\n kind,\n ...element2 instanceof HTMLSelectElement ? { options: Array.from(element2.options).filter((option) => !option.disabled).slice(0, 8).map((option) => ({ value: option.value.slice(0, 40), label: option.text.slice(0, 40) })) } : {}\n })),\n ...options.snapshot ? { context: options.snapshot() } : {}\n };\n },\n actions: {\n show_controls: { get description() {\n return text6().showControls;\n }, run(value) {\n const next = Number(value);\n if (!Number.isInteger(next) || next < 1 || next > Math.max(1, Math.ceil(controls().length / PAGE_SIZE))) throw new Error(text6().unknownPage);\n page = next - 1;\n return done();\n } },\n navigate_control: { get description() {\n return text6().navigateControl;\n }, run(value) {\n find2(value, "navigation").element.click();\n return done();\n } },\n set_field: { get description() {\n return text6().setField;\n }, run(value) {\n const input4 = parse(value), field3 = find2(input4.id, "field").element;\n const maximum = field3.maxLength >= 0 ? Math.min(1400, field3.maxLength) : 1400;\n if (input4.text.length > maximum) throw new Error(text6().fieldLimit(maximum));\n const prototype = field3 instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;\n Object.getOwnPropertyDescriptor(prototype, "value").set.call(field3, input4.text);\n field3.dispatchEvent(new Event("input", { bubbles: true }));\n field3.dispatchEvent(new Event("change", { bubbles: true }));\n return done();\n } },\n activate_control: { get description() {\n return text6().activateControl;\n }, run(value) {\n if (value.startsWith("{")) {\n const input4 = parse(value), field3 = find2(input4.id, "choice").element;\n if (!Array.from(field3.options).some((option) => option.value === input4.text && !option.disabled)) throw new Error(text6().choiceUnavailable);\n field3.value = input4.text;\n field3.dispatchEvent(new Event("change", { bubbles: true }));\n } else find2(value, "action").element.click();\n return { status: "started", message: text6().activated };\n } }\n }\n });\n const changed = () => {\n if (stopped || timer) return;\n timer = setTimeout(() => {\n timer = void 0;\n binding.changed();\n }, 100);\n };\n const observer = new MutationObserver(changed);\n observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["hidden", "disabled", "aria-hidden", "aria-disabled", "aria-label", "open"] });\n root.addEventListener("input", changed);\n root.addEventListener("change", changed);\n window.addEventListener("hashchange", changed);\n const stopLanguage = language.onChange(changed);\n return { changed: binding.changed, dispose() {\n if (stopped) return;\n stopped = true;\n clearTimeout(timer);\n observer.disconnect();\n root.removeEventListener("input", changed);\n root.removeEventListener("change", changed);\n window.removeEventListener("hashchange", changed);\n stopLanguage();\n binding.dispose();\n } };\n}\n\n// src/assistant-paid.ts\nasync function runAssistantPaidAction(execution, options) {\n const failed = () => ({ status: "failed", message: options.failure ?? "Failed: the reason is shown on screen." });\n let stop = () => {\n };\n const asked = new Promise((resolve2) => {\n stop = options.onAsked(() => resolve2(null));\n });\n const running3 = Promise.resolve().then(() => options.run()).catch(failed);\n let first;\n try {\n first = await Promise.race([running3, asked]);\n } finally {\n stop();\n }\n if (first) return first;\n void running3.then((result2) => execution.report(result2));\n return { status: "awaiting_user", message: options.waiting ?? "Price shown on screen: the participant approves it there. Not done yet." };\n}\n\n// src/assistant-contract.ts\nvar ASSISTANT_CONTEXT_MAX_BYTES = 24 * 1024;\nvar ASSISTANT_ARGUMENTS_MAX_BYTES = 8 * 1024;\nvar ASSISTANT_DESCRIPTION_MAX_CHARS = 4e3;\nvar ASSISTANT_CONFIRMATION_ACTIONS = /* @__PURE__ */ new Set(["navigate_control", "set_field", "activate_control"]);\nvar object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);\nfunction assertAssistantJson(value, maxBytes2, maxDepth = 8) {\n let nodes = 0;\n function visit(item, depth) {\n if (++nodes > 2048 || depth > maxDepth) throw new TypeError("Assistant data is too complex.");\n if (item === null || typeof item === "boolean" || typeof item === "string" || typeof item === "number" && Number.isFinite(item)) return;\n if (Array.isArray(item)) {\n for (const child of item) visit(child, depth + 1);\n return;\n }\n if (object(item) && [Object.prototype, null].includes(Object.getPrototypeOf(item))) {\n for (const [key2, child] of Object.entries(item)) {\n if (["__proto__", "constructor", "prototype"].includes(key2)) throw new TypeError("Unsafe Assistant data key.");\n visit(child, depth + 1);\n }\n return;\n }\n throw new TypeError("Assistant data must contain JSON values only.");\n }\n visit(value, 0);\n if (new TextEncoder().encode(JSON.stringify(value)).length > maxBytes2) throw new TypeError("Assistant data exceeds its byte budget.");\n}\nfunction assertAssistantArgumentsSchema(value) {\n assertAssistantJson(value, 4096, 14);\n function visit(schema, depth) {\n if (!object(schema) || depth > 6 || !["object", "array", "string", "number", "integer", "boolean", "null"].includes(String(schema.type))) throw new TypeError("Assistant argument schemas require an explicit supported type.");\n const common2 = ["type", "title", "description", "enum", "const"];\n const typed = schema.type === "object" ? ["properties", "required", "additionalProperties"] : schema.type === "array" ? ["items", "minItems", "maxItems"] : schema.type === "string" ? ["minLength", "maxLength"] : ["number", "integer"].includes(String(schema.type)) ? ["minimum", "maximum"] : [];\n if (Object.keys(schema).some((key2) => !common2.includes(key2) && !typed.includes(key2))) throw new TypeError("Unsupported Assistant JSON Schema keyword.");\n for (const key2 of ["title", "description"]) if (schema[key2] !== void 0 && typeof schema[key2] !== "string") throw new TypeError("Schema annotations must be text.");\n if (schema.enum !== void 0 && (!Array.isArray(schema.enum) || !schema.enum.length)) throw new TypeError("Schema enum must be a non-empty array.");\n if (schema.properties !== void 0) {\n if (!object(schema.properties)) throw new TypeError("Schema properties must be an object.");\n for (const child of Object.values(schema.properties)) visit(child, depth + 1);\n }\n if (schema.required !== void 0 && (!Array.isArray(schema.required) || schema.required.some((key2) => typeof key2 !== "string" || !object(schema.properties) || !Object.hasOwn(schema.properties, key2)))) throw new TypeError("Schema required keys must have declared properties.");\n if (schema.additionalProperties !== void 0 && typeof schema.additionalProperties !== "boolean") throw new TypeError("Schema additionalProperties must be a boolean.");\n if (schema.items !== void 0) visit(schema.items, depth + 1);\n for (const key2 of ["minLength", "maxLength", "minItems", "maxItems"]) if (schema[key2] !== void 0 && (!Number.isSafeInteger(schema[key2]) || Number(schema[key2]) < 0)) throw new TypeError("Schema limits must be positive integers.");\n for (const key2 of ["minimum", "maximum"]) if (schema[key2] !== void 0 && (typeof schema[key2] !== "number" || !Number.isFinite(schema[key2]))) throw new TypeError("Schema limits must be finite numbers.");\n }\n visit(value, 0);\n if (!object(value) || value.type !== "object") throw new TypeError("Assistant arguments must use an object schema.");\n}\nfunction canonical(value) {\n if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;\n if (object(value)) return `{${Object.keys(value).sort().map((key2) => `${JSON.stringify(key2)}:${canonical(value[key2])}`).join(",")}}`;\n return JSON.stringify(value);\n}\nfunction assertAssistantArguments(value, schema) {\n assertAssistantArgumentsSchema(schema);\n assertAssistantJson(value, ASSISTANT_ARGUMENTS_MAX_BYTES);\n function visit(item, node, path) {\n const fail = () => {\n throw new TypeError(`Invalid Assistant argument at ${path}.`);\n };\n if (node.const !== void 0 && canonical(item) !== canonical(node.const)) fail();\n if (node.enum && !node.enum.some((candidate) => canonical(candidate) === canonical(item))) fail();\n if (node.type === "object") {\n if (!object(item)) {\n fail();\n return;\n }\n if (node.required?.some((key2) => !Object.hasOwn(item, key2))) fail();\n for (const [key2, child] of Object.entries(item)) {\n const next = node.properties && Object.hasOwn(node.properties, key2) ? node.properties[key2] : void 0;\n if (next) visit(child, next, `${path}.${key2}`);\n else if (node.additionalProperties === false) fail();\n }\n } else if (node.type === "array") {\n if (!Array.isArray(item)) {\n fail();\n return;\n }\n if (node.minItems !== void 0 && item.length < node.minItems || node.maxItems !== void 0 && item.length > node.maxItems) fail();\n if (node.items) item.forEach((child, index) => visit(child, node.items, `${path}[${index}]`));\n } else if (node.type === "string") {\n if (typeof item !== "string") {\n fail();\n return;\n }\n const length = Array.from(item).length;\n if (node.minLength !== void 0 && length < node.minLength || node.maxLength !== void 0 && length > node.maxLength) fail();\n } else if (node.type === "number" || node.type === "integer") {\n if (typeof item !== "number" || node.type === "integer" && !Number.isInteger(item)) {\n fail();\n return;\n }\n if (node.minimum !== void 0 && item < node.minimum || node.maximum !== void 0 && item > node.maximum) fail();\n } else if (node.type === "null" ? item !== null : typeof item !== "boolean") fail();\n }\n visit(value, schema, "arguments");\n}\n\n// src/assistant.ts\nvar record3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;\nvar actionName = /^[a-z][a-z0-9_]{0,39}$/;\nvar featureId = /^[a-z][a-z0-9_]{0,31}$/;\nvar release;\nvar composition;\nfunction assertActions(entries) {\n if (entries.length > 24 || entries.some(([name, action]) => !actionName.test(name) || typeof action.description !== "string" || action.description.length > ASSISTANT_DESCRIPTION_MAX_CHARS || typeof action.run !== "function")) throw new NochaError("invalid_request", "Assistant actions require up to 24 names (40 characters), descriptions (4000 characters), and handlers.");\n for (const [, action] of entries) {\n if (action.argumentsSchema !== void 0) assertAssistantArgumentsSchema(action.argumentsSchema);\n if (action.confirmation !== void 0 && !["required", "none"].includes(action.confirmation)) throw new NochaError("invalid_request", "Invalid Assistant confirmation policy.");\n }\n}\nfunction describe(state3, entries) {\n if (!record3(state3)) throw new NochaError("invalid_request", "Assistant snapshot must be a JSON object.");\n assertAssistantJson(state3, 12 * 1024, 6);\n const actions = entries.map(([name, action]) => {\n const availability = typeof action.availability === "function" ? action.availability() : action.availability ?? { available: true };\n if (typeof availability.available !== "boolean" || availability.reason !== void 0 && (typeof availability.reason !== "string" || availability.reason.length > 400)) throw new NochaError("invalid_request", "Invalid Assistant action availability.");\n return {\n name,\n description: action.description,\n ...action.argumentsSchema ? { argumentsSchema: action.argumentsSchema } : {},\n availability,\n confirmation: ASSISTANT_CONFIRMATION_ACTIONS.has(name) ? "required" : action.confirmation ?? "none"\n };\n });\n const value = { state: state3, actions };\n assertAssistantJson(value, ASSISTANT_CONTEXT_MAX_BYTES - 256, 18);\n return value;\n}\nvar unavailable = Object.freeze({ available: false, reason: "This feature\'s state is unavailable." });\nvar legacyCompatible = (entries) => entries.every(([, action]) => !action.argumentsSchema && action.description.length <= 400 && (action.availability === void 0 || action.availability === unavailable) && action.confirmation !== "required");\nfunction connect(source2) {\n const bridgeId = crypto.randomUUID();\n const calls = /* @__PURE__ */ new Map();\n let settled2 = 0;\n const host2 = typeof window !== "undefined" && window.parent !== window;\n let disposed = false, version = 1, revision2 = 0, timer, negotiation, last = "";\n function send3(event) {\n if (!disposed && host2) postToHost({ protocol: NOCHA_BRIDGE_PROTOCOL, type: "event", event: { ...event, bridgeId } });\n }\n function context() {\n const state3 = source2.snapshot(), entries = source2.actions(), value = describe(state3, entries);\n const encoded = JSON.stringify(value);\n if (encoded !== last) {\n revision2++;\n last = encoded;\n }\n return { value, entries };\n }\n function publish(force = false) {\n if (disposed) return;\n const previous = last, { value, entries } = context();\n if (version === 1 && !legacyCompatible(entries)) return;\n if (!force && previous === last) return;\n const event = version === 2 ? { type: "experience.assistant.context", version, contextRevision: String(revision2), ...value } : { type: "experience.assistant.context", version, state: value.state, actions: entries.filter(([, action]) => action.availability !== unavailable).map(([name, action]) => ({ name, description: action.description })) };\n assertAssistantJson({ ...event, bridgeId }, version === 2 ? ASSISTANT_CONTEXT_MAX_BYTES : 12 * 1024, 18);\n send3(event);\n }\n function reportError(error) {\n if (typeof source2.onError === "function") notifyListener(source2.onError.bind(source2), error instanceof Error ? error : new Error(String(error)));\n }\n function safePublish(force = false) {\n try {\n publish(force);\n } catch (error) {\n last = "";\n send3({ type: "experience.assistant.clear" });\n reportError(error);\n }\n }\n function observe(callId, result2) {\n const call2 = calls.get(callId);\n if (!call2 || call2.terminal || disposed) return;\n if (!result2 || !["completed", "started", "awaiting_user", "failed"].includes(result2.status)) throw new NochaError("invalid_request", "The action did not return a valid outcome.");\n assertAssistantJson(result2, 8192);\n if (result2.message !== void 0 && (typeof result2.message !== "string" || result2.message.length > 2e3)) throw new NochaError("invalid_request", "Assistant outcome messages have at most 2000 characters.");\n call2.terminal = result2.status === "completed" || result2.status === "failed";\n call2.latest = { ok: result2.status !== "failed", ...result2 };\n if (call2.terminal) {\n calls.delete(callId);\n calls.set(callId, call2);\n settled2++;\n for (const [id, entry] of calls) {\n if (settled2 <= 200) break;\n if (entry.terminal) {\n calls.delete(id);\n settled2--;\n }\n }\n }\n send3({ type: "experience.assistant.result", callId, contextRevision: String(revision2), result: call2.latest });\n safePublish();\n }\n function receive(event) {\n if (!host2 || !isFromHost(event)) return;\n const envelope = record3(event.data), message2 = record3(envelope?.event);\n if (envelope?.protocol !== NOCHA_BRIDGE_PROTOCOL || envelope.type !== "event" || !message2) return;\n if (message2.type === "experience.assistant.request") {\n if (Array.isArray(message2.versions) && message2.versions.includes(2)) {\n version = 2;\n clearTimeout(negotiation);\n }\n safePublish(true);\n return;\n }\n if (message2.bridgeId !== bridgeId) return;\n if (message2.type === "experience.assistant.accept" && message2.version === 2) {\n version = 2;\n clearTimeout(negotiation);\n safePublish(true);\n return;\n }\n if (message2.type !== "experience.assistant.action") return;\n const { callId, action: name } = message2;\n if (typeof callId !== "string" || !callId.length || callId.length > 160 || typeof name !== "string") return;\n const previous = calls.get(callId);\n if (previous) {\n send3({ type: "experience.assistant.result", callId, contextRevision: String(revision2), result: previous.latest });\n return;\n }\n if (calls.size - settled2 >= 200) {\n send3({ type: "experience.assistant.result", callId, result: { ok: false, status: "failed", message: "Too many assistant actions are in progress. Retry once one of them finishes." } });\n return;\n }\n calls.set(callId, { latest: { ok: true, status: "started" }, terminal: false });\n void Promise.resolve().then(() => {\n if (disposed) throw new Error("The experience was closed.");\n const { value: latest2, entries } = context(), action = entries.find(([key2]) => key2 === name)?.[1], contract = latest2.actions.find((item) => item.name === name);\n if (!action || !contract || !contract.availability.available) throw new Error(contract?.availability.reason || "This action is unavailable.");\n if (version === 2 && message2.expectedContextRevision !== String(revision2)) {\n safePublish(true);\n throw new Error("Experience context changed. Read the current revision before acting.");\n }\n if (version === 2 && contract.confirmation === "required" && message2.confirmed !== true) throw new Error("This action requires host confirmation.");\n const execution = { callId, report: (result2) => observe(callId, result2) };\n if (action.argumentsSchema) {\n if (version !== 2) throw new Error("Structured arguments require Assistant bridge v2.");\n assertAssistantArguments(message2.arguments, action.argumentsSchema);\n return action.run(message2.arguments, execution);\n }\n const value = message2.value ?? record3(message2.arguments)?.value ?? "";\n if (typeof value !== "string" || value.length > 1600) throw new NochaError("invalid_request", "Legacy Assistant values are strings of at most 1600 characters.");\n return action.run(value, execution);\n }).then((result2) => observe(callId, result2)).catch((error) => observe(callId, { status: "failed", message: (error instanceof Error ? error.message : String(error)).slice(0, 2e3) }));\n }\n context();\n release?.();\n if (host2) window.addEventListener("message", receive);\n send3({ type: "experience.assistant.hello", versions: [2, 1] });\n safePublish(true);\n if (host2) negotiation = setTimeout(() => {\n if (version !== 2 && !legacyCompatible(source2.actions())) reportError(new Error("This experience requires a Nocha host supporting Assistant bridge v2."));\n }, 2e3);\n const binding = {\n changed() {\n if (disposed) return;\n clearTimeout(timer);\n timer = setTimeout(() => safePublish(), 100);\n },\n dispose() {\n if (disposed) return;\n send3({ type: "experience.assistant.clear" });\n disposed = true;\n clearTimeout(timer);\n clearTimeout(negotiation);\n if (host2) window.removeEventListener("message", receive);\n if (release === binding.dispose) release = void 0;\n source2.onDispose?.();\n }\n };\n release = binding.dispose;\n return binding;\n}\nfunction composedState(features2, failed, report) {\n const state3 = {}, previous = new Map(failed);\n failed.clear();\n for (const [id, feature] of features2) {\n try {\n const value = feature.snapshot ? feature.snapshot() : {};\n if (!record3(value)) throw new TypeError("snapshot must be a JSON object.");\n assertAssistantJson(value, 12 * 1024, 4);\n state3[id] = value;\n } catch (error) {\n const message2 = `Assistant feature ${id}: ${error instanceof Error ? error.message : String(error)}`;\n failed.set(id, message2);\n state3[id] = { unavailable: true };\n if (previous.get(id) !== message2) report?.(new NochaError("invalid_request", message2));\n }\n }\n return { features: state3 };\n}\nvar composedActions = (features2, failed) => [...features2].flatMap(([id, feature]) => failed.has(id) ? feature.actions.map(([name, action]) => [name, { ...action, availability: unavailable }]) : feature.actions);\nvar shortcuts = Object.freeze([]);\nvar shortcutListeners = /* @__PURE__ */ new Set();\nvar editable = (target) => target instanceof HTMLElement && (target.isContentEditable || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement || target instanceof HTMLInputElement && !["button", "checkbox", "color", "file", "image", "radio", "range", "reset", "submit"].includes(target.type));\nfunction onShortcutKey(event) {\n if (event.repeat || event.isComposing) return;\n const keys = shortcutKeysFromEvent(event);\n if (!keys || !shortcuts.some((shortcut) => shortcut.keys === keys)) return;\n if (editable(event.composedPath()[0] ?? event.target) && !event.metaKey && !event.ctrlKey) return;\n event.preventDefault();\n event.stopImmediatePropagation();\n postToHost({ protocol: NOCHA_BRIDGE_PROTOCOL, type: "event", event: { type: ASSISTANT_SHORTCUT_EVENT, payload: { keys } } });\n}\nif (getNochaMode() === "embedded") {\n subscribeBridgeEvents((event) => {\n if (event.type !== ASSISTANT_SHORTCUTS_EVENT) return;\n const list5 = record3(event.payload)?.shortcuts;\n if (!isAssistantShortcuts(list5)) return;\n const next = list5.map(({ action, keys, label, scope }) => Object.freeze({ action, keys, label, scope }));\n if (JSON.stringify(next) === JSON.stringify(shortcuts)) return;\n const had = shortcuts.length > 0;\n shortcuts = Object.freeze(next);\n if (shortcuts.length && !had) window.addEventListener("keydown", onShortcutKey, true);\n else if (!shortcuts.length && had) window.removeEventListener("keydown", onShortcutKey, true);\n for (const listener of [...shortcutListeners]) notifyListener(listener, shortcuts);\n });\n}\nvar OPEN_ANSWER_MS = 2e3;\nvar opening = false;\nasync function openAssistant(options) {\n assertHostCapability("assistant");\n if (options !== void 0 && !record3(options)) throw new NochaError("invalid_request", "Assistant open options must be an object.");\n const thread = options?.thread;\n if (thread !== void 0 && !isAssistantThread(thread)) throw new NochaError("invalid_request", "An assistant thread has 1 to 64 lowercase letters, digits, underscores or hyphens, starting with a letter.");\n const draft = options?.draft;\n if (draft !== void 0 && !isAssistantDraft(draft)) throw new NochaError("invalid_request", `An assistant draft is non-blank text of at most ${ASSISTANT_OPEN_DRAFT_MAX} characters.`);\n if (typeof navigator !== "undefined" && navigator.userActivation && !navigator.userActivation.isActive) throw new NochaError("user_action_required", "Open the assistant from a button or another deliberate user action");\n if (opening) throw new NochaError("rate_limited", "An assistant open request is already waiting for the host.");\n opening = true;\n try {\n if (hostingPending()) {\n await hostingReady();\n assertHostCapability("assistant");\n }\n const requestId = crypto.randomUUID();\n await new Promise((resolve2, reject2) => {\n const timer = setTimeout(() => {\n stop();\n reject2(new NochaError("capability_denied", "This Nocha host cannot open the assistant."));\n }, OPEN_ANSWER_MS);\n const stop = subscribeBridgeEvents((event) => {\n const answer = record3(event.payload);\n if (event.type !== ASSISTANT_OPENED_EVENT || answer?.requestId !== requestId) return;\n clearTimeout(timer);\n stop();\n if (answer.ok === true) {\n resolve2();\n return;\n }\n const code = ASSISTANT_OPEN_REFUSALS.includes(answer.code) ? answer.code : "capability_denied";\n reject2(new NochaError(code, code === "rate_limited" ? "Nocha just opened the assistant; wait for another user action." : code === "user_action_required" ? "Open the assistant while the person is on the experience, from a deliberate user action." : "Nocha cannot open the assistant here."));\n });\n postToHost({ protocol: NOCHA_BRIDGE_PROTOCOL, type: "event", event: { type: ASSISTANT_OPEN_EVENT, payload: { requestId, ...thread !== void 0 ? { thread } : {}, ...draft !== void 0 ? { draft } : {} } } });\n });\n } finally {\n opening = false;\n }\n}\nvar assistant = Object.freeze({\n registerControls(options) {\n assertHostCapability("assistant");\n return registerAssistantControls(assistant.register, options);\n },\n register(registration) {\n assertHostCapability("assistant");\n if (!record3(registration) || typeof registration.snapshot !== "function" || !record3(registration.actions)) {\n throw new NochaError("invalid_request", "Assistant registration requires snapshot() and an actions object.");\n }\n const entries = Object.entries(registration.actions);\n assertActions(entries);\n return connect({ snapshot: () => registration.snapshot(), actions: () => entries, onError: (error) => {\n if (typeof registration.onError === "function") registration.onError(error);\n } });\n },\n feature(id, options) {\n assertHostCapability("assistant");\n if (typeof id !== "string" || !featureId.test(id)) throw new NochaError("invalid_request", "Assistant feature ids have 1 to 32 lowercase letters, digits or underscores, starting with a letter.");\n if (!record3(options) || options.snapshot !== void 0 && typeof options.snapshot !== "function" || !record3(options.actions)) {\n throw new NochaError("invalid_request", "An Assistant feature requires an actions object and an optional snapshot().");\n }\n const actions = Object.entries(options.actions);\n assertActions(actions);\n const features2 = new Map(composition?.features);\n features2.delete(id);\n for (const [name] of actions) for (const [other, feature] of features2) {\n if (feature.actions.some(([taken]) => taken === name)) throw new NochaError("invalid_request", `Assistant action ${name} is already registered by feature ${other}.`);\n }\n if ([...features2.values()].reduce((sum, feature) => sum + feature.actions.length, actions.length) > 24) throw new NochaError("invalid_request", "Assistant features register up to 24 actions at once.");\n const entry = { ...options.snapshot ? { snapshot: () => options.snapshot() } : {}, actions };\n features2.set(id, entry);\n const failed = /* @__PURE__ */ new Map(), state3 = composedState(features2, failed);\n if (failed.has(id)) throw new NochaError("invalid_request", failed.get(id));\n describe(state3, composedActions(features2, failed));\n if (composition) {\n composition.features = features2;\n composition.binding.changed();\n } else {\n const active3 = { features: features2, failed: /* @__PURE__ */ new Map() };\n const report = (error) => console.error("Nocha assistant feature failed", error);\n active3.binding = connect({\n snapshot: () => composedState(active3.features, active3.failed, report),\n actions: () => composedActions(active3.features, active3.failed),\n onError: report,\n onDispose: () => {\n if (composition === active3) composition = void 0;\n }\n });\n composition = active3;\n }\n return {\n changed() {\n if (composition?.features.get(id) === entry) composition.binding.changed();\n },\n dispose() {\n const active3 = composition;\n if (active3?.features.get(id) !== entry) return;\n const rest = new Map(active3.features);\n rest.delete(id);\n if (!rest.size) {\n active3.binding.dispose();\n return;\n }\n active3.features = rest;\n active3.binding.changed();\n }\n };\n },\n shortcuts: () => shortcuts,\n open: openAssistant,\n paidAction: runAssistantPaidAction,\n onShortcuts(listener) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A shortcuts listener is required");\n shortcutListeners.add(listener);\n return () => {\n shortcutListeners.delete(listener);\n };\n }\n});\n\n// src/context.ts\nfunction createContext(usageId) {\n if (usageId !== void 0 && !isUsageId(usageId)) {\n throw new NochaError("invalid_request", "nocha.use() requires a usage id declared in NOCHA.json");\n }\n const optionsFor = (capability, operation2, options) => {\n assertHostCapability(capability);\n if (usageId === void 0 && !usageFreeCapabilities.has(capability)) throw new NochaError("usage_required", `${capability}.${operation2} requires nocha.use(<declared usage id>)`);\n if (options === null || typeof options !== "object") throw new NochaError("invalid_request", "Request options must be an object");\n const { idempotencyKey, timeoutMs, signal } = options;\n return {\n ...idempotencyKey !== void 0 ? { idempotencyKey } : {},\n ...timeoutMs !== void 0 ? { timeoutMs } : {},\n ...signal !== void 0 ? { signal } : {},\n ...usageId !== void 0 ? { usageId } : {}\n };\n };\n const spaced = (input4, options) => {\n if (options?.space === void 0) return input4;\n if (!isSpaceRef(options.space)) throw new NochaError("invalid_request", "space must be the ref of an attached space");\n if (input4 === null || typeof input4 !== "object" || Array.isArray(input4)) return input4;\n return { ...input4, [SPACE_INPUT_KEY]: options.space };\n };\n const invoke2 = (capability, operation2, input4 = {}, options = {}) => {\n try {\n return invokeBridge(capability, operation2, spaced(input4, options), optionsFor(capability, operation2, options));\n } catch (error) {\n return Promise.reject(error);\n }\n };\n const invokeWithPort = (capability, operation2, input4 = {}, options = {}) => {\n try {\n return invokeBridgeWithPort(capability, operation2, spaced(input4, options), optionsFor(capability, operation2, options));\n } catch (error) {\n return Promise.reject(error);\n }\n };\n return Object.freeze({ usageId, invoke: invoke2, invokeWithPort });\n}\n\n// src/failure.ts\nvar UNAVAILABLE = new Set(hostUnavailableErrorCodes);\nvar UNKNOWN_OUTCOME = new Set(unknownOutcomeErrorCodes);\nvar MAX_ATTEMPTS = 4;\nvar GENERATION_WAITS_MS = [3e3, 6e3, 1e4, 12e3, 12e3];\nfunction liveMediaCode(error) {\n if (isNochaError(error) || error === null || typeof error !== "object") return void 0;\n const code = error.nochaCode;\n return typeof code === "string" && code ? code : void 0;\n}\nfunction sdkFailureCode(error) {\n return isNochaError(error) ? error.wireCode ?? error.code : liveMediaCode(error);\n}\nfunction errorCodeOf(error) {\n const known = sdkFailureCode(error);\n if (known !== void 0) return known;\n const code = error !== null && typeof error === "object" ? error.code : void 0;\n return typeof code === "string" && code ? code : void 0;\n}\nfunction hasErrorCode(error, ...codes2) {\n const code = errorCodeOf(error);\n return code !== void 0 && codes2.includes(code);\n}\nfunction describeFailure(error) {\n const sdkClass = classifyError(error);\n const retryable = sdkClass === "transient";\n if (!isNochaError(error)) {\n const live = liveMediaCode(error);\n if (live !== void 0 && sdkClass !== "aborted") {\n if (!isNochaErrorCode(live)) return { kind: "unexpected", retryable: false, wireCode: live };\n const liveClass = nochaErrorClasses[live];\n return { kind: kindOf(live, liveClass), retryable: liveClass === "transient", code: live };\n }\n return { kind: sdkClass === "aborted" ? "cancelled" : "unexpected", retryable };\n }\n return {\n kind: kindOf(error.code, sdkClass),\n retryable,\n code: error.code,\n ...error.wireCode !== void 0 ? { wireCode: error.wireCode } : {},\n ...error.trace_id !== void 0 ? { traceId: error.trace_id } : {},\n ...error.operation_id !== void 0 ? { operationId: error.operation_id } : {},\n ...error.idempotency_key !== void 0 ? { idempotencyKey: error.idempotency_key } : {}\n };\n}\nfunction kindOf(code, sdkClass) {\n if (sdkClass === "aborted") return "cancelled";\n if (UNAVAILABLE.has(code)) return "unavailable";\n if (UNKNOWN_OUTCOME.has(code)) return "unknown_outcome";\n if (sdkClass === "transient") return "transient";\n if (sdkClass === "denied" || sdkClass === "billing") return "denied";\n return sdkClass === "invalid" ? "invalid" : "unexpected";\n}\nfunction shouldRetry(error, attempt) {\n return attempt + 1 < MAX_ATTEMPTS && describeFailure(error).retryable;\n}\nasync function retrying(call2, signal) {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await call2();\n } catch (error) {\n if (signal.aborted || !shouldRetry(error, attempt)) throw error;\n await pauseFor(500 * 2 ** attempt * (0.5 + Math.random() / 2), signal);\n }\n }\n}\nasync function retryingGeneration(call2, signal, onWait) {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await call2();\n } catch (error) {\n const wait2 = GENERATION_WAITS_MS[attempt];\n if (signal.aborted || wait2 === void 0 || !describeFailure(error).retryable) throw error;\n onWait?.(attempt + 1, wait2);\n await pauseFor(wait2, signal);\n }\n }\n}\nfunction pauseFor(ms2, signal) {\n return new Promise((resolve2, reject2) => {\n const aborted = () => new DOMException("Retry wait aborted", "AbortError");\n if (signal?.aborted) {\n reject2(aborted());\n return;\n }\n const stop = () => {\n clearTimeout(timer);\n reject2(aborted());\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener("abort", stop);\n resolve2();\n }, ms2);\n signal?.addEventListener("abort", stop, { once: true });\n });\n}\n\n// src/live-media-failure.ts\nvar liveMediaMessages = Object.freeze({\n elsewhere: {\n fr: "La cam\\xE9ra et le micro ne sont pas disponibles ici. Ouvrez l\\u2019exp\\xE9rience \\xE0 son adresse pour les utiliser.",\n en: "Camera and microphone are not available here. Open the experience at its own address to use them."\n },\n sign_in: { fr: "Connectez-vous pour utiliser la cam\\xE9ra ou le micro.", en: "Sign in to use the camera or microphone." },\n denied: {\n fr: "L\\u2019acc\\xE8s \\xE0 la cam\\xE9ra ou au micro est refus\\xE9. Autorisez-le dans les r\\xE9glages, puis r\\xE9essayez.",\n en: "Camera or microphone access is denied. Allow it in your settings, then try again."\n },\n busy: {\n fr: "La cam\\xE9ra ou le micro est utilis\\xE9 ailleurs. R\\xE9essayez dans un instant.",\n en: "The camera or microphone is in use elsewhere. Try again in a moment."\n },\n missing: {\n fr: "Aucune cam\\xE9ra ni aucun micro trouv\\xE9. Branchez-en un, puis r\\xE9essayez.",\n en: "No camera or microphone found. Connect one, then try again."\n },\n hidden: { fr: "Revenez sur l\\u2019exp\\xE9rience pour utiliser la cam\\xE9ra ou le micro.", en: "Return to the experience to use the camera or microphone." },\n update: {\n fr: "Cette version de Nocha ne prend pas en charge la cam\\xE9ra ni le micro en direct. Mettez Nocha \\xE0 jour.",\n en: "This version of Nocha does not support the live camera or microphone. Update Nocha."\n },\n usage: {\n fr: "Cette exp\\xE9rience n\\u2019a pas d\\xE9clar\\xE9 l\\u2019acc\\xE8s \\xE0 la cam\\xE9ra ou au micro.",\n en: "This experience has not declared camera or microphone access."\n },\n standalone: { fr: "La cam\\xE9ra et le micro ne sont disponibles que dans Nocha.", en: "Camera and microphone are only available in Nocha." },\n cancelled: { fr: "La demande de cam\\xE9ra ou de micro est annul\\xE9e.", en: "The camera or microphone request was cancelled." },\n unexpected: { fr: "La cam\\xE9ra ou le micro n\\u2019a pas pu d\\xE9marrer. R\\xE9essayez.", en: "The camera or microphone could not start. Try again." }\n});\nvar isLiveMediaProblem = (value) => typeof value === "string" && Object.hasOwn(liveMediaMessages, value);\nvar PROBLEMS = {\n media_requires_experience_host: "elsewhere",\n media_sign_in_required: "sign_in",\n sign_in_required: "sign_in",\n identity_required: "sign_in",\n authentication_required: "sign_in",\n media_permission_denied: "denied",\n device_permission_denied: "denied",\n NotAllowedError: "denied",\n SecurityError: "denied",\n media_device_busy: "busy",\n device_busy: "busy",\n device_timeout: "busy",\n NotReadableError: "busy",\n media_device_missing: "missing",\n device_unavailable: "missing",\n NotFoundError: "missing",\n OverconstrainedError: "missing",\n device_inactive: "hidden",\n device_operation_unknown: "update",\n client_update_required: "update",\n media_unsupported_host: "update",\n native_host_required: "update",\n NotSupportedError: "update",\n usage_unknown: "usage",\n usage_operation_denied: "usage",\n usage_resource_denied: "usage",\n usage_scope_denied: "usage",\n usage_required: "usage",\n capability_denied: "usage",\n bridge_unavailable: "standalone",\n aborted: "cancelled",\n request_cancelled: "cancelled",\n AbortError: "cancelled"\n};\nvar RETRY = {\n elsewhere: "never",\n sign_in: "gesture",\n denied: "gesture",\n busy: "later",\n missing: "gesture",\n hidden: "gesture",\n update: "never",\n usage: "never",\n standalone: "never",\n cancelled: "gesture"\n};\nvar HOST_WORDED = /* @__PURE__ */ new Set([\n "media_requires_experience_host",\n "media_sign_in_required",\n "media_permission_denied",\n "media_device_busy",\n "media_device_missing"\n]);\nfunction liveMediaLanguage(options) {\n const tag2 = options?.language ?? language.get();\n return typeof tag2 === "string" && tag2.toLowerCase().split("-")[0] === "fr" ? "fr" : "en";\n}\nfunction hostDetails(error) {\n if (isNochaError(error)) return error.details;\n const details = error !== null && typeof error === "object" ? error.nochaDetails : void 0;\n return details !== null && typeof details === "object" ? details : void 0;\n}\nfunction describeLiveMediaFailure(error, options) {\n const host2 = sdkFailureCode(error);\n const name = error !== null && typeof error === "object" ? error.name : void 0;\n const code = host2 ?? (typeof name === "string" && name && name !== "Error" ? name : "unknown_error");\n let problem = Object.hasOwn(PROBLEMS, code) ? PROBLEMS[code] : "unexpected";\n if (problem === "busy" && typeof document !== "undefined" && document.visibilityState === "hidden") problem = "hidden";\n const failure4 = describeFailure(error);\n const retry2 = problem !== "unexpected" ? RETRY[problem] : failure4.retryable ? "later" : failure4.kind === "invalid" || failure4.kind === "unavailable" ? "never" : "gesture";\n const hostMessage = host2 !== void 0 && HOST_WORDED.has(host2) ? error.message : void 0;\n const own = typeof hostMessage === "string" ? hostMessage.trim() : "";\n return {\n problem,\n code,\n message: own || liveMediaMessages[problem][liveMediaLanguage(options)],\n retry: retry2,\n hostOffersAddress: problem === "elsewhere" && host2 === "media_requires_experience_host" && hostDetails(error)?.offersAddress !== false\n };\n}\n\n// src/live-media-status.ts\nfunction liveMediaStatusOf(entry, options) {\n if (!isRecord(entry) || !isBoolean(entry.available)) return "unknown";\n if (entry.available) return { available: true };\n const problem = isLiveMediaProblem(entry.problem) ? entry.problem : "unexpected";\n const reason2 = isString(entry.reason) ? entry.reason.trim() : "";\n return { available: false, problem, message: reason2 || liveMediaMessages[problem][liveMediaLanguage(options)] };\n}\nvar liveMediaOffersAddress = (entry) => isRecord(entry) && entry.available === false && entry.problem === "elsewhere" && entry.offersAddress !== false;\n\n// src/live-media.ts\nvar installedMediaDevices = /* @__PURE__ */ new WeakSet();\nfunction domFailure(name, message2, code, details) {\n const error = new DOMException(message2, name);\n Object.defineProperty(error, "nochaCode", { configurable: true, enumerable: false, value: code });\n if (details) Object.defineProperty(error, "nochaDetails", { configurable: true, enumerable: false, value: details });\n return error;\n}\nfunction bridgeFailure(error) {\n const code = isNochaError(error) ? error.wireCode ?? error.code : "unknown_error";\n const message2 = error instanceof Error && error.message ? error.message : "Live camera or microphone access failed";\n const details = isNochaError(error) ? error.details : void 0;\n if (code === "media_permission_denied") return domFailure("NotAllowedError", message2, code, details);\n if (code === "media_device_busy") return domFailure("NotReadableError", message2, code, details);\n if (code === "media_device_missing") return domFailure("NotFoundError", message2, code, details);\n if (code === "device_operation_unknown") return domFailure("NotSupportedError", message2, code, details);\n if (code === "media_requires_experience_host" || code === "media_sign_in_required" || code === "usage_unknown" || code === "usage_operation_denied" || code === "usage_resource_denied" || code === "usage_scope_denied" || code === "usage_required" || code === "capability_denied") {\n return domFailure("SecurityError", message2, code, details);\n }\n if (error instanceof DOMException) return error;\n return domFailure("OperationError", message2, code, details);\n}\nfunction exactOrIdeal(value) {\n if (!isRecord(value)) return value;\n return value.exact ?? value.ideal;\n}\nfunction boundedNumber(value, minimum, maximum, name) {\n const selected2 = exactOrIdeal(value);\n if (selected2 === void 0) return void 0;\n if (!isFiniteNumber(selected2)) throw domFailure("OverconstrainedError", `${name} must be a finite number`, "invalid_request");\n if (isRecord(value) && value.exact !== void 0 && (selected2 < minimum || selected2 > maximum)) {\n throw domFailure("OverconstrainedError", `${name} cannot be satisfied`, "invalid_request");\n }\n return Math.round(Math.min(maximum, Math.max(minimum, selected2)));\n}\nfunction facingMode(value) {\n const selected2 = exactOrIdeal(value);\n const candidate = Array.isArray(selected2) ? selected2.find((item) => item === "user" || item === "environment") : selected2;\n if (candidate === "user" || candidate === "environment") return candidate;\n if (isRecord(value) && value.exact !== void 0) throw domFailure("OverconstrainedError", "facingMode cannot be satisfied", "invalid_request");\n return void 0;\n}\nfunction booleanConstraint(value) {\n const selected2 = exactOrIdeal(value);\n return typeof selected2 === "boolean" ? selected2 : void 0;\n}\nfunction videoInput(value) {\n if (value === void 0 || value === false) return null;\n if (value === true) return {};\n if (!isRecord(value)) throw domFailure("TypeError", "Invalid video constraints", "invalid_request");\n return {\n ...facingMode(value.facingMode) ? { facingMode: facingMode(value.facingMode) } : {},\n ...boundedNumber(value.width, 160, 1280, "width") !== void 0 ? { width: boundedNumber(value.width, 160, 1280, "width") } : {},\n ...boundedNumber(value.height, 120, 720, "height") !== void 0 ? { height: boundedNumber(value.height, 120, 720, "height") } : {},\n ...boundedNumber(value.frameRate, 5, 30, "frameRate") !== void 0 ? { frameRate: boundedNumber(value.frameRate, 5, 30, "frameRate") } : {}\n };\n}\nfunction audioInput(value) {\n if (value === void 0 || value === false) return null;\n if (value === true) return {};\n if (!isRecord(value)) throw domFailure("TypeError", "Invalid audio constraints", "invalid_request");\n const echoCancellation = booleanConstraint(value.echoCancellation);\n const noiseSuppression = booleanConstraint(value.noiseSuppression);\n const autoGainControl = booleanConstraint(value.autoGainControl);\n return {\n ...echoCancellation !== void 0 ? { echoCancellation } : {},\n ...noiseSuppression !== void 0 ? { noiseSuppression } : {},\n ...autoGainControl !== void 0 ? { autoGainControl } : {}\n };\n}\nfunction isLiveResult(value) {\n const video = isRecord(value) ? value.video : void 0;\n const audio = isRecord(value) ? value.audio : void 0;\n return isRecord(value) && isString(value.session) && (video === null || isRecord(video) && ["width", "height", "frameRate"].every((key2) => isFiniteNumber(video[key2])) && (video.facingMode === "user" || video.facingMode === "environment")) && (audio === null || isRecord(audio) && isFiniteNumber(audio.sampleRate) && audio.channelCount === 1);\n}\nfunction patchTrack(track, settings2, stopped) {\n const nativeStop = track.stop.bind(track);\n let closed = false;\n Object.defineProperty(track, "getSettings", {\n configurable: true,\n value: () => ({ ...MediaStreamTrack.prototype.getSettings.call(track), ...settings2 })\n });\n Object.defineProperty(track, "stop", {\n configurable: true,\n value: () => {\n if (closed) return;\n closed = true;\n nativeStop();\n stopped();\n }\n });\n return (ended) => {\n if (closed) return;\n closed = true;\n nativeStop();\n stopped();\n if (ended) track.dispatchEvent(new Event("ended"));\n };\n}\nfunction genericDevice(kind, deviceId, label) {\n const value = { deviceId, groupId: "nocha-live-media", kind, label };\n return { ...value, toJSON: () => ({ ...value }) };\n}\nfunction createLiveMedia(context) {\n const invokeBridge2 = (capability, operation2, input4, timeoutMs) => context.invokeWithPort(capability, operation2, input4, { timeoutMs });\n const getUserMedia = (constraints) => {\n let video;\n let audio;\n try {\n if (!isRecord(constraints)) throw domFailure("TypeError", "Media constraints are required", "invalid_request");\n const mediaConstraints = constraints;\n video = videoInput(mediaConstraints.video);\n audio = audioInput(mediaConstraints.audio);\n if (!video && !audio) throw domFailure("TypeError", "Camera or microphone constraints are required", "invalid_request");\n } catch (error) {\n return Promise.reject(bridgeFailure(error));\n }\n let eagerAudio = null;\n if (audio) {\n try {\n eagerAudio = new AudioContext();\n void eagerAudio.resume().catch(() => void 0);\n } catch {\n eagerAudio = null;\n }\n }\n const opened = video ? (() => {\n const input4 = { video, ...audio ? { audio } : { audio: false } };\n return invokeBridge2("device", "camera.stream", input4, deviceOperationDefinitions["camera.stream"].sdkTimeoutMs);\n })() : (() => {\n const input4 = { audio };\n return invokeBridge2("device", "microphone.stream", input4, deviceOperationDefinitions["microphone.stream"].sdkTimeoutMs);\n })();\n let pendingPort = null;\n let rebuiltAudio = null;\n return opened.then(async ({ result: raw, port }) => {\n pendingPort = port;\n if (!isLiveResult(raw)) throw new NochaError("invalid_result", "Nocha returned invalid live media settings");\n const result2 = raw;\n const tracks = [];\n const active3 = /* @__PURE__ */ new Set();\n const closeTracks = /* @__PURE__ */ new Map();\n const sources2 = /* @__PURE__ */ new Set();\n let hostEnded = false;\n let audioState = null;\n let requestFrame;\n let canvas = null;\n let gestureResume = null;\n let scheduledUntil = 0;\n const stopped = (track) => {\n active3.delete(track);\n if (hostEnded) return;\n try {\n port.postMessage({ type: "stop", kind: track.kind });\n } catch {\n }\n if (!active3.size) {\n port.close();\n if (audioState) void audioState.context.close().catch(() => void 0);\n if (gestureResume) {\n window.removeEventListener("pointerdown", gestureResume);\n window.removeEventListener("keydown", gestureResume);\n }\n }\n };\n if (result2.video) {\n canvas = document.createElement("canvas");\n canvas.width = result2.video.width;\n canvas.height = result2.video.height;\n let captured = null;\n try {\n captured = canvas.captureStream(0);\n } catch {\n }\n let track = captured?.getVideoTracks()[0];\n const framed = track;\n if (track && typeof framed?.requestFrame === "function") {\n requestFrame = () => framed.requestFrame();\n } else {\n for (const provisional of captured?.getTracks() ?? []) provisional.stop();\n captured = canvas.captureStream(result2.video.frameRate);\n track = captured.getVideoTracks()[0];\n }\n if (!track) throw new NochaError("invalid_result", "The browser cannot reconstruct a video track");\n tracks.push(track);\n active3.add(track);\n closeTracks.set(track, patchTrack(track, {\n width: result2.video.width,\n height: result2.video.height,\n frameRate: result2.video.frameRate,\n facingMode: result2.video.facingMode,\n deviceId: "nocha-camera"\n }, () => stopped(track)));\n }\n if (result2.audio) {\n let audioContext = eagerAudio;\n if (!audioContext || audioContext.sampleRate !== result2.audio.sampleRate) {\n if (audioContext) void audioContext.close().catch(() => void 0);\n audioContext = new AudioContext({ sampleRate: result2.audio.sampleRate });\n void audioContext.resume().catch(() => void 0);\n }\n rebuiltAudio = audioContext;\n const destination = audioContext.createMediaStreamDestination();\n const track = destination.stream.getAudioTracks()[0];\n if (!track) throw new NochaError("invalid_result", "The browser cannot reconstruct an audio track");\n audioState = { context: audioContext, destination };\n tracks.push(track);\n active3.add(track);\n closeTracks.set(track, patchTrack(track, {\n sampleRate: result2.audio.sampleRate,\n channelCount: 1,\n deviceId: "nocha-microphone"\n }, () => stopped(track)));\n gestureResume = () => {\n if (audioContext.state === "suspended") void audioContext.resume().catch(() => void 0);\n else {\n window.removeEventListener("pointerdown", gestureResume);\n window.removeEventListener("keydown", gestureResume);\n }\n };\n if (audioContext.state === "suspended") {\n window.addEventListener("pointerdown", gestureResume);\n window.addEventListener("keydown", gestureResume);\n }\n } else if (eagerAudio) void eagerAudio.close().catch(() => void 0);\n port.addEventListener("message", (event) => {\n const message2 = event.data;\n if (!isRecord(message2) || !isString(message2.type)) return;\n if (message2.type === "frame") {\n const bitmap = message2.bitmap;\n try {\n if (!canvas || !(bitmap instanceof ImageBitmap)) return;\n const drawing = canvas.getContext("2d", { alpha: false });\n if (!drawing) return;\n drawing.drawImage(bitmap, 0, 0, canvas.width, canvas.height);\n requestFrame?.();\n } finally {\n if (bitmap instanceof ImageBitmap) bitmap.close();\n try {\n port.postMessage({ type: "ack" });\n } catch {\n }\n }\n return;\n }\n if (message2.type === "audio" && audioState && message2.samples instanceof Float32Array && isFiniteNumber(message2.sampleRate) && message2.sampleRate === audioState.context.sampleRate) {\n if (audioState.context.state !== "running" || scheduledUntil - audioState.context.currentTime > 0.25) return;\n const buffer = audioState.context.createBuffer(1, message2.samples.length, message2.sampleRate);\n buffer.copyToChannel(new Float32Array(message2.samples), 0);\n const source2 = audioState.context.createBufferSource();\n source2.buffer = buffer;\n source2.connect(audioState.destination);\n const earliest = audioState.context.currentTime + 0.06;\n if (scheduledUntil < audioState.context.currentTime) scheduledUntil = earliest;\n const at = Math.max(earliest, scheduledUntil);\n scheduledUntil = at + buffer.duration;\n sources2.add(source2);\n source2.addEventListener("ended", () => {\n sources2.delete(source2);\n source2.disconnect();\n }, { once: true });\n source2.start(at);\n return;\n }\n if (message2.type === "ended") {\n hostEnded = true;\n for (const source2 of sources2) {\n try {\n source2.stop();\n } catch {\n }\n }\n sources2.clear();\n for (const close of closeTracks.values()) close(true);\n port.close();\n if (audioState) void audioState.context.close().catch(() => void 0);\n if (gestureResume) {\n window.removeEventListener("pointerdown", gestureResume);\n window.removeEventListener("keydown", gestureResume);\n }\n }\n });\n port.start();\n port.postMessage({ type: "start" });\n const stream2 = new MediaStream(tracks);\n pendingPort = null;\n return stream2;\n }).catch((error) => {\n if (pendingPort) {\n try {\n pendingPort.postMessage({ type: "stop" });\n } catch {\n }\n pendingPort.close();\n pendingPort = null;\n }\n if (eagerAudio) void eagerAudio.close().catch(() => void 0);\n if (rebuiltAudio && rebuiltAudio !== eagerAudio) void rebuiltAudio.close().catch(() => void 0);\n throw bridgeFailure(error);\n });\n };\n const install = () => {\n if (typeof navigator === "undefined" || !navigator.mediaDevices || installedMediaDevices.has(navigator.mediaDevices)) return;\n const mediaDevices = navigator.mediaDevices;\n Object.defineProperty(mediaDevices, "getUserMedia", { configurable: true, value: getUserMedia });\n Object.defineProperty(mediaDevices, "enumerateDevices", {\n configurable: true,\n value: async () => [\n genericDevice("videoinput", "nocha-camera", "Nocha camera"),\n genericDevice("audioinput", "nocha-microphone", "Nocha microphone")\n ]\n });\n installedMediaDevices.add(mediaDevices);\n };\n const liveAvailability = async (options) => {\n const value = await context.invoke("device", "availability", {}, options);\n return isRecord(value) && isRecord(value.capabilities) ? value.capabilities : null;\n };\n const status2 = async (options) => {\n const { language: language2, ...request2 } = options ?? {};\n let capabilities2;\n try {\n capabilities2 = await liveAvailability(request2);\n } catch (error) {\n const failure4 = describeLiveMediaFailure(error, { language: language2 });\n if (failure4.problem === "cancelled") throw error;\n if (failure4.problem !== "standalone") return { camera: "unknown", microphone: "unknown" };\n const known = { available: false, problem: failure4.problem, message: failure4.message };\n return { camera: known, microphone: known };\n }\n return { camera: liveMediaStatusOf(capabilities2?.liveCamera, { language: language2 }), microphone: liveMediaStatusOf(capabilities2?.liveMicrophone, { language: language2 }) };\n };\n const offerHost = async (options) => {\n let capabilities2;\n try {\n capabilities2 = await liveAvailability(options);\n } catch (error) {\n if (describeLiveMediaFailure(error).problem === "cancelled") throw error;\n return { offered: false };\n }\n return { offered: liveMediaOffersAddress(capabilities2?.liveMicrophone) || liveMediaOffersAddress(capabilities2?.liveCamera) };\n };\n return Object.freeze({ getUserMedia, install, status: status2, offerHost });\n}\n\n// src/device.ts\nvar features = ["camera", "photos", "audio", "motion", "haptics", "location", "share", "notifications", "alarms"];\nvar isAvailability = (value) => isRecord(value) && ["ios", "android", "web"].includes(String(value.platform)) && isRecord(value.capabilities) && features.every((feature) => {\n const entry = isRecord(value.capabilities) ? value.capabilities[feature] : void 0;\n return isRecord(entry) && isBoolean(entry.available) && (entry.reason === void 0 || isString(entry.reason)) && (entry.styles === void 0 || isArrayOf(entry.styles, isString)) && (entry.pattern === void 0 || isBoolean(entry.pattern));\n});\nvar isMedia = (value) => isRecord(value) && (value.cancelled === true || value.cancelled === false && isRecord(value.file) && isString(value.file.dataUrl) && value.file.dataUrl.startsWith("data:") && isString(value.file.mimeType) && isString(value.file.name));\nvar isScheduled = (kind, id) => (value) => isRecord(value) && isString(value.id) && (id === void 0 || value.id === id) && isString(value.title) && isString(value.at) && Number.isFinite(Date.parse(value.at)) && (value.body === void 0 || isString(value.body)) && value.kind === kind;\nvar isLocation = (value) => isRecord(value) && isFiniteNumber(value.latitude) && Math.abs(value.latitude) <= 90 && isFiniteNumber(value.longitude) && Math.abs(value.longitude) <= 180 && isNullable(value.accuracy, isFiniteNumber);\nvar completed = (value) => isRecord(value) && value.completed === true;\nfunction isMotion(value) {\n return isRecord(value) && isString(value.id) && (value.sensor === "accelerometer" || value.sensor === "gyroscope") && ["x", "y", "z", "timestamp"].every((key2) => isFiniteNumber(value[key2]));\n}\nvar field = (input4, key2) => isRecord(input4) ? input4[key2] : void 0;\nfunction createDevice(context, subscriptions) {\n const call2 = async (operation2, input4, check2, options) => {\n const value = await context.invoke(deviceOperationDefinitions[operation2].capability, deviceOperationDefinitions[operation2].operation, input4, options);\n if (!check2(value)) throw new NochaError("invalid_result", `Nocha returned an invalid device ${operation2} result`);\n return value;\n };\n const scheduling = (kind) => {\n const item = kind === "notifications" ? "notification" : "alarm";\n return {\n schedule: (input4, options) => call2(`${kind}.schedule`, input4, isScheduled(item, field(input4, "id")), options),\n list: (options) => call2(`${kind}.list`, {}, (value) => isRecord(value) && isArrayOf(value.items, isScheduled(item)), options),\n cancel: (input4, options) => call2(`${kind}.cancel`, input4, (value) => isRecord(value) && isBoolean(value.cancelled), options)\n };\n };\n return Object.freeze({\n availability: (options) => call2("availability", {}, isAvailability, options),\n camera: { capture: (options) => call2("camera.capture", {}, isMedia, options) },\n photos: { pick: (options) => call2("photos.pick", {}, isMedia, options) },\n media: createLiveMedia(context),\n motion: { async subscribe(input4, listener, options) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A motion listener is required");\n if (!isRecord(input4) || !isString(input4.id)) throw new NochaError("invalid_request", "A motion subscription id is required");\n if (subscriptions.has(input4.id)) throw new NochaError("invalid_request", "Motion subscription id is already active");\n subscriptions.add(input4.id);\n let closed = false;\n const stop = subscribeBridgeEvents((event) => {\n if (event.type === "device.motion.stopped" && isRecord(event.payload) && event.payload.id === input4.id) {\n closed = true;\n stop();\n subscriptions.delete(input4.id);\n return;\n }\n if (event.type === "device.motion" && isMotion(event.payload) && event.payload.id === input4.id && event.payload.sensor === input4.sensor) notifyListener(listener, event.payload);\n });\n try {\n await call2("motion.subscribe", input4, (value) => isRecord(value) && value.id === input4.id, options);\n } catch (error) {\n stop();\n subscriptions.delete(input4.id);\n void call2("motion.unsubscribe", { id: input4.id }, () => true, options).catch(() => {\n });\n throw error;\n }\n return async () => {\n if (closed) return;\n await call2("motion.unsubscribe", { id: input4.id }, (value) => isRecord(value) && isBoolean(value.removed), options);\n closed = true;\n stop();\n subscriptions.delete(input4.id);\n };\n } },\n haptics: {\n trigger: (input4 = {}, options) => call2("haptics.trigger", input4, completed, options),\n pattern: (input4, options) => call2("haptics.pattern", input4, (value) => isRecord(value) && isBoolean(value.completed), options),\n stop: (options) => call2("haptics.stop", {}, (value) => isRecord(value) && isBoolean(value.stopped), options)\n },\n location: { current: (options) => call2("location.current", {}, isLocation, options) },\n share: { open: (input4, options) => call2("share.open", input4, completed, options) },\n notifications: scheduling("notifications"),\n alarms: scheduling("alarms")\n });\n}\n\n// src/haptics.ts\nvar completed2 = (value) => isRecord(value) && value.completed === true;\nfunction createHaptics(context) {\n const call2 = async (operation2, input4, check2, options) => {\n const def = deviceOperationDefinitions[operation2];\n const value = await context.invoke(def.capability, def.operation, input4, options);\n if (!check2(value)) throw new NochaError("invalid_result", `Nocha returned an invalid device ${operation2} result`);\n return value;\n };\n const absorbLimit = async (nominal, pending3) => {\n try {\n return await pending3;\n } catch (error) {\n if (isNochaError(error) && error.code === "device_limit") return nominal;\n throw error;\n }\n };\n const trigger = (style2, options) => absorbLimit({ completed: true }, call2("haptics.trigger", { style: style2 }, completed2, options));\n return Object.freeze({\n impact: (style2 = "medium", options) => trigger(style2, options),\n selection: (options) => trigger("selection", options),\n notify: (type, options) => trigger(type, options),\n vibrate: (pattern, options) => absorbLimit({ completed: true }, call2("haptics.pattern", Array.isArray(pattern) ? { steps: pattern } : pattern, (value) => isRecord(value) && isBoolean(value.completed), options)),\n stop: (options) => absorbLimit({ stopped: true }, call2("haptics.stop", {}, (value) => isRecord(value) && isBoolean(value.stopped), options))\n });\n}\n\n// src/drive.ts\nvar forbiddenCharacter = (character) => character === "/" || character === "\\\\" || character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127;\nvar mimePattern = /^[a-z0-9][a-z0-9.+-]*\\/[a-z0-9][a-z0-9.+-]*$/;\nvar acceptPattern = /^[a-z0-9][a-z0-9.+-]*\\/(?:\\*|[a-z0-9][a-z0-9.+-]*)$/;\nfunction driveName(value, field3) {\n const name = typeof value === "string" ? value.trim() : "";\n if (!name || name.length > 255 || [...name].some(forbiddenCharacter) || name === "." || name === "..") throw invalid2(`${field3} must be a Drive name: 1 to 255 characters, without / or \\\\`);\n return name;\n}\nfunction dialogHints(folder, title) {\n if (folder !== void 0 && (!Array.isArray(folder) || folder.length > DRIVE_FOLDER_MAX_DEPTH)) throw invalid2(`folder must list at most ${DRIVE_FOLDER_MAX_DEPTH} folder names`);\n if (title !== void 0 && (typeof title !== "string" || !title.trim() || title.trim().length > 120)) throw invalid2("title must have 1 to 120 characters");\n const names = Array.isArray(folder) ? folder.map((item) => driveName(item, "Each folder")) : void 0;\n return { ...names?.length ? { folder: names } : {}, ...typeof title === "string" ? { title: title.trim() } : {} };\n}\nfunction timeoutOf(value, fallback) {\n const timeout = value ?? fallback;\n if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid2("timeoutMs must be a positive finite timer duration");\n return timeout;\n}\nfunction checkOptions(options) {\n if (!isRecord(options)) throw invalid2("Request options must be an object");\n if (options.onProgress !== void 0 && typeof options.onProgress !== "function") throw invalid2("onProgress must be a function");\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalid2("signal must be an AbortSignal");\n}\nvar isSaveResult = (value) => isRecord(value) && (value.saved === false || value.saved === true && isRecord(value.file) && isNonEmptyString(value.file.id) && isNonEmptyString(value.file.name) && isArrayOf(value.file.path, isString) && isString(value.file.mimeType) && isCount(value.file.sizeBytes));\nfunction requireUsage(context, operation2) {\n assertHostCapability("drive");\n if (context.usageId === void 0) throw new NochaError("usage_required", `drive.${operation2} requires nocha.use(<declared usage id>)`);\n return context.usageId;\n}\nfunction saveFile(context, input4, options) {\n const { file } = input4;\n if (!file.size) throw invalid2("A non-empty file is required");\n if (file.size > DRIVE_TRANSFER_MAX_BYTES) throw new NochaError("source_too_large", "A Drive file sent by an experience is at most 64 MiB");\n const fallbackName = "name" in file && typeof file.name === "string" && file.name.trim() ? file.name : "file";\n const name = driveName(input4.name ?? fallbackName, "name");\n const declared = (typeof input4.mimeType === "string" ? input4.mimeType : file.type).trim().toLowerCase().split(";", 1)[0] ?? "";\n if (input4.mimeType !== void 0 && !mimePattern.test(declared)) throw invalid2("mimeType must be a MIME type such as audio/mpeg");\n const hints = dialogHints(options.folder, options.title);\n const usageId = requireUsage(context, "save");\n if (options.idempotencyKey !== void 0 && !isIdempotencyKey(options.idempotencyKey)) throw invalid2("idempotencyKey must contain 8 to 200 characters");\n const timeoutMs = timeoutOf(options.timeoutMs, operationWaiting.drive.save);\n const wire3 = { name, mime_type: mimePattern.test(declared) ? declared : "application/octet-stream", size_bytes: file.size, ...hints };\n return uploadToHost({\n capability: driveOperationDefinitions.save.capability,\n operation: driveOperationDefinitions.save.operation,\n usageId,\n idempotencyKey: options.idempotencyKey,\n keySuffix: "drive",\n input: wire3,\n file,\n onProgress: options.onProgress,\n countedProgress: true,\n timeoutMs,\n signal: options.signal,\n validate: isSaveResult,\n abortMessage: "Drive save aborted",\n failureMessage: "Drive save failed",\n timeoutMessage: "Local Drive wait timed out; the file may still be saved",\n invalidResultMessage: "Nocha returned an invalid Drive save result"\n });\n}\nasync function saveVideo(context, input4, options) {\n const video = input4.video;\n if (!isRecord(video) || !isUsageId(video.usage) || !isNonEmptyString(video.id) || video.id.length > 200) {\n throw invalid2("video must name the declared video usage and the generation id: { usage, id }");\n }\n const name = input4.name === void 0 ? void 0 : driveName(input4.name, "name");\n const hints = dialogHints(options.folder, options.title);\n requireUsage(context, "save");\n const value = await context.invoke(driveOperationDefinitions.save.capability, driveOperationDefinitions.save.operation, {\n video: { usage: video.usage, id: video.id },\n ...name ? { name } : {},\n ...hints\n }, {\n ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},\n timeoutMs: timeoutOf(options.timeoutMs, operationWaiting.drive.save),\n ...options.signal !== void 0 ? { signal: options.signal } : {}\n });\n if (!isSaveResult(value)) throw new NochaError("invalid_result", "Nocha returned an invalid Drive save result");\n return value;\n}\nasync function save(context, input4, options = {}) {\n checkOptions(options);\n if (!isRecord(input4)) throw invalid2("Expected { file } or { video }");\n if ("file" in input4 && input4.file !== void 0) {\n if (!(input4.file instanceof Blob)) throw invalid2("file must be a Blob or a File");\n return saveFile(context, input4, options);\n }\n if ("video" in input4 && input4.video !== void 0) return saveVideo(context, input4, options);\n throw invalid2("Expected { file } or { video }");\n}\nfunction isPickTransfer(value, maxBytes2) {\n if (!isRecord(value)) return false;\n if (value.picked === false) return true;\n return value.picked === true && isRecord(value.drive) && isNonEmptyString(value.drive.id) && isArrayOf(value.drive.path, isString) && isCount(value.drive.sizeBytes) && isNonEmptyString(value.name) && isString(value.mime_type) && value.blob instanceof Blob && value.blob.size === value.drive.sizeBytes && value.blob.size <= maxBytes2;\n}\nasync function pick(context, input4 = {}, options = {}) {\n checkOptions(options);\n if (!isRecord(input4)) throw invalid2("Expected { accept?, maxBytes?, title?, folder? }");\n const accept = input4.accept;\n if (accept !== void 0 && (!Array.isArray(accept) || !accept.length || accept.length > 16 || accept.some((pattern) => typeof pattern !== "string" || !acceptPattern.test(pattern.trim().toLowerCase())))) {\n throw invalid2("accept must list 1 to 16 MIME patterns such as audio/* or audio/mpeg");\n }\n const maxBytes2 = input4.maxBytes ?? DRIVE_TRANSFER_MAX_BYTES;\n if (!isCount(maxBytes2) || maxBytes2 < 1 || maxBytes2 > DRIVE_TRANSFER_MAX_BYTES) throw invalid2("maxBytes must be an integer from 1 to 64 MiB");\n const hints = dialogHints(input4.folder, input4.title);\n const usageId = requireUsage(context, "pick");\n const timeout = timeoutOf(options.timeoutMs, operationWaiting.drive.pick);\n if (options.signal?.aborted) throw new NochaError("aborted", "Drive pick aborted");\n const wire3 = { ...accept ? { accept: accept.map((pattern) => pattern.trim().toLowerCase()) } : {}, ...input4.maxBytes !== void 0 ? { max_bytes: maxBytes2 } : {}, ...hints };\n return readHostMedia({\n noun: "Drive",\n timeoutMs: timeout,\n firstReplyMs: operationWaiting.drive["pick.firstReply"],\n options,\n messages: {\n aborted: "Drive pick aborted",\n timedOut: "Local Drive wait timed out",\n unavailable: "The Drive file is unavailable",\n unanswered: () => new NochaError("client_update_required", "Update Nocha to choose a file from the Drive")\n },\n accept: (result2) => !isPickTransfer(result2, maxBytes2) ? void 0 : result2.picked === false ? { picked: false } : {\n picked: true,\n file: new File([result2.blob], result2.name, { type: result2.mime_type || result2.blob.type }),\n drive: { id: result2.drive.id, path: [...result2.drive.path], sizeBytes: result2.drive.sizeBytes }\n },\n send: (requestId) => postToHost({\n protocol: NOCHA_MEDIA_PROTOCOL,\n type: "read",\n requestId,\n capability: driveOperationDefinitions.pick.capability,\n operation: driveOperationDefinitions.pick.operation,\n usageId,\n input: wire3\n })\n });\n}\nfunction createDrive(context) {\n return Object.freeze({\n save: (input4, options) => save(context, input4, options),\n pick: (input4, options) => pick(context, input4, options)\n });\n}\n\n// src/link.ts\nasync function open(context, url, options = {}) {\n if (typeof url !== "string" || !url.trim()) throw invalid2("open(url) requires an http(s) address");\n let address;\n try {\n address = new URL(url.trim());\n } catch {\n throw invalid2("open(url) requires an absolute http(s) address");\n }\n if (address.protocol !== "http:" && address.protocol !== "https:" || address.username || address.password) {\n throw invalid2("open(url) accepts a credential-free http(s) address only");\n }\n if (address.href.length > LINK_URL_MAX_LENGTH) throw invalid2(`open(url) accepts at most ${LINK_URL_MAX_LENGTH} characters`);\n const label = options.label?.trim();\n if (options.label !== void 0 && (typeof options.label !== "string" || !label || label.length > LINK_LABEL_MAX_LENGTH)) {\n throw invalid2(`label must hold 1 to ${LINK_LABEL_MAX_LENGTH} characters`);\n }\n const result2 = await context.invoke(\n linkOperationDefinitions.open.capability,\n linkOperationDefinitions.open.operation,\n { url: address.href, ...label ? { label } : {} },\n { ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}, ...options.signal ? { signal: options.signal } : {} }\n );\n if (!isRecord(result2) || typeof result2.opened !== "boolean") throw new NochaError("invalid_result", "Nocha returned an invalid link answer");\n return { opened: result2.opened };\n}\nfunction createLink(context) {\n return Object.freeze({ open: (url, options) => open(context, url, options) });\n}\n\n// src/library.ts\nvar nullableString = (value) => isNullable(value, isString);\nvar isLabel = (value) => isRecord(value) && isString(value.id) && isString(value.label);\nvar isPerson = (value) => isRecord(value) && isString(value.handle) && isString(value.displayName) && isBoolean(value.verified) && isBoolean(value.hasAvatar);\nvar isTeamRef2 = (value) => isRecord(value) && isString(value.slug) && isString(value.name);\nvar isExperience = (value) => isRecord(value) && isString(value.code) && isString(value.title) && nullableString(value.pitch) && nullableString(value.category) && isArrayOf(value.tags, isString) && isArrayOf(value.keywords, isString) && (value.visibility === null || value.visibility === "private" || value.visibility === "unlisted" || value.visibility === "listed") && nullableString(value.role) && nullableString(value.launchFormat) && isArrayOf(value.teams, isTeamRef2) && isNullable(value.creator, isPerson) && nullableString(value.updatedAt) && nullableString(value.listedAt) && isCount(value.onlineCount) && isBoolean(value.hasIcon) && isString(value.shareUrl);\nvar isJournalEntry = (value) => isRecord(value) && isString(value.id) && (value.kind === "publication" || value.kind === "message") && isString(value.at) && isNullable(value.author, isPerson) && isNullable(value.experience, isExperience) && isNullable(value.revisionNumber, isCount) && nullableString(value.note);\nvar isInterface = (value) => isRecord(value) && isString(value.code) && isString(value.title) && nullableString(value.pitch) && isBoolean(value.hasIcon) && isArrayOf(value.surfaces, (surface) => LIBRARY_SURFACES.includes(surface)) && LIBRARY_INTERFACE_SOURCES.includes(value.source) && isBoolean(value.chosen) && isBoolean(value.current) && isNullable(value.creator, (creator) => isRecord(creator) && isString(creator.handle) && isString(creator.displayName));\nvar isUniverse = (value) => isRecord(value) && isString(value.id) && isString(value.label) && isArrayOf(value.categories, isString);\nvar isKeywordFamily = (value) => isRecord(value) && isString(value.id) && isString(value.label) && isArrayOf(value.keywords, isLabel);\nvar isPage = (value, item) => isRecord(value) && isArrayOf(value.items, item) && nullableString(value.next);\nfunction paged(input4, keys) {\n if (!isRecord(input4)) throw invalid2("The library input must be an object");\n const out = {};\n for (const key2 of [...keys, "cursor"]) {\n if (input4[key2] === void 0) continue;\n if (typeof input4[key2] !== "string" || !input4[key2]) throw invalid2(`${key2} must be a non-empty string`);\n out[key2] = input4[key2];\n }\n return { ...out, ...limit(input4.limit) };\n}\nfunction uniqueStrings(value, name, max, length = 200) {\n if (!isArrayOf(value, isString) || value.length < 1 || value.length > max || new Set(value).size !== value.length || value.some((item) => !item.trim() || item.length > length)) throw invalid2(`${name} must list 1 to ${max} unique values`);\n return [...value];\n}\nfunction limit(value) {\n if (value === void 0) return {};\n if (!isCount(value) || value < 1 || value > LIBRARY_PAGE_MAX) throw invalid2(`limit must be an integer from 1 to ${LIBRARY_PAGE_MAX}`);\n return { limit: value };\n}\nvar requiredString = (value, name, max = 200) => {\n if (typeof value !== "string" || !value.trim() || value.length > max) throw invalid2(`${name} must hold 1 to ${max} characters`);\n return value;\n};\nfunction openTarget(target) {\n if (!isRecord(target)) throw invalid2("open(target) requires a target");\n switch (target.kind) {\n case "experience":\n case "studio":\n return { kind: target.kind, code: requiredString(target.code, "code") };\n case "team":\n return { kind: "team", team: requiredString(target.team, "team") };\n case "profile":\n return { kind: "profile", handle: requiredString(target.handle, "handle") };\n case "search":\n return target.query === void 0 ? { kind: "search" } : { kind: "search", query: requiredString(target.query, "query", LIBRARY_QUERY_MAX_LENGTH) };\n case "interface": {\n if (target.window !== void 0 && !isBoolean(target.window)) throw invalid2("window must be a boolean");\n return { kind: "interface", code: requiredString(target.code, "code"), ...target.window !== void 0 ? { window: target.window } : {} };\n }\n case "bookmarks":\n case "journal":\n case "create":\n case "credits":\n case "settings":\n case "desktop":\n case "experiences":\n case "teams":\n return { kind: target.kind };\n default:\n throw invalid2("Unknown library.open target kind");\n }\n}\nvar inRange = (value, min, max) => isFiniteNumber(value) && value >= min && value <= max;\nfunction openRect(from) {\n if (!isRecord(from) && !(typeof DOMRectReadOnly !== "undefined" && from instanceof DOMRectReadOnly)) throw invalid2("from must be a rectangle");\n const { x, y, width, height } = from;\n if (!inRange(x, -LIBRARY_RECT_OFFSET_MAX, LIBRARY_RECT_OFFSET_MAX) || !inRange(y, -LIBRARY_RECT_OFFSET_MAX, LIBRARY_RECT_OFFSET_MAX) || !inRange(width, 0, LIBRARY_RECT_SIZE_MAX) || !inRange(height, 0, LIBRARY_RECT_SIZE_MAX)) {\n throw invalid2(`from must hold finite x and y within \\xB1${LIBRARY_RECT_OFFSET_MAX} and width and height from 0 to ${LIBRARY_RECT_SIZE_MAX}`);\n }\n return { x, y, width, height };\n}\nfunction createLibrary(context) {\n const invoke2 = async (definition, input4, options, check2, what) => {\n const value = await context.invoke(\n definition.capability,\n definition.operation,\n input4,\n { ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}, ...options?.signal ? { signal: options.signal } : {} }\n );\n if (!check2(value)) throw invalidResult(`Nocha returned an invalid library ${what}`);\n return value;\n };\n const experiencePage = (value) => isPage(value, isExperience);\n return Object.freeze({\n experiences(input4, options) {\n if (!isRecord(input4) || !LIBRARY_SHELVES.includes(input4.shelf)) {\n return Promise.reject(invalid2(`shelf must be one of ${LIBRARY_SHELVES.join(", ")}`));\n }\n return Promise.resolve().then(() => invoke2(libraryOperationDefinitions.experiences, { shelf: input4.shelf, ...paged(input4, []) }, options, experiencePage, "page"));\n },\n catalogue: (input4 = {}, options) => Promise.resolve().then(() => {\n if (isRecord(input4) && input4.sort !== void 0 && input4.sort !== "recent") throw invalid2("sort must be \'recent\'");\n if (isRecord(input4) && input4.creator !== void 0 && (typeof input4.creator !== "string" || !LIBRARY_HANDLE_PATTERN.test(input4.creator))) throw invalid2("creator must be a profile handle");\n const tags = isRecord(input4) && input4.tags !== void 0 ? uniqueStrings(input4.tags, "tags", LIBRARY_CATALOGUE_TAGS_MAX, 120) : void 0;\n if (tags && input4.keyword !== void 0 && (tags.length >= LIBRARY_CATALOGUE_TAGS_MAX || tags.includes(input4.keyword))) {\n throw invalid2(`keyword and tags name at most ${LIBRARY_CATALOGUE_TAGS_MAX} unique tags`);\n }\n return invoke2(\n libraryOperationDefinitions.catalogue,\n { ...paged(input4, ["category", "keyword", "collection", "sort", "creator", "universe"]), ...tags ? { tags } : {} },\n options,\n experiencePage,\n "page"\n );\n }),\n // An older host pages nothing: `next` and `total` absent.\n search: (input4, options) => Promise.resolve().then(() => {\n const query = requiredString(isRecord(input4) ? input4.query : void 0, "query", LIBRARY_QUERY_MAX_LENGTH);\n return invoke2(libraryOperationDefinitions.search, { query, ...paged(input4, []) }, options, (value) => isRecord(value) && isArrayOf(value.experiences, isExperience) && isArrayOf(value.keywords, isLabel) && (value.next === void 0 || nullableString(value.next)) && (value.total === void 0 || isNullable(value.total, isCount)), "search");\n }),\n bookmarks: (input4 = {}, options) => Promise.resolve().then(() => invoke2(libraryOperationDefinitions.bookmarks, paged(input4, ["folder"]), options, (value) => isRecord(value) && isArrayOf(value.folders, (folder) => isRecord(folder) && isString(folder.id) && isString(folder.name)) && isArrayOf(value.items, isExperience) && nullableString(value.next), "bookmarks")),\n teams: (options) => invoke2(libraryOperationDefinitions.teams, {}, options, (value) => isRecord(value) && isArrayOf(value.teams, (team) => isTeamRef2(team) && nullableString(team.role)), "team list"),\n teamExperiences: (input4, options) => Promise.resolve().then(() => {\n requiredString(isRecord(input4) ? input4.team : void 0, "team");\n return invoke2(libraryOperationDefinitions.teamExperiences, paged(input4, ["team", "tag"]), options, experiencePage, "page");\n }),\n journal: (input4 = {}, options) => Promise.resolve().then(() => {\n if (isRecord(input4) && input4.following !== void 0 && !isBoolean(input4.following)) throw invalid2("following must be a boolean");\n return invoke2(\n libraryOperationDefinitions.journal,\n { ...paged(input4, []), ...input4.following !== void 0 ? { following: input4.following } : {} },\n options,\n (value) => isPage(value, isJournalEntry),\n "journal"\n );\n }),\n // An older host answers neither `universes` nor `keywordFamilies`.\n facets: (options) => Promise.resolve().then(() => {\n const category = options?.category;\n if (category !== void 0 && (typeof category !== "string" || !category.trim() || category.length > 80)) throw invalid2("category must hold 1 to 80 characters");\n return invoke2(libraryOperationDefinitions.facets, category !== void 0 ? { category } : {}, options, (value) => isRecord(value) && isArrayOf(value.categories, isLabel) && isArrayOf(value.keywords, isLabel) && (value.universes === void 0 || isArrayOf(value.universes, isUniverse)) && (value.keywordFamilies === void 0 || isArrayOf(value.keywordFamilies, isKeywordFamily)), "facets");\n }),\n // An older host omits `depth`, `window` and `opener`: it mounts its interface at the page\'s root.\n account: (options) => invoke2(\n libraryOperationDefinitions.account,\n {},\n options,\n (value) => isRecord(value) && isString(value.handle) && isString(value.displayName) && isBoolean(value.verified) && isBoolean(value.hasAvatar) && isString(value.language) && LIBRARY_SURFACES.includes(value.surface) && nullableString(value.team) && nullableString(value.query) && (value.depth === void 0 || isCount(value.depth)) && (value.window === void 0 || isBoolean(value.window)) && (value.opener === void 0 || nullableString(value.opener)) && isNullable(value.credits, (credits4) => isRecord(credits4) && isString(credits4.availableMicrocredits)),\n "account"\n ).then((account) => ({ ...account, depth: account.depth ?? 0, window: account.window ?? false, opener: account.opener ?? null })),\n icons: (input4, options) => Promise.resolve().then(() => {\n if (!isRecord(input4) || !isArrayOf(input4.codes, isString) || input4.codes.length < 1 || input4.codes.length > LIBRARY_ICON_CODES_MAX) {\n throw invalid2(`codes must list 1 to ${LIBRARY_ICON_CODES_MAX} experience codes`);\n }\n if (!LIBRARY_ICON_SIZES.includes(input4.size)) throw invalid2(`size must be one of ${LIBRARY_ICON_SIZES.join(", ")}`);\n return invoke2(libraryOperationDefinitions.icons, { codes: input4.codes, size: input4.size }, options, (value) => isRecord(value) && isRecord(value.icons) && Object.values(value.icons).every(nullableString), "icons");\n }),\n avatars: (input4, options) => Promise.resolve().then(() => {\n if (!isRecord(input4) || !isArrayOf(input4.handles, isString) || input4.handles.length < 1 || input4.handles.length > LIBRARY_AVATAR_HANDLES_MAX || new Set(input4.handles).size !== input4.handles.length || !input4.handles.every((handle) => LIBRARY_HANDLE_PATTERN.test(handle))) {\n throw invalid2(`handles must list 1 to ${LIBRARY_AVATAR_HANDLES_MAX} unique profile handles`);\n }\n if (!LIBRARY_ICON_SIZES.includes(input4.size)) throw invalid2(`size must be one of ${LIBRARY_ICON_SIZES.join(", ")}`);\n return invoke2(libraryOperationDefinitions.avatars, { handles: [...input4.handles], size: input4.size }, options, (value) => isRecord(value) && isRecord(value.avatars) && Object.values(value.avatars).every(nullableString), "avatars");\n }),\n open: (target, options) => Promise.resolve().then(() => invoke2(\n libraryOperationDefinitions.open,\n {\n target: openTarget(target),\n ...options?.from !== void 0 ? { from: openRect(options.from) } : {},\n ...options?.choose === true ? { choose: true } : {}\n },\n options,\n (value) => isRecord(value) && value.opened === true,\n "open answer"\n )),\n collections: (options) => invoke2(libraryOperationDefinitions.collections, {}, options, (value) => isRecord(value) && isArrayOf(value.collections, (item) => isRecord(item) && isString(item.slug) && isString(item.title) && nullableString(item.subtitle) && isCount(item.count)), "collection list"),\n interfaces: (options) => invoke2(libraryOperationDefinitions.interfaces, {}, options, (value) => isRecord(value) && isArrayOf(value.interfaces, isInterface), "interface list"),\n prefetch: (input4, options) => Promise.resolve().then(async () => {\n if (!isRecord(input4) || !isArrayOf(input4.codes, isString) || input4.codes.length < 1 || input4.codes.length > LIBRARY_PREFETCH_CODES_MAX || new Set(input4.codes).size !== input4.codes.length || input4.codes.some((code) => !code.trim() || code.length > 200)) {\n throw invalid2(`codes must list 1 to ${LIBRARY_PREFETCH_CODES_MAX} unique experience codes`);\n }\n try {\n return await invoke2(libraryOperationDefinitions.prefetch, { codes: [...input4.codes] }, options, (value) => isRecord(value) && isCount(value.accepted), "prefetch answer");\n } catch (error) {\n if (error instanceof NochaError && error.code === "rate_limited") return { accepted: 0 };\n throw error;\n }\n }),\n bookmark: (input4, options) => Promise.resolve().then(() => {\n const code = requiredString(isRecord(input4) ? input4.code : void 0, "code");\n if (!isBoolean(input4.on)) throw invalid2("on must be a boolean");\n return invoke2(libraryOperationDefinitions.bookmark, { code, on: input4.on }, options, (value) => isRecord(value) && isBoolean(value.bookmarked), "bookmark answer");\n }),\n bookmarked: (input4, options) => Promise.resolve().then(() => {\n const codes2 = uniqueStrings(isRecord(input4) ? input4.codes : void 0, "codes", LIBRARY_BOOKMARKED_CODES_MAX);\n return invoke2(libraryOperationDefinitions.bookmarked, { codes: codes2 }, options, (value) => isRecord(value) && isRecord(value.states) && Object.values(value.states).every(isBoolean), "bookmark states");\n }),\n onChange(listener) {\n assertHostCapability("library");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A library listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== "library.changed") return;\n const payload = event.payload;\n if (isRecord(payload) && isArrayOf(payload.shelves, isString)) notifyListener(listener, { shelves: [...payload.shelves] });\n else warnOnce("library.changed", "the host sent a library change this SDK does not understand");\n });\n }\n });\n}\n\n// src/experiences.ts\nvar uuidPattern2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nvar waitOptions2 = (options) => ({\n ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},\n ...options?.signal ? { signal: options.signal } : {}\n});\nfunction assertTarget(experience, operation2) {\n if (typeof experience !== "string" || !EXPOSED_NAME_PATTERN.test(experience)) throw invalid2("experience is an exposed name: lowercase letters, digits and -, 2 to 40 characters");\n if (operation2 !== void 0 && (typeof operation2 !== "string" || !EXPOSED_OPERATION_PATTERN.test(operation2))) throw invalid2("operation is an exposed operation id such as persos.list");\n}\nfunction pickExperience(experience, operation2, input4 = null, options) {\n return Promise.resolve().then(async () => {\n assertHostCapability("experiences");\n assertTarget(experience, operation2);\n const value = await invokeBridgeWithFiles("experiences", experiencesOperationDefinitions.pick.operation, { experience, operation: operation2, input: input4 }, waitOptions2(options));\n if (isRecord(value) && value.status === "cancelled") return { status: "cancelled" };\n if (!isRecord(value) || value.status !== "done" || !Object.hasOwn(value, "value")) throw invalidResult("Nocha returned an invalid experiences answer");\n return { status: "done", value: value.value };\n });\n}\nvar presentations = ["background", "sheet", "picker"];\nvar hexColor = /^#[0-9a-f]{3,8}$/i;\nvar CALL_EVENT2 = "experiences.call";\nvar CANCEL_EVENT2 = "experiences.cancel";\nvar hostTimeoutMs2 = 3e4;\nvar handlers2 = /* @__PURE__ */ new Map();\nvar running2 = /* @__PURE__ */ new Map();\nvar unsubscribe2 = null;\nfunction send2(input4, timeoutMs = hostTimeoutMs2) {\n const key2 = `experiences-${input4.step}:${input4.callId}:${crypto.randomUUID().slice(0, 8)}`;\n return invokeBridgeWithFiles("experiences", experiencesOperationDefinitions.handle.operation, input4, { idempotencyKey: key2, timeoutMs });\n}\nfunction readCall2(payload) {\n if (!isRecord(payload) || typeof payload.callId !== "string" || !uuidPattern2.test(payload.callId)) return null;\n if (typeof payload.operation !== "string" || !EXPOSED_OPERATION_PATTERN.test(payload.operation) || !isRecord(payload.caller) || typeof payload.caller.title !== "string") return null;\n const name = payload.caller.name;\n if (name !== void 0 && (typeof name !== "string" || !EXPOSED_NAME_PATTERN.test(name))) return null;\n const presentation = presentations.find((item) => item === payload.presentation);\n const palette = Array.isArray(payload.palette) ? payload.palette.filter((color) => typeof color === "string" && hexColor.test(color)).slice(0, 16) : [];\n return {\n callId: payload.callId,\n operation: payload.operation,\n caller: { ...name !== void 0 ? { name } : {}, title: payload.caller.title },\n input: payload.input ?? null,\n ...presentation ? { presentation } : {},\n ...palette.length ? { palette } : {}\n };\n}\nasync function run2(event, handler) {\n const controller = new AbortController();\n running2.set(event.callId, controller);\n const fail = (error) => {\n const wire3 = isNochaError(error) ? error.wireCode ?? error.code : isRecord(error) ? error.code : void 0;\n const code = typeof wire3 === "string" && CODE_PATTERN.test(wire3) ? wire3 : "experience_call_failed";\n const text6 = (error instanceof Error ? error.message : typeof error === "string" ? error : "").trim().slice(0, 300).trim();\n return send2({ step: "fail", callId: event.callId, code, message: text6 || "The experience could not answer." }).catch((sent) => console.warn("Nocha experiences: the failure was not delivered", sent));\n };\n try {\n await send2({ step: "accept", callId: event.callId });\n const context = Object.freeze({\n caller: Object.freeze({ ...event.caller }),\n operation: event.operation,\n signal: controller.signal,\n ...event.presentation ? { presentation: event.presentation } : {},\n ...event.palette ? { palette: Object.freeze([...event.palette]) } : {}\n });\n let output;\n try {\n output = await handler(event.input, context);\n } catch (error) {\n if (!controller.signal.aborted) await fail(error);\n return;\n }\n if (controller.signal.aborted) return;\n await send2({ step: "complete", callId: event.callId, output: output ?? null }, experiencesOperationDefinitions.handle.sdkTimeoutMs).catch(async (error) => {\n if (!controller.signal.aborted) await fail(error);\n });\n } catch (error) {\n warnOnce("experiences.accept", `the host did not take the call (${isNochaError(error) ? error.code : "unknown_error"})`);\n } finally {\n running2.delete(event.callId);\n }\n}\nfunction subscribe2() {\n if (unsubscribe2) return;\n unsubscribe2 = subscribeBridgeEvents((event) => {\n if (event.type === CANCEL_EVENT2) {\n const callId = isRecord(event.payload) ? event.payload.callId : void 0;\n if (typeof callId === "string") running2.get(callId)?.abort(new NochaError("aborted", "The call was cancelled"));\n return;\n }\n if (event.type !== CALL_EVENT2) return;\n const received = readCall2(event.payload);\n if (!received) {\n warnOnce(CALL_EVENT2, "the host sent an experiences call this SDK does not understand");\n return;\n }\n const handler = handlers2.get(received.operation);\n if (handler && !running2.has(received.callId)) void run2(received, handler);\n });\n}\nfunction createExperiences(context) {\n const usage = (operation2) => {\n assertHostCapability("experiences");\n if (context.usageId === void 0) throw new NochaError("usage_required", `experiences.${operation2} requires nocha.use(<declared usage id>)`);\n return context.usageId;\n };\n return Object.freeze({\n available: (experience, options) => Promise.resolve().then(async () => {\n assertTarget(experience);\n try {\n const value = await invokeBridgeWithFiles("experiences", experiencesOperationDefinitions.available.operation, { experience }, { usageId: usage("available"), ...waitOptions2(options) });\n if (!isRecord(value) || typeof value.available !== "boolean" || value.title !== void 0 && typeof value.title !== "string") throw invalidResult("Nocha returned an invalid experiences answer");\n return value.available && typeof value.title === "string" ? { available: true, title: value.title } : { available: false };\n } catch (error) {\n if (isNochaError(error) && !["aborted", "invalid_result", "usage_required", "invalid_request", "experience_call_denied"].includes(error.code)) return { available: false };\n throw error;\n }\n }),\n call: (experience, operation2, input4 = null, options) => Promise.resolve().then(async () => {\n assertTarget(experience, operation2);\n const value = await invokeBridgeWithFiles("experiences", experiencesOperationDefinitions.call.operation, { experience, operation: operation2, input: input4 }, { usageId: usage("call"), ...waitOptions2(options) });\n if (!isRecord(value) || !Object.hasOwn(value, "output")) throw invalidResult("Nocha returned an invalid experiences answer");\n return value.output;\n }),\n open: (experience, options) => Promise.resolve().then(async () => {\n if (typeof experience !== "string" || !(EXPERIENCE_OPEN_CODE_PATTERN.test(experience) || experience.startsWith("https://") && experience.length <= EXPERIENCE_OPEN_URL_MAX_LENGTH)) {\n throw invalid2(`experience is a code or an https:// share address of at most ${EXPERIENCE_OPEN_URL_MAX_LENGTH} characters`);\n }\n const input4 = { experience, ...options?.from !== void 0 ? { from: openRect(options.from) } : {} };\n const value = await invokeBridgeWithFiles("experiences", experiencesOperationDefinitions.open.operation, input4, { usageId: usage("open"), ...waitOptions2(options) });\n if (!isRecord(value) || value.opened !== true) throw invalidResult("Nocha returned an invalid experiences answer");\n return { opened: true };\n }),\n handle(operation2, handler) {\n assertHostCapability("experiences");\n if (typeof operation2 !== "string" || !EXPOSED_OPERATION_PATTERN.test(operation2)) throw new NochaError("invalid_request", "An exposed operation id is dotted lowerCamel segments, such as persos.list");\n if (typeof handler !== "function") throw new NochaError("invalid_request", "experiences.handle takes a function (input, context) => output");\n if (handlers2.has(operation2)) throw new NochaError("invalid_request", `Another handler already serves ${operation2}`);\n handlers2.set(operation2, handler);\n subscribe2();\n return () => {\n if (handlers2.get(operation2) === handler) handlers2.delete(operation2);\n };\n },\n pick: (experience, operation2, input4 = null, options) => pickExperience(experience, operation2, input4, options)\n });\n}\n\n// src/host-feed.ts\nvar includes = (list5, value) => list5.includes(value);\nvar isSource2 = (value) => isRecord(value) && includes(HOST_SOURCE_KINDS, value.kind) && (value.kind !== "keyword" || isString(value.keyword)) && (value.categories === void 0 || isArrayOf(value.categories, isString)) && (value.excerpts === void 0 || isBoolean(value.excerpts));\nvar isStage = (value) => isRecord(value) && isCount(value.top) && isCount(value.right) && isCount(value.bottom) && isCount(value.left);\nvar isConfig = (value) => isRecord(value) && isSource2(value.source) && isStage(value.stage) && includes(HOST_RAIL_MODES, value.rail) && includes(HOST_RAIL_SIDES, value.railSide) && isBoolean(value.edges) && includes(HOST_TRANSITIONS, value.transition);\nvar nullableString2 = (value) => isNullable(value, isString);\nvar isItem = (value) => isRecord(value) && isString(value.code) && isString(value.title) && nullableString2(value.iconUrl) && nullableString2(value.creatorHandle) && isArrayOf(value.keywords, isString) && includes(HOST_ITEM_KINDS, value.kind) && nullableString2(value.excerptId);\nvar isNavigated = (value) => isRecord(value) && isCount(value.index);\nfunction configureInput(input4) {\n if (!isRecord(input4)) throw invalid2("host.configure takes an object");\n if (input4.source !== void 0 && !(isRecord(input4.source) && includes(HOST_SOURCE_KINDS, input4.source.kind))) {\n throw invalid2(`source.kind must be one of ${HOST_SOURCE_KINDS.join(", ")}`);\n }\n if (isRecord(input4.source) && input4.source.kind === "keyword" && !isString(input4.source.keyword)) throw invalid2("a keyword source names its keyword");\n if (input4.stage !== void 0 && !isRecord(input4.stage)) throw invalid2("stage takes top, right, bottom and left margins");\n const keys = ["source", "stage", "rail", "railSide", "edges", "transition"];\n return Object.fromEntries(keys.filter((key2) => input4[key2] !== void 0).map((key2) => [key2, input4[key2]]));\n}\nfunction createHost(context) {\n const invoke2 = async (definition, input4, options, check2, what) => {\n const value = await context.invoke(\n definition.capability,\n definition.operation,\n input4,\n { ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}, ...options?.signal ? { signal: options.signal } : {} }\n );\n if (!check2(value)) throw invalidResult(`Nocha returned an invalid host ${what}`);\n return value;\n };\n const navigate = (input4, options) => invoke2(hostOperationDefinitions["host.navigate"], input4, options, isNavigated, "navigation");\n return Object.freeze({\n configure: (input4, options) => Promise.resolve().then(() => invoke2(hostOperationDefinitions["host.configure"], configureInput(input4), options, isConfig, "configuration")),\n next: (options) => Promise.resolve().then(() => navigate({ to: "next" }, options)),\n previous: (options) => Promise.resolve().then(() => navigate({ to: "previous" }, options)),\n goTo: (index, options) => Promise.resolve().then(() => {\n if (!isCount(index) || index >= HOST_ITEMS_MAX) throw invalid2(`index must be an integer from 0 to ${HOST_ITEMS_MAX - 1}`);\n return navigate({ to: "index", index }, options);\n }),\n reload: (options) => Promise.resolve().then(() => navigate({ to: "reload" }, options)),\n items: (options) => Promise.resolve().then(async () => (await invoke2(hostOperationDefinitions["host.items"], {}, options, (value) => isRecord(value) && isArrayOf(value.items, isItem) && value.items.length <= HOST_ITEMS_MAX, "item list")).items),\n onChange(listener) {\n assertHostCapability("experiences");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A host listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== HOST_CHANGE_EVENT) return;\n const payload = event.payload;\n if (isRecord(payload) && isCount(payload.index) && isItem(payload.item) && includes(HOST_CHANGE_PHASES, payload.phase) && includes(HOST_DIRECTIONS, payload.direction)) {\n notifyListener(listener, { index: payload.index, item: { ...payload.item, keywords: [...payload.item.keywords] }, phase: payload.phase, direction: payload.direction });\n } else warnOnce(HOST_CHANGE_EVENT, "the host sent a host change this SDK does not understand");\n });\n }\n });\n}\n\n// src/transfer-payload.ts\nfunction blobProblem(items, blobs) {\n if (!Array.isArray(blobs) || blobs.length !== items.length || !blobs.every((blob) => blob instanceof Blob)) {\n return new NochaError("invalid_result", `payload() must resolve one Blob per requested item (${items.length})`);\n }\n for (const [index, blob] of blobs.entries()) {\n const item = items[index];\n if (blob.size > TRANSFER_MAX_BYTES) return new NochaError("source_too_large", `Item ${item.id} is larger than ${TRANSFER_MAX_BYTES} bytes`);\n if (blob.size === 0) return new NochaError("invalid_result", `Item ${item.id} is empty`);\n if (item.size !== void 0 && blob.size !== item.size) return new NochaError("invalid_result", `Item ${item.id} has ${blob.size} bytes, not the announced ${item.size}`);\n }\n return null;\n}\nvar keyOf = (items) => items.map((item) => item.id).join("\\n");\nfunction createPayloadReader(source2, all) {\n const readings = /* @__PURE__ */ new Map();\n let closed = false;\n const stop = (reading) => {\n if (reading.pending) reading.controller.abort();\n };\n const start = (items) => {\n const key2 = keyOf(items);\n const controller = new AbortController();\n const reading = { ids: items.map((item) => item.id), blobs: Promise.resolve([]), controller, waiters: 0, pending: true, progress: /* @__PURE__ */ new Set() };\n const onProgress = (loaded, total) => {\n reading.last = [loaded, total];\n for (const listener of reading.progress) try {\n listener(loaded, total);\n } catch {\n }\n };\n reading.blobs = (async () => {\n const blobs = await source2.payload(items, { signal: controller.signal, onProgress });\n const problem = blobProblem(items, blobs);\n if (problem) throw problem;\n return blobs;\n })();\n reading.blobs.then(() => {\n reading.pending = false;\n }, () => {\n reading.pending = false;\n if (readings.get(key2) === reading) readings.delete(key2);\n });\n if (!closed) readings.set(key2, reading);\n return reading;\n };\n return {\n read(items, signal, onProgress) {\n if (signal.aborted) return Promise.reject(signal.reason);\n const reading = readings.get(keyOf(items)) ?? readings.get(keyOf(all)) ?? start(items);\n const pick4 = (blobs) => {\n if (reading.ids.length === items.length && reading.ids.every((id, index) => id === items[index].id)) return blobs;\n return items.map((item) => blobs[reading.ids.indexOf(item.id)]);\n };\n reading.waiters += 1;\n reading.progress.add(onProgress);\n if (reading.last) onProgress(...reading.last);\n return new Promise((resolve2, reject2) => {\n let left = false;\n const leave = () => {\n if (left) return;\n left = true;\n signal.removeEventListener("abort", onAbort);\n reading.progress.delete(onProgress);\n reading.waiters -= 1;\n if (closed && reading.waiters === 0) stop(reading);\n };\n const onAbort = () => {\n leave();\n reject2(signal.reason);\n };\n signal.addEventListener("abort", onAbort, { once: true });\n reading.blobs.then((blobs) => {\n leave();\n resolve2(pick4(blobs));\n }, (error) => {\n leave();\n reject2(error);\n });\n });\n },\n prime(items) {\n if (closed || readings.has(keyOf(items))) return;\n start(items).blobs.catch(() => {\n });\n },\n close() {\n if (closed) return;\n closed = true;\n for (const reading of readings.values()) if (reading.waiters === 0) stop(reading);\n readings.clear();\n }\n };\n}\n\n// src/transfer-preview.ts\nvar previewSide = 320;\nvar previewTypes = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);\nasync function sourceOf(preview2) {\n if (preview2 instanceof Blob) {\n if (!preview2.type.startsWith("image/") || typeof createImageBitmap !== "function") return null;\n const bitmap = await createImageBitmap(preview2);\n return { image: bitmap, width: bitmap.width, height: bitmap.height, close: () => bitmap.close() };\n }\n if (typeof HTMLImageElement !== "undefined" && preview2 instanceof HTMLImageElement) {\n if (!preview2.complete) await preview2.decode();\n return { image: preview2, width: preview2.naturalWidth, height: preview2.naturalHeight };\n }\n if (typeof HTMLCanvasElement !== "undefined" && preview2 instanceof HTMLCanvasElement) return { image: preview2, width: preview2.width, height: preview2.height };\n if (typeof HTMLVideoElement !== "undefined" && preview2 instanceof HTMLVideoElement) {\n return preview2.readyState >= 2 ? { image: preview2, width: preview2.videoWidth, height: preview2.videoHeight } : null;\n }\n if (typeof ImageBitmap !== "undefined" && preview2 instanceof ImageBitmap) return { image: preview2, width: preview2.width, height: preview2.height };\n return null;\n}\nasync function encode(canvas, quality) {\n if (typeof OffscreenCanvas !== "undefined" && canvas instanceof OffscreenCanvas) return canvas.convertToBlob({ type: "image/jpeg", quality });\n return new Promise((resolve2) => canvas.toBlob(resolve2, "image/jpeg", quality));\n}\nasync function reducePreview(preview2) {\n let source2 = null;\n try {\n source2 = await sourceOf(preview2);\n if (!source2 || source2.width < 1 || source2.height < 1) return null;\n const scale = Math.min(1, previewSide / Math.max(source2.width, source2.height));\n const width = Math.max(1, Math.round(source2.width * scale));\n const height = Math.max(1, Math.round(source2.height * scale));\n const canvas = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(width, height) : Object.assign(document.createElement("canvas"), { width, height });\n const context = canvas.getContext("2d");\n if (!context) return null;\n context.fillStyle = "#ffffff";\n context.fillRect(0, 0, width, height);\n context.drawImage(source2.image, 0, 0, width, height);\n for (const quality of [0.82, 0.6]) {\n const blob = await encode(canvas, quality);\n if (!blob || !previewTypes.has(blob.type)) return null;\n if (blob.size <= TRANSFER_PREVIEW_MAX_BYTES) return blob;\n }\n return null;\n } catch {\n return null;\n } finally {\n source2?.close?.();\n }\n}\n\n// src/transfer-zones.ts\nvar dropCallbackMs = 25e3;\nvar zones = /* @__PURE__ */ new Map();\nvar hover = null;\nvar lastDragId = null;\nvar generated = 0;\nvar wired = false;\nvar itemOf = ({ id, name, type, size, durationMs, width, height }) => ({\n id,\n name,\n type,\n ...size !== void 0 ? { size } : {},\n ...durationMs !== void 0 ? { durationMs } : {},\n ...width !== void 0 ? { width } : {},\n ...height !== void 0 ? { height } : {}\n});\nfunction zoneAt(x, y) {\n if (typeof document === "undefined") return null;\n for (let element2 = document.elementsFromPoint(x, y)[0] ?? null; element2; element2 = element2.parentElement) {\n const zone = zones.get(element2);\n if (zone) return zone;\n }\n return zones.get(document.documentElement) ?? null;\n}\nvar zoneIdAt = (x, y) => zoneAt(x, y)?.id ?? null;\nvar findZone = (id) => [...zones.values()].find((zone) => zone.id === id) ?? null;\nvar zoneAccepts = (zone, items) => items.length > 0 && items.length <= zone.maxItems && (!zone.accept || items.every((item) => matchesTransferTypes(zone.accept, item.type)));\nfunction rectOf(zone) {\n const rect = zone.element === document.documentElement ? { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight } : zone.element.getBoundingClientRect();\n const size = (value) => Math.max(0, Math.min(1e5, Number.isFinite(value) ? value : 0));\n return { x: clampCoordinate(rect.x), y: clampCoordinate(rect.y), width: size(rect.width), height: size(rect.height) };\n}\nfunction paint(current4) {\n for (const zone of zones.values()) {\n const state3 = !current4 ? null : zone === current4.zone ? zoneAccepts(zone, current4.items) ? "over" : "refused" : zoneAccepts(zone, current4.items) ? "ready" : null;\n if (state3) zone.element.setAttribute("data-nocha-drop", state3);\n else zone.element.removeAttribute("data-nocha-drop");\n }\n if (current4) document.documentElement.setAttribute("data-nocha-transfer", "over");\n else document.documentElement.removeAttribute("data-nocha-transfer");\n}\nfunction endHover() {\n const previous = hover;\n hover = null;\n paint(null);\n if (previous?.zone?.onHover) notifyListener(previous.zone.onHover, null);\n}\nfunction onDragOver(message2) {\n if (hover && hover.dragId !== message2.dragId) endHover();\n const items = message2.items.map(itemOf);\n const zone = zoneAt(message2.x, message2.y);\n const previous = hover?.zone ?? null;\n hover = { dragId: message2.dragId, items, source: { ...message2.source }, zone };\n lastDragId = message2.dragId;\n paint(hover);\n const accepts = zone ? zoneAccepts(zone, items) : false;\n if (previous && previous !== zone && previous.onHover) notifyListener(previous.onHover, null);\n if (zone?.onHover) notifyListener(zone.onHover, { items, source: { ...message2.source }, x: message2.x, y: message2.y, accepts });\n postTransfer({ protocol: NOCHA_TRANSFER_PROTOCOL, type: "hover", dragId: message2.dragId, zone: zone ? {\n id: zone.id,\n usageId: zone.usageId,\n role: zone.role,\n ...zone.label ? { label: zone.label } : {},\n accepts,\n rect: rectOf(zone)\n } : null });\n}\nfunction errorMessage(error) {\n const message2 = isNochaError(error) || error instanceof Error ? error.message : typeof error === "string" ? error : "";\n return message2 ? message2.slice(0, 200) : void 0;\n}\nasync function runDrop(zone, drop) {\n if (!zoneAccepts(zone, drop.items)) return { accepted: false };\n markTransferDrop();\n let timer;\n try {\n const verdict = await Promise.race([\n Promise.resolve().then(() => zone.onDrop(drop)),\n new Promise((resolve2) => {\n timer = setTimeout(() => resolve2("timeout"), dropCallbackMs);\n })\n ]);\n return { accepted: verdict !== false };\n } catch (error) {\n const message2 = errorMessage(error);\n return { accepted: false, ...message2 ? { message: message2 } : {} };\n } finally {\n clearTimeout(timer);\n }\n}\nasync function onDrop(message2) {\n const zone = (message2.zone !== null ? findZone(message2.zone) : null) ?? zoneAt(message2.x, message2.y);\n endHover();\n let verdict = { accepted: false, message: "No drop zone here" };\n if (zone) {\n const items = message2.items.map((item) => ({\n ...itemOf(item),\n file: new File([item.blob], item.name, { type: item.type }),\n ...item.drive ? { drive: { id: item.drive.id, path: [...item.drive.path] } } : {}\n }));\n verdict = await runDrop(zone, {\n zone: zone.id,\n role: message2.role,\n files: items.map((item) => item.file),\n items,\n source: { ...message2.source },\n x: message2.x,\n y: message2.y\n });\n }\n postTransfer({ protocol: NOCHA_TRANSFER_PROTOCOL, type: "drop-result", dragId: message2.dragId, ...verdict });\n}\nfunction wire() {\n if (wired) return;\n wired = true;\n onTransferHostMessage((message2) => {\n if (message2.type === "drag-over") onDragOver(message2);\n else if (message2.type === "drag-leave" || message2.type === "drag-result") {\n if (hover?.dragId === message2.dragId) endHover();\n } else if (message2.type === "drop" && (hover?.dragId === message2.dragId || lastDragId === message2.dragId)) {\n lastDragId = null;\n void onDrop(message2).catch((error) => console.error("Nocha drop failed", error));\n }\n });\n onTransferClose(() => {\n lastDragId = null;\n endHover();\n });\n}\nvar invalid3 = (message2) => new NochaError("invalid_request", message2);\nfunction registerDropZone(usageId, element2, options) {\n if (typeof Element === "undefined" || !(element2 instanceof Element)) throw invalid3("dropZone requires an element");\n if (!options || typeof options !== "object") throw invalid3("dropZone requires options");\n const { id, role, accept, label, maxItems, onDrop: drop, onHover } = options;\n if (id !== void 0 && (typeof id !== "string" || !TRANSFER_ITEM_ID_PATTERN.test(id))) throw invalid3("A drop zone id has 1 to 64 letters, digits, dots, colons, dashes or underscores");\n if (typeof role !== "string" || !TRANSFER_ROLE_PATTERN.test(role)) throw invalid3("A drop zone role is a lowercase name declared in accepts");\n if (accept !== void 0 && (!Array.isArray(accept) || !accept.length || !accept.every(isTransferTypePattern))) throw invalid3("accept lists listed MIME types or image/*, video/*, audio/*");\n if (label !== void 0 && (typeof label !== "string" || !label.trim() || label.length > TRANSFER_LABEL_MAX || !isOneLine(label))) throw invalid3("A drop zone label is one line of at most 60 characters");\n if (maxItems !== void 0 && (!Number.isSafeInteger(maxItems) || maxItems < 1 || maxItems > TRANSFER_MAX_ITEMS)) throw invalid3("maxItems is 1 to 32");\n if (typeof drop !== "function") throw invalid3("dropZone requires onDrop");\n if (onHover !== void 0 && typeof onHover !== "function") throw invalid3("onHover must be a function");\n if (zones.has(element2)) throw invalid3("This element is already a drop zone");\n const ids2 = new Set([...zones.values()].map((zone2) => zone2.id));\n if (id !== void 0 && ids2.has(id)) throw invalid3(`Drop zone ${id} already exists`);\n let zoneId = id;\n while (zoneId === void 0 || ids2.has(zoneId)) zoneId = `zone-${++generated}`;\n wire();\n const zone = {\n id: zoneId,\n element: element2,\n usageId,\n role,\n accept: accept ? [...accept] : null,\n ...label !== void 0 ? { label: label.trim() } : {},\n maxItems: maxItems ?? TRANSFER_MAX_ITEMS,\n onDrop: drop,\n ...onHover ? { onHover } : {}\n };\n zones.set(element2, zone);\n if (hover) paint(hover);\n return () => {\n if (zones.get(element2) !== zone) return;\n zones.delete(element2);\n element2.removeAttribute("data-nocha-drop");\n if (hover?.zone === zone) hover.zone = null;\n };\n}\n\n// src/transfer-source.ts\nvar previewBudgetMs = 80;\nvar progressIntervalMs2 = 150;\nvar heartbeatMs = 2e3;\nvar resultGraceMs = TRANSFER_PAYLOAD_TIMEOUT_MS + TRANSFER_DROP_TIMEOUT_MS + 3e4;\nvar clickSwallowMs = 400;\nvar mouseSlop = 6;\nvar touchSlop = 10;\nvar maxDurationMs = 24 * 36e5;\nvar active = null;\nvar wired2 = false;\nvar invalid4 = (message2) => new NochaError("invalid_request", message2);\nvar transferUnavailable = () => new NochaError("transfer_unavailable", "This Nocha host does not carry drags between windows");\nvar isInteger = (value, min, max) => typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max;\nfunction prepareItems(source2) {\n if (!isRecord(source2) || typeof source2.payload !== "function") throw invalid4("A transfer source needs items and payload()");\n if (source2.eager !== void 0 && typeof source2.eager !== "boolean") throw invalid4("eager must be a boolean");\n let list5;\n try {\n list5 = typeof source2.items === "function" ? source2.items() : source2.items;\n } catch (error) {\n throw invalid4(`The transfer items could not be listed: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!Array.isArray(list5) || list5.length < 1 || list5.length > TRANSFER_MAX_ITEMS) throw invalid4(`A drag carries 1 to ${TRANSFER_MAX_ITEMS} items`);\n const ids2 = /* @__PURE__ */ new Set();\n const wire3 = list5.map((item) => {\n if (!isRecord(item)) throw invalid4("Each transfer item is an object");\n const { id, name, size, durationMs, width, height } = item;\n if (typeof id !== "string" || !TRANSFER_ITEM_ID_PATTERN.test(id)) throw invalid4("An item id has 1 to 64 letters, digits, dots, colons, dashes or underscores");\n if (ids2.has(id)) throw invalid4(`Item id ${id} is used twice`);\n ids2.add(id);\n if (typeof name !== "string" || !name.trim() || name.length > 255 || /[/\\\\]/.test(name) || !isOneLine(name) || name.trim() === "." || name.trim() === "..") {\n throw invalid4(`Item ${id} needs a file name of 1 to 255 characters without /, \\\\ or control characters`);\n }\n const type = normalizeTransferType(item.type);\n if (!type) throw invalid4(`Item ${id}: ${String(item.type)} does not travel between windows`);\n if (size !== void 0 && !isInteger(size, 0, Number.MAX_SAFE_INTEGER)) throw invalid4(`Item ${id}: size is a whole number of bytes`);\n if (typeof size === "number" && size > TRANSFER_MAX_BYTES) throw new NochaError("source_too_large", `Item ${id} is larger than ${TRANSFER_MAX_BYTES} bytes`);\n if (durationMs !== void 0 && !isInteger(durationMs, 0, maxDurationMs)) throw invalid4(`Item ${id}: durationMs is a whole number of milliseconds`);\n if (width !== void 0 && !isInteger(width, 1, 1e5)) throw invalid4(`Item ${id}: width is a whole number of pixels`);\n if (height !== void 0 && !isInteger(height, 1, 1e5)) throw invalid4(`Item ${id}: height is a whole number of pixels`);\n return {\n id,\n name,\n type,\n ...size !== void 0 ? { size } : {},\n ...durationMs !== void 0 ? { durationMs } : {},\n ...width !== void 0 ? { width } : {},\n ...height !== void 0 ? { height } : {}\n };\n });\n return { items: list5, wire: wire3 };\n}\nfunction labelOf(source2, wire3) {\n const raw = typeof source2.label === "string" && source2.label.trim() ? source2.label : wire3[0]?.name ?? "";\n const label = toOneLine(raw).replace(/\\s+/g, " ").trim().slice(0, TRANSFER_LABEL_MAX).trim();\n return label || void 0;\n}\nasync function servePayload(drag, request2) {\n const { signal } = drag.controller;\n const base2 = { protocol: NOCHA_TRANSFER_PROTOCOL, dragId: drag.dragId, requestId: request2.requestId };\n const post = (message2) => {\n if (!signal.aborted) postTransfer(message2);\n };\n const fail = (code, message2) => post({ ...base2, type: "payload-error", code, message: message2.slice(0, 500) });\n const byId = new Map(drag.items.map((item) => [item.id, item]));\n const items = request2.itemIds.map((id) => byId.get(id));\n if (items.some((item) => !item) || new Set(request2.itemIds).size !== items.length) {\n fail("invalid_request", "The host asked for an item this drag does not carry");\n return;\n }\n const requested = items;\n let lastProgress = -Infinity;\n const onProgress = (loaded, total) => {\n const now = performance.now();\n if (now - lastProgress < progressIntervalMs2 || typeof loaded !== "number" || !Number.isFinite(loaded)) return;\n lastProgress = now;\n const count2 = (value) => Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.floor(value)));\n post({ ...base2, type: "payload-progress", loaded: count2(loaded), ...typeof total === "number" && Number.isFinite(total) ? { total: count2(total) } : {} });\n };\n try {\n const blobs = await drag.payloads.read(requested, signal, onProgress);\n if (signal.aborted) return;\n post({ ...base2, type: "payload", blobs: blobs.map((blob, index) => {\n const type = normalizeTransferType(requested[index].type);\n return blob.type === type ? blob : blob.slice(0, blob.size, type);\n }) });\n } catch (error) {\n if (signal.aborted) return;\n const code = isNochaError(error) && CODE_PATTERN.test(error.code) ? error.code : "invocation_failed";\n fail(code, error instanceof Error && error.message ? error.message : "The experience could not read the files");\n }\n}\nfunction endOf(drag, result2) {\n switch (result2.outcome) {\n case "dropped":\n return { outcome: "dropped", target: result2.target ?? "experience" };\n case "returned": {\n const x = result2.x ?? drag.x, y = result2.y ?? drag.y;\n return { outcome: "returned", x, y, zone: zoneIdAt(x, y) };\n }\n case "refused":\n return { outcome: "refused", ...result2.code !== void 0 ? { code: result2.code } : {} };\n default:\n return { outcome: "cancelled" };\n }\n}\nfunction wire2() {\n if (wired2) return;\n wired2 = true;\n onTransferHostMessage((message2) => {\n const drag = active;\n if (!drag || !("dragId" in message2) || message2.dragId !== drag.dragId) return;\n if (message2.type === "payload-request") void servePayload(drag, message2);\n else if (message2.type === "drag-result") drag.settle(endOf(drag, message2));\n });\n onTransferClose(() => active?.cancel());\n}\nfunction runDrag(usageId, init, source2, prepared, payloads) {\n if (active) return Promise.reject(new NochaError("rate_limited", "Another drag is under way"));\n wire2();\n const { pointerId, captureTarget } = init;\n return new Promise((resolve2) => {\n let frame = 0;\n let watchdog;\n let captured = false;\n const heartbeat = setInterval(() => {\n if (!frame) flush();\n }, heartbeatMs);\n const position = () => ({ x: clampCoordinate(drag.x), y: clampCoordinate(drag.y) });\n const sendEnd = (cancelled) => postTransfer({ protocol: NOCHA_TRANSFER_PROTOCOL, type: "drag-end", dragId: drag.dragId, ...position(), cancelled });\n const flush = () => {\n frame = 0;\n if (drag.started && !drag.released && !drag.settled) postTransfer({ protocol: NOCHA_TRANSFER_PROTOCOL, type: "drag-move", dragId: drag.dragId, ...position() });\n };\n const track = (event) => {\n drag.x = event.clientX;\n drag.y = event.clientY;\n };\n const release2 = () => {\n if (drag.released) return;\n drag.released = true;\n drag.stopPointer();\n if (drag.started) sendEnd(false);\n watchdog = setTimeout(() => drag.settle({ outcome: "cancelled" }), resultGraceMs);\n };\n const onMove = (event) => {\n if (event.pointerId !== pointerId) return;\n track(event);\n if (!frame) frame = requestAnimationFrame(flush);\n };\n const onUp = (event) => {\n if (event.pointerId === pointerId) {\n track(event);\n release2();\n }\n };\n const onCancel = (event) => {\n if (event.pointerId === pointerId) drag.cancel();\n };\n const onLost = (event) => {\n if (captured && event.pointerId === pointerId && event.target === captureTarget && !drag.released) drag.cancel();\n };\n const onKey = (event) => {\n if (event.key === "Escape" && !drag.released) {\n event.preventDefault();\n drag.cancel();\n }\n };\n const onVisibility = () => {\n if (document.visibilityState === "hidden") drag.cancel();\n };\n const listeners2 = [\n [window, "pointermove", onMove],\n [window, "pointerup", onUp],\n [window, "pointercancel", onCancel],\n [window, "lostpointercapture", onLost],\n [window, "keydown", onKey],\n [document, "visibilitychange", onVisibility]\n ];\n const drag = {\n dragId: crypto.randomUUID(),\n items: prepared.items,\n source: source2,\n pointerId,\n x: init.x,\n y: init.y,\n started: false,\n released: false,\n settled: false,\n controller: new AbortController(),\n payloads,\n cancel() {\n if (drag.settled) return;\n if (drag.started && !drag.released) sendEnd(true);\n drag.settle({ outcome: "cancelled" });\n },\n stopPointer() {\n for (const [target, type, listener] of listeners2) target.removeEventListener(type, listener, true);\n clearInterval(heartbeat);\n if (frame) cancelAnimationFrame(frame);\n frame = 0;\n if (captured && captureTarget?.hasPointerCapture(pointerId)) try {\n captureTarget.releasePointerCapture(pointerId);\n } catch {\n }\n captured = false;\n },\n settle(end) {\n if (drag.settled) return;\n drag.settled = true;\n if (active === drag) active = null;\n drag.stopPointer();\n clearTimeout(watchdog);\n drag.controller.abort();\n resolve2(end);\n }\n };\n active = drag;\n if (captureTarget) try {\n captureTarget.setPointerCapture(pointerId);\n captured = true;\n } catch {\n }\n for (const [target, type, listener] of listeners2) target.addEventListener(type, listener, true);\n let preview2;\n try {\n preview2 = typeof source2.preview === "function" ? source2.preview() : source2.preview;\n } catch {\n preview2 = null;\n }\n const label = labelOf(source2, prepared.wire);\n void (async () => {\n const blob = preview2 ? await Promise.race([reducePreview(preview2), new Promise((done) => setTimeout(() => done(null), previewBudgetMs))]) : null;\n if (drag.settled) return;\n const start = init.origin ? { x: clampCoordinate(init.origin.x), y: clampCoordinate(init.origin.y) } : position();\n postTransfer({\n protocol: NOCHA_TRANSFER_PROTOCOL,\n type: "drag-start",\n dragId: drag.dragId,\n usageId,\n ...start,\n pointerType: init.pointerType,\n items: prepared.wire,\n ...label ? { label } : {},\n ...blob ? { preview: blob } : {}\n });\n drag.started = true;\n if (source2.eager === true) payloads.prime(prepared.items);\n if (drag.released) sendEnd(false);\n })().catch((error) => {\n console.error("Nocha drag failed to start", error);\n drag.cancel();\n });\n });\n}\nvar pointerTypeOf = (value) => value === "touch" || value === "pen" ? value : "mouse";\nfunction startDrag(usageId, event, source2) {\n if (!transferAvailable()) return Promise.reject(transferUnavailable());\n const live = typeof PointerEvent !== "undefined" && event instanceof PointerEvent && event.isTrusted && event.buttons !== 0 && event.type !== "pointerup" && event.type !== "pointercancel";\n if (!live) return Promise.reject(invalid4("start() needs the live PointerEvent of a pressed pointer"));\n let prepared;\n try {\n prepared = prepareItems(source2);\n } catch (error) {\n return Promise.reject(error);\n }\n const payloads = createPayloadReader(source2, prepared.items);\n return runDrag(usageId, {\n pointerId: event.pointerId,\n pointerType: pointerTypeOf(event.pointerType),\n x: event.clientX,\n y: event.clientY,\n captureTarget: event.target instanceof Element ? event.target : null\n }, source2, prepared, payloads).finally(() => payloads.close());\n}\nasync function deliverToSelf(end, items, payloads) {\n const zone = end.zone !== null ? findZone(end.zone) : null;\n if (!zone || !zoneAccepts(zone, items)) return;\n const controller = new AbortController();\n const stop = onTransferClose(() => controller.abort());\n try {\n const blobs = await payloads.read(items, controller.signal, () => {\n });\n if (controller.signal.aborted) return;\n const dropped = items.map((item, index) => {\n const type = normalizeTransferType(item.type);\n return { ...item, type, file: new File([blobs[index]], item.name, { type }) };\n });\n const verdict = await runDrop(zone, {\n zone: zone.id,\n role: zone.role,\n files: dropped.map((item) => item.file),\n items: dropped,\n source: { kind: "experience", title: document.title || "Nocha", self: true },\n x: end.x,\n y: end.y\n });\n if (!verdict.accepted && verdict.message) console.warn(`Nocha drop refused: ${verdict.message}`);\n } catch (error) {\n if (controller.signal.aborted) return;\n console.error("Nocha could not drop the files on this document", error);\n } finally {\n stop();\n }\n}\nvar lockedStyles = [["-webkit-touch-callout", "none"], ["user-select", "none"], ["-webkit-user-select", "none"], ["-webkit-user-drag", "none"]];\nfunction makeDraggable(usageId, element2, options) {\n if (typeof Element === "undefined" || !(element2 instanceof Element)) throw invalid4("draggable requires an element");\n if (!isRecord(options) || typeof options.payload !== "function" || options.items === void 0) throw invalid4("draggable requires items and payload()");\n for (const name of ["canStart", "onStart", "onEnd"]) {\n if (options[name] !== void 0 && typeof options[name] !== "function") throw invalid4(`${name} must be a function`);\n }\n const holdMs = typeof options.holdMs === "number" && Number.isFinite(options.holdMs) ? Math.min(1500, Math.max(150, options.holdMs)) : 350;\n const style2 = element2.style;\n const saved = lockedStyles.map(([name]) => [name, style2?.getPropertyValue(name) ?? "", style2?.getPropertyPriority(name) ?? ""]);\n for (const [name, value] of lockedStyles) style2?.setProperty(name, value);\n let press = null;\n let dragging = false;\n let disposed = false;\n let unlockScroll = null;\n const onPressMove = (event) => {\n if (!press || event.pointerId !== press.pointerId) return;\n const distance2 = Math.hypot(event.clientX - press.x, event.clientY - press.y);\n if (press.pointerType === "touch") {\n if (distance2 > touchSlop) endPress();\n else press.last = event;\n } else if (distance2 >= mouseSlop) launch(event);\n };\n const onPressEnd = (event) => {\n if (press && event.pointerId === press.pointerId) endPress();\n };\n const pressListeners = [\n ["pointermove", onPressMove],\n ["pointerup", onPressEnd],\n ["pointercancel", onPressEnd]\n ];\n function endPress() {\n if (!press) return;\n clearTimeout(press.timer);\n press = null;\n for (const [type, listener] of pressListeners) window.removeEventListener(type, listener, true);\n }\n function lockScroll(pointerId) {\n const block = (event) => {\n if (event.cancelable) event.preventDefault();\n };\n const lift = (event) => {\n if (event.pointerId === pointerId) unlock();\n };\n const unlock = () => {\n document.removeEventListener("touchmove", block, true);\n window.removeEventListener("pointerup", lift, true);\n window.removeEventListener("pointercancel", lift, true);\n if (unlockScroll === unlock) unlockScroll = null;\n };\n document.addEventListener("touchmove", block, { capture: true, passive: false });\n window.addEventListener("pointerup", lift, true);\n window.addEventListener("pointercancel", lift, true);\n unlockScroll = unlock;\n }\n function swallowClick(pointerId) {\n let timer;\n const swallow = (event) => {\n event.preventDefault();\n event.stopPropagation();\n remove2();\n };\n const arm = (event) => {\n if (event.pointerId === pointerId && timer === void 0) timer = setTimeout(remove2, clickSwallowMs);\n };\n const remove2 = () => {\n clearTimeout(timer);\n window.removeEventListener("click", swallow, true);\n window.removeEventListener("pointerup", arm, true);\n window.removeEventListener("pointercancel", arm, true);\n };\n window.addEventListener("click", swallow, true);\n window.addEventListener("pointerup", arm, true);\n window.addEventListener("pointercancel", arm, true);\n }\n function launch(event) {\n const current4 = press;\n if (!current4) return;\n endPress();\n if (!transferAvailable() || active) return;\n let prepared;\n try {\n prepared = prepareItems(options);\n } catch (error) {\n console.error("Nocha draggable items are invalid", error);\n return;\n }\n if (current4.pointerType === "touch") {\n try {\n navigator.vibrate?.(10);\n } catch {\n }\n lockScroll(current4.pointerId);\n }\n dragging = true;\n swallowClick(current4.pointerId);\n element2.setAttribute("data-nocha-dragging", "");\n if (options.onStart) notifyListener(() => options.onStart(), void 0);\n const payloads = createPayloadReader(options, prepared.items);\n runDrag(usageId, {\n pointerId: current4.pointerId,\n pointerType: current4.pointerType,\n x: event.clientX,\n y: event.clientY,\n origin: { x: current4.x, y: current4.y },\n captureTarget: element2\n }, options, prepared, payloads).catch((error) => {\n console.error("Nocha drag failed", error);\n return { outcome: "cancelled" };\n }).then((end) => {\n dragging = false;\n element2.removeAttribute("data-nocha-dragging");\n unlockScroll?.();\n if (options.onEnd) notifyListener(options.onEnd.bind(options), end);\n if (end.outcome === "returned" && !disposed) void deliverToSelf(end, prepared.items, payloads).finally(() => payloads.close());\n else payloads.close();\n });\n }\n const onPointerDown = (event) => {\n if (press || dragging || active || !event.isPrimary || !transferAvailable()) return;\n const pointerType = pointerTypeOf(event.pointerType);\n if (pointerType !== "touch" && event.button !== 0) return;\n if (options.canStart) {\n try {\n if (!options.canStart(event)) return;\n } catch (error) {\n console.error("Nocha canStart failed", error);\n return;\n }\n }\n press = { pointerId: event.pointerId, pointerType, x: event.clientX, y: event.clientY, last: event };\n for (const [type, listener] of pressListeners) window.addEventListener(type, listener, true);\n if (pointerType === "touch") press.timer = setTimeout(() => {\n if (press) launch(press.last);\n }, holdMs);\n };\n const onBlocked = (event) => {\n if (press || dragging) event.preventDefault();\n };\n element2.addEventListener("pointerdown", onPointerDown);\n element2.addEventListener("contextmenu", onBlocked);\n element2.addEventListener("dragstart", onBlocked);\n return () => {\n if (disposed) return;\n disposed = true;\n endPress();\n element2.removeEventListener("pointerdown", onPointerDown);\n element2.removeEventListener("contextmenu", onBlocked);\n element2.removeEventListener("dragstart", onBlocked);\n for (const [name, value, priority] of saved) {\n if (value) style2?.setProperty(name, value, priority);\n else style2?.removeProperty(name);\n }\n if (dragging && active?.source === options) active.cancel();\n };\n}\n\n// src/transfer.ts\nfunction createTransfer(context) {\n const usage = () => {\n activateTransfer();\n if (context.usageId === void 0) throw new NochaError("usage_required", "transfer requires nocha.use(<declared usage id>)");\n return context.usageId;\n };\n return Object.freeze({\n get available() {\n activateTransfer();\n return transferAvailable();\n },\n onAvailabilityChange(listener) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "An availability listener is required");\n activateTransfer();\n notifyListener(listener, transferAvailable());\n return onTransferAvailability(listener);\n },\n draggable(element2, options) {\n return makeDraggable(usage(), element2, options);\n },\n start(event, source2) {\n let usageId;\n try {\n usageId = usage();\n } catch (error) {\n return Promise.reject(error);\n }\n return startDrag(usageId, event, source2);\n },\n dropZone(element2, options) {\n return registerDropZone(usage(), element2, options);\n }\n });\n}\n\n// src/connectors.ts\nfunction createConnectors(context) {\n return Object.freeze({\n async status(options) {\n const value = await context.invoke("connectors", "status", {}, options);\n if (!isRecord(value) || typeof value.granted !== "boolean" || typeof value.ready !== "boolean" || !Array.isArray(value.operations) || !value.operations.every((item) => typeof item === "string") || !(value.account === null || isRecord(value.account) && typeof value.account.label === "string" && ["google", "github", "notion"].includes(String(value.account.provider)))) {\n throw new NochaError("invalid_result", "Nocha returned an invalid connector status");\n }\n return value;\n },\n async request(options) {\n const value = await context.invoke("connectors", "request", {}, options);\n if (!isRecord(value) || typeof value.granted !== "boolean") throw new NochaError("invalid_result", "Nocha returned an invalid connector authorization");\n return { granted: value.granted };\n },\n async invoke(operation2, input4, options) {\n if (typeof operation2 !== "string" || !operation2) throw new NochaError("invalid_request", "Expected a declared connector operation");\n return await context.invoke("connectors", "invoke", { operation: operation2, input: input4 }, options);\n },\n async revoke(options) {\n await context.invoke("connectors", "revoke", {}, options);\n }\n });\n}\n\n// src/email.ts\nvar isResult = (value) => isRecord(value) && isUuid(value.id) && (value.status === "queued" || value.status === "sent" || value.status === "duplicate");\nfunction createEmail(context) {\n return Object.freeze({\n async send(input4, options) {\n const operation2 = emailOperationDefinitions.send;\n const value = await context.invoke(operation2.capability, operation2.operation, input4, options);\n if (!isResult(value)) throw new NochaError("invalid_result", "Nocha returned an invalid email result");\n return value;\n }\n });\n}\n\n// src/retry.ts\nvar retryBaseMs = 500;\nvar retryMaxMs = 8e3;\nfunction retryDelayMs(error, attempt) {\n if (classifyError(error) !== "transient") return void 0;\n const ceiling2 = Math.min(retryMaxMs, retryBaseMs * 2 ** Math.min(Math.max(0, attempt), 4));\n return ceiling2 * (0.5 + Math.random() / 2);\n}\n\n// src/multiplayer-subscriptions.ts\nvar operation = multiplayerOperationDefinitions.subscribe;\nvar pendingEventLimit = 256;\nvar pendingEventByteLimit = 1048576;\nvar encoder = new TextEncoder();\nfunction subscriptionResult(value, topic, subscribed) {\n if (!isRecord(value) || value.topic !== topic || value.subscribed !== subscribed) {\n throw new NochaError("invalid_result", "Nocha returned an invalid multiplayer subscription result");\n }\n}\nvar definitiveRefusal = (error) => ["denied", "invalid", "billing"].includes(classifyError(error));\nfunction createMultiplayerSubscriptions(listeners2, reconcile) {\n const topics = /* @__PURE__ */ new Map();\n const cleanupFailures = /* @__PURE__ */ new Map();\n const callers = /* @__PURE__ */ new Set();\n const scope = new AbortController();\n let closed;\n const retire = (topic) => {\n if (closed || topic.callers.size || topics.get(topic.name) !== topic) return Promise.resolve();\n if (topic.closing) return topic.closing;\n topic.controller.abort();\n topic.closing = (async () => {\n await Promise.all([...topic.authorizations.values()].map((pending3) => pending3.catch(() => {\n })));\n if (closed || !topic.mayExist) return;\n topic.lateResult = false;\n const value = await invokeBridge(operation.capability, operation.operation, { topic: topic.name, action: "unsubscribe" }, {\n usageId: topic.usageId,\n timeoutMs: operation.sdkTimeoutMs,\n signal: scope.signal\n });\n subscriptionResult(value, topic.name, false);\n })().catch((error) => {\n cleanupFailures.set(topic.name, error);\n throw error;\n }).finally(() => {\n if (topics.get(topic.name) !== topic) return;\n topics.delete(topic.name);\n topic.closing = void 0;\n if (!closed && topic.lateResult) {\n topic.lateResult = false;\n topics.set(topic.name, topic);\n void retire(topic).catch(() => {\n });\n }\n reconcile();\n });\n return topic.closing;\n };\n const reconcileAbandoned = (abandoned, usageId, confirmed2 = false) => {\n if (closed) return;\n if (cleanupFailures.has(abandoned.name) && definitiveRefusal(cleanupFailures.get(abandoned.name))) return;\n const current4 = topics.get(abandoned.name);\n if (current4?.callers.size) return;\n const topic = current4 ?? abandoned;\n if (!current4) topics.set(topic.name, topic);\n topic.mayExist = true;\n if (confirmed2 || !topic.authorized) topic.usageId = usageId;\n if (confirmed2) topic.authorized = true;\n topic.lateResult = true;\n void retire(topic).catch(() => {\n });\n };\n const authorize = (topic, options) => {\n const key2 = options.usageId ?? "";\n let pending3 = topic.authorizations.get(key2);\n if (pending3) return pending3;\n pending3 = invokeBridgeWithLateResult(operation.capability, operation.operation, { topic: topic.name }, {\n ...options,\n timeoutMs: operation.sdkTimeoutMs,\n signal: topic.controller.signal\n }, {\n signal: scope.signal,\n onResult: () => reconcileAbandoned(topic, options.usageId, true),\n onError: (error) => {\n if (!definitiveRefusal(error)) reconcileAbandoned(topic, options.usageId);\n },\n // Even a completely lost reply cannot hide setup that finished after the first\n // deletion. Reconcile once at the host operation\'s normal waiting ceiling.\n onExpired: () => reconcileAbandoned(topic, options.usageId)\n }).then((value) => {\n topic.mayExist = true;\n subscriptionResult(value, topic.name, true);\n topic.authorized = true;\n topic.usageId = options.usageId;\n }).catch((error) => {\n if (!definitiveRefusal(error)) {\n topic.mayExist = true;\n if (!topic.authorized) topic.usageId = options.usageId;\n }\n if (topic.authorizations.get(key2) === pending3) topic.authorizations.delete(key2);\n throw error;\n });\n topic.authorizations.set(key2, pending3);\n return pending3;\n };\n const subscribe4 = async (name, listener, options = {}) => {\n if (closed) throw closed;\n const { signal, timeoutMs, idempotencyKey } = options;\n if (signal !== void 0 && !(signal instanceof AbortSignal)) throw new NochaError("invalid_request", "signal must be an AbortSignal");\n if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647)) {\n throw new NochaError("invalid_request", "timeoutMs must be a positive finite timer duration");\n }\n if (idempotencyKey !== void 0 && !isIdempotencyKey(idempotencyKey)) throw new NochaError("invalid_request", "The idempotency key must have 8 to 200 characters without control characters");\n const aborted = () => new NochaError("aborted", "Local multiplayer subscription was aborted");\n if (signal?.aborted) throw aborted();\n let active3 = true;\n let ready = false;\n let stopped;\n const buffered = [];\n let bufferedBytes = 0;\n let topic;\n let closing;\n let timer;\n let rejectWait;\n const cancelled = new Promise((_resolve, reject2) => {\n rejectWait = reject2;\n });\n const clearBuffer = () => {\n buffered.length = 0;\n bufferedBytes = 0;\n };\n const guarded = (event) => {\n if (!active3 || signal?.aborted) return;\n if (ready) {\n listener(event);\n return;\n }\n try {\n const serialized = JSON.stringify(event);\n if (serialized === void 0) throw new Error("The event is not serializable");\n const remaining = pendingEventByteLimit - bufferedBytes;\n const bytes = serialized.length > remaining ? serialized.length : encoder.encode(serialized).byteLength;\n if (buffered.length >= pendingEventLimit || bytes > remaining) {\n void cancel2(new NochaError("multiplayer_unavailable", "Too many multiplayer events arrived before subscription authorization; reload the authoritative snapshot", {\n details: { topic: name, reason: "subscription_buffer_overflow", maximumEvents: pendingEventLimit, maximumBytes: pendingEventByteLimit }\n })).catch(() => {\n });\n return;\n }\n buffered.push(structuredClone(event));\n bufferedBytes += bytes;\n } catch {\n void cancel2(new NochaError("invalid_result", "A multiplayer event could not be buffered before authorization")).catch(() => {\n });\n }\n };\n const stopWaiting = () => {\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n };\n const cancel2 = (error) => {\n if (!active3) return closing ?? Promise.resolve();\n active3 = false;\n stopped = error;\n clearBuffer();\n stopWaiting();\n signal?.removeEventListener("abort", onAbort);\n callers.delete(cancel2);\n if (topic) {\n topic.callers.delete(cancel2);\n const callbacks = listeners2.get(name);\n callbacks?.delete(guarded);\n if (!callbacks?.size) listeners2.delete(name);\n }\n rejectWait(error);\n closing = topic ? retire(topic) : Promise.resolve();\n reconcile();\n return closing;\n };\n const onAbort = () => {\n void cancel2(aborted()).catch(() => {\n });\n };\n callers.add(cancel2);\n signal?.addEventListener("abort", onAbort, { once: true });\n timer = setTimeout(() => {\n void cancel2(new NochaError("invocation_timed_out", "Local multiplayer subscription timed out")).catch(() => {\n });\n }, timeoutMs ?? operation.sdkTimeoutMs);\n const setup = async () => {\n while (active3 && !closed) {\n if (cleanupFailures.has(name)) throw cleanupFailures.get(name);\n const current4 = topics.get(name);\n if (current4?.closing) {\n await current4.closing;\n continue;\n }\n topic = current4 ?? {\n name,\n usageId: options.usageId,\n callers: /* @__PURE__ */ new Set(),\n authorizations: /* @__PURE__ */ new Map(),\n controller: new AbortController(),\n authorized: false,\n mayExist: false,\n lateResult: false\n };\n topics.set(name, topic);\n topic.callers.add(cancel2);\n let callbacks = listeners2.get(name);\n if (!callbacks) {\n callbacks = /* @__PURE__ */ new Set();\n listeners2.set(name, callbacks);\n }\n callbacks.add(guarded);\n await authorize(topic, options);\n if (!active3 || closed) throw closed ?? stopped ?? aborted();\n stopWaiting();\n for (let index = 0; active3 && index < buffered.length; index++) notifyListener(listener, buffered[index]);\n clearBuffer();\n if (!active3 || closed) throw closed ?? stopped ?? aborted();\n ready = true;\n return () => cancel2(new NochaError("request_cancelled", "Multiplayer listener was disposed"));\n }\n throw closed ?? aborted();\n };\n try {\n return await Promise.race([setup(), cancelled]);\n } catch (error) {\n void cancel2(isNochaError(error) ? error : new NochaError("invocation_failed", String(error))).catch(() => {\n });\n throw error;\n }\n };\n return {\n subscribe: subscribe4,\n /** The host owns socket teardown on revocation, scope replacement or document exit.\n * Cancel our callbacks, waits and late observers without invoking a successor scope. */\n close(error = new NochaError("request_cancelled", "The multiplayer host scope closed")) {\n if (closed) return;\n closed = error;\n scope.abort();\n for (const cancel2 of callers) void cancel2(error).catch(() => {\n });\n for (const topic of topics.values()) topic.controller.abort();\n topics.clear();\n cleanupFailures.clear();\n listeners2.clear();\n reconcile();\n }\n };\n}\n\n// src/multiplayer.ts\nfunction record4(value) {\n return value !== null && typeof value === "object" && !Array.isArray(value);\n}\nfunction identity(value) {\n return record4(value) && typeof value.user === "string" && typeof value.display_name === "string" && (value.role === "participant" || value.role === "observer");\n}\nfunction isPresenceSnapshot(value) {\n return record4(value) && identity(value.self) && Array.isArray(value.members) && value.members.every(identity) && typeof value.count === "number" && Number.isInteger(value.count) && value.count >= 0;\n}\nfunction isPresenceEvent(value) {\n return record4(value) && isPresenceSnapshot(value.snapshot) && (value.type === "reconcile" || (value.type === "join" || value.type === "leave") && identity(value.member));\n}\nfunction isLiveSender(value) {\n return identity(value) || record4(value) && value.user === "system" && value.role === "system" && value.display_name === "Nocha";\n}\nfunction parseLiveEvent(value) {\n if (!record4(value) || typeof value.topic !== "string" || typeof value.eventId !== "string" || !value.eventId || typeof value.publishedAt !== "string" || !value.publishedAt || value.delivery !== "ephemeral" && value.delivery !== "durable" || value.recovered !== void 0 && typeof value.recovered !== "boolean" || !isLiveSender(value.sender)) return null;\n return { topic: value.topic, data: value.data, sender: value.sender, delivery: value.delivery, eventId: value.eventId, publishedAt: value.publishedAt, recovered: value.recovered === true };\n}\nfunction isLiveConnection(value) {\n return record4(value) && ["connecting", "connected", "recovering", "unavailable", "closed"].includes(String(value.status)) && (value.reason === void 0 || typeof value.reason === "string") && (value.attempt === void 0 || typeof value.attempt === "number" && Number.isInteger(value.attempt) && value.attempt >= 0);\n}\nfunction isLiveRecoveryRequired(value) {\n return record4(value) && typeof value.topic === "string" && value.reason === "history_lost";\n}\n\n// src/multiplayer-facade.ts\nfunction createLiveHub() {\n const connections = /* @__PURE__ */ new Set();\n const recoveries = /* @__PURE__ */ new Set();\n const events = /* @__PURE__ */ new Set();\n const presence = /* @__PURE__ */ new Set();\n const topics = /* @__PURE__ */ new Map();\n let lastConnection;\n let lastPresence;\n let presenceRevision = 0;\n let stop;\n const reconcile = () => {\n if (!events.size && !presence.size && !topics.size && !connections.size && !recoveries.size) {\n stop?.();\n stop = void 0;\n }\n };\n const subscriptions = createMultiplayerSubscriptions(topics, reconcile);\n let tracking = false;\n let workspaceKey;\n const track = () => {\n if (tracking) return;\n tracking = true;\n subscribeBridgeEvents((event) => {\n if (event.type === "workspace.changed" && isRecord(event.payload)) {\n const { id, environment, revisionId, participantId, permissions } = event.payload;\n if (isNonEmptyString(id) && isNonEmptyString(revisionId) && (environment === "play" || environment === "development") && (participantId === null || typeof participantId === "string")) {\n const next = JSON.stringify([id, environment, revisionId, participantId]);\n if (workspaceKey !== void 0 && workspaceKey !== next || isRecord(permissions) && permissions.read === false) subscriptions.close();\n workspaceKey = next;\n }\n return;\n }\n if (event.type !== "multiplayer.connection" || !isLiveConnection(event.payload)) return;\n if (event.payload.status === "closed") subscriptions.close();\n if (lastConnection?.status === event.payload.status && lastConnection.reason === event.payload.reason && lastConnection.attempt === event.payload.attempt) return;\n lastConnection = event.payload;\n for (const listener of connections) notifyListener(listener, event.payload);\n });\n window.addEventListener("pagehide", (event) => {\n if (!event.persisted) subscriptions.close();\n });\n };\n const listen = () => {\n track();\n stop ??= subscribeBridgeEvents((event) => {\n if (event.type === "multiplayer.recovery.required" && isLiveRecoveryRequired(event.payload)) {\n for (const listener of recoveries) notifyListener(listener, event.payload);\n }\n if (event.type === "multiplayer.presence" && isPresenceEvent(event.payload)) {\n const payload = event.payload;\n lastPresence = payload;\n presenceRevision += 1;\n for (const listener of presence) notifyListener(listener, payload);\n }\n if (event.type === "multiplayer.event") {\n const payload = parseLiveEvent(event.payload);\n if (payload) for (const listener of topics.get(payload.topic) ?? []) notifyListener(listener, payload);\n }\n for (const listener of events) notifyListener(listener, event);\n });\n };\n const onConnection = (listener) => {\n assertHostCapability("multiplayer");\n connections.add(listener);\n listen();\n const initial = lastConnection;\n if (initial) queueMicrotask(() => {\n if (connections.has(listener) && lastConnection === initial) notifyListener(listener, initial);\n });\n return () => {\n connections.delete(listener);\n reconcile();\n };\n };\n return {\n connections,\n recoveries,\n events,\n presence,\n topics,\n track,\n listen,\n reconcile,\n onConnection,\n get lastConnection() {\n return lastConnection;\n },\n get lastPresence() {\n return lastPresence;\n },\n get presenceRevision() {\n return presenceRevision;\n },\n subscribe: subscriptions.subscribe,\n onEvent(listener) {\n assertHostCapability("events");\n events.add(listener);\n listen();\n return () => {\n events.delete(listener);\n reconcile();\n };\n }\n };\n}\nvar durableKey = /^[A-Za-z0-9._:-]{8,200}$/;\nfunction presenceSnapshot(value) {\n if (!isPresenceSnapshot(value)) throw new NochaError("invalid_result", "Nocha returned an invalid presence snapshot");\n return value;\n}\nfunction createMultiplayer(context, hub) {\n return Object.freeze({\n onConnection: hub.onConnection,\n onRecoveryRequired(listener) {\n assertHostCapability("multiplayer");\n hub.recoveries.add(listener);\n hub.listen();\n return () => {\n hub.recoveries.delete(listener);\n hub.reconcile();\n };\n },\n async presence(options) {\n hub.track();\n return presenceSnapshot(await context.invoke(multiplayerOperationDefinitions["presence"].capability, multiplayerOperationDefinitions["presence"].operation, {}, options));\n },\n onPresence(listener, options) {\n assertHostCapability("multiplayer");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A presence listener is required");\n const { onError, ...request2 } = options ?? {};\n const fail = (error) => {\n if (typeof onError === "function") notifyListener(onError, error);\n };\n if (context.usageId === void 0) {\n fail(new NochaError("usage_required", "multiplayer.onPresence requires nocha.use(<declared usage id>)"));\n return () => {\n };\n }\n let active3 = true;\n const controller = new AbortController();\n let attempt = 0;\n let pending3 = false;\n let timer;\n const cancelRetry = () => {\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n hub.connections.delete(onConnection);\n };\n const dispose = () => {\n active3 = false;\n controller.abort();\n cancelRetry();\n hub.presence.delete(listener);\n request2.signal?.removeEventListener("abort", dispose);\n hub.reconcile();\n };\n const initialize = () => {\n if (!active3 || pending3 || hub.presence.has(listener)) return;\n if (hub.lastConnection?.status === "closed") {\n dispose();\n return;\n }\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n pending3 = true;\n const startedRevision = hub.presenceRevision;\n void context.invoke(multiplayerOperationDefinitions["presence"].capability, multiplayerOperationDefinitions["presence"].operation, {}, { ...request2, signal: controller.signal }).then((value) => {\n if (!active3) return;\n const snapshot3 = presenceSnapshot(value);\n const last = hub.lastPresence;\n const current4 = hub.presenceRevision !== startedRevision && last?.snapshot.self.user === snapshot3.self.user ? last.snapshot : snapshot3;\n attempt = 0;\n cancelRetry();\n hub.presence.add(listener);\n hub.listen();\n notifyListener(listener, { type: "reconcile", snapshot: current4 });\n }).catch((cause) => {\n if (!active3) return;\n const error = isNochaError(cause) ? cause : new NochaError("invocation_failed", String(cause));\n const delay = retryDelayMs(error, attempt);\n if (delay === void 0) {\n dispose();\n if (error.code !== "aborted") fail(error);\n return;\n }\n attempt += 1;\n timer = setTimeout(initialize, delay);\n }).finally(() => {\n pending3 = false;\n });\n };\n const onConnection = (event) => {\n if (event.status === "closed") dispose();\n else if (event.status === "connected") initialize();\n };\n if (request2.signal?.aborted) return dispose;\n request2.signal?.addEventListener("abort", dispose, { once: true });\n hub.connections.add(onConnection);\n hub.listen();\n initialize();\n return dispose;\n },\n async subscribe(topic, listener, options) {\n assertHostCapability("multiplayer");\n if (context.usageId === void 0) throw new NochaError("usage_required", "multiplayer.subscribe requires nocha.use(<declared usage id>)");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A multiplayer listener is required");\n if (typeof topic !== "string" || !topic) throw new NochaError("invalid_request", "A multiplayer topic is required");\n hub.listen();\n try {\n const unsubscribe3 = await hub.subscribe(topic, listener, { ...options, usageId: context.usageId });\n return async () => {\n try {\n await unsubscribe3();\n } finally {\n hub.reconcile();\n }\n };\n } catch (error) {\n hub.reconcile();\n throw error;\n }\n },\n async publish(topic, data, options = {}) {\n assertHostCapability("multiplayer");\n const { delivery, ...request2 } = options ?? {};\n if (delivery === "durable" && !(typeof request2.idempotencyKey === "string" && durableKey.test(request2.idempotencyKey))) {\n throw new NochaError("invalid_request", "A durable publication requires an idempotencyKey of 8 to 200 characters among A-Z a-z 0-9 . _ : -");\n }\n hub.track();\n const receipt2 = await context.invoke(multiplayerOperationDefinitions["publish"].capability, multiplayerOperationDefinitions["publish"].operation, { topic, data, delivery: delivery === "durable" ? "durable" : "ephemeral" }, request2);\n if (!isRecord(receipt2) || receipt2.accepted !== true || !isNonEmptyString(receipt2.eventId)) throw new NochaError("invalid_result", "Nocha returned an invalid publication receipt");\n return { accepted: true, eventId: receipt2.eventId };\n }\n });\n}\n\n// src/navigation-capture.ts\nvar locationKey = (location2) => `${location2.pathname}${location2.search}${location2.hash}`;\nfunction documentOrigin() {\n try {\n const origin = new URL(document.URL).origin;\n if (origin && origin !== "null") return origin;\n } catch {\n }\n return "";\n}\nfunction distributedFile(href, url) {\n const base2 = new URL(".", document.baseURI).pathname;\n if (base2 === "/") return false;\n const underBase = url.pathname.startsWith(base2) || `${url.pathname}/` === base2;\n const rootedOrFull = href.startsWith("/") || /^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(href);\n return underBase && rootedOrFull;\n}\nfunction logicalTarget(href, current4) {\n let url;\n try {\n url = new URL(href, document.baseURI);\n } catch {\n return void 0;\n }\n const own = documentOrigin();\n if (!own || url.protocol !== "http:" && url.protocol !== "https:" || url.origin !== own) return void 0;\n if (distributedFile(href, url)) return void 0;\n let source2 = href;\n if (/^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(href)) {\n const base2 = new URL(".", document.baseURI).pathname;\n source2 = `${url.pathname.startsWith(base2) ? url.pathname.slice(base2.length - 1) : url.pathname}${url.search}${url.hash}`;\n }\n try {\n return locationKey(normalizeExperienceLocation(source2, current4));\n } catch {\n return null;\n }\n}\nfunction internalLinkTarget(event, current4) {\n if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return void 0;\n const link = event.composedPath().find((node) => node instanceof Element && node.localName === "a" && node.hasAttribute("href"));\n if (!link) return void 0;\n const target = link.getAttribute("target");\n if (target && target !== "_self" || link.hasAttribute("download") || link.getAttribute("data-nocha-link") === "native" || (link.getAttribute("rel") ?? "").split(/\\s+/).includes("external")) return void 0;\n return logicalTarget(link.getAttribute("href").trim(), current4);\n}\nfunction bindHistory(bridge) {\n const history = window.history;\n const states = /* @__PURE__ */ new Map();\n let state3 = history.state;\n const target = (url) => {\n if (url === null || url === void 0) return void 0;\n const next = logicalTarget(String(url), bridge.current());\n if (typeof next !== "string") throw new NochaError("invalid_request", "Expected an internal experience location");\n return next;\n };\n const write2 = (replace) => (data, _unused, url) => {\n const next = target(url);\n state3 = data;\n states.set(next ?? locationKey(bridge.current()), data);\n if (next !== void 0) (replace ? bridge.replace : bridge.push)(next);\n };\n const own = {\n pushState: write2(false),\n replaceState: write2(true),\n back: () => bridge.back(),\n forward: () => {\n },\n go: (delta = 0) => {\n if (delta < 0) bridge.back();\n }\n };\n for (const [name, value] of Object.entries(own)) Object.defineProperty(history, name, { configurable: true, writable: true, value });\n Object.defineProperty(history, "state", { configurable: true, get: () => state3 });\n const address = (location2) => new URL(locationKey(location2), documentOrigin() || "https://experience.invalid").href;\n return {\n restore() {\n for (const name of [...Object.keys(own), "state"]) delete history[name];\n },\n changed(previous, next) {\n state3 = states.get(locationKey(next)) ?? null;\n window.dispatchEvent(new PopStateEvent("popstate", { state: state3 }));\n if (previous.pathname === next.pathname && previous.search === next.search && previous.hash !== next.hash) {\n window.dispatchEvent(new HashChangeEvent("hashchange", { oldURL: address(previous), newURL: address(next) }));\n }\n }\n };\n}\n\n// src/navigation.ts\nvar sameLocation = (a, b) => a?.pathname === b.pathname && a.search === b.search && a.hash === b.hash;\nfunction reportNavigationError(cause, options) {\n const error = isNochaError(cause) ? cause : new NochaError("navigation_unavailable", String(cause));\n if (typeof options?.onError === "function") notifyListener(options.onError, error);\n else warnOnce("navigation", error.message);\n}\nvar connectCeilingMs = 6e4;\nfunction createEmbeddedNavigation() {\n let current4 = { pathname: "/", search: "", hash: "" };\n const clicks = /* @__PURE__ */ new Map();\n let documentId;\n let revision2 = -1;\n let connected = false;\n let listening = false;\n let restoring = false;\n let canGoBack = false;\n let unavailable2 = false;\n const silent = /* @__PURE__ */ new Set();\n let historyBinding;\n const listeners2 = /* @__PURE__ */ new Set();\n const waiting = /* @__PURE__ */ new Map();\n let ready;\n let resolveReady;\n const connect2 = () => {\n if (ready) return ready;\n if (typeof window === "undefined" || window.parent === window) return Promise.reject(new NochaError("bridge_unavailable", "Navigation requires a Nocha experience frame"));\n const id = documentId ??= crypto.randomUUID();\n revision2 = -1;\n if (!listening) {\n window.addEventListener("message", onMessage);\n listening = true;\n }\n if (!restoring) {\n restoring = true;\n window.addEventListener("pageshow", (event) => {\n if (event.persisted) resynchronize();\n });\n }\n const announce2 = () => {\n if (!connected) postToHost({ protocol: NOCHA_NAVIGATION_PROTOCOL, type: "ready", documentId: id });\n };\n const started = Date.now();\n let deadline = started + capabilityDeadlines.navigation.connect;\n let loaded = typeof document === "undefined" || document.readyState === "complete";\n const timers = /* @__PURE__ */ new Set();\n const later = (delay, run3) => {\n const timer = setTimeout(() => {\n timers.delete(timer);\n run3();\n }, delay);\n timers.add(timer);\n };\n const onLoad = () => {\n loaded = true;\n deadline = Math.min(Math.max(deadline, Date.now() + 2e3), started + connectCeilingMs);\n later(50, announce2);\n later(250, announce2);\n };\n const pending3 = new Promise((resolve2, reject2) => {\n const finish = () => {\n for (const timer of timers) clearTimeout(timer);\n timers.clear();\n window.removeEventListener("load", onLoad);\n };\n const retry2 = (delay) => later(delay, () => {\n if (connected) return;\n const now = Date.now();\n if (loaded && now >= deadline || now >= started + connectCeilingMs) {\n finish();\n if (ready === pending3) ready = void 0;\n unavailable2 = true;\n reject2(new NochaError("navigation_unavailable", "This host does not support experience navigation"));\n return;\n }\n announce2();\n retry2(Math.min(2e3, delay * 2));\n });\n resolveReady = () => {\n finish();\n connected = true;\n unavailable2 = false;\n resolve2();\n };\n if (!loaded) window.addEventListener("load", onLoad, { once: true });\n retry2(100);\n });\n ready = pending3;\n announce2();\n return pending3;\n };\n const resynchronize = () => {\n if (!ready || !connected) return;\n connected = false;\n ready = void 0;\n resolveReady = void 0;\n void connect2().catch((error) => {\n for (const listener of errorListeners) reportNavigationError(error, listener);\n });\n };\n const errorListeners = /* @__PURE__ */ new Set();\n const onMessage = (event) => {\n if (!isFromHost(event)) return;\n const message2 = event.data;\n if (!message2 || message2.protocol !== NOCHA_NAVIGATION_PROTOCOL || message2.type !== "snapshot" || message2.documentId !== documentId || !Number.isSafeInteger(message2.revision) || message2.revision <= revision2 || !isExperienceLocation(message2.location) || typeof message2.canGoBack !== "boolean") return;\n revision2 = message2.revision;\n canGoBack = message2.canGoBack;\n const previous = current4;\n const changed = !sameLocation(current4, message2.location);\n current4 = Object.freeze({ ...message2.location });\n resolveReady?.();\n resolveReady = void 0;\n const quiet = message2.requestId !== void 0 && silent.delete(message2.requestId);\n if (changed) for (const listener of listeners2) listener(current4);\n if (changed && !quiet) {\n try {\n historyBinding?.changed(previous, current4);\n } catch (error) {\n reportNavigationError(error, void 0);\n }\n }\n if (message2.requestId) {\n const pending3 = waiting.get(message2.requestId);\n if (pending3) {\n waiting.delete(message2.requestId);\n clearTimeout(pending3.timer);\n pending3.resolve(current4);\n }\n }\n };\n const command = async (action, target, quiet = false) => {\n await connect2();\n const location2 = target === void 0 ? void 0 : normalizeExperienceLocation(target, current4);\n if (action === "navigate" && location2 && sameLocation(current4, location2)) return current4;\n const requestId = crypto.randomUUID();\n if (quiet) silent.add(requestId);\n return new Promise((resolve2, reject2) => {\n const timer = setTimeout(() => {\n waiting.delete(requestId);\n silent.delete(requestId);\n resynchronize();\n reject2(new NochaError("navigation_timed_out", "Navigation was not acknowledged"));\n }, capabilityDeadlines.navigation.command);\n waiting.set(requestId, { resolve: resolve2, reject: reject2, timer });\n postToHost({ protocol: NOCHA_NAVIGATION_PROTOCOL, type: "intent", documentId, requestId, action, ...location2 ? { location: location2 } : {} });\n });\n };\n return Object.freeze({\n get: async () => {\n await connect2();\n return current4;\n },\n navigate: (target) => command("navigate", target),\n replace: (target) => command("replace", target),\n back: () => command("back"),\n onChange(listener, options) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A navigation listener is required");\n let previous;\n const deliver = (location2) => {\n if (sameLocation(previous, location2)) return;\n previous = location2;\n notifyListener(listener, location2);\n };\n const errors = options ?? {};\n listeners2.add(deliver);\n errorListeners.add(errors);\n void connect2().then(\n () => {\n if (listeners2.has(deliver)) deliver(current4);\n },\n (error) => {\n if (listeners2.has(deliver)) reportNavigationError(error, errors);\n }\n );\n return () => {\n listeners2.delete(deliver);\n errorListeners.delete(errors);\n };\n },\n canGoBack: () => canGoBack,\n capture(options) {\n if (typeof document === "undefined") return () => {\n };\n const root = options?.root ?? document;\n let stopped = false;\n const stops = [];\n if (!clicks.has(root)) {\n const onClick = (event) => {\n const target = internalLinkTarget(event, current4);\n if (target === void 0) return;\n if (!connected && unavailable2) return;\n event.preventDefault();\n if (target === null) {\n warnOnce("navigation", "A link to a reserved reader address was ignored");\n return;\n }\n const anchor = target.startsWith(`${current4.pathname}${current4.search}#`) ? target.slice(target.indexOf("#") + 1) : void 0;\n command("navigate", target).then(\n () => {\n if (!anchor) return;\n let id = anchor;\n try {\n id = decodeURIComponent(anchor);\n } catch {\n }\n document.getElementById(id)?.scrollIntoView();\n },\n (error) => reportNavigationError(error, void 0)\n );\n };\n root.addEventListener("click", onClick);\n clicks.set(root, () => root.removeEventListener("click", onClick));\n stops.push(() => {\n clicks.get(root)?.();\n clicks.delete(root);\n });\n }\n if (options?.history && !historyBinding) {\n const fail = (error) => reportNavigationError(error, void 0);\n historyBinding = bindHistory({\n current: () => current4,\n push: (target) => {\n command("navigate", target, true).catch(fail);\n },\n replace: (target) => {\n command("replace", target, true).catch(fail);\n },\n back: () => {\n command("back").catch(fail);\n }\n });\n stops.push(() => {\n historyBinding?.restore();\n historyBinding = void 0;\n });\n }\n return () => {\n if (stopped) return;\n stopped = true;\n for (const stop of stops) stop();\n };\n }\n });\n}\nfunction createStandaloneNavigation() {\n let current4 = Object.freeze({ pathname: "/", search: "", hash: "" });\n let connected = false;\n const listeners2 = /* @__PURE__ */ new Set();\n const traversals = /* @__PURE__ */ new Set();\n const read4 = () => {\n const url = new URL(window.location.href);\n for (const key2 of [...url.searchParams.keys()]) if (key2.startsWith("__nocha_")) url.searchParams.delete(key2);\n return normalizeExperienceLocation({ pathname: url.pathname, search: url.search, hash: url.hash });\n };\n const update2 = () => {\n const next = read4();\n if (next.pathname !== current4.pathname || next.search !== current4.search || next.hash !== current4.hash) {\n current4 = Object.freeze(next);\n for (const listener of listeners2) notifyListener(listener, current4);\n }\n for (const complete of traversals) complete();\n };\n const connect2 = () => {\n if (typeof window === "undefined") throw new NochaError("navigation_unavailable", "Navigation requires a browser");\n if (connected) return;\n current4 = Object.freeze(read4());\n window.addEventListener("popstate", update2);\n window.addEventListener("hashchange", update2);\n connected = true;\n };\n const command = async (replace, target) => {\n connect2();\n const next = normalizeExperienceLocation(target, current4);\n if (!replace && next.pathname === current4.pathname && next.search === current4.search && next.hash === current4.hash) return current4;\n const url = new URL(`${next.pathname}${next.search}${next.hash}`, window.location.origin);\n if (replace) window.history.replaceState(window.history.state, "", url.href);\n else window.history.pushState(null, "", url.href);\n update2();\n return current4;\n };\n return Object.freeze({\n get: async () => {\n connect2();\n return current4;\n },\n navigate: (target) => command(false, target),\n replace: (target) => command(true, target),\n back: async () => {\n connect2();\n return new Promise((resolve2) => {\n const complete = () => {\n clearTimeout(timer);\n traversals.delete(complete);\n resolve2(current4);\n };\n const timer = setTimeout(complete, 1e3);\n traversals.add(complete);\n window.history.back();\n });\n },\n onChange(listener, options) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A navigation listener is required");\n try {\n connect2();\n } catch (error) {\n reportNavigationError(error, options);\n return () => {\n };\n }\n listeners2.add(listener);\n queueMicrotask(() => {\n if (listeners2.has(listener)) notifyListener(listener, current4);\n });\n return () => {\n listeners2.delete(listener);\n };\n },\n // history.length counts entries before this experience too: never a reliable answer.\n canGoBack: () => false,\n capture: () => () => {\n }\n });\n}\nvar selected;\nvar source = () => selected ??= getNochaMode() === "standalone" ? createStandaloneNavigation() : createEmbeddedNavigation();\nvar settled = (run3) => hostingPending() ? hostingReady().then(run3) : run3();\nvar navigation = Object.freeze({\n get: () => settled(() => source().get()),\n navigate: (target) => settled(() => source().navigate(target)),\n replace: (target) => settled(() => source().replace(target)),\n back: () => settled(() => source().back()),\n onChange: (listener, options) => {\n if (!hostingPending()) return source().onChange(listener, options);\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A navigation listener is required");\n let stop, active3 = true;\n void hostingReady().then(() => {\n if (active3) stop = source().onChange(listener, options);\n });\n return () => {\n active3 = false;\n stop?.();\n };\n },\n canGoBack: () => !hostingPending() && source().canGoBack(),\n capture: (options) => {\n if (!hostingPending()) return source().capture(options);\n let stop, active3 = true;\n void hostingReady().then(() => {\n if (active3) stop = source().capture(options);\n });\n return () => {\n active3 = false;\n stop?.();\n };\n }\n});\n\n// src/gamepad-target.ts\nvar selector2 = \'button,a[href],[role="button"],[role="tab"],select,input[type="button"],input[type="submit"]\';\nvar styleText = "[data-nocha-gamepad-target]{outline:2px solid CanvasText;outline-offset:2px}";\nvar current3;\nvar stickArmed = true;\nvar armed = { up: true, down: true, left: true, right: true, cross: true };\nfunction ensureStyle() {\n if (typeof document === "undefined" || document.querySelector("style[data-nocha-gamepad-target-style]")) return;\n const style2 = document.createElement("style");\n style2.setAttribute("data-nocha-gamepad-target-style", "");\n style2.textContent = styleText;\n document.head.append(style2);\n}\nfunction clearTarget() {\n current3?.removeAttribute(GAMEPAD_TARGET_ATTRIBUTE);\n current3 = void 0;\n}\nfunction show(element2) {\n if (current3 !== element2) {\n current3?.removeAttribute(GAMEPAD_TARGET_ATTRIBUTE);\n current3 = element2;\n element2.setAttribute(GAMEPAD_TARGET_ATTRIBUTE, "");\n }\n ensureStyle();\n}\nfunction visible(element2) {\n if (!element2.isConnected || element2.closest(\'[hidden],[inert],[aria-hidden="true"],[data-assistant-private]\')) return false;\n if (element2.matches(\':disabled,[aria-disabled="true"]\') || !element2.getClientRects().length) return false;\n const style2 = getComputedStyle(element2);\n return style2.visibility !== "hidden" && style2.display !== "none";\n}\nfunction targets2() {\n const root = document.body;\n if (!root) return [];\n const modal = root.querySelector(\'dialog[open],[role="dialog"][aria-modal="true"]\');\n const scope = modal ?? root;\n const found = [];\n for (const element2 of Array.from(scope.querySelectorAll(selector2))) {\n if (found.length >= 200) break;\n if (visible(element2)) found.push(element2);\n }\n return found;\n}\nfunction pressed(snapshot3, index) {\n for (const pad of snapshot3.pads) {\n if (!pad.connected) continue;\n const button = pad.buttons[index];\n if (!button) continue;\n if (button.pressed || button.value >= 0.5) return true;\n }\n return false;\n}\nfunction edge(name, active3) {\n if (!active3) {\n armed[name] = true;\n return false;\n }\n if (!armed[name]) return false;\n armed[name] = false;\n return true;\n}\nfunction stickAxis(snapshot3, index) {\n for (const pad of snapshot3.pads) {\n if (!pad.connected) continue;\n const value = pad.axes[index];\n if (typeof value === "number" && Number.isFinite(value)) return value;\n }\n return 0;\n}\nfunction step(list5, delta) {\n if (!list5.length) {\n clearTarget();\n return;\n }\n const at = current3 ? list5.indexOf(current3) : -1;\n const next = at < 0 ? delta > 0 ? 0 : list5.length - 1 : (at + delta + list5.length) % list5.length;\n const element2 = list5[next];\n if (element2) show(element2);\n}\nfunction syncGamepadTarget(snapshot3, claimed) {\n const connected = snapshot3.pads.some((pad) => pad.connected);\n if (claimed || !connected || typeof document === "undefined" || document.hidden) {\n clearTarget();\n stickArmed = true;\n armed.up = armed.down = armed.left = armed.right = armed.cross = true;\n return;\n }\n const list5 = targets2();\n if (current3 && !list5.includes(current3)) clearTarget();\n const x = stickAxis(snapshot3, 0);\n const y = stickAxis(snapshot3, 1);\n if (Math.abs(x) < 0.3 && Math.abs(y) < 0.3) stickArmed = true;\n const up = edge("up", pressed(snapshot3, GAMEPAD_BUTTON.up)) || stickArmed && y < -0.55;\n const down = edge("down", pressed(snapshot3, GAMEPAD_BUTTON.down)) || stickArmed && y > 0.55;\n const left = edge("left", pressed(snapshot3, GAMEPAD_BUTTON.left)) || stickArmed && x < -0.55;\n const right = edge("right", pressed(snapshot3, GAMEPAD_BUTTON.right)) || stickArmed && x > 0.55;\n if ((up || down || left || right) && (Math.abs(x) >= 0.55 || Math.abs(y) >= 0.55)) stickArmed = false;\n if (up && !down) step(list5, -1);\n else if (down && !up) step(list5, 1);\n else if (left && !right) step(list5, -1);\n else if (right && !left) step(list5, 1);\n if (edge("cross", pressed(snapshot3, GAMEPAD_BUTTON.cross))) current3?.click();\n}\n\n// src/gamepad.ts\nvar DUALSENSE_ID = /dualsense|054c.*(?:0ce6|0df2)/i;\nfunction cleanId(id) {\n let out = "";\n const source2 = id.length > GAMEPAD_ID_MAX_CHARS * 4 ? id.slice(0, GAMEPAD_ID_MAX_CHARS * 4) : id;\n for (const character of source2) {\n const code = character.charCodeAt(0);\n if (code < 32 || code === 127) continue;\n out += character;\n if (out.length >= GAMEPAD_ID_MAX_CHARS) break;\n }\n return out;\n}\nfunction axesOf(pad) {\n const axes = [];\n const count2 = Math.min(pad.axes.length, GAMEPAD_MAX_AXES);\n for (let index = 0; index < count2; index += 1) {\n const raw = pad.axes[index];\n const value = typeof raw === "number" && Number.isFinite(raw) ? raw : 0;\n axes.push(Math.max(-1, Math.min(1, value)));\n }\n return axes;\n}\nfunction buttonsOf(pad) {\n const buttons = [];\n const count2 = Math.min(pad.buttons.length, GAMEPAD_MAX_BUTTONS);\n for (let index = 0; index < count2; index += 1) {\n const button = pad.buttons[index];\n const raw = button && typeof button.value === "number" && Number.isFinite(button.value) ? button.value : 0;\n const value = Math.max(0, Math.min(1, raw));\n buttons.push({ pressed: typeof button?.pressed === "boolean" ? button.pressed : value >= 0.5, value });\n }\n return buttons;\n}\nfunction usable(pad) {\n if (!pad?.connected) return false;\n if (pad.mapping === "standard") return true;\n return DUALSENSE_ID.test(pad.id) && pad.axes.length >= 4 && pad.buttons.length >= 12;\n}\nfunction readLive() {\n if (typeof navigator === "undefined" || typeof navigator.getGamepads !== "function") return [];\n let list5;\n try {\n list5 = Array.from(navigator.getGamepads());\n } catch {\n return [];\n }\n const pads = [];\n for (const pad of list5) {\n if (!usable(pad)) continue;\n pads.push({\n index: pad.index,\n id: cleanId(String(pad.id ?? "")),\n mapping: pad.mapping === "standard" ? "standard" : "",\n axes: axesOf(pad),\n buttons: buttonsOf(pad)\n });\n }\n return pads;\n}\nfunction padFrom(slot, live) {\n return Object.freeze({\n slot: slot.slot,\n index: slot.connected && live ? live.index : -1,\n id: slot.id,\n mapping: live?.mapping ?? "",\n connected: slot.connected,\n axes: Object.freeze([...live?.axes ?? []]),\n buttons: Object.freeze((live?.buttons ?? []).map((button) => Object.freeze({ ...button })))\n });\n}\nfunction createGamepad() {\n const slots = [];\n const held = /* @__PURE__ */ new Set();\n const subscribers = /* @__PURE__ */ new Set();\n let lastSnapshot = "";\n let posted = "";\n let frame = 0;\n function summary() {\n const ids2 = slots.filter((slot) => slot.connected).map((slot) => slot.id);\n return { count: ids2.length, ids: ids2, claimed: held.size > 0 };\n }\n function publish() {\n if (getNochaMode() !== "embedded") return;\n const payload = summary();\n const encoded = JSON.stringify(payload);\n if (encoded === posted) return;\n posted = encoded;\n try {\n postToHost({ protocol: NOCHA_BRIDGE_PROTOCOL, type: "event", event: { type: GAMEPAD_SUMMARY_EVENT, payload } });\n } catch {\n posted = "";\n }\n }\n function sample() {\n const live = readLive();\n const pending3 = live.slice();\n for (const slot of slots) {\n if (!slot.connected) continue;\n const at = pending3.findIndex((pad) => pad.index === slot.index && pad.id === slot.id);\n if (at < 0) slot.connected = false;\n else pending3.splice(at, 1);\n }\n for (const pad of pending3) {\n const remembered = slots.find((slot) => !slot.connected && slot.id === pad.id);\n if (remembered) {\n remembered.connected = true;\n remembered.index = pad.index;\n continue;\n }\n if (slots.length >= GAMEPAD_MAX_SLOTS) continue;\n slots.push({ slot: slots.length, id: pad.id, index: pad.index, connected: true });\n }\n const pads = slots.map((slot) => padFrom(slot, slot.connected ? live.find((pad) => pad.index === slot.index && pad.id === slot.id) : void 0));\n return Object.freeze({ pads: Object.freeze(pads) });\n }\n function cancelFrame() {\n if (!frame || typeof cancelAnimationFrame !== "function") return;\n cancelAnimationFrame(frame);\n frame = 0;\n }\n function targeting() {\n return held.size === 0 && slots.some((slot) => slot.connected);\n }\n function ensureFrame() {\n if (frame || typeof requestAnimationFrame !== "function") return;\n if (typeof document !== "undefined" && document.hidden) return;\n if (subscribers.size === 0 && !targeting()) return;\n frame = requestAnimationFrame(() => {\n frame = 0;\n if (subscribers.size === 0 && !targeting()) return;\n poll();\n ensureFrame();\n });\n }\n function poll() {\n const snapshot3 = sample();\n const encoded = JSON.stringify(snapshot3);\n publish();\n syncGamepadTarget(snapshot3, held.size > 0);\n if (encoded !== lastSnapshot) {\n lastSnapshot = encoded;\n for (const listener of [...subscribers]) notifyListener(listener, snapshot3);\n }\n ensureFrame();\n return snapshot3;\n }\n if (typeof window !== "undefined") {\n const onGamepad = () => {\n poll();\n ensureFrame();\n };\n window.addEventListener("gamepadconnected", onGamepad);\n window.addEventListener("gamepaddisconnected", onGamepad);\n document.addEventListener("visibilitychange", () => {\n if (document.hidden) cancelFrame();\n else {\n poll();\n ensureFrame();\n }\n });\n poll();\n }\n return Object.freeze({\n poll,\n subscribe(listener) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A gamepad listener is required");\n subscribers.add(listener);\n const before = lastSnapshot;\n const snapshot3 = poll();\n if (before === lastSnapshot) notifyListener(listener, snapshot3);\n ensureFrame();\n return () => {\n subscribers.delete(listener);\n if (subscribers.size === 0 && !targeting()) cancelFrame();\n };\n },\n claim(slot) {\n if (typeof slot !== "number" || !Number.isSafeInteger(slot) || slot < 0) throw new NochaError("invalid_request", "gamepad.claim() requires a slot number.");\n if (!slots.some((item) => item.slot === slot)) throw new NochaError("invalid_request", "This gamepad slot is not connected yet.");\n if (held.has(slot)) throw new NochaError("invalid_request", "This gamepad slot is already claimed.");\n held.add(slot);\n publish();\n syncGamepadTarget(sample(), true);\n if (subscribers.size === 0) cancelFrame();\n let released = false;\n return Object.freeze({\n slot,\n read() {\n const snapshot3 = poll();\n return snapshot3.pads.find((pad) => pad.slot === slot) ?? padFrom({ slot, id: "", index: -1, connected: false }, void 0);\n },\n release() {\n if (released) return;\n released = true;\n held.delete(slot);\n publish();\n syncGamepadTarget(sample(), held.size > 0);\n ensureFrame();\n }\n });\n },\n claimed() {\n return held.size > 0;\n }\n });\n}\n\n// src/network.ts\nfunction isResponse(value) {\n return isRecord(value) && typeof value.status === "number" && Number.isInteger(value.status) && value.status >= 100 && value.status <= 599 && isString(value.contentType) && isString(value.body);\n}\nfunction isAsset(value) {\n return isRecord(value) && isString(value.mimeType) && isBase64(value.base64) && typeof value.sha256 === "string" && /^[0-9a-f]{64}$/.test(value.sha256);\n}\nfunction createNetwork(context) {\n return Object.freeze({\n async request(input4, options) {\n const value = await context.invoke(networkOperationDefinitions["request"].capability, networkOperationDefinitions["request"].operation, input4, options);\n if (!isResponse(value)) throw new NochaError("invalid_result", "Nocha returned an invalid network response");\n return value;\n },\n async asset(input4, options) {\n const value = await context.invoke(networkOperationDefinitions["asset"].capability, networkOperationDefinitions["asset"].operation, input4, options);\n if (!isAsset(value)) throw new NochaError("invalid_result", "Nocha returned an invalid network asset");\n return value;\n }\n });\n}\n\n// src/notifications.ts\nvar isResult2 = (value) => isRecord(value) && ["queued", "suppressed", "duplicate"].includes(String(value.status)) && (value.reason === void 0 || isString(value.reason));\nvar isScheduleResult = (value) => isRecord(value) && ["scheduled", "replaced", "suppressed"].includes(String(value.status)) && (value.reason === void 0 || isString(value.reason));\nvar isCancelResult = (value) => isRecord(value) && (value.status === "cancelled" || value.status === "absent");\nvar isInstant = (value) => isString(value) && Number.isFinite(Date.parse(value));\nvar isScheduledItem = (value) => isRecord(value) && isString(value.id) && isInstant(value.at) && isString(value.title) && (value.body === void 0 || isString(value.body)) && (value.destination === void 0 || isExperienceLocation(value.destination));\nvar isReceipt = (value) => isRecord(value) && isString(value.id) && isInstant(value.at) && (value.status === "queued" || value.status === "suppressed") && (value.reason === void 0 || isString(value.reason));\nfunction createNotifications(context) {\n const call2 = notificationsOperationDefinitions;\n return Object.freeze({\n async send(input4, options) {\n const payload = input4?.destination === void 0 ? input4 : { ...input4, destination: normalizeExperienceLocation(input4.destination) };\n const value = await context.invoke(notificationsOperationDefinitions["send"].capability, notificationsOperationDefinitions["send"].operation, payload, options);\n if (!isResult2(value)) throw new NochaError("invalid_result", "Nocha returned an invalid notification result");\n return value;\n },\n async schedule(input4, options) {\n const payload = input4?.destination === void 0 ? input4 : { ...input4, destination: normalizeExperienceLocation(input4.destination) };\n const value = await context.invoke(call2.schedule.capability, call2.schedule.operation, payload, options);\n if (!isScheduleResult(value)) throw new NochaError("invalid_result", "Nocha returned an invalid notification schedule result");\n return value;\n },\n async cancel(input4, options) {\n const value = await context.invoke(call2.cancel.capability, call2.cancel.operation, input4, options);\n if (!isCancelResult(value)) throw new NochaError("invalid_result", "Nocha returned an invalid notification cancellation");\n return value;\n },\n async scheduled(options) {\n const value = await context.invoke(call2.list.capability, call2.list.operation, {}, options);\n if (!isRecord(value) || !isArrayOf(value.items, isScheduledItem) || !isArrayOf(value.receipts, isReceipt)) {\n throw new NochaError("invalid_result", "Nocha returned an invalid list of scheduled notifications");\n }\n return { items: value.items, receipts: value.receipts };\n }\n });\n}\n\n// src/places.ts\nvar isPlace = (value) => isRecord(value) && isString(value.id) && isString(value.title) && isFiniteNumber(value.latitude) && isFiniteNumber(value.longitude) && isString(value.link) && isArrayOf(value.keywords, isString) && isString(value.createdAt) && isString(value.updatedAt) && (value.radiusMeters === void 0 || isFiniteNumber(value.radiusMeters));\nfunction createPlaces(context) {\n const call2 = placesOperationDefinitions;\n return Object.freeze({\n async list(options) {\n const value = await context.invoke(call2.list.capability, call2.list.operation, {}, options);\n if (!isRecord(value) || !isArrayOf(value.places, isPlace)) throw new NochaError("invalid_result", "Nocha returned an invalid place list");\n return { places: value.places };\n },\n async publish(place, options) {\n const value = await context.invoke(call2.publish.capability, call2.publish.operation, place, options);\n if (!isRecord(value) || !isPlace(value.place)) throw new NochaError("invalid_result", "Nocha returned an invalid place");\n return { place: value.place };\n },\n async remove(id, options) {\n const value = await context.invoke(call2.remove.capability, call2.remove.operation, { id }, options);\n if (!isRecord(value) || !isBoolean(value.removed)) throw new NochaError("invalid_result", "Nocha returned an invalid place removal");\n return { removed: value.removed };\n }\n });\n}\n\n// src/excerpts.ts\nvar isExcerpt = (value) => isRecord(value) && isString(value.id) && isString(value.title) && isString(value.link) && isArrayOf(value.keywords, isString) && (value.origin === "manifest" || value.origin === "experience") && isString(value.createdAt) && isString(value.updatedAt) && isString(value.publishedAt) && (value.language === void 0 || isString(value.language)) && (value.durationSeconds === void 0 || isFiniteNumber(value.durationSeconds));\nfunction createExcerpts(context) {\n const call2 = excerptsOperationDefinitions;\n return Object.freeze({\n async list(options) {\n const value = await context.invoke(call2.list.capability, call2.list.operation, {}, options);\n if (!isRecord(value) || !isArrayOf(value.excerpts, isExcerpt) || !isBoolean(value.canPublish)) throw new NochaError("invalid_result", "Nocha returned an invalid excerpt list");\n return { excerpts: value.excerpts, canPublish: value.canPublish };\n },\n async publish(excerpt, options) {\n const value = await context.invoke(call2.publish.capability, call2.publish.operation, excerpt, options);\n if (!isRecord(value) || !isExcerpt(value.excerpt)) throw new NochaError("invalid_result", "Nocha returned an invalid excerpt");\n return { excerpt: value.excerpt };\n },\n async remove(id, options) {\n const value = await context.invoke(call2.remove.capability, call2.remove.operation, { id }, options);\n if (!isRecord(value) || !isBoolean(value.removed)) throw new NochaError("invalid_result", "Nocha returned an invalid excerpt removal");\n return { removed: value.removed };\n }\n });\n}\n\n// src/profiles.ts\nvar isProfile = (value) => isRecord(value) && isString(value.participant) && isString(value.handle) && isString(value.displayName) && isBoolean(value.verified) && (value.avatar === null || isString(value.avatar) && value.avatar.startsWith("data:image/"));\nfunction createProfiles(context) {\n const call2 = profilesOperationDefinitions;\n return Object.freeze({\n async me(options) {\n const value = await context.invoke(call2.me.capability, call2.me.operation, {}, options);\n if (!isRecord(value) || !(value.profile === null || isProfile(value.profile))) throw new NochaError("invalid_result", "Nocha returned an invalid profile");\n return { profile: value.profile };\n },\n async get(input4, options) {\n const participants = Array.isArray(input4?.participants) ? input4.participants : [];\n if (!participants.length || participants.length > PROFILES_PARTICIPANTS_MAX || new Set(participants).size !== participants.length || participants.some((participant) => !isString(participant) || !PROFILE_PARTICIPANT_PATTERN.test(participant)))\n throw new NochaError("invalid_request", `profiles.get takes 1 to ${PROFILES_PARTICIPANTS_MAX} unique participant pseudonyms`);\n if (input4.size !== void 0 && !PROFILE_AVATAR_SIZES.includes(input4.size))\n throw new NochaError("invalid_request", "profiles.get size is small or medium");\n const value = await context.invoke(\n call2.get.capability,\n call2.get.operation,\n { participants: [...participants], ...input4.size ? { size: input4.size } : {} },\n options\n );\n if (!isRecord(value) || !isRecord(value.profiles) || participants.some((participant) => {\n const profile = value.profiles[participant];\n return !(profile === null || isProfile(profile));\n })) throw new NochaError("invalid_result", "Nocha returned invalid profiles");\n const profiles2 = value.profiles;\n return { profiles: Object.fromEntries(participants.map((participant) => [participant, profiles2[participant] ?? null])) };\n }\n });\n}\n\n// src/inbox.ts\nvar sources = /* @__PURE__ */ new Set(["api", "email", "schedule", "manual", "test"]);\nvar isTrigger = (value) => isRecord(value) && isNonEmptyString(value.id) && isString(value.slug) && isString(value.name);\nvar isEmail = (value) => isRecord(value) && isString(value.from) && isArrayOf(value.to, isString) && isArrayOf(value.cc, isString) && isString(value.subject) && Array.isArray(value.attachments) && isBoolean(value.authenticated);\nvar isEvent = (value) => isRecord(value) && isNonEmptyString(value.id) && sources.has(String(value.source)) && isNullable(value.trigger, isTrigger) && isNullable(value.task, isString) && Object.hasOwn(value, "payload") && isNullable(value.email, isEmail) && (value.status === "pending" || value.status === "acked") && isString(value.createdAt);\nvar isPage2 = (value) => isRecord(value) && isArrayOf(value.items, isEvent) && isNullable(value.next, isNonEmptyString);\nvar isAck = (value) => isRecord(value) && isCount(value.acked);\nvar minimumIntervalMs = 5e3;\nvar defaultIntervalMs = 15e3;\nvar pageSize = 50;\nvar rememberedIds = 1e3;\nfunction createInbox(context) {\n return Object.freeze({\n async list(input4, options) {\n const value = await context.invoke(inboxOperationDefinitions["list"].capability, inboxOperationDefinitions["list"].operation, input4 ?? {}, options);\n if (!isPage2(value)) throw new NochaError("invalid_result", "Nocha returned an invalid inbox page");\n return value;\n },\n async ack(input4, options) {\n const value = await context.invoke(inboxOperationDefinitions["ack"].capability, inboxOperationDefinitions["ack"].operation, input4, options);\n if (!isAck(value)) throw new NochaError("invalid_result", "Nocha returned an invalid inbox acknowledgement");\n return value;\n },\n watch(listener, options) {\n assertHostCapability("inbox");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "An inbox listener is required");\n const { onError, intervalMs = defaultIntervalMs, signal } = options ?? {};\n if (typeof intervalMs !== "number" || !Number.isFinite(intervalMs) || intervalMs < minimumIntervalMs) {\n throw new NochaError("invalid_request", `inbox.watch polls every ${minimumIntervalMs} ms at least`);\n }\n const fail = (error) => {\n if (typeof onError === "function") notifyListener(onError, error);\n };\n if (context.usageId === void 0) {\n fail(new NochaError("usage_required", "inbox.watch requires nocha.use(<declared usage id>)"));\n return () => {\n };\n }\n let active3 = true;\n const controller = new AbortController();\n let timer;\n let after;\n let attempt = 0;\n const delivered = [];\n const seen = /* @__PURE__ */ new Set();\n const dispose = () => {\n active3 = false;\n controller.abort();\n if (timer !== void 0) clearTimeout(timer);\n signal?.removeEventListener("abort", dispose);\n };\n const later = (delayMs) => {\n if (active3) timer = setTimeout(() => {\n void poll();\n }, delayMs);\n };\n const poll = async () => {\n timer = void 0;\n try {\n const value = await context.invoke(\n inboxOperationDefinitions["list"].capability,\n inboxOperationDefinitions["list"].operation,\n { ...after === void 0 ? {} : { after }, limit: pageSize },\n { signal: controller.signal }\n );\n if (!active3) return;\n if (!isPage2(value)) throw new NochaError("invalid_result", "Nocha returned an invalid inbox page");\n const fresh2 = value.items.filter((event) => !seen.has(event.id));\n for (const event of fresh2) {\n seen.add(event.id);\n delivered.push(event.id);\n }\n while (delivered.length > rememberedIds) seen.delete(delivered.shift());\n after = value.items.at(-1)?.id ?? after;\n attempt = 0;\n if (fresh2.length) notifyListener(listener, fresh2);\n later(value.next ? minimumIntervalMs : intervalMs);\n } catch (cause) {\n if (!active3) return;\n const error = isNochaError(cause) ? cause : new NochaError("invocation_failed", String(cause));\n const delay = retryDelayMs(error, attempt);\n if (delay === void 0) {\n dispose();\n if (error.code !== "aborted") fail(error);\n return;\n }\n attempt += 1;\n later(Math.max(delay, minimumIntervalMs));\n }\n };\n if (signal?.aborted) {\n dispose();\n return dispose;\n }\n signal?.addEventListener("abort", dispose, { once: true });\n void poll();\n return dispose;\n }\n });\n}\n\n// src/search-results.ts\nvar objectId = (value) => typeof value === "string" && /^[A-Za-z0-9._:-]{1,64}$/.test(value);\nvar geo = (value) => isRecord(value) && isFiniteNumber(value.lat) && isFiniteNumber(value.lng);\nvar bands = /* @__PURE__ */ new Set([1, 2, 5, 10, 25, 50, 100]);\nvar distance = (value) => isRecord(value) && (bands.has(value.withinKm) || value.beyondKm === 100 || isFiniteNumber(value.meters) && value.meters >= 0);\nvar reason = (value) => isRecord(value) && (value.kind === "shared" && isString(value.attribute) && isArrayOf(value.values, isString) || value.kind === "near" && isFiniteNumber(value.withinKm) || (value.kind === "recent" || value.kind === "popular") && isString(value.attribute) || value.kind === "text");\nvar range = (value) => Array.isArray(value) && value.length === 2 && value.every(isCount);\nvar facetValue = (value) => isRecord(value) && isString(value.value) && isCount(value.count);\nvar optional = (value, check2) => value === void 0 || check2(value);\nfunction isSearchHit(value) {\n return isRecord(value) && objectId(value.objectID) && isBoolean(value.mine) && isRecord(value.attributes) && isFiniteNumber(value.score) && isString(value.updatedAt) && optional(value.distance, distance) && optional(value.geo, geo) && optional(value.reasons, (item) => isArrayOf(item, reason)) && optional(value.highlights, (item) => isRecord(item) && Object.values(item).every((ranges) => isArrayOf(ranges, range))) && optional(value.mutual, (item) => isArrayOf(item, isString));\n}\nfunction isSearchPage(value) {\n return isRecord(value) && isArrayOf(value.hits, isSearchHit) && isNullable(value.nextCursor, isNonEmptyString) && isBoolean(value.exhaustive) && isRecord(value.total) && isCount(value.total.atLeast) && optional(value.facets, (facets) => isRecord(facets) && Object.values(facets).every((values) => isArrayOf(values, facetValue)));\n}\nfunction isOwnRecord(value) {\n return isRecord(value) && objectId(value.objectID) && isCount(value.revision) && value.revision >= 1 && (value.state === "visible" || value.state === "hidden" || value.state === "invalid") && isRecord(value.attributes) && isNullable(value.locatedAt, isString) && optional(value.geo, geo) && isString(value.createdAt) && isString(value.updatedAt);\n}\nvar isSearchMine = (value) => isRecord(value) && isArrayOf(value.records, isOwnRecord);\nvar isSearchReceipt = (value, expected) => isRecord(value) && objectId(value.objectID) && (expected === void 0 || value.objectID === expected) && isCount(value.revision) && value.revision >= 1;\nvar isSearchVisibility = (value, expected, visible2) => isRecord(value) && objectId(value.objectID) && (expected === void 0 || value.objectID === expected) && value.visible === visible2;\nvar isSearchRemoved = (value) => isRecord(value) && isBoolean(value.removed);\nvar isSearchGet = (value, expected) => value === null || isSearchHit(value) && value.objectID === expected;\n\n// src/search.ts\nvar indexName = (value) => typeof value === "string" && /^[a-z][a-z0-9_-]{0,39}$/.test(value);\nfunction input(value) {\n return isRecord(value) ? value : {};\n}\nasync function validated(request2, check2, what) {\n const value = await request2;\n if (!check2(value)) throw new NochaError("invalid_result", `Nocha returned an invalid search ${what}`);\n return value;\n}\nfunction createSearch(context) {\n return Object.freeze({\n index(name) {\n if (!indexName(name)) throw new NochaError("invalid_request", "search.index requires a declared index name");\n const index = name;\n return Object.freeze({\n save: (value, options) => validated(context.invoke(\n searchOperationDefinitions.save.capability,\n searchOperationDefinitions.save.operation,\n { ...value, index },\n options\n ), (result2) => isSearchReceipt(result2, input(value).objectID), "write receipt"),\n patch: (value, options) => validated(context.invoke(\n searchOperationDefinitions.patch.capability,\n searchOperationDefinitions.patch.operation,\n { ...value, index },\n options\n ), (result2) => isSearchReceipt(result2, input(value).objectID), "write receipt"),\n remove: (value, options) => validated(context.invoke(\n searchOperationDefinitions.remove.capability,\n searchOperationDefinitions.remove.operation,\n { ...value, index },\n options\n ), isSearchRemoved, "removal receipt"),\n setVisible: (value, options) => validated(context.invoke(\n searchOperationDefinitions.visibility.capability,\n searchOperationDefinitions.visibility.operation,\n { ...value, index },\n options\n ), (result2) => isSearchVisibility(result2, input(value).objectID, input(value).visible), "visibility"),\n locate: (value, options) => validated(context.invoke(\n searchOperationDefinitions.locate.capability,\n searchOperationDefinitions.locate.operation,\n { ...value, index },\n options\n ), (result2) => isRecord(result2) && result2.located === true && isString(result2.nextChangeAt), "location receipt"),\n mine: (options) => validated(context.invoke(\n searchOperationDefinitions.mine.capability,\n searchOperationDefinitions.mine.operation,\n { index },\n options\n ), isSearchMine, "record list"),\n query: (value, options) => validated(context.invoke(\n searchOperationDefinitions.query.capability,\n searchOperationDefinitions.query.operation,\n { ...value, index },\n options\n ), isSearchPage, "page"),\n get: (value, options) => validated(context.invoke(\n searchOperationDefinitions.get.capability,\n searchOperationDefinitions.get.operation,\n { ...value, index },\n options\n ), (result2) => isSearchGet(result2, input(value).objectID), "record"),\n similar: (value, options) => validated(context.invoke(\n searchOperationDefinitions.similar.capability,\n searchOperationDefinitions.similar.operation,\n { ...value, index },\n options\n ), isSearchPage, "page"),\n forMe: (value, options) => validated(context.invoke(\n searchOperationDefinitions.forMe.capability,\n searchOperationDefinitions.forMe.operation,\n { ...value, index },\n options\n ), isSearchPage, "page"),\n mark: (value, options) => validated(context.invoke(\n searchOperationDefinitions.mark.capability,\n searchOperationDefinitions.mark.operation,\n { ...value, index },\n options\n ), (result2) => isRecord(result2) && result2.marked === true && isBoolean(result2.mutual), "mark receipt"),\n unmark: (value, options) => validated(context.invoke(\n searchOperationDefinitions.unmark.capability,\n searchOperationDefinitions.unmark.operation,\n { ...value, index },\n options\n ), isSearchRemoved, "mark removal"),\n marks: (value, options) => validated(context.invoke(\n searchOperationDefinitions.marks.capability,\n searchOperationDefinitions.marks.operation,\n { ...value, index },\n options\n ), isSearchPage, "page"),\n block: (value, options) => validated(context.invoke(\n searchOperationDefinitions.block.capability,\n searchOperationDefinitions.block.operation,\n { ...value, index },\n options\n ), (result2) => isRecord(result2) && result2.blocked === true, "block receipt"),\n unblock: (value, options) => validated(context.invoke(\n searchOperationDefinitions.unblock.capability,\n searchOperationDefinitions.unblock.operation,\n { ...value, index },\n options\n ), (result2) => isRecord(result2) && result2.blocked === false, "block removal")\n });\n }\n });\n}\n\n// src/machine-streams.ts\nvar PENDING_OUTPUT_BYTES = 1048576;\nvar PENDING_EVENTS = 256;\nvar U32 = 4294967295;\nvar isDimension2 = (value) => Number.isInteger(value) && value >= 1 && value <= 1e3;\nvar isSize = (value) => isRecord(value) && isDimension2(value.cols) && isDimension2(value.rows);\nvar isRole = (value) => value === "controller" || value === "observer";\nvar isSeq = (value) => isCount(value) && value <= U32;\nvar isSession = (value) => isRecord(value) && isString(value.id) && isString(value.title) && isNullable(value.cwd, isString) && isString(value.createdAt) && isCount(value.viewers);\nvar isMachineError = (value) => machineErrorCodes.includes(value);\nvar isClosed = (value) => (isMachineError(value.code) || value.code === "ended" || value.code === "closed" || machineStreamIdentityCodes.includes(value.code)) && (value.message === void 0 || isString(value.message));\nfunction notify(listeners2, ...args) {\n for (const listener of [...listeners2]) {\n try {\n listener(...args);\n } catch (error) {\n setTimeout(() => {\n throw error;\n });\n }\n }\n}\nfunction subscribe3(listeners2, listener, first) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A listener must be a function");\n listeners2.add(listener);\n if (listeners2.size === 1) queueMicrotask(first);\n return () => {\n listeners2.delete(listener);\n };\n}\nfunction closedEvent(value) {\n return {\n t: "closed",\n code: value.code,\n ...isString(value.message) ? { message: value.message } : {},\n retryable: value.retryable === true\n };\n}\nfunction reconnectingEvent(value) {\n if (!isCount(value.attempt) || !isCount(value.retryAfterMs)) return null;\n return { t: "reconnecting", attempt: value.attempt, retryAfterMs: value.retryAfterMs, ...isMachineError(value.reason) ? { reason: value.reason } : {} };\n}\nfunction latest(listeners2, listener, version, current4) {\n const unsubscribe3 = subscribe3(listeners2, listener, () => {\n });\n const seen = version();\n queueMicrotask(() => {\n const value = current4();\n if (value && version() === seen && listeners2.has(listener)) notify([listener], value);\n });\n return unsubscribe3;\n}\nfunction bounded(name, value, check2) {\n if (!check2(value)) throw new NochaError("invalid_request", `Invalid ${name}`);\n}\nfunction terminalStream(port, manualAck) {\n let role = null;\n let size = null;\n let closed = false;\n const outputs = /* @__PURE__ */ new Set();\n const events = /* @__PURE__ */ new Set();\n let pendingOutputs = [];\n let pendingBytes = 0;\n let pendingEvents = [];\n let ackSeq = 0;\n let ackScheduled = false;\n const post = (message2) => {\n if (closed) return;\n try {\n port.postMessage(message2);\n } catch {\n }\n };\n const acknowledge = (seq) => {\n if (seq <= 0) return;\n ackSeq = seq;\n if (ackScheduled) return;\n ackScheduled = true;\n queueMicrotask(() => {\n ackScheduled = false;\n post({ t: "ack", seq: ackSeq });\n });\n };\n const emit = (event) => {\n if (!pendingEvents) {\n notify(events, event);\n return;\n }\n pendingEvents.push(event);\n if (pendingEvents.length > PENDING_EVENTS) pendingEvents.shift();\n };\n const output = (data, meta2) => {\n if (!pendingOutputs) {\n notify(outputs, data, meta2);\n return;\n }\n pendingOutputs.push([data, meta2]);\n pendingBytes += data.byteLength;\n while (pendingBytes > PENDING_OUTPUT_BYTES && pendingOutputs.length > 1) pendingBytes -= pendingOutputs.shift()[0].byteLength;\n };\n const finish = (event) => {\n if (closed) return;\n closed = true;\n port.onmessage = null;\n port.close();\n emit(event);\n };\n port.onmessage = (event) => {\n const message2 = event.data;\n if (closed || !isRecord(message2)) return;\n switch (message2.t) {\n case "output": {\n if (!(message2.data instanceof ArrayBuffer) || !isSeq(message2.stream) || !isSeq(message2.seq)) return;\n output(new Uint8Array(message2.data), { stream: message2.stream, seq: message2.seq, replay: message2.replay === true });\n if (!manualAck) acknowledge(message2.seq);\n return;\n }\n case "opened":\n if (!isSeq(message2.stream) || !isBoolean(message2.reset) || !isRole(message2.role) || !isSize(message2.size) || !isBoolean(message2.owner)) return;\n role = message2.role;\n size = { cols: message2.size.cols, rows: message2.size.rows };\n emit({ t: "opened", stream: message2.stream, reset: message2.reset, role, size: { ...size }, owner: message2.owner });\n return;\n case "replayComplete":\n if (!isSeq(message2.stream) || !isSeq(message2.seq) || !isCount(message2.historyLines) || !isBoolean(message2.hasMoreHistory)) return;\n emit({ t: "replayComplete", stream: message2.stream, seq: message2.seq, historyLines: message2.historyLines, hasMoreHistory: message2.hasMoreHistory });\n if (!manualAck) acknowledge(message2.seq);\n return;\n case "size":\n if (!isDimension2(message2.cols) || !isDimension2(message2.rows) || !isBoolean(message2.owner)) return;\n size = { cols: message2.cols, rows: message2.rows };\n emit({ t: "size", cols: message2.cols, rows: message2.rows, owner: message2.owner });\n return;\n case "presence":\n if (!isArrayOf(message2.viewers, (viewer) => isRecord(viewer) && isString(viewer.id) && isString(viewer.name))) return;\n emit({ t: "presence", viewers: message2.viewers.map((viewer) => ({ id: viewer.id, name: viewer.name })) });\n return;\n case "notice":\n if (message2.code !== "locked" && message2.code !== "input_overflow") return;\n emit({ t: "notice", code: message2.code, ...isCount(message2.droppedBytes) ? { droppedBytes: message2.droppedBytes } : {} });\n return;\n case "reconnecting": {\n const reconnecting = reconnectingEvent(message2);\n if (reconnecting) emit(reconnecting);\n return;\n }\n case "closed":\n if (isClosed(message2)) finish(closedEvent(message2));\n return;\n }\n };\n return Object.freeze({\n get role() {\n return role;\n },\n get size() {\n return size ? { ...size } : null;\n },\n get closed() {\n return closed;\n },\n onOutput: (listener) => subscribe3(outputs, listener, () => {\n const queued = pendingOutputs ?? [];\n pendingOutputs = null;\n pendingBytes = 0;\n for (const [data, meta2] of queued) notify(outputs, data, meta2);\n }),\n onEvent: (listener) => subscribe3(events, listener, () => {\n const queued = pendingEvents ?? [];\n pendingEvents = null;\n for (const event of queued) notify(events, event);\n }),\n // The host drops input only during a reset\'s snapshot: filtering xterm\'s answers to a gap replay is the experience\'s.\n write: (text6) => {\n if (typeof text6 !== "string") throw new NochaError("invalid_request", "Terminal input must be a string");\n if (text6) post({ t: "input", data: text6 });\n },\n resize: (cols, rows) => {\n bounded("terminal size", { cols, rows }, isSize);\n post({ t: "resize", cols, rows });\n },\n ack: (seq) => {\n bounded("acknowledged seq", seq, isSeq);\n if (manualAck && seq > 0) post({ t: "ack", seq });\n },\n setVisible: (visible2) => {\n bounded("visibility", visible2, isBoolean);\n post({ t: "visibility", visible: visible2 });\n },\n history: (lines) => {\n bounded("history length", lines, (value) => Number.isInteger(value) && value >= 1e4 && value <= 5e4);\n post({ t: "history", lines });\n },\n scroll: (lines) => {\n bounded("scroll distance", lines, (value) => Number.isInteger(value) && value !== 0 && Math.abs(value) <= 1e3);\n post({ t: "scroll", lines });\n },\n close: () => {\n if (closed) return;\n post({ t: "close" });\n finish({ t: "closed", code: "closed", retryable: false });\n }\n });\n}\nfunction watchStream(port) {\n let machine2 = null;\n let inventory = null;\n let closed = false;\n const machines = /* @__PURE__ */ new Set();\n const inventories = /* @__PURE__ */ new Set();\n const events = /* @__PURE__ */ new Set();\n let pendingEvents = [];\n let version = 0;\n const emit = (event) => {\n if (!pendingEvents) {\n notify(events, event);\n return;\n }\n pendingEvents.push(event);\n if (pendingEvents.length > PENDING_EVENTS) pendingEvents.shift();\n };\n const finish = (event) => {\n if (closed) return;\n closed = true;\n port.onmessage = null;\n port.close();\n emit(event);\n };\n const copyInventory = (value) => ({ revision: value.revision, sessions: value.sessions.map((session) => ({ ...session })) });\n port.onmessage = (event) => {\n const message2 = event.data;\n if (closed || !isRecord(message2)) return;\n if (message2.t === "machine") {\n if (!isBoolean(message2.online) || !isRecord(message2.terminal) || !isBoolean(message2.terminal.enabled) || !isBoolean(message2.terminal.tmux)) return;\n machine2 = { online: message2.online, terminal: { enabled: message2.terminal.enabled, tmux: message2.terminal.tmux } };\n version += 1;\n notify(machines, { ...machine2, terminal: { ...machine2.terminal } });\n } else if (message2.t === "inventory") {\n if (!isCount(message2.revision) || !isArrayOf(message2.sessions, isSession)) return;\n inventory = copyInventory({ revision: message2.revision, sessions: message2.sessions });\n version += 1;\n notify(inventories, copyInventory(inventory));\n } else if (message2.t === "reconnecting") {\n const reconnecting = reconnectingEvent(message2);\n if (reconnecting) emit(reconnecting);\n } else if (message2.t === "closed" && isClosed(message2)) finish(closedEvent(message2));\n };\n return Object.freeze({\n get machine() {\n return machine2 ? { ...machine2, terminal: { ...machine2.terminal } } : null;\n },\n get inventory() {\n return inventory ? copyInventory(inventory) : null;\n },\n get closed() {\n return closed;\n },\n onMachine: (listener) => latest(machines, listener, () => version, () => machine2 ? { ...machine2, terminal: { ...machine2.terminal } } : null),\n onInventory: (listener) => latest(inventories, listener, () => version, () => inventory ? copyInventory(inventory) : null),\n onEvent: (listener) => subscribe3(events, listener, () => {\n const queued = pendingEvents ?? [];\n pendingEvents = null;\n for (const event of queued) notify(events, event);\n }),\n close: () => {\n if (closed) return;\n try {\n port.postMessage({ t: "close" });\n } catch {\n }\n finish({ t: "closed", code: "closed", retryable: false });\n }\n });\n}\n\n// src/machine.ts\nvar isAccess = (value) => value === "control" || value === "observe";\nvar isMachine = (value) => isRecord(value) && isString(value.id) && isString(value.name) && value.platform === "macos" && isBoolean(value.online) && isNullable(value.lastSeenAt, isString) && isAccess(value.access) && isRecord(value.terminal) && isBoolean(value.terminal.enabled) && isBoolean(value.terminal.tmux) && isArrayOf(value.features, isString);\nvar isSession2 = (value) => isRecord(value) && isString(value.id) && isString(value.title) && isNullable(value.cwd, isString) && isString(value.createdAt) && isCount(value.viewers);\nvar isSessionResult = (value) => isRecord(value) && isSession2(value.session);\nvar shape = (check2) => (value) => isRecord(value) && check2(value);\nvar isStrings = (value) => isArrayOf(value, isString);\nvar isRoot = shape((value) => isString(value.id) && isString(value.name) && isString(value.displayPath) && isBoolean(value.exists) && isBoolean(value.git) && isString(value.sensitive));\nvar isProject = shape((value) => isString(value.path) && isString(value.name) && isBoolean(value.git) && isNullable(value.branch, isString));\nvar isEntry = shape((value) => isString(value.name) && isString(value.path) && isString(value.kind) && isCount(value.size) && isString(value.mtime) && isBoolean(value.ignored) && isBoolean(value.sensitive) && isBoolean(value.suspicious));\nvar isRange = (value) => Array.isArray(value) && value.length === 2 && isCount(value[0]) && isCount(value[1]);\nvar isVersion = (value) => isRecord(value) && isNullable(value.hash, isString) && isCount(value.size) && isString(value.mtime);\nvar isFound = shape((value) => isString(value.path) && typeof value.score === "number" && isArrayOf(value.ranges, isRange));\nvar isMatch = shape((value) => isString(value.path) && isCount(value.line) && isCount(value.column) && isString(value.preview) && isArrayOf(value.ranges, isRange));\nvar isStatusEntry = shape((value) => isString(value.path) && isString(value.index) && isString(value.worktree));\nvar isGitStatus = shape((value) => isNullable(value.branch, isString) && isBoolean(value.detached) && isNullable(value.head, isString) && isNullable(value.upstream, isString) && isCount(value.ahead) && isCount(value.behind) && isNullable(value.lastFetchAt, isString) && isNullable(value.operation, isString) && isArrayOf(value.entries, isStatusEntry) && isBoolean(value.truncated) && isCount(value.stashes));\nvar isCommit = shape((value) => isString(value.sha) && isStrings(value.parents) && isString(value.author) && isString(value.date) && isString(value.subject) && isStrings(value.refs));\nvar isChangedFile = shape((value) => isString(value.path) && isString(value.status) && isNullable(value.additions, isCount) && isNullable(value.deletions, isCount));\nvar isBranch = shape((value) => isString(value.name) && isString(value.sha) && isString(value.date));\nvar isConversation = shape((value) => isString(value.id) && isString(value.vendor) && isString(value.root) && isString(value.path) && isString(value.title) && isString(value.createdAt) && isString(value.updatedAt) && isString(value.state) && isNullable(value.model, isString) && isNullable(value.effort, isString) && isString(value.mode) && isCount(value.lastSeq) && isBoolean(value.closed) && isCount(value.pending) && (value.usage === null || isRecord(value.usage)));\nvar isEvent2 = shape((value) => isCount(value.seq) && isCount(value.at) && isNullable(value.turn, isString) && isString(value.kind));\nvar isLive = shape((value) => isString(value.item) && isString(value.type) && isString(value.text));\nvar isUpdate = shape((value) => isString(value.id) && isString(value.state) && isCount(value.lastSeq) && isArrayOf(value.events, isEvent2) && isArrayOf(value.live, isLive) && isBoolean(value.reset));\nvar isModel = shape((value) => isString(value.id) && isString(value.label) && isBoolean(value.default));\nvar withStatus = shape((value) => isGitStatus(value.status));\nvar withConversation = shape((value) => isConversation(value.conversation));\nvar flag = (key2) => shape((value) => isBoolean(value[key2]));\nfunction createMachine(context) {\n const call2 = async (operation2, input4, check2, options) => {\n const value = await context.invoke(machineOperationDefinitions[operation2].capability, machineOperationDefinitions[operation2].operation, input4, options);\n if (!check2(value)) throw new NochaError("invalid_result", `Nocha returned an invalid machine ${operation2} result`);\n return value;\n };\n const invokeBridge2 = (capability, operation2, input4, options) => context.invokeWithPort(capability, operation2, input4, options);\n const stream2 = async (operation2, input4, options) => {\n const { result: result2, port } = await invokeBridge2(machineOperationDefinitions[operation2].capability, machineOperationDefinitions[operation2].operation, input4, options);\n if (!isRecord(result2) || result2.stream !== (operation2 === "terminal.attach" ? "terminal" : "watch")) {\n port.close();\n throw new NochaError("invalid_result", `Nocha returned an invalid machine ${operation2} result`);\n }\n return port;\n };\n const terminal = Object.freeze({\n sessions: (input4, options) => call2(\n "terminal.sessions",\n input4,\n (value) => isRecord(value) && isCount(value.revision) && isArrayOf(value.sessions, isSession2),\n options\n ),\n create: (input4, options) => call2("terminal.create", input4, isSessionResult, options),\n close: (input4, options) => call2("terminal.close", input4, (value) => isRecord(value) && value.closed === true, options),\n rename: (input4, options) => call2("terminal.rename", input4, isSessionResult, options),\n attach: async (input4, options) => terminalStream(await stream2("terminal.attach", input4, options), isRecord(input4) && input4.manualAck === true),\n watch: async (input4, options) => watchStream(await stream2("terminal.watch", input4, options))\n });\n const workspace3 = Object.freeze({\n roots: (input4, options) => call2("workspace.roots", input4, shape((value) => isCount(value.revision) && isArrayOf(value.roots, isRoot)), options),\n discover: (input4, options) => call2("workspace.discover", input4, shape((value) => isArrayOf(value.projects, isProject) && isBoolean(value.truncated)), options),\n requestRoot: (input4, options) => call2("workspace.requestRoot", input4, shape((value) => isNullable(value.root, isRoot)), options)\n });\n const files = Object.freeze({\n list: (input4, options) => call2("files.list", input4, shape((value) => isArrayOf(value.entries, isEntry) && isNullable(value.next, isString)), options),\n stat: (input4, options) => call2("files.stat", input4, shape((value) => isEntry(value.entry) && isNullable(value.hash, isString)), options),\n read: (input4, options) => call2("files.read", input4, shape((value) => isCount(value.size) && isString(value.mtime) && isNullable(value.hash, isString) && isCount(value.offset) && isCount(value.length) && isBoolean(value.eof) && isBoolean(value.binary) && isString(value.encoding) && isString(value.data) && isNullable(value.lineEnding, isString)), options),\n write: (input4, options) => call2("files.write", input4, shape((value) => value.written === true ? isString(value.hash) && isCount(value.size) && isString(value.mtime) : value.written === false && isVersion(value.conflict)), options),\n mkdir: (input4, options) => call2("files.mkdir", input4, shape((value) => value.created === true), options),\n move: (input4, options) => call2("files.move", input4, shape((value) => value.moved === true), options),\n trash: (input4, options) => call2("files.trash", input4, shape((value) => isCount(value.trashed)), options),\n find: (input4, options) => call2("files.find", input4, shape((value) => isArrayOf(value.results, isFound) && isBoolean(value.truncated) && isCount(value.scanned)), options),\n search: (input4, options) => call2("files.search", input4, shape((value) => isArrayOf(value.matches, isMatch) && isCount(value.files) && isBoolean(value.truncated) && isCount(value.elapsedMs)), options),\n tree: (input4, options) => call2("files.tree", input4, shape((value) => isRecord(value.snapshot) && isRecord(value.snapshot.tree) && isRecord(value.snapshot.totals) && isRecord(value.truncation) && isString(value.fingerprint) && isString(value.generatedAt) && isCount(value.elapsedMs)), options)\n });\n const git = Object.freeze({\n status: (input4, options) => call2("git.status", input4, isGitStatus, options),\n diff: (input4, options) => call2("git.diff", input4, shape((value) => isString(value.diff) && isStrings(value.binary) && isBoolean(value.truncated)), options),\n log: (input4, options) => call2("git.log", input4, shape((value) => isArrayOf(value.commits, isCommit) && isNullable(value.next, isString)), options),\n show: (input4, options) => call2("git.show", input4, shape((value) => isRecord(value.commit) && isString(value.commit.sha) && isString(value.commit.body) && isArrayOf(value.files, isChangedFile) && (value.diff === void 0 || isString(value.diff)) && isBoolean(value.truncated)), options),\n branches: (input4, options) => call2("git.branches", input4, shape((value) => isNullable(value.current, isString) && isArrayOf(value.local, isBranch) && isArrayOf(value.remote, isBranch) && isBoolean(value.truncated)), options),\n stage: (input4, options) => call2("git.stage", input4, withStatus, options),\n unstage: (input4, options) => call2("git.unstage", input4, withStatus, options),\n discard: (input4, options) => call2("git.discard", input4, shape((value) => isGitStatus(value.status) && isNullable(value.backup, isString)), options),\n commit: (input4, options) => call2("git.commit", input4, shape((value) => isString(value.sha) && isGitStatus(value.status)), options),\n checkout: (input4, options) => call2("git.checkout", input4, withStatus, options),\n fetch: (input4, options) => call2("git.fetch", input4, withStatus, options)\n });\n const agents = Object.freeze({\n capabilities: (input4, options) => call2("agents.capabilities", input4, shape((value) => isBoolean(value.available) && isNullable(value.version, isString) && isArrayOf(value.models, isModel) && isStrings(value.efforts) && isStrings(value.modes)), options),\n list: (input4, options) => call2("agents.list", input4, shape((value) => isArrayOf(value.conversations, isConversation)), options),\n read: (input4, options) => call2("agents.read", input4, shape((value) => isArrayOf(value.events, isEvent2) && isCount(value.first) && isCount(value.last) && isBoolean(value.more)), options),\n events: (input4, options) => call2("agents.events", input4, shape((value) => isArrayOf(value.conversations, isUpdate)), options),\n item: (input4, options) => call2("agents.item", input4, shape((value) => isString(value.output) && isBoolean(value.truncated)), options),\n start: (input4, options) => call2("agents.start", input4, withConversation, options),\n send: (input4, options) => call2("agents.send", input4, flag("queued"), options),\n configure: (input4, options) => call2("agents.configure", input4, withConversation, options),\n interrupt: (input4, options) => call2("agents.interrupt", input4, flag("interrupted"), options),\n respond: (input4, options) => call2("agents.respond", input4, flag("resolved"), options),\n rename: (input4, options) => call2("agents.rename", input4, withConversation, options),\n close: (input4, options) => call2("agents.close", input4, shape((value) => value.closed === true), options)\n });\n return Object.freeze({\n list: (options) => call2("list", {}, (value) => isRecord(value) && isCount(value.paired) && isArrayOf(value.machines, isMachine), options),\n connect: (input4 = {}, options) => call2("connect", input4, (value) => isRecord(value) && isArrayOf(value.machines, isMachine), options),\n revoke: (input4 = {}, options) => call2("revoke", input4, (value) => isRecord(value) && isCount(value.revoked), options),\n terminal,\n workspace: workspace3,\n files,\n git,\n agents\n });\n}\n\n// src/hardware.ts\nvar captureStates = ["recording", "stopped", "expired", "failed"];\nvar isHostHeader = (value) => isRecord(value) && isNonEmptyString(value.hostId) && isString(value.hostName) && isString(value.collectedAt);\nvar isEvenCount = (value) => isCount(value) && value % 2 === 0;\nvar isMetrics = (value) => isHostHeader(value) && isString(value.context) && isBoolean(value.metricsAvailable) && Array.isArray(value.nodes) && Array.isArray(value.pods) && isArrayOf(value.warnings, isString);\nvar isHueLights = (value) => isHostHeader(value) && isArrayOf(value.lights, (light) => isRecord(light) && isString(light.id) && isString(light.name) && isBoolean(light.on) && isNullable(light.brightness, isFiniteNumber) && isBoolean(light.colorSupported)) && (value.groups === void 0 || Array.isArray(value.groups));\nvar isLedsSnapshot = (value) => isHostHeader(value) && isArrayOf(value.devices, (device) => isRecord(device) && isString(device.id) && isString(device.name) && isBoolean(device.online)) && Array.isArray(value.effects) && Array.isArray(value.scenes) && (value.commandId === void 0 || isString(value.commandId)) && (value.stateStatus === void 0 || value.stateStatus === "confirmed" || value.stateStatus === "optimistic");\nvar isAudioDevices = (value) => isHostHeader(value) && isArrayOf(value.devices, (device) => isRecord(device) && isString(device.id) && isBoolean(device.online) && isNullable(device.captureId, isString));\nvar isCapture = (deviceId) => (value) => isRecord(value) && isString(value.captureId) && value.deviceId === deviceId && value.state === "recording" && value.format === "s16le" && value.sampleRate === 16e3 && value.channels === 1;\nvar isChunk = (captureId) => (value) => isRecord(value) && value.captureId === captureId && captureStates.includes(String(value.state)) && isEvenCount(value.cursor) && isBase64(value.data) && isEvenCount(value.bytes) && isCount(value.totalBytes) && isCount(value.durationMs);\nvar isStopped = (captureId) => (value) => isRecord(value) && value.captureId === captureId && captureStates.includes(String(value.state)) && isCount(value.totalBytes) && isCount(value.durationMs);\nvar isTranscript = (captureId) => (value) => isRecord(value) && value.captureId === captureId && isString(value.text) && isCount(value.durationMs);\nvar isShare = (value) => isNullable(value, isFiniteNumber);\nvar isNetwork = (value) => isRecord(value) && isString(value.collectedAt) && isNullable(value.locksBusy, isCount) && isArrayOf(value.machines, (machine2) => isRecord(machine2) && isNonEmptyString(machine2.id) && isBoolean(machine2.reachable) && isShare(machine2.cpuBusy) && isShare(machine2.memoryUsed) && isArrayOf(machine2.agents, (group) => isRecord(group) && isString(group.engine) && isString(group.surface) && isCount(group.count)) && isArrayOf(machine2.jobs, (group) => isRecord(group) && isString(group.kind) && isString(group.status) && isCount(group.count)));\nvar isDesktopState = (value) => isRecord(value) && isRecord(value.terminal) && isString(value.terminal.app) && isBoolean(value.terminal.running) && isCount(value.terminal.windows) && isNullable(value.terminal.tabs, isCount) && isBoolean(value.terminal.frontmost) && isArrayOf(value.agents, (agent) => isRecord(agent) && isNonEmptyString(agent.id) && isString(agent.label)) && isRecord(value.dictation) && isBoolean(value.dictation.available);\nvar isDesktopDictation = (action) => (value) => isRecord(value) && value.action === action && value.delivered === true;\nvar isDesktopTerminal = (input4) => (value) => isRecord(value) && value.action === input4.action && isNullable(value.agentId, isString) && value.agentId === (input4.action === "tab.open" ? input4.agentId ?? null : null) && isCount(value.windows) && isNullable(value.tabs, isCount);\nvar field2 = (input4, key2) => isRecord(input4) ? input4[key2] : void 0;\nfunction createHardware(context) {\n const call2 = async (operation2, input4, check2, options) => {\n const value = await context.invoke(hardwareOperationDefinitions[operation2].capability, hardwareOperationDefinitions[operation2].operation, input4, options);\n if (!check2(value)) throw new NochaError("invalid_result", `Nocha returned an invalid hardware ${operation2} result`);\n return value;\n };\n return Object.freeze({\n metrics: (options) => call2("metrics.read", {}, isMetrics, options),\n hue: Object.freeze({\n lights: (options) => call2("hue.lights.read", {}, isHueLights, options),\n set: (input4, options) => call2("hue.lights.set", input4, isHueLights, options)\n }),\n leds: Object.freeze({\n read: (options) => call2("leds.read", {}, isLedsSnapshot, options),\n set: (input4, options) => call2("leds.set", input4, isLedsSnapshot, options)\n }),\n audio: Object.freeze({\n devices: (options) => call2("audio.devices", {}, isAudioDevices, options),\n start: (input4, options) => call2("audio.start", input4, isCapture(field2(input4, "deviceId")), options),\n read: (input4, options) => call2("audio.read", input4, isChunk(field2(input4, "captureId")), options),\n stop: (input4, options) => call2("audio.stop", input4, isStopped(field2(input4, "captureId")), options),\n transcribe: (input4, options) => call2("audio.transcribe", input4, isTranscript(field2(input4, "captureId")), options)\n }),\n network: (options) => call2("network.read", {}, isNetwork, options),\n desktop: Object.freeze({\n read: (options) => call2("desktop.read", {}, isDesktopState, options),\n dictation: (input4, options) => call2("desktop.dictation", input4, isDesktopDictation(field2(input4, "action")), options),\n terminal: (input4, options) => call2("desktop.terminal", input4, isDesktopTerminal(input4), options)\n })\n });\n}\n\n// src/player.ts\nvar renewMs = 6e4;\nvar cached = null;\nvar pending2 = null;\nvar fresh = (token) => !!token && Date.parse(token.expiresAt) - renewMs > Date.now();\nfunction request() {\n const requestId = crypto.randomUUID();\n return new Promise((resolve2, reject2) => {\n const finish = () => {\n clearTimeout(timer);\n window.removeEventListener("message", receive);\n };\n const receive = (event) => {\n const message2 = event.data;\n if (!isFromHost(event) || !isExternalFrameMessage(message2) || !("requestId" in message2) || message2.requestId !== requestId) return;\n if (message2.type === "player-token.result") {\n finish();\n const token = message2.token && Object.freeze({ ...message2.token });\n if (fresh(token)) cached = token;\n resolve2(token);\n } else if (message2.type === "player-token.error") {\n finish();\n reject2(wireError(message2.error));\n }\n };\n const timer = setTimeout(() => {\n finish();\n reject2(new NochaError("invocation_timed_out", "The Nocha frame did not answer the player token request"));\n }, operationWaiting.default);\n window.addEventListener("message", receive);\n postToHost({ protocol: NOCHA_EXTERNAL_PROTOCOL, type: "player-token.request", requestId });\n });\n}\nvar player = Object.freeze({\n async token() {\n const hosting = await hostingReady();\n if (hosting === "hosted") throw new NochaError("not_external", "nocha.player.token() is for self-hosted experiences only");\n if (hosting === "standalone") throw new NochaError("bridge_unavailable", "nocha.player.token() requires the Nocha frame");\n if (fresh(cached)) return cached;\n return pending2 ??= request().finally(() => {\n pending2 = null;\n });\n }\n});\n\n// src/state.ts\nfunction createStateWatch(invoke2, subscribeEvents, subscribeConnection) {\n return (listener, options) => {\n assertHostCapability("state");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A state listener is required");\n let active3 = true;\n const controller = new AbortController();\n let authorized = false;\n let snapshot3 = null;\n let buffered = null;\n let connection2;\n let pending3 = false;\n let queued = false;\n let generation = 0;\n let attempt = 0;\n let timer;\n let stopEvents = () => {\n };\n let stopConnection = () => {\n };\n const emit = (status2, error) => {\n if (!active3) return;\n notifyListener(listener, { status: status2, snapshot: snapshot3, ...error ? { error } : {} });\n };\n const dispose = () => {\n active3 = false;\n controller.abort();\n if (timer !== void 0) clearTimeout(timer);\n stopEvents();\n stopConnection();\n options?.signal?.removeEventListener("abort", dispose);\n };\n const accept = (next) => {\n if (!snapshot3 || next.sequence > snapshot3.sequence) snapshot3 = next;\n };\n const currentStatus = () => connection2 === void 0 || connection2 === "connected" ? "synchronized" : "recovering";\n const refresh = () => {\n if (!active3) return;\n if (pending3) {\n queued = true;\n return;\n }\n if (timer !== void 0) clearTimeout(timer);\n timer = void 0;\n const startedGeneration = generation;\n pending3 = true;\n void invoke2("state", "get", {}, { ...options, signal: controller.signal }).then((value) => {\n if (!active3 || startedGeneration !== generation) return;\n if (!isStateSnapshot(value)) throw new NochaError("invalid_result", "Nocha returned an invalid shared state snapshot");\n authorized = true;\n accept(value);\n if (buffered) {\n accept(buffered);\n buffered = null;\n }\n attempt = 0;\n emit(currentStatus());\n }).catch((cause) => {\n if (!active3 || startedGeneration !== generation) return;\n const error = isNochaError(cause) ? cause : new NochaError("invocation_failed", String(cause));\n const delay = retryDelayMs(error, attempt);\n if (delay === void 0) {\n emit("closed", error);\n dispose();\n return;\n }\n attempt += 1;\n emit("unavailable", error);\n timer = setTimeout(refresh, delay);\n }).finally(() => {\n pending3 = false;\n if (queued && active3) {\n queued = false;\n refresh();\n }\n });\n };\n if (options?.signal?.aborted) return dispose;\n stopEvents = subscribeEvents((event) => {\n if (!active3 || event.type !== "state.set") return;\n const value = { sequence: event.sequence, state: event.payload };\n if (!isStateSnapshot(value)) {\n refresh();\n return;\n }\n if (!authorized) {\n if (!buffered || value.sequence > buffered.sequence) buffered = value;\n return;\n }\n accept(value);\n emit(currentStatus());\n });\n stopConnection = subscribeConnection((event) => {\n if (!active3 || connection2 === event.status) return;\n connection2 = event.status;\n if (event.status === "closed") {\n emit("closed");\n dispose();\n return;\n }\n if (event.status === "connected") {\n refresh();\n return;\n }\n generation += 1;\n emit(event.status === "unavailable" ? "unavailable" : snapshot3 ? "recovering" : "loading");\n });\n options?.signal?.addEventListener("abort", dispose, { once: true });\n emit("loading");\n refresh();\n return dispose;\n };\n}\nfunction isStateSnapshot(value) {\n return isRecord(value) && isCount(value.sequence) && Object.hasOwn(value, "state");\n}\n\n// src/database-watch.ts\nvar READ_SPACING_MS = 250;\nfunction createDatabaseWatch(context, isPage3, subscribeEvents, subscribeConnection) {\n return (input4, listener, options) => {\n assertHostCapability("database");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A database listener is required");\n const collection = isRecord(input4) ? input4.collection : void 0;\n if (typeof collection !== "string") throw new NochaError("invalid_request", "database.watch requires a collection");\n if (context.usageId === void 0) {\n notifyListener(listener, { status: "closed", page: null, error: new NochaError("usage_required", "database.watch requires nocha.use(<declared usage id>)") });\n return () => {\n };\n }\n const query = { collection, ...input4.limit !== void 0 ? { limit: input4.limit } : {}, ...input4.mine !== void 0 ? { mine: input4.mine } : {} };\n let active3 = true;\n let watching = false;\n let page = null;\n let connection2;\n let pending3 = false;\n let queued = false;\n let attempt = 0;\n let lastRead = 0;\n let timer;\n const controller = new AbortController();\n let stopEvents = () => {\n };\n let stopConnection = () => {\n };\n const emit = (status2, error) => {\n if (active3) notifyListener(listener, { status: status2, page, ...error ? { error } : {} });\n };\n const dispose = () => {\n active3 = false;\n controller.abort();\n if (timer !== void 0) clearTimeout(timer);\n stopEvents();\n stopConnection();\n options?.signal?.removeEventListener("abort", dispose);\n };\n const close = (error) => {\n emit("closed", error);\n dispose();\n };\n const currentStatus = () => connection2 === void 0 || connection2 === "connected" ? "synchronized" : "recovering";\n const read4 = () => {\n if (!active3) return;\n if (pending3) {\n queued = true;\n return;\n }\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n const wait2 = lastRead + READ_SPACING_MS - Date.now();\n if (watching && wait2 > 0) {\n timer = setTimeout(read4, wait2);\n return;\n }\n pending3 = true;\n lastRead = Date.now();\n const first = !watching;\n void context.invoke(\n storageOperations.database.query.capability,\n storageOperations.database.query.operation,\n { ...query, watch: true },\n { ...options, signal: controller.signal }\n ).then((value) => {\n if (!active3) return;\n if (first && !(isRecord(value) && value.watching === true)) {\n close(new NochaError("client_update_required", "This Nocha host cannot follow a database collection"));\n return;\n }\n if (!isPage3(value, query)) throw new NochaError("invalid_result", "Nocha returned an invalid database page");\n const { records: records3, nextCursor } = value;\n watching = true;\n attempt = 0;\n page = { records: records3, nextCursor };\n emit(currentStatus());\n }).catch((cause) => {\n if (!active3) return;\n const error = isNochaError(cause) ? cause : new NochaError("invocation_failed", String(cause));\n const delay = retryDelayMs(error, attempt);\n if (delay === void 0) {\n close(error);\n return;\n }\n attempt += 1;\n emit("unavailable", error);\n timer = setTimeout(read4, delay);\n }).finally(() => {\n pending3 = false;\n if (queued && active3) {\n queued = false;\n read4();\n }\n });\n };\n if (options?.signal?.aborted) return dispose;\n stopEvents = subscribeEvents((event) => {\n if (!active3 || event.type !== "database.changed" || !isRecord(event.payload) || event.payload.collection !== collection) return;\n read4();\n });\n stopConnection = subscribeConnection((event) => {\n if (!active3 || connection2 === event.status) return;\n const previous = connection2;\n connection2 = event.status;\n if (event.status === "closed") {\n close();\n return;\n }\n if (event.status === "connected") {\n if (watching && previous !== void 0) read4();\n else if (watching) emit(currentStatus());\n return;\n }\n emit(event.status === "unavailable" ? "unavailable" : page ? "recovering" : "loading");\n });\n options?.signal?.addEventListener("abort", dispose, { once: true });\n emit("loading");\n read4();\n return dispose;\n };\n}\n\n// src/storage.ts\nfunction invalidResult2(what) {\n throw new NochaError("invalid_result", `Nocha returned an invalid ${what}`);\n}\nasync function validated2(request2, check2, what) {\n const value = await request2;\n if (!check2(value)) invalidResult2(what);\n return value;\n}\nvar isAuthor = (value) => isNullable(value, isString);\nvar isVisibility2 = (value) => value === "private" || value === "shared";\nvar isTeam = (value) => value === void 0 || isSpaceTeam(value);\nfunction isDatabaseEntry(value) {\n return isRecord(value) && isUuid(value.id) && isCount(value.revision) && value.revision >= 1 && isRecord(value.record) && isAuthor(value.author) && (value.visibility === void 0 || isVisibility2(value.visibility)) && (value.mine === void 0 || typeof value.mine === "boolean") && isTeam(value.team);\n}\nfunction input2(value) {\n return isRecord(value) ? value : {};\n}\nvar isMemoryKey = (value) => typeof value === "string" && /^[a-zA-Z0-9._:-]{1,100}$/.test(value);\nfunction isMemoryList(value) {\n return isRecord(value) && Array.isArray(value.items) && value.items.every((item) => isRecord(item) && isMemoryKey(item.key) && isCount(item.sequence) && item.sequence >= 1) && isNullable(value.nextCursor, isString);\n}\nfunction shareInput(value, visibility) {\n return { collection: input2(value).collection, id: input2(value).id, visibility };\n}\nfunction createState(context, watch) {\n return Object.freeze({\n get: (options) => validated2(context.invoke(storageOperations.state.get.capability, storageOperations.state.get.operation, {}, options), isStateSnapshot, "shared state snapshot"),\n set: (value, options) => validated2(context.invoke(storageOperations.state.set.capability, storageOperations.state.set.operation, {\n state: input2(value).state,\n ...input2(value).expectedSequence !== void 0 ? { expectedSequence: input2(value).expectedSequence } : {}\n }, options), (next) => isStateSnapshot(next) && next.sequence >= 1, "shared state snapshot"),\n watch: (listener, options) => {\n if (context.usageId !== void 0) return watch(listener, options);\n assertHostCapability("state");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A state listener is required");\n notifyListener(listener, { status: "closed", snapshot: null, error: new NochaError("usage_required", "state.watch requires nocha.use(<declared usage id>)") });\n return () => {\n };\n }\n });\n}\nfunction createMemory(context) {\n const isMemory = (key2) => (value) => isRecord(value) && value.key === key2 && isCount(value.sequence) && Object.hasOwn(value, "value");\n return Object.freeze({\n get: (value, options) => validated2(context.invoke(storageOperations.memory.get.capability, storageOperations.memory.get.operation, value, options), isMemory(input2(value).key), "memory value"),\n set: (value, options) => validated2(context.invoke(storageOperations.memory.set.capability, storageOperations.memory.set.operation, value, options), isMemory(input2(value).key), "memory value"),\n remove: (value, options) => validated2(\n context.invoke(storageOperations.memory.remove.capability, storageOperations.memory.remove.operation, value, options),\n (result2) => isRecord(result2) && result2.key === input2(value).key && result2.removed === true && isCount(result2.sequence),\n "memory removal receipt"\n ),\n list: (value, options) => validated2(context.invoke(storageOperations.memory.list.capability, storageOperations.memory.list.operation, value, options), isMemoryList, "memory key list")\n });\n}\nfunction isDatabasePage(result2, query) {\n return isRecord(result2) && Array.isArray(result2.records) && result2.records.every(isDatabaseEntry) && isNullable(result2.nextCursor, isString) && (input2(query).mine !== true || result2.records.every((record6) => isRecord(record6) && record6.mine === true));\n}\nfunction createDatabase(context) {\n return Object.freeze({\n insert: (value, options) => {\n if (!options?.idempotencyKey) return Promise.reject(new NochaError("invalid_request", "database.insert requires a persisted idempotencyKey"));\n return validated2(\n context.invoke(storageOperations.database.insert.capability, storageOperations.database.insert.operation, value, options),\n (result2) => isRecord(result2) && isUuid(result2.id) && isCount(result2.revision) && result2.revision >= 1 && isAuthor(result2.author) && (result2.visibility === void 0 || isVisibility2(result2.visibility)) && isTeam(result2.team),\n "database insert receipt"\n );\n },\n get: (value, options) => validated2(\n context.invoke(storageOperations.database.get.capability, storageOperations.database.get.operation, value, options),\n (result2) => result2 === null || isDatabaseEntry(result2) && result2.id === input2(value).id,\n "database record"\n ),\n query: (value, options) => validated2(\n context.invoke(storageOperations.database.query.capability, storageOperations.database.query.operation, value, options),\n (result2) => isDatabasePage(result2, value),\n "database page"\n ),\n update: (value, options) => validated2(\n context.invoke(storageOperations.database.update.capability, storageOperations.database.update.operation, value, options),\n (result2) => isRecord(result2) && result2.id === input2(value).id && isCount(result2.revision) && result2.revision >= 2 && isAuthor(result2.author) && isTeam(result2.team),\n "database update receipt"\n ),\n remove: (value, options) => validated2(\n context.invoke(storageOperations.database.remove.capability, storageOperations.database.remove.operation, value, options),\n (result2) => isRecord(result2) && result2.removed === true,\n "database removal receipt"\n ),\n setVisibility: (value, options) => validated2(\n context.invoke(storageOperations.database.visibility.capability, storageOperations.database.visibility.operation, value, options),\n (result2) => isRecord(result2) && result2.id === input2(value).id && isVisibility2(result2.visibility),\n "database visibility"\n ),\n share: (value, options) => validated2(\n context.invoke(storageOperations.database.visibility.capability, storageOperations.database.visibility.operation, shareInput(value, "shared"), options),\n (result2) => isRecord(result2) && result2.id === input2(value).id && result2.visibility === "shared",\n "database visibility"\n ),\n unshare: (value, options) => validated2(\n context.invoke(storageOperations.database.visibility.capability, storageOperations.database.visibility.operation, shareInput(value, "private"), options),\n (result2) => isRecord(result2) && result2.id === input2(value).id && result2.visibility === "private",\n "database visibility"\n )\n });\n}\n\n// src/clipping-types.ts\nvar CLIPPING_LIMITS = {\n source_maximum_bytes: 512 * 1024 * 1024,\n source_maximum_seconds: 30 * 60,\n target_minimum_seconds: 15,\n target_maximum_seconds: 120,\n instruction_maximum_characters: 2e3,\n accepted_mime_types: ["video/mp4", "video/quicktime", "video/webm"]\n};\n\n// src/clipping.ts\nfunction validJob(value) {\n return isRecord(value) && typeof value.id === "string" && ["proposal", "export"].includes(String(value.kind)) && ["queued", "running", "cancelling", "succeeded", "failed", "cancelled"].includes(String(value.status)) && Number.isFinite(value.progress) && Number(value.progress) >= 0 && Number(value.progress) <= 1 && typeof value.confirmed_maximum_microcredits === "string" && /^\\d+$/.test(value.confirmed_maximum_microcredits) && typeof value.spent_microcredits === "string" && /^\\d+$/.test(value.spent_microcredits);\n}\nfunction validExport(value) {\n return isRecord(value) && typeof value.id === "string" && Number.isInteger(value.plan_version) && typeof value.source_signature === "string" && validJob(value.job) && (value.result === null || isRecord(value.result) && typeof value.result.download_url === "string" && value.result.mime_type === "video/mp4" && Number.isFinite(value.result.duration_seconds) && Number.isFinite(value.result.size_bytes));\n}\nfunction validResource(value) {\n if (!isRecord(value) || typeof value.id !== "string" || value.project_id !== value.id || typeof value.title !== "string" || !isRecord(value.settings) || !Number.isFinite(value.settings.target_duration_seconds) || !["gentle", "balanced", "dynamic"].includes(String(value.settings.intensity)) || typeof value.settings.preserve_speech !== "boolean" || typeof value.settings.shorten_silences !== "boolean" || typeof value.settings.instruction !== "string" || !Array.isArray(value.exports) || !value.exports.every(validExport) || value.proposal_job !== null && !validJob(value.proposal_job)) return false;\n if (value.source !== null && (!isRecord(value.source) || typeof value.source.signature !== "string" || typeof value.source.name !== "string" || typeof value.source.has_audio !== "boolean" || !["duration_seconds", "size_bytes", "width", "height"].every((key2) => Number.isFinite(value.source[key2])) || !["preview_url", "thumbnail_url"].every((key2) => value.source[key2] === null || typeof value.source[key2] === "string"))) return false;\n if (value.plan !== null && (!isRecord(value.plan) || !Number.isInteger(value.plan.version) || typeof value.plan.source_signature !== "string" || !Number.isFinite(value.plan.duration_seconds) || !Array.isArray(value.plan.evidence) || !value.plan.evidence.every((item) => isRecord(item) && typeof item.id === "string" && typeof item.description === "string" && ["visual", "speech", "audio"].includes(String(item.kind)) && Number.isFinite(item.start_seconds) && Number.isFinite(item.end_seconds)) || !Array.isArray(value.plan.segments) || !value.plan.segments.every((segment) => isRecord(segment) && typeof segment.id === "string" && typeof segment.explanation === "string" && Array.isArray(segment.evidence_ids) && segment.evidence_ids.every((id) => typeof id === "string") && Number.isFinite(segment.start_seconds) && Number.isFinite(segment.end_seconds) && Number(segment.end_seconds) > Number(segment.start_seconds)))) return false;\n return true;\n}\nvar validators = {\n prepareMutation: (result2) => isRecord(result2) && typeof result2.idempotency_key === "string" && "request" in result2,\n readMutation: (result2) => isRecord(result2) && (result2.pending === null || isRecord(result2.pending) && typeof result2.pending.idempotency_key === "string" && "request" in result2.pending),\n completeMutation: (result2) => isRecord(result2) && result2.completed === true,\n remove: (result2) => isRecord(result2) && result2.deleted === true,\n list: (result2) => isRecord(result2) && Array.isArray(result2.items) && result2.items.every(validResource),\n estimate: (result2) => isRecord(result2) && typeof result2.maximum_microcredits === "string" && /^\\d+$/.test(result2.maximum_microcredits) && typeof result2.valid_until === "string",\n createExport: validExport,\n getJob: validJob,\n cancelJob: validJob,\n resumeJob: validJob\n};\nasync function call(context, operation2, input4, options) {\n const result2 = await context.invoke(videoOperationDefinitions[operation2].capability, videoOperationDefinitions[operation2].operation, input4, options);\n if (!(validators[operation2.slice("clipping.".length)] ?? validResource)(result2)) throw new NochaError("invalid_result", "Nocha returned an invalid clipping result");\n return result2;\n}\nfunction text2(value, field3) {\n if (typeof value !== "string" || !value) throw invalid2(`${field3} must be a non-empty string`);\n return value;\n}\nfunction integer(value, field3) {\n if (typeof value !== "number" || !Number.isInteger(value)) throw invalid2(`${field3} must be an integer`);\n return value;\n}\nfunction ceiling(value) {\n if (typeof value !== "string" || !/^\\d+$/.test(value)) throw invalid2("confirmedMaximumMicrocredits must be a decimal integer string");\n return value;\n}\nfunction document2(value, field3) {\n if (!isRecord(value)) throw invalid2(`${field3} must be an object`);\n return value;\n}\nfunction input3(value) {\n if (!isRecord(value)) throw invalid2("A clipping request object is required");\n return value;\n}\nasync function uploadSource(context, request2, options = {}) {\n const value = input3(request2);\n const id = text2(value.id, "id");\n const file = value.file;\n if (!(file instanceof Blob) || file.size <= 0) throw invalid2("A non-empty video file is required");\n if (value.filename !== void 0 && typeof value.filename !== "string") throw invalid2("filename must be a string");\n const filename = value.filename ?? ("name" in file ? String(file.name) : "source.mp4");\n const mimeType = file.type || (/\\.mov$/i.test(filename) ? "video/quicktime" : /\\.webm$/i.test(filename) ? "video/webm" : "video/mp4");\n if (!CLIPPING_LIMITS.accepted_mime_types.includes(mimeType)) throw invalid2("Select an MP4, MOV or WebM video");\n assertHostCapability("video");\n const usageId = context.usageId;\n if (usageId === void 0) throw new NochaError("usage_required", "video.clipping.uploadSource requires nocha.use(<declared usage id>)");\n const upload2 = { id, filename, mime_type: mimeType, size_bytes: file.size };\n const definition = videoOperationDefinitions["clipping.uploadSource"];\n return uploadToHost({\n capability: definition.capability,\n operation: definition.operation,\n unnamed: true,\n usageId,\n idempotencyKey: options.idempotencyKey,\n keySuffix: "upload",\n input: upload2,\n file,\n onProgress: options.onProgress,\n timeoutMs: options.timeoutMs ?? deadlineMs(definition.capability, definition.operation, upload2),\n signal: options.signal,\n validate: (result2) => validResource(result2),\n abortMessage: "Video upload aborted",\n failureMessage: "Video upload failed"\n });\n}\nfunction createClipping(context) {\n const run3 = (operation2, build, options) => {\n try {\n return call(context, operation2, build(), options);\n } catch (error) {\n return Promise.reject(error);\n }\n };\n return Object.freeze({\n prepareMutation: (request2, options) => run3("clipping.prepareMutation", () => {\n const value = input3(request2);\n return { slot: text2(value.slot, "slot"), request: value.request };\n }, options),\n readMutation: (request2, options) => run3("clipping.readMutation", () => ({ slot: text2(input3(request2).slot, "slot") }), options),\n completeMutation: (request2, options) => run3("clipping.completeMutation", () => {\n const value = input3(request2);\n return { slot: text2(value.slot, "slot"), idempotency_key: text2(value.idempotencyKey, "idempotencyKey") };\n }, options),\n create: (request2, options) => run3("clipping.create", () => {\n const value = input3(request2);\n return { title: text2(value.title, "title"), ...value.settings !== void 0 ? { settings: document2(value.settings, "settings") } : {} };\n }, options),\n list: (request2 = {}, options) => run3("clipping.list", () => {\n const value = input3(request2);\n return { ...value.limit !== void 0 ? { limit: integer(value.limit, "limit") } : {}, ...value.cursor !== void 0 ? { cursor: text2(value.cursor, "cursor") } : {} };\n }, options),\n get: (request2, options) => run3("clipping.get", () => ({ id: text2(input3(request2).id, "id") }), options),\n remove: (request2, options) => run3("clipping.remove", () => ({ id: text2(input3(request2).id, "id") }), options),\n uploadSource: (request2, options) => uploadSource(context, request2, options),\n estimate: (request2, options) => run3("clipping.estimate", () => {\n const value = input3(request2);\n return { id: text2(value.id, "id"), settings: document2(value.settings, "settings"), ...value.kind !== void 0 ? { kind: value.kind } : {} };\n }, options),\n propose: (request2, options) => run3("clipping.propose", () => {\n const value = input3(request2);\n return { id: text2(value.id, "id"), settings: document2(value.settings, "settings"), expected_version: integer(value.expectedVersion, "expectedVersion"), confirmed_maximum_microcredits: ceiling(value.confirmedMaximumMicrocredits) };\n }, options),\n updatePlan: (request2, options) => run3("clipping.updatePlan", () => {\n const value = input3(request2);\n if (!Array.isArray(value.segments)) throw invalid2("segments must be a list");\n return { id: text2(value.id, "id"), expected_version: integer(value.expectedVersion, "expectedVersion"), source_signature: text2(value.sourceSignature, "sourceSignature"), segments: value.segments };\n }, options),\n createExport: (request2, options) => run3("clipping.createExport", () => {\n const value = input3(request2);\n return { id: text2(value.id, "id"), plan_version: integer(value.planVersion, "planVersion"), source_signature: text2(value.sourceSignature, "sourceSignature"), confirmed_maximum_microcredits: ceiling(value.confirmedMaximumMicrocredits) };\n }, options),\n getJob: (request2, options) => run3("clipping.getJob", () => {\n const value = input3(request2);\n return { id: text2(value.id, "id"), job_id: text2(value.jobId, "jobId") };\n }, options),\n cancelJob: (request2, options) => run3("clipping.cancelJob", () => {\n const value = input3(request2);\n return { id: text2(value.id, "id"), job_id: text2(value.jobId, "jobId") };\n }, options),\n resumeJob: (request2, options) => run3("clipping.resumeJob", () => {\n const value = input3(request2);\n return { id: text2(value.id, "id"), job_id: text2(value.jobId, "jobId"), confirmed_maximum_microcredits: ceiling(value.confirmedMaximumMicrocredits) };\n }, options)\n });\n}\n\n// src/video-input.ts\nvar aspectRatios = /* @__PURE__ */ new Set(["9:16", "16:9", "1:1"]);\nvar locales = new Set(videoLocales);\nvar speechModes = /* @__PURE__ */ new Set(["none", "auto", "required"]);\nvar resolutions = /* @__PURE__ */ new Set(["720p", "1080p"]);\nvar efforts = /* @__PURE__ */ new Set(["auto", "low", "medium", "high"]);\nvar videoWorkflowFamilies = /* @__PURE__ */ new Set(["classic", "narrative", "image_loop", "analysis"]);\nvar videoStages = ["preparing", "planning", "generating_speech", "generating_media", "assembling"];\nvar workflowId = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/;\nvar analysisSubjectId = /^[plo][1-9]\\d{0,2}$/;\nfunction videoId(value) {\n if (typeof value !== "string" || !isUuid(value.trim())) throw invalid2("A valid video generation id is required");\n return value.trim();\n}\nfunction positiveInteger(value, label) {\n if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw invalid2(`${label} must be a positive integer`);\n return value;\n}\nfunction videoWorkflowRef(value, label = "workflow") {\n if (!isRecord(value) || typeof value.id !== "string" || !workflowId.test(value.id.trim())) throw invalid2(`${label} needs an id such as film-classique or fmt_\\u2026`);\n return { id: value.id.trim(), ...value.revision === void 0 ? {} : { revision: positiveInteger(value.revision, `${label}.revision`) } };\n}\nfunction text3(value, label) {\n if (value === void 0) return void 0;\n if (typeof value !== "string" || !value.trim()) throw invalid2(`${label} must be a non-empty string`);\n return value.trim();\n}\nfunction replaces(value, label) {\n if (value === void 0) return void 0;\n if (!isRecord(value)) throw invalid2(`${label} must be an object`);\n const subject2 = text3(value.subjectId, `${label}.subjectId`), description = text3(value.description, `${label}.description`);\n if (subject2 !== void 0 && !analysisSubjectId.test(subject2)) throw invalid2(`${label}.subjectId must be a subject of the analysis such as p1, l1 or o1`);\n if (!subject2 && !description) throw invalid2(`${label} needs a subjectId, a description or both`);\n return { ...subject2 ? { subject_id: subject2 } : {}, ...description ? { description } : {} };\n}\nfunction reference(value, index) {\n const label = `references[${index}]`;\n if (!isRecord(value)) throw invalid2(`${label} must be an object`);\n const role = text3(value.role, `${label}.role`), name = text3(value.name, `${label}.name`), description = text3(value.description, `${label}.description`);\n const replaced = replaces(value.replaces, `${label}.replaces`);\n const details = { ...role ? { role } : {}, ...name ? { name } : {}, ...description ? { description } : {}, ...replaced ? { replaces: replaced } : {} };\n if (value.assetId === void 0 === (value.studioReferenceId === void 0)) throw invalid2(`${label} needs one assetId or one studioReferenceId`);\n const id = value.assetId ?? value.studioReferenceId;\n if (typeof id !== "string" || !isUuid(id.trim())) throw invalid2(`${label} id must be a uuid`);\n return value.assetId !== void 0 ? { asset_id: id.trim().toLowerCase(), ...details } : { studio_reference_id: id.trim().toLowerCase(), ...details };\n}\nfunction member(value, values, label, fallback) {\n if (value === void 0 && fallback !== void 0) return fallback;\n if (!values.has(value)) throw invalid2(`${label} must be one of ${[...values].join(", ")}`);\n return value;\n}\nfunction parameterValue(value, label) {\n if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return;\n if (!isRecord(value) || Object.keys(value).some((key2) => key2 !== "provider" && key2 !== "model") || typeof value.provider !== "string" || !value.provider || typeof value.model !== "string" || !value.model) {\n throw invalid2(`${label} must be a string, finite number, boolean or { provider, model } route`);\n }\n}\nfunction parameterMap(value, label) {\n if (!isRecord(value)) throw invalid2(`${label} must be an object`);\n for (const [key2, item] of Object.entries(value)) parameterValue(item, `${label}.${key2}`);\n}\nfunction parameterValues(value) {\n if (value === void 0) return;\n if (!isRecord(value) || Object.keys(value).some((key2) => key2 !== "workflow" && key2 !== "modules")) {\n throw invalid2("parameters must contain only workflow and modules dictionaries");\n }\n if (value.workflow !== void 0) parameterMap(value.workflow, "parameters.workflow");\n if (value.modules !== void 0) {\n if (!isRecord(value.modules)) throw invalid2("parameters.modules must be an object");\n for (const [instanceId, parameters] of Object.entries(value.modules)) parameterMap(parameters, `parameters.modules.${instanceId}`);\n }\n}\nfunction canonicalParameters(input4) {\n parameterValues(input4.parameters);\n const alias = input4.outputResolution === void 0 ? void 0 : member(input4.outputResolution, resolutions, "outputResolution");\n if (alias === void 0) return input4.parameters;\n const canonical2 = input4.parameters?.workflow?.output_resolution;\n if (canonical2 !== void 0 && canonical2 !== alias) {\n throw invalid2("outputResolution conflicts with parameters.workflow.output_resolution");\n }\n return { ...input4.parameters, workflow: { ...input4.parameters?.workflow, output_resolution: alias } };\n}\nfunction propertyJson(value, label, parents) {\n if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return;\n if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n throw invalid2(`${label} must be a JSON value`);\n }\n if (parents.has(value)) throw invalid2(`${label} must not contain a cycle`);\n parents.add(value);\n for (const item of Array.isArray(value) ? value : Object.values(value)) propertyJson(item, label, parents);\n parents.delete(value);\n}\nfunction properties(value) {\n if (value === void 0) return;\n if (!isRecord(value)) throw invalid2("properties must be an object keyed by workflow step");\n for (const [step3, values] of Object.entries(value)) {\n if (!videoStepIdPattern.test(step3)) throw invalid2(`properties.${step3} is not a workflow step id`);\n if (!isRecord(values)) throw invalid2(`properties.${step3} must be an object`);\n for (const [key2, item] of Object.entries(values)) {\n if (!workflowId.test(key2)) throw invalid2(`properties.${step3} has an invalid property key`);\n propertyJson(item, `properties.${step3}.${key2}`, /* @__PURE__ */ new Set());\n }\n }\n}\nfunction videoRequestWire(input4) {\n if (!isRecord(input4)) throw invalid2("A video request is required");\n const legacy = ["profile", "contentLocale", "qualityProfile", "referenceAssetIds", "referenceMetadata", "studioReferenceIds", "imageAssetId", "circuitFormat", "generationUsage"].find((field3) => input4[field3] !== void 0);\n if (legacy) throw invalid2(`${legacy} is not a video request field: choose a workflow and pass references (see the 6.0.0 migration guide)`);\n if (typeof input4.prompt !== "string" || !input4.prompt.trim()) throw invalid2("prompt must be a non-empty string");\n if (input4.referencePreparation !== void 0 && input4.referencePreparation !== "auto") throw invalid2("referencePreparation must be auto when provided");\n if (input4.references !== void 0 && !Array.isArray(input4.references)) throw invalid2("references must be a list");\n if (input4.sourceAnalysisId !== void 0 && (typeof input4.sourceAnalysisId !== "string" || !isUuid(input4.sourceAnalysisId.trim()))) {\n throw invalid2("sourceAnalysisId must be the id of an analyse-video generation");\n }\n const parameters = canonicalParameters(input4);\n properties(input4.properties);\n return {\n api: 2,\n workflow: videoWorkflowRef(input4.workflow),\n goal: input4.prompt.trim(),\n duration_seconds: positiveInteger(input4.durationSeconds, "durationSeconds"),\n speech: member(input4.speech, speechModes, "speech"),\n aspect_ratio: member(input4.aspectRatio, aspectRatios, "aspectRatio", "9:16"),\n locale: member(input4.locale, locales, "locale", "fr-FR"),\n ...parameters === void 0 ? {} : { parameters },\n ...input4.properties === void 0 ? {} : { properties: input4.properties },\n ...input4.references === void 0 ? {} : { references: input4.references.map(reference) },\n ...input4.referencePreparation ? { reference_preparation: "auto" } : {},\n ...input4.sourceAnalysisId === void 0 ? {} : { source_analysis_id: input4.sourceAnalysisId.trim().toLowerCase() },\n ...input4.effort === void 0 ? {} : { effort: member(input4.effort, efforts, "effort") }\n };\n}\nfunction videoCreateWire(input4) {\n const request2 = videoRequestWire(input4);\n return { ...request2, ...videoNotifyWire(input4), confirmed_maximum_microcredits: confirmedMaximum(input4.confirmedMaximumMicrocredits) };\n}\nfunction videoNotifyWire(input4) {\n const notify2 = input4.notify;\n if (notify2 === void 0) return {};\n if (!isRecord(notify2) || typeof notify2.dedupeKey !== "string" || !/^[A-Za-z0-9_-]+$/.test(notify2.dedupeKey)) {\n throw invalid2("notify needs a dedupeKey made of letters, digits, - and _");\n }\n if (!isRecord(notify2.messages)) throw invalid2("notify needs messages for succeeded and failed");\n const { succeeded, failed, cancelled, stages: stages2 } = notify2.messages;\n if (stages2 !== void 0 && (!isRecord(stages2) || Object.keys(stages2).some((stage) => !videoStages.includes(stage)))) {\n throw invalid2(`notify messages stages are keyed by ${videoStages.join(", ")}`);\n }\n return { notify: {\n dedupe_key: notify2.dedupeKey,\n ...notify2.search === void 0 ? {} : { search: notifySearch(notify2.search) },\n messages: {\n succeeded: notifyMessage(succeeded, "succeeded"),\n failed: notifyMessage(failed, "failed"),\n ...cancelled === void 0 ? {} : { cancelled: notifyMessage(cancelled, "cancelled") },\n ...stages2 === void 0 ? {} : { stages: Object.fromEntries(Object.entries(stages2).map(([stage, message2]) => [stage, notifyMessage(message2, stage)])) }\n }\n } };\n}\nfunction notifyMessage(value, label) {\n if (!isRecord(value) || typeof value.title !== "string" || !value.title.trim()) throw invalid2(`notify message ${label} needs a title`);\n if (value.body !== void 0 && typeof value.body !== "string") throw invalid2(`notify message ${label} body must be a string`);\n return { title: value.title, ...value.body === void 0 ? {} : { body: value.body } };\n}\nfunction notifySearch(value) {\n const location2 = typeof value === "string" && value.startsWith("?") ? normalizeExperienceLocation({ pathname: "/", search: value, hash: "" }) : null;\n if (!location2 || location2.pathname !== "/" || location2.hash || !location2.search) throw invalid2("notify search must be a query such as ?film=<key>");\n return location2.search;\n}\nfunction confirmedMaximum(value) {\n if (!isMicrocredits(value)) throw invalid2("confirmedMaximumMicrocredits must be a positive integer string");\n return value;\n}\nfunction videoWorkflowsWire(input4) {\n if (input4 === void 0) return {};\n if (!isRecord(input4)) throw invalid2("workflows takes { durationSeconds?, family? }");\n return {\n ...input4.durationSeconds === void 0 ? {} : { duration_seconds: positiveInteger(input4.durationSeconds, "durationSeconds") },\n ...input4.family === void 0 ? {} : { family: member(input4.family, videoWorkflowFamilies, "family") }\n };\n}\n\n// src/video-playback.ts\nasync function readVideoPlayback(context, input4, options = {}) {\n const id = videoId(isRecord(input4) ? input4.id : void 0);\n return openHostPlayback(context, {\n operation: "get",\n label: "video.playback",\n input: { id },\n options,\n route: "media",\n accept: (result2) => result2.id === id && result2.mimeType === "video/mp4" ? "video/mp4" : void 0\n });\n}\nasync function openHostPlayback(context, read4) {\n const { options } = read4;\n if (!isRecord(options)) throw invalid2("Request options must be an object");\n if (options.signal !== void 0 && !(options.signal instanceof AbortSignal)) throw invalid2("signal must be an AbortSignal");\n const timeout = options.timeoutMs ?? operationWaiting.video.default;\n if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0 || timeout > 2147483647) throw invalid2("timeoutMs must be a positive finite timer duration");\n assertHostCapability("video");\n if (context.usageId === void 0) throw new NochaError("usage_required", `${read4.label} requires nocha.use(<declared usage id>)`);\n if (options.signal?.aborted) throw new NochaError("aborted", "Video playback aborted");\n const requestId = crypto.randomUUID();\n const path = new RegExp(`^/api/video/[0-9a-f-]{36}/${read4.route}$`, "i");\n return new Promise((resolve2, reject2) => {\n let accepted = false;\n const cleanup = () => {\n clearTimeout(timer);\n clearTimeout(unanswered);\n window.removeEventListener("message", receive);\n options.signal?.removeEventListener("abort", abort);\n };\n const stop = (error) => {\n cleanup();\n try {\n postToHost({ protocol: NOCHA_VIDEO_PLAYBACK_PROTOCOL, type: "abort", requestId });\n } catch {\n }\n reject2(error);\n };\n const abort = () => stop(new NochaError("aborted", "Video playback aborted"));\n const receive = (event) => {\n const message2 = event.data;\n if (!isFromHost(event) || !isRecord(message2) || message2.protocol !== NOCHA_VIDEO_PLAYBACK_PROTOCOL || message2.requestId !== requestId) return;\n clearTimeout(unanswered);\n if (message2.type === "accepted") {\n accepted = true;\n return;\n }\n if (message2.type !== "result" && message2.type !== "error") return;\n cleanup();\n if (message2.type === "error") {\n const unsupported = read4.operation !== "get" && !accepted && isRecord(message2.error) && message2.error.code === "invalid_request";\n reject2(unsupported ? new NochaError("playback_unsupported_host", "Update the Nocha host to read project media") : wireError(message2.error, { code: "media_unavailable", message: "Video playback is unavailable" }));\n return;\n }\n const result2 = message2.result;\n const mimeType = isRecord(result2) ? read4.accept(result2) : void 0;\n if (isRecord(result2) && mimeType && typeof result2.url === "string" && typeof result2.expiresAt === "string" && Number.isFinite(Date.parse(result2.expiresAt)) && Date.parse(result2.expiresAt) > Date.now()) {\n try {\n const url = new URL(result2.url);\n if ((url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && !url.hash && path.test(url.pathname) && url.searchParams.get("token") && Array.from(url.searchParams.keys()).every((key2) => key2 === "token")) {\n resolve2({ url: url.href, expiresAt: result2.expiresAt, mimeType });\n return;\n }\n } catch {\n }\n }\n reject2(new NochaError("invalid_result", "Nocha returned an invalid video playback URL"));\n };\n const unanswered = setTimeout(() => stop(new NochaError("playback_unsupported_host", "Update the Nocha host to stream video playback")), Math.min(timeout, 15e3));\n const timer = setTimeout(() => stop(new NochaError("invocation_timed_out", "Local video playback authorization timed out")), timeout);\n window.addEventListener("message", receive);\n options.signal?.addEventListener("abort", abort, { once: true });\n try {\n postToHost({ protocol: NOCHA_VIDEO_PLAYBACK_PROTOCOL, type: "open", requestId, capability: "video", operation: read4.operation, usageId: context.usageId, input: read4.input });\n } catch (cause) {\n cleanup();\n reject2(new NochaError("invalid_request", `The request cannot be sent to the Nocha host: ${String(cause)}`));\n }\n });\n}\n\n// src/video-projects.ts\nvar identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;\nvar settingKeys3 = /* @__PURE__ */ new Set(["video", "resolution", "model_quality", "aspect_ratio", "upscale_4k", "native_audio"]);\nvar mediaTypes2 = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp", "video/mp4"]);\nfunction identifier2(value, label) {\n if (typeof value !== "string" || !identifierPattern.test(value.trim())) throw invalid2(`A valid ${label} is required`);\n return value.trim();\n}\nfunction revision(value, label) {\n if (typeof value !== "string" || !value || value.length > 200) throw invalid2(`${label} must be a project revision`);\n return value;\n}\nfunction settings(value) {\n if (!isRecord(value) || !Object.keys(value).length || Object.keys(value).some((key2) => !settingKeys3.has(key2))) {\n throw invalid2(`settings takes at least one of ${Array.from(settingKeys3).join(", ")}`);\n }\n return value;\n}\nfunction confirmed(value) {\n if (value !== true) throw new NochaError("user_action_required", "The participant must confirm this change");\n const activation = globalThis.navigator?.userActivation;\n if (activation && activation.isActive === false) throw new NochaError("user_action_required", "Call this from the participant\'s gesture");\n return true;\n}\nfunction invoke(context, operation2, input4, options) {\n return context.invoke(videoOperationDefinitions[operation2].capability, videoOperationDefinitions[operation2].operation, input4, options);\n}\nfunction project(value, label) {\n if (!isRecord(value) || typeof value.id !== "string" || typeof value.revision !== "string") throw invalidResult(`Nocha returned an invalid ${label}`);\n return value;\n}\nfunction state2(value) {\n const read4 = project(value, "Tripirl project");\n if (!isRecord(read4.settings) || !isRecord(read4.actions) || !isRecord(read4.options)) throw invalidResult("Nocha returned an invalid Tripirl project");\n return read4;\n}\nfunction notModified(value) {\n return isRecord(value) && value.not_modified === true;\n}\nfunction read3(input4) {\n if (!isRecord(input4)) throw invalid2("A project request is required");\n return {\n project_id: identifier2(input4.projectId, "project id"),\n ...input4.ifNoneMatch === void 0 ? {} : { if_none_match: revision(input4.ifNoneMatch, "ifNoneMatch") }\n };\n}\nfunction change(input4) {\n if (!isRecord(input4)) throw invalid2("A project request is required");\n return { project_id: identifier2(input4.projectId, "project id"), expected_revision: revision(input4.expectedRevision, "expectedRevision") };\n}\nasync function list2(context, input4 = {}, options) {\n if (!isRecord(input4) || input4.limit !== void 0 && (!Number.isInteger(input4.limit) || input4.limit < 1 || input4.limit > 50) || input4.cursor !== void 0 && (typeof input4.cursor !== "string" || !input4.cursor)) throw invalid2("list takes a limit from 1 to 50 and a string cursor");\n const value = await invoke(context, "projects.list", { ...input4.cursor ? { cursor: input4.cursor } : {}, ...input4.limit === void 0 ? {} : { limit: input4.limit } }, options);\n if (!isRecord(value) || !Array.isArray(value.items) || !(value.next_cursor === null || typeof value.next_cursor === "string")) throw invalidResult("Nocha returned an invalid project list");\n return { items: value.items.map((item) => project(item, "Tripirl project")), next_cursor: value.next_cursor };\n}\nasync function get3(context, input4, options) {\n const value = await invoke(context, "projects.get", read3(input4), options);\n return notModified(value) ? value : state2(value);\n}\nasync function artifacts(context, input4, options) {\n const value = await invoke(context, "projects.artifacts", read3(input4), options);\n if (notModified(value)) return value;\n if (!isRecord(value) || typeof value.revision !== "string" || !["references", "world_references", "storyboards", "clips"].every((key2) => Array.isArray(value[key2]))) {\n throw invalidResult("Nocha returned invalid project artifacts");\n }\n return value;\n}\nasync function media(context, input4, options = {}) {\n if (!isRecord(input4)) throw invalid2("A project media request is required");\n const projectId = identifier2(input4.projectId, "project id"), mediaId = identifier2(input4.mediaId, "media id");\n const link = await openHostPlayback(context, {\n operation: "projects.media",\n label: "video.projects.media",\n input: { project_id: projectId, media_id: mediaId },\n options,\n route: "project-media",\n accept: (result2) => result2.id === mediaId && mediaTypes2.has(result2.mimeType) ? result2.mimeType : void 0\n });\n return { id: mediaId, ...link };\n}\nasync function preview(context, input4, options) {\n const value = await invoke(context, "projects.previewSettings", { ...change(input4), settings: settings(isRecord(input4) ? input4.settings : void 0) }, options);\n if (!isRecord(value) || typeof value.revision !== "string" || !Array.isArray(value.steps) || !Array.isArray(value.changes)) throw invalidResult("Nocha returned an invalid settings preview");\n return value;\n}\nasync function update(context, input4, options) {\n const request2 = { ...change(input4), settings: settings(isRecord(input4) ? input4.settings : void 0), confirmed: confirmed(isRecord(input4) ? input4.confirmed : void 0) };\n return state2(await invoke(context, "projects.updateSettings", request2, options));\n}\nasync function resume(context, input4, options) {\n const request2 = { ...change(input4), confirmed: confirmed(isRecord(input4) ? input4.confirmed : void 0) };\n return state2(await invoke(context, "projects.resume", request2, options));\n}\nasync function cancel(context, input4, options) {\n return state2(await invoke(context, "projects.cancel", change(input4), options));\n}\nvar uuidPattern3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nasync function addReference(context, input4, options) {\n if (!isRecord(input4) || typeof input4.assetId !== "string" || !uuidPattern3.test(input4.assetId)) throw invalid2("addReference takes the assetId of a video");\n const title = typeof input4.title === "string" ? input4.title.trim().slice(0, 200) : "";\n const value = await invoke(context, "projects.addReference", {\n ...input4.projectId === void 0 ? {} : { project_id: identifier2(input4.projectId, "project id") },\n asset_id: input4.assetId,\n ...title ? { title } : {}\n }, options);\n if (!isRecord(value) || typeof value.projectId !== "string" || typeof value.sourceId !== "string" || typeof value.url !== "string") {\n throw invalidResult("Nocha returned an invalid project reference");\n }\n return { projectId: value.projectId, sourceId: value.sourceId, url: value.url };\n}\nfunction createVideoProjects(context) {\n return Object.freeze({\n list: (input4, options) => list2(context, input4, options),\n get: (input4, options) => get3(context, input4, options),\n artifacts: (input4, options) => artifacts(context, input4, options),\n media: (input4, options) => media(context, input4, options),\n cancel: (input4, options) => cancel(context, input4, options),\n previewSettings: (input4, options) => preview(context, input4, options),\n updateSettings: (input4, options) => update(context, input4, options),\n resume: (input4, options) => resume(context, input4, options),\n addReference: (input4, options) => addReference(context, input4, options)\n });\n}\n\n// src/video-media.ts\nfunction isMediaResult(value, id) {\n return isRecord(value) && value.id === id && value.mime_type === "video/mp4" && value.blob instanceof Blob && value.blob.type === "video/mp4" && value.blob.size > 0 && value.size_bytes === value.blob.size;\n}\nasync function readVideoMedia(context, input4, options = {}) {\n const id = videoId(isRecord(input4) ? input4.id : void 0);\n const timeout = mediaReadTimeout(options, operationWaiting.video.media);\n assertHostCapability("video");\n const usageId = context.usageId;\n if (usageId === void 0) throw new NochaError("usage_required", "video.media requires nocha.use(<declared usage id>)");\n if (options.signal?.aborted) throw new NochaError("aborted", "Video read aborted");\n return readHostMedia({\n noun: "video",\n timeoutMs: timeout,\n firstReplyMs: operationWaiting.video["media.firstReply"],\n options,\n accept: (result2) => isMediaResult(result2, id) ? result2.blob : void 0,\n send: (requestId) => postToHost({\n protocol: NOCHA_MEDIA_PROTOCOL,\n type: "read",\n requestId,\n capability: videoOperationDefinitions["get"].capability,\n operation: videoOperationDefinitions["get"].operation,\n usageId,\n input: { id }\n })\n });\n}\n\n// src/video-resource.ts\nvar string2 = (value) => typeof value === "string";\nvar text4 = (value) => string2(value) ? value : null;\nvar count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\nvar measure = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;\nvar credits2 = (value) => string2(value) && /^\\d+$/.test(value);\nvar pick2 = (value, values) => string2(value) && values.includes(value) ? value : null;\nvar keep = (value, values) => Array.isArray(value) ? value.filter((item) => pick2(item, values) !== null) : [];\nvar counts = (value) => Array.isArray(value) ? value.filter(count) : [];\nvar records2 = (value) => Array.isArray(value) ? value.filter(isRecord) : [];\nvar optionalText = (value, key2) => string2(value[key2]) ? { [key2]: value[key2] } : {};\nvar families = ["classic", "narrative", "image_loop", "analysis"];\nvar kinds = ["film", "image_loop", "analysis"];\nvar speech = ["none", "auto", "required"];\nvar ratios = ["9:16", "16:9", "1:1"];\nvar locales2 = videoLocales;\nvar resolutions2 = ["720p", "1080p"];\nvar efforts2 = ["auto", "low", "medium", "high"];\nvar stages = ["preparing", "planning", "generating_speech", "generating_media", "assembling"];\nvar costEffects = ["none", "may_change_quantity", "may_change_unit_price", "may_change_route"];\nvar resumeReasons = [\n "interrupted",\n "inputs_changed",\n "provider_unavailable",\n "storage_full",\n "paid_work_retained",\n "retryable_failure",\n "final_failure",\n "budget_exhausted",\n "workflow_taken_over",\n "media_expired"\n];\nvar resumeActions = ["keep", "redo", "run"];\nfunction resume2(value) {\n if (value === void 0) return void 0;\n if (!isRecord(value)) return null;\n const estimated = value.estimated_microcredits;\n if (typeof value.available !== "boolean" || !credits2(value.remaining_microcredits) || !(estimated === null || credits2(estimated))) return null;\n return {\n available: value.available,\n reason: pick2(value.reason, resumeReasons),\n steps: records2(value.steps).flatMap((step3) => {\n const action = pick2(step3.action, resumeActions);\n return string2(step3.id) && action && typeof step3.paid === "boolean" ? [{ id: step3.id, action, paid: step3.paid }] : [];\n }),\n estimated_microcredits: estimated,\n remaining_microcredits: value.remaining_microcredits\n };\n}\nvar scalar = (value) => typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);\nfunction parameterValue2(value) {\n if (scalar(value)) return value;\n return isRecord(value) && string2(value.provider) && string2(value.model) ? { provider: value.provider, model: value.model } : void 0;\n}\nfunction parameterMap2(value) {\n if (!isRecord(value)) return void 0;\n return Object.fromEntries(Object.entries(value).flatMap(([key2, item]) => {\n const parsed = parameterValue2(item);\n return parsed === void 0 ? [] : [[key2, parsed]];\n }));\n}\nfunction parameterValues2(value) {\n if (!isRecord(value)) return void 0;\n const workflow2 = parameterMap2(value.workflow);\n const modules = isRecord(value.modules) ? Object.fromEntries(Object.entries(value.modules).flatMap(([instanceId, item]) => {\n const parsed = parameterMap2(item);\n return parsed === void 0 ? [] : [[instanceId, parsed]];\n })) : void 0;\n return { ...workflow2 === void 0 ? {} : { workflow: workflow2 }, ...modules === void 0 ? {} : { modules } };\n}\nfunction parameterDefinition(value) {\n const scope = pick2(value.scope, ["workflow", "module"]);\n const costEffect = pick2(value.cost_effect, costEffects);\n const moduleId = value.module_id, instanceId = value.module_instance_id;\n const identity2 = scope === "workflow" ? moduleId === null && instanceId === null : scope === "module" && string2(moduleId) && string2(instanceId);\n const defaultValue = value.default === null ? null : parameterValue2(value.default);\n if (!string2(value.key) || !scope || !costEffect || !identity2 || defaultValue === void 0) return null;\n const base2 = {\n key: value.key,\n scope,\n module_id: moduleId,\n module_instance_id: instanceId,\n default: defaultValue,\n cost_effect: costEffect\n };\n const constraints = isRecord(value.constraints) ? value.constraints : null;\n if (value.type === "boolean" && value.constraints === null) return { ...base2, type: "boolean", constraints: null };\n if ((value.type === "integer" || value.type === "number") && constraints) {\n const values = Object.fromEntries(["minimum", "maximum", "step"].flatMap((key2) => typeof constraints[key2] === "number" && Number.isFinite(constraints[key2]) ? [[key2, constraints[key2]]] : []));\n return { ...base2, type: value.type, constraints: values };\n }\n if (value.type === "string" && constraints) {\n return { ...base2, type: "string", constraints: count(constraints.max_length) ? { max_length: constraints.max_length } : {} };\n }\n if (value.type === "enum" && constraints && Array.isArray(constraints.values) && constraints.values.every(scalar)) {\n return { ...base2, type: "enum", constraints: { values: constraints.values } };\n }\n if (value.type === "route" && constraints?.need === "video.generate" && Array.isArray(constraints.routes)) {\n const routes = constraints.routes.map(parameterValue2).filter((route) => isRecord(route));\n if (routes.length === constraints.routes.length) return { ...base2, type: "route", constraints: { need: "video.generate", routes } };\n }\n return null;\n}\nfunction failure3(value) {\n return isRecord(value) && string2(value.code) && string2(value.message) ? { code: value.code, message: value.message, retryable: value.retryable === true } : null;\n}\nfunction result(value) {\n if (value === null) return null;\n if (isRecord(value) && value.kind !== void 0) return readVideoAnalysisResult(value);\n if (!isRecord(value) || measure(value.actual_duration_seconds) === null || !string2(value.download_url) || !string2(value.download_url_expires_at) || value.mime_type !== "video/mp4" || !string2(value.sha256) || !count(value.size_bytes)) return void 0;\n return {\n actual_duration_seconds: value.actual_duration_seconds,\n download_url: value.download_url,\n download_url_expires_at: value.download_url_expires_at,\n mime_type: "video/mp4",\n sha256: value.sha256,\n size_bytes: value.size_bytes,\n ...string2(value.filename) && value.filename.trim().length > 0 && value.filename.length <= 255 ? { filename: value.filename } : {},\n ...string2(value.asset_id) && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.asset_id) ? { asset_id: value.asset_id } : {},\n ...count(value.width) && value.width > 0 ? { width: value.width } : {},\n ...count(value.height) && value.height > 0 ? { height: value.height } : {},\n ...pick2(value.aspect_ratio, ratios) ? { aspect_ratio: pick2(value.aspect_ratio, ratios) } : {}\n };\n}\nfunction workflowRef(value) {\n if (!isRecord(value) || !string2(value.id) || !value.id) return null;\n return { id: value.id, family: pick2(value.family, families), revision: count(value.revision) ? value.revision : null, digest: text4(value.digest), ...optionalText(value, "name") };\n}\nfunction automation(value) {\n if (!isRecord(value) || !string2(value.id) || !string2(value.started_at) || !string2(value.updated_at)) return void 0;\n return {\n id: value.id,\n status: pick2(value.status, ["running", "stopping", "completed", "blocked", "cancelled"]),\n started_at: value.started_at,\n updated_at: value.updated_at,\n finished_at: text4(value.finished_at),\n error: failure3(value.error),\n steps: records2(value.steps).filter((step3) => string2(step3.id)).map((step3) => ({\n id: step3.id,\n operation: text4(step3.operation),\n status: pick2(step3.status, ["pending", "queued", "running", "retrying", "completed", "partial", "blocked", "cancelled", "skipped"]),\n freshness: pick2(step3.freshness, ["fresh", "outdated", "update_available", "missing"]),\n produced_by: isRecord(step3.produced_by) && string2(step3.produced_by.module_id) && count(step3.produced_by.revision) ? { module_id: step3.produced_by.module_id, revision: step3.produced_by.revision } : null,\n jobs_count: count(step3.jobs_count) ? step3.jobs_count : 0,\n error: failure3(step3.error)\n })),\n jobs: records2(value.jobs).filter((job) => string2(job.id) && string2(job.operation) && string2(job.created_at) && string2(job.updated_at)).map((job) => {\n const progress = isRecord(job.progress) ? job.progress : {};\n const module = isRecord(job.module) && string2(job.module.id) && string2(job.module.instance_id) && count(job.module.revision) ? { id: job.module.id, instance_id: job.module.instance_id, revision: job.module.revision } : null;\n return {\n id: job.id,\n step_id: text4(job.step_id),\n operation: job.operation,\n module,\n status: pick2(job.status, ["queued", "running", "retrying", "succeeded", "failed", "cancelled", "blocked"]),\n attempt: count(job.attempt) ? job.attempt : null,\n progress: { percent: measure(progress.percent), completed_units: measure(progress.completed_units), total_units: measure(progress.total_units) },\n created_at: job.created_at,\n started_at: text4(job.started_at),\n updated_at: job.updated_at,\n finished_at: text4(job.finished_at),\n error: failure3(job.error)\n };\n }),\n jobs_total: count(value.jobs_total) ? value.jobs_total : 0,\n jobs_truncated: value.jobs_truncated === true\n };\n}\nfunction readVideoGeneration(value) {\n if (!isRecord(value) || !string2(value.id) || !value.id || !string2(value.created_at) || !string2(value.updated_at)) return null;\n const output = result(value.result);\n if (output === void 0) return null;\n if (value.audience_view === "shared") {\n if (value.status !== "succeeded" || !output || !string2(value.collection_id)) return null;\n return {\n audience_view: "shared",\n id: value.id,\n collection_id: value.collection_id,\n kind: pick2(value.kind, kinds),\n status: "succeeded",\n created_at: value.created_at,\n updated_at: value.updated_at,\n result: output\n };\n }\n const workflow2 = workflowRef(value.workflow);\n const request2 = isRecord(value.request) ? value.request : null;\n const requested = request2 ? workflowRef({ ...isRecord(request2.workflow) ? request2.workflow : {}, family: null }) : null;\n const progress = isRecord(value.progress) ? value.progress : null;\n const cost = isRecord(value.cost) ? value.cost : null;\n if (!workflow2 || !request2 || !requested || !string2(request2.goal) || !count(request2.duration_seconds) || !progress || measure(progress.percent) === null || !credits2(value.estimated_maximum_microcredits) || !cost || !credits2(cost.total_microcredits)) return null;\n const parameters = isRecord(value.parameters) ? value.parameters : null;\n const generation = parameters && isRecord(parameters.generation) ? parameters.generation : null;\n const requestedParameters = parameterValues2(request2.parameters);\n const requestedProperties = readVideoProperties(request2.properties);\n const effectiveProperties = readEffectiveVideoProperties(value.properties);\n const effectiveWorkflow = parameters ? parameterMap2(parameters.workflow) : void 0;\n const effectiveModules = parameters && isRecord(parameters.modules) ? Object.fromEntries(Object.entries(parameters.modules).flatMap(([instanceId, item]) => {\n if (!isRecord(item) || !string2(item.module_id)) return [];\n const values = parameterMap2(item.values);\n return values === void 0 ? [] : [[instanceId, { module_id: item.module_id, values }]];\n })) : void 0;\n const origin = isRecord(value.origin) && value.origin.type === "nocha_experience" && ["experience_id", "experience_code", "experience_title", "revision_id"].every((key2) => string2(value.origin[key2])) ? value.origin : null;\n const access2 = isRecord(value.automation_access) ? value.automation_access : null;\n const automationValue = automation(value.automation);\n const resumeValue = resume2(value.resume);\n const editPlan = readVideoEditPlan(value.edit_plan);\n const reviewWarnings = readVideoReviewWarnings(value.review_warnings);\n const generationValue = {\n audience_view: "author",\n id: value.id,\n status: pick2(value.status, ["queued", "running", "cancelling", "succeeded", "failed", "cancelled"]),\n kind: pick2(value.kind, kinds),\n workflow: workflow2,\n request: {\n workflow: { id: requested.id, ...requested.revision === null ? {} : { revision: requested.revision } },\n goal: request2.goal,\n duration_seconds: request2.duration_seconds,\n aspect_ratio: pick2(request2.aspect_ratio, ratios),\n locale: pick2(request2.locale, locales2),\n speech: pick2(request2.speech, speech),\n ...request2.output_resolution === void 0 ? {} : { output_resolution: pick2(request2.output_resolution, resolutions2) },\n ...request2.parameters === void 0 ? {} : { parameters: requestedParameters ?? {} },\n ...requestedProperties === void 0 ? {} : { properties: requestedProperties },\n ...request2.reference_preparation === "auto" ? { reference_preparation: "auto" } : {},\n ...string2(request2.source_analysis_id) && request2.source_analysis_id ? { source_analysis_id: request2.source_analysis_id } : {},\n ...request2.effort === void 0 ? {} : { effort: pick2(request2.effort, efforts2) },\n collection_id: text4(request2.collection_id),\n confirmed_maximum_microcredits: credits2(request2.confirmed_maximum_microcredits) ? request2.confirmed_maximum_microcredits : null\n },\n parameters: parameters && count(parameters.duration_seconds) ? {\n duration_seconds: parameters.duration_seconds,\n aspect_ratio: pick2(parameters.aspect_ratio, ratios),\n locale: pick2(parameters.locale, locales2),\n speech: pick2(parameters.speech, speech),\n output_resolution: pick2(parameters.output_resolution, resolutions2),\n reference_count: count(parameters.reference_count) ? parameters.reference_count : 0,\n ...parameters.reference_preparation === "auto" ? { reference_preparation: "auto" } : {},\n ...generation ? { generation: {\n intensity: pick2(generation.intensity, ["low", "medium", "high"]),\n ...count(generation.preference_revision) ? { preference_revision: generation.preference_revision } : {},\n ...string2(generation.policy_signature) ? { policy_signature: generation.policy_signature } : {}\n } } : {},\n ...effectiveWorkflow === void 0 ? {} : { workflow: effectiveWorkflow },\n ...effectiveModules === void 0 ? {} : { modules: effectiveModules }\n } : null,\n ...effectiveProperties === void 0 ? {} : { properties: effectiveProperties },\n references: records2(value.references).filter((item) => string2(item.asset_id)).map((item) => {\n const replaces2 = readVideoReferenceReplaces(item.replaces);\n return {\n asset_id: item.asset_id,\n ...optionalText(item, "role"),\n ...optionalText(item, "name"),\n ...optionalText(item, "description"),\n ...replaces2 ? { replaces: replaces2 } : {},\n availability: pick2(item.availability, ["available", "expired", "pending"])\n };\n }),\n origin: origin ? {\n type: "nocha_experience",\n experience_id: origin.experience_id,\n experience_code: origin.experience_code,\n experience_title: origin.experience_title,\n revision_id: origin.revision_id\n } : null,\n progress: {\n percent: Math.min(100, progress.percent),\n stage: pick2(progress.stage, stages),\n ...progress.step === null || string2(progress.step) ? { step: progress.step } : {}\n },\n ...automationValue ? { automation: automationValue } : {},\n automation_access: access2 && typeof access2.read_only === "boolean" ? { read_only: access2.read_only, taken_over_at: text4(access2.taken_over_at), media_expired_at: text4(access2.media_expired_at) } : null,\n collection_id: text4(value.collection_id),\n estimated_maximum_microcredits: value.estimated_maximum_microcredits,\n cost: {\n total_microcredits: cost.total_microcredits,\n ...credits2(cost.base_charge_microcredits) ? { base_charge_microcredits: cost.base_charge_microcredits } : {},\n ...credits2(cost.creator_fee_microcredits) ? { creator_fee_microcredits: cost.creator_fee_microcredits } : {}\n },\n actual_duration_seconds: measure(value.actual_duration_seconds),\n error: failure3(value.error),\n ...resumeValue === void 0 ? {} : { resume: resumeValue },\n result: output,\n ...editPlan === void 0 ? {} : { edit_plan: editPlan },\n ...reviewWarnings?.length ? { review_warnings: reviewWarnings } : {},\n created_at: value.created_at,\n updated_at: value.updated_at\n };\n return generationValue;\n}\nfunction readVideoEstimate(value) {\n if (!isRecord(value) || !string2(value.maximum_microcredits) || !/^[1-9]\\d*$/.test(value.maximum_microcredits) || !string2(value.valid_until)) return null;\n const workflow2 = workflowRef(value.workflow);\n return workflow2 ? { maximum_microcredits: value.maximum_microcredits, valid_until: value.valid_until, workflow: workflow2 } : null;\n}\nfunction step2(value) {\n if (!string2(value.id)) return null;\n const module = isRecord(value.module) && string2(value.module.id) && string2(value.module.title) && count(value.module.revision) ? { id: value.module.id, title: value.module.title, revision: value.module.revision } : void 0;\n return {\n id: value.id,\n operation: text4(value.operation),\n lane: text4(value.lane),\n execution: pick2(value.execution, ["segment", "historical"]),\n ...module ? { module } : {},\n ...typeof value.restartable === "boolean" ? { restartable: value.restartable } : {},\n ...Array.isArray(value.properties) ? { properties: value.properties.flatMap((item) => {\n const definition = readVideoPropertyDefinition(item);\n return definition ? [definition] : [];\n }) } : {},\n modules: records2(value.modules).filter((item) => string2(item.id) && string2(item.instance_id) && string2(item.title) && count(item.revision)).map((item) => ({ id: item.id, instance_id: item.instance_id, title: item.title, revision: item.revision }))\n };\n}\nfunction referenceRole(value) {\n const media2 = pick2(value.media, ["image", "video", "audio"]);\n if (!string2(value.role) || !value.role || !media2 || !count(value.min) || !count(value.max) || value.max < 1) return null;\n return { role: value.role, media: media2, min: value.min, max: value.max, gap_seconds: measure(value.gap_seconds), crossfade_seconds: measure(value.crossfade_seconds) };\n}\nfunction readVideoWorkflow(value) {\n if (!isRecord(value) || !string2(value.id) || !value.id || !string2(value.name) || !isRecord(value.duration_seconds) || !isRecord(value.references)) return null;\n const durations = value.duration_seconds, references = value.references, availability = isRecord(value.availability) ? value.availability : {};\n if (!count(durations.min) || !count(durations.max) || !count(references.min) || !count(references.max)) return null;\n return {\n id: value.id,\n origin: pick2(value.origin, ["builtin", "saved"]),\n revision: count(value.revision) ? value.revision : null,\n latest_revision: count(value.latest_revision) ? value.latest_revision : null,\n digest: text4(value.digest),\n base_id: text4(value.base_id),\n name: value.name,\n description: string2(value.description) ? value.description : "",\n kind: pick2(value.kind, kinds),\n family: pick2(value.family, families),\n variant: pick2(value.variant, ["native", "voix", "bande-son", "video-noire", "micro", "live"]),\n duration_seconds: { min: durations.min, max: durations.max, allowed: Array.isArray(durations.allowed) ? counts(durations.allowed) : null },\n default_for_durations_seconds: counts(value.default_for_durations_seconds),\n aspect_ratios: keep(value.aspect_ratios, ratios),\n output_resolutions: keep(value.output_resolutions, resolutions2),\n locales: keep(value.locales, locales2),\n speech_modes: records2(value.speech_modes).flatMap((item) => {\n const mode = pick2(item.mode, speech);\n return mode ? [{ mode, durations_seconds: Array.isArray(item.durations_seconds) ? counts(item.durations_seconds) : null }] : [];\n }),\n references: {\n min: references.min,\n max: references.max,\n mime_types: Array.isArray(references.mime_types) ? references.mime_types.filter(string2) : [],\n requires_non_character: references.requires_non_character === true,\n roles: records2(references.roles).map(referenceRole).filter((item) => item !== null)\n },\n reference_preparation: value.reference_preparation === true,\n restart_from: Array.isArray(value.restart_from) ? value.restart_from.filter(string2) : [],\n provider_needs: Array.isArray(value.provider_needs) ? value.provider_needs.filter(string2) : [],\n interaction: pick2(value.interaction, ["none", "recordings", "live"]),\n steps: records2(value.steps).map(step2).filter((item) => item !== null),\n parameters: records2(value.parameters).map(parameterDefinition).filter((item) => item !== null),\n availability: availability.status === "available" ? { status: "available" } : {\n status: "unavailable",\n message: string2(availability.message) ? availability.message : "",\n reason: pick2(availability.reason, ["interactive", "providers", "modules", "render_target", "base", "unavailable"])\n }\n };\n}\n\n// src/video.ts\nvar connectionActions = /* @__PURE__ */ new Set(["status", "connect", "disconnect"]);\nvar active2 = /* @__PURE__ */ new Set(["queued", "running", "cancelling"]);\nvar invalidResult3 = (label) => new NochaError("invalid_result", `Nocha returned an invalid ${label}`);\nvar api = 2;\nfunction readable(value) {\n const generation = readVideoGeneration(value);\n if (!generation) throw invalidResult3("video generation");\n return generation;\n}\nfunction authored(value) {\n const generation = readable(value);\n if (generation.audience_view !== "author") throw invalidResult3("video generation");\n return generation;\n}\nasync function connection(context, input4 = {}, options) {\n const action = isRecord(input4) ? input4.action ?? "status" : void 0;\n if (!connectionActions.has(action)) throw invalid2("action must be status, connect or disconnect");\n const value = await context.invoke(videoOperationDefinitions["connection"].capability, videoOperationDefinitions["connection"].operation, { action }, options);\n if (!isRecord(value) || !["connected", "disconnected", "authorization_required"].includes(String(value.status)) || value.status === "connected" && (!Array.isArray(value.scopes) || !value.scopes.every((scope) => typeof scope === "string") || typeof value.connected_at !== "string") || value.status === "authorization_required" && typeof value.authorization_url !== "string") throw invalidResult3("video connection");\n return value;\n}\nasync function workflows(context, input4, options) {\n const value = await context.invoke(videoOperationDefinitions["workflows"].capability, videoOperationDefinitions["workflows"].operation, videoWorkflowsWire(input4), options);\n if (!isRecord(value) || !Array.isArray(value.items)) throw invalidResult3("video workflow list");\n return { items: value.items.map(readVideoWorkflow).filter((item) => item !== null) };\n}\nasync function workflow(context, input4, options) {\n const value = readVideoWorkflow(await context.invoke(videoOperationDefinitions["workflow"].capability, videoOperationDefinitions["workflow"].operation, videoWorkflowRef(input4, "input"), options));\n if (!value) throw invalidResult3("video workflow");\n return value;\n}\nasync function estimate2(context, input4, options) {\n const value = readVideoEstimate(await context.invoke(videoOperationDefinitions["estimate"].capability, videoOperationDefinitions["estimate"].operation, videoRequestWire(input4), options));\n if (!value) throw invalidResult3("video estimate");\n return value;\n}\nfunction paidOptions(operation2, options) {\n if (!isRecord(options) || typeof options.idempotencyKey !== "string" || !options.idempotencyKey) {\n throw new NochaError("invalid_request", `video.${operation2} requires a persisted idempotencyKey`);\n }\n return options;\n}\nasync function create(context, input4, options) {\n const keyed = paidOptions("create", options);\n return authored(await context.invoke(videoOperationDefinitions["create"].capability, videoOperationDefinitions["create"].operation, videoCreateWire(input4), keyed));\n}\nasync function list3(context, input4 = {}, options) {\n if (!isRecord(input4) || input4.limit !== void 0 && !Number.isInteger(input4.limit) || input4.cursor !== void 0 && typeof input4.cursor !== "string") {\n throw invalid2("list takes an integer limit and a string cursor");\n }\n const workflow2 = input4.workflow === void 0 ? void 0 : videoWorkflowRef({ id: input4.workflow }, "list workflow").id;\n const value = await context.invoke(videoOperationDefinitions["list"].capability, videoOperationDefinitions["list"].operation, {\n api,\n ...input4.cursor ? { cursor: input4.cursor } : {},\n ...input4.limit === void 0 ? {} : { limit: input4.limit },\n ...workflow2 ? { workflow: workflow2 } : {}\n }, options);\n if (!isRecord(value) || !Array.isArray(value.items) || !isRecord(value.pagination) || typeof value.pagination.has_more !== "boolean" || !(value.pagination.next_cursor === null || typeof value.pagination.next_cursor === "string")) throw invalidResult3("video generation list");\n return { items: value.items.map(readable), pagination: { has_more: value.pagination.has_more, next_cursor: value.pagination.next_cursor } };\n}\nasync function get4(context, input4, options) {\n return readable(await context.invoke(videoOperationDefinitions["get"].capability, videoOperationDefinitions["get"].operation, { api, id: videoId(isRecord(input4) ? input4.id : void 0) }, options));\n}\nasync function retry(context, input4, options) {\n const keyed = paidOptions("retry", options);\n if (!isRecord(input4)) throw invalid2("A retry request is required");\n if (input4.restartFrom !== void 0 && (typeof input4.restartFrom !== "string" || !input4.restartFrom.trim())) throw invalid2("restartFrom must be a step of the workflow");\n return authored(await context.invoke(videoOperationDefinitions["retry"].capability, videoOperationDefinitions["retry"].operation, {\n api,\n id: videoId(input4.id),\n confirmed_maximum_microcredits: confirmedMaximum(input4.confirmedMaximumMicrocredits),\n ...input4.restartFrom ? { restart_from: input4.restartFrom.trim() } : {}\n }, keyed));\n}\nasync function mutate(context, operation2, input4, options) {\n return authored(await context.invoke(videoOperationDefinitions[operation2].capability, videoOperationDefinitions[operation2].operation, { api, id: videoId(isRecord(input4) ? input4.id : void 0) }, options));\n}\nasync function setVisibility2(context, operation2, input4, options) {\n const id = videoId(isRecord(input4) ? input4.id : void 0);\n const value = await context.invoke(videoOperationDefinitions[operation2].capability, videoOperationDefinitions[operation2].operation, { api, id }, options);\n if (!isRecord(value) || value.id !== id || value.visibility !== "private" && value.visibility !== "shared") throw invalidResult3("video visibility");\n return { id, visibility: value.visibility };\n}\nfunction visibilityOperation(input4) {\n const visibility = isRecord(input4) ? input4.visibility : void 0;\n if (visibility !== "private" && visibility !== "shared") throw invalid2("visibility must be \'private\' or \'shared\'");\n return visibility === "shared" ? "share" : "unshare";\n}\nfunction pause(ms2, signal) {\n if (signal?.aborted) return Promise.reject(new NochaError("aborted", "Video wait was aborted"));\n const page = typeof document === "undefined" ? void 0 : document;\n return new Promise((resolve2, reject2) => {\n const cleanup = () => {\n clearTimeout(timer);\n signal?.removeEventListener("abort", onAbort);\n page?.removeEventListener("visibilitychange", onVisibility);\n };\n const done = () => {\n cleanup();\n resolve2();\n };\n const onAbort = () => {\n cleanup();\n reject2(new NochaError("aborted", "Video wait was aborted"));\n };\n const onVisibility = () => {\n if (!page?.hidden) done();\n };\n const timer = setTimeout(() => {\n if (!page?.hidden) done();\n }, ms2);\n signal?.addEventListener("abort", onAbort, { once: true });\n page?.addEventListener("visibilitychange", onVisibility);\n });\n}\nfunction nextInterval(startedAt, fixed) {\n if (fixed !== void 0) return fixed;\n const elapsed = Date.now() - startedAt;\n return elapsed < videoWaitSchedule.fastForMs ? videoWaitSchedule.fastMs : elapsed < videoWaitSchedule.steadyForMs ? videoWaitSchedule.steadyMs : videoWaitSchedule.slowMs;\n}\nasync function wait(context, input4, options = {}) {\n const id = videoId(isRecord(input4) ? input4.id : void 0);\n if (!isRecord(options)) throw invalid2("Wait options must be an object");\n if (options.intervalMs !== void 0 && (typeof options.intervalMs !== "number" || !Number.isFinite(options.intervalMs))) throw invalid2("intervalMs must be a number");\n const fixed = options.intervalMs === void 0 ? void 0 : Math.max(videoWaitSchedule.minimumIntervalMs, options.intervalMs);\n const startedAt = Date.now();\n let failures = 0;\n for (; ; ) {\n let current4;\n try {\n current4 = await get4(context, { id }, options.signal ? { signal: options.signal } : {});\n failures = 0;\n } catch (error) {\n if (!isNochaError(error) || !error.retryable || failures >= 3) throw error;\n failures += 1;\n if (options.onRetry) notifyListener((attempt) => options.onRetry(error, attempt), failures);\n await pause(nextInterval(startedAt, fixed), options.signal);\n continue;\n }\n if (options.onUpdate) notifyListener(options.onUpdate, current4);\n if (!active2.has(current4.status)) return current4;\n await pause(nextInterval(startedAt, fixed), options.signal);\n }\n}\nfunction createVideo(context) {\n return Object.freeze({\n connection: (input4, options) => connection(context, input4, options),\n workflows: (input4, options) => workflows(context, input4, options),\n workflow: (input4, options) => workflow(context, input4, options),\n estimate: (input4, options) => estimate2(context, input4, options),\n create: (input4, options) => create(context, input4, options),\n list: (input4, options) => list3(context, input4, options),\n get: (input4, options) => get4(context, input4, options),\n retry: (input4, options) => retry(context, input4, options),\n cancel: (input4, options) => mutate(context, "cancel", input4, options),\n remove: (input4, options) => mutate(context, "remove", input4, options),\n share: (input4, options) => setVisibility2(context, "share", input4, options),\n unshare: (input4, options) => setVisibility2(context, "unshare", input4, options),\n setVisibility: (input4, options) => visibilityOperation(input4) === "share" ? setVisibility2(context, "share", input4, options) : setVisibility2(context, "unshare", input4, options),\n wait: (input4, options) => wait(context, input4, options),\n playback: (input4, options) => readVideoPlayback(context, input4, options),\n media: (input4, options) => readVideoMedia(context, input4, options),\n clipping: createClipping(context),\n projects: createVideoProjects(context)\n });\n}\n\n// src/viewport.ts\nvar zeroSafeArea = Object.freeze({ top: 0, right: 0, bottom: 0, left: 0 });\nvar edges = ["top", "right", "bottom", "left"];\nvar cssFields = {\n layoutWidth: "--nocha-layout-width",\n layoutHeight: "--nocha-layout-height",\n visualWidth: "--nocha-viewport-width",\n visualHeight: "--nocha-viewport-height",\n offsetTop: "--nocha-viewport-offset-top",\n offsetLeft: "--nocha-viewport-offset-left",\n keyboardInset: "--nocha-keyboard-inset"\n};\nfunction editable2(element2) {\n return element2 instanceof HTMLElement && (element2.isContentEditable || element2 instanceof HTMLTextAreaElement && !element2.disabled && !element2.readOnly || element2 instanceof HTMLInputElement && !element2.disabled && !element2.readOnly && !["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "hidden"].includes(element2.type));\n}\nfunction revealFocus(viewport) {\n if (Math.abs(viewport.scale - 1) >= 0.05) return;\n const input4 = document.activeElement;\n if (!editable2(input4)) return;\n const style2 = getComputedStyle(document.documentElement);\n const inset = (edge2) => Math.max(0, Number.parseFloat(style2.getPropertyValue(`--nocha-safe-area-inset-${edge2}`)) || 0);\n const top = Math.max(viewport.offsetTop, inset("top")) + 12;\n const bottom = Math.min(viewport.offsetTop + viewport.visualHeight, viewport.layoutHeight - inset("bottom")) - 12;\n if (bottom <= top) return;\n for (let parent = input4.parentElement; parent; parent = parent.parentElement) {\n const parentStyle = getComputedStyle(parent);\n if (!/(auto|scroll)/.test(parentStyle.overflowY) || parent.scrollHeight <= parent.clientHeight) continue;\n const box = parent.getBoundingClientRect();\n const visibleTop = Math.max(top, box.top + parent.clientTop);\n const visibleBottom = Math.min(bottom, box.top + parent.clientTop + parent.clientHeight);\n if (visibleBottom <= visibleTop) continue;\n const field3 = input4.getBoundingClientRect();\n const delta = field3.height > visibleBottom - visibleTop ? field3.top - visibleTop : field3.bottom > visibleBottom ? field3.bottom - visibleBottom : field3.top < visibleTop ? field3.top - visibleTop : 0;\n if (delta) parent.scrollTop += delta;\n }\n const scrolling = document.scrollingElement;\n if (scrolling && scrolling.scrollHeight > scrolling.clientHeight && ![document.documentElement, document.body].some((element2) => element2 && /(hidden|clip)/.test(getComputedStyle(element2).overflowY))) {\n const field3 = input4.getBoundingClientRect();\n const delta = field3.height > bottom - top ? field3.top - top : field3.bottom > bottom ? field3.bottom - bottom : field3.top < top ? field3.top - top : 0;\n if (delta) scrolling.scrollTop += delta;\n }\n}\nfunction createViewport() {\n let snapshot3 = null;\n const listeners2 = /* @__PURE__ */ new Set();\n let safeArea = zeroSafeArea;\n const safeListeners = /* @__PURE__ */ new Set();\n let declared = false;\n const announce2 = () => {\n if (typeof document === "undefined" || getNochaMode() !== "embedded") return;\n declared ||= document.querySelector(\'meta[name="nocha:safe-area"]\')?.getAttribute("content")?.trim().toLowerCase() === "overlay";\n if (!declared) return;\n try {\n postToHost({ protocol: NOCHA_BRIDGE_PROTOCOL, type: "event", event: { type: SAFE_AREA_DECLARATION_EVENT, payload: { mode: "overlay" } } });\n } catch {\n }\n };\n if (typeof window !== "undefined" && typeof document !== "undefined") {\n for (const edge2 of edges) document.documentElement.style.setProperty(`--nocha-safe-${edge2}`, `var(--nocha-safe-area-inset-${edge2}, env(safe-area-inset-${edge2}, 0px))`);\n let host2 = null;\n let frame = 0;\n let focusTimer = 0;\n let baselineHeight = document.documentElement.clientHeight || window.innerHeight;\n let baselineWidth = document.documentElement.clientWidth || window.innerWidth;\n let stop;\n let orientationChanged = false;\n const update2 = () => {\n frame = 0;\n const layoutWidth = Math.max(1, document.documentElement.clientWidth || window.innerWidth);\n const layoutHeight = Math.max(1, document.documentElement.clientHeight || window.innerHeight);\n const visual = window.visualViewport;\n const scale = visual?.scale || 1;\n if (orientationChanged || !editable2(document.activeElement) || Math.abs(layoutWidth - baselineWidth) > 80) {\n orientationChanged = false;\n baselineHeight = layoutHeight;\n baselineWidth = layoutWidth;\n }\n const offsetTop = Math.max(0, Math.min(layoutHeight - 1, visual?.offsetTop || 0));\n const offsetLeft = Math.max(0, Math.min(layoutWidth - 1, visual?.offsetLeft || 0));\n const visualHeight = Math.max(1, Math.min(layoutHeight - offsetTop, visual?.height || layoutHeight));\n const visualWidth = Math.max(1, Math.min(layoutWidth - offsetLeft, visual?.width || layoutWidth));\n const keyboardVisible = editable2(document.activeElement) && Math.abs(scale - 1) < 0.05 && baselineHeight - visualHeight > 100;\n const local = {\n layoutWidth,\n layoutHeight,\n visualWidth,\n visualHeight,\n offsetTop,\n offsetLeft,\n keyboardVisible,\n keyboardInset: keyboardVisible ? Math.max(0, layoutHeight - offsetTop - visualHeight) : 0,\n scale\n };\n const next = host2 ?? local;\n if (!snapshot3 || Object.keys(next).some((key2) => next[key2] !== snapshot3?.[key2])) {\n snapshot3 = Object.freeze({ ...next });\n const cssViewport = Math.abs(next.scale - 1) < 0.05 ? next : {\n ...next,\n visualWidth: next.layoutWidth,\n visualHeight: next.layoutHeight,\n offsetTop: 0,\n offsetLeft: 0,\n keyboardInset: 0\n };\n for (const [key2, property] of Object.entries(cssFields)) document.documentElement.style.setProperty(property, `${cssViewport[key2]}px`);\n document.documentElement.toggleAttribute("data-nocha-keyboard-visible", next.keyboardVisible);\n for (const listener of listeners2) notifyListener(listener, snapshot3);\n }\n revealFocus(next);\n };\n const schedule = () => {\n if (!frame) frame = window.requestAnimationFrame(update2);\n };\n const start = () => {\n if (stop) return;\n const controller = new AbortController();\n const { signal } = controller;\n const unsubscribe3 = subscribeBridgeEvents((event) => {\n if (event.type === "experience.viewport" && isExperienceViewport(event.payload)) {\n host2 = Object.freeze({ ...event.payload });\n schedule();\n }\n if (event.type === "experience.safe-area" && event.payload && typeof event.payload === "object" && !Array.isArray(event.payload)) {\n const insets = event.payload;\n if (!edges.every((edge2) => typeof insets[edge2] === "number" && Number.isFinite(insets[edge2]) && insets[edge2] >= 0)) return;\n for (const edge2 of edges) document.documentElement.style.setProperty(`--nocha-safe-area-inset-${edge2}`, `${insets[edge2]}px`);\n announce2();\n if (edges.some((edge2) => insets[edge2] !== safeArea[edge2])) {\n safeArea = Object.freeze({ top: insets.top, right: insets.right, bottom: insets.bottom, left: insets.left });\n for (const listener of safeListeners) notifyListener(listener, safeArea);\n }\n schedule();\n }\n });\n window.addEventListener("resize", schedule, { signal });\n window.addEventListener("orientationchange", () => {\n orientationChanged = true;\n schedule();\n }, { signal });\n window.visualViewport?.addEventListener("resize", schedule, { signal });\n window.visualViewport?.addEventListener("scroll", schedule, { signal });\n document.addEventListener("focusin", () => {\n schedule();\n window.clearTimeout(focusTimer);\n focusTimer = window.setTimeout(schedule, 350);\n }, { signal });\n document.addEventListener("focusout", schedule, { signal });\n stop = () => {\n controller.abort();\n unsubscribe3();\n window.cancelAnimationFrame(frame);\n window.clearTimeout(focusTimer);\n frame = 0;\n host2 = null;\n stop = void 0;\n };\n update2();\n };\n window.addEventListener("pagehide", () => stop?.());\n window.addEventListener("pageshow", start);\n start();\n announce2();\n if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", announce2, { once: true });\n }\n return Object.freeze({\n get: () => snapshot3,\n subscribe(listener) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A viewport listener is required");\n listeners2.add(listener);\n if (snapshot3) notifyListener(listener, snapshot3);\n return () => {\n listeners2.delete(listener);\n };\n },\n safeArea: () => safeArea,\n subscribeSafeArea(listener) {\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A safe-area listener is required");\n safeListeners.add(listener);\n notifyListener(listener, safeArea);\n return () => {\n safeListeners.delete(listener);\n };\n },\n declareSafeArea() {\n declared = true;\n announce2();\n }\n });\n}\n\n// src/voice.ts\nvar among = (values, value) => values.includes(String(value));\nfunction validState(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const v = value;\n return (v.callId === null || typeof v.callId === "string") && among(voiceCallConnections, v.connection) && among(voiceCallMicrophones, v.microphone) && among(voiceCallPlaybacks, v.playback) && among(voiceCallReasonings, v.reasoning) && among(voiceCallSettlements, v.settlement);\n}\nvar line2 = (value, max) => typeof value === "string" && value.trim().length > 0 && value.length <= max && !/\\p{Cc}/u.test(value);\nfunction validPersona(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const persona = value, limits = VOICE_CALL_PERSONA_LIMITS;\n const { boundaries } = persona;\n return Object.keys(persona).every((key2) => ["fictionalRole", "objective", "tone", "opening", "boundaries"].includes(key2)) && line2(persona.fictionalRole, limits.fictionalRole) && line2(persona.objective, limits.objective) && line2(persona.tone, limits.tone) && (persona.opening === void 0 || line2(persona.opening, limits.opening)) && (boundaries === void 0 || Array.isArray(boundaries) && boundaries.length <= limits.boundaries && boundaries.every((item) => line2(item, limits.boundary)));\n}\nfunction assertStartInput(input4) {\n const value = input4 ?? {};\n if (value.voice !== void 0 && !assistantVoices.includes(value.voice) || value.persona !== void 0 && !validPersona(value.persona)) {\n throw new NochaError("invalid_request", "A call voice is one of assistantVoices; a call persona keeps VOICE_CALL_PERSONA_LIMITS");\n }\n}\nfunction createVoice(context) {\n const invoke2 = async (operation2, input4, options) => {\n const result2 = await context.invoke(aiOperationDefinitions[operation2].capability, aiOperationDefinitions[operation2].operation, input4, options);\n if (!validState(result2)) throw new NochaError("invalid_result", "Nocha returned an invalid voice call state");\n return result2;\n };\n return Object.freeze({\n start: async (input4, options) => {\n assertStartInput(input4);\n return invoke2("voice.start", input4, options);\n },\n stop: (input4, options) => invoke2("voice.stop", input4, options),\n state: (input4 = {}, options) => invoke2("voice.state", input4, options),\n onState: (listener) => {\n assertHostCapability("voice");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A voice state listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type === "voice.state" && validState(event.payload)) notifyListener(listener, event.payload);\n });\n }\n });\n}\n\n// src/workspace.ts\nfunction parseWorkspace(value) {\n if (!isRecord(value) || !isNonEmptyString(value.id) || !isNonEmptyString(value.revisionId)) return null;\n const { kind, environment, participantId, permissions } = value;\n if (kind !== "public" && kind !== "personal" && kind !== "team" || environment !== "play" && environment !== "development" || !(participantId === null || typeof participantId === "string") || !isRecord(permissions) || !isBoolean(permissions.read) || !isBoolean(permissions.contribute) || !isBoolean(permissions.manage)) return null;\n return {\n id: value.id,\n kind,\n environment,\n revisionId: value.revisionId,\n participantId,\n permissions: { read: permissions.read, contribute: permissions.contribute, manage: permissions.manage }\n };\n}\nvar workspace2 = Object.freeze({\n get: async () => {\n const parsed = parseWorkspace(await invokeBridge("workspace", "get"));\n if (!parsed) throw new NochaError("invalid_result", "Nocha returned an invalid workspace presentation");\n return parsed;\n },\n onChange: (listener) => {\n assertHostCapability("workspace");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A workspace listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== "workspace.changed") return;\n const parsed = parseWorkspace(event.payload);\n if (parsed) notifyListener(listener, parsed);\n else warnOnce("workspace.changed", "the host sent a workspace presentation this SDK does not understand");\n });\n }\n});\n\n// src/spaces.ts\nfunction parseSpace(value) {\n if (!isRecord(value) || !isSpaceRef(value.ref) || !(value.label === null || typeof value.label === "string")) return null;\n const workspace3 = parseWorkspace(value);\n return workspace3 ? { ...workspace3, ref: value.ref, label: value.label } : null;\n}\nfunction parseSpaces(value) {\n if (!Array.isArray(value)) return null;\n const spaces2 = value.map(parseSpace);\n return spaces2.every((space) => space !== null) ? spaces2 : null;\n}\nasync function announced2() {\n assertHostCapability("spaces");\n const context = await experienceContext.get();\n if (context.spaces !== true) throw new NochaError("bridge_unavailable", "This reader does not serve nocha.spaces to this experience: declare a space on every data usage in NOCHA.json");\n}\nasync function attach(input4) {\n await announced2();\n const parsed = parseSpace(await invokeBridge("spaces", "attach", input4));\n if (!parsed) throw new NochaError("invalid_result", "Nocha returned an invalid space");\n return parsed;\n}\nvar spaces = Object.freeze({\n list: async () => {\n await announced2();\n const parsed = parseSpaces(await invokeBridge("spaces", "list"));\n if (!parsed) throw new NochaError("invalid_result", "Nocha returned an invalid space list");\n return parsed;\n },\n personal: () => attach({ kind: "personal" }),\n public: () => attach({ kind: "public" }),\n team: (options) => {\n const choose2 = options?.choose;\n if (choose2 !== void 0 && choose2 !== "remembered" && choose2 !== "always") return Promise.reject(new NochaError("invalid_request", "choose is \'remembered\' or \'always\'"));\n return attach({ kind: "team", ...choose2 ? { choose: choose2 } : {} });\n },\n actAsTeam: async (options) => {\n const choose2 = options?.choose;\n if (choose2 !== void 0 && choose2 !== "remembered" && choose2 !== "always") throw new NochaError("invalid_request", "choose is \'remembered\' or \'always\'");\n await announced2();\n const team = await invokeBridge("spaces", "actAsTeam", choose2 ? { choose: choose2 } : {});\n if (team !== null && !isSpaceTeam(team)) throw new NochaError("invalid_result", "Nocha returned an invalid team");\n return team;\n },\n onChange: (listener) => {\n assertHostCapability("spaces");\n if (typeof listener !== "function") throw new NochaError("invalid_request", "A spaces listener is required");\n return subscribeBridgeEvents((event) => {\n if (event.type !== SPACES_CHANGED_EVENT) return;\n const parsed = parseSpaces(isRecord(event.payload) ? event.payload.spaces : void 0);\n if (parsed) notifyListener(listener, parsed);\n else warnOnce(SPACES_CHANGED_EVENT, "the host sent spaces this SDK does not understand");\n });\n }\n});\n\n// src/screens.ts\nasync function webReader() {\n try {\n return (await experienceContext.get()).device.platform === "web";\n } catch {\n return false;\n }\n}\nfunction checkedValue(screen, input4, result2) {\n if (result2.status !== "done") return { status: "cancelled" };\n if (screen === "confirm" && result2.value !== true) throw invalidResult("Nocha returned an invalid confirm answer");\n if (screen === "credits.confirm" && (!isRecord(result2.value) || result2.value.confirmedMaximumMicrocredits !== input4.maximumMicrocredits)) {\n throw invalidResult("Nocha returned an invalid credits confirmation");\n }\n return { status: "done", value: result2.value };\n}\nasync function open2(screen, input4 = {}) {\n assertHostCapability("screens");\n if (!isScreenId(screen)) throw invalid2("screen is a screen id such as confirm or credits.confirm");\n if (!isRecord(input4)) throw invalid2("The screen input must be a JSON object");\n if (typeof navigator !== "undefined" && navigator.userActivation && !navigator.userActivation.isActive && !moduleCallActive()) {\n throw new NochaError("user_action_required", "Open a host screen from a button or another deliberate user action");\n }\n if (!await webReader()) throw new NochaError("capability_denied", "This Nocha reader does not show host screens");\n const value = await invokeBridge("screens", screensOperations.open.operation, { screen, input: input4 });\n if (!isScreenResult(value)) throw invalidResult("Nocha returned an invalid screen result");\n return checkedValue(screen, input4, value);\n}\nvar screens = Object.freeze({\n open: open2,\n available: async (screen) => {\n if (!isScreenId(screen)) return false;\n if (!await webReader()) return false;\n try {\n const value = await invokeBridge("screens", screensOperations.available.operation, { screen });\n return isRecord(value) && value.available === true;\n } catch (error) {\n if (isNochaError(error)) return false;\n throw error;\n }\n }\n});\n\n// src/content-refusal.ts\nvar CONTENT_REFUSAL_CODES = [\n "provider_http_400",\n "content_policy_violation",\n "refusal",\n "moderation_blocked",\n "content_filter",\n "content_filtered",\n "safety_violation",\n "safety"\n];\nvar PATTERN = new RegExp(`\\\\b(${CONTENT_REFUSAL_CODES.join("|")})\\\\b|content policy|moderation|safety system`, "i");\nfunction errorCode(value) {\n const { wireCode, code } = value;\n if (typeof wireCode === "string") return wireCode;\n return typeof code === "string" ? code : "";\n}\nfunction isContentRefusal(value) {\n if (typeof value === "string") return PATTERN.test(value);\n if (!value || typeof value !== "object") return false;\n const { message: message2, failure: failure4, details } = value;\n return PATTERN.test(errorCode(value)) || typeof message2 === "string" && PATTERN.test(message2) || !!failure4 && failure4 !== value && isContentRefusal(failure4) || !!details && typeof details === "object" && PATTERN.test(JSON.stringify(details));\n}\n\n// src/validate.ts\nvar validate_exports = {};\n__export(validate_exports, {\n InvalidData: () => InvalidData,\n boolean: () => boolean,\n check: () => check,\n externalId: () => externalId,\n finite: () => finite3,\n fromBase64: () => fromBase64,\n integer: () => integer2,\n isRecord: () => isRecord,\n isoDate: () => isoDate,\n jsonBytes: () => jsonBytes,\n jsonObject: () => jsonObject,\n line: () => line3,\n list: () => list4,\n microcredits: () => microcredits,\n nonNegative: () => nonNegative,\n number: () => number,\n oneOf: () => oneOf2,\n onlyKeys: () => onlyKeys,\n optionalLine: () => optionalLine,\n optionalText: () => optionalText2,\n record: () => record5,\n singleLine: () => singleLine,\n text: () => text5,\n tuple: () => tuple\n});\nvar InvalidData = class extends Error {\n constructor(field3) {\n super(`Invalid stored field: ${field3}`);\n this.field = field3;\n this.name = "InvalidData";\n }\n field;\n};\nfunction record5(value, field3) {\n if (!isRecord(value)) throw new InvalidData(field3);\n return value;\n}\nfunction check(value, guard, field3) {\n if (!guard(value)) throw new InvalidData(field3);\n return value;\n}\nvar CONTROL = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/;\nfunction text5(value, max, field3) {\n if (typeof value !== "string" || [...value].length > max || CONTROL.test(value)) throw new InvalidData(field3);\n return value;\n}\nfunction line3(value, max, field3) {\n const result2 = text5(value, max, field3);\n if (/[\\r\\n]/.test(result2)) throw new InvalidData(field3);\n return result2.trim();\n}\nfunction singleLine(value, max, field3) {\n const result2 = text5(value, max, field3);\n if (/[\\r\\n\\u2028\\u2029]/.test(result2)) throw new InvalidData(field3);\n return result2;\n}\nfunction optionalText2(value, max, field3) {\n return value === null || value === void 0 ? null : text5(value, max, field3);\n}\nfunction optionalLine(value, max, field3) {\n return value === null || value === void 0 ? null : singleLine(value, max, field3);\n}\nfunction number(value, min, max, field3) {\n if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) throw new InvalidData(field3);\n return value;\n}\nfunction integer2(value, min, max, field3) {\n const result2 = number(value, min, max, field3);\n if (!Number.isInteger(result2)) throw new InvalidData(field3);\n return result2;\n}\nfunction finite3(value, field3) {\n return number(value, -Number.MAX_VALUE, Number.MAX_VALUE, field3);\n}\nfunction nonNegative(value, field3) {\n return number(value, 0, Number.MAX_VALUE, field3);\n}\nfunction boolean(value, field3) {\n if (typeof value !== "boolean") throw new InvalidData(field3);\n return value;\n}\nfunction oneOf2(value, options, field3) {\n if (typeof value !== "string" || !options.includes(value)) throw new InvalidData(field3);\n return value;\n}\nfunction list4(value, max, field3) {\n if (!Array.isArray(value) || value.length > max) throw new InvalidData(field3);\n return value;\n}\nfunction tuple(value, min, max, field3) {\n if (!Array.isArray(value) || value.length < min || value.length > max) throw new InvalidData(field3);\n return value;\n}\nfunction onlyKeys(value, keys, field3) {\n for (const key2 of Object.keys(value)) if (!keys.includes(key2)) throw new InvalidData(`${field3}.${key2}`);\n}\nfunction isoDate(value, field3) {\n const result2 = text5(value, 40, field3);\n if (!Number.isFinite(Date.parse(result2))) throw new InvalidData(field3);\n return result2;\n}\nfunction microcredits(value, field3) {\n if (typeof value !== "string" || !/^\\d{1,20}$/.test(value)) throw new InvalidData(field3);\n return value;\n}\nfunction externalId(value, field3) {\n if (typeof value !== "string" || !/^[!-~]{1,128}$/.test(value)) throw new InvalidData(field3);\n return value;\n}\nvar PADDED_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nfunction fromBase64(value, field3) {\n if (typeof value !== "string" || !PADDED_BASE64.test(value)) throw new InvalidData(field3);\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\nfunction jsonObject(value) {\n const encoded = JSON.stringify(value);\n return { json: JSON.parse(encoded), bytes: new TextEncoder().encode(encoded).byteLength };\n}\nfunction jsonBytes(value) {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n}\n\n// src/ui-theme.ts\nvar uiThemeCss = `\n:host {\n --nocha-ui-x-font: var(--nocha-ui-font, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif);\n --nocha-ui-x-mono: var(--nocha-ui-mono, ui-monospace, "SF Mono", Menlo, Consolas, monospace);\n --nocha-ui-x-text: var(--nocha-ui-text, #f3f3f1);\n --nocha-ui-x-surface: var(--nocha-ui-surface, #121212);\n --nocha-ui-x-accent: var(--nocha-ui-accent, #f3f3f1);\n --nocha-ui-x-muted: var(--nocha-ui-muted, #a3a3a0);\n --nocha-ui-x-raised: var(--nocha-ui-raised, #1e1e1e);\n --nocha-ui-x-line: var(--nocha-ui-line, rgba(255, 255, 255, 0.14));\n --nocha-ui-x-on-accent: var(--nocha-ui-on-accent, #121212);\n --nocha-ui-x-radius: var(--nocha-ui-radius, 0px);\n --nocha-ui-x-backdrop: var(--nocha-ui-backdrop, rgba(0, 0, 0, 0.62));\n color-scheme: dark;\n font-family: var(--nocha-ui-x-font);\n font-size: 16px;\n line-height: 1.35;\n color: var(--nocha-ui-x-text);\n -webkit-text-size-adjust: 100%;\n text-size-adjust: 100%;\n}\n@media (prefers-color-scheme: light) {\n :host {\n --nocha-ui-x-text: var(--nocha-ui-text, #141414);\n --nocha-ui-x-surface: var(--nocha-ui-surface, #ffffff);\n --nocha-ui-x-accent: var(--nocha-ui-accent, #141414);\n --nocha-ui-x-muted: var(--nocha-ui-muted, #66665f);\n --nocha-ui-x-raised: var(--nocha-ui-raised, #f1f1ee);\n --nocha-ui-x-line: var(--nocha-ui-line, rgba(0, 0, 0, 0.14));\n --nocha-ui-x-on-accent: var(--nocha-ui-on-accent, #ffffff);\n --nocha-ui-x-backdrop: var(--nocha-ui-backdrop, rgba(0, 0, 0, 0.38));\n color-scheme: light;\n }\n}\n@supports (color: color-mix(in srgb, red, blue)) {\n :host {\n --nocha-ui-x-muted: var(--nocha-ui-muted, color-mix(in srgb, var(--nocha-ui-x-text) 62%, var(--nocha-ui-x-surface)));\n --nocha-ui-x-raised: var(--nocha-ui-raised, color-mix(in srgb, var(--nocha-ui-x-text) 8%, var(--nocha-ui-x-surface)));\n --nocha-ui-x-line: var(--nocha-ui-line, color-mix(in srgb, var(--nocha-ui-x-text) 16%, transparent));\n --nocha-ui-x-on-accent: var(--nocha-ui-on-accent, var(--nocha-ui-x-surface));\n }\n}\n*, *::before, *::after { box-sizing: border-box; }\n/* The hidden attribute always wins over a component\'s own display. */\n:host([hidden]), [hidden] { display: none !important; }\nbutton, input, select { font: inherit; color: inherit; letter-spacing: inherit; }\nbutton {\n margin: 0; padding: 0; border: 0; border-radius: 0; background: none; cursor: pointer; text-align: inherit;\n -webkit-tap-highlight-color: transparent; touch-action: manipulation;\n}\nbutton:disabled { cursor: default; }\n:focus { outline: none; }\n:focus-visible { outline: 2px solid var(--nocha-ui-x-accent); outline-offset: -2px; }\n.nocha-ui-icon { width: 20px; height: 20px; fill: currentColor; flex: none; display: block; }\n.nocha-ui-hidden {\n position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; border: 0; overflow: hidden;\n clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap;\n}\n@media (prefers-reduced-motion: reduce) {\n *, *::before, *::after {\n animation-duration: 0.01ms !important; animation-iteration-count: 1 !important;\n transition-duration: 0.01ms !important; scroll-behavior: auto !important;\n }\n}\n`;\n\n// src/ui-host.ts\nvar sheets;\nfunction constructedSheet(css) {\n if (typeof CSSStyleSheet === "undefined" || !("replaceSync" in CSSStyleSheet.prototype)) return null;\n sheets ??= /* @__PURE__ */ new Map();\n let sheet = sheets.get(css);\n if (!sheet) {\n try {\n sheet = new CSSStyleSheet();\n sheet.replaceSync(css);\n } catch {\n return null;\n }\n sheets.set(css, sheet);\n }\n return sheet;\n}\nfunction adoptStyles(root, css) {\n const sheet = constructedSheet(css);\n if (sheet && Array.isArray(root.adoptedStyleSheets)) {\n if (!root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];\n return;\n }\n const marker = String(css.length) + ":" + css.slice(0, 64);\n for (const style3 of Array.from(root.querySelectorAll("style"))) if (style3.dataset.nochaUi === marker) return;\n const style2 = root.ownerDocument.createElement("style");\n style2.dataset.nochaUi = marker;\n style2.textContent = css;\n root.prepend(style2);\n}\nfunction mountUiHost(css, container, tag2 = "nocha-ui") {\n if (typeof document === "undefined") throw new Error("Nocha components need a document");\n const ui = createUiHost(css, tag2);\n (container ?? document.body).append(ui.host);\n return ui;\n}\nfunction createUiHost(css, tag2 = "nocha-ui") {\n if (typeof document === "undefined") throw new Error("Nocha components need a document");\n const host2 = document.createElement(tag2.includes("-") ? tag2 : "nocha-ui");\n const root = host2.attachShadow({ mode: "open" });\n adoptStyles(root, uiThemeCss);\n adoptStyles(root, css);\n return { host: host2, root, remove: () => host2.remove() };\n}\nfunction element(document3, tag2, className, attributes, ...children) {\n const node = document3.createElement(tag2);\n if (className) node.className = className;\n for (const [name, value] of Object.entries(attributes ?? {})) {\n if (value === false || value === null || value === void 0) continue;\n node.setAttribute(name, value === true ? "" : value);\n }\n for (const child of children) if (child) node.append(child);\n return node;\n}\nfunction icon(document3, name, className = "nocha-ui-icon") {\n const svg = document3.createElementNS("http://www.w3.org/2000/svg", "svg");\n svg.setAttribute("viewBox", "0 0 24 24");\n svg.setAttribute("aria-hidden", "true");\n svg.setAttribute("focusable", "false");\n svg.setAttribute("class", className);\n const path = document3.createElementNS("http://www.w3.org/2000/svg", "path");\n path.setAttribute("d", iconPaths[name]);\n svg.append(path);\n return svg;\n}\nvar iconPaths = {\n play: "M8 5.5v13l11-6.5z",\n stop: "M7 7h10v10H7z",\n close: "M6.4 5 5 6.4 10.6 12 5 17.6 6.4 19l5.6-5.6 5.6 5.6 1.4-1.4-5.6-5.6L19 6.4 17.6 5 12 10.6z",\n star: "M12 3.5l2.6 5.6 6.1.7-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.8l6.1-.7z",\n check: "M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6L20.1 8.4 18.7 7z",\n chevron: "M7.4 9 12 13.6 16.6 9 18 10.4l-6 6-6-6z",\n chevronUp: "M7.4 15 12 10.4 16.6 15 18 13.6l-6-6-6 6z",\n search: "M15.5 14h-.8l-.3-.3A6.5 6.5 0 1 0 9.5 16a6.5 6.5 0 0 0 4.2-1.6l.3.3v.8l5 5 1.5-1.5zm-6 0A4.5 4.5 0 1 1 14 9.5 4.5 4.5 0 0 1 9.5 14z",\n dash: "M6 11h12v2H6z",\n plus: "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",\n before: "M15.4 7.4 14 6l-6 6 6 6 1.4-1.4-4.6-4.6z",\n after: "M8.6 7.4 10 6l6 6-6 6-1.4-1.4 4.6-4.6z",\n film: "M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V4z",\n start: "M18.4 16.6 13.8 12l4.6-4.6L17 6l-6 6 6 6zM6 6h2v12H6z",\n end: "M5.6 7.4 10.2 12l-4.6 4.6L7 18l6-6-6-6zM16 6h2v12h-2z",\n note: "M12 3v10.6a4 4 0 1 0 2 3.4V7h4V3z",\n mic: "M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5.3-3c0 3-2.5 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.4 2.7 6.2 6 6.7V21h2v-3.3c3.3-.5 6-3.3 6-6.7z"\n};\n\n// src/ui-text.ts\nfunction uiLocale(locale) {\n const browser = typeof navigator === "undefined" ? "" : navigator.language ?? "";\n const wanted = typeof locale === "string" && locale.trim() || language.get() || browser;\n return /^fr(?:$|[-_])/iu.test(wanted.trim()) ? "fr" : "en";\n}\nfunction uiTexts(tables, locale, labels) {\n const base2 = tables[locale];\n if (!labels || typeof labels !== "object") return base2;\n const merged = { ...base2 };\n for (const [key2, value] of Object.entries(labels)) {\n if (!(key2 in base2) || value === void 0) continue;\n const current4 = base2[key2];\n if (typeof current4 === "string" && typeof value === "string") merged[key2] = value;\n else if (current4 && typeof current4 === "object" && value && typeof value === "object") {\n merged[key2] = { ...current4, ...Object.fromEntries(Object.entries(value).filter(([, text6]) => typeof text6 === "string")) };\n }\n }\n return merged;\n}\nvar fill = (text6, values) => text6.replace(/\\{(\\w+)\\}/gu, (whole, key2) => key2 in values ? String(values[key2]) : whole);\nvar displayNames;\nfunction languageName(code, locale) {\n let name;\n try {\n displayNames ??= {};\n name = (displayNames[locale] ??= new Intl.DisplayNames([locale], { type: "language" })).of(code);\n } catch {\n name = void 0;\n }\n return capitalized(name && name !== code ? name : code.toUpperCase());\n}\nvar listedLabel = (value) => capitalized(value.replace(/[_-]+/gu, " ").replace(/\\s+/gu, " ").trim());\nvar capitalized = (value) => value.charAt(0).toLocaleUpperCase() + value.slice(1);\n\n// src/voice-browser-categories.ts\nvar nameMax = 60;\nvar cleanName = (value) => value.replace(/\\s+/gu, " ").trim().slice(0, nameMax);\nvar newId = () => typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID().replace(/-/g, "").slice(0, 12) : Math.random().toString(36).slice(2, 14);\nvar sameRef = (a, b) => a.id === b.id;\nfunction readCategory(value) {\n if (!value || typeof value !== "object") return null;\n const { id, name, voices: voices2 } = value;\n if (typeof id !== "string" || !id || typeof name !== "string") return null;\n const refs = (Array.isArray(voices2) ? voices2 : []).filter((ref) => Boolean(ref) && typeof ref.id === "string" && Boolean(ref.id) && typeof ref.model === "string").map((ref) => ({ id: ref.id, model: ref.model }));\n return { id, name, voices: refs };\n}\nvar VoiceCategories = class {\n #context;\n #list = [];\n /** The category the list is filtered by, the facet\'s panel open, the category being renamed or confirmed for deletion. */\n #active = null;\n #open = false;\n #renaming = null;\n #deleting = null;\n #menu = null;\n #disposed = false;\n constructor(context) {\n this.#context = context;\n }\n get active() {\n return this.#list.find((category) => category.id === this.#active) ?? null;\n }\n get open() {\n return this.#open;\n }\n /** Reads the store again; a failed read keeps what is shown. */\n async load() {\n try {\n const listed = await this.#context.store.list();\n if (this.#disposed) return;\n this.#list = (Array.isArray(listed) ? listed : []).map(readCategory).filter((item) => item !== null);\n if (this.#active && !this.active) this.#active = null;\n this.#context.changed(true);\n } catch {\n }\n }\n /** The voice is in at least one category. */\n has(id) {\n return this.#list.some((category) => category.voices.some((ref) => ref.id === id));\n }\n /** Leaves the category filter (another view was chosen). */\n clear() {\n this.#active = null;\n }\n /** Closes the facet\'s panel (a filter group opened instead). */\n fold() {\n this.#open = false;\n this.#renaming = null;\n this.#deleting = null;\n }\n /** The bar\'s chip: \xAB Mes cat\xE9gories \xBB, or the active category\'s name. */\n chip(onToggle) {\n const { doc, text: text6 } = this.#context;\n const active3 = this.active;\n const chip = element(\n doc,\n "button",\n `nocha-voice-picker__chip${active3 ? " nocha-voice-picker__chip--active" : ""}`,\n {\n type: "button",\n "aria-expanded": String(this.#open),\n "aria-label": active3 ? `${text6.categories} \\xB7 ${active3.name}` : text6.categories\n },\n active3 ? element(doc, "span", "", {}, active3.name) : element(doc, "span", "nocha-voice-picker__chip-label", {}, text6.categories),\n icon(doc, "chevron")\n );\n chip.addEventListener("click", () => {\n this.#open = !this.#open;\n this.#renaming = null;\n this.#deleting = null;\n onToggle();\n });\n return chip;\n }\n /** The facet\'s panel in the choices row: one chip per category, then renaming or deleting the active one. */\n panel(choices) {\n const { doc, text: text6 } = this.#context;\n choices.hidden = false;\n choices.setAttribute("aria-label", text6.categories);\n const active3 = this.active;\n if (active3 && this.#renaming === active3.id) {\n choices.replaceChildren(this.#nameForm(active3.name, text6.save, (name) => {\n this.#renaming = null;\n void this.#write({ ...active3, name });\n }, () => {\n this.#renaming = null;\n this.#context.filtered();\n }));\n return;\n }\n if (active3 && this.#deleting === active3.id) {\n const confirm = this.#button(text6.deleteCategory, () => void this.#remove(active3), true);\n const back = this.#button(text6.cancel, () => {\n this.#deleting = null;\n this.#context.filtered();\n });\n choices.replaceChildren(element(doc, "span", "nocha-voice-picker__prompt", {}, fill(text6.confirmDelete, { name: active3.name })), confirm, back);\n return;\n }\n if (!this.#list.length) {\n choices.replaceChildren(element(doc, "span", "nocha-voice-picker__prompt", {}, text6.noCategories));\n return;\n }\n const chips = this.#list.map((category) => {\n const chip = element(\n doc,\n "button",\n "nocha-voice-picker__chip",\n { type: "button", "aria-pressed": String(category.id === this.#active) },\n category.name,\n element(doc, "span", "nocha-voice-picker__count", {}, String(category.voices.length))\n );\n chip.addEventListener("click", () => {\n this.#active = this.#active === category.id ? null : category.id;\n this.#open = false;\n this.#context.filtered();\n });\n return chip;\n });\n const manage = active3 ? [\n this.#button(text6.rename, () => {\n this.#renaming = active3.id;\n this.#context.filtered();\n }),\n this.#button(text6.deleteCategory, () => {\n this.#deleting = active3.id;\n this.#context.filtered();\n })\n ] : [];\n choices.replaceChildren(...chips, ...manage);\n }\n /** The voice\'s menu over the browser: each category as a toggle, then a new one. `ref`: the pair kept for it. */\n openMenu(entry, ref) {\n const { doc, text: text6 } = this.#context;\n this.closeMenu();\n const name = entry.spokenName || entry.name;\n const close = element(doc, "button", "nocha-voice-picker__close", { type: "button", "aria-label": text6.close }, icon(doc, "close"));\n close.addEventListener("click", () => this.closeMenu());\n const toggles = element(doc, "div", "nocha-voice-picker__menu-list");\n const drawToggles = () => {\n toggles.replaceChildren(...this.#list.map((category) => {\n const inside = category.voices.some((item) => sameRef(item, ref));\n const chip = element(\n doc,\n "button",\n "nocha-voice-picker__chip",\n { type: "button", "aria-pressed": String(inside) },\n inside ? icon(doc, "check") : icon(doc, "plus"),\n category.name\n );\n chip.addEventListener("click", () => {\n const voices2 = inside ? category.voices.filter((item) => !sameRef(item, ref)) : [{ ...ref }, ...category.voices];\n void this.#write({ ...category, voices: voices2 }).then(drawToggles);\n drawToggles();\n });\n return chip;\n }));\n };\n drawToggles();\n const form = this.#nameForm("", text6.create, (categoryName) => {\n void this.#write({ id: newId(), name: categoryName, voices: [{ ...ref }] }).then(drawToggles);\n drawToggles();\n });\n const menu = element(\n doc,\n "div",\n "nocha-voice-picker__menu",\n { role: "dialog", "aria-label": fill(text6.categorize, { name }) },\n element(\n doc,\n "div",\n "nocha-voice-picker__menu-head",\n {},\n element(doc, "span", "nocha-voice-picker__menu-title", {}, fill(text6.categorize, { name })),\n close\n ),\n toggles,\n element(doc, "div", "nocha-voice-picker__menu-new", {}, form)\n );\n menu.addEventListener("keydown", (event) => {\n if (event.key !== "Escape") return;\n event.stopPropagation();\n this.closeMenu();\n });\n this.#menu = menu;\n this.#context.frame.append(menu);\n form.querySelector("input")?.focus();\n }\n /** True when a menu was open. */\n closeMenu() {\n const menu = this.#menu;\n this.#menu = null;\n menu?.remove();\n return Boolean(menu);\n }\n dispose() {\n this.#disposed = true;\n this.closeMenu();\n }\n #button(label, run3, strong = false) {\n const button = element(this.#context.doc, "button", `nocha-voice-picker__chip${strong ? " nocha-voice-picker__chip--active" : ""}`, { type: "button" }, label);\n button.addEventListener("click", run3);\n return button;\n }\n /** A name field and its button: an empty name does nothing. */\n #nameForm(value, label, done, cancel2) {\n const { doc, text: text6 } = this.#context;\n const input4 = element(doc, "input", "nocha-voice-picker__input nocha-voice-picker__input--name", {\n type: "text",\n placeholder: value ? text6.categoryName : text6.newCategory,\n "aria-label": text6.categoryName,\n maxlength: String(nameMax),\n autocomplete: "off",\n enterkeyhint: "done"\n });\n input4.value = value;\n const form = element(\n doc,\n "form",\n "nocha-voice-picker__name-form",\n {},\n input4,\n element(doc, "button", "nocha-voice-picker__chip nocha-voice-picker__chip--active", { type: "submit" }, label),\n cancel2 && this.#button(text6.cancel, cancel2)\n );\n form.addEventListener("submit", (event) => {\n event.preventDefault();\n const name = cleanName(input4.value);\n if (!name) return;\n input4.value = "";\n done(name);\n });\n return form;\n }\n /** Shows the category at once, then keeps the store\'s answer; a refusal takes it back and says so. */\n async #write(category) {\n const before = this.#list;\n const known = before.some((item) => item.id === category.id);\n this.#list = known ? before.map((item) => item.id === category.id ? category : item) : [...before, category];\n this.#context.changed(true);\n try {\n const saved = readCategory(await this.#context.store.save(category)) ?? category;\n if (this.#disposed) return;\n this.#list = this.#list.map((item) => item.id === category.id ? saved : item);\n this.#context.changed(true);\n } catch {\n if (this.#disposed) return;\n this.#list = known ? this.#list.map((item) => item.id === category.id ? before.find((old) => old.id === category.id) ?? item : item) : this.#list.filter((item) => item.id !== category.id);\n this.#context.changed(true);\n this.#context.say(this.#context.text.categoriesFailed);\n }\n }\n async #remove(category) {\n const before = this.#list;\n this.#list = before.filter((item) => item.id !== category.id);\n this.#deleting = null;\n if (this.#active === category.id) this.#active = null;\n this.#context.filtered();\n this.#context.changed(true);\n try {\n await this.#context.store.remove(category.id);\n } catch {\n if (this.#disposed) return;\n this.#list = before.some((item) => item.id === category.id) && !this.#list.some((item) => item.id === category.id) ? [...this.#list, category] : this.#list;\n this.#context.changed(true);\n this.#context.say(this.#context.text.categoriesFailed);\n }\n }\n};\n\n// src/voice-favorites-account.ts\nvar accountTtlMs = 6e4;\nvar absentCodes = /* @__PURE__ */ new Set(["client_update_required", "bridge_unavailable", "native_host_required"]);\nvar anonymousCodes = /* @__PURE__ */ new Set(["identity_required", "unauthorized", "sign_in_required", "authentication_required"]);\nvar reads2;\nvar listeners;\nfunction deviceReason(error) {\n if (!isNochaError(error)) return "failed";\n if (absentCodes.has(error.code)) return "absent";\n if (error.code === "capability_denied") return "denied";\n return anonymousCodes.has(error.code) ? "anonymous" : "failed";\n}\nvar isFavoritesLimit = (error) => isNochaError(error) && error.code === "voice_favorites_limit";\nfunction readAccountFavorites(ai, options = {}) {\n if (typeof ai.voiceFavorites !== "function") return Promise.resolve({ status: "device", reason: "absent" });\n reads2 ??= /* @__PURE__ */ new WeakMap();\n const cached2 = reads2.get(ai);\n if (cached2 && !options.refresh && Date.now() - cached2.at < accountTtlMs) return cached2.read;\n const read4 = ai.voiceFavorites().then(\n (value) => ({ status: "account", value }),\n (error) => {\n const reason2 = deviceReason(error);\n if (reason2 === "failed" && reads2?.get(ai)?.read === read4) reads2.delete(ai);\n return { status: "device", reason: reason2 };\n }\n );\n reads2.set(ai, { at: Date.now(), read: read4 });\n return read4;\n}\nasync function writeAccountFavorites(ai, input4) {\n if (typeof ai.voiceFavoritesUpdate !== "function") throw new Error("This host keeps no favourite voices");\n let value;\n try {\n value = await ai.voiceFavoritesUpdate(input4);\n } catch (error) {\n reads2?.delete(ai);\n throw error;\n }\n reads2 ??= /* @__PURE__ */ new WeakMap();\n reads2.set(ai, { at: Date.now(), read: Promise.resolve({ status: "account", value }) });\n for (const listener of Array.from(listeners?.get(ai) ?? [])) listener(value);\n return value;\n}\nfunction onAccountFavorites(ai, listener) {\n listeners ??= /* @__PURE__ */ new WeakMap();\n let set = listeners.get(ai);\n if (!set) listeners.set(ai, set = /* @__PURE__ */ new Set());\n set.add(listener);\n return () => {\n listeners?.get(ai)?.delete(listener);\n };\n}\n\n// src/voice-picker-data.ts\nvar pageSize2 = 30;\nvar listingTtlMs = 5 * 6e4;\nvar listingCacheSize = 40;\nvar previewCacheSize = 30;\nvar listings;\nvar modelReads;\nfunction listingCache(ai) {\n listings ??= /* @__PURE__ */ new WeakMap();\n let cache = listings.get(ai);\n if (!cache) listings.set(ai, cache = /* @__PURE__ */ new Map());\n return cache;\n}\nvar queryKey = (query) => JSON.stringify([\n query.model,\n query.language ?? "",\n query.collection ?? "",\n query.query ?? "",\n query.gender ?? "",\n query.age ?? "",\n query.accent ?? "",\n query.useCase ?? "",\n query.verifiedFor ?? "",\n query.featured ?? null,\n query.maxPriceMultiplier ?? null,\n query.sort ?? "",\n query.models?.map((model) => model.model) ?? null\n]);\nvar ageToken = { young: "young", middle: "middle_aged", old: "old" };\nvar isFacet = (value) => typeof value === "string" && VOICE_FACET_PATTERN.test(value);\nfunction voicesInput(query) {\n return voicesInputFor(query.spec, {\n ...query.model ? { model: query.model } : {},\n ...query.language ? { language: query.language } : {},\n ...query.collection ? { collection: query.collection } : {},\n ...query.query ? { query: query.query } : {},\n ...query.gender ? { gender: query.gender } : {},\n ...query.age ? { age: ageToken[query.age] } : {},\n ...isFacet(query.accent) ? { accent: query.accent } : {},\n ...isFacet(query.useCase) ? { useCases: [query.useCase] } : {},\n ...query.verifiedFor ? { verifiedFor: query.verifiedFor } : {},\n ...query.featured !== void 0 ? { featured: query.featured } : {},\n ...query.maxPriceMultiplier !== void 0 ? { maxPriceMultiplier: query.maxPriceMultiplier } : {},\n ...query.sort ? { sort: query.sort } : {}\n });\n}\nfunction aliasListing(query) {\n const entries = aliasListingEntries(query.model, query.collection, query.query);\n return { entries, cursor: null, model: query.model, defaultVoice: entries[0]?.ref.id ?? "", source: "aliases", at: Date.now() };\n}\nasync function readEveryModel(ai, query, rankLanguage, signal) {\n const input4 = voicesInput({ ...query, spec: void 0 });\n const models2 = (query.models ?? []).filter((model) => !isModelUnavailable(model) && modelAnswersInput(model, input4));\n const settled2 = await Promise.allSettled(models2.map((model) => readVoicePages(\n (page, options) => ai.voices(page, options),\n { ...voicesInputFor(model, input4), model: model.model },\n {\n model: model.model,\n limit: () => pageSize2,\n until: 1,\n legacyFallback: true,\n options: { signal }\n }\n )));\n const failed = models2.filter((_model, index) => settled2[index].status === "rejected").map((model) => model.model);\n const firstFailure = settled2.find((page) => page.status === "rejected");\n if (firstFailure && failed.length === models2.length) throw firstFailure.reason;\n const pages = settled2.flatMap((page) => page.status === "fulfilled" ? [page.value] : []);\n const listed = pages.filter((page) => page !== null);\n if (listed.length < pages.length) return aliasListing({ ...query, model: models2[0]?.model ?? "" });\n const ids2 = /* @__PURE__ */ new Set();\n const entries = listed.flatMap((page) => page.entries).filter((entry) => !ids2.has(entry.ref.id) && Boolean(ids2.add(entry.ref.id)));\n const lead = listed[0];\n return {\n entries: rankVoiceEntries(entries, rankLanguage, lead ? { id: lead.defaultVoice, model: lead.model } : "", query.sort),\n cursor: null,\n model: lead?.model ?? "",\n defaultVoice: lead?.defaultVoice ?? "",\n source: "listed",\n at: Date.now(),\n ...failed.length ? { failed } : {}\n };\n}\nasync function readVoices(ai, query, listing, rankLanguage, signal) {\n const cache = listingCache(ai);\n const key2 = queryKey(query);\n if (!listing) {\n const cached2 = cache.get(key2);\n if (cached2 && Date.now() - cached2.at < listingTtlMs) return cached2;\n cache.delete(key2);\n } else if (!listing.cursor) return listing;\n if (query.models) {\n const every = await readEveryModel(ai, query, rankLanguage, signal);\n if (!every.failed) remember(cache, key2, every);\n return every;\n }\n const page = await readVoicePages((input4, options) => ai.voices(input4, options), voicesInput(query), {\n model: listing?.model || query.model,\n ...listing?.cursor ? { cursor: listing.cursor } : {},\n known: listing?.entries.map((entry) => entry.ref.id) ?? [],\n limit: () => pageSize2,\n until: 1,\n legacyFallback: !listing,\n options: { signal }\n });\n if (!page) {\n const fallback = aliasListing(query);\n remember(cache, key2, fallback);\n return fallback;\n }\n const defaultVoice = listing?.defaultVoice || page.defaultVoice;\n const next = {\n entries: [...listing?.entries ?? [], ...rankVoiceEntries(page.entries, rankLanguage, defaultVoice, query.sort)],\n cursor: page.cursor,\n model: page.model,\n defaultVoice,\n source: "listed",\n at: listing?.at ?? Date.now()\n };\n remember(cache, key2, next);\n return next;\n}\nfunction remember(cache, key2, listing) {\n cache.delete(key2);\n cache.set(key2, listing);\n while (cache.size > listingCacheSize) cache.delete(cache.keys().next().value);\n}\nvar lookupPageLimit = 6;\nvar libraryLookupLimit = 4;\nvar isLibraryVoice = (id) => id.startsWith("library:");\nvar voiceIdLabel = (id) => id.slice(id.lastIndexOf(":") + 1) || id;\nvar bareRef = (ref) => ({ id: ref.id, model: ref.model });\nfunction providedName(ref) {\n const name = ref.name;\n return typeof name === "string" ? name.replace(/\\s+/gu, " ").trim().slice(0, 80) : "";\n}\nvar unfound;\nfunction lookedUpInVain(ai, id) {\n const at = unfound?.get(ai)?.get(id);\n return at !== void 0 && Date.now() - at < listingTtlMs;\n}\nasync function findVoices(ai, refs, signal) {\n const found = /* @__PURE__ */ new Map();\n const wanted = new Map(refs.filter((ref) => isSpeechVoiceId(ref.id) && !lookedUpInVain(ai, ref.id)).map((ref) => [ref.id, ref]));\n const take = (entries) => {\n for (const entry of entries) {\n const ref = wanted.get(entry.ref.id);\n if (!ref || found.has(ref.id)) continue;\n found.set(ref.id, { ...entry, ref: bareRef(ref) });\n }\n };\n for (const listing of Array.from(listings?.get(ai)?.values() ?? [])) take(listing.entries);\n for (const ref of Array.from(wanted.values())) if (isSpeechVoiceAlias(ref.id)) take(aliasVoiceEntries(ref.model));\n const missing = () => Array.from(wanted.keys()).filter((id) => !found.has(id));\n const builtIn = () => missing().filter((id) => !isLibraryVoice(id));\n const models2 = Array.from(new Set(builtIn().map((id) => wanted.get(id)?.model ?? "")));\n const searched = /* @__PURE__ */ new Set();\n try {\n for (const model of models2) {\n let listing = null;\n for (let pages = 0; pages < lookupPageLimit && builtIn().length && !signal.aborted; pages += 1) {\n const next = await readVoices(ai, { model, collection: "standard" }, listing, "", signal);\n take(next.entries);\n if (!next.cursor || next === listing) break;\n listing = next;\n }\n }\n for (const id of missing().filter(isLibraryVoice).slice(0, libraryLookupLimit)) {\n if (signal.aborted) break;\n const model = wanted.get(id)?.model ?? "";\n take((await readVoices(ai, { model, collection: "library", query: voiceIdLabel(id) }, null, "", signal)).entries);\n searched.add(id);\n }\n } catch {\n return found;\n }\n if (!signal.aborted) {\n unfound ??= /* @__PURE__ */ new WeakMap();\n let missed = unfound.get(ai);\n if (!missed) unfound.set(ai, missed = /* @__PURE__ */ new Map());\n for (const id of missing()) if (!isLibraryVoice(id) || searched.has(id)) missed.set(id, Date.now());\n }\n return found;\n}\nfunction readModels(ai) {\n modelReads ??= /* @__PURE__ */ new WeakMap();\n const cached2 = modelReads.get(ai);\n if (cached2 && Date.now() - cached2.at < listingTtlMs) return cached2.read;\n const read4 = ai.models({ need: "audio.synthesize" }).then((listed) => ({ models: listed.models, defaultModel: listed.default_model })).catch(() => {\n modelReads?.delete(ai);\n return { models: [], defaultModel: "" };\n });\n modelReads.set(ai, { at: Date.now(), read: read4 });\n return read4;\n}\nvar samples;\nvar languageRefused;\nvar silence;\nvar unavailableVoices;\nfunction silentWav() {\n if (silence) return silence;\n const samplesCount = 400;\n const bytes = new Uint8Array(44 + samplesCount);\n const view = new DataView(bytes.buffer);\n const text6 = (offset, value) => {\n for (let i = 0; i < value.length; i += 1) bytes[offset + i] = value.charCodeAt(i);\n };\n text6(0, "RIFF");\n view.setUint32(4, 36 + samplesCount, true);\n text6(8, "WAVE");\n text6(12, "fmt ");\n view.setUint32(16, 16, true);\n view.setUint16(20, 1, true);\n view.setUint16(22, 1, true);\n view.setUint32(24, 8e3, true);\n view.setUint32(28, 8e3, true);\n view.setUint16(32, 1, true);\n view.setUint16(34, 8, true);\n text6(36, "data");\n view.setUint32(40, samplesCount, true);\n bytes.fill(128, 44);\n let binary = "";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return silence = `data:audio/wav;base64,${btoa(binary)}`;\n}\nfunction sampleLanguage(entry, language2) {\n const base2 = baseLanguage(language2);\n return base2 && entry.dialects?.some((dialect) => dialect.language === base2 && dialect.preview === true) ? base2 : void 0;\n}\nvar playableUrl = /^(?:data:audio\\/|blob:)/u;\nfunction createSamplePlayer(ai, onState, audition) {\n let audio = null;\n let current4 = null;\n const missing = /* @__PURE__ */ new Set();\n const finish = (state3) => {\n if (!current4) return;\n const { id } = current4;\n current4.stop.abort();\n current4 = null;\n onState(id, state3);\n };\n const element2 = () => {\n if (audio) return audio;\n audio = new Audio();\n audio.preload = "auto";\n audio.addEventListener("ended", () => {\n if (current4 && audio?.src !== silentWav()) finish("idle");\n });\n audio.addEventListener("error", () => {\n if (current4 && audio?.src !== silentWav()) finish("failed");\n });\n return audio;\n };\n const fetchSample = async (entry, language2, signal) => {\n samples ??= /* @__PURE__ */ new Map();\n languageRefused ??= /* @__PURE__ */ new WeakSet();\n const asked = language2 && !languageRefused.has(ai) ? language2 : void 0;\n const key2 = `${entry.ref.model}\\0${entry.ref.id}\\0${asked ?? ""}`;\n const cached2 = samples.get(key2);\n if (cached2) {\n samples.delete(key2);\n samples.set(key2, cached2);\n return cached2;\n }\n const base2 = { voice: entry.ref.id, ...isSpeechModelId(entry.ref.model) ? { model: entry.ref.model } : {} };\n let preview2;\n try {\n preview2 = await ai.voicePreview({ ...base2, ...asked ? { language: asked } : {} }, { signal });\n } catch (error) {\n if (!asked || !isNochaError(error) || error.code !== "invalid_request") throw error;\n languageRefused.add(ai);\n preview2 = await ai.voicePreview(base2, { signal });\n }\n remember2(key2, preview2.dataUrl);\n return preview2.dataUrl;\n };\n const remember2 = (key2, url) => {\n samples ??= /* @__PURE__ */ new Map();\n samples.set(key2, url);\n while (samples.size > previewCacheSize) samples.delete(samples.keys().next().value);\n };\n const paidSample = async (entry, signal) => {\n const key2 = `${entry.ref.model}\\0${entry.ref.id}\\0audition`;\n const cached2 = samples?.get(key2);\n if (cached2) {\n samples?.delete(key2);\n samples?.set(key2, cached2);\n return cached2;\n }\n let url;\n try {\n url = await audition(entry, signal);\n } catch (error) {\n if (isNochaError(error) && error.code === "voice_unavailable") (unavailableVoices ??= /* @__PURE__ */ new Set()).add(entry.ref.id);\n throw error;\n }\n if (url === null || signal.aborted) return null;\n if (typeof url !== "string" || !playableUrl.test(url)) throw new Error("audition must return a data: or blob: URL");\n remember2(key2, url);\n return url;\n };\n const lacksSample = (entry) => !entry.preview || missing.has(entry.ref.id);\n return {\n /** Call it from the click itself: it starts the element at once, then plays the sample when it arrives. Calling it\n * again for the voice that is playing stops it. */\n toggle(entry, language2) {\n const id = entry.ref.id;\n if (current4?.id === id) {\n element2().pause();\n finish("idle");\n return;\n }\n if (current4) {\n element2().pause();\n finish("idle");\n }\n if (unavailableVoices?.has(id)) {\n onState(id, "unavailable");\n return;\n }\n if (lacksSample(entry) && !audition) {\n onState(id, "missing");\n return;\n }\n const player2 = element2();\n player2.src = silentWav();\n void player2.play().catch(() => void 0);\n const stop = new AbortController();\n current4 = { id, stop };\n onState(id, "loading");\n const free = !lacksSample(entry);\n const read4 = free ? fetchSample(entry, sampleLanguage(entry, language2), stop.signal).catch((error) => {\n if (!isNochaError(error) || !voicePreviewMissingCodes.has(error.code)) throw error;\n missing.add(id);\n if (!audition || stop.signal.aborted) throw error;\n return paidSample(entry, stop.signal);\n }) : paidSample(entry, stop.signal);\n read4.then((url) => {\n if (current4?.id !== id || stop.signal.aborted) return;\n if (url === null) {\n finish("idle");\n return;\n }\n player2.src = url;\n onState(id, "playing");\n return player2.play().catch(() => {\n if (current4?.id === id) finish("failed");\n });\n }, (error) => {\n if (current4?.id !== id || stop.signal.aborted) return;\n finish(unavailableVoices?.has(id) ? "unavailable" : isNochaError(error) && voicePreviewMissingCodes.has(error.code) ? "missing" : "failed");\n });\n },\n /** Whether the voice plays only through the experience\'s paid `audition`. */\n paid: (entry) => Boolean(audition) && lacksSample(entry),\n /** Whether the voice has nothing to play: no free sample and no `audition`. */\n silent: (entry) => !audition && lacksSample(entry),\n /** Whether a sample of this voice answered `voice_unavailable` earlier in the page. */\n unavailable: (entry) => Boolean(unavailableVoices?.has(entry.ref.id)),\n stop() {\n if (!current4) return;\n audio?.pause();\n finish("idle");\n },\n dispose() {\n current4?.stop.abort();\n current4 = null;\n if (audio) {\n audio.pause();\n audio.removeAttribute("src");\n audio.load();\n audio = null;\n }\n }\n };\n}\nfunction placeholderEntry(ref) {\n const alias = isSpeechVoiceAlias(ref.id) ? aliasVoiceEntries(ref.model).find((entry) => entry.ref.id === ref.id) : void 0;\n if (alias) return { ...alias, ref: bareRef(ref) };\n const given = providedName(ref);\n const name = given || voiceIdLabel(ref.id);\n return {\n ref: bareRef(ref),\n name,\n spokenName: given ? spokenVoiceName(given) || name.slice(0, 40) : name.slice(0, 40),\n collection: isLibraryVoice(ref.id) ? "library" : "standard",\n languages: [],\n traits: {},\n preview: true,\n premium: null\n };\n}\nvar isUnnamed = (entry) => !entry.alias && (entry.name === entry.ref.id || entry.name === voiceIdLabel(entry.ref.id));\n\n// src/voice-memory.ts\nvar favoriteLimit = 60;\nvar recentLimit = 8;\nvar memoryStore;\nvar migrations;\nvar storeKey = (storageKey) => `nocha-voices:${typeof storageKey === "string" && storageKey ? storageKey.slice(0, 80) : "default"}`;\nfunction storedEntry(value) {\n if (!value || typeof value !== "object") return null;\n const item = value;\n const ref = item.ref;\n if (!ref || !isSpeechVoiceId(ref.id) || typeof ref.model !== "string" || typeof item.name !== "string") return null;\n const traits = item.traits && typeof item.traits === "object" ? item.traits : {};\n const bare = item.name === ref.id && !isSpeechVoiceAlias(item.alias);\n const name = bare ? voiceIdLabel(ref.id) : item.name.slice(0, 80);\n return {\n ref: { id: ref.id, model: ref.model },\n name,\n spokenName: !bare && typeof item.spokenName === "string" ? item.spokenName.slice(0, 40) : name.slice(0, 40),\n collection: item.collection === "library" || isLibraryVoice(ref.id) ? "library" : "standard",\n ...isSpeechVoiceAlias(item.alias) ? { alias: item.alias } : {},\n languages: Array.isArray(item.languages) ? item.languages.filter((code) => typeof code === "string").slice(0, 12) : [],\n traits: {\n ...traits.gender === "female" || traits.gender === "male" || traits.gender === "neutral" ? { gender: traits.gender } : {},\n ...traits.age === "young" || traits.age === "middle" || traits.age === "old" ? { age: traits.age } : {},\n ...typeof traits.accent === "string" ? { accent: traits.accent.slice(0, 40) } : {}\n },\n ...Array.isArray(item.models) ? { models: item.models.filter(isSpeechModelId).slice(0, 24) } : {},\n preview: item.preview === true,\n premium: typeof item.premium === "number" && Number.isFinite(item.premium) && item.premium > 1 ? item.premium : null,\n ...typeof item.useCase === "string" ? { useCase: item.useCase.slice(0, 50) } : {},\n ...Array.isArray(item.dialects) ? { dialects: speechVoiceDialects(item.dialects) } : {}\n };\n}\nvar keptEntry = ({ description: _description, popularity: _popularity, usage7d: _usage7d, usage1y: _usage1y, ...entry }) => entry;\nfunction createVoiceMemory(storageKey, seed, ai) {\n const key2 = storeKey(storageKey);\n const read4 = () => {\n let raw;\n try {\n raw = globalThis.localStorage?.getItem(key2) ?? null;\n } catch {\n raw = null;\n }\n if (raw === null) return memoryStore?.get(key2) ?? { favorites: [], recents: [] };\n try {\n const parsed = JSON.parse(raw);\n const list5 = (value, limit3) => (Array.isArray(value) ? value : []).map(storedEntry).filter((entry) => entry !== null).slice(0, limit3);\n return {\n favorites: list5(parsed.favorites, favoriteLimit),\n recents: list5(parsed.recents, recentLimit),\n ...parsed.seeded === true ? { seeded: true } : {},\n ...parsed.pushed === true ? { pushed: true } : {}\n };\n } catch {\n return { favorites: [], recents: [] };\n }\n };\n const write2 = (value) => {\n memoryStore ??= /* @__PURE__ */ new Map();\n memoryStore.set(key2, value);\n try {\n globalThis.localStorage?.setItem(key2, JSON.stringify(value));\n } catch {\n }\n };\n let state3 = read4();\n if (!state3.favorites.length && !state3.seeded && Array.isArray(seed) && seed.length) {\n const ids2 = /* @__PURE__ */ new Set();\n const favorites2 = seed.filter((ref) => Boolean(ref) && isSpeechVoiceId(ref.id) && typeof ref.model === "string" && (ref.model === "" || isSpeechModelId(ref.model)) && !ids2.has(ref.id) && Boolean(ids2.add(ref.id))).slice(0, favoriteLimit).map(placeholderEntry);\n if (favorites2.length) write2(state3 = { ...state3, favorites: favorites2, seeded: true });\n }\n let account = null;\n let limit2 = 100;\n const names = /* @__PURE__ */ new Map();\n const listeners2 = /* @__PURE__ */ new Set();\n const emit = () => {\n for (const listener of Array.from(listeners2)) listener();\n };\n const stopListening = ai ? onAccountFavorites(ai, (value) => {\n account = value.favorites;\n limit2 = value.limit;\n emit();\n }) : null;\n let syncing = null;\n const favorites = () => account ? account.map((entry) => isUnnamed(entry) ? names.get(entry.ref.id) ?? entry : entry) : state3.favorites;\n const mirror = (entry, on) => {\n state3 = read4();\n const rest = state3.favorites.filter((item) => item.ref.id !== entry.ref.id);\n write2(state3 = { ...state3, favorites: on ? [keptEntry(entry), ...rest].slice(0, favoriteLimit) : rest, seeded: true });\n };\n const migrate = (favoritesAi, held, cap) => {\n if (read4().pushed) return Promise.resolve();\n migrations ??= /* @__PURE__ */ new WeakMap();\n let running3 = migrations.get(favoritesAi);\n if (!running3) migrations.set(favoritesAi, running3 = /* @__PURE__ */ new Map());\n const pending3 = running3.get(key2);\n if (pending3) return pending3;\n const migration = (async () => {\n state3 = read4();\n if (state3.pushed) return;\n const have = new Set(held.map((entry) => entry.ref.id));\n const add = state3.favorites.filter((entry) => !have.has(entry.ref.id)).slice(0, Math.max(0, cap - held.length));\n try {\n if (add.length) await writeAccountFavorites(favoritesAi, { add });\n } catch (error) {\n if (!isFavoritesLimit(error)) return;\n }\n state3 = read4();\n write2(state3 = { ...state3, pushed: true });\n })().finally(() => running3?.delete(key2));\n running3.set(key2, migration);\n return migration;\n };\n return {\n favorites,\n recents: () => state3.recents,\n isFavorite: (id) => favorites().some((entry) => entry.ref.id === id),\n find: (id) => favorites().find((entry) => entry.ref.id === id) ?? state3.recents.find((entry) => entry.ref.id === id) ?? state3.favorites.find((entry) => entry.ref.id === id),\n /** How many favourites the account keeps at most (100 until it answers). */\n limit: () => limit2,\n /** `account` once the account\'s favourites were read, else `device`. */\n source: () => account ? "account" : "device",\n /** Reads the account\'s favourites (shared for 60 s per `ai`) and runs the migration once; the device\'s stay shown\n * when the account keeps none. Never throws. */\n sync(options = {}) {\n if (!ai) return Promise.resolve();\n syncing ??= readAccountFavorites(ai, options).then(async (result2) => {\n if (result2.status !== "account") {\n if (result2.reason !== "failed") account = null;\n return;\n }\n account = result2.value.favorites;\n limit2 = result2.value.limit;\n await migrate(ai, result2.value.favorites, result2.value.limit);\n }).finally(() => {\n syncing = null;\n emit();\n });\n return syncing;\n },\n /** Adds or removes a favourite. On the account: shown at once, written, and taken back when the write fails (a full\n * list rejects with `voice_favorites_limit` before any write). Resolves with the new state. */\n async toggleFavorite(entry) {\n if (!account) state3 = read4();\n const on = !favorites().some((item) => item.ref.id === entry.ref.id);\n if (!account || !ai) {\n mirror(entry, on);\n emit();\n return on;\n }\n if (on && account.length >= limit2) throw new NochaError("voice_favorites_limit", "Favourite voices are full");\n const before = account;\n account = on ? [keptEntry(entry), ...before] : before.filter((item) => item.ref.id !== entry.ref.id);\n emit();\n try {\n await writeAccountFavorites(ai, on ? { add: [entry] } : { remove: [entry.ref.id] });\n } catch (error) {\n account = before;\n emit();\n throw error;\n }\n mirror(entry, on);\n return on;\n },\n /** Kept voices still unnamed. */\n unnamed: () => [...favorites(), ...state3.recents].filter(isUnnamed).map((entry) => ({ ...entry.ref })),\n /** Names the kept voices that still bear their id with these listed entries; true when one changed. */\n name(entries) {\n const listed = new Map(Array.from(entries).map((entry) => [entry.ref.id, entry]));\n const named = (entry) => {\n const found = isUnnamed(entry) ? listed.get(entry.ref.id) : void 0;\n return found && !isUnnamed(found) ? keptEntry({ ...found, ref: { ...entry.ref } }) : entry;\n };\n let renamed = false;\n for (const entry of account ?? []) {\n const found = named(entry);\n if (found !== entry && !names.has(entry.ref.id)) {\n names.set(entry.ref.id, found);\n renamed = true;\n }\n }\n state3 = read4();\n const next = { ...state3, favorites: state3.favorites.map(named), recents: state3.recents.map(named) };\n const changed = next.favorites.some((entry, index) => entry !== state3.favorites[index]) || next.recents.some((entry, index) => entry !== state3.recents[index]);\n if (changed) write2(state3 = next);\n return changed || renamed;\n },\n used(entry) {\n state3 = read4();\n write2(state3 = { ...state3, recents: [keptEntry(entry), ...state3.recents.filter((item) => item.ref.id !== entry.ref.id)].slice(0, recentLimit) });\n },\n /** Calls `listener` whenever the favourites shown change; returns the unsubscription. */\n subscribe(listener) {\n listeners2.add(listener);\n return () => {\n listeners2.delete(listener);\n };\n },\n dispose() {\n listeners2.clear();\n stopListening?.();\n }\n };\n}\n\n// src/voice-picker-bar.ts\nvar groups = ["language", "accent", "gender", "age", "useCase", "collection", "cost", "sort"];\nfunction filterChips(context) {\n const { doc, text: text6, state: state3 } = context;\n const chips = [];\n const chipClass = (enabled2, active3 = false) => `nocha-voice-picker__chip${active3 ? " nocha-voice-picker__chip--active" : ""}${enabled2 ? "" : " nocha-voice-picker__chip--disabled"}`;\n const inert = (enabled2) => ({ disabled: !enabled2, "aria-disabled": enabled2 ? null : "true", title: enabled2 ? null : text6.unsupportedFilter });\n for (const group of groups) {\n if (!context.offered(group)) continue;\n const value = context.valueOf(group);\n const enabled2 = context.answers(group);\n const active3 = value !== void 0;\n const label = active3 ? context.choicesOf(group).find((choice) => choice.value === value)?.label ?? listedLabel(value ?? "") : "";\n const chip = element(doc, "button", chipClass(enabled2, active3), {\n type: "button",\n "aria-expanded": String(context.openGroup === group),\n "aria-controls": context.choicesId,\n "aria-label": label ? `${text6.filters[group]}${context.locale === "fr" ? " : " : ": "}${label}` : text6.filters[group],\n ...inert(enabled2)\n }, label ? element(doc, "span", "", {}, label) : element(doc, "span", "nocha-voice-picker__chip-label", {}, text6.filters[group]), icon(doc, "chevron"));\n if (enabled2) chip.addEventListener("click", () => context.toggleGroup(group));\n chips.push(chip);\n }\n if (context.show.includes("model") && state3.model && !state3.allModels) {\n const enabled2 = context.answers("verifiedOnly");\n const verified = element(\n doc,\n "button",\n chipClass(enabled2),\n { type: "button", "aria-pressed": String(state3.verifiedOnly), ...inert(enabled2) },\n icon(doc, "check"),\n text6.verifiedOnly\n );\n if (enabled2) verified.addEventListener("click", () => context.toggleVerified());\n chips.push(verified);\n }\n if (context.show.includes("favorites")) {\n const favorites = element(\n doc,\n "button",\n "nocha-voice-picker__chip",\n { type: "button", "aria-pressed": String(state3.favorites) },\n icon(doc, "star"),\n text6.favorites\n );\n favorites.addEventListener("click", () => context.toggleFavorites());\n chips.unshift(favorites);\n }\n return chips;\n}\nfunction choiceChips(doc, choices, current4, choose2) {\n return choices.map((choice) => {\n const chip = element(doc, "button", "nocha-voice-picker__chip", { type: "button", "aria-pressed": String(choice.value === current4) }, choice.label);\n chip.addEventListener("click", () => choose2(choice.value));\n return chip;\n });\n}\n\n// src/voice-picker-facets.ts\nvar controlFacets = {\n language: "language",\n accent: "accent",\n gender: "gender",\n age: "age",\n useCase: "use_cases",\n collection: "collection",\n cost: "max_price_multiplier",\n sort: "sort",\n search: "query",\n verifiedOnly: "verified_for"\n};\nfunction answersFilter(models2, control) {\n return !models2.length || models2.some((model) => (control !== "collection" || model.capabilities?.voice_catalogue !== "fixed") && modelAnswersFacets(model, [controlFacets[control]]));\n}\nvar valueControls = ["language", "accent", "gender", "age", "useCase", "collection", "cost", "sort"];\nfunction dropUnanswered(state3, models2, shown) {\n for (const control of valueControls) if (shown(control) && !answersFilter(models2, control)) state3[control] = void 0;\n if (shown("search") && !answersFilter(models2, "search")) state3.query = "";\n if (shown("model") && !answersFilter(models2, "verifiedOnly")) state3.verifiedOnly = false;\n}\nfunction everyModel(models2, defaultModel) {\n return [...models2].sort((a, b) => Number(b.model === defaultModel) - Number(a.model === defaultModel));\n}\nfunction offeredModels(models2, wanted) {\n const named = Array.isArray(wanted) ? models2.filter((model) => wanted.includes(model.model)) : [];\n return named.length ? named : [...models2];\n}\nfunction filterChoices(group, context) {\n const { text: text6, locale, state: state3 } = context, any = { value: void 0, label: text6.any };\n const sorted = (values, label) => Array.from(new Set(values)).map((value) => ({ value, label: label(value) })).sort((a, b) => a.label.localeCompare(b.label, locale));\n switch (group) {\n case "language": {\n const listed = context.answering.flatMap((model) => model.languages ?? []);\n const codes2 = [...listed.map(baseLanguage), ...Array.from(context.languages), ...state3.language ? [state3.language] : []].filter((code) => /^[a-z]{2,3}$/u.test(code));\n const choices = sorted(codes2, (code) => languageName(code, locale));\n const own = choices.findIndex((choice) => choice.value === context.rankLanguage);\n if (own > 0) choices.unshift(...choices.splice(own, 1));\n return [any, ...choices];\n }\n case "accent":\n return [any, ...sorted([...Array.from(context.accents), ...state3.accent ? [state3.accent] : []], listedLabel)];\n case "gender":\n return [any, ...speechVoiceGenders.map((value) => ({ value, label: text6.genders[value] }))];\n case "age":\n return [any, ...speechVoiceAges.map((value) => ({ value, label: text6.ages[value] }))];\n case "useCase":\n return [any, ...sorted([...Array.from(context.useCases), ...state3.useCase ? [state3.useCase] : []], listedLabel)];\n case "collection":\n return [any, { value: "standard", label: text6.collections.standard }, { value: "library", label: text6.collections.library }];\n case "cost": {\n const fixed = context.ceiling;\n const under = (value) => typeof fixed !== "number" || !(fixed > 0) || value < fixed;\n if (!under(1)) return [];\n return [{ value: "1", label: text6.costs.one }, ...under(2) ? [{ value: "2", label: text6.costs.two }] : [], { value: void 0, label: text6.costs.all }];\n }\n case "sort":\n return [\n { value: void 0, label: text6.sorts.relevance },\n { value: "usage_character_count_1y", label: text6.sorts.popular },\n { value: "trending", label: text6.sorts.trending }\n ];\n }\n}\n\n// src/voice-picker-list.ts\nfunction showStatus(doc, status2, message2, action) {\n if (message2 === null) {\n status2.hidden = true;\n status2.replaceChildren();\n return;\n }\n const children = [element(doc, "span", "", {}, message2)];\n if (action) {\n const button = element(doc, "button", "nocha-voice-picker__chip", { type: "button" }, action.label);\n button.addEventListener("click", action.run);\n children.push(button);\n }\n status2.replaceChildren(...children);\n status2.hidden = false;\n}\nfunction pinnedEntry(ref, memory, listing, found) {\n if (!ref) return null;\n const kept = memory.find(ref.id);\n return listing?.entries.find((entry) => entry.ref.id === ref.id) ?? (found?.ref.id === ref.id ? found : null) ?? (kept && !isUnnamed(kept) ? kept : null) ?? placeholderEntry(ref);\n}\nfunction renderFavorites(context) {\n const { doc, text: text6, memory, pinned, ceiling: ceiling2, fits } = context;\n const query = context.query.toLowerCase();\n const matches2 = (entry) => !query || entry.name.toLowerCase().includes(query);\n const affordable = (entry) => ceiling2 === void 0 || (entry.premium ?? 1) <= ceiling2;\n const shown = (entry) => matches2(entry) && affordable(entry) && fits(entry) && entry.ref.id !== pinned?.ref.id;\n const favorites = memory.favorites().filter(shown);\n const recents = memory.recents().filter((entry) => shown(entry) && !memory.isFavorite(entry.ref.id));\n const section = (label) => element(doc, "li", "nocha-voice-picker__section", { role: "presentation" }, label);\n context.list.replaceChildren(\n ...pinned ? [context.pinRow(pinned)] : [],\n ...favorites.length ? [section(text6.favorites), ...favorites.map((entry) => context.row(entry))] : [],\n ...recents.length ? [section(text6.recents), ...recents.map((entry) => context.row(entry))] : []\n );\n if (pinned || favorites.length || recents.length) context.showStatus(null);\n else context.showStatus(text6.emptyFavorites);\n}\nfunction closeOnBackdrop(dialog, close) {\n dialog.addEventListener("click", (event) => {\n if (event.target !== dialog) return;\n const box = dialog.getBoundingClientRect();\n const outside = event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom;\n if (outside) close();\n });\n}\nfunction renderChoices(doc, choices, text6, group, handlers3) {\n choices.hidden = !group;\n if (!group) {\n choices.replaceChildren();\n return;\n }\n choices.setAttribute("aria-label", text6.filters[group]);\n choices.replaceChildren(...choiceChips(doc, handlers3.choicesOf(group), handlers3.valueOf(group), (value) => handlers3.choose(group, value)));\n}\n\n// src/voice-picker-models.ts\nvar microcreditsPerCredit = 1e4;\nvar numbers;\nfunction credits3(value, locale) {\n const small = value > 0 && value < 0.01;\n const key2 = `${locale}:${small}`;\n numbers ??= /* @__PURE__ */ new Map();\n let format = numbers.get(key2);\n if (!format) {\n format = new Intl.NumberFormat(locale, small ? { maximumSignificantDigits: 2 } : { maximumFractionDigits: 2 });\n numbers.set(key2, format);\n }\n return format.format(value);\n}\nfunction shownPrice(model) {\n const price = model?.price;\n const figure = price?.micro_credits_per_1000;\n return price && price.unit === "character" && typeof figure === "number" && Number.isFinite(figure) && figure >= 0 ? price : null;\n}\nfunction priceLabel(model, locale, text6, multiplier = 1) {\n const price = shownPrice(model);\n if (!price) return null;\n const factor = Number.isFinite(multiplier) && multiplier > 0 ? multiplier : 1;\n const figure = credits3(price.micro_credits_per_1000 * factor / microcreditsPerCredit, locale);\n return price.ceiling ? { label: fill(text6.priceCeiling, { credits: figure }), title: fill(text6.priceCeilingTitle, { credits: figure }) } : { label: fill(text6.price, { credits: figure }), title: fill(text6.priceTitle, { credits: figure }) };\n}\nfunction modelNote(model, failed, text6) {\n if (isModelUnavailable(model)) return text6.modelUnavailableHint;\n if (failed) return text6.modelFailed;\n return model?.availability === "degraded" ? text6.modelDegraded : null;\n}\nfunction modelButtons(context) {\n const { doc, text: text6, locale, models: models2 } = context;\n const button = (value, name, model) => {\n const unavailable2 = isModelUnavailable(model);\n const degraded = model?.availability === "degraded";\n const failed = Boolean(value && context.failed.has(value));\n const price = priceLabel(model, locale, text6);\n const access2 = model?.access === "relayed" || model?.access === "direct" ? model.access : void 0;\n const state3 = unavailable2 ? text6.modelUnavailable : degraded ? text6.modelDegradedShort : failed ? text6.modelFailedShort : "";\n const title = [\n name,\n price?.title,\n access2 && (access2 === "relayed" ? text6.relayedTitle : text6.directTitle),\n unavailable2 ? text6.modelUnavailableHint : degraded ? text6.modelDegraded : failed ? text6.modelFailed : ""\n ].filter(Boolean).join(" \\xB7 ");\n const modifiers = [unavailable2 && "unavailable", degraded && "degraded", failed && "failed"].filter(Boolean).map((modifier) => ` nocha-voice-picker__model--${modifier}`).join("");\n const chosen = value === context.selected;\n const item = element(\n doc,\n "button",\n `nocha-voice-picker__model${modifiers}`,\n {\n type: "button",\n "aria-pressed": String(chosen),\n title,\n "aria-label": title,\n disabled: unavailable2 && !chosen,\n "aria-disabled": unavailable2 ? "true" : null\n },\n element(\n doc,\n "span",\n "nocha-voice-picker__model-name",\n {},\n name,\n (degraded || failed) && !unavailable2 ? element(doc, "span", "nocha-voice-picker__model-warning", { "aria-hidden": "true" }, "!") : null\n ),\n element(\n doc,\n "span",\n "nocha-voice-picker__model-meta",\n {},\n price && element(doc, "span", "nocha-voice-picker__model-price", {}, price.label),\n access2 && element(doc, "span", "nocha-voice-picker__model-access", {}, access2 === "relayed" ? text6.relayed : text6.direct),\n state3 && element(doc, "span", "nocha-voice-picker__model-state", {}, state3)\n )\n );\n if (!unavailable2) item.addEventListener("click", () => context.choose(value));\n return item;\n };\n return [\n ...models2.length > 1 ? [button(void 0, text6.allModels)] : [],\n ...models2.map((model) => button(model.model, model.label || model.model, model))\n ];\n}\nfunction modelBar(doc, text6) {\n return element(doc, "div", "nocha-voice-picker__models", { role: "group", "aria-label": text6.models, hidden: true });\n}\nfunction chooseModelButton(doc, text6, run3, className) {\n const action = element(doc, "button", className, { type: "button" }, text6.chooseModel);\n action.addEventListener("click", run3);\n return action;\n}\nfunction voiceTarget(entry, choice) {\n const { allModels, model, offered, listed } = choice;\n if (!allModels) return !model ? entry.ref.model : voiceFits(entry.ref, model, listed) ? model : null;\n if (!offered.length) return entry.ref.model || model || null;\n const serving = offered.filter((item) => !isModelUnavailable(item));\n if (serving.some((item) => item.model === entry.ref.model)) return entry.ref.model;\n return serving.find((item) => voiceFits(entry.ref, item, listed))?.model ?? null;\n}\nfunction modelLabel(models2, id) {\n const model = id ? models2.find((item) => item.model === id) : void 0;\n return model ? model.label || model.model : "";\n}\n\n// src/voice-picker-row.ts\nvar numbers2;\nfunction formatted(value, locale, compact) {\n const key2 = `${locale}:${compact}`;\n numbers2 ??= /* @__PURE__ */ new Map();\n let format = numbers2.get(key2);\n if (!format) {\n format = new Intl.NumberFormat(locale, compact ? { notation: "compact", maximumFractionDigits: 1 } : { maximumFractionDigits: 2 });\n numbers2.set(key2, format);\n }\n return format.format(value);\n}\nfunction premiumBadge(multiplier, locale, text6, model) {\n if (multiplier === null || !(multiplier > 1)) return null;\n const number2 = formatted(multiplier, locale, false);\n const price = priceLabel(model, locale, text6, multiplier);\n return { label: `\\xD7${number2}`, title: [fill(text6.premium, { multiplier: number2 }), price?.title].filter(Boolean).join(" \\xB7 ") };\n}\nfunction popularityBadge(entry, locale, text6) {\n const usage = entry.usage1y, adds = entry.popularity;\n if (usage === void 0 && adds === void 0) return null;\n const parts = [\n usage !== void 0 && fill(text6.usage, { count: formatted(usage, locale, true) }),\n adds !== void 0 && fill(text6.adds, { count: formatted(adds, locale, true) })\n ].filter((part) => Boolean(part));\n return { label: usage !== void 0 ? `\\u25B6 ${formatted(usage, locale, true)}` : `+${formatted(adds, locale, true)}`, title: parts.join(" \\xB7 ") };\n}\nvar rematchTitle = (entry, text6) => entry.ref.model ? text6.modelUnavailableHint : text6.rematchTitle;\nfunction voiceRow(context, entry) {\n const { doc, text: text6 } = context, name = entry.spokenName || entry.name;\n const selected2 = context.selected() === entry.ref.id;\n const rest = (entry.name.startsWith(name) ? entry.name.slice(name.length) : entry.name).replace(/^[\\s\\-\u2013\u2014|,(]+/u, "").replace(/\\)$/u, "").trim();\n const listen = element(\n doc,\n "button",\n "nocha-voice-picker__listen",\n { type: "button" },\n element(doc, "span", "nocha-voice-picker__listen-ring", {}, icon(doc, "play"))\n );\n listen.addEventListener("click", () => {\n const model = context.model(entry);\n context.samples.toggle(model && model !== entry.ref.model ? { ...entry, ref: { id: entry.ref.id, model } } : entry, context.sampleLanguage());\n });\n const popular = popularityBadge(entry, context.locale, text6);\n const rematch = context.rematch(entry);\n const pickable = context.pickable !== false;\n const choose2 = element(\n doc,\n pickable ? "button" : "div",\n "nocha-voice-picker__choose",\n pickable ? {\n type: "button",\n disabled: rematch,\n title: rematch ? rematchTitle(entry, text6) : null,\n "aria-label": [fill(text6.choose, { name: entry.name }), context.modelLabel(entry), rematch && rematchTitle(entry, text6), popular?.title].filter(Boolean).join(" \\xB7 ")\n } : {},\n element(\n doc,\n "span",\n "nocha-voice-picker__line",\n {},\n element(doc, "span", "nocha-voice-picker__name", {}, name),\n rest && element(doc, "span", "nocha-voice-picker__full", {}, rest)\n ),\n rowMeta(context, entry)\n );\n if (pickable) choose2.addEventListener("click", () => context.pick(entry));\n const favorite = element(doc, "button", "nocha-voice-picker__favorite", { type: "button" }, icon(doc, "star"));\n favorite.addEventListener("click", () => context.toggleFavorite(entry));\n const openCategories = context.categorize;\n const categorize = openCategories ? element(doc, "button", "nocha-voice-picker__categorize", { type: "button", "aria-haspopup": "dialog" }, icon(doc, "plus")) : void 0;\n categorize?.addEventListener("click", () => openCategories?.(entry));\n const item = element(\n doc,\n "li",\n `nocha-voice-picker__item${selected2 ? " nocha-voice-picker__item--selected" : ""}`,\n {},\n listen,\n choose2,\n selected2 && element(doc, "span", "nocha-voice-picker__check", { title: text6.selected }, icon(doc, "check")),\n categorize,\n favorite\n );\n const row2 = { item, listen, favorite, entry, ...categorize ? { categorize } : {} };\n updateVoiceRow(context, row2);\n return row2;\n}\nfunction rowMeta(context, entry) {\n const { doc, text: text6, locale } = context;\n const wanted = context.language();\n const language2 = entry.languages.includes(wanted) || entry.dialects?.some((dialect2) => dialect2.language === wanted) ? wanted : entry.languages[0];\n const dialect = entry.dialects?.find((item) => item.language === language2 && item.accent);\n const accent = dialect?.accent ?? (language2 === entry.languages[0] ? entry.traits.accent : void 0);\n const others = entry.languages.filter((code) => code !== language2).length;\n const traits = [\n entry.traits.gender ? text6.genders[entry.traits.gender] : entry.traits.listed?.gender && listedLabel(entry.traits.listed.gender),\n entry.traits.age ? text6.ages[entry.traits.age] : entry.traits.listed?.age && listedLabel(entry.traits.listed.age)\n ].filter(Boolean).join(" \\xB7 ");\n const tag2 = (content, modifier, title) => element(doc, "span", `nocha-voice-picker__tag${modifier ? ` nocha-voice-picker__tag--${modifier}` : ""}`, { title }, content);\n const model = context.model(entry);\n const verified = Boolean(model && entry.models?.length) && voiceVerifiedFor(entry, model);\n const premium = premiumBadge(entry.premium, locale, text6, context.spec(entry));\n const popular = popularityBadge(entry, locale, text6);\n const modelName = context.modelLabel(entry);\n return element(\n doc,\n "span",\n "nocha-voice-picker__meta",\n {},\n modelName && tag2(modelName, "model"),\n context.rematch(entry) && tag2(text6.rematch, "rematch", rematchTitle(entry, text6)),\n language2 && tag2([language2.toUpperCase(), accent && listedLabel(accent)].filter(Boolean).join(" \\xB7 "), "language", languageName(language2, locale)),\n others > 0 && tag2(`+${others}`, void 0, fill(text6.languages, { count: others + 1 })),\n traits && tag2(traits),\n premium && element(doc, "span", "nocha-voice-picker__tag nocha-voice-picker__tag--premium", { title: premium.title, "aria-label": premium.title }, premium.label),\n popular && element(doc, "span", "nocha-voice-picker__tag nocha-voice-picker__tag--popularity", { title: popular.title }, popular.label),\n verified && element(doc, "span", "nocha-voice-picker__verified", { title: text6.verified, role: "img", "aria-label": text6.verified }, icon(doc, "check")),\n element(doc, "span", "nocha-voice-picker__tag nocha-voice-picker__tag--missing", { hidden: true }, text6.noPreview)\n );\n}\nfunction updateVoiceRow(context, row2) {\n const { item, listen, favorite, entry } = row2, { text: text6, samples: samples2 } = context;\n const id = entry.ref.id;\n const state3 = context.sampleState(id);\n const busy = state3 === "playing" || state3 === "loading";\n const unavailable2 = samples2.unavailable(entry);\n const paid = !unavailable2 && samples2.paid(entry);\n const missing = unavailable2 || !paid && (samples2.silent(entry) || state3 === "missing");\n const name = entry.spokenName || entry.name;\n item.classList.toggle("nocha-voice-picker__item--playing", state3 === "playing");\n item.classList.toggle("nocha-voice-picker__item--loading", state3 === "loading");\n item.classList.toggle("nocha-voice-picker__item--unavailable", unavailable2);\n listen.disabled = missing;\n listen.classList.toggle("nocha-voice-picker__listen--paid", paid);\n listen.setAttribute("aria-label", unavailable2 ? text6.voiceUnavailable : missing ? text6.noPreview : busy ? text6.stop : paid ? `${text6.auditionPaid} \\xB7 ${name}` : fill(text6.listen, { name }));\n listen.title = listen.getAttribute("aria-label") ?? "";\n listen.querySelector(".nocha-voice-picker__listen-ring")?.replaceChildren(icon(context.doc, missing ? "dash" : busy ? "stop" : "play"));\n const tag2 = item.querySelector(".nocha-voice-picker__tag--missing");\n if (tag2) {\n tag2.hidden = !missing && !paid;\n tag2.textContent = unavailable2 ? text6.voiceUnavailable : paid ? text6.auditionPaid : text6.noPreview;\n }\n const on = context.memory.isFavorite(id);\n favorite.setAttribute("aria-pressed", String(on));\n favorite.setAttribute("aria-label", fill(on ? text6.removeFavorite : text6.addFavorite, { name }));\n if (row2.categorize) {\n const kept = context.categorized?.(id) ?? false;\n row2.categorize.setAttribute("aria-pressed", String(kept));\n row2.categorize.setAttribute("aria-label", fill(kept ? text6.categorized : text6.categorize, { name }));\n row2.categorize.title = row2.categorize.getAttribute("aria-label") ?? "";\n }\n}\n\n// src/voice-picker-state.ts\nfunction pickOf(entry, model) {\n const ref = { id: entry.ref.id, model };\n return { ref: { ...ref }, entry: { ...entry, ref: { ...ref } } };\n}\nfunction initialState(options) {\n const filters = options.filters ?? {};\n return {\n query: "",\n model: options.model ?? "",\n allModels: false,\n ...options.language ? { language: baseLanguage(options.language) } : {},\n ...isFacet(filters.accent) ? { accent: filters.accent.toLowerCase() } : {},\n ...speechVoiceGenders.includes(filters.gender) ? { gender: filters.gender } : {},\n ...speechVoiceAges.includes(filters.age) ? { age: filters.age } : {},\n ...isFacet(filters.useCases?.[0]) ? { useCase: filters.useCases[0] } : {},\n ...filters.collection === "standard" || filters.collection === "library" ? { collection: filters.collection } : {},\n verifiedOnly: filters.verifiedFor !== void 0,\n favorites: false\n };\n}\nfunction voiceQuery({ state: state3, fixed, show: show2, models: models2, defaultModel, spec, ceiling: ceiling2 }) {\n const verifiedFor = state3.allModels ? void 0 : show2.includes("model") ? state3.verifiedOnly && state3.model ? state3.model : void 0 : fixed.verifiedFor;\n return {\n model: state3.allModels ? "" : state3.model,\n ...state3.allModels ? { models: everyModel(models2, defaultModel) } : {},\n ...!state3.allModels && spec ? { spec } : {},\n ...state3.language ? { language: state3.language } : {},\n ...state3.collection ? { collection: state3.collection } : {},\n ...state3.query ? { query: state3.query } : {},\n ...state3.gender ? { gender: state3.gender } : {},\n ...state3.age ? { age: state3.age } : {},\n ...state3.accent ? { accent: state3.accent } : {},\n ...state3.useCase ? { useCase: state3.useCase } : {},\n ...verifiedFor ? { verifiedFor } : {},\n ...typeof fixed.featured === "boolean" ? { featured: fixed.featured } : {},\n ...ceiling2 !== void 0 ? { maxPriceMultiplier: ceiling2 } : {},\n ...state3.sort ? { sort: state3.sort } : {}\n };\n}\nfunction priceCeiling(fixed, cost) {\n const own = typeof fixed === "number" && Number.isFinite(fixed) && fixed > 0 ? fixed : void 0;\n const chosen = cost ? Number(cost) : void 0;\n return chosen !== void 0 && own !== void 0 ? Math.min(chosen, own) : chosen ?? own;\n}\nvar SeenFacets = class {\n languages = /* @__PURE__ */ new Set();\n accents = /* @__PURE__ */ new Map();\n useCases = /* @__PURE__ */ new Set();\n learn(entries) {\n for (const entry of entries) {\n for (const code of entry.languages) this.languages.add(code);\n for (const dialect of entry.dialects ?? []) {\n this.languages.add(dialect.language);\n if (isFacet(dialect.accent)) this.accentsOf(dialect.language).add(dialect.accent);\n }\n const accent = entry.traits.accent;\n if (isFacet(accent)) {\n this.accentsOf("").add(accent);\n for (const code of entry.languages.slice(0, 1)) this.accentsOf(code).add(accent);\n }\n if (isFacet(entry.useCase)) this.useCases.add(entry.useCase);\n }\n }\n accentsOf(language2) {\n let accents = this.accents.get(language2);\n if (!accents) this.accents.set(language2, accents = /* @__PURE__ */ new Set());\n return accents;\n }\n};\nfunction applyChoice(state3, group, value) {\n if (group === "language") {\n if (state3.language !== value) state3.accent = void 0;\n state3.language = value;\n } else if (group === "gender") state3.gender = value;\n else if (group === "age") state3.age = value;\n else if (group === "collection") state3.collection = value;\n else if (group === "sort") state3.sort = value;\n else state3[group] = value;\n if (group !== "cost") state3.favorites = false;\n}\nfunction isFiltered(state3, show2) {\n return Boolean(state3.query || state3.accent || state3.gender || state3.age || state3.useCase || state3.collection || state3.cost || state3.verifiedOnly && !state3.allModels || state3.language && show2.includes("language"));\n}\nfunction clearFilterState(state3, show2) {\n const keep2 = (group) => !show2.includes(group);\n if (!keep2("accent")) state3.accent = void 0;\n if (!keep2("gender")) state3.gender = void 0;\n if (!keep2("age")) state3.age = void 0;\n if (!keep2("useCase")) state3.useCase = void 0;\n if (!keep2("collection")) state3.collection = void 0;\n if (!keep2("cost")) state3.cost = void 0;\n if (!keep2("language")) state3.language = void 0;\n if (show2.includes("model")) state3.verifiedOnly = false;\n state3.query = "";\n}\n\n// src/voice-picker-types.ts\nvar voicePickerFilters = ["search", "language", "accent", "gender", "age", "useCase", "model", "collection", "cost", "sort", "favorites"];\nvar voicePickerTexts = {\n fr: {\n title: "Choisir une voix",\n close: "Fermer",\n search: "Rechercher une voix",\n loading: "Chargement\\u2026",\n empty: "Aucune voix",\n emptyFavorites: "Ni favorite ni r\\xE9cente",\n clearFilters: "Effacer les filtres",\n unavailable: "Catalogue indisponible",\n retry: "R\\xE9essayer",\n listen: "\\xC9couter {name}",\n stop: "Arr\\xEAter",\n noPreview: "Pas d\\u2019extrait gratuit",\n addFavorite: "Ajouter {name} aux favorites",\n removeFavorite: "Retirer {name} des favorites",\n favorites: "Favorites",\n recents: "R\\xE9centes",\n selected: "Choisie",\n verified: "V\\xE9rifi\\xE9e pour ce mod\\xE8le",\n verifiedOnly: "V\\xE9rifi\\xE9es",\n premium: "Co\\xFBte {multiplier} fois plus de cr\\xE9dits",\n any: "Toutes",\n choose: "Choisir {name}",\n fieldEmpty: "Choisir une voix",\n languages: "{count} langues",\n auditionPaid: "Essai payant",\n voiceUnavailable: "Voix indisponible",\n usage: "{count} caract\\xE8res lus en 1 an",\n adds: "{count} ajouts",\n favoritesFull: "Favorites pleines ({limit} au plus) : retirez-en une d\\u2019abord",\n favoritesFailed: "Favorite non enregistr\\xE9e, r\\xE9essayez",\n allModels: "Tous les mod\\xE8les",\n unsupportedFilter: "Ce mod\\xE8le ne propose pas ce filtre",\n models: "Mod\\xE8le",\n price: "{credits} cr / 1 000 car.",\n priceCeiling: "jusqu\\u2019\\xE0 {credits} cr / 1 000 car.",\n priceTitle: "{credits} cr\\xE9dits pour 1 000 caract\\xE8res",\n priceCeilingTitle: "Au plus {credits} cr\\xE9dits pour 1 000 caract\\xE8res, selon le co\\xFBt du fournisseur",\n relayed: "Relay\\xE9",\n direct: "Direct",\n relayedTitle: "Servi par une plateforme interm\\xE9diaire",\n directTitle: "Servi par son propre fournisseur",\n modelUnavailable: "Indisponible",\n modelUnavailableHint: "Ce mod\\xE8le est indisponible pour le moment : choisissez-en un autre",\n modelDegraded: "Service perturb\\xE9 : la cr\\xE9ation de la voix peut \\xE9chouer ou tarder",\n modelDegradedShort: "Perturb\\xE9",\n modelFailed: "Les voix de ce mod\\xE8le n\\u2019ont pas pu \\xEAtre lues",\n modelFailedShort: "Non lu",\n chooseModel: "Choisir un autre mod\\xE8le",\n rematch: "\\xC0 r\\xE9associer",\n rematchTitle: "Favorite gard\\xE9e sans mod\\xE8le : retrouvez-la dans la liste d\\u2019un mod\\xE8le",\n voiceMismatch: "Cette voix ne va pas avec {model} : choisissez-en une",\n modelRefused: "Ce mod\\xE8le n\\u2019a pas pu cr\\xE9er la voix",\n categories: "Mes cat\\xE9gories",\n categorize: "Ajouter {name} \\xE0 une cat\\xE9gorie",\n categorized: "{name} : cat\\xE9gories",\n newCategory: "Nouvelle cat\\xE9gorie",\n categoryName: "Nom de la cat\\xE9gorie",\n create: "Cr\\xE9er",\n rename: "Renommer",\n save: "Enregistrer",\n cancel: "Annuler",\n deleteCategory: "Supprimer",\n confirmDelete: "Supprimer \\xAB {name} \\xBB ?",\n emptyCategory: "Aucune voix dans cette cat\\xE9gorie",\n noCategories: "Aucune cat\\xE9gorie : ajoutez une voix \\xE0 une nouvelle cat\\xE9gorie",\n categoriesFailed: "Cat\\xE9gorie non enregistr\\xE9e, r\\xE9essayez",\n filters: {\n language: "Langue",\n accent: "Accent",\n gender: "Genre",\n age: "\\xC2ge",\n useCase: "Usage",\n model: "Mod\\xE8le",\n collection: "Source",\n cost: "Co\\xFBt",\n sort: "Tri"\n },\n costs: { one: "\\xD71", two: "jusqu\\u2019\\xE0 \\xD72", all: "Toutes" },\n sorts: { relevance: "Pertinence", popular: "Populaires", trending: "Tendance" },\n genders: { female: "F\\xE9minine", male: "Masculine", neutral: "Neutre" },\n ages: { young: "Jeune", middle: "Adulte", old: "\\xC2g\\xE9e" },\n collections: { standard: "Int\\xE9gr\\xE9es", library: "Biblioth\\xE8que" }\n },\n en: {\n title: "Choose a voice",\n close: "Close",\n search: "Search voices",\n loading: "Loading\\u2026",\n empty: "No voices",\n emptyFavorites: "No favourite or recent voices",\n clearFilters: "Clear filters",\n unavailable: "Catalogue unavailable",\n retry: "Retry",\n listen: "Listen to {name}",\n stop: "Stop",\n noPreview: "No free sample",\n addFavorite: "Add {name} to favourites",\n removeFavorite: "Remove {name} from favourites",\n favorites: "Favourites",\n recents: "Recent",\n selected: "Chosen",\n verified: "Verified for this model",\n verifiedOnly: "Verified",\n premium: "Costs {multiplier} times as many credits",\n any: "All",\n choose: "Choose {name}",\n fieldEmpty: "Choose a voice",\n languages: "{count} languages",\n auditionPaid: "Paid sample",\n voiceUnavailable: "Voice unavailable",\n usage: "{count} characters read in a year",\n adds: "Added {count} times",\n favoritesFull: "Favourites are full ({limit} at most): remove one first",\n favoritesFailed: "Favourite not saved, try again",\n allModels: "All models",\n unsupportedFilter: "This model has no such filter",\n models: "Model",\n price: "{credits} cr / 1,000 chars",\n priceCeiling: "up to {credits} cr / 1,000 chars",\n priceTitle: "{credits} credits per 1,000 characters",\n priceCeilingTitle: "At most {credits} credits per 1,000 characters, following the provider\\u2019s cost",\n relayed: "Relayed",\n direct: "Direct",\n relayedTitle: "Served through an intermediary platform",\n directTitle: "Served by its own provider",\n modelUnavailable: "Unavailable",\n modelUnavailableHint: "This model is unavailable right now: choose another one",\n modelDegraded: "Service disrupted: creating speech may fail or take longer",\n modelDegradedShort: "Disrupted",\n modelFailed: "This model\\u2019s voices could not be read",\n modelFailedShort: "Not read",\n chooseModel: "Choose another model",\n rematch: "To match again",\n rematchTitle: "Favourite kept without a model: find it again in a model\\u2019s list",\n voiceMismatch: "This voice does not go with {model}: choose one",\n modelRefused: "This model could not create the speech",\n categories: "My categories",\n categorize: "Add {name} to a category",\n categorized: "{name}: categories",\n newCategory: "New category",\n categoryName: "Category name",\n create: "Create",\n rename: "Rename",\n save: "Save",\n cancel: "Cancel",\n deleteCategory: "Delete",\n confirmDelete: "Delete \\u201C{name}\\u201D?",\n emptyCategory: "No voices in this category",\n noCategories: "No categories yet: add a voice to a new one",\n categoriesFailed: "Category not saved, try again",\n filters: {\n language: "Language",\n accent: "Accent",\n gender: "Gender",\n age: "Age",\n useCase: "Use",\n model: "Model",\n collection: "Source",\n cost: "Cost",\n sort: "Sort"\n },\n costs: { one: "\\xD71 only", two: "up to \\xD72", all: "All" },\n sorts: { relevance: "Relevance", popular: "Popular", trending: "Trending" },\n genders: { female: "Female", male: "Male", neutral: "Neutral" },\n ages: { young: "Young", middle: "Middle-aged", old: "Old" },\n collections: { standard: "Built-in", library: "Library" }\n }\n};\nvar voiceImagineTexts = {\n fr: {\n label: "Utiliser seulement mes voix favorites",\n count: "{count} favorites",\n countOne: "1 favorite",\n none: "Ajoutez des voix favorites (\\u2605) dans le choix des voix pour l\\u2019activer",\n device: "R\\xE9glage gard\\xE9 sur cet appareil",\n loading: "Chargement\\u2026",\n drawEmpty: "Aucune voix favorite : voix tir\\xE9es dans tout le catalogue",\n drawIncompatible: "Aucune voix favorite{gender}{language} : voix tir\\xE9es dans tout le catalogue",\n drawUnavailable: "Voix favorites indisponibles : voix tir\\xE9es dans tout le catalogue",\n genders: { female: "f\\xE9minine", male: "masculine", neutral: "neutre" },\n inLanguage: "en {language}"\n },\n en: {\n label: "Only use my favourite voices",\n count: "{count} favourites",\n countOne: "1 favourite",\n none: "Star voices (\\u2605) in the voice picker to turn this on",\n device: "Saved on this device only",\n loading: "Loading\\u2026",\n drawEmpty: "No favourite voices: voices drawn from the whole catalogue",\n drawIncompatible: "No{gender} favourite voices{language}: voices drawn from the whole catalogue",\n drawUnavailable: "Favourite voices unavailable: voices drawn from the whole catalogue",\n genders: { female: "female", male: "male", neutral: "neutral" },\n inLanguage: "in {language}"\n }\n};\n\n// src/voice-browser-core.ts\nvar searchDelayMs = 300;\nvar noticeMs = 4e3;\nvar VoiceBrowserCore = class {\n #ai;\n #options;\n #init;\n #doc;\n #text;\n #locale;\n #show;\n #memory;\n #samples;\n #sampleStates = /* @__PURE__ */ new Map();\n #rankLanguage;\n #input;\n #modelBar;\n #modelNote;\n #bar;\n #choices;\n #body;\n #list;\n #status;\n #notice;\n #sentinel;\n #rowContext;\n #rows = /* @__PURE__ */ new Map();\n #seen = new SeenFacets();\n /** The entries the catalogue answered, to show a category\'s voices by name. */\n #entries = /* @__PURE__ */ new Map();\n #categories;\n /** The title\'s id, for the frame\'s `aria-labelledby`. */\n titleId;\n /** Every model the host lists (their voice groups), those the selector offers, those whose voices failed to read. */\n #listed = [];\n #models = [];\n #failed = /* @__PURE__ */ new Set();\n #defaultModel = "";\n #state;\n #openGroup = null;\n #listing = null;\n #reading = null;\n #loadingMore = false;\n #exhausted = false;\n #searchTimer;\n #noticeTimer;\n #observer = null;\n #ready = null;\n #selected;\n /** The current voice (with the name its experience gave), and its entry once a read or the field named it (`pinCurrent`). */\n #current;\n #found = null;\n #lookup = null;\n /** Shown: between `start` and `stop`. */\n #active = false;\n #disposed = false;\n constructor(ai, options, init) {\n this.#ai = ai;\n this.#options = options;\n this.#init = init;\n this.#selected = options.value?.id;\n this.#current = options.value ? { ...options.value } : null;\n if (init.known && init.known.ref.id === options.value?.id) this.#found = init.known;\n this.#locale = uiLocale(options.locale);\n this.#text = uiTexts(voicePickerTexts, this.#locale, options.labels);\n this.#show = (Array.isArray(options.show) ? options.show : voicePickerFilters).filter((name) => voicePickerFilters.includes(name));\n this.#memory = createVoiceMemory(options.storageKey, options.favoritesSeed, ai);\n this.#memory.subscribe(() => this.#refreshRows());\n this.#samples = createSamplePlayer(ai, (id, state3) => this.#sampleChanged(id, state3), options.audition);\n const browser = typeof navigator === "undefined" ? "" : navigator.language;\n this.#rankLanguage = baseLanguage(options.language ?? language.get() ?? browser);\n this.#state = initialState(options);\n const doc = this.#doc = init.frame.ownerDocument;\n const titleId = this.titleId = `nocha-voice-picker-title-${Math.random().toString(36).slice(2, 10)}`;\n let close = null;\n if (init.close) {\n const closing = init.close;\n close = element(doc, "button", "nocha-voice-picker__close", { type: "button", "aria-label": this.#text.close }, icon(doc, "close"));\n close.addEventListener("click", () => closing());\n }\n this.#input = this.#show.includes("search") ? element(doc, "input", "nocha-voice-picker__input", {\n type: "search",\n placeholder: this.#text.search,\n "aria-label": this.#text.search,\n autocomplete: "off",\n spellcheck: "false",\n enterkeyhint: "search"\n }) : null;\n this.#input?.addEventListener("input", () => this.#searchChanged());\n this.#modelBar = modelBar(doc, this.#text);\n this.#modelNote = element(doc, "div", "nocha-voice-picker__model-note", { role: "status", hidden: true });\n this.#bar = element(doc, "div", "nocha-voice-picker__bar");\n this.#choices = element(doc, "div", "nocha-voice-picker__options", { hidden: true, id: `${titleId}-options` });\n this.#list = element(doc, "ul", "nocha-voice-picker__list", { role: "list" });\n this.#sentinel = element(doc, "li", "nocha-voice-picker__sentinel", { "aria-hidden": "true" });\n this.#status = element(doc, "div", "nocha-voice-picker__status", { role: "status", hidden: true });\n this.#notice = element(doc, "div", "nocha-voice-picker__notice", { role: "status", hidden: true });\n this.#body = element(doc, "div", "nocha-voice-picker__body", {}, this.#list, this.#status);\n const search = this.#input && element(doc, "div", "nocha-voice-picker__search", {}, icon(doc, "search"), this.#input);\n init.frame.setAttribute("aria-labelledby", titleId);\n init.frame.append(\n element(\n doc,\n "header",\n "nocha-voice-picker__head",\n {},\n element(doc, "h2", "nocha-voice-picker__title", { id: titleId }, options.title ?? this.#text.title),\n close\n ),\n this.#modelBar,\n this.#modelNote,\n ...search ? [search] : [],\n this.#bar,\n this.#choices,\n this.#notice,\n this.#body\n );\n const store = init.categories;\n this.#categories = store ? new VoiceCategories({\n doc,\n text: this.#text,\n store,\n frame: init.frame,\n changed: (list5) => {\n this.#refreshRows();\n if (list5 && this.#categories?.active) this.#renderList(true);\n this.#renderBar();\n },\n filtered: () => {\n if (this.#categories?.active) this.#state.favorites = false;\n this.#renderBar();\n void this.#reload();\n },\n say: (message2) => this.#say(message2)\n }) : null;\n this.#rowContext = {\n doc,\n text: this.#text,\n locale: this.#locale,\n samples: this.#samples,\n memory: this.#memory,\n language: () => this.#state.language ?? this.#rankLanguage,\n sampleLanguage: () => this.#state.language ?? this.#rankLanguage,\n model: (entry) => this.#sentWith(entry) ?? "",\n selected: () => this.#selected,\n // Over every model each row names its model; in one model\'s list, only a pinned voice of another one.\n modelLabel: (entry) => this.#state.allModels || this.#target(entry) === null ? modelLabel(this.#listed, this.#sentWith(entry)) : "",\n spec: (entry) => this.#listed.find((model) => model.model === this.#sentWith(entry)),\n rematch: (entry) => this.#rematch(entry),\n sampleState: (id) => this.#sampleStates.get(id) ?? "idle",\n pickable: Boolean(init.pick),\n pick: (entry) => this.#picked(entry),\n toggleFavorite: (entry) => this.#toggleFavorite(entry),\n ...this.#categories ? {\n categorize: (entry) => this.#categories?.openMenu(entry, this.#keptRef(entry)),\n categorized: (id) => this.#categories?.has(id) ?? false\n } : {}\n };\n if (typeof IntersectionObserver !== "undefined") {\n this.#observer = new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) void this.#more();\n }, { root: this.#body, rootMargin: "0px 0px 600px 0px" });\n }\n }\n /** Shown: reads the models, the list, the account\'s favourites and the categories. */\n start() {\n if (this.#disposed) return;\n this.#active = true;\n if (this.#input && typeof matchMedia === "function" && matchMedia("(pointer: fine)").matches) this.#input.focus();\n this.#ready ??= readModels(this.#ai).then(({ models: models2, defaultModel }) => {\n this.#listed = models2;\n this.#models = offeredModels(models2, this.#options.models);\n this.#defaultModel = chooseSpeechModel(this.#models, defaultModel, void 0);\n this.#state.model = chooseSpeechModel(this.#models, defaultModel, this.#state.model || void 0);\n this.#dropUnanswered();\n });\n void this.#ready.then(() => {\n if (this.#disposed || !this.#active) return;\n this.#renderBar();\n if (this.#init.focusModels) this.#modelBar.querySelector(\'[aria-pressed="true"]\')?.focus();\n void this.#reload();\n void this.#name();\n });\n void this.#memory.sync().then(() => {\n if (!this.#disposed && this.#active && this.#state.favorites) this.#renderList(true);\n });\n void this.#categories?.load();\n this.#renderBar();\n }\n /** Reads everything again (`VoiceBrowser.refresh`). */\n refresh() {\n if (this.#disposed || !this.#active) return;\n void this.#memory.sync({ refresh: true });\n void this.#categories?.load();\n void this.#reload();\n }\n /** Hidden: the sample stops, the open filter folds. */\n stop() {\n this.#active = false;\n this.#samples.stop();\n this.#openGroup = null;\n this.#categories?.fold();\n this.#categories?.closeMenu();\n }\n /** Escape in the page: folds what is open first; false once nothing was. */\n fold() {\n if (this.#categories?.closeMenu()) return true;\n if (this.#openGroup || this.#categories?.open) {\n this.#openGroup = null;\n this.#categories?.fold();\n this.#renderBar();\n return true;\n }\n return false;\n }\n dispose() {\n if (this.#disposed) return;\n this.stop();\n this.#disposed = true;\n this.#reading?.abort();\n this.#lookup?.abort();\n clearTimeout(this.#searchTimer);\n clearTimeout(this.#noticeTimer);\n this.#observer?.disconnect();\n this.#samples.dispose();\n this.#memory.dispose();\n this.#categories?.dispose();\n }\n /* ------------------------------------------------------------------ reads */\n #query() {\n return voiceQuery({\n state: this.#state,\n fixed: this.#options.filters ?? {},\n show: this.#show,\n models: this.#models,\n defaultModel: this.#defaultModel,\n spec: this.#spec(),\n ceiling: this.#ceiling()\n });\n }\n #ceiling() {\n return priceCeiling(this.#options.filters?.maxPriceMultiplier, this.#state.cost);\n }\n /** The favourites view or a category: drawn from what is kept, no catalogue read. */\n #local() {\n return this.#state.favorites || Boolean(this.#categories?.active);\n }\n async #reload() {\n this.#reading?.abort();\n const reading = this.#reading = new AbortController();\n this.#listing = null;\n this.#exhausted = false;\n if (this.#local() || this.#blocked()) {\n this.#renderList(true);\n return;\n }\n this.#renderList(true);\n this.#showStatus(this.#text.loading);\n const model = this.#state.allModels ? "" : this.#state.model;\n try {\n const listing = await readVoices(this.#ai, this.#query(), null, this.#rankLanguage, reading.signal);\n if (reading.signal.aborted || this.#disposed) return;\n this.#listing = listing;\n this.#failed = new Set(listing.failed ?? []);\n this.#learn(listing.entries);\n this.#renderBar();\n this.#renderList(true);\n } catch {\n if (reading.signal.aborted || this.#disposed) return;\n this.#failed = new Set(model ? [model] : this.#models.map((item) => item.model));\n this.#renderModels();\n this.#showStatus(this.#text.unavailable, { label: this.#text.retry, run: () => void this.#reload() });\n }\n }\n async #more() {\n const listing = this.#listing, reading = this.#reading;\n if (!listing?.cursor || !reading || this.#loadingMore || this.#exhausted || this.#local()) return;\n this.#loadingMore = true;\n try {\n const next = await readVoices(this.#ai, this.#query(), listing, this.#rankLanguage, reading.signal);\n if (reading.signal.aborted || this.#listing !== listing) return;\n if (next.entries.length === listing.entries.length) this.#exhausted = true;\n this.#listing = next;\n this.#learn(next.entries.slice(listing.entries.length));\n this.#renderBar();\n this.#renderList(false);\n } catch {\n } finally {\n this.#loadingMore = false;\n }\n if (this.#listing?.cursor && !this.#exhausted && this.#sentinelNear()) void this.#more();\n }\n /** Names the kept voices that still bear their id (a favourite seed, a category\'s voices) and the pinned current\n * voice, from one catalogue read per opening. */\n async #name() {\n const current4 = this.#options.pinCurrent ? this.#current : null;\n const known = (ref) => {\n const kept = this.#memory.find(ref.id);\n return this.#found?.ref.id === ref.id || Boolean(kept && !isUnnamed(kept));\n };\n const shelved = (this.#categories?.active?.voices ?? []).filter((ref) => !this.#entries.has(ref.id) && isUnnamed(this.#entryOf(ref)));\n const refs = [...this.#memory.unnamed(), ...shelved, ...current4 && !known(current4) && isUnnamed(placeholderEntry(current4)) ? [current4] : []].filter((ref) => !lookedUpInVain(this.#ai, ref.id));\n if (!refs.length || this.#lookup) return;\n const lookup = this.#lookup = new AbortController();\n const found = await findVoices(this.#ai, refs, lookup.signal);\n this.#lookup = null;\n if (lookup.signal.aborted || this.#disposed) return;\n const renamed = this.#memory.name(found.values());\n for (const entry of found.values()) this.#entries.set(entry.ref.id, entry);\n const pinned = current4 ? found.get(current4.id) : void 0;\n if (pinned && this.#current?.id === pinned.ref.id) this.#found = pinned;\n if (!this.#active) return;\n if (this.#state.favorites && (renamed || pinned) || this.#categories?.active && shelved.some((ref) => found.has(ref.id))) this.#renderList(true);\n else if (pinned) this.#repin();\n }\n #sentinelNear() {\n if (!this.#sentinel.isConnected) return false;\n return this.#sentinel.getBoundingClientRect().top < this.#body.getBoundingClientRect().bottom + 600;\n }\n /** Names the kept voices the catalogue answered and remembers its facets (`SeenFacets`). */\n #learn(entries) {\n this.#memory.name(entries);\n this.#seen.learn(entries);\n for (const entry of entries) this.#entries.set(entry.ref.id, entry);\n }\n /* ---------------------------------------------------------------- filters */\n /** The models a filter must be answered by: the chosen one, or in \xAB all models \xBB at least one of them. */\n #answering() {\n return this.#state.allModels ? this.#models : this.#models.filter((model) => model.model === this.#state.model);\n }\n #answers(control) {\n return answersFilter(this.#answering(), control);\n }\n /** The person\'s filters the model cannot answer, cleared (the search text with them) so none is sent unheeded. */\n #dropUnanswered() {\n dropUnanswered(this.#state, this.#answering(), (filter) => this.#show.includes(filter));\n if (this.#input && !this.#answers("search")) {\n clearTimeout(this.#searchTimer);\n this.#input.value = "";\n }\n }\n #offered(group) {\n if (!this.#show.includes(group)) return false;\n if (group === "accent" || group === "useCase" || group === "language" || group === "cost") return this.#choicesOf(group).length > 1;\n return true;\n }\n #choicesOf(group) {\n return filterChoices(group, {\n text: this.#text,\n locale: this.#locale,\n answering: this.#answering(),\n languages: this.#seen.languages,\n accents: this.#seen.accents.get(this.#state.language ?? "") ?? /* @__PURE__ */ new Set(),\n useCases: this.#seen.useCases,\n state: this.#state,\n rankLanguage: this.#rankLanguage,\n ceiling: this.#options.filters?.maxPriceMultiplier\n });\n }\n #valueOf(group) {\n return this.#state[group];\n }\n /** The person\'s model choice: a model id, or `undefined` for all of them. The favourites view stays, showing the\n * voices that go with the new model. */\n #chooseModel(value) {\n const state3 = this.#state;\n if (value === void 0 ? state3.allModels : !state3.allModels && state3.model === value) return;\n state3.allModels = value === void 0;\n if (value !== void 0) state3.model = value;\n this.#dropUnanswered();\n this.#failed.delete(value ?? "");\n this.#openGroup = null;\n this.#renderBar();\n void this.#reload();\n }\n #choose(group, value) {\n applyChoice(this.#state, group, value);\n this.#openGroup = null;\n this.#renderBar();\n void this.#reload();\n }\n #renderBar() {\n const open3 = this.#openGroup;\n if (open3 && !this.#answers(open3)) this.#openGroup = null;\n const chips = filterChips({\n doc: this.#doc,\n text: this.#text,\n locale: this.#locale,\n show: this.#show,\n openGroup: this.#openGroup,\n choicesId: this.#choices.id,\n state: this.#state,\n offered: (group) => this.#offered(group),\n answers: (control) => this.#answers(control),\n valueOf: (group) => this.#valueOf(group),\n choicesOf: (group) => this.#choicesOf(group),\n toggleGroup: (group) => {\n this.#openGroup = this.#openGroup === group ? null : group;\n this.#categories?.fold();\n this.#renderBar();\n },\n toggleVerified: () => {\n this.#state.verifiedOnly = !this.#state.verifiedOnly;\n this.#state.favorites = false;\n this.#categories?.clear();\n this.#renderBar();\n void this.#reload();\n },\n toggleFavorites: () => {\n this.#state.favorites = !this.#state.favorites;\n this.#openGroup = null;\n this.#categories?.clear();\n this.#categories?.fold();\n this.#renderBar();\n void this.#reload();\n }\n });\n if (this.#categories) {\n chips.splice(this.#show.includes("favorites") ? 1 : 0, 0, this.#categories.chip(() => {\n this.#openGroup = null;\n this.#renderBar();\n }));\n }\n if (this.#input) {\n const enabled2 = this.#answers("search");\n this.#input.disabled = !enabled2;\n this.#input.title = enabled2 ? "" : this.#text.unsupportedFilter;\n }\n const scroll = this.#bar.scrollLeft;\n this.#bar.replaceChildren(...chips);\n this.#bar.scrollLeft = scroll;\n this.#bar.hidden = !chips.length;\n this.#renderChoices();\n this.#renderModels();\n }\n /* ----------------------------------------------------------------- models */\n /** The listed model the picker reads for (none in \xAB all models \xBB). */\n #spec() {\n return this.#state.allModels ? void 0 : this.#listed.find((model) => model.model === this.#state.model);\n }\n /** The chosen model cannot serve now: nothing is listed for it until the person chooses another one. */\n #blocked = () => isModelUnavailable(this.#spec());\n /** A voice that goes with no model it could be sent with now (kept without one, or with one not offered or down). */\n #rematch = (entry) => this.#sentWith(entry) === null;\n /** The model shown when the voice goes with it, else its own when the picker may choose it now. */\n #sentWith(entry) {\n const own = entry.ref.model, models2 = this.#models;\n return this.#target(entry) ?? (own && (!models2.length || models2.some((model) => model.model === own && !isModelUnavailable(model))) ? own : null);\n }\n #target(entry) {\n return voiceTarget(entry, { ...this.#state, offered: this.#models, listed: this.#listed });\n }\n /** The pair a category keeps for a voice: the model it is shown for, else its own. */\n #keptRef(entry) {\n return { id: entry.ref.id, model: this.#sentWith(entry) ?? entry.ref.model };\n }\n #renderModels() {\n const shown = this.#show.includes("model") && this.#models.length > 0;\n this.#modelBar.hidden = !shown;\n const scroll = this.#modelBar.scrollLeft;\n this.#modelBar.replaceChildren(...shown ? modelButtons({\n doc: this.#doc,\n text: this.#text,\n locale: this.#locale,\n models: this.#models,\n failed: this.#failed,\n selected: this.#state.allModels ? void 0 : this.#state.model,\n choose: (value) => this.#chooseModel(value)\n }) : []);\n this.#modelBar.scrollLeft = scroll;\n const note = this.#state.allModels ? this.#failed.size ? this.#text.modelFailed : null : modelNote(this.#spec(), this.#failed.has(this.#state.model), this.#text);\n this.#modelNote.hidden = !note;\n this.#modelNote.textContent = note ?? "";\n }\n #renderChoices() {\n if (this.#categories?.open) {\n this.#categories.panel(this.#choices);\n return;\n }\n renderChoices(this.#doc, this.#choices, this.#text, this.#openGroup, {\n choicesOf: (group) => this.#choicesOf(group),\n valueOf: (group) => this.#valueOf(group),\n choose: (group, value) => this.#choose(group, value)\n });\n }\n #searchChanged() {\n clearTimeout(this.#searchTimer);\n this.#searchTimer = setTimeout(() => {\n const query = this.#input?.value.replace(/\\s+/gu, " ").trim().slice(0, 100) ?? "";\n if (query === this.#state.query) return;\n this.#state.query = query;\n if (this.#local()) this.#renderList(true);\n else void this.#reload();\n }, searchDelayMs);\n }\n /* ------------------------------------------------------------------- list */\n #showStatus(message2, action) {\n showStatus(this.#doc, this.#status, message2, action);\n }\n #pinned() {\n return pinnedEntry(this.#options.pinCurrent ? this.#current : null, this.#memory, this.#listing, this.#found);\n }\n #pinRow(entry) {\n const item = this.#row(entry);\n item.classList.add("nocha-voice-picker__item--pinned");\n return item;\n }\n /** The pinned row again, in place, once a read named its voice. */\n #repin() {\n const entry = this.#pinned();\n const row2 = entry && this.#rows.get(entry.ref.id);\n if (entry && row2?.item.classList.contains("nocha-voice-picker__item--pinned")) row2.item.replaceWith(this.#pinRow(entry));\n }\n #renderList(reset) {\n if (reset) {\n this.#observer?.unobserve(this.#sentinel);\n this.#rows.clear();\n this.#list.replaceChildren();\n this.#body.scrollTop = 0;\n }\n if (this.#categories?.active) {\n this.#renderCategory();\n return;\n }\n if (this.#blocked()) {\n this.#showStatus(this.#text.modelUnavailableHint);\n return;\n }\n if (this.#state.favorites) {\n this.#renderFavorites();\n return;\n }\n const pinned = reset ? this.#pinned() : null;\n if (pinned) this.#list.append(this.#pinRow(pinned));\n const entries = this.#listing?.entries ?? [];\n if (!this.#listing) return;\n this.#sentinel.remove();\n const fresh2 = entries.filter((entry) => !this.#rows.has(entry.ref.id));\n this.#list.append(...fresh2.map((entry) => this.#row(entry)));\n if (this.#listing.cursor && !this.#exhausted) {\n this.#list.append(this.#sentinel);\n this.#observer?.observe(this.#sentinel);\n }\n if (entries.length) this.#showStatus(null);\n else this.#showStatus(this.#text.empty, this.#filtered() ? { label: this.#text.clearFilters, run: () => this.#clearFilters() } : void 0);\n if (this.#listing.cursor && !this.#observer) void this.#more();\n }\n #renderFavorites() {\n renderFavorites({\n doc: this.#doc,\n text: this.#text,\n memory: this.#memory,\n list: this.#list,\n query: this.#state.query,\n pinned: this.#pinned(),\n ceiling: this.#ceiling(),\n // Only the voices that go with the chosen model; over every model, each with its own (or to be matched again).\n fits: (entry) => this.#target(entry) !== null || this.#state.allModels && this.#rematch(entry),\n row: (entry) => this.#row(entry),\n pinRow: (entry) => this.#pinRow(entry),\n showStatus: (message2) => this.#showStatus(message2)\n });\n }\n /** A kept voice as best known: as the catalogue listed it, as kept, else by its id (named by `#name`). */\n #entryOf(ref) {\n const listed = this.#entries.get(ref.id) ?? this.#memory.find(ref.id);\n return listed && !isUnnamed(listed) ? { ...listed, ref: { ...ref } } : placeholderEntry(ref);\n }\n /** The active category\'s voices, whatever the model: each is chosen with the model it was kept for (or matched again). */\n #renderCategory() {\n const category = this.#categories?.active;\n if (!category) return;\n const query = this.#state.query.toLowerCase(), ceiling2 = this.#ceiling();\n const entries = category.voices.map((ref) => this.#entryOf(ref)).filter((entry) => (!query || entry.name.toLowerCase().includes(query)) && (ceiling2 === void 0 || (entry.premium ?? 1) <= ceiling2));\n this.#list.replaceChildren(...entries.map((entry) => this.#row(entry)));\n this.#showStatus(entries.length ? null : this.#text.emptyCategory);\n if (category.voices.some((ref) => !this.#entries.has(ref.id))) void this.#name();\n }\n #filtered() {\n return isFiltered(this.#state, this.#show);\n }\n #clearFilters() {\n clearFilterState(this.#state, this.#show);\n if (this.#input) this.#input.value = "";\n this.#renderBar();\n void this.#reload();\n }\n #row(entry) {\n const row2 = voiceRow(this.#rowContext, entry);\n this.#rows.set(entry.ref.id, row2);\n return row2.item;\n }\n #updateRow(id) {\n const row2 = this.#rows.get(id);\n if (row2) updateVoiceRow(this.#rowContext, row2);\n }\n /** Every row\'s star (and category mark) again, once they changed (a read of the account\'s, a write, another picker\'s\n * write). */\n #refreshRows() {\n for (const row2 of Array.from(this.#rows.values())) updateVoiceRow(this.#rowContext, row2);\n }\n /** The star: shown at once; a refused write is taken back by the memory and said here. */\n #toggleFavorite(entry) {\n this.#memory.toggleFavorite(entry).then(() => this.#updateRow(entry.ref.id), (error) => {\n this.#updateRow(entry.ref.id);\n this.#say(isFavoritesLimit(error) ? fill(this.#text.favoritesFull, { limit: this.#memory.limit() }) : this.#text.favoritesFailed);\n });\n }\n #say(message2) {\n clearTimeout(this.#noticeTimer);\n this.#notice.textContent = message2;\n this.#notice.hidden = false;\n this.#noticeTimer = setTimeout(() => {\n this.#notice.hidden = true;\n }, noticeMs);\n }\n #sampleChanged(id, state3) {\n if (state3 === "idle" || state3 === "failed") this.#sampleStates.delete(id);\n else this.#sampleStates.set(id, state3);\n this.#updateRow(id);\n }\n #picked(entry) {\n const pick4 = this.#init.pick;\n const target = this.#sentWith(entry);\n if (!pick4 || target === null) return;\n if (!this.#state.allModels && target !== this.#state.model) {\n this.#state.model = target;\n this.#dropUnanswered();\n this.#renderBar();\n }\n const chosen = pickOf(entry, target);\n this.#memory.used(chosen.entry);\n this.#selected = chosen.ref.id;\n this.#current = { ...chosen.ref };\n this.#found = chosen.entry;\n pick4(chosen);\n }\n};\n\n// src/voice-picker-css.ts\nvar voicePickerCss = `\n:host { display: contents; }\n/* The hidden attribute always wins over a rule\'s display. */\n:host([hidden]), [hidden] { display: none !important; }\n.nocha-voice-picker {\n position: fixed; inset: 0; margin: auto; padding: 0;\n width: min(640px, calc(100vw - 48px)); height: min(800px, calc(100vh - 64px)); height: min(800px, calc(100dvh - 64px));\n max-width: none; max-height: none; overflow: hidden;\n background: var(--nocha-ui-x-surface); color: var(--nocha-ui-x-text);\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius);\n font-family: var(--nocha-ui-x-font); box-shadow: 0 24px 80px rgba(0, 0, 0, 0.35);\n}\n.nocha-voice-picker[open] { display: flex; flex-direction: column; animation: nocha-voice-picker-in 160ms ease-out; }\n.nocha-voice-picker::backdrop { background: var(--nocha-ui-backdrop, rgba(0, 0, 0, 0.62)); }\n@keyframes nocha-voice-picker-in { from { opacity: 0; transform: translateY(12px); } }\n@media (max-width: 639.98px), (pointer: coarse) {\n .nocha-voice-picker {\n inset: 0; width: 100%; height: 100%; margin: 0; border: 0; box-shadow: none;\n border-radius: 0; padding-bottom: env(safe-area-inset-bottom);\n }\n .nocha-voice-picker[open] { animation: nocha-voice-picker-rise 220ms cubic-bezier(0.2, 0.8, 0.2, 1); }\n}\n@keyframes nocha-voice-picker-rise { from { transform: translateY(100%); } }\n/* In the page (mountVoiceBrowser): the container\'s whole box, no dialog. */\n.nocha-voice-picker.nocha-voice-picker--page {\n position: relative; inset: auto; display: flex; flex-direction: column; width: 100%; height: 100%; min-height: 0;\n margin: 0; border: 0; border-radius: 0; box-shadow: none; animation: none; padding-bottom: env(safe-area-inset-bottom);\n}\n\n.nocha-voice-picker__head {\n display: flex; align-items: center; gap: 8px; flex: none;\n padding: 6px 6px 0 20px; padding-top: max(6px, env(safe-area-inset-top));\n}\n.nocha-voice-picker__title {\n flex: 1; min-width: 0; margin: 0; font-size: 19px; font-weight: 650; letter-spacing: -0.01em;\n white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.nocha-voice-picker__close, .nocha-voice-picker__listen, .nocha-voice-picker__favorite, .nocha-voice-field__listen {\n display: inline-flex; align-items: center; justify-content: center; flex: none;\n width: 44px; height: 44px; color: var(--nocha-ui-x-muted); border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-voice-picker__close { width: 48px; height: 48px; color: var(--nocha-ui-x-text); }\n.nocha-voice-picker__close .nocha-ui-icon { width: 24px; height: 24px; }\n\n.nocha-voice-picker__models {\n display: flex; gap: 8px; flex: none; overflow-x: auto; padding: 8px 16px 0; scrollbar-width: none;\n -webkit-overflow-scrolling: touch; overscroll-behavior-x: contain;\n}\n.nocha-voice-picker__models::-webkit-scrollbar { display: none; }\n@media (min-width: 640px) and (pointer: fine) { .nocha-voice-picker__models { flex-wrap: wrap; overflow-x: visible; } }\n.nocha-voice-picker__model {\n display: flex; flex-direction: column; align-items: flex-start; justify-content: center; gap: 2px; flex: none;\n min-height: 48px; max-width: 240px; padding: 6px 12px; text-align: left; color: var(--nocha-ui-x-text);\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius); background: transparent;\n}\n.nocha-voice-picker__model[aria-pressed="true"] { border-color: var(--nocha-ui-x-accent); box-shadow: inset 0 0 0 1px var(--nocha-ui-x-accent); }\n.nocha-voice-picker__model-name {\n display: flex; align-items: center; gap: 6px; max-width: 100%; font-size: 14px; font-weight: 600;\n white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.nocha-voice-picker__model-warning {\n display: inline-flex; align-items: center; justify-content: center; flex: none; width: 16px; height: 16px;\n border: 1px solid currentColor; border-radius: 50%; color: var(--nocha-ui-x-accent); font-size: 11px; font-weight: 700;\n}\n.nocha-voice-picker__model-meta {\n display: flex; align-items: center; gap: 4px 8px; flex-wrap: wrap; font-size: 12px; color: var(--nocha-ui-x-muted);\n}\n.nocha-voice-picker__model-price { font-family: var(--nocha-ui-x-mono); }\n.nocha-voice-picker__model-access { text-transform: lowercase; opacity: 0.8; }\n.nocha-voice-picker__model-state { font-style: italic; }\n/* An unavailable model: in sight, greyed and inert, saying why; a degraded one warns and stays choosable. */\n.nocha-voice-picker__model--unavailable { color: var(--nocha-ui-x-muted); border-style: dashed; opacity: 0.55; cursor: not-allowed; }\n.nocha-voice-picker__model--degraded .nocha-voice-picker__model-state,\n.nocha-voice-picker__model--failed .nocha-voice-picker__model-state { color: var(--nocha-ui-x-accent); }\n.nocha-voice-picker__model-note {\n flex: none; margin: 8px 16px 0; padding: 8px 12px; font-size: 13px; color: var(--nocha-ui-x-text);\n border: 1px solid var(--nocha-ui-x-accent); border-radius: var(--nocha-ui-x-radius); background: var(--nocha-ui-x-raised);\n}\n@media (pointer: coarse) { .nocha-voice-picker__model { min-height: 52px; } }\n\n.nocha-voice-picker__search { position: relative; flex: none; padding: 8px 16px 4px; }\n.nocha-voice-picker__search .nocha-ui-icon {\n position: absolute; left: 28px; top: 50%; margin-top: 2px; transform: translateY(-50%); color: var(--nocha-ui-x-muted); pointer-events: none;\n}\n.nocha-voice-picker__input {\n display: block; width: 100%; height: 44px; margin: 0; padding: 0 12px 0 40px;\n font-size: 16px; color: var(--nocha-ui-x-text); background: var(--nocha-ui-x-raised);\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius); outline: none;\n -webkit-appearance: none; appearance: none;\n}\n.nocha-voice-picker__input::placeholder { color: var(--nocha-ui-x-muted); opacity: 1; }\n.nocha-voice-picker__input:focus-visible, .nocha-voice-picker__input:focus { border-color: var(--nocha-ui-x-accent); }\n\n.nocha-voice-picker__bar {\n display: flex; gap: 8px; flex: none; overflow-x: auto; padding: 8px 16px; scrollbar-width: none;\n -webkit-overflow-scrolling: touch; overscroll-behavior-x: contain;\n}\n.nocha-voice-picker__bar::-webkit-scrollbar { display: none; }\n/* A mouse does not swipe: on a desktop panel the chips wrap instead of scrolling out of sight. */\n@media (min-width: 640px) and (pointer: fine) { .nocha-voice-picker__bar { flex-wrap: wrap; overflow-x: visible; } }\n.nocha-voice-picker__chip {\n display: inline-flex; align-items: center; gap: 6px; flex: none; min-height: 36px; padding: 0 12px;\n font-size: 14px; line-height: 1.1; white-space: nowrap; color: var(--nocha-ui-x-text);\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius); background: transparent;\n}\n.nocha-voice-picker__chip .nocha-ui-icon { width: 16px; height: 16px; }\n.nocha-voice-picker__chip[aria-expanded="true"] { border-color: var(--nocha-ui-x-text); }\n.nocha-voice-picker__chip[aria-expanded="true"] .nocha-ui-icon { transform: rotate(180deg); }\n.nocha-voice-picker__chip--active, .nocha-voice-picker__chip[aria-pressed="true"] {\n background: var(--nocha-ui-x-accent); border-color: var(--nocha-ui-x-accent); color: var(--nocha-ui-x-on-accent);\n}\n.nocha-voice-picker__chip-label { color: var(--nocha-ui-x-muted); }\n/* A filter the chosen model does not answer: in sight, greyed and inert; the search field likewise. */\n.nocha-voice-picker__chip--disabled { color: var(--nocha-ui-x-muted); border-style: dashed; opacity: 0.55; cursor: not-allowed; }\n.nocha-voice-picker__input:disabled { opacity: 0.55; cursor: not-allowed; }\n.nocha-voice-picker__chip--active .nocha-voice-picker__chip-label { color: inherit; opacity: 0.72; }\n@media (pointer: coarse) { .nocha-voice-picker__chip { min-height: 44px; padding: 0 14px; } }\n\n.nocha-voice-picker__options {\n display: flex; flex-wrap: wrap; gap: 8px; flex: none; max-height: 34%; overflow-y: auto;\n padding: 4px 16px 12px; border-bottom: 1px solid var(--nocha-ui-x-line);\n}\n\n.nocha-voice-picker__body {\n position: relative; flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain;\n -webkit-overflow-scrolling: touch; border-top: 1px solid var(--nocha-ui-x-line);\n}\n.nocha-voice-picker__options:not([hidden]) + .nocha-voice-picker__body { border-top: 0; }\n.nocha-voice-picker__list { list-style: none; margin: 0; padding: 0; }\n.nocha-voice-picker__section {\n padding: 16px 20px 6px; font-size: 13px; font-weight: 600; color: var(--nocha-ui-x-muted);\n}\n.nocha-voice-picker__item {\n display: flex; align-items: center; gap: 2px; min-height: 68px; padding: 0 6px;\n border-bottom: 1px solid var(--nocha-ui-x-line);\n}\n@media (hover: hover) { .nocha-voice-picker__item:hover { background: var(--nocha-ui-x-raised); } }\n.nocha-voice-picker__item--selected { box-shadow: inset 3px 0 0 var(--nocha-ui-x-accent); background: var(--nocha-ui-x-raised); }\n.nocha-voice-picker__choose {\n display: flex; flex-direction: column; justify-content: center; gap: 3px; flex: 1; min-width: 0;\n align-self: stretch; padding: 10px 6px; border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-voice-picker__line { display: flex; align-items: baseline; gap: 8px; min-width: 0; }\n.nocha-voice-picker__name {\n flex: none; max-width: 100%; font-size: 17px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.nocha-voice-picker__full {\n flex: 1; min-width: 0; font-size: 13px; color: var(--nocha-ui-x-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.nocha-voice-picker__meta {\n display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px; font-size: 13px; color: var(--nocha-ui-x-muted);\n}\n.nocha-voice-picker__tag { white-space: nowrap; }\n.nocha-voice-picker__tag--language { color: var(--nocha-ui-x-text); }\n.nocha-voice-picker__tag--premium, .nocha-voice-field__premium {\n padding: 0 5px; border: 1px solid currentColor; border-radius: var(--nocha-ui-x-radius);\n color: var(--nocha-ui-x-accent); font-family: var(--nocha-ui-x-mono); font-size: 12px; font-weight: 600; line-height: 16px;\n}\n.nocha-voice-picker__tag--popularity { font-family: var(--nocha-ui-x-mono); font-size: 12px; }\n.nocha-voice-picker__tag--missing { font-style: italic; }\n.nocha-voice-picker__tag--model { color: var(--nocha-ui-x-text); }\n.nocha-voice-picker__tag--rematch { font-style: italic; color: var(--nocha-ui-x-accent); }\n.nocha-voice-picker__choose:disabled { cursor: not-allowed; opacity: 0.7; }\n/* The current voice shown first (pinCurrent), a thicker rule below it; a voice the experience found unavailable, struck out. */\n.nocha-voice-picker__item--pinned { border-bottom-width: 2px; }\n.nocha-voice-picker__item--unavailable .nocha-voice-picker__name, .nocha-voice-picker__item--unavailable .nocha-voice-picker__full,\n.nocha-voice-field__name--unavailable { text-decoration: line-through; color: var(--nocha-ui-x-muted); }\n.nocha-voice-picker__verified { display: inline-flex; color: var(--nocha-ui-x-text); }\n.nocha-voice-picker__verified .nocha-ui-icon { width: 16px; height: 16px; }\n.nocha-voice-picker__check { color: var(--nocha-ui-x-accent); }\n.nocha-voice-picker__listen, .nocha-voice-field__listen { color: var(--nocha-ui-x-text); }\n.nocha-voice-picker__listen-ring, .nocha-voice-field__ring {\n display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-voice-picker__listen-ring .nocha-ui-icon, .nocha-voice-field__ring .nocha-ui-icon { width: 18px; height: 18px; }\n.nocha-voice-picker__listen:disabled, .nocha-voice-field__listen:disabled { color: var(--nocha-ui-x-muted); opacity: 0.55; }\n.nocha-voice-picker__listen:disabled .nocha-voice-picker__listen-ring, .nocha-voice-field__listen:disabled .nocha-voice-field__ring { border-style: dashed; }\n.nocha-voice-picker__listen--paid .nocha-voice-picker__listen-ring, .nocha-voice-field__listen--paid .nocha-voice-field__ring {\n border-style: dashed; border-color: var(--nocha-ui-x-accent);\n}\n.nocha-voice-field__listen--playing .nocha-voice-field__ring {\n background: var(--nocha-ui-x-accent); border-color: var(--nocha-ui-x-accent); color: var(--nocha-ui-x-on-accent);\n}\n.nocha-voice-picker__item--playing .nocha-voice-picker__listen-ring,\n.nocha-voice-picker__item--loading .nocha-voice-picker__listen-ring {\n background: var(--nocha-ui-x-accent); border-color: var(--nocha-ui-x-accent); color: var(--nocha-ui-x-on-accent);\n}\n.nocha-voice-picker__item--loading .nocha-voice-picker__listen-ring { animation: nocha-voice-picker-pulse 900ms ease-in-out infinite alternate; }\n@keyframes nocha-voice-picker-pulse { to { opacity: 0.45; } }\n.nocha-voice-picker__favorite .nocha-ui-icon { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linejoin: round; }\n.nocha-voice-picker__favorite[aria-pressed="true"] { color: var(--nocha-ui-x-accent); }\n.nocha-voice-picker__favorite[aria-pressed="true"] .nocha-ui-icon { fill: currentColor; }\n\n/* The person\'s categories: a voice\'s mark, the facet\'s panel, a voice\'s menu over the frame. */\n.nocha-voice-picker__categorize { display: inline-flex; align-items: center; justify-content: center; flex: none; width: 44px; height: 44px; color: var(--nocha-ui-x-muted); border-radius: var(--nocha-ui-x-radius); }\n.nocha-voice-picker__categorize[aria-pressed="true"] { color: var(--nocha-ui-x-accent); }\n.nocha-voice-picker__count { font-family: var(--nocha-ui-x-mono); font-size: 12px; opacity: 0.72; }\n.nocha-voice-picker__prompt { display: inline-flex; align-items: center; min-height: 36px; font-size: 14px; color: var(--nocha-ui-x-muted); }\n.nocha-voice-picker__name-form { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; width: 100%; margin: 0; }\n.nocha-voice-picker__input--name { flex: 1; min-width: 160px; width: auto; padding: 0 12px; }\n.nocha-voice-picker__menu {\n position: absolute; left: 0; right: 0; bottom: 0; z-index: 2; display: flex; flex-direction: column; gap: 12px;\n max-height: 70%; overflow-y: auto; padding: 8px 16px 16px; padding-bottom: max(16px, env(safe-area-inset-bottom));\n background: var(--nocha-ui-x-surface); border-top: 1px solid var(--nocha-ui-x-line); box-shadow: 0 -16px 48px rgba(0, 0, 0, 0.3);\n}\n.nocha-voice-picker__menu-head { display: flex; align-items: center; gap: 8px; }\n.nocha-voice-picker__menu-title { flex: 1; min-width: 0; font-size: 16px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.nocha-voice-picker__menu-list { display: flex; flex-wrap: wrap; gap: 8px; }\n.nocha-voice-picker__menu-list:empty { display: none; }\n\n.nocha-voice-picker__status {\n display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 40px 20px; text-align: center;\n color: var(--nocha-ui-x-muted); font-size: 15px;\n}\n.nocha-voice-picker__sentinel { height: 1px; }\n.nocha-voice-picker__notice {\n flex: none; margin: 0 16px 8px; padding: 10px 12px; font-size: 14px;\n background: var(--nocha-ui-x-raised); border: 1px solid var(--nocha-ui-x-accent); border-radius: var(--nocha-ui-x-radius);\n}\n\n.nocha-voice-field {\n display: flex; align-items: center; gap: 2px; width: 100%; min-height: 60px; padding: 0 4px;\n background: var(--nocha-ui-x-surface); color: var(--nocha-ui-x-text);\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius); font-family: var(--nocha-ui-x-font);\n}\n.nocha-voice-field__open {\n display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; align-self: stretch; padding: 8px 8px 8px 6px;\n border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-voice-field__text { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; }\n.nocha-voice-field__head { display: flex; align-items: center; gap: 8px; min-width: 0; }\n.nocha-voice-field__premium { flex: none; }\n.nocha-voice-field__name { min-width: 0; font-size: 16px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n.nocha-voice-field__name--empty { font-weight: 500; color: var(--nocha-ui-x-muted); }\n.nocha-voice-field__meta { font-size: 13px; color: var(--nocha-ui-x-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n.nocha-voice-field__meta:empty { display: none; }\n.nocha-voice-field__open .nocha-ui-icon { color: var(--nocha-ui-x-muted); }\n@media (hover: hover) { .nocha-voice-field__open:hover { background: var(--nocha-ui-x-raised); } }\n.nocha-voice-field__alert {\n display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-top: 6px; padding: 8px 10px;\n font-family: var(--nocha-ui-x-font); font-size: 13px; color: var(--nocha-ui-x-text); background: var(--nocha-ui-x-raised);\n border: 1px solid var(--nocha-ui-x-accent); border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-voice-field__alert-text { flex: 1; min-width: 0; }\n.nocha-voice-field__action {\n flex: none; min-height: 36px; padding: 0 12px; font-size: 14px; color: var(--nocha-ui-x-on-accent);\n background: var(--nocha-ui-x-accent); border: 1px solid var(--nocha-ui-x-accent); border-radius: var(--nocha-ui-x-radius);\n}\n@media (pointer: coarse) { .nocha-voice-field__action { min-height: 44px; } }\n`;\n\n// src/voice-system-picker.ts\nvar VOICE_EXPERIENCE = "voix";\nvar VOICE_OPERATION = "voix.choose";\nvar unreachableCodes = /* @__PURE__ */ new Set([\n "client_update_required",\n "bridge_unavailable",\n "capability_denied",\n "invalid_input",\n "unknown_error",\n "experience_call_unavailable",\n "experience_call_denied",\n "invocation_timed_out"\n]);\nvar unreachable = false;\nfunction systemReachable() {\n return !unreachable;\n}\nfunction mayAskSystem(options) {\n return !unreachable && !options.container;\n}\nfunction demandOf(options) {\n const demand = { locale: uiLocale(options.locale) };\n if (options.language) demand.language = options.language;\n if (options.model) demand.model = options.model;\n if (options.models?.length) demand.models = [...options.models];\n if (options.value !== void 0) {\n const value = options.value;\n demand.value = value ? { id: value.id, ...value.model ? { model: value.model } : {}, ...value.name ? { name: value.name } : {} } : null;\n }\n if (options.filters) {\n const filters = {};\n for (const [key2, item] of Object.entries(options.filters)) {\n if (typeof item === "string" || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) filters[key2] = item;\n else if (Array.isArray(item)) filters[key2] = item.filter((part) => typeof part === "string");\n }\n demand.filters = filters;\n }\n if (options.show) demand.show = [...options.show];\n if (options.title) demand.title = options.title;\n if (options.storageKey) demand.storageKey = options.storageKey;\n return demand;\n}\nfunction pickOf2(value) {\n if (!isRecord(value) || !isRecord(value.ref) || !isRecord(value.entry)) return null;\n const { id, model } = value.ref;\n if (typeof id !== "string" || !id || typeof model !== "string") return null;\n const entry = value.entry;\n if (typeof entry.name !== "string" || !entry.name) return null;\n const ref = { id, model };\n return {\n ref: { ...ref },\n entry: {\n ...entry,\n ref: { ...ref },\n name: entry.name,\n spokenName: typeof entry.spokenName === "string" && entry.spokenName ? entry.spokenName : entry.name,\n collection: entry.collection === "standard" ? "standard" : "library",\n languages: Array.isArray(entry.languages) ? entry.languages.filter((code) => typeof code === "string") : [],\n traits: isRecord(entry.traits) ? entry.traits : {},\n preview: entry.preview === true,\n premium: typeof entry.premium === "number" && Number.isFinite(entry.premium) ? entry.premium : null\n }\n };\n}\nasync function askSystemVoicePicker(options, signal) {\n if (unreachable) return void 0;\n let answer;\n try {\n answer = await pickExperience(VOICE_EXPERIENCE, VOICE_OPERATION, demandOf(options), { signal });\n } catch (error) {\n if (signal.aborted) return null;\n const code = isNochaError(error) ? error.wireCode ?? error.code : void 0;\n if (code === "aborted" || code === "request_cancelled") return null;\n if (code !== void 0 && unreachableCodes.has(code)) unreachable = true;\n return void 0;\n }\n if (answer.status === "cancelled") return null;\n const pick4 = pickOf2(answer.value);\n if (!pick4) return void 0;\n const memory = createVoiceMemory(options.storageKey);\n memory.used(pick4.entry);\n memory.dispose();\n return pick4;\n}\n\n// src/voice-picker.ts\nvar VoicePickerDialog = class {\n #ui;\n #dialog;\n #core;\n #settle = null;\n #opening = null;\n #chosen = null;\n #disposed = false;\n /** `known`: the current voice\'s entry as its field already shows it; `focusModels`: open on the model selector. */\n constructor(ai, options, known = null, focusModels = false) {\n this.#ui = mountUiHost(voicePickerCss, options.container, "nocha-voice-picker");\n const doc = this.#ui.host.ownerDocument;\n this.#dialog = element(doc, "dialog", "nocha-voice-picker");\n this.#core = new VoiceBrowserCore(ai, options, {\n frame: this.#dialog,\n known,\n focusModels,\n close: () => this.close(),\n pick: (pick4) => {\n this.#chosen = pick4;\n this.close();\n }\n });\n this.#dialog.addEventListener("close", () => this.#closed());\n this.#dialog.addEventListener("cancel", () => {\n this.#chosen = null;\n });\n closeOnBackdrop(this.#dialog, () => this.close());\n this.#ui.root.append(this.#dialog);\n }\n open() {\n if (this.#disposed) return Promise.resolve(null);\n if (this.#opening) return this.#opening;\n this.#chosen = null;\n this.#opening = new Promise((resolve2) => {\n this.#settle = resolve2;\n });\n if (!this.#dialog.open) this.#dialog.showModal();\n this.#core.start();\n return this.#opening;\n }\n isOpen() {\n return this.#dialog.open;\n }\n close() {\n if (this.#dialog.open) this.#dialog.close();\n else this.#closed();\n }\n dispose() {\n if (this.#disposed) return;\n this.close();\n this.#disposed = true;\n this.#core.dispose();\n this.#ui.remove();\n }\n #closed() {\n this.#core.stop();\n const settle = this.#settle;\n this.#settle = null;\n this.#opening = null;\n settle?.(this.#chosen);\n }\n};\nfunction createVoicePicker(ai, options = {}) {\n return pickerOf(ai, options, null);\n}\nfunction pickerOf(ai, options, known, focusModels = false, system = mayAskSystem(options)) {\n let dialog = null;\n let disposed = false;\n let asking = null;\n const dispose = () => {\n disposed = true;\n options.signal?.removeEventListener("abort", dispose);\n asking?.stop.abort();\n dialog?.dispose();\n dialog = null;\n };\n if (options.signal?.aborted) disposed = true;\n else options.signal?.addEventListener("abort", dispose, { once: true });\n const openDialog = () => {\n if (disposed) return Promise.resolve(null);\n dialog ??= new VoicePickerDialog(ai, options, known, focusModels);\n return dialog.open();\n };\n return {\n open() {\n if (disposed) return Promise.resolve(null);\n if (asking) return asking.promise;\n if (!system || dialog?.isOpen() || !systemReachable()) return openDialog();\n const stop = new AbortController();\n const promise = askSystemVoicePicker(options, stop.signal).then((answer) => answer === void 0 ? openDialog() : answer).finally(() => {\n if (asking?.stop === stop) asking = null;\n });\n asking = { promise, stop };\n return promise;\n },\n close: () => {\n asking?.stop.abort();\n dialog?.close();\n },\n dispose\n };\n}\nfunction pickVoice(ai, options = {}) {\n return openVoicePicker(ai, options, null);\n}\nasync function openVoicePicker(ai, options, known, focusModels = false, system = mayAskSystem(options)) {\n const picker = pickerOf(ai, options, known, focusModels, system);\n try {\n return await picker.open();\n } finally {\n picker.dispose();\n }\n}\n\n// src/voice-recovery.ts\nvar unavailableCodes = /* @__PURE__ */ new Set(["provider_unavailable", "model_unavailable"]);\nvar requoteCodes = /* @__PURE__ */ new Set(["idempotency_conflict", "generation_quote_expired", "generation_quote_conflict"]);\nvar providerAccountCodes = /* @__PURE__ */ new Set(["provider_http_401", "provider_http_402", "provider_http_403"]);\nvar exhaustedCredits = /\\bcredits_exhausted\\b/iu;\nvar word = (value) => typeof value === "string" ? value : "";\nfunction voiceModelRecovery(error) {\n const code = errorCodeOf(error) ?? "";\n if (requoteCodes.has(code)) return "requote";\n const details = error !== null && typeof error === "object" ? error.details : void 0;\n const record6 = details !== null && typeof details === "object" ? details : {};\n const provider = word(record6.provider_code);\n if (unavailableCodes.has(code)) return "choose_model";\n if (code === "generation_failed" && (unavailableCodes.has(provider) || providerAccountCodes.has(provider))) return "choose_model";\n return [code, provider, word(record6.reason), word(record6.code)].some((value) => exhaustedCredits.test(value)) ? "choose_model" : null;\n}\n\n// src/voice-field.ts\nvar isPick = (value) => Boolean(value && typeof value === "object" && "ref" in value && "entry" in value);\nfunction createVoiceField(container, ai, initial = {}) {\n const ui = mountUiHost(voicePickerCss, container, "nocha-voice-field");\n const doc = ui.host.ownerDocument;\n let options = { ...initial };\n const locale = uiLocale(options.locale);\n const text6 = uiTexts(voicePickerTexts, locale, options.labels);\n const memory = createVoiceMemory(options.storageKey, options.favoritesSeed, ai);\n let value = options.value ?? null;\n let sample = "idle";\n let picking = null;\n let found = null;\n let lookup = null;\n let disposed = false;\n let listed = [];\n let mismatch = null;\n let recovery = null;\n const ring = element(doc, "span", "nocha-voice-field__ring");\n const listen = element(doc, "button", "nocha-voice-field__listen", { type: "button" }, ring);\n const nameNode = element(doc, "span", "nocha-voice-field__name");\n const premium = element(doc, "span", "nocha-voice-field__premium", { hidden: true });\n const meta2 = element(doc, "span", "nocha-voice-field__meta");\n const openButton = element(\n doc,\n "button",\n "nocha-voice-field__open",\n { type: "button", "aria-haspopup": "dialog" },\n element(doc, "span", "nocha-voice-field__text", {}, element(doc, "span", "nocha-voice-field__head", {}, nameNode, premium), meta2),\n icon(doc, "chevron")\n );\n const field3 = element(doc, "div", "nocha-voice-field", {}, listen, openButton);\n const alertText = element(doc, "span", "nocha-voice-field__alert-text");\n const action = chooseModelButton(doc, text6, () => void open3(!mismatch), "nocha-voice-field__action");\n const alert = element(doc, "div", "nocha-voice-field__alert", { role: "status", hidden: true }, alertText, action);\n ui.root.append(field3, alert);\n const samples2 = createSamplePlayer(ai, (_id, state3) => {\n sample = state3 === "failed" ? "idle" : state3;\n render();\n }, options.audition);\n const entry = () => {\n if (!value) return null;\n if (isPick(value)) return value.entry;\n const kept = memory.find(value.id);\n if (kept && !isUnnamed(kept)) return { ...kept, ref: bareRef(value) };\n if (found?.ref.id === value.id) return { ...found, ref: bareRef(value) };\n const placeholder = placeholderEntry(value);\n return isUnnamed(placeholder) && lookup ? null : placeholder;\n };\n function name() {\n lookup?.abort();\n lookup = null;\n const ref = value && !isPick(value) ? value : null;\n if (!ref || found?.ref.id === ref.id || lookedUpInVain(ai, ref.id) || !isUnnamed(entry() ?? placeholderEntry(ref))) return;\n const reading = lookup = new AbortController();\n void findVoices(ai, [ref], reading.signal).then((entries) => {\n if (reading.signal.aborted || disposed) return;\n lookup = null;\n const named = entries.get(ref.id);\n if (named) {\n found = named;\n memory.name([named]);\n }\n render();\n });\n }\n function render() {\n const shown = entry();\n const unavailable2 = Boolean(shown && samples2.unavailable(shown));\n const label = shown ? shown.spokenName || shown.name : value ? text6.loading : text6.fieldEmpty;\n nameNode.textContent = label;\n nameNode.className = `nocha-voice-field__name${value ? "" : " nocha-voice-field__name--empty"}${unavailable2 ? " nocha-voice-field__name--unavailable" : ""}`;\n const cost = shown ? premiumBadge(shown.premium, locale, text6) : null;\n premium.hidden = !cost;\n premium.textContent = cost?.label ?? "";\n premium.title = cost?.title ?? "";\n const model = value && listed.length > 1 ? modelLabel(listed, (isPick(value) ? value.ref : value).model) : "";\n const traits = shown ? [\n model,\n shown.languages[0]?.toUpperCase(),\n shown.traits.accent && listedLabel(shown.traits.accent),\n shown.traits.gender && text6.genders[shown.traits.gender],\n shown.traits.age && text6.ages[shown.traits.age]\n ].filter(Boolean).join(" \\xB7 ") : "";\n const paid = shown && !unavailable2 ? samples2.paid(shown) : false;\n const missing = !shown || unavailable2 || !paid && (samples2.silent(shown) || sample === "missing");\n const busy = sample === "playing" || sample === "loading";\n const note = unavailable2 ? text6.voiceUnavailable : paid ? text6.auditionPaid : text6.noPreview;\n meta2.textContent = shown && (missing || paid) ? [traits, note].filter(Boolean).join(" \\xB7 ") : traits;\n openButton.setAttribute("aria-label", value ? `${[label, cost?.title].filter(Boolean).join(" \\xB7 ")} \\u2014 ${text6.title}` : text6.fieldEmpty);\n listen.disabled = missing;\n listen.classList.toggle("nocha-voice-field__listen--playing", busy);\n listen.classList.toggle("nocha-voice-field__listen--paid", paid);\n listen.setAttribute("aria-label", unavailable2 ? text6.voiceUnavailable : missing ? text6.noPreview : busy ? text6.stop : paid ? `${text6.auditionPaid} \\xB7 ${label}` : fill(text6.listen, { name: label }));\n listen.title = listen.getAttribute("aria-label") ?? "";\n ring.replaceChildren(icon(doc, missing ? "dash" : busy ? "stop" : "play"));\n const current4 = value ? isPick(value) ? value.ref : value : null;\n const down = Boolean(current4 && isModelUnavailable(listed.find((item) => item.model === current4.model)));\n const say = mismatch ? fill(text6.voiceMismatch, { model: modelLabel(listed, mismatch) || mismatch }) : down ? text6.modelUnavailableHint : recovery === "choose_model" ? text6.modelRefused : "";\n alert.hidden = !say;\n alertText.textContent = say;\n const shows = !Array.isArray(options.show) || options.show.includes("model");\n const others = offeredModels(listed, options.models).filter((item) => !isModelUnavailable(item) && item.model !== current4?.model);\n action.textContent = mismatch ? text6.fieldEmpty : text6.chooseModel;\n action.hidden = !mismatch && !(shows && others.length > 0);\n }\n const fieldModel = (defaultModel) => chooseSpeechModel(offeredModels(listed, options.models), defaultModel, options.model);\n function refit() {\n const asked = value;\n void readModels(ai).then(({ models: models2, defaultModel }) => {\n if (disposed) return;\n listed = models2;\n if (value !== asked) return render();\n const model = options.model ? models2.length ? fieldModel(defaultModel) : options.model : "";\n const ref = value ? isPick(value) ? value.ref : value : null;\n mismatch = null;\n let moved = null;\n if (ref && model && ref.model !== model) {\n if (voiceFits(ref, model, models2)) {\n const next = { id: ref.id, model };\n value = isPick(value) ? { ref: next, entry: { ...value.entry, ref: next } } : { ...ref, model };\n moved = isPick(value) ? value : { ref: next, entry: { ...entry() ?? placeholderEntry(value), ref: next } };\n } else mismatch = model;\n }\n render();\n if (moved) options.onChange?.(moved);\n });\n }\n listen.addEventListener("click", () => {\n const shown = entry();\n if (shown) samples2.toggle(shown, options.language);\n });\n const open3 = async (focusModels = false) => {\n if (disposed) return null;\n if (picking) return null;\n samples2.stop();\n picking = new AbortController();\n const outer = options.signal;\n const stop = () => picking?.abort();\n outer?.addEventListener("abort", stop, { once: true });\n try {\n const current4 = value ? isPick(value) ? value.ref : value : null;\n const shown = entry();\n const pick4 = await openVoicePicker(\n ai,\n { ...options, value: current4, container: options.container ?? container, signal: picking.signal },\n shown && !isUnnamed(shown) ? shown : null,\n focusModels,\n mayAskSystem(options)\n );\n if (pick4 && !disposed) {\n value = pick4;\n sample = "idle";\n mismatch = null;\n recovery = null;\n if (pick4.ref.model) options = { ...options, model: pick4.ref.model };\n render();\n options.onChange?.(pick4);\n }\n return pick4;\n } finally {\n outer?.removeEventListener("abort", stop);\n picking = null;\n if (!disposed) openButton.focus();\n }\n };\n openButton.addEventListener("click", () => void open3());\n name();\n render();\n refit();\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n options.signal?.removeEventListener("abort", dispose);\n picking?.abort();\n lookup?.abort();\n samples2.dispose();\n memory.dispose();\n ui.remove();\n };\n if (options.signal?.aborted) dispose();\n else options.signal?.addEventListener("abort", dispose, { once: true });\n const set = (next) => {\n samples2.stop();\n value = next ?? null;\n sample = "idle";\n mismatch = null;\n recovery = null;\n name();\n render();\n };\n return {\n value: () => value,\n set,\n update(next) {\n if (!next || typeof next !== "object" || disposed) return;\n const { model, models: models2, language: language2, filters } = next;\n if (model !== void 0 && model !== options.model || models2 !== void 0) recovery = null;\n options = {\n ...options,\n ...next.model !== void 0 ? { model } : {},\n ...next.models !== void 0 ? { models: models2 } : {},\n ..."language" in next ? { language: language2 || void 0 } : {},\n ...next.filters !== void 0 ? { filters } : {}\n };\n if (next.value !== void 0) set(next.value);\n else render();\n if (next.model !== void 0 || next.models !== void 0 || next.value !== void 0) refit();\n },\n failed(error) {\n const found2 = voiceModelRecovery(error);\n if (disposed) return found2;\n recovery = found2;\n render();\n return found2;\n },\n open: () => open3(),\n dispose\n };\n}\n\n// src/voice-browser.ts\nfunction mountVoiceBrowser(container, ai, options = {}) {\n const { onPick, onCancel, categories, signal, ...picker } = options;\n const ui = mountUiHost(voicePickerCss, container, "nocha-voice-browser");\n const frame = element(ui.host.ownerDocument, "section", "nocha-voice-picker nocha-voice-picker--page");\n const core = new VoiceBrowserCore(ai, { ...picker, audition: void 0 }, {\n frame,\n ...onPick ? { pick: onPick } : {},\n ...onCancel ? { close: onCancel } : {},\n ...categories ? { categories } : {}\n });\n frame.addEventListener("keydown", (event) => {\n if (event.key !== "Escape" || event.defaultPrevented) return;\n if (core.fold()) event.preventDefault();\n else if (onCancel) {\n event.preventDefault();\n onCancel();\n }\n });\n ui.root.append(frame);\n let destroyed = false;\n const destroy = () => {\n if (destroyed) return;\n destroyed = true;\n signal?.removeEventListener("abort", destroy);\n core.dispose();\n ui.remove();\n };\n if (signal?.aborted) destroy();\n else {\n signal?.addEventListener("abort", destroy, { once: true });\n core.start();\n }\n return { refresh: () => {\n if (!destroyed) core.refresh();\n }, destroy };\n}\n\n// src/voice-audition.ts\nvar sampleLines = { fr: "Bonjour, je suis {name}. Voici ma voix.", en: "Hi, I\'m {name}. This is my voice." };\nvar sampleLanguage2 = (entry) => entry.languages[0] === "en" ? "en" : "fr";\nfunction speechAudition(ai, options) {\n if (typeof options?.confirm !== "function") throw invalid2("confirm must be a function asking the person");\n const { text: text6, language: language2, share, generationUsage } = options;\n if (text6 !== void 0 && typeof text6 !== "string" && typeof text6 !== "function") throw invalid2("text must be a string or a function");\n if (language2 !== void 0 && typeof language2 !== "string") throw invalid2("language must be a BCP-47 string");\n return async (entry, signal) => {\n const spoken = language2 || sampleLanguage2(entry);\n const line4 = typeof text6 === "function" ? text6(entry) : text6 ?? fill(sampleLines[baseLanguage(spoken) === "en" ? "en" : "fr"], { name: entry.spokenName || entry.name });\n const { model, id } = entry.ref;\n const input4 = {\n need: "audio.synthesize",\n prompt: speechModelSupportsTags(model) ? line4 : stripSpeechTags(line4),\n voice: id,\n language: spoken,\n ...model ? { model } : {},\n ...share ? { share: "experience" } : {},\n ...generationUsage ? { generationUsage } : {}\n };\n for (let attempt = 0; ; attempt += 1) {\n const quote = await ai.estimate(input4, { signal });\n if (quote.shared !== "ready" && quote.shared !== "pending" && !await options.confirm(quote, entry)) return null;\n if (signal?.aborted) return null;\n const charge = quote.estimated_charge_microcredits;\n try {\n const result2 = await ai.generate({ ...input4, quoteId: quote.quote_id, ...isMicrocredits(charge) ? { maximumCostMicrocredits: charge } : {} }, { signal });\n return `data:${result2.mime_type};base64,${result2.audio_base64}`;\n } catch (error) {\n if (attempt > 0 || signal?.aborted || voiceModelRecovery(error) !== "requote") throw error;\n }\n }\n };\n}\n\n// src/voice-random.ts\nvar catalogueLimit = 100;\nvar cataloguePages = 2;\nfunction shuffled(items, random) {\n const copy2 = items.slice();\n for (let index = copy2.length - 1; index > 0; index -= 1) {\n const other = Math.min(index, Math.floor(random() * (index + 1)));\n [copy2[index], copy2[other]] = [copy2[other], copy2[index]];\n }\n return copy2;\n}\nfunction drawn(pool, count2, random, model) {\n const order = shuffled(pool, random);\n if (!order.length) return [];\n return Array.from({ length: count2 }, (_, index) => {\n const entry = order[index % order.length];\n return model ? { ...entry, ref: { id: entry.ref.id, model } } : { ...entry, ref: { ...entry.ref } };\n });\n}\nfunction drawFilters(options, model) {\n const language2 = model.spec?.capabilities?.multilingual === true ? "" : baseLanguage(options.language);\n const gender = options.gender && modelAnswersFacets(model.spec, ["gender"]) ? options.gender : void 0;\n return { language: language2, ...gender ? { gender } : {} };\n}\nfunction compatible(entry, options, excluded, model) {\n const { language: language2, gender } = drawFilters(options, model);\n if (excluded.has(entry.ref.id)) return false;\n if (language2 && !entry.languages.includes(language2) && !entry.dialects?.some((dialect) => dialect.language === language2)) return false;\n if (gender && entry.traits.gender !== gender) return false;\n if (options.maxPriceMultiplier !== void 0 && (entry.premium ?? 1) > options.maxPriceMultiplier) return false;\n return model.target ? voiceFits(entry.ref, model.target, model.models) : Boolean(entry.ref.model) || isSpeechVoiceAlias(entry.ref.id);\n}\nasync function catalogue(ai, options, excluded, model) {\n const { language: language2, gender } = drawFilters(options, model);\n const input4 = {\n ...voicesInputFor(model.spec, {\n ...model.target ? { model: model.target } : {},\n ...language2 ? { language: language2 } : {},\n ...gender ? { gender } : {},\n ...options.maxPriceMultiplier !== void 0 ? { maxPriceMultiplier: options.maxPriceMultiplier } : {}\n }),\n limit: catalogueLimit\n };\n const pool = /* @__PURE__ */ new Map();\n let cursor;\n for (let page = 0; page < cataloguePages; page += 1) {\n let listed;\n try {\n listed = await ai.voices({ ...input4, ...cursor ? { cursor } : {} });\n } catch (error) {\n if (page || !isLegacySpeechHost(error)) throw error;\n return aliasVoiceEntries(model.target ?? "").filter((entry) => !excluded.has(entry.ref.id));\n }\n for (const voice of listed.voices) {\n const entry = speechVoiceEntry(voice, listed.model);\n if (entry && !excluded.has(entry.ref.id) && (!gender || entry.traits.gender === gender || isSpeechVoiceAlias(entry.ref.id))) {\n pool.set(entry.ref.id, entry);\n }\n }\n cursor = listed.next_cursor ?? void 0;\n if (!cursor || pool.size >= options.count) break;\n }\n return Array.from(pool.values());\n}\nfunction message(fallback, options, locale, model) {\n const text6 = voiceImagineTexts[locale];\n if (fallback === "empty") return text6.drawEmpty;\n if (fallback === "unavailable") return text6.drawUnavailable;\n const { language: code, gender } = drawFilters(options, model);\n const name = code ? languageName(code, locale) : "";\n return fill(text6.drawIncompatible, {\n gender: gender ? ` ${text6.genders[gender]}` : "",\n language: name ? ` ${fill(text6.inLanguage, { language: locale === "fr" ? name.toLocaleLowerCase("fr") : name })}` : ""\n });\n}\nasync function pickRandomVoices(ai, options) {\n const count2 = options?.count;\n if (!Number.isInteger(count2) || count2 < 1 || count2 > 100) throw invalid2("count must be an integer from 1 to 100");\n if (options.from !== void 0 && !["favorites", "catalogue", "preference"].includes(options.from)) throw invalid2("from must be favorites, catalogue or preference");\n const ceiling2 = options.maxPriceMultiplier;\n if (ceiling2 !== void 0 && !(typeof ceiling2 === "number" && Number.isFinite(ceiling2) && ceiling2 > 0)) throw invalid2("maxPriceMultiplier must be a positive number");\n const random = typeof options.random === "function" ? options.random : Math.random;\n const locale = uiLocale(options.locale);\n const excluded = new Set(Array.isArray(options.exclude) ? options.exclude.filter((id) => typeof id === "string") : []);\n const from = options.from ?? "preference";\n const listed = typeof ai.models === "function" ? await readModels(ai) : { models: [], defaultModel: "" };\n const serving = listed.models.filter((item) => !isModelUnavailable(item));\n const target = options.model || (listed.models.length ? chooseSpeechModel(serving.length ? serving : listed.models, listed.defaultModel, void 0) : void 0);\n const model = { target, models: listed.models, spec: listed.models.find((item) => item.model === target) };\n const fromCatalogue = async (fallback) => ({\n voices: drawn(await catalogue(ai, options, excluded, model), count2, random, target),\n source: "catalogue",\n ...fallback ? { fallback, message: message(fallback, options, locale, model) } : {}\n });\n if (from === "catalogue") return fromCatalogue();\n const account = await readAccountFavorites(ai);\n if (account.status !== "account") return fromCatalogue(from === "favorites" ? "unavailable" : void 0);\n if (from === "preference" && !account.value.imagineFromFavorites) return fromCatalogue();\n const favorites = account.value.favorites;\n if (!favorites.length) return fromCatalogue("empty");\n const pool = favorites.filter((entry) => compatible(entry, options, excluded, model));\n if (!pool.length) return fromCatalogue("incompatible");\n return { voices: drawn(pool, count2, random, target), source: "favorites" };\n}\n\n// src/voice-imagine-toggle.ts\nvar deviceKey = "nocha-voice-imagine";\nvar toggleCss = `\n:host { display: block; }\n.nocha-voice-imagine {\n display: flex; align-items: center; gap: 12px; min-height: 44px; padding: 6px 0; cursor: pointer;\n color: var(--nocha-ui-x-text); font-family: var(--nocha-ui-x-font); font-size: 15px;\n}\n.nocha-voice-imagine--disabled { cursor: default; }\n.nocha-voice-imagine__control { position: relative; flex: none; width: 24px; height: 24px; }\n.nocha-voice-imagine__box { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: inherit; }\n.nocha-voice-imagine__mark {\n display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; color: transparent;\n background: var(--nocha-ui-x-surface); border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius);\n pointer-events: none;\n}\n.nocha-voice-imagine__mark .nocha-ui-icon { width: 18px; height: 18px; }\n.nocha-voice-imagine__box:checked + .nocha-voice-imagine__mark {\n background: var(--nocha-ui-x-accent); border-color: var(--nocha-ui-x-accent); color: var(--nocha-ui-x-on-accent);\n}\n.nocha-voice-imagine__box:focus-visible + .nocha-voice-imagine__mark { outline: 2px solid var(--nocha-ui-x-accent); outline-offset: 2px; }\n.nocha-voice-imagine__box:disabled + .nocha-voice-imagine__mark { opacity: 0.45; border-style: dashed; }\n.nocha-voice-imagine__text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }\n.nocha-voice-imagine--disabled .nocha-voice-imagine__label { color: var(--nocha-ui-x-muted); }\n.nocha-voice-imagine__hint { font-size: 13px; color: var(--nocha-ui-x-muted); }\n`;\nfunction readDevice() {\n try {\n return globalThis.localStorage?.getItem(deviceKey) === "true";\n } catch {\n return false;\n }\n}\nfunction writeDevice(on) {\n try {\n globalThis.localStorage?.setItem(deviceKey, String(on));\n } catch {\n }\n}\nfunction createImagineFavoritesToggle(ai, options = {}) {\n const ui = createUiHost(toggleCss, "nocha-voice-imagine");\n const doc = ui.host.ownerDocument;\n const text6 = voiceImagineTexts[uiLocale(options.locale)];\n const hintId = `nocha-voice-imagine-hint-${Math.random().toString(36).slice(2, 10)}`;\n const box = element(doc, "input", "nocha-voice-imagine__box", { type: "checkbox", "aria-describedby": hintId, disabled: true });\n const label = element(doc, "span", "nocha-voice-imagine__label", {}, typeof options.label === "string" && options.label ? options.label : text6.label);\n const hint = element(doc, "span", "nocha-voice-imagine__hint", { id: hintId }, text6.loading);\n const root = element(\n doc,\n "label",\n "nocha-voice-imagine nocha-voice-imagine--disabled",\n {},\n element(doc, "span", "nocha-voice-imagine__control", {}, box, element(doc, "span", "nocha-voice-imagine__mark", {}, icon(doc, "check"))),\n element(doc, "span", "nocha-voice-imagine__text", {}, label, hint)\n );\n ui.root.append(root);\n let mode = null;\n let checked = false;\n let destroyed = false;\n const render = (favorites) => {\n const count2 = favorites?.favorites.length ?? 0;\n const empty = mode === "account" && count2 === 0;\n box.disabled = mode === null || empty;\n box.checked = checked && !empty;\n root.classList.toggle("nocha-voice-imagine--disabled", box.disabled);\n hint.textContent = mode === null ? text6.loading : mode === "device" ? text6.device : empty ? text6.none : count2 === 1 ? text6.countOne : fill(text6.count, { count: count2 });\n };\n let shown;\n const show2 = (favorites) => {\n mode = "account";\n shown = favorites;\n checked = favorites.imagineFromFavorites;\n render(favorites);\n };\n const stopListening = onAccountFavorites(ai, (value) => {\n if (!destroyed) show2(value);\n });\n const load = async (refresh) => {\n const result2 = await readAccountFavorites(ai, { refresh });\n if (destroyed) return;\n if (result2.status === "account") show2(result2.value);\n else if (mode !== "account" || result2.reason !== "failed") {\n mode = "device";\n checked = readDevice();\n render();\n }\n };\n box.addEventListener("change", () => {\n const on = box.checked;\n checked = on;\n options.onChange?.(on);\n if (mode === "device") {\n writeDevice(on);\n return;\n }\n render(shown);\n void writeAccountFavorites(ai, { imagineFromFavorites: on }).catch(() => {\n if (destroyed || checked !== on) return;\n checked = !on;\n render(shown);\n options.onChange?.(!on);\n });\n });\n void load(false);\n return {\n element: ui.host,\n get checked() {\n return box.checked;\n },\n refresh: () => load(true),\n destroy() {\n if (destroyed) return;\n destroyed = true;\n stopListening();\n ui.remove();\n }\n };\n}\n\n// src/video-settings-controls.ts\nvar cls = (name) => `nocha-video-settings__${name}`;\nvar counter = 0;\nvar uid = (prefix) => `${prefix}-${(counter += 1).toString(36)}`;\nfunction row(doc, text6, ...controls) {\n const id = uid("nocha-video-label");\n const label = element(doc, "span", cls("label"), { id }, text6);\n const control = element(doc, "div", cls("control"), {}, ...controls);\n return { element: element(doc, "div", cls("row"), {}, label, control), label, id };\n}\nfunction segments(doc, labelledBy, onChange, chips = false) {\n const group = element(doc, "div", cls(chips ? "chips" : "segments"), { role: "radiogroup", "aria-labelledby": labelledBy });\n let buttons = [];\n let key2 = "";\n let current4;\n const mark = () => {\n const found = buttons.some((item) => item.option.value === current4);\n buttons.forEach(({ button, option }, index) => {\n const on = option.value === current4;\n button.setAttribute("aria-checked", String(on));\n button.tabIndex = on || !found && index === 0 ? 0 : -1;\n });\n };\n group.addEventListener("keydown", (event) => {\n const moves = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };\n const enabled2 = buttons.filter((item) => !item.option.disabled);\n if (!enabled2.length) return;\n const index = Math.max(0, enabled2.findIndex((item) => item.option.value === current4));\n const next = event.key === "Home" ? enabled2[0] : event.key === "End" ? enabled2[enabled2.length - 1] : moves[event.key] === void 0 ? void 0 : enabled2[(index + (moves[event.key] ?? 0) + enabled2.length) % enabled2.length];\n if (!next) return;\n event.preventDefault();\n next.button.focus();\n if (next.option.value !== current4) {\n current4 = next.option.value;\n mark();\n onChange(next.option.value);\n }\n });\n return {\n element: group,\n update(options, value) {\n const next = JSON.stringify(options.map((option) => [option.value, option.text, option.label ?? "", Boolean(option.disabled)]));\n if (next !== key2) {\n key2 = next;\n buttons = options.map((option) => {\n const word2 = typeof option.value !== "string" || !/^[\\d:.\\s]+[a-z]?$/iu.test(option.text);\n const button = element(\n doc,\n "button",\n `${cls("segment")}${word2 ? ` ${cls("segment--word")}` : ""}`,\n { type: "button", role: "radio", "aria-label": option.label, disabled: Boolean(option.disabled) },\n option.text\n );\n button.addEventListener("click", () => {\n if (option.value === current4) return;\n current4 = option.value;\n mark();\n onChange(option.value);\n });\n return { button, option };\n });\n group.replaceChildren(...buttons.map((item) => item.button));\n }\n current4 = value;\n mark();\n }\n };\n}\nfunction switchControl(doc, text6, onChange, labelledBy) {\n const button = element(\n doc,\n "button",\n cls("switch"),\n { type: "button", role: "switch", "aria-checked": "false", "aria-labelledby": labelledBy },\n element(doc, "span", cls("track")),\n text6 ? element(doc, "span", cls("switch-text"), {}, text6) : null\n );\n button.addEventListener("click", () => {\n const next = button.getAttribute("aria-checked") !== "true";\n button.setAttribute("aria-checked", String(next));\n onChange(next);\n });\n return {\n element: button,\n set(checked, disabled = false) {\n button.setAttribute("aria-checked", String(checked));\n button.disabled = disabled;\n }\n };\n}\nfunction selectControl(doc, labelledBy, onChange) {\n const select = element(doc, "select", "", { "aria-labelledby": labelledBy });\n const wrap = element(doc, "span", cls("select"), {}, select, icon(doc, "chevron"));\n let key2 = "";\n select.addEventListener("change", () => onChange(select.value));\n return {\n element: wrap,\n select,\n update(options, value) {\n const next = JSON.stringify(options.map((option) => [option.value, option.text, option.group ?? "", Boolean(option.disabled)]));\n if (next !== key2) {\n key2 = next;\n const nodes = [];\n const groups3 = /* @__PURE__ */ new Map();\n let open3 = "";\n for (const option of options) {\n const node = element(doc, "option", "", { value: option.value, disabled: Boolean(option.disabled) }, option.text);\n const label = option.group ?? "";\n if (!label) nodes.push(node);\n else {\n if (open3 !== label || !groups3.has(label)) {\n groups3.set(label, element(doc, "optgroup", "", { label }));\n nodes.push(groups3.get(label));\n }\n groups3.get(label)?.append(node);\n }\n open3 = label;\n }\n select.replaceChildren(...nodes);\n }\n select.value = value;\n select.disabled = options.filter((option) => !option.disabled).length < 2;\n }\n };\n}\nfunction sliderControl(doc, labelledBy, onChange) {\n const input4 = element(doc, "input", cls("slider"), { type: "range", min: "0", max: "0", step: "1", "aria-labelledby": labelledBy });\n const output = element(doc, "output", cls("value"), { "aria-hidden": "true" });\n let stops = [];\n let format = (value) => String(value);\n const read4 = () => stops[Math.round(Number(input4.value))];\n const show2 = (value) => {\n output.textContent = value === void 0 ? "\\u2014" : format(value);\n input4.setAttribute("aria-valuetext", output.textContent);\n };\n input4.addEventListener("input", () => show2(read4()));\n input4.addEventListener("change", () => {\n const value = read4();\n if (value !== void 0) onChange(value);\n });\n return {\n element: element(doc, "div", cls("range"), {}, input4, output),\n output,\n update(next, value, formatter) {\n stops = next;\n format = formatter;\n input4.max = String(Math.max(0, next.length - 1));\n input4.value = String(Math.max(0, next.indexOf(value)));\n input4.disabled = next.length < 2;\n input4.hidden = next.length < 2;\n show2(next.includes(value) ? value : void 0);\n }\n };\n}\n\n// src/video-settings-css.ts\nvar videoSettingsCss = `\n:host { display: block; container-type: inline-size; }\n/* The hidden attribute always wins over a rule\'s display (the 4K switch, a single resolution\'s segments). */\n:host([hidden]), [hidden] { display: none !important; }\n/* One column that never grows past the component: a long summary or name ellipsizes instead of widening the page. */\n.nocha-video-settings, .nocha-workflows, .nocha-video-settings__group, .nocha-video-settings__more-body, .nocha-video-settings__media,\n.nocha-video-settings__block, .nocha-video-settings__row { grid-template-columns: minmax(0, 1fr); }\n.nocha-video-settings__more, .nocha-video-settings__summary { min-width: 0; }\n.nocha-video-settings, .nocha-workflows {\n display: grid; gap: 20px; min-width: 0; font-family: var(--nocha-ui-x-font); color: var(--nocha-ui-x-text);\n}\n.nocha-video-settings--compact { gap: 12px; font-size: 15px; }\n/* Inert while the experience runs a command (setDisabled): dimmed, nothing reacts. */\n.nocha-video-settings--disabled { opacity: 0.5; filter: saturate(0.4); transition: opacity 120ms ease; }\n.nocha-video-settings__group { display: grid; gap: 16px; min-width: 0; }\n.nocha-video-settings--compact .nocha-video-settings__group { gap: 4px; }\n.nocha-video-settings__row { display: grid; gap: 8px; min-width: 0; }\n.nocha-video-settings--compact .nocha-video-settings__row {\n grid-template-columns: minmax(84px, 30%) minmax(0, 1fr); align-items: center; gap: 12px; min-height: 48px;\n}\n/* The workflow list needs the whole width, whatever the density. */\n.nocha-video-settings--compact .nocha-video-settings__row--workflow { grid-template-columns: minmax(0, 1fr); align-items: start; gap: 8px; }\n.nocha-video-settings__label { font-size: 13px; font-weight: 600; color: var(--nocha-ui-x-muted); min-width: 0; }\n.nocha-video-settings--compact .nocha-video-settings__label { font-weight: 500; font-size: 14px; }\n.nocha-video-settings__control { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; min-width: 0; }\n.nocha-video-settings__control > .nocha-workflows, .nocha-video-settings__control > .nocha-video-settings__range { flex: 1 1 100%; min-width: 0; }\n.nocha-video-settings__control > .nocha-video-settings__range--property { flex: 1 1 160px; }\n.nocha-video-settings__more-body > .nocha-video-settings__group + .nocha-video-settings__group:not([hidden]),\n.nocha-video-settings__group--top > .nocha-video-settings__group + .nocha-video-settings__group:not([hidden]) {\n padding-top: 20px; border-top: 1px solid var(--nocha-ui-x-line);\n}\n.nocha-video-settings--compact .nocha-video-settings__more-body > .nocha-video-settings__group + .nocha-video-settings__group:not([hidden]),\n.nocha-video-settings--compact .nocha-video-settings__group--top > .nocha-video-settings__group + .nocha-video-settings__group:not([hidden]) { padding-top: 8px; }\n.nocha-video-settings__note { margin: 0; font-size: 13px; line-height: 1.4; color: var(--nocha-ui-x-muted); }\n.nocha-video-settings--compact .nocha-video-settings__note { grid-column: 2; }\n\n/* A fixed workflow\'s title, heading the compact panel. */\n.nocha-video-settings__title {\n min-width: 0; font-size: 15px; font-weight: 600; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n\n/* \\xAB R\\xE9glages \\xBB, folded into one line. */\n.nocha-video-settings__more { border-top: 1px solid var(--nocha-ui-x-line); border-bottom: 1px solid var(--nocha-ui-x-line); }\n.nocha-video-settings__summary {\n display: flex; align-items: center; gap: 12px; min-height: 52px; padding: 0 2px; list-style: none; cursor: pointer;\n -webkit-tap-highlight-color: transparent;\n}\n.nocha-video-settings__summary::-webkit-details-marker { display: none; }\n/* Full text colour and weight: a page\'s own color on <summary> (or a UA marker colour) never pales the label. */\n.nocha-video-settings__summary-title { flex: none; font-size: 15px; font-weight: 650; color: var(--nocha-ui-x-text); }\n.nocha-video-settings__summary-line {\n flex: 1; min-width: 0; text-align: right; color: var(--nocha-ui-x-muted); font: 13px/1 var(--nocha-ui-x-mono);\n font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n/* Two chevrons swapped, never one turned: a capture or a slow frame never shows it halfway. */\n.nocha-video-settings__summary .nocha-ui-icon { color: var(--nocha-ui-x-muted); }\n.nocha-video-settings__more[open] > .nocha-video-settings__summary .nocha-video-settings__chevron--closed,\n.nocha-video-settings__more:not([open]) > .nocha-video-settings__summary .nocha-video-settings__chevron--open { display: none; }\n.nocha-video-settings__more[open] > .nocha-video-settings__summary .nocha-video-settings__summary-line { visibility: hidden; }\n.nocha-video-settings__more-body { display: grid; gap: 20px; padding: 4px 0 20px; }\n.nocha-video-settings--compact .nocha-video-settings__more-body { gap: 8px; padding-bottom: 12px; }\n\n/* The bridge\'s line: the settings summed up, and \\xAB R\\xE9glages \\xBB, which opens the mini-experience \\xAB R\\xE9glages vid\\xE9o \\xBB. */\n.nocha-video-settings__bar {\n display: flex; align-items: center; gap: 12px; min-width: 0; min-height: 52px;\n border-top: 1px solid var(--nocha-ui-x-line); border-bottom: 1px solid var(--nocha-ui-x-line);\n}\n.nocha-video-settings__bar .nocha-video-settings__summary-line { text-align: left; color: var(--nocha-ui-x-text); line-height: 1.3; }\n.nocha-video-settings__open {\n flex: none; display: inline-flex; align-items: center; min-height: 44px; padding: 0 16px; font-size: 15px; font-weight: 650;\n color: var(--nocha-ui-x-text); border: 1px solid var(--nocha-ui-x-text); border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-video-settings__open[aria-busy="true"] { opacity: 0.6; }\n@media (hover: hover) { .nocha-video-settings__open:not(:disabled):hover { background: var(--nocha-ui-x-raised); } }\n\n/* Segments and chips: a radio group, the chosen one filled. */\n.nocha-video-settings__segments { display: inline-flex; max-width: 100%; border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius); }\n.nocha-video-settings__segment {\n display: inline-flex; align-items: center; justify-content: center; min-width: 56px; min-height: 44px; padding: 0 14px;\n font: 500 14px/1 var(--nocha-ui-x-mono); font-variant-numeric: tabular-nums; white-space: nowrap;\n}\n.nocha-video-settings__segment--word { font-family: var(--nocha-ui-x-font); }\n.nocha-video-settings__segment + .nocha-video-settings__segment { border-left: 1px solid var(--nocha-ui-x-line); }\n.nocha-video-settings__segment[aria-checked="true"] { background: var(--nocha-ui-x-accent); color: var(--nocha-ui-x-on-accent); }\n.nocha-video-settings__chips { display: flex; flex-wrap: wrap; gap: 8px; }\n.nocha-video-settings__chips .nocha-video-settings__segment {\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-video-settings__chips .nocha-video-settings__segment + .nocha-video-settings__segment { border-left: 1px solid var(--nocha-ui-x-line); }\n.nocha-video-settings__chips .nocha-video-settings__segment[aria-checked="true"] { border-color: var(--nocha-ui-x-accent); }\n@media (hover: hover) {\n .nocha-video-settings__segment:not([aria-checked="true"]):hover { background: var(--nocha-ui-x-raised); }\n}\n\n/* Duration: a slider over the admitted seconds, read in figures. */\n.nocha-video-settings__fixed {\n display: inline-flex; align-items: center; min-height: 44px; font: 600 15px/1 var(--nocha-ui-x-mono); font-variant-numeric: tabular-nums;\n}\n.nocha-video-settings__range { display: flex; align-items: center; gap: 16px; width: 100%; min-width: 0; }\n.nocha-video-settings__slider {\n flex: 1; min-width: 0; height: 44px; margin: 0; background: transparent; cursor: pointer; -webkit-appearance: none; appearance: none;\n accent-color: var(--nocha-ui-x-accent);\n}\n.nocha-video-settings__slider::-webkit-slider-runnable-track { height: 2px; background: var(--nocha-ui-x-line); }\n.nocha-video-settings__slider::-moz-range-track { height: 2px; background: var(--nocha-ui-x-line); }\n.nocha-video-settings__slider::-moz-range-progress { height: 2px; background: var(--nocha-ui-x-accent); }\n.nocha-video-settings__slider::-webkit-slider-thumb {\n width: 14px; height: 24px; margin-top: -11px; border: 0; border-radius: var(--nocha-ui-x-radius); background: var(--nocha-ui-x-text);\n -webkit-appearance: none; appearance: none;\n}\n.nocha-video-settings__slider::-moz-range-thumb { width: 14px; height: 24px; border: 0; border-radius: var(--nocha-ui-x-radius); background: var(--nocha-ui-x-text); }\n@media (pointer: coarse) {\n .nocha-video-settings__slider::-webkit-slider-thumb { width: 22px; height: 32px; margin-top: -15px; }\n .nocha-video-settings__slider::-moz-range-thumb { width: 22px; height: 32px; }\n}\n.nocha-video-settings__value {\n flex: none; min-width: 5.5ch; text-align: right; font: 600 16px/1 var(--nocha-ui-x-mono); font-variant-numeric: tabular-nums;\n}\n.nocha-video-settings__value--auto { color: var(--nocha-ui-x-muted); font-weight: 500; }\n\n/* Selects. */\n.nocha-video-settings__select { position: relative; display: block; width: 100%; max-width: 420px; min-width: 0; }\n.nocha-video-settings__select select {\n display: block; width: 100%; min-height: 44px; margin: 0; padding: 0 40px 0 12px; font-size: 15px;\n background: var(--nocha-ui-x-raised); border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius);\n -webkit-appearance: none; appearance: none; cursor: pointer; text-overflow: ellipsis;\n}\n.nocha-video-settings__select select:disabled { cursor: default; color: var(--nocha-ui-x-muted); }\n.nocha-video-settings__select .nocha-ui-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); color: var(--nocha-ui-x-muted); pointer-events: none; }\n.nocha-video-settings__select select:focus-visible { outline: 2px solid var(--nocha-ui-x-accent); outline-offset: -2px; }\n\n/* Switches. */\n.nocha-video-settings__switch { display: inline-flex; align-items: center; gap: 12px; min-height: 44px; padding-right: 4px; }\n.nocha-video-settings__track {\n position: relative; flex: none; width: 40px; height: 22px; border: 1px solid var(--nocha-ui-x-line);\n border-radius: var(--nocha-ui-x-radius); background: var(--nocha-ui-x-raised); transition: background-color 120ms ease;\n}\n.nocha-video-settings__track::after {\n content: ""; position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: var(--nocha-ui-x-radius);\n background: var(--nocha-ui-x-muted); transition: transform 120ms ease;\n}\n.nocha-video-settings__switch[aria-checked="true"] .nocha-video-settings__track { background: var(--nocha-ui-x-accent); border-color: var(--nocha-ui-x-accent); }\n.nocha-video-settings__switch[aria-checked="true"] .nocha-video-settings__track::after { transform: translateX(18px); background: var(--nocha-ui-x-on-accent); }\n.nocha-video-settings__switch-text { font: 500 14px/1 var(--nocha-ui-x-mono); }\n.nocha-video-settings__switch:disabled { opacity: 0.45; }\n\n/* References, music, voice. */\n.nocha-video-settings__media { display: grid; gap: 20px; }\n.nocha-video-settings--compact .nocha-video-settings__media { gap: 12px; }\n.nocha-video-settings__block { display: grid; gap: 8px; min-width: 0; }\n.nocha-video-settings__head { display: flex; align-items: baseline; gap: 8px; min-height: 20px; }\n.nocha-video-settings__count { font: 12px/1 var(--nocha-ui-x-mono); font-variant-numeric: tabular-nums; color: var(--nocha-ui-x-muted); }\n.nocha-video-settings__required { font-size: 12px; color: var(--nocha-ui-x-accent); }\n.nocha-video-settings__tiles { display: flex; flex-wrap: wrap; gap: 8px; list-style: none; margin: 0; padding: 0; }\n.nocha-video-settings__tile {\n display: grid; grid-template-rows: 88px 44px; width: 132px; border: 1px solid var(--nocha-ui-x-line);\n border-radius: var(--nocha-ui-x-radius); overflow: hidden; background: var(--nocha-ui-x-raised);\n}\n.nocha-video-settings__thumb { width: 100%; height: 100%; object-fit: cover; display: block; background: var(--nocha-ui-x-raised); }\n.nocha-video-settings__thumb--empty { display: grid; place-items: center; color: var(--nocha-ui-x-muted); font-size: 12px; padding: 6px; text-align: center; overflow: hidden; }\n.nocha-video-settings__tools { display: grid; grid-template-columns: repeat(3, 44px); border-top: 1px solid var(--nocha-ui-x-line); }\n.nocha-video-settings__tool { display: grid; place-items: center; width: 44px; height: 44px; color: var(--nocha-ui-x-text); }\n.nocha-video-settings__tool:disabled { color: var(--nocha-ui-x-muted); opacity: 0.4; }\n.nocha-video-settings__tool .nocha-ui-icon { width: 18px; height: 18px; }\n@media (hover: hover) { .nocha-video-settings__tool:not(:disabled):hover { background: var(--nocha-ui-x-line); } }\n.nocha-video-settings__add {\n display: grid; place-content: center; justify-items: center; gap: 6px; width: 132px; min-height: 134px; font-size: 14px;\n color: var(--nocha-ui-x-muted); border: 1px dashed var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius);\n}\n.nocha-video-settings__add:disabled { opacity: 0.4; }\n.nocha-video-settings__add--line {\n display: inline-flex; align-items: center; gap: 8px; width: auto; min-height: 44px; padding: 0 14px; justify-self: start;\n}\n.nocha-video-settings__add--line .nocha-ui-icon { width: 18px; height: 18px; }\n@media (hover: hover) { .nocha-video-settings__add:not(:disabled):hover { color: var(--nocha-ui-x-text); border-color: var(--nocha-ui-x-text); } }\n.nocha-video-settings__tile--pending .nocha-video-settings__thumb { animation: nocha-video-settings-pulse 900ms ease-in-out infinite alternate; }\n@keyframes nocha-video-settings-pulse { to { opacity: 0.4; } }\n.nocha-video-settings__sounds { display: grid; list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--nocha-ui-x-line); }\n.nocha-video-settings__sound {\n display: flex; align-items: center; gap: 4px; min-height: 44px; padding-left: 10px; border-bottom: 1px solid var(--nocha-ui-x-line);\n}\n.nocha-video-settings__sound-name { flex: 1; min-width: 0; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n.nocha-video-settings__error { font-size: 13px; color: var(--nocha-ui-x-accent); }\n.nocha-video-settings__file { display: none; }\n.nocha-video-settings__voice { min-width: 0; }\n\n/* Status. */\n.nocha-video-settings__status { display: flex; align-items: center; gap: 12px; min-height: 44px; font-size: 14px; color: var(--nocha-ui-x-muted); }\n.nocha-video-settings__retry {\n min-height: 44px; padding: 0 14px; color: var(--nocha-ui-x-text); border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius);\n}\n\n/* Workflows as cards. */\n.nocha-workflows { gap: 8px; }\n.nocha-workflows__cards {\n display: grid; grid-template-columns: repeat(auto-fill, minmax(168px, 1fr)); gap: 1px; background: var(--nocha-ui-x-line);\n border: 1px solid var(--nocha-ui-x-line); border-radius: var(--nocha-ui-x-radius); overflow: hidden;\n}\n@container (max-width: 440px) { .nocha-workflows__cards { grid-template-columns: repeat(2, minmax(0, 1fr)); } }\n@container (max-width: 260px) { .nocha-workflows__cards { grid-template-columns: minmax(0, 1fr); } }\n.nocha-workflows__card {\n position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 4px; min-width: 0; min-height: 96px;\n padding: 12px 14px; background: var(--nocha-ui-x-surface); text-align: left; transition: background-color 120ms ease;\n}\n.nocha-workflows--compact-density .nocha-workflows__card { min-height: 76px; padding: 10px 12px; }\n@media (hover: hover) { .nocha-workflows__card:not([aria-disabled="true"]):hover { background: var(--nocha-ui-x-raised); } }\n.nocha-workflows__card[aria-checked="true"] { background: var(--nocha-ui-x-raised); }\n.nocha-workflows__card[aria-checked="true"]::after {\n content: ""; position: absolute; inset: 0; border: 2px solid var(--nocha-ui-x-accent); pointer-events: none;\n}\n.nocha-workflows__card[aria-disabled="true"] { cursor: default; }\n.nocha-workflows__card[aria-disabled="true"] > * { opacity: 0.5; }\n.nocha-workflows__name { max-width: 100%; font-size: 15px; font-weight: 650; line-height: 1.25; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n.nocha-workflows__text {\n display: -webkit-box; overflow: hidden; font-size: 13px; line-height: 1.35; color: var(--nocha-ui-x-muted);\n -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2;\n}\n.nocha-workflows__text--reason { font-style: italic; }\n.nocha-workflows__meta { display: flex; align-items: center; gap: 8px; margin-top: auto; padding-top: 4px; color: var(--nocha-ui-x-muted); min-width: 0; }\n.nocha-workflows__range { color: var(--nocha-ui-x-text); font: 500 12px/1 var(--nocha-ui-x-mono); font-variant-numeric: tabular-nums; white-space: nowrap; }\n.nocha-workflows__badges { display: inline-flex; gap: 6px; }\n.nocha-workflows__badges .nocha-ui-icon { width: 14px; height: 14px; }\n.nocha-workflows__member { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 12px; }\n.nocha-workflows__member-label { font-size: 13px; font-weight: 600; color: var(--nocha-ui-x-muted); }\n\n/* Workflows as dense lines. */\n.nocha-workflows__list { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--nocha-ui-x-line); }\n.nocha-workflows__heading { padding: 14px 0 6px; font-size: 12px; font-weight: 600; color: var(--nocha-ui-x-muted); border-bottom: 1px solid var(--nocha-ui-x-line); }\n.nocha-workflows__line {\n display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; align-items: center; gap: 12px; width: 100%; min-height: 52px;\n padding: 6px 4px 6px 10px; border-bottom: 1px solid var(--nocha-ui-x-line); text-align: left;\n}\n@media (hover: hover) { .nocha-workflows__line:not([aria-disabled="true"]):hover { background: var(--nocha-ui-x-raised); } }\n.nocha-workflows__line[aria-checked="true"] { background: var(--nocha-ui-x-raised); box-shadow: inset 3px 0 0 var(--nocha-ui-x-accent); }\n.nocha-workflows__line[aria-disabled="true"] { cursor: default; }\n.nocha-workflows__line[aria-disabled="true"] > * { opacity: 0.5; }\n.nocha-workflows__dot { width: 12px; height: 12px; border: 1px solid var(--nocha-ui-x-muted); border-radius: var(--nocha-ui-x-radius); }\n.nocha-workflows__line[aria-checked="true"] .nocha-workflows__dot { background: var(--nocha-ui-x-accent); border-color: var(--nocha-ui-x-accent); }\n.nocha-workflows__words { display: flex; align-items: baseline; gap: 10px; min-width: 0; }\n.nocha-workflows__words .nocha-workflows__name { flex: none; max-width: 60%; font-size: 15px; font-weight: 600; }\n.nocha-workflows__words .nocha-workflows__text { display: block; flex: 1; min-width: 0; white-space: nowrap; text-overflow: ellipsis; }\n@container (max-width: 440px) {\n .nocha-workflows__words { flex-direction: column; align-items: flex-start; gap: 2px; }\n .nocha-workflows__words .nocha-workflows__name { max-width: 100%; }\n .nocha-workflows__words .nocha-workflows__text { width: 100%; }\n}\n.nocha-workflows__line .nocha-workflows__meta { margin: 0; padding: 0; }\n\n/* Workflows as a menu. */\n.nocha-workflows__detail { display: flex; align-items: center; gap: 10px; min-height: 20px; color: var(--nocha-ui-x-muted); font-size: 13px; min-width: 0; }\n.nocha-workflows__detail .nocha-workflows__text { display: block; flex: 1; min-width: 0; white-space: nowrap; text-overflow: ellipsis; }\n`;\n\n// src/video-workflow-rules.ts\nvar speechOrder = ["none", "auto", "required"];\nvar maxSeconds = 600;\nfunction videoSpeechFor(workflow2, seconds, preferred) {\n const admits = (mode) => workflow2.speech_modes.some((entry) => entry.mode === mode && (entry.durations_seconds === null || entry.durations_seconds.includes(seconds)));\n if (preferred && admits(preferred)) return preferred;\n return speechOrder.find(admits) ?? null;\n}\nvar videoSpeechModes = (workflow2, seconds) => speechOrder.filter((mode) => workflow2.speech_modes.some((entry) => entry.mode === mode && (entry.durations_seconds === null || entry.durations_seconds.includes(seconds))));\nfunction videoWorkflowDurations(workflow2) {\n const { min, max, allowed } = workflow2.duration_seconds;\n const top = Math.min(max, maxSeconds);\n const candidates = allowed ?? Array.from({ length: Math.max(0, top - min + 1) }, (_, index) => min + index);\n return [...new Set(candidates)].sort((a, b) => a - b).filter((value) => value >= Math.max(1, min) && value <= top && videoSpeechFor(workflow2, value) !== null);\n}\nfunction nearest(admitted, wanted) {\n let best = null;\n for (const value of admitted) if (best === null || Math.abs(value - wanted) < Math.abs(best - wanted)) best = value;\n return best;\n}\nfunction durationRangeText(admitted, stops) {\n const first = admitted[0];\n const last = admitted[admitted.length - 1];\n if (first === void 0 || last === void 0) return "\\u2014";\n if (first === last) return `${first} s`;\n if (stops && admitted.length <= 4) return `${admitted.join(" \\xB7 ")} s`;\n return `${first}\\u2013${last} s`;\n}\nvar legacyRoles = {\n "clip-debut-fin": ["start_frame", "end_frame"],\n "clip-debut-fin-references": ["start_frame", "end_frame"],\n "edition-video": ["source_video"],\n "analyse-video": ["source_video"]\n};\nvar musicVoice = ["film-narratif-musique-voix", "film-narratif-musique-voix-audio"];\nvar audioTypes2 = ["audio/mpeg", "audio/wav"];\nvar imageRoles = ["character", "location", "style"];\nvar roleOf = (workflow2, role) => workflow2.references.roles.find((entry) => entry.role === role);\nfunction roleMax(workflow2, role) {\n if (workflow2.references.roles.length) return roleOf(workflow2, role)?.max ?? 0;\n if (role === "soundtrack" || role === "voice") {\n if (!workflow2.references.mime_types.some((type) => audioTypes2.includes(type))) return 0;\n return role === "soundtrack" || musicVoice.includes(workflow2.id) || musicVoice.includes(workflow2.base_id ?? "") ? 1 : 0;\n }\n return (legacyRoles[workflow2.id] ?? legacyRoles[workflow2.base_id ?? ""] ?? []).includes(role) ? 1 : 0;\n}\nfunction roleMin(workflow2, role) {\n const published = roleOf(workflow2, role)?.min;\n if (published !== void 0) return published;\n if (role === "voice") return roleMax(workflow2, "voice") > 0 ? 1 : 0;\n return role === "source_video" && roleMax(workflow2, role) > 0 ? 1 : 0;\n}\nfunction referenceSlots(workflow2) {\n const published = workflow2.references.roles.map((role) => ({ role: role.role, media: role.media, min: role.min, max: role.max }));\n if (!workflow2.references.roles.length) {\n for (const role of ["source_video", "start_frame", "end_frame", "soundtrack", "voice"]) {\n const max = roleMax(workflow2, role);\n if (max > 0) published.push({ role, media: role === "source_video" ? "video" : role === "soundtrack" || role === "voice" ? "audio" : "image", min: roleMin(workflow2, role), max });\n }\n }\n const modules = published.reduce((total, slot) => total + (slot.media === "audio" ? 0 : slot.max), 0);\n const images = Math.min(imageCapacity(workflow2), Math.max(0, visualCapacity(workflow2) - modules));\n const types = workflow2.references.mime_types;\n const takesImages = images > 0 && (!types.length || types.some((type) => type.startsWith("image/")));\n return [...published, ...takesImages ? imageRoles.map((role) => ({ role, media: "image", min: 0, max: images })) : []];\n}\nfunction visualCapacity(workflow2) {\n const audio = workflow2.references.roles.reduce((total, role) => total + (role.media === "audio" ? role.max : 0), 0);\n return Math.max(0, workflow2.references.max - audio);\n}\nvar imageCapacity = (workflow2) => Math.min(8, visualCapacity(workflow2));\nfunction mediaTypes3(workflow2, media2) {\n const listed = workflow2.references.mime_types.filter((type) => type.startsWith(`${media2}/`));\n if (listed.length) return listed;\n return media2 === "image" ? ["image/jpeg", "image/png", "image/webp"] : media2 === "audio" ? [...audioTypes2] : ["video/mp4", "video/quicktime"];\n}\nvar stepPattern = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\nvar keyPattern = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;\nvar routeName = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,127}$/;\nvar worldStep = "worldReferences";\nvar reservedVideoPropertyKeys = /* @__PURE__ */ new Set([\n "resolution",\n "timing",\n "speech",\n "enabled",\n "layout",\n "mode",\n "nativeAudio",\n "upscale4k",\n "soundtrackExport",\n "model",\n "route",\n "modelQuality",\n "writing"\n]);\nvar isRoute = (value) => Boolean(value && typeof value === "object" && typeof value.provider === "string" && routeName.test(value.provider) && typeof value.model === "string" && routeName.test(value.model));\nvar scalar2 = (value) => typeof value === "string" && value.length > 0 && value.length <= 64 || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);\nfunction* properties2(workflow2) {\n for (const step3 of workflow2.steps.slice(0, 32)) {\n if (!stepPattern.test(step3.id)) continue;\n for (const definition of (step3.properties ?? []).slice(0, 64)) yield { step: step3.id, definition };\n }\n}\nvar find = (workflow2, key2, type, step3) => {\n for (const item of properties2(workflow2)) if (item.definition.key === key2 && item.definition.type === type && (!step3 || item.step === step3)) return item;\n return void 0;\n};\nfunction modelOffer(workflow2) {\n const item = find(workflow2, "route", "route", "clips") ?? find(workflow2, "route", "route");\n if (!item || item.definition.type !== "route") return null;\n const fallback = isRoute(item.definition.default) ? item.definition.default : null;\n const routes = [];\n for (const route of item.definition.constraints.routes.slice(0, 32)) {\n if (!isRoute(route) || routes.some((held) => held.model === route.model)) continue;\n routes.push(fallback && route.model === fallback.model ? { ...fallback } : { provider: route.provider, model: route.model });\n }\n if (fallback && !routes.some((route) => route.model === fallback.model)) routes.unshift({ ...fallback });\n return routes.length ? { step: item.step, routes, fallback: fallback?.model ?? null } : null;\n}\nfunction qualityOffer(workflow2) {\n const item = find(workflow2, "modelQuality", "enum", "clips") ?? find(workflow2, "modelQuality", "enum");\n if (!item || item.definition.type !== "enum") return null;\n const values = [...new Set(item.definition.constraints.values.filter(scalar2))].slice(0, 32);\n if (values.length < 1) return null;\n const fallback = scalar2(item.definition.default) && values.includes(item.definition.default) ? item.definition.default : null;\n return { step: item.step, values, fallback };\n}\nfunction worldOffer(workflow2) {\n const mode = find(workflow2, "mode", "enum", worldStep);\n const values = mode?.definition.type === "enum" ? mode.definition.constraints.values : [];\n const fallback = mode && (mode.definition.default === "auto" || mode.definition.default === "off") ? mode.definition.default : null;\n if (!mode || !fallback || !values.includes("auto") || !values.includes("off")) {\n return workflow2.reference_preparation ? { step: null, mode: "auto", timing: null } : null;\n }\n const timing = find(workflow2, "timing", "enum", worldStep);\n const moments = timing?.definition.type === "enum" ? ["beforeStory", "afterStory"].filter((value) => timing.definition.constraints.values.includes(value)) : [];\n const timingFallback = timing && moments.includes(timing.definition.default) ? timing.definition.default : null;\n return { step: mode.step, mode: fallback, timing: timingFallback && moments.length > 1 ? { values: [...moments], fallback: timingFallback } : null };\n}\nfunction upscaleOffer(workflow2) {\n const item = find(workflow2, "upscale4k", "boolean", "filmExport");\n return item ? { step: item.step, fallback: item.definition.default === true } : null;\n}\nfunction soundtrackExportStep(workflow2) {\n for (const { step: step3, definition } of properties2(workflow2)) {\n if (definition.key === "soundtrackExport" && definition.type === "enum" && definition.constraints.values.includes("add") && definition.constraints.values.includes("none")) return step3;\n }\n return null;\n}\nfunction offeredProperties(workflow2, allow) {\n const list5 = [];\n const perStep = /* @__PURE__ */ new Map();\n for (const { step: step3, definition } of properties2(workflow2)) {\n const { key: key2 } = definition;\n if (!keyPattern.test(key2) || reservedVideoPropertyKeys.has(key2) || allow !== "all" && !allow.includes(`${step3}.${key2}`)) continue;\n if ((perStep.get(step3) ?? 0) >= 12 || !perStep.has(step3) && perStep.size >= 12) continue;\n let offered = null;\n if (definition.type === "boolean") offered = { step: step3, key: key2, type: "boolean", fallback: typeof definition.default === "boolean" ? definition.default : null };\n else if (definition.type === "enum") {\n const values = [...new Set(definition.constraints.values.filter(scalar2))].slice(0, 32);\n if (values.length) offered = { step: step3, key: key2, type: "enum", values, fallback: scalar2(definition.default) && values.includes(definition.default) ? definition.default : null };\n } else if (definition.type === "integer" || definition.type === "number") {\n const { minimum: min, maximum: max, step: size } = definition.constraints;\n if (typeof min === "number" && typeof max === "number" && min < max) {\n const value = definition.default;\n offered = {\n step: step3,\n key: key2,\n type: definition.type,\n min,\n max,\n step_size: typeof size === "number" && size > 0 ? size : null,\n fallback: typeof value === "number" && value >= min && value <= max ? value : min\n };\n }\n }\n if (!offered) continue;\n perStep.set(step3, (perStep.get(step3) ?? 0) + 1);\n list5.push(offered);\n }\n return list5;\n}\nfunction admitsProperty(property, value) {\n if (property.type === "boolean") return typeof value === "boolean";\n if (property.type === "enum") return scalar2(value) && property.values.includes(value);\n return typeof value === "number" && value >= property.min && value <= property.max && (property.type === "number" || Number.isInteger(value));\n}\nvar isPropertyStep = (value) => typeof value === "string" && stepPattern.test(value);\nvar isPropertyKey = (value) => typeof value === "string" && keyPattern.test(value);\nvar isPropertyScalar = scalar2;\nvar isRouteModel = (value) => typeof value === "string" && routeName.test(value);\n\n// src/video-settings-media.ts\nvar roleLabel = (text6, role) => text6.roles[role] ?? role;\nvar fileName = (file) => (file.name || "media").slice(0, 120);\nfunction mediaView(doc, text6, options, actions) {\n const root = element(doc, "div", cls("media"));\n const voiceSlot = element(doc, "div", cls("voice"));\n const pending3 = [];\n const madeUrls = /* @__PURE__ */ new Set();\n let disposed = false;\n let last = null;\n const rerender = () => {\n if (last && !disposed) render(last.workflow, last.plan, last.references, last.voiceField);\n };\n function upload2(role, files, send3, image) {\n for (const file of files) {\n const key2 = uid("nocha-video-upload");\n const previewUrl = image && typeof URL !== "undefined" && typeof URL.createObjectURL === "function" ? URL.createObjectURL(file) : null;\n if (previewUrl) madeUrls.add(previewUrl);\n const entry = { key: key2, role, name: fileName(file), previewUrl, failed: false };\n pending3.push(entry);\n send3(file).then((result2) => {\n const index = pending3.indexOf(entry);\n if (index >= 0) pending3.splice(index, 1);\n if (disposed || !result2 || typeof result2.assetId !== "string" || !result2.assetId) throw new Error("no asset");\n actions.changed([...actions.held(), { assetId: result2.assetId, role, name: entry.name, ...previewUrl ? { previewUrl } : {} }]);\n }).catch(() => {\n if (disposed) return;\n entry.failed = true;\n if (!pending3.includes(entry)) pending3.push(entry);\n rerender();\n });\n }\n rerender();\n }\n function picker(accept, multiple, onFiles) {\n const input4 = element(doc, "input", cls("file"), { type: "file", accept: accept.join(","), multiple, tabindex: "-1", "aria-hidden": "true" });\n input4.addEventListener("change", () => {\n const files = Array.from(input4.files ?? []);\n input4.value = "";\n if (files.length) onFiles(files);\n });\n return input4;\n }\n function remove2(reference2) {\n if (reference2.previewUrl && madeUrls.has(reference2.previewUrl)) {\n URL.revokeObjectURL(reference2.previewUrl);\n madeUrls.delete(reference2.previewUrl);\n }\n actions.changed(actions.held().filter((item) => item !== reference2));\n }\n function move(reference2, delta) {\n const held = [...actions.held()];\n const same = held.map((item, index) => ({ item, index })).filter((entry) => entry.item.role === reference2.role);\n const at = same.findIndex((entry) => entry.item === reference2);\n const other = same[at + delta];\n const self = same[at];\n if (!other || !self) return;\n held[self.index] = other.item;\n held[other.index] = self.item;\n actions.changed(held);\n }\n function tools(reference2, index, count2, name) {\n const tool = (kind, label, disabled, run3) => {\n const button = element(\n doc,\n "button",\n cls("tool"),\n { type: "button", "aria-label": label, title: label, disabled, "data-focus": `${kind}:${reference2.assetId}` },\n icon(doc, kind)\n );\n button.addEventListener("click", run3);\n return button;\n };\n return element(\n doc,\n "div",\n cls("tools"),\n {},\n tool("before", fill(text6.moveBefore, { name }), index === 0, () => move(reference2, -1)),\n tool("close", fill(text6.remove, { name }), false, () => remove2(reference2)),\n tool("after", fill(text6.moveAfter, { name }), index >= count2 - 1, () => move(reference2, 1))\n );\n }\n function head(label, count2, max, min) {\n return element(\n doc,\n "div",\n cls("head"),\n {},\n element(doc, "span", cls("label"), {}, label),\n max > 1 && element(doc, "span", cls("count"), {}, `${count2}/${max}`),\n min > count2 && element(doc, "span", cls("required"), {}, text6.required)\n );\n }\n function failedLine(role) {\n return pending3.filter((item) => item.role === role && item.failed).map((item) => {\n const dismiss = element(doc, "button", cls("tool"), { type: "button", "aria-label": fill(text6.remove, { name: item.name }) }, icon(doc, "close"));\n dismiss.addEventListener("click", () => {\n pending3.splice(pending3.indexOf(item), 1);\n rerender();\n });\n return element(doc, "div", cls("sound"), {}, element(doc, "span", `${cls("sound-name")} ${cls("error")}`, {}, `${text6.uploadFailed} \\xB7 ${item.name}`), dismiss);\n });\n }\n function visualBlock(workflow2, plan, slot, references) {\n const upload_ = options.references ? options.references.upload : null;\n if (!upload_) return null;\n const mine = references.filter((item) => item.role === slot.role);\n const waiting = pending3.filter((item) => item.role === slot.role && !item.failed);\n const visual = references.filter((item) => item.role !== "soundtrack" && item.role !== "voice").length + pending3.filter((item) => !item.failed && item.role !== "soundtrack" && item.role !== "voice").length;\n const room = Math.max(0, Math.min(slot.max - mine.length - waiting.length, plan.pool - visual));\n const label = roleLabel(text6, slot.role);\n const input4 = picker(mediaTypes3(workflow2, slot.media), room > 1, (files) => upload2(slot.role, files.slice(0, room), (file) => upload_(file, slot.role), slot.media === "image"));\n const empty = !mine.length && !waiting.length;\n const add = element(\n doc,\n "button",\n `${cls("add")}${empty ? ` ${cls("add--line")}` : ""}`,\n { type: "button", disabled: room < 1, "data-focus": `add:${slot.role}`, "aria-label": `${text6.add} \\xB7 ${label}` },\n icon(doc, "plus"),\n element(doc, "span", "", {}, text6.add)\n );\n add.addEventListener("click", () => input4.click());\n const tiles = element(\n doc,\n "ul",\n cls("tiles"),\n { "aria-label": label },\n ...mine.map((reference2, index) => {\n const name = reference2.name || label;\n const thumb = reference2.previewUrl && slot.media === "image" ? element(doc, "img", cls("thumb"), { src: reference2.previewUrl, alt: name, draggable: "false" }) : element(doc, "span", `${cls("thumb")} ${cls("thumb--empty")}`, {}, name);\n return element(doc, "li", cls("tile"), {}, thumb, tools(reference2, index, mine.length, name));\n }),\n ...waiting.map((item) => element(\n doc,\n "li",\n `${cls("tile")} ${cls("tile--pending")}`,\n { "aria-busy": "true" },\n item.previewUrl ? element(doc, "img", cls("thumb"), { src: item.previewUrl, alt: item.name }) : element(doc, "span", `${cls("thumb")} ${cls("thumb--empty")}`, {}, item.name),\n element(doc, "span", `${cls("thumb")} ${cls("thumb--empty")}`, {}, text6.uploading)\n )),\n empty || room < 1 ? null : element(doc, "li", "", {}, add)\n );\n const generic = slot.role === "character" || slot.role === "location" || slot.role === "style";\n return element(\n doc,\n "section",\n cls("block"),\n {},\n head(label, mine.length, generic ? 0 : slot.max, slot.min),\n empty ? add : tiles,\n ...failedLine(slot.role),\n input4\n );\n }\n function soundRows(references, role) {\n const mine = references.filter((item) => item.role === role && !item.track);\n const waiting = pending3.filter((item) => item.role === role && !item.failed);\n return element(\n doc,\n "ul",\n cls("sounds"),\n { hidden: !mine.length && !waiting.length },\n ...mine.map((reference2, index) => {\n const name = reference2.name || roleLabel(text6, role);\n return element(doc, "li", cls("sound"), {}, element(doc, "span", cls("sound-name"), {}, name), ...Array.from(tools(reference2, index, mine.length, name).childNodes));\n }),\n ...waiting.map((item) => element(\n doc,\n "li",\n `${cls("sound")} ${cls("tile--pending")}`,\n { "aria-busy": "true" },\n element(doc, "span", cls("sound-name"), {}, `${text6.uploading} ${item.name}`)\n ))\n );\n }\n function importButton(role, room, label, send3) {\n const input4 = picker(["audio/mpeg", "audio/wav", ".mp3", ".wav"], room > 1, (files) => upload2(role, files.slice(0, room), send3, false));\n const button = element(\n doc,\n "button",\n `${cls("add")} ${cls("add--line")}`,\n { type: "button", disabled: room < 1, "data-focus": `import:${role}` },\n icon(doc, "plus"),\n element(doc, "span", "", {}, label)\n );\n button.addEventListener("click", () => input4.click());\n return [button, input4];\n }\n function musicBlock(workflow2, plan, references) {\n const music = options.music;\n if (!music || plan.music < 1) return null;\n const mine = references.filter((item) => item.role === "soundtrack");\n const waiting = pending3.filter((item) => item.role === "soundtrack" && !item.failed).length;\n const room = plan.music - mine.length - waiting;\n const tracks = (music.tracks ?? []).slice(0, 24);\n const chips = tracks.length ? element(\n doc,\n "div",\n cls("chips"),\n { role: "group", "aria-label": text6.music },\n ...tracks.map((track) => {\n const on = mine.some((item) => item.track === track.id);\n const chip = element(\n doc,\n "button",\n `${cls("segment")} ${cls("segment--word")}`,\n { type: "button", "aria-pressed": String(on), "aria-checked": String(on), "data-focus": `track:${track.id}` },\n track.label\n );\n chip.addEventListener("click", () => {\n const held = actions.held();\n if (on) actions.changed(held.filter((item) => !(item.role === "soundtrack" && item.track === track.id)));\n else {\n const kept = plan.music <= 1 ? held.filter((item) => item.role !== "soundtrack") : held;\n actions.changed([...kept, { assetId: track.assetId, role: "soundtrack", name: track.label.slice(0, 120), track: track.id }]);\n }\n });\n return chip;\n })\n ) : null;\n const min = roleOf(workflow2, "soundtrack")?.min ?? 0;\n return element(\n doc,\n "section",\n cls("block"),\n {},\n head(text6.music, mine.length, plan.music, min),\n chips,\n soundRows(references, "soundtrack"),\n ...failedLine("soundtrack"),\n ...music.import && music.upload ? importButton("soundtrack", room, text6.importMusic, music.upload) : []\n );\n }\n function voiceBlock(workflow2, plan, references, voiceField) {\n const voice = options.voice;\n if (!voice || !voiceField && plan.voices < 1) return null;\n const mine = references.filter((item) => item.role === "voice");\n const waiting = pending3.filter((item) => item.role === "voice" && !item.failed).length;\n const min = roleOf(workflow2, "voice")?.min ?? 0;\n return element(\n doc,\n "section",\n cls("block"),\n {},\n head(text6.voice, mine.length, plan.voices, plan.voices > 0 ? min : 0),\n voiceField ? voiceSlot : null,\n soundRows(references, "voice"),\n ...failedLine("voice"),\n ...plan.voices > 0 && voice.upload ? importButton("voice", plan.voices - mine.length - waiting, text6.importVoice, voice.upload) : []\n );\n }\n function render(workflow2, plan, references, voiceField) {\n last = { workflow: workflow2, plan, references, voiceField };\n const blocks = [\n ...plan.slots.map((slot) => visualBlock(workflow2, plan, slot, references)),\n musicBlock(workflow2, plan, references),\n voiceBlock(workflow2, plan, references, voiceField)\n ].filter((block) => block !== null);\n const focused = root.getRootNode().activeElement;\n const key2 = focused && root.contains(focused) ? focused.dataset.focus : void 0;\n root.replaceChildren(...blocks);\n root.hidden = !blocks.length;\n if (key2) {\n const again = Array.from(root.querySelectorAll("[data-focus]")).find((node) => node.dataset.focus === key2 && !node.disabled);\n (again ?? root.querySelector(`[data-focus^="add:"], [data-focus^="import:"]`))?.focus();\n }\n }\n return {\n element: root,\n voiceSlot,\n render,\n dispose() {\n disposed = true;\n for (const url of madeUrls) URL.revokeObjectURL(url);\n madeUrls.clear();\n }\n };\n}\n\n// src/video-presentation.ts\nvar groups2 = [\n { id: "story", title: { fr: "R\\xE9cit", en: "Story" }, setting: { fr: "\\xC9criture", en: "Writing" }, members: [\n { id: "film-narratif-libre", label: { fr: "Mise en sc\\xE8ne libre", en: "Free direction" } },\n { id: "film-narratif-paragraphes", label: { fr: "En paragraphes", en: "In paragraphs" } },\n { id: "film-narratif-frames-enchainees", label: { fr: "Images encha\\xEEn\\xE9es", en: "Chained frames" } },\n { id: "film-narratif-voix-ia", label: { fr: "Dialogues en voix IA", en: "AI voice dialogue" } }\n ] },\n { id: "storyboard", title: { fr: "Storyboard", en: "Storyboard" }, setting: { fr: "Voix", en: "Voices" }, members: [\n { id: "film-narratif-storyboard", label: { fr: "Sans voix IA", en: "No AI voices" } },\n { id: "film-narratif-storyboard-voix-ia", label: { fr: "Voix IA", en: "AI voices" } }\n ] },\n { id: "start-end", title: { fr: "D\\xE9but \\u2192 fin", en: "Start \\u2192 end" }, setting: { fr: "Images", en: "Images" }, members: [\n { id: "clip-debut-fin", label: { fr: "D\\xE9but et fin seules", en: "Start and end only" } },\n { id: "clip-debut-fin-references", label: { fr: "Avec r\\xE9f\\xE9rences", en: "With references" } }\n ] },\n { id: "music-voice", title: { fr: "Musique et voix", en: "Music and voice" }, setting: { fr: "Son", en: "Sound" }, members: [\n { id: "film-narratif-musique-voix", label: { fr: "Voix en synchro labiale", en: "Lip-synced voice" } },\n { id: "film-narratif-musique-voix-audio", label: { fr: "Son en r\\xE9f\\xE9rence", en: "Sound as reference" } }\n ] }\n];\nvar titles = {\n "film-classique": { fr: "Classique", en: "Classic" },\n "image-loop": { fr: "Boucle d\\u2019image", en: "Image loop" },\n "analyse-video": { fr: "Analyse vid\\xE9o", en: "Video analysis" },\n "film-narratif-paragraphes": { fr: "R\\xE9cit en paragraphes", en: "Story in paragraphs" },\n "film-narratif-libre": { fr: "R\\xE9cit libre", en: "Free story" },\n "film-narratif-storyboard": { fr: "Storyboard", en: "Storyboard" },\n "film-narratif-musique-voix": { fr: "Musique et voix", en: "Music and voice" },\n "film-narratif-musique-voix-audio": { fr: "Musique et voix", en: "Music and voice" },\n "clip-debut-fin": { fr: "D\\xE9but \\u2192 fin", en: "Start \\u2192 end" },\n "clip-debut-fin-references": { fr: "D\\xE9but \\u2192 fin", en: "Start \\u2192 end" },\n "edition-video": { fr: "\\xC9dition vid\\xE9o", en: "Video edit" },\n "clip-musical": { fr: "Clip musical", en: "Music clip" },\n "film-storyboard-quatre-plans": { fr: "Classique en 4 plans", en: "Classic in 4 shots" },\n "film-narratif-frames-enchainees": { fr: "Images encha\\xEEn\\xE9es", en: "Chained frames" },\n "film-narratif-voix-ia": { fr: "R\\xE9cit en voix IA", en: "Story with AI voices" },\n "film-narratif-voix-ia-live": { fr: "Voix IA en direct", en: "Live AI voices" },\n "film-narratif-voix-ia-multilingues": { fr: "Voix IA multilingues", en: "Multilingual AI voices" },\n "film-narratif-voix-ia-bande-son": { fr: "Voix IA en bande son", en: "AI voices as a track" },\n "film-narratif-voix-ia-bande-son-sync": { fr: "Voix IA en synchro", en: "AI voices in sync" },\n "film-narratif-storyboard-voix-ia": { fr: "Storyboard en voix IA", en: "Storyboard with AI voices" },\n "film-narratif-22s": { fr: "R\\xE9cit de 22 s", en: "22 s story" },\n "film-narratif-30s": { fr: "R\\xE9cit de 12 ou 30 s", en: "12 or 30 s story" },\n "film-narratif-60s": { fr: "R\\xE9cit de 60 s", en: "60 s story" },\n "passage-4k": { fr: "Passage 4K", en: "4K pass" }\n};\nvar descriptions = {\n "film-classique": { fr: "Un film complet depuis ton brief et tes images.", en: "A complete film from your brief and images." },\n "image-loop": { fr: "Une boucle muette et sans raccord depuis une image.", en: "A silent seamless loop from one image." },\n "analyse-video": { fr: "Lit une vid\\xE9o et en d\\xE9crit les plans.", en: "Reads a video and describes its shots." },\n "film-narratif-paragraphes": { fr: "Un plan par paragraphe de ton r\\xE9cit.", en: "One shot per paragraph of your story." },\n "film-narratif-libre": { fr: "Ton r\\xE9cit mis en sc\\xE8ne plan par plan.", en: "Your story staged shot by shot." },\n "film-narratif-frames-enchainees": { fr: "Chaque plan part de la derni\\xE8re image du pr\\xE9c\\xE9dent.", en: "Each shot starts from the last frame of the one before." },\n "film-narratif-voix-ia": { fr: "Ton r\\xE9cit avec des dialogues dits par des voix IA.", en: "Your story with dialogue spoken by AI voices." },\n "film-narratif-storyboard": { fr: "Des planches dessin\\xE9es, puis le film.", en: "Drawn boards first, then the film." },\n "film-narratif-storyboard-voix-ia": { fr: "Des planches dessin\\xE9es, puis le film avec voix IA.", en: "Drawn boards first, then the film with AI voices." },\n "film-narratif-musique-voix": { fr: "Ta musique et ta voix, les visages en synchro.", en: "Your music and voice, faces in sync." },\n "film-narratif-musique-voix-audio": { fr: "Ta musique et ta voix guident les images.", en: "Your music and voice guide the pictures." },\n "clip-debut-fin": { fr: "Un plan d\\u2019une image de d\\xE9but \\xE0 une image de fin.", en: "A shot from a start frame to an end frame." },\n "clip-debut-fin-references": { fr: "D\\xE9but \\u2192 fin, guid\\xE9 par tes r\\xE9f\\xE9rences.", en: "Start \\u2192 end, guided by your references." },\n "edition-video": { fr: "Retouche une vid\\xE9o de tes rushes.", en: "Reworks a video from your rushes." },\n "clip-musical": { fr: "Ta chanson telle quelle, mise en images.", en: "Your song as is, set to pictures." },\n "film-storyboard-quatre-plans": { fr: "Un film classique d\\xE9coup\\xE9 en quatre plans.", en: "A classic film cut into four shots." }\n};\nvar badgeWords = {\n source_video: { fr: "Vid\\xE9o source", en: "Source video" },\n start_frame: { fr: "Image de d\\xE9but", en: "Start frame" },\n end_frame: { fr: "Image de fin", en: "End frame" },\n soundtrack: { fr: "Musique", en: "Music" },\n voice: { fr: "Voix", en: "Voice" },\n saved: { fr: "Format enregistr\\xE9", en: "Saved format" }\n};\nvar unavailableWords = {\n interactive: { fr: "Demande une pr\\xE9sence pendant le tournage", en: "Needs someone present while it runs" },\n providers: { fr: "Studio indisponible pour le moment", en: "Studio unavailable for now" },\n modules: { fr: "\\xC9tape indisponible pour le moment", en: "A step is unavailable for now" },\n render_target: { fr: "Rendu indisponible pour le moment", en: "Rendering unavailable for now" },\n base: { fr: "Son format d\\u2019origine n\\u2019existe plus", en: "Its base format is gone" },\n unavailable: { fr: "Indisponible", en: "Unavailable" }\n};\nvar savedTitle = { fr: "Format enregistr\\xE9", en: "Saved format" };\nvar brands = /\\b(tripirl|watchirl|nocha|kling|veo|sora|runway|seedance|minimax|hailuo|luma|pika|wan|eleven ?labs|openai|gemini|google)\\b/iu;\nvar unbranded = (name) => capitalized(name.replace(new RegExp(brands.source, "giu"), " ").replace(/\\s+/gu, " ").replace(/^[\\s\\-\u2013\u2014|:\xB7,]+|[\\s\\-\u2013\u2014|:\xB7,]+$/gu, "").slice(0, 80));\nvar modelNames = {\n "seedance-2": "Seedance 2",\n "seedance-2.5": "Seedance 2.5",\n "wan-3": "Wan 3.0",\n "minimax-h3": "MiniMax H3"\n};\nfunction shortVideoDescription(description) {\n const first = description.replace(/\\s+/gu, " ").trim().split(/(?<=[.!?])\\s/u)[0] ?? "";\n const characters = [...first];\n return characters.length <= 70 ? first : `${characters.slice(0, 69).join("").trimEnd()}\\u2026`;\n}\nvar groupOf = (id) => groups2.find((group) => group.members.some((member2) => member2.id === id));\nfunction videoWorkflowPresentation(workflow2, locale) {\n const lang = uiLocale(locale);\n const saved = workflow2.origin === "saved";\n const known = titles[workflow2.id];\n const name = workflow2.name.trim();\n const title = known ? known[lang] : saved ? name && !brands.test(name) ? name.slice(0, 80) : savedTitle[lang] : [unbranded(name), unbranded(listedLabel(workflow2.id))].find((words2) => /\\p{L}{2}/u.test(words2)) ?? listedLabel(workflow2.id).slice(0, 80);\n const line4 = descriptions[workflow2.id];\n const description = line4 ? line4[lang] : (saved || lang === "en") && !brands.test(workflow2.description) ? shortVideoDescription(workflow2.description) : "";\n const group = saved ? void 0 : groupOf(workflow2.id);\n const badges2 = [];\n for (const kind of ["source_video", "start_frame", "end_frame", "soundtrack", "voice"]) {\n if (roleMax(workflow2, kind) > 0) badges2.push({ kind, label: badgeWords[kind][lang] });\n }\n if (saved) badges2.push({ kind: "saved", label: badgeWords.saved[lang] });\n const durations = videoWorkflowDurations(workflow2);\n const interactive = workflow2.interaction !== null && workflow2.interaction !== "none";\n const available = workflow2.availability.status === "available" && !interactive;\n const reason2 = workflow2.availability.status === "unavailable" ? workflow2.availability.reason ?? "unavailable" : interactive ? "interactive" : null;\n return {\n id: workflow2.id,\n title,\n description,\n group: group ? { id: group.id, title: group.title[lang], setting: group.setting[lang] } : null,\n member: group?.members.find((member2) => member2.id === workflow2.id)?.label[lang] ?? null,\n badges: badges2,\n durations,\n durationRange: durationRangeText(durations, workflow2.duration_seconds.allowed !== null),\n available,\n unavailableReason: available ? null : unavailableWords[reason2 ?? "unavailable"][lang]\n };\n}\nvar videoWorkflowGroupOrder = (id) => {\n const group = groupOf(id);\n return group ? groups2.indexOf(group) * 10 + group.members.findIndex((member2) => member2.id === id) : -1;\n};\nvar routeKey = (model) => model.toLowerCase().replace(/^.*\\//u, "").replace(/[\\s_]+/gu, "-").replace(/([a-z]{2,})(?=\\d)/gu, "$1-").replace(/(\\d)\\.0(?!\\d)/gu, "$1");\nfunction videoRouteLabel(route) {\n const model = typeof route === "string" ? route : route.model;\n const key2 = `-${routeKey(model)}-`;\n const known = Object.entries(modelNames).find(([name]) => key2.includes(`-${name}-`));\n if (known) return known[1];\n const words2 = model.replace(/[-_\\s]+/gu, " ").trim();\n return words2.charAt(0).toUpperCase() + words2.slice(1);\n}\nvar propertyWords = {\n drawingStyle: { fr: "Style des planches", en: "Board style" },\n colorMode: { fr: "Couleur", en: "Colour" },\n renderStyle: { fr: "Trait", en: "Line" },\n quality: { fr: "Finition", en: "Finish" },\n sheetSize: { fr: "Taille des planches", en: "Board size" },\n shotAspect: { fr: "Cadre des cases", en: "Panel frame" },\n groupedGenerations: { fr: "Planches group\\xE9es", en: "Grouped boards" },\n drawShotDensity: { fr: "Plans par planche", en: "Shots per board" },\n filmForm: { fr: "Montage", en: "Editing" },\n filmRhythm: { fr: "Rythme", en: "Rhythm" },\n clipGranularity: { fr: "Dur\\xE9e des clips", en: "Clip length" },\n sequenceTransitionMode: { fr: "Passage entre clips", en: "Clip handoff" },\n cameraFlowMode: { fr: "Cam\\xE9ra", en: "Camera" },\n cameraPacingProfile: { fr: "Allure cam\\xE9ra", en: "Camera pace" },\n maximumTargets: { fr: "R\\xE9f\\xE9rences pr\\xE9par\\xE9es", en: "Prepared references" },\n staging: { fr: "Mise en place", en: "Staging" },\n profile: { fr: "Style des consignes", en: "Prompt style" },\n storyboardUse: { fr: "Storyboard envoy\\xE9", en: "Storyboard sent" },\n exposeTimings: { fr: "Minutage dans les consignes", en: "Timings in prompts" },\n modelQuality: { fr: "Rendu", en: "Render" },\n motion: { fr: "Mouvement", en: "Motion" },\n audio: { fr: "Son", en: "Sound" },\n voiceSource: { fr: "Source des voix", en: "Voice source" },\n track: { fr: "Prises", en: "Takes" },\n transport: { fr: "Envoi des voix", en: "Voice delivery" },\n lipSync: { fr: "Synchro labiale", en: "Lip sync" },\n direction: { fr: "Jeu des voix", en: "Voice acting" },\n soundEffects: { fr: "Bruitages", en: "Sound effects" },\n soundtrackStartSec: { fr: "D\\xE9part de la musique (s)", en: "Music start (s)" },\n blackVideoMusicPercent: { fr: "Musique sous la voix guide (%)", en: "Music under the guide voice (%)" },\n exportMusicPercent: { fr: "Musique \\xE0 l\\u2019export (%)", en: "Music in the export (%)" },\n exportSound: { fr: "Son \\xE0 l\\u2019export", en: "Export sound" }\n};\nvar valueWords = {\n colorSketch: { fr: "Croquis couleur", en: "Colour sketch" },\n pencil: { fr: "Crayon", en: "Pencil" },\n blackWhite: { fr: "Noir et blanc", en: "Black and white" },\n color: { fr: "Couleur", en: "Colour" },\n sketch: { fr: "Esquisse", en: "Sketch" },\n cleanLine: { fr: "Trait net", en: "Clean line" },\n animaticMarker: { fr: "Feutre", en: "Marker" },\n finalVisual: { fr: "Rendu final", en: "Final look" },\n low: { fr: "Basse", en: "Low" },\n medium: { fr: "Moyenne", en: "Medium" },\n high: { fr: "Haute", en: "High" },\n small: { fr: "Petite", en: "Small" },\n large: { fr: "Grande", en: "Large" },\n square: { fr: "Carr\\xE9", en: "Square" },\n video: { fr: "Format du film", en: "Film format" },\n faithful: { fr: "Fid\\xE8le", en: "Faithful" },\n varied: { fr: "Libre", en: "Varied" },\n source: { fr: "D\\u2019origine", en: "Original" },\n generated: { fr: "G\\xE9n\\xE9r\\xE9", en: "Generated" },\n adaptive: { fr: "Adaptatif", en: "Adaptive" },\n natural: { fr: "Naturel", en: "Natural" },\n fullTake: { fr: "Plan unique", en: "One take" },\n off: { fr: "Non", en: "Off" },\n standard: { fr: "Standard", en: "Standard" },\n fast: { fr: "Rapide", en: "Fast" },\n mini: { fr: "L\\xE9ger", en: "Light" }\n};\nvar keyValueWords = {\n filmForm: { continuous: { fr: "Continu", en: "Continuous" }, cut: { fr: "Coup\\xE9", en: "Cut" } },\n filmRhythm: { tight: { fr: "Serr\\xE9", en: "Tight" }, longTakes: { fr: "Plans longs", en: "Long takes" } },\n clipGranularity: { dense: { fr: "6 s", en: "6 s" }, detailed: { fr: "10 s", en: "10 s" }, economy: { fr: "16 s", en: "16 s" } },\n sequenceTransitionMode: {\n continuous: { fr: "Relais doux", en: "Soft handoff" },\n reuse: { fr: "Image reprise", en: "Exact reuse" },\n cut: { fr: "Image neuve", en: "Fresh frame" }\n },\n cameraFlowMode: { single: { fr: "Cam\\xE9ra unique", en: "Single camera" }, coverage: { fr: "Couverture", en: "Coverage" } },\n cameraPacingProfile: {\n flowing: { fr: "Fluide", en: "Flowing" },\n kinetic: { fr: "Nerveuse", en: "Kinetic" },\n dreamy: { fr: "R\\xEAveuse", en: "Dreamy" },\n held: { fr: "Pos\\xE9e", en: "Held" }\n },\n drawShotDensity: { compact: { fr: "Peu", en: "Few" }, balanced: { fr: "\\xC9quilibr\\xE9", en: "Balanced" }, detailed: { fr: "Beaucoup", en: "Many" } },\n profile: { productionDirector: { fr: "D\\xE9taill\\xE9es", en: "Detailed" }, compact: { fr: "Courtes", en: "Short" } },\n voiceSource: { ai: { fr: "Casting IA", en: "AI casting" }, microphone: { fr: "Micro", en: "Microphone" } },\n track: { clip: { fr: "Une par clip", en: "One per clip" }, film: { fr: "Bande unique", en: "Single track" } },\n transport: { blackVideo: { fr: "Vid\\xE9o noire", en: "Black video" }, audio: { fr: "R\\xE9f\\xE9rence audio", en: "Audio reference" } },\n storyboardUse: {\n sheetAsShotSequence: { fr: "Planche enti\\xE8re", en: "Whole board" },\n framesAsShotSequence: { fr: "Cases une \\xE0 une", en: "Panel by panel" },\n openingBoundary: { fr: "Premi\\xE8re case", en: "First panel" }\n },\n exportSound: { video: { fr: "Son des clips", en: "Clip sound" }, provided: { fr: "Voix et musique fournies", en: "Provided voice and music" } },\n lipSync: { strict: { fr: "Stricte", en: "Strict" } },\n direction: { off: { fr: "Neutre", en: "Neutral" }, subtle: { fr: "Subtil", en: "Subtle" }, expressive: { fr: "Expressif", en: "Expressive" } }\n};\nvar units = { sec: "(s)", secs: "(s)", seconds: "(s)", ms: "(ms)", percent: "(%)", pct: "(%)" };\nfunction humanized(key2) {\n const words2 = key2.replace(/[_-]/gu, " ").replace(/([a-z0-9])([A-Z])/gu, "$1 $2").toLowerCase().trim().split(/\\s+/u);\n const unit = words2.length > 1 ? units[words2[words2.length - 1] ?? ""] : void 0;\n const text6 = (unit ? [...words2.slice(0, -1), unit] : words2).join(" ");\n return text6.charAt(0).toUpperCase() + text6.slice(1);\n}\nfunction videoPropertyLabel(key2, locale) {\n return propertyWords[key2]?.[uiLocale(locale)] ?? humanized(key2);\n}\nfunction videoPropertyValueLabel(key2, value, locale) {\n const lang = uiLocale(locale);\n if (typeof value === "boolean") return value ? lang === "fr" ? "Oui" : "Yes" : lang === "fr" ? "Non" : "No";\n const words2 = keyValueWords[key2]?.[String(value)] ?? valueWords[String(value)];\n return words2 ? words2[lang] : typeof value === "string" ? humanized(value) : String(value);\n}\nvar stepWords = {\n sourceAnalyses: { fr: "Analyse des sources", en: "Source analysis" },\n projectAnalysis: { fr: "Analyse du projet", en: "Project analysis" },\n story: { fr: "Histoire", en: "Story" },\n worldReferences: { fr: "R\\xE9f\\xE9rences du monde", en: "World references" },\n locationBible: { fr: "R\\xE9f\\xE9rences du monde", en: "World references" },\n shotPlan: { fr: "D\\xE9coupage", en: "Shot plan" },\n dialogueAudio: { fr: "Voix des dialogues", en: "Dialogue audio" },\n storyboardSheets: { fr: "Storyboards", en: "Storyboards" },\n clipPrompts: { fr: "Prompts des clips", en: "Clip prompts" },\n clips: { fr: "Clips", en: "Clips" },\n filmExport: { fr: "Film", en: "Film" }\n};\nvar stageWords = {\n preparing: { fr: "Pr\\xE9paration", en: "Preparing" },\n planning: { fr: "\\xC9criture", en: "Planning" },\n generating_speech: { fr: "Voix", en: "Speech" },\n generating_media: { fr: "Images et clips", en: "Images and clips" },\n assembling: { fr: "Montage", en: "Assembling" }\n};\nfunction videoStepLabel(id, locale) {\n return stepWords[id]?.[uiLocale(locale)] ?? humanized(id);\n}\nfunction videoStageLabel(stage, locale) {\n return stageWords[stage]?.[uiLocale(locale)] ?? humanized(stage);\n}\n\n// src/video-settings-state.ts\nvar aspects = ["9:16", "16:9", "1:1"];\nvar resolutions3 = ["720p", "1080p"];\nvar speeches = ["none", "auto", "required"];\nvar audioRoles = ["soundtrack", "voice"];\nvar within = (list5, allowed) => allowed ? list5.filter((item) => allowed.includes(item)) : [...list5];\nfunction planOf(workflow2, options) {\n const all = videoWorkflowDurations(workflow2);\n const bounds = options.duration || void 0;\n const narrowed = bounds ? all.filter((value) => (bounds.min === void 0 || value >= bounds.min) && (bounds.max === void 0 || value <= bounds.max) && (!bounds.allowed || bounds.allowed.includes(value))) : all;\n const model = options.model ? modelOffer(workflow2) : null;\n const allowedModels = options.model ? options.model.allowed : void 0;\n const routes = model ? within(model.routes.map((route) => route.model), allowedModels) : [];\n const references = options.references || void 0;\n const slots = references ? referenceSlots(workflow2).filter((slot) => slot.media !== "audio" && (!references.roles || references.roles.includes(slot.role))) : [];\n return {\n durations: narrowed.length ? narrowed : all,\n aspects: options.aspectRatio ? within(workflow2.aspect_ratios, options.aspectRatio.allowed) : [],\n resolutions: options.resolution ? within(workflow2.output_resolutions, options.resolution.allowed) : [],\n locales: options.locale ? within(workflow2.locales, options.locale.allowed) : [],\n model: model && routes.length ? { ...model, routes: model.routes.filter((route) => routes.includes(route.model)) } : null,\n quality: options.modelQuality ? qualityOffer(workflow2) : null,\n world: options.autoReference ? worldOffer(workflow2) : null,\n upscale: options.upscale4k ? upscaleOffer(workflow2) : null,\n properties: options.properties ? offeredProperties(workflow2, options.properties.allow) : [],\n slots,\n music: options.music ? roleMax(workflow2, "soundtrack") : 0,\n voices: options.voice && options.voice.upload ? roleMax(workflow2, "voice") : 0,\n pool: Math.min(visualCapacity(workflow2), references?.max ?? 20)\n };\n}\nvar pick3 = (list5, ...wanted) => {\n for (const value of wanted) if (value !== void 0 && value !== null && list5.includes(value)) return value;\n return list5[0];\n};\nfunction choiceOf(list5, fallback, ...wanted) {\n for (const value of wanted) if (value !== void 0 && value !== null && list5.includes(value)) return value;\n return fallback === null || list5.includes(fallback) ? fallback : list5[0] ?? null;\n}\nfunction resolve(workflow2, plan, options, wanted, held, ui) {\n const all = videoWorkflowDurations(workflow2);\n const duration = options.duration ? options.duration.default : workflow2.default_for_durations_seconds.find((value) => all.includes(value)) ?? all[0] ?? 10;\n const durationSeconds = nearest(plan.durations, wanted.durationSeconds ?? duration) ?? wanted.durationSeconds ?? duration;\n const speechDefault = options.speech ? options.speech.default : void 0;\n const speech2 = videoSpeechFor(workflow2, durationSeconds, wanted.speech ?? speechDefault) ?? "none";\n const listedAspects = plan.aspects.length ? plan.aspects : workflow2.aspect_ratios;\n const aspectRatio = pick3(listedAspects, wanted.aspectRatio, options.aspectRatio ? options.aspectRatio.default : void 0, "9:16") ?? "9:16";\n const listedLocales = plan.locales.length ? plan.locales : workflow2.locales;\n const locale = pick3(listedLocales, wanted.locale, options.locale ? options.locale.default : void 0, ui === "fr" ? "fr-FR" : "en-US") ?? "fr-FR";\n const listedResolutions = plan.resolutions.length ? plan.resolutions : workflow2.output_resolutions;\n const resolution = pick3(listedResolutions, wanted.resolution, options.resolution ? options.resolution.default : void 0, "720p") ?? "720p";\n const upscale4k = plan.upscale ? wanted.upscale4k ?? (options.upscale4k ? options.upscale4k.default : plan.upscale.fallback) : false;\n const model = plan.model ? choiceOf(\n plan.model.routes.map((route) => route.model),\n plan.model.fallback,\n wanted.model,\n options.model ? options.model.default : void 0\n ) : null;\n const modelQuality = plan.quality ? choiceOf(\n plan.quality.values,\n plan.quality.fallback,\n wanted.modelQuality,\n options.modelQuality ? options.modelQuality.default : void 0\n ) : null;\n const autoReference = plan.world ? wanted.autoReference ?? (options.autoReference ? options.autoReference.default : void 0) ?? plan.world.mode : null;\n const timing = plan.world?.timing;\n const referenceTiming = timing ? wanted.referenceTiming && timing.values.includes(wanted.referenceTiming) ? wanted.referenceTiming : timing.fallback : null;\n const properties3 = {};\n for (const property of plan.properties) {\n const value = wanted.properties?.[property.step]?.[property.key];\n if (admitsProperty(property, value)) (properties3[property.step] ??= {})[property.key] = value;\n }\n return {\n workflow: workflowRef2(workflow2),\n durationSeconds,\n speech: speech2,\n aspectRatio,\n locale,\n resolution,\n upscale4k,\n model,\n modelQuality,\n autoReference,\n referenceTiming,\n properties: properties3,\n references: admittedReferences(plan, held),\n voice: wanted.voice ?? null\n };\n}\nvar workflowRef2 = (workflow2) => ({ id: workflow2.id, ...workflow2.origin === "saved" && workflow2.revision !== null ? { revision: workflow2.revision } : {} });\nfunction admittedReferences(plan, held) {\n const counts2 = /* @__PURE__ */ new Map();\n let pool = 0;\n const kept = [];\n for (const reference2 of held) {\n const audio = audioRoles.includes(reference2.role);\n const max = reference2.role === "soundtrack" ? plan.music : reference2.role === "voice" ? plan.voices : plan.slots.find((slot) => slot.role === reference2.role)?.max ?? 0;\n const count2 = counts2.get(reference2.role) ?? 0;\n if (count2 >= max || !audio && pool >= plan.pool) continue;\n counts2.set(reference2.role, count2 + 1);\n if (!audio) pool += 1;\n kept.push(reference2);\n }\n return kept;\n}\nfunction issuesOf(workflow2, plan, value) {\n const issues = [];\n const count2 = (role) => value.references.filter((reference2) => reference2.role === role).length;\n for (const slot of plan.slots) if (slot.min > count2(slot.role)) issues.push({ kind: "references", role: slot.role, min: slot.min });\n for (const [role, max] of [["soundtrack", plan.music], ["voice", plan.voices]]) {\n const min = workflow2.references.roles.find((entry) => entry.role === role)?.min ?? 0;\n if (max > 0 && min > count2(role)) issues.push({ kind: "references", role, min });\n }\n if (plan.slots.length && workflow2.references.requires_non_character && !value.references.some((reference2) => reference2.role === "location" || reference2.role === "style")) issues.push({ kind: "non_character" });\n return issues;\n}\nfunction propertiesOf(workflow2, plan, value, music, exported) {\n const result2 = {};\n const put = (step3, key2, item) => {\n (result2[step3] ??= {})[key2] = item;\n };\n for (const property of plan.properties) {\n const item = value.properties[property.step]?.[property.key];\n if (admitsProperty(property, item) && item !== property.fallback) put(property.step, property.key, item);\n }\n const route = plan.model && value.model !== plan.model.fallback ? plan.model.routes.find((item) => item.model === value.model) : void 0;\n if (plan.model && route) put(plan.model.step, "route", { provider: route.provider, model: route.model });\n if (plan.quality && value.modelQuality !== null && value.modelQuality !== plan.quality.fallback) put(plan.quality.step, "modelQuality", value.modelQuality);\n const world = plan.world;\n if (world?.step) {\n if (value.autoReference && value.autoReference !== world.mode) put(world.step, "mode", value.autoReference);\n if (value.autoReference === "auto" && world.timing && value.referenceTiming && value.referenceTiming !== world.timing.fallback) {\n put(world.step, "timing", value.referenceTiming);\n }\n }\n if (plan.upscale && value.upscale4k !== plan.upscale.fallback) put(plan.upscale.step, "upscale4k", value.upscale4k);\n const exportStep = music ? soundtrackExportStep(workflow2) : null;\n if (exportStep) put(exportStep, "soundtrackExport", exported === "add" || exported === "none" ? exported : "add");\n return Object.keys(result2).length ? result2 : void 0;\n}\nvar referenceInput = (reference2) => ({ assetId: reference2.assetId, role: reference2.role, ...reference2.name ? { name: reference2.name.slice(0, 120) } : {} });\nvar audioRank = (role) => role === "soundtrack" ? 1 : role === "voice" ? 2 : 0;\nfunction requestOf(workflow2, plan, options, value, input4, wanted = {}) {\n if (!input4 || typeof input4.prompt !== "string") throw invalid2("toRequest needs a prompt");\n const references = [...value.references.map(referenceInput), ...input4.references ?? []].map((reference2, index) => ({ reference: reference2, index })).sort((a, b) => audioRank(a.reference.role) - audioRank(b.reference.role) || a.index - b.index).map((item) => item.reference);\n const music = references.some((reference2) => reference2.role === "soundtrack");\n const exportStep = music ? soundtrackExportStep(workflow2) : null;\n const exported = exportStep ? wanted.properties?.[exportStep]?.soundtrackExport : void 0;\n const properties3 = propertiesOf(workflow2, plan, value, music, typeof exported === "string" ? exported : void 0);\n const images = references.some((reference2) => audioRank(reference2.role) === 0 && reference2.role !== "source_video");\n const prepare = workflow2.reference_preparation && images && plan.world !== null && plan.world.step === null && value.autoReference === "auto";\n return {\n workflow: workflowRef2(workflow2),\n prompt: input4.prompt,\n durationSeconds: value.durationSeconds,\n speech: value.speech,\n ...workflow2.aspect_ratios.includes(value.aspectRatio) || !workflow2.aspect_ratios.length ? { aspectRatio: value.aspectRatio } : {},\n ...workflow2.locales.includes(value.locale) ? { locale: value.locale } : {},\n ...options.resolution && workflow2.output_resolutions.includes(value.resolution) ? { outputResolution: value.resolution } : {},\n ...properties3 ? { properties: properties3 } : {},\n ...references.length ? { references } : {},\n ...prepare ? { referencePreparation: "auto" } : {},\n ...input4.effort ? { effort: input4.effort } : {}\n };\n}\nvar speechChoices = (workflow2, options, seconds) => options.speech ? videoSpeechModes(workflow2, seconds) : [];\nvar memoryStore2;\nvar storeKey2 = (key2) => `nocha-video-settings:${key2.slice(0, 80)}`;\nvar oneOf3 = (list5, value) => list5.includes(value) ? value : void 0;\nvar isRecord2 = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);\nvar workflowIdPattern = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/u;\nfunction readWorkflowRef(value) {\n if (typeof value === "string") return workflowIdPattern.test(value) ? { id: value } : void 0;\n if (!isRecord2(value) || typeof value.id !== "string" || !workflowIdPattern.test(value.id)) return void 0;\n return { id: value.id, ...Number.isSafeInteger(value.revision) && Number(value.revision) > 0 ? { revision: value.revision } : {} };\n}\nfunction readWanted(value) {\n if (!isRecord2(value)) return {};\n const wanted = {};\n if (Number.isSafeInteger(value.durationSeconds) && Number(value.durationSeconds) > 0 && Number(value.durationSeconds) <= 600) wanted.durationSeconds = value.durationSeconds;\n const speech2 = oneOf3(speeches, value.speech);\n if (speech2) wanted.speech = speech2;\n const aspect = oneOf3(aspects, value.aspectRatio);\n if (aspect) wanted.aspectRatio = aspect;\n const locale = oneOf3(videoLocales, value.locale);\n if (locale) wanted.locale = locale;\n const resolution = oneOf3(resolutions3, value.resolution);\n if (resolution) wanted.resolution = resolution;\n if (typeof value.upscale4k === "boolean") wanted.upscale4k = value.upscale4k;\n if (isRouteModel(value.model)) wanted.model = value.model;\n if (isPropertyScalar(value.modelQuality)) wanted.modelQuality = value.modelQuality;\n const mode = oneOf3(["auto", "off"], value.autoReference);\n if (mode) wanted.autoReference = mode;\n const timing = oneOf3(["beforeStory", "afterStory"], value.referenceTiming);\n if (timing) wanted.referenceTiming = timing;\n if (isRecord2(value.properties)) {\n const properties3 = {};\n for (const [step3, values] of Object.entries(value.properties).slice(0, 12)) {\n if (!isPropertyStep(step3) || !isRecord2(values)) continue;\n const entries = Object.entries(values).filter((entry) => isPropertyKey(entry[0]) && isPropertyScalar(entry[1])).slice(0, 12);\n if (entries.length) properties3[step3] = Object.fromEntries(entries);\n }\n wanted.properties = properties3;\n }\n const voice = value.voice;\n if (isRecord2(voice) && isSpeechVoiceId(voice.id) && typeof voice.model === "string" && (voice.model === "" || isSpeechModelId(voice.model))) {\n const name = typeof voice.name === "string" ? voice.name.replace(/\\s+/gu, " ").trim().slice(0, 80) : "";\n wanted.voice = { id: voice.id, model: voice.model, ...name ? { name } : {} };\n } else if (voice === null) wanted.voice = null;\n return wanted;\n}\nfunction readStored(key2) {\n if (!key2) return null;\n let raw;\n try {\n raw = globalThis.localStorage?.getItem(storeKey2(key2));\n } catch {\n raw = void 0;\n }\n raw ??= memoryStore2?.get(storeKey2(key2)) ?? null;\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw);\n const workflow2 = readWorkflowRef(parsed.workflow);\n const tracks = Array.isArray(parsed.tracks) ? parsed.tracks.filter((id) => typeof id === "string" && id.length <= 80).slice(0, 10) : [];\n return { ...workflow2 ? { workflow: workflow2 } : {}, wanted: readWanted(parsed.wanted), tracks };\n } catch {\n return null;\n }\n}\nfunction writeStored(key2, stored) {\n if (!key2) return;\n const raw = JSON.stringify(stored);\n memoryStore2 ??= /* @__PURE__ */ new Map();\n memoryStore2.set(storeKey2(key2), raw);\n try {\n globalThis.localStorage?.setItem(storeKey2(key2), raw);\n } catch {\n }\n}\nfunction readReferences(value) {\n if (!Array.isArray(value)) return [];\n return value.slice(0, 24).flatMap((item) => {\n if (!isRecord2(item) || typeof item.assetId !== "string" || !item.assetId || typeof item.role !== "string" || !/^[a-z][a-z0-9_]{0,31}$/u.test(item.role)) return [];\n return [{\n assetId: item.assetId,\n role: item.role,\n ...typeof item.name === "string" && item.name ? { name: item.name.slice(0, 120) } : {},\n ...typeof item.track === "string" ? { track: item.track } : {},\n ...typeof item.previewUrl === "string" && /^(?:blob:|data:image\\/|https:)/u.test(item.previewUrl) ? { previewUrl: item.previewUrl } : {}\n }];\n });\n}\n\n// src/video-settings-types.ts\nvar videoSettingsTexts = {\n fr: {\n settings: "R\\xE9glages",\n workflow: "Style",\n duration: "Dur\\xE9e",\n format: "Format",\n quality: "Qualit\\xE9",\n upscale: "4K",\n language: "Langue",\n speech: "Paroles",\n model: "Mod\\xE8le vid\\xE9o",\n modelQuality: "Rendu",\n autoReference: "Auto-ref",\n referenceTiming: "Pr\\xE9paration",\n timingNote: "Quand le studio \\xE9crit lui-m\\xEAme l\\u2019histoire \\xE0 partir du brief, la pr\\xE9paration se fait toujours apr\\xE8s l\\u2019histoire.",\n beforeStory: "D\\xE8s l\\u2019envoi des r\\xE9f\\xE9rences",\n afterStory: "Apr\\xE8s l\\u2019histoire",\n auto: "Auto",\n references: "R\\xE9f\\xE9rences",\n music: "Musique",\n voice: "Voix",\n add: "Ajouter",\n importMusic: "Importer une musique",\n importVoice: "Importer une voix",\n remove: "Retirer {name}",\n moveBefore: "Avancer {name}",\n moveAfter: "Reculer {name}",\n noMusic: "Sans musique",\n required: "Requis",\n uploading: "Envoi\\u2026",\n uploadFailed: "Envoi impossible",\n loading: "Chargement\\u2026",\n unavailable: "Styles indisponibles",\n retry: "R\\xE9essayer",\n empty: "Aucun style",\n seconds: "{value} s",\n speechModes: { none: "Aucune", auto: "Libres", required: "Exig\\xE9es" },\n roles: {\n character: "Personnages",\n location: "Lieux",\n style: "Style visuel",\n source_video: "Vid\\xE9o source",\n start_frame: "Image de d\\xE9but",\n end_frame: "Image de fin",\n soundtrack: "Musique",\n voice: "Voix"\n }\n },\n en: {\n settings: "Settings",\n workflow: "Style",\n duration: "Length",\n format: "Format",\n quality: "Quality",\n upscale: "4K",\n language: "Language",\n speech: "Dialogue",\n model: "Video model",\n modelQuality: "Render",\n autoReference: "Auto-ref",\n referenceTiming: "Preparation",\n timingNote: "When the studio writes the story itself from the brief, the preparation always comes after the story.",\n beforeStory: "As soon as references are sent",\n afterStory: "After the story",\n auto: "Auto",\n references: "References",\n music: "Music",\n voice: "Voice",\n add: "Add",\n importMusic: "Import music",\n importVoice: "Import a voice",\n remove: "Remove {name}",\n moveBefore: "Move {name} earlier",\n moveAfter: "Move {name} later",\n noMusic: "No music",\n required: "Required",\n uploading: "Sending\\u2026",\n uploadFailed: "Could not send",\n loading: "Loading\\u2026",\n unavailable: "Styles unavailable",\n retry: "Retry",\n empty: "No style",\n seconds: "{value} s",\n speechModes: { none: "None", auto: "Free", required: "Required" },\n roles: {\n character: "Characters",\n location: "Places",\n style: "Visual style",\n source_video: "Source video",\n start_frame: "Start frame",\n end_frame: "End frame",\n soundtrack: "Music",\n voice: "Voice"\n }\n }\n};\n\n// src/video-workflow-picker.ts\nvar builtinDefaults = ["film-narratif-libre", "film-narratif-storyboard", "clip-debut-fin"];\nvar badgeIcons = {\n source_video: "film",\n start_frame: "start",\n end_frame: "end",\n soundtrack: "note",\n voice: "mic",\n saved: "star"\n};\nfunction offeredWorkflows(items, choice) {\n const seen = /* @__PURE__ */ new Set();\n const unique = items.filter((item) => !seen.has(item.id) && seen.add(item.id));\n const analysis = choice.family === "analysis" || Boolean(choice.ids?.some((id) => unique.find((item) => item.id === id)?.family === "analysis"));\n const kept = unique.filter((item) => (analysis || item.family !== "analysis") && (!choice.family || item.family === choice.family) && (!choice.ids || choice.ids.includes(item.id)) && (!choice.filter || safeFilter(choice.filter, item)));\n return choice.ids ? choice.ids.flatMap((id) => kept.filter((item) => item.id === id)) : kept;\n}\nvar safeFilter = (filter, workflow2) => {\n try {\n return filter(workflow2) === true;\n } catch {\n return false;\n }\n};\nvar isAvailable = (workflow2) => workflow2.availability.status === "available" && (workflow2.interaction === null || workflow2.interaction === "none");\nfunction defaultWorkflow(offered, choice, wanted, seconds) {\n const available = offered.filter(isAvailable);\n const byId = (id) => id ? available.find((item) => item.id === id) : void 0;\n const defaults = typeof choice.default === "string" ? [choice.default] : choice.default ?? [];\n return byId(wanted?.id) ?? defaults.map(byId).find(Boolean) ?? builtinDefaults.map(byId).find(Boolean) ?? (seconds === void 0 ? void 0 : available.find((item) => item.default_for_durations_seconds.includes(seconds))) ?? available[0] ?? null;\n}\nfunction entriesOf(workflows2, locale, groups3) {\n const entries = [];\n for (const workflow2 of workflows2) {\n const shown = videoWorkflowPresentation(workflow2, locale);\n if (!groups3 || !shown.group) {\n entries.push({ key: workflow2.id, title: shown.title, heading: null, setting: null, members: [{ workflow: workflow2, shown }] });\n continue;\n }\n const group = shown.group;\n const existing = entries.find((entry) => entry.key === `group:${group.id}`);\n if (existing) existing.members.push({ workflow: workflow2, shown });\n else entries.push({ key: `group:${group.id}`, title: group.title, heading: group.title, setting: group.setting, members: [{ workflow: workflow2, shown }] });\n }\n for (const entry of entries) entry.members.sort((a, b) => videoWorkflowGroupOrder(a.workflow.id) - videoWorkflowGroupOrder(b.workflow.id));\n return entries;\n}\nfunction badges(doc, list5) {\n return element(\n doc,\n "span",\n "nocha-workflows__badges",\n {},\n ...list5.map((badge) => element(\n doc,\n "span",\n "",\n { title: badge.label },\n icon(doc, badgeIcons[badge.kind]),\n element(doc, "span", "nocha-ui-hidden", {}, badge.label)\n ))\n );\n}\nfunction workflowList(doc, text6, locale, display, groups3, compactDensity, onPick) {\n const root = element(doc, "div", `nocha-workflows${compactDensity ? " nocha-workflows--compact-density" : ""}`);\n const labelId = uid("nocha-workflows");\n const label = element(doc, "span", "nocha-ui-hidden", { id: labelId }, text6.workflow);\n let entries = [];\n let listKey = "";\n let selected2 = null;\n let options = [];\n const memberLabel = uid("nocha-workflows-member");\n const pickId = (id) => {\n const found = entries.flatMap((entry) => entry.members).find((item) => item.workflow.id === id);\n if (found?.shown.available) onPick(found.workflow);\n };\n const member2 = selectControl(doc, memberLabel, pickId);\n const memberRow = element(\n doc,\n "div",\n "nocha-workflows__member",\n { hidden: true },\n element(doc, "span", "nocha-workflows__member-label", { id: memberLabel }),\n member2.element\n );\n const menu = selectControl(doc, labelId, pickId);\n const detail = element(doc, "div", "nocha-workflows__detail");\n const lead = (entry) => entry.members.find((item) => item.workflow.id === selected2) ?? entry.members.find((item) => item.shown.available) ?? entry.members[0];\n function card(entry) {\n const shown = lead(entry)?.shown;\n const available = entry.members.some((item) => item.shown.available);\n const durations = [...new Set(entry.members.flatMap((item) => item.shown.durations))].sort((a, b) => a - b);\n const stops = entry.members.every((item) => item.workflow.duration_seconds.allowed !== null);\n const marks = [...new Map(entry.members.flatMap((item) => item.shown.badges).map((badge) => [badge.kind, badge])).values()];\n const line5 = available ? shown?.description ?? "" : shown?.unavailableReason ?? "";\n return element(\n doc,\n "button",\n "nocha-workflows__card",\n { type: "button", role: "radio", "aria-disabled": available ? null : "true" },\n element(doc, "span", "nocha-workflows__name", {}, entry.title),\n line5 && element(doc, "span", `nocha-workflows__text${available ? "" : " nocha-workflows__text--reason"}`, {}, line5),\n element(\n doc,\n "span",\n "nocha-workflows__meta",\n {},\n element(doc, "span", "nocha-workflows__range", {}, durationRangeText(durations, stops)),\n badges(doc, marks)\n )\n );\n }\n function line4(item, grouped) {\n const { shown } = item;\n const name = grouped && shown.member ? shown.member : shown.title;\n const words2 = shown.available ? shown.description : shown.unavailableReason ?? "";\n return element(\n doc,\n "button",\n "nocha-workflows__line",\n { type: "button", role: "radio", "aria-disabled": shown.available ? null : "true" },\n element(doc, "span", "nocha-workflows__dot"),\n element(\n doc,\n "span",\n "nocha-workflows__words",\n {},\n element(doc, "span", "nocha-workflows__name", {}, name),\n words2 && element(doc, "span", `nocha-workflows__text${shown.available ? "" : " nocha-workflows__text--reason"}`, {}, words2)\n ),\n element(doc, "span", "nocha-workflows__meta", {}, element(doc, "span", "nocha-workflows__range", {}, shown.durationRange), badges(doc, shown.badges))\n );\n }\n function build() {\n options = [];\n if (display === "select") {\n root.replaceChildren(label, menu.element, detail);\n return;\n }\n const group = element(\n doc,\n "div",\n display === "cards" ? "nocha-workflows__cards" : "nocha-workflows__list",\n { role: "radiogroup", "aria-labelledby": labelId }\n );\n for (const entry of entries) {\n if (display === "cards") {\n const button = card(entry);\n options.push({ button, workflow: null, entry });\n group.append(button);\n continue;\n }\n const grouped = Boolean(entry.heading) && entry.members.length > 1;\n if (grouped) group.append(element(doc, "div", "nocha-workflows__heading", { "aria-hidden": "true" }, entry.heading));\n for (const item of entry.members) {\n const button = line4(item, grouped);\n if (grouped) button.setAttribute("aria-label", `${entry.heading} \\xB7 ${item.shown.member ?? item.shown.title}`);\n options.push({ button, workflow: item.workflow, entry });\n group.append(button);\n }\n }\n for (const option of options) {\n option.button.addEventListener("click", () => {\n const workflow2 = option.workflow ?? lead(option.entry)?.workflow;\n const found = workflow2 && option.entry.members.find((item) => item.workflow.id === workflow2.id);\n if (found?.shown.available) onPick(found.workflow);\n else {\n const first = option.entry.members.find((item) => item.shown.available);\n if (first) onPick(first.workflow);\n }\n });\n }\n group.addEventListener("keydown", (event) => {\n const moves = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };\n const delta = moves[event.key];\n const enabled2 = options.filter((option) => option.button.getAttribute("aria-disabled") !== "true");\n if (delta === void 0 || !enabled2.length) return;\n event.preventDefault();\n const index = Math.max(0, enabled2.findIndex((option) => option.button.getAttribute("aria-checked") === "true"));\n const next = enabled2[(index + delta + enabled2.length) % enabled2.length];\n next?.button.focus();\n next?.button.click();\n });\n root.replaceChildren(label, group, ...display === "cards" ? [memberRow] : []);\n }\n function mark() {\n if (display === "select") {\n const menuOptions = entries.flatMap((entry2) => entry2.members.map((item) => {\n const grouped = Boolean(entry2.heading) && entry2.members.length > 1;\n const name = grouped && item.shown.member ? item.shown.member : item.shown.title;\n return {\n value: item.workflow.id,\n text: item.shown.available ? name : `${name} \\u2014 ${item.shown.unavailableReason ?? ""}`,\n disabled: !item.shown.available,\n ...grouped && entry2.heading ? { group: entry2.heading } : {}\n };\n }));\n menu.update(menuOptions, selected2 ?? "");\n const current4 = entries.flatMap((entry2) => entry2.members).find((item) => item.workflow.id === selected2)?.shown;\n detail.replaceChildren(...current4 ? [\n element(doc, "span", "nocha-workflows__range", {}, current4.durationRange),\n current4.description && element(doc, "span", "nocha-workflows__text", {}, current4.description),\n badges(doc, current4.badges)\n ].filter((node) => Boolean(node)) : []);\n return;\n }\n let focusable = false;\n for (const option of options) {\n const on = option.workflow ? option.workflow.id === selected2 : option.entry.members.some((item) => item.workflow.id === selected2);\n option.button.setAttribute("aria-checked", String(on));\n option.button.tabIndex = on ? 0 : -1;\n focusable ||= on;\n }\n const first = options.find((option) => option.button.getAttribute("aria-disabled") !== "true");\n if (!focusable && first) first.button.tabIndex = 0;\n if (display !== "cards") return;\n const entry = entries.find((item) => item.members.some((member3) => member3.workflow.id === selected2));\n memberRow.hidden = !entry?.setting || entry.members.length < 2;\n if (!entry?.setting || entry.members.length < 2) return;\n const labelNode = memberRow.querySelector(".nocha-workflows__member-label");\n if (labelNode) labelNode.textContent = entry.setting;\n member2.update(entry.members.map((item) => ({\n value: item.workflow.id,\n disabled: !item.shown.available,\n text: item.shown.available ? item.shown.member ?? item.shown.title : `${item.shown.member ?? item.shown.title} \\u2014 ${item.shown.unavailableReason ?? ""}`\n })), selected2 ?? "");\n }\n return {\n element: root,\n render(workflows2, chosen) {\n const key2 = JSON.stringify(workflows2.map((item) => [item.id, item.revision, item.availability.status, item.name]));\n selected2 = chosen;\n if (key2 !== listKey) {\n listKey = key2;\n entries = entriesOf(workflows2, locale, groups3);\n build();\n } else if (display === "cards") {\n for (const option of options) {\n const fresh2 = card(option.entry);\n option.button.replaceChildren(...Array.from(fresh2.childNodes));\n }\n }\n mark();\n }\n };\n}\nasync function readWorkflows(video, choice, signal) {\n const listed = await video.workflows(choice.family ? { family: choice.family } : {}, { signal });\n return offeredWorkflows(listed.items, choice);\n}\nfunction createWorkflowPicker(container, video, options = {}) {\n const ui = mountUiHost(videoSettingsCss, container, "nocha-workflow-picker");\n const doc = ui.host.ownerDocument;\n const locale = uiLocale(options.uiLocale);\n const text6 = uiTexts(videoSettingsTexts, locale, options.labels);\n const stop = new AbortController();\n let workflows2 = [];\n let current4 = null;\n let disposed = false;\n const list5 = workflowList(doc, text6, locale, options.display ?? "cards", options.groups !== false, false, (workflow2) => {\n if (workflow2.id === current4?.id) return;\n current4 = workflow2;\n list5.render(workflows2, current4.id);\n options.onChange?.(workflow2);\n });\n const status2 = element(doc, "div", cls("status"), { role: "status" }, text6.loading);\n const root = element(doc, "div", "nocha-video-settings", {}, status2, list5.element);\n ui.root.append(root);\n const wanted = typeof options.value === "string" ? { id: options.value } : options.value ?? null;\n let reading = null;\n let ready;\n const reload = () => {\n if (reading) return reading;\n const current5 = reading = read4().finally(() => {\n if (reading === current5) reading = null;\n });\n ready = current5;\n current5.catch(() => void 0);\n return current5;\n };\n const setDisabled = (on) => {\n root.inert = on;\n root.classList.toggle("nocha-video-settings--disabled", on);\n if (on) root.setAttribute("aria-disabled", "true");\n else root.removeAttribute("aria-disabled");\n };\n const read4 = async () => {\n status2.hidden = false;\n status2.replaceChildren(text6.loading);\n try {\n workflows2 = await readWorkflows(video, options, stop.signal);\n } catch (error) {\n if (!disposed) {\n const retry2 = element(doc, "button", cls("retry"), { type: "button" }, text6.retry);\n retry2.addEventListener("click", () => {\n void reload();\n });\n status2.replaceChildren(text6.unavailable, retry2);\n }\n throw error;\n }\n current4 = defaultWorkflow(workflows2, options, current4 ? { id: current4.id } : wanted);\n status2.hidden = workflows2.length > 0;\n if (!workflows2.length) status2.replaceChildren(text6.empty);\n list5.render(workflows2, current4?.id ?? null);\n return current4;\n };\n if (options.disabled) setDisabled(true);\n reload();\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n stop.abort();\n options.signal?.removeEventListener("abort", dispose);\n ui.remove();\n };\n if (options.signal?.aborted) dispose();\n else options.signal?.addEventListener("abort", dispose, { once: true });\n return {\n get ready() {\n return ready;\n },\n get value() {\n return current4;\n },\n get workflows() {\n return workflows2;\n },\n set(id) {\n const ref = typeof id === "string" ? { id } : id;\n const found = workflows2.find((item) => item.id === ref.id && isAvailable(item));\n if (!found) return;\n current4 = found;\n list5.render(workflows2, found.id);\n },\n reload,\n setDisabled: (on) => setDisabled(on === true),\n dispose\n };\n}\n\n// src/video-settings.ts\nvar isFixed = (choice) => Boolean(choice && typeof choice.fixed === "string");\nvar wantedKeys = [\n "durationSeconds",\n "speech",\n "aspectRatio",\n "locale",\n "resolution",\n "upscale4k",\n "model",\n "modelQuality",\n "autoReference",\n "referenceTiming",\n "properties",\n "voice"\n];\nvar voiceSpeaks = (workflow2) => workflow2.speech_modes.some((entry) => entry.mode !== "none") || roleMax(workflow2, "voice") > 0;\nfunction mountVideoSettings(container, video, options = {}) {\n return buildVideoSettings(container, video, options).settings;\n}\nfunction buildVideoSettings(container, video, initial = {}, open3) {\n const ui = mountUiHost(videoSettingsCss, container, "nocha-video-settings");\n let options = { ...initial };\n const doc = ui.host.ownerDocument;\n const locale = uiLocale(options.uiLocale);\n const text6 = uiTexts(videoSettingsTexts, locale, options.labels);\n const compact = options.density === "compact";\n const folded = options.collapsed ?? compact;\n let choice = isFixed(options.workflow) ? {} : options.workflow ?? {};\n let followDefault = false;\n const stop = new AbortController();\n const stored = readStored(options.storageKey);\n let wanted = { ...stored?.wanted, ...readWanted(options.value ?? {}) };\n let wantedWorkflow = readWorkflowRef(options.value?.workflow) ?? stored?.workflow ?? null;\n const tracks = options.music ? options.music.tracks ?? [] : [];\n let held = options.value?.references ? readReferences(options.value.references) : (stored?.tracks ?? []).flatMap((id) => tracks.filter((track) => track.id === id).map((track) => ({ assetId: track.assetId, role: "soundtrack", name: track.label.slice(0, 120), track: track.id })));\n let workflows2 = [];\n let workflow2 = null;\n let plan = null;\n let value = null;\n let voiceField = null;\n let disposed = false;\n let bridged = Boolean(open3);\n const status2 = element(doc, "div", cls("status"), { role: "status" }, text6.loading);\n const list5 = isFixed(options.workflow) ? null : workflowList(doc, text6, locale, choice.display ?? "cards", choice.groups !== false, compact, (picked) => {\n if (picked.id === workflow2?.id) return;\n wantedWorkflow = workflowRef2(picked);\n adopt(picked);\n commit("user");\n });\n const workflowRow = list5 ? row(doc, text6.workflow, list5.element) : null;\n workflowRow?.element.classList.add(cls("row--workflow"));\n const durationRow = row(doc, text6.duration);\n const durationControl = durationRow.element.querySelector(`.${cls("control")}`);\n const slider = sliderControl(doc, durationRow.id, (seconds) => change2({ durationSeconds: seconds }));\n const durationChips = segments(doc, durationRow.id, (seconds) => change2({ durationSeconds: seconds }), true);\n const durationFixed = element(doc, "span", cls("fixed"), { hidden: true });\n durationControl.append(slider.element, durationChips.element, durationFixed);\n const formatRow = row(doc, text6.format);\n const format = segments(doc, formatRow.id, (aspect) => change2({ aspectRatio: aspect }));\n formatRow.element.lastElementChild?.append(format.element);\n const qualityRow = row(doc, text6.quality);\n const quality = segments(doc, qualityRow.id, (resolution) => change2({ resolution }));\n const upscale = switchControl(doc, text6.upscale, (on) => change2({ upscale4k: on }));\n qualityRow.element.lastElementChild?.append(quality.element, upscale.element);\n const languageRow = row(doc, text6.language);\n const language2 = selectControl(doc, languageRow.id, (code) => change2({ locale: code }));\n languageRow.element.lastElementChild?.append(language2.element);\n const speechRow = row(doc, text6.speech);\n const speech2 = segments(doc, speechRow.id, (mode) => change2({ speech: mode }));\n speechRow.element.lastElementChild?.append(speech2.element);\n const modelRow = row(doc, text6.model);\n const model = selectControl(doc, modelRow.id, (key2) => change2({ model: key2 || null }));\n modelRow.element.lastElementChild?.append(model.element);\n const qualityModelRow = row(doc, text6.modelQuality);\n const modelQualityMenu = selectControl(doc, qualityModelRow.id, (index) => {\n const values = plan?.quality?.values ?? [];\n change2({ modelQuality: index === "" ? null : values[Number(index)] ?? null });\n });\n qualityModelRow.element.lastElementChild?.append(modelQualityMenu.element);\n const autoRow = row(doc, text6.autoReference);\n const auto = switchControl(doc, "", (on) => change2({ autoReference: on ? "auto" : "off" }), autoRow.id);\n autoRow.element.lastElementChild?.append(auto.element);\n const timingRow = row(doc, text6.referenceTiming);\n const timing = selectControl(doc, timingRow.id, (moment) => change2({ referenceTiming: moment === "afterStory" ? "afterStory" : "beforeStory" }));\n timingRow.element.lastElementChild?.append(timing.element);\n const timingNote = element(doc, "p", cls("note"), {}, text6.timingNote);\n timingRow.element.append(timingNote);\n const propertiesGroup = element(doc, "div", cls("group"));\n let propertiesKey = "";\n const media2 = mediaView(doc, text6, options, {\n held: () => held,\n changed(next) {\n held = next;\n commit("user");\n }\n });\n const shape2 = element(doc, "div", cls("group"), {}, durationRow.element, formatRow.element, qualityRow.element, languageRow.element, speechRow.element);\n const tech = element(doc, "div", cls("group"), {}, modelRow.element, qualityModelRow.element, autoRow.element, timingRow.element);\n const body = [...workflowRow ? [workflowRow.element] : [], shape2, tech, propertiesGroup];\n const summaryLine = element(doc, "span", cls("summary-line"));\n const more = folded ? element(\n doc,\n "details",\n cls("more"),\n {},\n element(\n doc,\n "summary",\n cls("summary"),\n {},\n element(doc, "span", cls("summary-title"), {}, text6.settings),\n summaryLine,\n icon(doc, "chevron", `nocha-ui-icon ${cls("chevron")} ${cls("chevron--closed")}`),\n icon(doc, "chevronUp", `nocha-ui-icon ${cls("chevron")} ${cls("chevron--open")}`)\n ),\n element(doc, "div", cls("more-body"), {}, ...body)\n ) : element(doc, "div", `${cls("group")} ${cls("group--top")}`, {}, ...body);\n const title = compact && isFixed(options.workflow) ? element(doc, "div", cls("title"), { hidden: true }) : null;\n const barLine = element(doc, "span", cls("summary-line"));\n const opener = element(doc, "button", cls("open"), { type: "button" }, text6.settings);\n opener.addEventListener("click", () => open3?.());\n const bar = open3 ? element(doc, "div", cls("bar"), { hidden: true }, barLine, opener) : null;\n const root = element(doc, "div", `nocha-video-settings${compact ? " nocha-video-settings--compact" : ""}`, {}, status2, title, bar, more, media2.element);\n ui.root.append(root);\n function propertyControl(property) {\n const label = videoPropertyLabel(property.key, locale);\n const line4 = row(doc, label);\n const current4 = value?.properties[property.step]?.[property.key];\n if (property.type === "boolean" || property.type === "enum") {\n const values = property.type === "boolean" ? [true, false] : property.values;\n const menu = selectControl(doc, line4.id, (index) => setProperty(property, index === "" ? void 0 : values[Number(index)]));\n menu.update(\n [\n { value: "", text: property.fallback === null ? text6.auto : `${text6.auto} \\xB7 ${videoPropertyValueLabel(property.key, property.fallback, locale)}` },\n ...values.map((item, index) => ({ value: String(index), text: videoPropertyValueLabel(property.key, item, locale) }))\n ],\n current4 === void 0 ? "" : String(values.indexOf(current4))\n );\n line4.element.lastElementChild?.append(menu.element);\n return line4.element;\n }\n const integer3 = property.type === "integer";\n const step3 = property.step_size ?? (integer3 ? 1 : Math.max((property.max - property.min) / 100, 1e-6));\n const input4 = element(doc, "input", cls("slider"), { type: "range", min: String(property.min), max: String(property.max), step: String(step3), "aria-labelledby": line4.id });\n input4.value = String(typeof current4 === "number" ? current4 : property.fallback);\n const output = element(doc, "output", `${cls("value")}${current4 === void 0 ? ` ${cls("value--auto")}` : ""}`, {}, input4.value);\n const reset = element(doc, "button", cls("segment"), { type: "button", "aria-pressed": String(current4 === void 0), "aria-checked": String(current4 === void 0) }, text6.auto);\n input4.addEventListener("input", () => {\n output.textContent = input4.value;\n });\n input4.addEventListener("change", () => setProperty(property, integer3 ? Math.round(Number(input4.value)) : Number(input4.value)));\n reset.addEventListener("click", () => setProperty(property, void 0));\n line4.element.lastElementChild?.append(element(doc, "div", `${cls("range")} ${cls("range--property")}`, {}, input4, output), reset);\n return line4.element;\n }\n function setProperty(property, item) {\n const properties3 = { ...wanted.properties };\n const values = { ...properties3[property.step] };\n if (item === void 0 || !admitsProperty(property, item)) delete values[property.key];\n else values[property.key] = item;\n if (Object.keys(values).length) properties3[property.step] = values;\n else delete properties3[property.step];\n propertiesKey = "";\n change2({ properties: properties3 });\n }\n function summary(full = false) {\n if (!workflow2 || !value) return "";\n const parts = [\n list5 ? videoWorkflowPresentation(workflow2, locale).title : "",\n options.duration ? fill(text6.seconds, { value: value.durationSeconds }) : "",\n plan && (full || plan.aspects.length > 1) ? value.aspectRatio : "",\n plan && (full || plan.resolutions.length > 1) ? `${value.resolution}${value.upscale4k ? " \\xB7 4K" : ""}` : value.upscale4k ? "4K" : "",\n plan?.model && value.model ? videoRouteLabel(value.model) : ""\n ];\n return parts.filter(Boolean).join(" \\xB7 ");\n }\n function render() {\n if (disposed) return;\n const ready2 = Boolean(workflow2 && plan && value);\n rowsShown(ready2 && hasAnyRow());\n if (!workflow2 || !plan || !value) {\n media2.element.hidden = true;\n return;\n }\n list5?.render(workflows2, workflow2.id);\n if (title) {\n title.textContent = videoWorkflowPresentation(workflow2, locale).title || workflow2.name;\n title.hidden = !title.textContent;\n }\n if (workflowRow) workflowRow.element.hidden = workflows2.length < 2 && isAvailable(workflow2);\n durationRow.element.hidden = !options.duration || !plan.durations.length;\n const seconds = (count2) => fill(text6.seconds, { value: count2 });\n const fixed = plan.durations.length === 1;\n durationFixed.hidden = !fixed;\n durationFixed.textContent = fixed ? seconds(value.durationSeconds) : "";\n const chips = Boolean(options.duration && options.duration.control === "chips");\n durationChips.element.hidden = fixed || !chips;\n slider.element.hidden = fixed || chips;\n if (chips) {\n durationChips.update(plan.durations.map((count2) => ({ value: count2, text: seconds(count2) })), value.durationSeconds);\n } else slider.update(plan.durations, value.durationSeconds, seconds);\n formatRow.element.hidden = plan.aspects.length < 2;\n format.update(plan.aspects.map((aspect) => ({ value: aspect, text: aspect })), value.aspectRatio);\n quality.update(plan.resolutions.map((resolution) => ({ value: resolution, text: resolution })), value.resolution);\n quality.element.hidden = plan.resolutions.length < 2;\n upscale.element.hidden = !plan.upscale;\n upscale.set(value.upscale4k);\n qualityRow.element.hidden = plan.resolutions.length < 2 && !plan.upscale;\n languageRow.element.hidden = plan.locales.length < 2;\n language2.update(plan.locales.map((code) => ({ value: code, text: `${languageName(code.split("-")[0] ?? code, locale)} \\xB7 ${code.split("-")[1] ?? ""}` })), value.locale);\n const modes = speechChoices(workflow2, options, value.durationSeconds);\n speechRow.element.hidden = modes.length < 2;\n speech2.update(modes.map((mode) => ({ value: mode, text: text6.speechModes[mode] })), value.speech);\n const routes = plan.model?.routes ?? [];\n modelRow.element.hidden = !plan.model || routes.length < 2 && plan.model.fallback !== null;\n model.update([\n ...plan.model && plan.model.fallback === null ? [{ value: "", text: text6.auto }] : [],\n ...routes.map((route) => ({ value: route.model, text: videoRouteLabel(route) }))\n ], value.model ?? "");\n const qualities = plan.quality?.values ?? [];\n qualityModelRow.element.hidden = !plan.quality || qualities.length < 2 && plan.quality.fallback !== null;\n modelQualityMenu.update(\n [\n ...plan.quality && plan.quality.fallback === null ? [{ value: "", text: text6.auto }] : [],\n ...qualities.map((item, index) => ({ value: String(index), text: videoPropertyValueLabel("modelQuality", item, locale) }))\n ],\n value.modelQuality === null ? "" : String(qualities.indexOf(value.modelQuality))\n );\n autoRow.element.hidden = !plan.world;\n auto.set(value.autoReference === "auto");\n const moments = options.autoReference && options.autoReference.timing !== false ? plan.world?.timing : null;\n timingRow.element.hidden = !moments;\n timing.update(\n (moments?.values ?? []).map((moment) => ({ value: moment, text: moment === "beforeStory" ? text6.beforeStory : text6.afterStory })),\n value.referenceTiming ?? ""\n );\n timing.select.disabled = value.autoReference !== "auto" || (moments?.values.length ?? 0) < 2;\n const key2 = JSON.stringify([workflow2.id, workflow2.revision, plan.properties.map((item) => [item.step, item.key]), value.properties]);\n if (key2 !== propertiesKey) {\n propertiesKey = key2;\n propertiesGroup.replaceChildren(...plan.properties.map(propertyControl));\n }\n propertiesGroup.hidden = !plan.properties.length;\n shape2.hidden = [durationRow, formatRow, qualityRow, languageRow, speechRow].every((item) => item.element.hidden);\n tech.hidden = [modelRow, qualityModelRow, autoRow, timingRow].every((item) => item.element.hidden);\n rowsShown(hasAnyRow());\n summaryLine.textContent = summary();\n barLine.textContent = summary(true) || videoWorkflowPresentation(workflow2, locale).title || workflow2.name;\n const speaks = Boolean(options.voice && options.voice.ai) && voiceSpeaks(workflow2);\n if (speaks && !voiceField && options.voice && options.voice.ai) {\n const { ai, ...field3 } = options.voice;\n voiceField = createVoiceField(media2.voiceSlot, ai, {\n ...field3,\n locale: field3.locale ?? locale,\n value: wanted.voice ?? null,\n onChange: (pick4) => change2({ voice: pick4.ref })\n });\n }\n media2.render(workflow2, plan, value.references, speaks);\n }\n function rowsShown(shown) {\n more.hidden = bridged || !shown;\n if (bar) bar.hidden = !bridged || !shown;\n }\n function hasAnyRow() {\n return [workflowRow, durationRow, formatRow, qualityRow, languageRow, speechRow, modelRow, qualityModelRow, autoRow, timingRow].some((item) => item && !item.element.hidden) || !propertiesGroup.hidden && propertiesGroup.childElementCount > 0;\n }\n function adopt(next) {\n workflow2 = next;\n plan = planOf(next, options);\n }\n function commit(source2) {\n if (disposed) return;\n if (workflow2 && plan) value = resolve(workflow2, plan, options, wanted, held, locale);\n writeStored(options.storageKey, {\n ...wantedWorkflow ? { workflow: wantedWorkflow } : {},\n wanted,\n tracks: held.flatMap((reference2) => reference2.track ? [reference2.track] : [])\n });\n render();\n if (source2 && value && options.onChange) {\n try {\n options.onChange(snapshot3(value), { source: source2 });\n } catch {\n }\n }\n }\n function change2(next) {\n wanted = { ...wanted, ...next };\n commit("user");\n }\n const snapshot3 = (current4) => JSON.parse(JSON.stringify(current4));\n let reading = null;\n let ready;\n function reload() {\n if (reading) return reading;\n const current4 = reading = read4().finally(() => {\n if (reading === current4) reading = null;\n });\n ready = current4;\n current4.catch(() => void 0);\n return current4;\n }\n async function read4() {\n status2.hidden = false;\n status2.replaceChildren(text6.loading);\n try {\n if (isFixed(options.workflow)) {\n const fixed = options.workflow;\n workflows2 = [await video.workflow({ id: fixed.fixed, ...fixed.revision ? { revision: fixed.revision } : {} }, { signal: stop.signal })];\n } else {\n workflows2 = await readWorkflows(video, choice, stop.signal);\n const remembered = wantedWorkflow;\n const listed = remembered ? workflows2.find((item) => item.id === remembered.id) : void 0;\n if (remembered?.revision && listed && listed.origin === "saved" && listed.revision !== remembered.revision) {\n try {\n const kept = await video.workflow(remembered, { signal: stop.signal });\n workflows2 = workflows2.map((item) => item.id === kept.id ? kept : item);\n } catch {\n }\n }\n }\n } catch (error) {\n if (!disposed) {\n const retry2 = element(doc, "button", cls("retry"), { type: "button" }, text6.retry);\n retry2.addEventListener("click", () => {\n void reload();\n });\n status2.replaceChildren(text6.unavailable, retry2);\n rowsShown(false);\n }\n throw error;\n }\n if (disposed) return null;\n const current4 = followDefault ? null : workflow2 ? workflowRef2(workflow2) : null;\n followDefault = false;\n const chosen = isFixed(options.workflow) ? workflows2[0] ?? null : defaultWorkflow(workflows2, choice, wantedWorkflow ?? current4, options.duration ? options.duration.default : void 0);\n status2.hidden = Boolean(chosen);\n if (!chosen) status2.replaceChildren(text6.empty);\n if (chosen) adopt(chosen);\n commit("catalogue");\n return chosen;\n }\n function assign(next, source2) {\n if (!next || typeof next !== "object") return;\n wanted = { ...wanted, ...readWanted(next) };\n for (const key2 of wantedKeys) if (next[key2] === null) delete wanted[key2];\n if (next.references === null) held = [];\n else if (next.references) held = readReferences(next.references);\n const ref = next.workflow ? readWorkflowRef(next.workflow) : void 0;\n const found = ref && !isFixed(options.workflow) ? workflows2.find((item) => item.id === ref.id && isAvailable(item)) : void 0;\n const back = next.workflow === null && !isFixed(options.workflow) ? defaultWorkflow(workflows2, choice, null, options.duration ? options.duration.default : void 0) : null;\n if (next.workflow === null && !isFixed(options.workflow)) wantedWorkflow = null;\n if (found) wantedWorkflow = workflowRef2(found);\n if (found || back) adopt(found ?? back);\n voiceField?.set(wanted.voice ?? null);\n commit(source2);\n }\n function setDisabled(on) {\n root.inert = on;\n root.classList.toggle("nocha-video-settings--disabled", on);\n if (on) root.setAttribute("aria-disabled", "true");\n else root.removeAttribute("aria-disabled");\n }\n rowsShown(false);\n media2.element.hidden = true;\n if (options.disabled) setDisabled(true);\n reload();\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n stop.abort();\n options.signal?.removeEventListener("abort", dispose);\n voiceField?.dispose();\n media2.dispose();\n ui.remove();\n };\n if (options.signal?.aborted) dispose();\n else options.signal?.addEventListener("abort", dispose, { once: true });\n const settings2 = {\n get ready() {\n return ready;\n },\n get value() {\n return snapshot3(value ?? { ...emptyValue, references: [...held], voice: wanted.voice ?? null });\n },\n get workflow() {\n return workflow2;\n },\n get workflows() {\n return workflows2;\n },\n get issues() {\n return workflow2 && plan && value ? issuesOf(workflow2, plan, value) : [];\n },\n toRequest(input4) {\n if (!workflow2 || !plan || !value) throw invalid2("The video settings have not read their workflow yet: await settings.ready");\n return requestOf(workflow2, plan, options, value, input4, wanted);\n },\n set: (next, how) => assign(next, how?.notify === true ? "set" : null),\n update(next, how) {\n if (!next || typeof next !== "object" || disposed) return;\n const { workflow: wanting, ...rest } = next;\n const known = ["duration", "aspectRatio", "upscale4k", "resolution"].filter((key2) => key2 in rest);\n options = { ...options, ...Object.fromEntries(known.map((key2) => [key2, rest[key2]])) };\n const refilter = Boolean(wanting && !isFixed(options.workflow) && "filter" in wanting);\n const redefault = Boolean(wanting && !isFixed(options.workflow) && "default" in wanting);\n if (wanting && !isFixed(options.workflow)) {\n choice = { ...choice, ..."filter" in wanting ? { filter: wanting.filter } : {}, ..."default" in wanting ? { default: wanting.default } : {} };\n options = { ...options, workflow: choice };\n }\n const back = redefault && !wantedWorkflow && !refilter ? defaultWorkflow(workflows2, choice, null, options.duration ? options.duration.default : void 0) : null;\n if (redefault && !wantedWorkflow && refilter) followDefault = true;\n if (back ?? workflow2) adopt(back ?? workflow2);\n commit(how?.notify === true ? "set" : null);\n if (refilter) void (reading ? reading.catch(() => void 0).then(() => reload()) : reload());\n },\n defaults() {\n return workflow2 && plan ? snapshot3(resolve(workflow2, plan, options, {}, [], locale)) : null;\n },\n reload,\n setDisabled: (on) => setDisabled(on === true),\n dispose\n };\n return {\n settings: settings2,\n state: () => ({ options, wanted, workflow: wantedWorkflow ?? (workflow2 ? workflowRef2(workflow2) : null), uiLocale: locale }),\n choose: (next) => assign(next, "user"),\n busy(on) {\n opener.disabled = on;\n if (on) opener.setAttribute("aria-busy", "true");\n else opener.removeAttribute("aria-busy");\n },\n inline() {\n if (!bridged || disposed) return;\n bridged = false;\n render();\n if (folded) more.open = true;\n },\n signal: stop.signal\n };\n}\nvar emptyValue = {\n workflow: null,\n durationSeconds: 0,\n speech: "none",\n aspectRatio: "9:16",\n locale: "fr-FR",\n resolution: "720p",\n upscale4k: false,\n model: null,\n modelQuality: null,\n autoReference: null,\n referenceTiming: null,\n properties: {},\n references: [],\n voice: null\n};\n\n// src/video-settings-bridge.ts\nvar VIDEO_SETTINGS_EXPERIENCE = "reglages-video";\nvar VIDEO_SETTINGS_OPERATION = "reglagesVideo.choose";\nvar unreachableCodes2 = /* @__PURE__ */ new Set([\n "client_update_required",\n "bridge_unavailable",\n "capability_denied",\n "invalid_input",\n "unknown_error",\n "experience_call_unavailable",\n "experience_call_denied",\n "experience_call_invalid",\n "invocation_timed_out"\n]);\nvar unreachable2 = false;\nvar isRecord3 = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);\nfunction requestOf2(engine) {\n const { options, wanted, workflow: workflow2, uiLocale: uiLocale2 } = engine.state();\n const chosen = { ...wanted };\n delete chosen.voice;\n const listed = engine.settings.workflows.map((item) => item.id);\n const choice = options.workflow;\n const request2 = {\n workflow: choice && "fixed" in choice ? { fixed: choice.fixed, ...choice.revision ? { revision: choice.revision } : {} } : {\n ...listed.length ? { ids: listed } : choice?.ids ? { ids: [...choice.ids] } : {},\n ...!listed.length && choice?.family ? { family: choice.family } : {},\n ...choice?.default !== void 0 ? { default: typeof choice.default === "string" ? choice.default : [...choice.default] } : {},\n ...choice?.display ? { display: choice.display } : {},\n ...choice?.groups !== void 0 ? { groups: choice.groups } : {}\n },\n value: { ...chosen, workflow: workflow2 },\n uiLocale: uiLocale2\n };\n for (const key2 of ["density", "duration", "aspectRatio", "resolution", "upscale4k", "model", "modelQuality", "autoReference", "speech", "locale", "properties"]) {\n if (options[key2] !== void 0) Object.assign(request2, { [key2]: options[key2] });\n }\n return JSON.parse(JSON.stringify(request2));\n}\nasync function choose(engine) {\n try {\n const input4 = requestOf2(engine);\n const result2 = await pickExperience(VIDEO_SETTINGS_EXPERIENCE, VIDEO_SETTINGS_OPERATION, input4, { signal: engine.signal });\n if (result2.status !== "done" || !isRecord3(result2.value)) return;\n const choice = { ...result2.value };\n delete choice.references;\n delete choice.voice;\n engine.choose(choice);\n } catch (error) {\n if (engine.signal.aborted || isNochaError(error) && error.code === "aborted") return;\n if (isNochaError(error) && unreachableCodes2.has(error.code)) unreachable2 = true;\n engine.inline();\n }\n}\nfunction createVideoSettings(container, video, options = {}) {\n if (options.inline === true || unreachable2 || !capabilities.has("experiences")) return mountVideoSettings(container, video, options);\n let opening2 = false;\n const engine = buildVideoSettings(container, video, options, () => {\n if (opening2) return;\n if (unreachable2) {\n engine.inline();\n return;\n }\n opening2 = true;\n engine.busy(true);\n void choose(engine).finally(() => {\n opening2 = false;\n engine.busy(false);\n });\n });\n return engine.settings;\n}\n\n// src/index.ts\nfunction createFacades(context, shared) {\n const multiplayer = createMultiplayer(context, shared.hub);\n return {\n automations: createAutomations(context),\n connectors: createConnectors(context),\n backend: createBackend(context),\n ai: createAi(context),\n assets: createAssets(context),\n video: createVideo(context),\n state: createState(context, createStateWatch(context.invoke, subscribeBridgeEvents, multiplayer.onConnection)),\n memory: createMemory(context),\n database: Object.freeze({ ...createDatabase(context), watch: createDatabaseWatch(context, isDatabasePage, subscribeBridgeEvents, multiplayer.onConnection) }),\n search: createSearch(context),\n machine: createMachine(context),\n network: createNetwork(context),\n notifications: createNotifications(context),\n places: createPlaces(context),\n excerpts: createExcerpts(context),\n profiles: createProfiles(context),\n inbox: createInbox(context),\n email: createEmail(context),\n multiplayer,\n hardware: createHardware(context),\n device: createDevice(context, shared.motion),\n haptics: createHaptics(context),\n drive: createDrive(context),\n link: createLink(context),\n library: createLibrary(context),\n experiences: createExperiences(context),\n host: createHost(context),\n transfer: createTransfer(context),\n voice: createVoice(context)\n };\n}\nfunction createSdk(context, shared) {\n return Object.freeze({\n ...createFacades(context, shared),\n get mode() {\n return getNochaMode();\n },\n get hosting() {\n return currentHosting();\n },\n ready: hostingReady(),\n capabilities,\n use(usageId) {\n const cached2 = shared.bound.get(usageId);\n if (cached2) return cached2;\n const bound = createSdk(createContext(usageId), shared);\n shared.bound.set(usageId, bound);\n return bound;\n },\n assistant,\n access,\n workspace: workspace2,\n spaces,\n screens,\n navigation,\n gamepad: shared.gamepad,\n player,\n language,\n module: moduleFacade,\n context: experienceContext,\n viewport: shared.viewport,\n onEvent: shared.hub.onEvent\n });\n}\nvar nocha = createSdk(createContext(), {\n hub: createLiveHub(),\n motion: /* @__PURE__ */ new Set(),\n viewport: createViewport(),\n gamepad: createGamepad(),\n bound: /* @__PURE__ */ new Map()\n});\nvar index_default = nocha;\nexport {\n CHARACTER_PACKAGE_CARD_MAX_BYTES,\n CHARACTER_PACKAGE_FORMAT,\n CHARACTER_PACKAGE_IMAGE_MAX_BYTES,\n CHARACTER_PACKAGE_RIG_FORMATS,\n CONTENT_REFUSAL_CODES,\n EXPERIENCE_CALL_FILES_MAX_BYTES,\n EXPERIENCE_CALL_FILE_MAX_BYTES,\n EXPERIENCE_CALL_JSON_MAX_BYTES,\n EXPOSED_NAME_PATTERN,\n EXPOSED_OPERATION_PATTERN,\n HOST_ITEMS_MAX,\n HOST_KEYWORD_MAX_LENGTH,\n HOST_STAGE_MARGIN_MAX,\n LIBRARY_BOOKMARKED_CODES_MAX,\n LIBRARY_CATALOGUE_TAGS_MAX,\n LIBRARY_INTERFACE_SOURCES,\n LIBRARY_PAGE_DEFAULT,\n LIBRARY_PAGE_MAX,\n LIBRARY_PREFETCH_CODES_MAX,\n LIBRARY_SHELVES,\n LIBRARY_SURFACES,\n LINK_LABEL_MAX_LENGTH,\n LINK_URL_MAX_LENGTH,\n NOTIFICATION_SCHEDULE_MAX_LEAD_MS,\n NOTIFICATION_SCHEDULE_MAX_PENDING,\n NOTIFICATION_SCHEDULE_MIN_LEAD_MS,\n NochaError,\n PROFILES_PARTICIPANTS_MAX,\n PROFILE_AVATAR_SIZES,\n PROFILE_PARTICIPANT_PATTERN,\n RECORDED_AUDIO_MAX_BYTES,\n SPEECH_TAG_MAX_LENGTH,\n SPEECH_TAG_PATTERN,\n TRANSCRIPTION_AUDIO_TYPES,\n VIDEO_SETTINGS_EXPERIENCE,\n VIDEO_SETTINGS_OPERATION,\n VOICE_CALL_PERSONA_LIMITS,\n aliasVoiceEntries,\n assistantVoices,\n base64ToBytes,\n blobToDataUrl,\n bytesToBase64,\n classifyError,\n createImagineFavoritesToggle,\n createVideoSettings,\n createVoiceField,\n createVoicePicker,\n createWorkflowPicker,\n dataUrlToBlob,\n index_default as default,\n describeFailure,\n describeLiveMediaFailure,\n errorCodeOf,\n hasErrorCode,\n isContentRefusal,\n isEmotionSpeechTag,\n isLegacySpeechHost,\n isNochaError,\n isNochaErrorCode,\n isSoundEffectSpeechTag,\n isSpeechModelId,\n isSpeechTag,\n isSpeechVoiceAlias,\n isSpeechVoiceId,\n isVocalSpeechTag,\n legacySpeechHostCodes,\n liveMediaMessages,\n mountVideoSettings,\n mountVoiceBrowser,\n nocha,\n pauseFor,\n pickRandomVoices,\n pickVoice,\n reservedVideoPropertyKeys,\n retrying,\n retryingGeneration,\n shortVideoDescription,\n shouldRetry,\n speechAudioBlob,\n speechAudition,\n speechModelSettings,\n speechModelSupportsTags,\n speechTags,\n speechVoiceAges,\n speechVoiceAliases,\n speechVoiceDialects,\n speechVoiceEntry,\n speechVoiceGenders,\n speechVoiceLanguages,\n speechVoiceSettings,\n speechVoiceTraits,\n spokenVoiceName,\n stripSpeechTags,\n transferMimeTypes,\n validate_exports as validate,\n videoLocales,\n videoPropertyLabel,\n videoPropertyValueLabel,\n videoRouteLabel,\n videoSpeechFor,\n videoStageLabel,\n videoStepLabel,\n videoWorkflowDurations,\n videoWorkflowPresentation,\n voiceFavoriteEntry,\n voiceFits,\n voiceModelRecovery,\n voicePreviewMissingCodes,\n voiceVerifiedFor\n};\n';
6
6
 
7
7
  // src/vite-sources.ts
8
8
  function viteConfigMergeSource(root, module = join(root, "node_modules", "vite", "dist", "node", "index.js"), configLoader = "bundle", confinement) {
@@ -77,7 +77,24 @@ function nochaCheckPublicDirectory(file, ancestors = new Set()) {
77
77
  for (const name of nochaReaddirSync(path)) nochaCheckPublicDirectory(nochaResolvePath(path, name), ancestors);
78
78
  ancestors.delete(path);
79
79
  }
80
+ // Rolldown (Vite 8) gives build plugins no getWatchFiles(): record what vite:css reads (\`@import\`) itself.
81
+ function nochaRecordCssReads(plugins, reads) {
82
+ const css = plugins.find(plugin => plugin.name === "vite:css"), hook = css?.transform;
83
+ if (!hook || hook.nochaRecorded) return;
84
+ const handler = typeof hook === "function" ? hook : hook.handler;
85
+ const recorded = function (...args) {
86
+ const context = new Proxy(this, { get(target, key) {
87
+ if (key === "addWatchFile") return file => { reads.add(file); return target.addWatchFile(file); };
88
+ const value = Reflect.get(target, key);
89
+ return typeof value === "function" ? value.bind(target) : value;
90
+ } });
91
+ return handler.apply(context, args);
92
+ };
93
+ css.transform = typeof hook === "function" ? recorded : { ...hook, handler: recorded };
94
+ css.transform.nochaRecorded = true;
95
+ }
80
96
  function nochaSourceConfinement() {
97
+ const nochaCssReads = new Set();
81
98
  return {
82
99
  name: "nocha-source-confinement",
83
100
  enforce: "pre",
@@ -92,7 +109,9 @@ function nochaSourceConfinement() {
92
109
  : typeof inlineLimit === "function" ? inlineLimit(file, content) : inlineLimit === undefined ? undefined : content.length < Number(inlineLimit) };
93
110
  },
94
111
  },
112
+ buildStart() { nochaCssReads.clear(); },
95
113
  configResolved(config) {
114
+ nochaRecordCssReads(config.plugins, nochaCssReads);
96
115
  nochaViteRoot = config.root;
97
116
  nochaCacheRoots = [...new Set([nochaNormalPath(config.cacheDir), nochaRealPath(config.cacheDir)])];
98
117
  // Vite copies publicDir outside Rollup's graph, following file and directory symlinks.
@@ -141,7 +160,8 @@ function nochaSourceConfinement() {
141
160
  },
142
161
  generateBundle(_, bundle) {
143
162
  const modules = [...this.getModuleIds()].filter(id => !this.getModuleInfo(id)?.isExternal);
144
- const read = [...modules, ...this.getWatchFiles().filter(file => nochaStylesheet.test(file.split("?")[0])),
163
+ const watched = [...(typeof this.getWatchFiles === "function" ? this.getWatchFiles() : []), ...nochaCssReads];
164
+ const read = [...modules, ...watched.filter(file => nochaStylesheet.test(file.split("?")[0])),
145
165
  ...Object.values(bundle).flatMap(file => file.type === "asset" ? file.originalFileNames ?? [] : [])
146
166
  .map(name => nochaResolvePath(nochaViteRoot, name))];
147
167
  const outside = read.find(id => !nochaConfinedSource(id));