@frankieone/one-sdk 1.7.2 → 1.7.3-rc.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 (363) hide show
  1. package/dist/commit.txt +1 -1
  2. package/dist/esm/modules/biometrics/definition.d.ts +3 -3
  3. package/dist/esm/modules/biometrics/events.d.ts +2 -2
  4. package/dist/esm/modules/biometrics/index.d.ts +1 -1
  5. package/dist/esm/modules/biometrics/index.d.ts.map +1 -1
  6. package/dist/esm/modules/biometrics/index.js +12 -6
  7. package/dist/esm/modules/biometrics/index.js.map +1 -1
  8. package/dist/esm/modules/biometrics/parseConfiguration.d.ts +1 -1
  9. package/dist/esm/modules/biometrics/vendors/Incode/index.d.ts +3 -3
  10. package/dist/esm/modules/biometrics/vendors/OcrLabs/index.d.ts +2 -2
  11. package/dist/esm/modules/biometrics/vendors/Onfido/index.d.ts +5 -5
  12. package/dist/esm/modules/biometrics/vendors/common/createSession.d.ts +4 -4
  13. package/dist/esm/modules/biometrics/vendors/common/errors.d.ts +3 -3
  14. package/dist/esm/modules/biometrics/vendors/common/initProcess.d.ts +4 -4
  15. package/dist/esm/modules/biometrics/vendors/dummy-biometrics/index.d.ts +2 -2
  16. package/dist/esm/modules/business/actions/emitEvents.d.ts +2 -2
  17. package/dist/esm/modules/business/actions/search.d.ts +3 -3
  18. package/dist/esm/modules/business/actions/upload.d.ts +4 -4
  19. package/dist/esm/modules/business/definition.d.ts +4 -4
  20. package/dist/esm/modules/business/events.d.ts +1 -1
  21. package/dist/esm/modules/common/modules/HOF.d.ts +1 -1
  22. package/dist/esm/modules/common/modules/ReactiveStore.d.ts +1 -1
  23. package/dist/esm/modules/common/modules/defineModule.d.ts +1 -1
  24. package/dist/esm/modules/common/modules/error.d.ts +1 -1
  25. package/dist/esm/modules/common/modules/eventHub/index.d.ts.map +1 -1
  26. package/dist/esm/modules/common/modules/eventHub/index.js +14 -6
  27. package/dist/esm/modules/common/modules/eventHub/index.js.map +1 -1
  28. package/dist/esm/modules/common/modules/eventHub/types.d.ts +2 -2
  29. package/dist/esm/modules/common/modules/eventHub/windowEventHub.d.ts +1 -1
  30. package/dist/esm/modules/common/modules/eventHub/windowEventHub.d.ts.map +1 -1
  31. package/dist/esm/modules/common/modules/eventHub/windowEventHub.js +4 -2
  32. package/dist/esm/modules/common/modules/eventHub/windowEventHub.js.map +1 -1
  33. package/dist/esm/modules/common/modules/objectUtils.d.ts +1 -1
  34. package/dist/esm/modules/common/modules/vendorLoading.d.ts +4 -4
  35. package/dist/esm/modules/common/shared/models/DeviceCheck.d.ts +1 -1
  36. package/dist/esm/modules/common/shared/models/UBOData.d.ts +3 -3
  37. package/dist/esm/modules/common/types/Accessors.d.ts +1 -1
  38. package/dist/esm/modules/common/types/oneSDKModules/baseParameters.types.d.ts +6 -6
  39. package/dist/esm/modules/common/types/oneSDKModules/contextObject.d.ts +1 -1
  40. package/dist/esm/modules/common/types/oneSDKModules/definition.types.d.ts +2 -2
  41. package/dist/esm/modules/common/types/oneSDKModules/initialiseFunction.d.ts +2 -2
  42. package/dist/esm/modules/common/types/oneSDKModules/typeSystem.types.d.ts +1 -1
  43. package/dist/esm/modules/common/types/oneSDKVendorWrappers/initialiseFunction.d.ts +1 -1
  44. package/dist/esm/modules/common/types/recipeConfiguration.types.d.ts +5 -5
  45. package/dist/esm/modules/common/vendors/form/promisifyForm.d.ts +2 -2
  46. package/dist/esm/modules/common/vendors/form/useForm.d.ts +4 -4
  47. package/dist/esm/modules/common/vendors/incode/createEventHandlers.d.ts +4 -4
  48. package/dist/esm/modules/common/vendors/incode/index.d.ts +1 -1
  49. package/dist/esm/modules/common/vendors/incode/startCamera.d.ts +3 -3
  50. package/dist/esm/modules/common/vendors/onfido/index.d.ts +3 -3
  51. package/dist/esm/modules/common/vendors/onfido/onfido.types.d.ts +1 -1
  52. package/dist/esm/modules/config/modules.d.ts +18 -18
  53. package/dist/esm/modules/device/definition.d.ts +2 -2
  54. package/dist/esm/modules/device/events.d.ts +1 -1
  55. package/dist/esm/modules/device/index.d.ts +4 -4
  56. package/dist/esm/modules/device/index.d.ts.map +1 -1
  57. package/dist/esm/modules/device/index.js +19 -16
  58. package/dist/esm/modules/device/index.js.map +1 -1
  59. package/dist/esm/modules/device/parseConfiguration.d.ts +1 -1
  60. package/dist/esm/modules/device/vendors/Sardine.d.ts +6 -6
  61. package/dist/esm/modules/device/vendors/Threatmetrix/index.d.ts +4 -4
  62. package/dist/esm/modules/exports.d.ts +1 -1
  63. package/dist/esm/modules/features.config.d.ts +1 -1
  64. package/dist/esm/modules/federation/definition.d.ts +2 -2
  65. package/dist/esm/modules/federation/index.d.ts +2 -2
  66. package/dist/esm/modules/federation/index.d.ts.map +1 -1
  67. package/dist/esm/modules/federation/index.js +15 -14
  68. package/dist/esm/modules/federation/index.js.map +1 -1
  69. package/dist/esm/modules/federation/parseConfiguration.d.ts +1 -1
  70. package/dist/esm/modules/federation/vendors/Singpass.d.ts +5 -5
  71. package/dist/esm/modules/form/definition.d.ts +7 -7
  72. package/dist/esm/modules/form/events.d.ts +3 -3
  73. package/dist/esm/modules/form/index.d.ts.map +1 -1
  74. package/dist/esm/modules/form/index.js +5 -3
  75. package/dist/esm/modules/form/index.js.map +1 -1
  76. package/dist/esm/modules/form/validateConfiguration.d.ts +1 -1
  77. package/dist/esm/modules/form/vendors/formio/formioSdk.d.ts +1 -1
  78. package/dist/esm/modules/form/vendors/formio/index.d.ts +3 -3
  79. package/dist/esm/modules/form/vendors/formio/transformers/assignFormioDataToIndividualModule.d.ts +1 -1
  80. package/dist/esm/modules/form/vendors/formio/transformers/assignIndividualDataToFormioSdk.d.ts +1 -1
  81. package/dist/esm/modules/form/vendors/legacy/index.d.ts +5 -5
  82. package/dist/esm/modules/form/vendors/legacy/legacyUIEvents.types.d.ts +5 -5
  83. package/dist/esm/modules/form/vendors/legacy/loadLegacyUI.d.ts +3 -3
  84. package/dist/esm/modules/form/vendors/react/App.d.ts +2 -2
  85. package/dist/esm/modules/form/vendors/react/appConfig.type.d.ts +2 -2
  86. package/dist/esm/modules/form/vendors/react/components/base/SharedInput/Input.d.ts +1 -1
  87. package/dist/esm/modules/form/vendors/react/components/view/ActionFormField/ActionFormField.js +2 -2
  88. package/dist/esm/modules/form/vendors/react/components/view/ActionFormField/ActionFormField.js.map +1 -1
  89. package/dist/esm/modules/form/vendors/react/components/view/FrankieAddress/FrankieAddress.js +2 -2
  90. package/dist/esm/modules/form/vendors/react/components/view/FrankieAddress/FrankieAddress.js.map +1 -1
  91. package/dist/esm/modules/form/vendors/react/components/view/FrankieFormMapper/FrankieFormMapper.d.ts +1 -1
  92. package/dist/esm/modules/form/vendors/react/constants/form.const.d.ts +1 -0
  93. package/dist/esm/modules/form/vendors/react/constants/form.const.d.ts.map +1 -1
  94. package/dist/esm/modules/form/vendors/react/constants/form.const.js +1 -0
  95. package/dist/esm/modules/form/vendors/react/constants/form.const.js.map +1 -1
  96. package/dist/esm/modules/form/vendors/react/constants/icons.d.ts +62 -62
  97. package/dist/esm/modules/form/vendors/react/constants/icons.d.ts.map +1 -1
  98. package/dist/esm/modules/form/vendors/react/constants/icons.js +74 -62
  99. package/dist/esm/modules/form/vendors/react/constants/icons.js.map +1 -1
  100. package/dist/esm/modules/form/vendors/react/constants/layoutMapper.const.d.ts +7 -7
  101. package/dist/esm/modules/form/vendors/react/constants/staticScreenMapper.const.d.ts +3 -3
  102. package/dist/esm/modules/form/vendors/react/features/Consent/Consent.d.ts.map +1 -1
  103. package/dist/esm/modules/form/vendors/react/features/Consent/Consent.js +31 -14
  104. package/dist/esm/modules/form/vendors/react/features/Consent/Consent.js.map +1 -1
  105. package/dist/esm/modules/form/vendors/react/features/Consent/hostedBusinessConsent.config.d.ts +1 -1
  106. package/dist/esm/modules/form/vendors/react/features/DocUpload/FileUploader/Main.d.ts +1 -1
  107. package/dist/esm/modules/form/vendors/react/features/DocUpload/FileUploader/Progress.d.ts +1 -1
  108. package/dist/esm/modules/form/vendors/react/features/DocUpload/FileUploader/Review.d.ts +1 -1
  109. package/dist/esm/modules/form/vendors/react/features/DocUpload/FileUploader/index.d.ts +1 -1
  110. package/dist/esm/modules/form/vendors/react/features/IdPreps/driversLicense.config.d.ts +1 -1
  111. package/dist/esm/modules/form/vendors/react/features/IdPreps/mediCare.config.d.ts +1 -1
  112. package/dist/esm/modules/form/vendors/react/features/IdPreps/passport.config.d.ts +1 -1
  113. package/dist/esm/modules/form/vendors/react/features/IdSelection/idSelection.config.d.ts +6 -6
  114. package/dist/esm/modules/form/vendors/react/features/IdSelection/idSelection.const.d.ts +4 -4
  115. package/dist/esm/modules/form/vendors/react/features/IdSelection/manualIdSelection.config.d.ts +47 -47
  116. package/dist/esm/modules/form/vendors/react/features/PersonalDetails/PersonalDetails.js +1 -1
  117. package/dist/esm/modules/form/vendors/react/features/PersonalDetails/PersonalDetails.js.map +1 -1
  118. package/dist/esm/modules/form/vendors/react/features/PersonalDetails/personalDetails.config.d.ts +392 -392
  119. package/dist/esm/modules/form/vendors/react/features/Review/Review.d.ts.map +1 -1
  120. package/dist/esm/modules/form/vendors/react/features/Review/Review.js +5 -0
  121. package/dist/esm/modules/form/vendors/react/features/Review/Review.js.map +1 -1
  122. package/dist/esm/modules/form/vendors/react/features/Review/review.config.d.ts.map +1 -1
  123. package/dist/esm/modules/form/vendors/react/features/Review/review.config.js +0 -1
  124. package/dist/esm/modules/form/vendors/react/features/Review/review.config.js.map +1 -1
  125. package/dist/esm/modules/form/vendors/react/features/ReviewDocument/ReviewDocument.d.ts.map +1 -1
  126. package/dist/esm/modules/form/vendors/react/features/ReviewDocument/ReviewDocument.js +3 -2
  127. package/dist/esm/modules/form/vendors/react/features/ReviewDocument/ReviewDocument.js.map +1 -1
  128. package/dist/esm/modules/form/vendors/react/features/Welcome/hostedBusinessWelcome.config.d.ts +1 -1
  129. package/dist/esm/modules/form/vendors/react/features/Welcome/manualWelcome.config.d.ts +4 -4
  130. package/dist/esm/modules/form/vendors/react/features/Welcome/welcome.config.d.ts +1 -1
  131. package/dist/esm/modules/form/vendors/react/hooks/useConfigFactory.hooks.js +1 -1
  132. package/dist/esm/modules/form/vendors/react/hooks/useConfigFactory.hooks.js.map +1 -1
  133. package/dist/esm/modules/form/vendors/react/hooks/useConsents.hook.d.ts +6 -0
  134. package/dist/esm/modules/form/vendors/react/hooks/useConsents.hook.d.ts.map +1 -0
  135. package/dist/esm/modules/form/vendors/react/hooks/useConsents.hook.js +44 -0
  136. package/dist/esm/modules/form/vendors/react/hooks/useConsents.hook.js.map +1 -0
  137. package/dist/esm/modules/form/vendors/react/hooks/useEventContext.d.ts +3 -3
  138. package/dist/esm/modules/form/vendors/react/hooks/useFormMapper.hook.d.ts +526 -526
  139. package/dist/esm/modules/form/vendors/react/hooks/useManualConfigFactory.hook.js +1 -1
  140. package/dist/esm/modules/form/vendors/react/hooks/useManualConfigFactory.hook.js.map +1 -1
  141. package/dist/esm/modules/form/vendors/react/hooks/useManualWrapperFactory.hook.d.ts +829 -1
  142. package/dist/esm/modules/form/vendors/react/hooks/useManualWrapperFactory.hook.d.ts.map +1 -1
  143. package/dist/esm/modules/form/vendors/react/hooks/useManualWrapperFactory.hook.js +11 -2
  144. package/dist/esm/modules/form/vendors/react/hooks/useManualWrapperFactory.hook.js.map +1 -1
  145. package/dist/esm/modules/form/vendors/react/hooks/usePersonalDetailsUpdateFactory.hook.d.ts +1 -1
  146. package/dist/esm/modules/form/vendors/react/hooks/usePersonalDetailsUpdateFactory.hook.js +1 -1
  147. package/dist/esm/modules/form/vendors/react/hooks/usePersonalDetailsUpdateFactory.hook.js.map +1 -1
  148. package/dist/esm/modules/form/vendors/react/hooks/useReviewUpdateFactory.hook.d.ts +6 -6
  149. package/dist/esm/modules/form/vendors/react/index.d.ts +4 -4
  150. package/dist/esm/modules/form/vendors/react/model/address.model.d.ts +2 -2
  151. package/dist/esm/modules/form/vendors/react/model/googleAddress.model.d.ts +1 -1
  152. package/dist/esm/modules/form/vendors/react/model/idDetails.model.d.ts +1 -1
  153. package/dist/esm/modules/form/vendors/react/model/personalDetails.model.d.ts +1 -1
  154. package/dist/esm/modules/form/vendors/react/model/review.model.d.ts +2 -2
  155. package/dist/esm/modules/form/vendors/react/types/pages.type.d.ts +1 -1
  156. package/dist/esm/modules/form/vendors/react/utils/layout.util.d.ts +1 -1
  157. package/dist/esm/modules/form/vendors/react/utils/object.util.d.ts +2 -2
  158. package/dist/esm/modules/form/vendors/react/utils/object.util.js +1 -1
  159. package/dist/esm/modules/form/vendors/react/utils/object.util.js.map +1 -1
  160. package/dist/esm/modules/frankie-client/ClientsDictionary.d.ts +1 -1
  161. package/dist/esm/modules/frankie-client/DummyFrankieApiClient.d.ts +1 -1
  162. package/dist/esm/modules/frankie-client/FrankieApiClient.d.ts +2 -2
  163. package/dist/esm/modules/frankie-client/clients/ApplicantClient.d.ts +4 -4
  164. package/dist/esm/modules/frankie-client/clients/BusinessClient.d.ts +1 -1
  165. package/dist/esm/modules/frankie-client/clients/FederationClient.d.ts +1 -1
  166. package/dist/esm/modules/frankie-client/clients/IDVClient.d.ts +2 -2
  167. package/dist/esm/modules/frankie-client/clients/OCRClient.d.ts +1 -1
  168. package/dist/esm/modules/frankie-client/clients/SupportingDocumentsClient.d.ts +3 -3
  169. package/dist/esm/modules/frankie-client/clients/TelemetryEventsClient.d.ts +1 -1
  170. package/dist/esm/modules/frankie-client/index.d.ts +1 -1
  171. package/dist/esm/modules/frankie-client/mocks/federation/index.d.ts +1 -1
  172. package/dist/esm/modules/frankie-client/mocks/idvAndBiometrics/idvSubmission.d.ts +4 -4
  173. package/dist/esm/modules/frankie-client/mocks/individual/loadIndividual.d.ts +1 -1
  174. package/dist/esm/modules/frankie-client/mocks/individual/resolveDocumentData.d.ts +2 -2
  175. package/dist/esm/modules/frankie-client/mocks/individual/resolveIndividualData.d.ts +3 -3
  176. package/dist/esm/modules/frankie-client/mocks/ocr/ocrSubmission.d.ts +1 -1
  177. package/dist/esm/modules/frankie-client/mocks/options/simplified/idvFlow.d.ts +4 -4
  178. package/dist/esm/modules/frankie-client/mocks/options/simplified/ocrFlow.d.ts +4 -4
  179. package/dist/esm/modules/frankie-client/mocks/options/simplified/preloadedIndividual.d.ts +5 -5
  180. package/dist/esm/modules/frankie-client/mocks/storage/mockStorage.d.ts +1 -1
  181. package/dist/esm/modules/idv/actions/mount.d.ts +3 -3
  182. package/dist/esm/modules/idv/definition.types.d.ts +8 -8
  183. package/dist/esm/modules/idv/events.types.d.ts +5 -5
  184. package/dist/esm/modules/idv/index.d.ts.map +1 -1
  185. package/dist/esm/modules/idv/index.js +9 -5
  186. package/dist/esm/modules/idv/index.js.map +1 -1
  187. package/dist/esm/modules/idv/parseConfiguration.d.ts +1 -1
  188. package/dist/esm/modules/idv/vendors/Incode/index.d.ts +5 -5
  189. package/dist/esm/modules/idv/vendors/Mastercard/index.d.ts +2 -2
  190. package/dist/esm/modules/idv/vendors/OcrLabs/endFlow.d.ts +4 -4
  191. package/dist/esm/modules/idv/vendors/OcrLabs/index.d.ts +3 -3
  192. package/dist/esm/modules/idv/vendors/OcrLabs/startDummyFlow.d.ts +2 -2
  193. package/dist/esm/modules/idv/vendors/OcrLabs/startFlow.d.ts +2 -2
  194. package/dist/esm/modules/idv/vendors/Onfido/index.d.ts +4 -4
  195. package/dist/esm/modules/idv/vendors/common/checkStatusEventMapping.d.ts +3 -3
  196. package/dist/esm/modules/idv/vendors/common/iframeUtils/createIframe.d.ts +2 -2
  197. package/dist/esm/modules/idv/vendors/common/iframeUtils/createIframeEventListener.d.ts +1 -1
  198. package/dist/esm/modules/idv/vendors/common/iframeUtils/defineIframeIDVWrapper.d.ts +7 -7
  199. package/dist/esm/modules/idv/vendors/common/iframeUtils/updateIndividualModuleState.d.ts +3 -3
  200. package/dist/esm/modules/idv/vendors/common/initialiseSession.d.ts +4 -4
  201. package/dist/esm/modules/idv/vendors/common/windowUtils/createWindow.d.ts +1 -1
  202. package/dist/esm/modules/index.d.ts +4 -4
  203. package/dist/esm/modules/individual/actions/addReference.d.ts +3 -3
  204. package/dist/esm/modules/individual/actions/addresses.d.ts +2 -2
  205. package/dist/esm/modules/individual/actions/consents.d.ts +1 -1
  206. package/dist/esm/modules/individual/actions/documents.d.ts +2 -2
  207. package/dist/esm/modules/individual/actions/email.d.ts +2 -2
  208. package/dist/esm/modules/individual/actions/emitEvents.d.ts +3 -3
  209. package/dist/esm/modules/individual/actions/phoneNumber.d.ts +2 -2
  210. package/dist/esm/modules/individual/actions/profileType.d.ts +2 -2
  211. package/dist/esm/modules/individual/actions/search.d.ts +3 -3
  212. package/dist/esm/modules/individual/actions/submit.d.ts +5 -5
  213. package/dist/esm/modules/individual/definition.d.ts +8 -8
  214. package/dist/esm/modules/individual/events.d.ts +1 -1
  215. package/dist/esm/modules/meta.json +1 -1
  216. package/dist/esm/modules/ocr/actions/mount.d.ts +4 -4
  217. package/dist/esm/modules/ocr/actions/start.d.ts +7 -7
  218. package/dist/esm/modules/ocr/definition.d.ts +5 -5
  219. package/dist/esm/modules/ocr/events.d.ts +2 -2
  220. package/dist/esm/modules/ocr/index.d.ts +11 -11
  221. package/dist/esm/modules/ocr/index.d.ts.map +1 -1
  222. package/dist/esm/modules/ocr/index.js +6 -3
  223. package/dist/esm/modules/ocr/index.js.map +1 -1
  224. package/dist/esm/modules/ocr/vendors/Incode/index.d.ts +3 -3
  225. package/dist/esm/modules/ocr/vendors/Onfido/index.d.ts +2 -2
  226. package/dist/esm/modules/ocr/vendors/common/createSession.d.ts +4 -4
  227. package/dist/esm/modules/ocr/vendors/common/initProcess.d.ts +2 -2
  228. package/dist/esm/modules/ocr/vendors/common/mutationObserver.d.ts +2 -2
  229. package/dist/esm/modules/ocr/vendors/common/statusEvaluators.d.ts +5 -5
  230. package/dist/esm/modules/ocr/vendors/dummy-ocr/index.d.ts +3 -3
  231. package/dist/esm/modules/sdk/initialisation/componentLoader.d.ts +2 -2
  232. package/dist/esm/modules/sdk/initialisation/configurationParser.d.ts +1 -1
  233. package/dist/esm/modules/sdk/initialisation/sharedDependencies.d.ts +4 -4
  234. package/dist/esm/modules/sdk/initialisation/sharedDependencies.d.ts.map +1 -1
  235. package/dist/esm/modules/sdk/initialisation/sharedDependencies.js +20 -8
  236. package/dist/esm/modules/sdk/initialisation/sharedDependencies.js.map +1 -1
  237. package/dist/esm/modules/sdk/types/globalEvents.d.ts +2 -2
  238. package/dist/esm/modules/sdk/types/oneSDK.d.ts +5 -5
  239. package/dist/esm/modules/sdk/types/oneSDKParameters.d.ts +2 -2
  240. package/dist/esm/modules/session/SessionContext.d.ts +1 -1
  241. package/dist/esm/modules/session/definition.d.ts +3 -3
  242. package/dist/esm/modules/session/index.d.ts +5 -5
  243. package/dist/esm/modules/session/index.d.ts.map +1 -1
  244. package/dist/esm/modules/session/index.js +24 -16
  245. package/dist/esm/modules/session/index.js.map +1 -1
  246. package/dist/esm/modules/session/types/module.d.ts +1 -1
  247. package/dist/esm/modules/types.d.ts +13 -13
  248. package/dist/esm/modules/workflow/definition.types.d.ts +1 -1
  249. package/dist/esm/modules/workflow/index.d.ts +1 -1
  250. package/dist/version.txt +0 -1
  251. package/package.json +8 -5
  252. package/dist/esm/node_modules/@reduxjs/toolkit/dist/uncheckedindexed.d.ts +0 -6
  253. package/dist/esm/node_modules/@reduxjs/toolkit/dist/uncheckedindexed.d.ts.map +0 -1
  254. package/dist/umd/080b774e0f4f9c679e85.svg +0 -45
  255. package/dist/umd/0c9574c81d7d87e9ccd3.svg +0 -34
  256. package/dist/umd/0cd8e74f8a68e0b1ae14.svg +0 -3
  257. package/dist/umd/10183d99573bcd186235.svg +0 -5
  258. package/dist/umd/124.js +0 -2
  259. package/dist/umd/124.js.map +0 -1
  260. package/dist/umd/1c9c1ef03c6dd661b89b.woff +0 -0
  261. package/dist/umd/1df3f35eac93c61986b1.svg +0 -60
  262. package/dist/umd/1f76ff5e84787152adc5.svg +0 -50
  263. package/dist/umd/2451ce2859277292a2a3.svg +0 -4
  264. package/dist/umd/24c67c1821feba22f3f7.svg +0 -5
  265. package/dist/umd/2546128ef2e2d56276b7.svg +0 -5
  266. package/dist/umd/26a8e1ce5e5578874420.woff2 +0 -0
  267. package/dist/umd/2f32844e02839dd608a4.svg +0 -4
  268. package/dist/umd/329d07fd3f40d3967c81.svg +0 -4
  269. package/dist/umd/32cb4eea6ca1acb9f788.svg +0 -45
  270. package/dist/umd/3443b53b9b1a00c340f7.svg +0 -27
  271. package/dist/umd/34fe2370aa5e73787795.svg +0 -30
  272. package/dist/umd/36ddfb506829cb8cde72.svg +0 -113
  273. package/dist/umd/396cc7cc5e61acfa8fc8.svg +0 -15
  274. package/dist/umd/3a660ff8435efa515e98.svg +0 -4
  275. package/dist/umd/3b687e48c6bb765ed976.svg +0 -5
  276. package/dist/umd/3d245ccf2dde73ceca07.svg +0 -114
  277. package/dist/umd/42caa2dd6b4f0de68157.svg +0 -51
  278. package/dist/umd/463e54e898297e314139.svg +0 -81
  279. package/dist/umd/4ac349963383ebda508b.svg +0 -50
  280. package/dist/umd/4db0db393dfe2f9f90c1.svg +0 -60
  281. package/dist/umd/4ee01199f6f6b7e6fb24.svg +0 -195
  282. package/dist/umd/4ff338b86cdba19934cf.svg +0 -86
  283. package/dist/umd/58b74e594849c43b2248.woff2 +0 -0
  284. package/dist/umd/5c23763467ce9cfda119.svg +0 -41
  285. package/dist/umd/5ddf80d7ddb1d1c5a0bc.woff +0 -0
  286. package/dist/umd/6375eb14534238c06a4b.svg +0 -27
  287. package/dist/umd/6558f8e71743e073c18b.svg +0 -3
  288. package/dist/umd/67cbc8178ea76ef0d8b4.svg +0 -4
  289. package/dist/umd/6c874e1a72a4fa9eeed8.woff2 +0 -0
  290. package/dist/umd/71b71503b4f733079331.svg +0 -3
  291. package/dist/umd/7f6d57b96337c21c053d.woff +0 -0
  292. package/dist/umd/8053f51266aa9d864691.svg +0 -4
  293. package/dist/umd/80929602ea97f94dc18c.svg +0 -65
  294. package/dist/umd/8a06059b84b1aa2bf661.svg +0 -29
  295. package/dist/umd/8f10666ff21ef0238370.svg +0 -13
  296. package/dist/umd/949.js +0 -3
  297. package/dist/umd/949.js.LICENSE.txt +0 -60
  298. package/dist/umd/949.js.map +0 -1
  299. package/dist/umd/9d49ce231cb895b6ef29.svg +0 -50
  300. package/dist/umd/9dee3446081d7d47623b.svg +0 -4
  301. package/dist/umd/a96ec21d243a49916487.svg +0 -47
  302. package/dist/umd/ac457c4800183645b1ad.svg +0 -45
  303. package/dist/umd/af823d3a76ce1e2e36af.woff +0 -0
  304. package/dist/umd/aff615d38d2fce3f82b2.svg +0 -83
  305. package/dist/umd/bc42b55176ae1021b9e4.svg +0 -80
  306. package/dist/umd/biometrics-dummy.js +0 -2
  307. package/dist/umd/biometrics-dummy.js.map +0 -1
  308. package/dist/umd/biometrics-incode.js +0 -2
  309. package/dist/umd/biometrics-incode.js.map +0 -1
  310. package/dist/umd/biometrics-ocrlabs.js +0 -2
  311. package/dist/umd/biometrics-ocrlabs.js.map +0 -1
  312. package/dist/umd/biometrics-onfido.js +0 -2
  313. package/dist/umd/biometrics-onfido.js.map +0 -1
  314. package/dist/umd/c0dede047f9a2b7c1309.svg +0 -51
  315. package/dist/umd/c16900512bb2f899c7eb.svg +0 -5
  316. package/dist/umd/c7a05c7d7d1f9347ae1b.svg +0 -53
  317. package/dist/umd/ce5b46abe62641bddb20.svg +0 -5
  318. package/dist/umd/d15d58eb544d245877e2.svg +0 -16
  319. package/dist/umd/d216030199c873b0bf41.woff2 +0 -0
  320. package/dist/umd/d563d85c23bcbd268d5e.svg +0 -30
  321. package/dist/umd/d70a547a409868c43a95.svg +0 -43
  322. package/dist/umd/d9ed930ae3bb52f2abe1.svg +0 -4
  323. package/dist/umd/dc45d5d9fb4b8959e156.svg +0 -24
  324. package/dist/umd/dd199fa4125e4ebef289.svg +0 -67
  325. package/dist/umd/dddc2581e578cfb3b997.svg +0 -195
  326. package/dist/umd/device-sardine.js +0 -2
  327. package/dist/umd/device-sardine.js.map +0 -1
  328. package/dist/umd/device-threatmetrix.js +0 -2
  329. package/dist/umd/device-threatmetrix.js.map +0 -1
  330. package/dist/umd/df83da88c151bcf97231.svg +0 -45
  331. package/dist/umd/e7ac03e5736bea4d6346.svg +0 -53
  332. package/dist/umd/e84075ff43e508e4fbd5.svg +0 -5
  333. package/dist/umd/e85b9f93aac09995bad2.svg +0 -80
  334. package/dist/umd/ef3c33f0d919896ee0bf.svg +0 -25
  335. package/dist/umd/f22fe25046b4ca4a969a.svg +0 -65
  336. package/dist/umd/f4a5163b8f91c2c66892.svg +0 -4
  337. package/dist/umd/f670207e1feb7ec4f6d4.svg +0 -5
  338. package/dist/umd/f75020be237d9de68d86.svg +0 -192
  339. package/dist/umd/fc7c8869af28cb1b9c21.svg +0 -5
  340. package/dist/umd/fdb0a109281e6c12eff6.svg +0 -75
  341. package/dist/umd/form-formio.js +0 -2
  342. package/dist/umd/form-formio.js.map +0 -1
  343. package/dist/umd/form-legacy.js +0 -2
  344. package/dist/umd/form-legacy.js.map +0 -1
  345. package/dist/umd/form-react.js +0 -2
  346. package/dist/umd/form-react.js.map +0 -1
  347. package/dist/umd/idv-incode.js +0 -2
  348. package/dist/umd/idv-incode.js.map +0 -1
  349. package/dist/umd/idv-mastercard.js +0 -2
  350. package/dist/umd/idv-mastercard.js.map +0 -1
  351. package/dist/umd/idv-ocrlabs.js +0 -2
  352. package/dist/umd/idv-ocrlabs.js.map +0 -1
  353. package/dist/umd/idv-onfido.js +0 -2
  354. package/dist/umd/idv-onfido.js.map +0 -1
  355. package/dist/umd/ocr-dummy.js +0 -2
  356. package/dist/umd/ocr-dummy.js.map +0 -1
  357. package/dist/umd/ocr-incode.js +0 -2
  358. package/dist/umd/ocr-incode.js.map +0 -1
  359. package/dist/umd/ocr-onfido.js +0 -2
  360. package/dist/umd/ocr-onfido.js.map +0 -1
  361. package/dist/umd/oneSdk.umd.js +0 -3
  362. package/dist/umd/oneSdk.umd.js.LICENSE.txt +0 -8
  363. package/dist/umd/oneSdk.umd.js.map +0 -1
@@ -1,2 +0,0 @@
1
- "use strict";(self.webpackChunkOneSdk=self.webpackChunkOneSdk||[]).push([[877],{1768:(e,t,n)=>{n.r(t),n.d(t,{initialise:()=>h});var r,i=n(8016),o=n(2365),a=n(3655),s=n(5473),c=n(9188);r=()=>(()=>{var e={6010:(e,t,n)=>{const r=n(6284);e.exports=new r},7329:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;const i=r(n(1227)),o="awaitqueue";t.Logger=class{constructor(e){e?(this._debug=(0,i.default)(`${o}:${e}`),this._warn=(0,i.default)(`${o}:WARN:${e}`),this._error=(0,i.default)(`${o}:ERROR:${e}`)):(this._debug=(0,i.default)(o),this._warn=(0,i.default)(`${o}:WARN`),this._error=(0,i.default)(`${o}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}},2186:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AwaitQueue=t.AwaitQueueRemovedTaskError=t.AwaitQueueStoppedError=void 0;const r=new(n(7329).Logger);class i extends Error{constructor(e){super(null!=e?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,i)}}t.AwaitQueueStoppedError=i;class o extends Error{constructor(e){super(null!=e?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,o)}}t.AwaitQueueRemovedTaskError=o,t.AwaitQueue=class{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}async push(e,t){if(t=null!=t?t:e.name,r.debug(`push() [name:${t}]`),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise(((n,i)=>{const o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),r.debug(`resolving task [name:${o.name}]`),n(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),r.debug(`rejecting task [name:${o.name}]: %s`,String(e)),i(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(o.id,o),1===this.pendingTasks.size&&this.execute(o)}))}stop(){r.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())r.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new i);this.stopping=!1}remove(e){r.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new o):r.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let t=0;return Array.from(this.pendingTasks.values()).map((n=>({idx:t++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0})))}async execute(e){if(r.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}}},1206:function(e){e.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=90)}({17:function(e,t,n){t.__esModule=!0,t.default=void 0;var r=n(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var n=t.match(e);return n&&n.length>0&&n[1]||""},e.getSecondMatch=function(e,t){var n=t.match(e);return n&&n.length>1&&n[2]||""},e.matchAndReturnConst=function(e,t,n){if(e.test(t))return n},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,n,r){void 0===r&&(r=!1);var i=e.getVersionPrecision(t),o=e.getVersionPrecision(n),a=Math.max(i,o),s=0,c=e.map([t,n],(function(t){var n=a-e.getVersionPrecision(t),r=t+new Array(n+1).join(".0");return e.map(r.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(r&&(s=a-Math.min(i,o)),a-=1;a>=s;){if(c[0][a]>c[1][a])return 1;if(c[0][a]===c[1][a]){if(a===s)return 0;a-=1}else if(c[0][a]<c[1][a])return-1}},e.map=function(e,t){var n,r=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(n=0;n<e.length;n+=1)r.push(t(e[n]));return r},e.find=function(e,t){var n,r;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(n=0,r=e.length;n<r;n+=1){var i=e[n];if(t(i,n))return i}},e.assign=function(e){for(var t,n,r=e,i=arguments.length,o=new Array(i>1?i-1:0),a=1;a<i;a++)o[a-1]=arguments[a];if(Object.assign)return Object.assign.apply(Object,[e].concat(o));var s=function(){var e=o[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach((function(t){r[t]=e[t]}))};for(t=0,n=o.length;t<n;t+=1)s();return e},e.getBrowserAlias=function(e){return r.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return r.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default},18:function(e,t,n){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,n){t.__esModule=!0,t.default=void 0;var r,i=(r=n(91))&&r.__esModule?r:{default:r},o=n(18),a=function(){function e(){}var t;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},(t=[{key:"BROWSER_MAP",get:function(){return o.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return o.ENGINE_MAP}},{key:"OS_MAP",get:function(){return o.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return o.PLATFORMS_MAP}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(e,t),e}();t.default=a,e.exports=t.default},91:function(e,t,n){t.__esModule=!0,t.default=void 0;var r=c(n(92)),i=c(n(93)),o=c(n(94)),a=c(n(95)),s=c(n(17));function c(e){return e&&e.__esModule?e:{default:e}}var u=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=s.default.find(r.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=s.default.find(i.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=s.default.find(o.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=s.default.find(a.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return s.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,n={},r=0,i={},o=0;if(Object.keys(e).forEach((function(t){var a=e[t];"string"==typeof a?(i[t]=a,o+=1):"object"==typeof a&&(n[t]=a,r+=1)})),r>0){var a=Object.keys(n),c=s.default.find(a,(function(e){return t.isOS(e)}));if(c){var u=this.satisfies(n[c]);if(void 0!==u)return u}var d=s.default.find(a,(function(e){return t.isPlatform(e)}));if(d){var l=this.satisfies(n[d]);if(void 0!==l)return l}}if(o>0){var p=Object.keys(i),h=s.default.find(p,(function(e){return t.isBrowser(e,!0)}));if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var n=this.getBrowserName().toLowerCase(),r=e.toLowerCase(),i=s.default.getBrowserTypeByAlias(r);return t&&i&&(r=i.toLowerCase()),r===n},t.compareVersion=function(e){var t=[0],n=e,r=!1,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(n=e.substr(1),"="===e[1]?(r=!0,n=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?n=e.substr(1):"~"===e[0]&&(r=!0,n=e.substr(1)),t.indexOf(s.default.compareVersions(i,n,r))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=u,e.exports=t.default},92:function(e,t,n){t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},o=/version\/(\d+(\.?_?\d+)+)/i,a=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},n=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},n=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},n=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},n=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},n=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},n=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},n=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},n=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},n=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},n=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},n=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},n=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},n=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},n=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},n=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return n&&(t.version=n),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},n=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},n=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},n=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},n=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},n=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},n=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},n=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},n=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},n=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},n=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},n=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},n=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},n=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){var t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe:function(e){var t={name:"Android Browser"},n=i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},n=i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},n=i.default.getFirstMatch(o,e);return n&&(t.version=n),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=a,e.exports=t.default},93:function(e,t,n){t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},o=n(18),a=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:o.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),n=i.default.getWindowsVersionName(t);return{name:o.OS_MAP.Windows,version:t,versionName:n}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:o.OS_MAP.iOS},n=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return n&&(t.version=n),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),n=i.default.getMacOSVersionName(t),r={name:o.OS_MAP.MacOS,version:t};return n&&(r.versionName=n),r}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:o.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),n=e.test(/android/i);return t&&n},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),n=i.default.getAndroidVersionName(t),r={name:o.OS_MAP.Android,version:t};return n&&(r.versionName=n),r}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),n={name:o.OS_MAP.WebOS};return t&&t.length&&(n.version=t),n}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:o.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:o.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:o.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.PlayStation4,version:t}}}];t.default=a,e.exports=t.default},94:function(e,t,n){t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},o=n(18),a=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",n={type:o.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(n.model=t),n}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),n=e.test(/like (ipod|iphone)/i);return t&&!n},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:o.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.tv}}}];t.default=a,e.exports=t.default},95:function(e,t,n){t.__esModule=!0,t.default=void 0;var r,i=(r=n(17))&&r.__esModule?r:{default:r},o=n(18),a=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:o.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:o.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:o.ENGINE_MAP.Trident},n=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:o.ENGINE_MAP.Presto},n=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:function(e){var t=e.test(/gecko/i),n=e.test(/like gecko/i);return t&&!n},describe:function(e){var t={name:o.ENGINE_MAP.Gecko},n=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:o.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:o.ENGINE_MAP.WebKit},n=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return n&&(t.version=n),t}}];t.default=a,e.exports=t.default}})},1227:(e,t,n)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e="MISSING_ENV_VAR".DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(2447)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},2447:(e,t,n)=>{e.exports=function(e){function t(e){let n,i,o,a=null;function s(...e){if(!s.enabled)return;const r=s,i=Number(new Date),o=i-(n||i);r.diff=o,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";a++;const o=t.formatters[i];if("function"==typeof o){const t=e[a];n=o.call(r,t),e.splice(a,1),a--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=r,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(s),s}function r(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=n(7824),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},7187:e=>{var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,i)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function s(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,n,r){var i,o,a,u;if(s(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),a=o[t]),void 0===a)a=o[t]=n,++e._eventsCount;else if("function"==typeof a?a=o[t]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),(i=c(e))>0&&a.length>i&&!a.warned){a.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=a.length,u=d,console&&console.warn&&console.warn(u)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function p(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function m(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){r.once&&e.removeEventListener(t,i),n(o)}))}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return c(this)},o.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)r(c,this,t);else{var u=c.length,d=f(c,u);for(n=0;n<u;++n)r(d[n],this,t)}return!0},o.prototype.addListener=function(e,t){return u(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return u(this,e,t,!0)},o.prototype.once=function(e,t){return s(t),this.on(e,l(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,l(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,r,i,o,a;if(s(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,a||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return p(this,e,!0)},o.prototype.rawListeners=function(e){return p(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},o.prototype.listenerCount=h,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},5714:(e,t,n)=>{n.r(t),n.d(t,{AgeGenderNet:()=>Sm,BoundingBox:()=>Lh,Box:()=>Nh,ComposableTask:()=>dg,ComputeAllFaceDescriptorsTask:()=>ov,ComputeFaceDescriptorsTaskBase:()=>iv,ComputeSingleFaceDescriptorTask:()=>av,DetectAllFaceLandmarksTask:()=>cv,DetectAllFacesTask:()=>lv,DetectFaceLandmarksTaskBase:()=>sv,DetectFacesTaskBase:()=>dv,DetectSingleFaceLandmarksTask:()=>uv,DetectSingleFaceTask:()=>pv,Dimensions:()=>wh,FACE_EXPRESSION_LABELS:()=>cm,FaceDetection:()=>jh,FaceDetectionNet:()=>Ym,FaceExpressionNet:()=>dm,FaceExpressions:()=>um,FaceLandmark68Net:()=>Cm,FaceLandmark68TinyNet:()=>km,FaceLandmarkNet:()=>Tm,FaceLandmarks:()=>Yh,FaceLandmarks5:()=>Qh,FaceLandmarks68:()=>Jh,FaceMatch:()=>Zh,FaceMatcher:()=>wv,FaceRecognitionNet:()=>Am,Gender:()=>xm,LabeledBox:()=>ef,LabeledFaceDescriptors:()=>tf,Mtcnn:()=>_g,MtcnnOptions:()=>zm,NetInput:()=>If,NeuralNetwork:()=>Uf,ObjectDetection:()=>Bh,Point:()=>Fh,PredictedBox:()=>nf,Rect:()=>$h,SsdMobilenetv1:()=>Hm,SsdMobilenetv1Options:()=>qm,TinyFaceDetector:()=>Cg,TinyFaceDetectorOptions:()=>ug,TinyYolov2:()=>sg,TinyYolov2Options:()=>og,TinyYolov2SizeType:()=>$m,allFaces:()=>yv,allFacesMtcnn:()=>vv,allFacesSsdMobilenetv1:()=>mv,allFacesTinyYolov2:()=>gv,awaitMediaLoaded:()=>Sf,bufferToImage:()=>Rf,computeFaceDescriptor:()=>Og,createCanvas:()=>Ef,createCanvasFromMedia:()=>kf,createFaceDetectionNet:()=>Xm,createFaceRecognitionNet:()=>Fm,createMtcnn:()=>xv,createSsdMobilenetv1:()=>Km,createTinyFaceDetector:()=>_v,createTinyYolov2:()=>cg,detectAllFaces:()=>fv,detectFaceLandmarks:()=>Ig,detectFaceLandmarksTiny:()=>Mg,detectLandmarks:()=>Kg,detectSingleFace:()=>hv,draw:()=>o,env:()=>ff,euclideanDistance:()=>bv,extendWithAge:()=>Bm,extendWithFaceDescriptor:()=>Nm,extendWithFaceDetection:()=>of,extendWithFaceExpressions:()=>pm,extendWithFaceLandmarks:()=>mm,extendWithGender:()=>Wm,extractFaceTensors:()=>Af,extractFaces:()=>Of,fetchImage:()=>Nf,fetchJson:()=>Lf,fetchNetWeights:()=>Bf,fetchOrThrow:()=>Ff,getContext2dOrThrow:()=>gf,getMediaDimensions:()=>Cf,imageTensorToCanvas:()=>Tf,imageToSquare:()=>Pf,inverseSigmoid:()=>Kh,iou:()=>Wh,isMediaElement:()=>Df,isMediaLoaded:()=>_f,isWithAge:()=>Lm,isWithFaceDetection:()=>rf,isWithFaceExpressions:()=>lm,isWithFaceLandmarks:()=>fm,isWithGender:()=>jm,loadAgeGenderModel:()=>Gg,loadFaceDetectionModel:()=>qg,loadFaceExpressionModel:()=>Vg,loadFaceLandmarkModel:()=>Wg,loadFaceLandmarkTinyModel:()=>zg,loadFaceRecognitionModel:()=>Ug,loadMtcnnModel:()=>Bg,loadSsdMobilenetv1Model:()=>Ng,loadTinyFaceDetectorModel:()=>Lg,loadTinyYolov2Model:()=>jg,loadWeightMap:()=>Wf,locateFaces:()=>Hg,matchDimensions:()=>zf,minBbox:()=>zh,mtcnn:()=>Pg,nets:()=>Eg,nonMaxSuppression:()=>Uh,normalize:()=>Vh,padToSquare:()=>Gh,predictAgeAndGender:()=>Fg,recognizeFaceExpressions:()=>Ag,resizeResults:()=>Sv,resolveInput:()=>mf,shuffleArray:()=>qh,sigmoid:()=>Hh,ssdMobilenetv1:()=>kg,tf:()=>r,tinyFaceDetector:()=>Tg,tinyYolov2:()=>Dg,toNetInput:()=>Mf,utils:()=>i,validateConfig:()=>tg});var r={};n.r(r),n.d(r,{AdadeltaOptimizer:()=>nh,AdagradOptimizer:()=>rh,AdamOptimizer:()=>ih,AdamaxOptimizer:()=>oh,DataStorage:()=>gi,ENV:()=>p,Environment:()=>d,KernelBackend:()=>vi,MomentumOptimizer:()=>sh,Optimizer:()=>th,RMSPropOptimizer:()=>ch,Rank:()=>Se,Reduction:()=>$d,SGDOptimizer:()=>ah,Tensor:()=>_e,TensorBuffer:()=>ye,Variable:()=>Te,abs:()=>Xs,acos:()=>$s,acosh:()=>Ys,add:()=>Xc,addN:()=>$c,addStrict:()=>Yc,all:()=>hd,any:()=>fd,argMax:()=>md,argMin:()=>gd,asin:()=>Qs,asinh:()=>Js,atan:()=>Zs,atan2:()=>Qc,atanh:()=>ec,avgPool:()=>rd,avgPool3d:()=>ad,backend:()=>dn,backend_util:()=>Li,basicLSTMCell:()=>Od,batchNorm:()=>Bc,batchNorm2d:()=>jc,batchNorm3d:()=>Wc,batchNorm4d:()=>zc,batchNormalization:()=>Lc,batchNormalization2d:()=>Ac,batchNormalization3d:()=>Fc,batchNormalization4d:()=>Nc,batchToSpaceND:()=>fr,booleanMaskAsync:()=>Iu,broadcastTo:()=>mr,browser:()=>Gp,buffer:()=>pr,cast:()=>gr,ceil:()=>tc,clipByValue:()=>nc,clone:()=>vr,complex:()=>Tn,concat:()=>Xn,concat1d:()=>$n,concat2d:()=>Yn,concat3d:()=>Qn,concat4d:()=>Jn,conv1d:()=>Fu,conv2d:()=>Nu,conv2dTranspose:()=>Gu,conv3d:()=>Lu,conv3dTranspose:()=>qu,cos:()=>rc,cosh:()=>ic,cumsum:()=>yr,customGrad:()=>pi,deprecationWarn:()=>Kt,depthToSpace:()=>br,depthwiseConv2d:()=>Wu,diag:()=>Hd,disableDeprecationWarnings:()=>Ht,dispose:()=>Zt,disposeVariables:()=>Xt,div:()=>Jc,divNoNan:()=>Zc,divStrict:()=>eu,dot:()=>Ku,dropout:()=>Kd,elu:()=>Rd,enableDebugMode:()=>qt,enableProdMode:()=>Gt,engine:()=>$t,env:()=>l,equal:()=>mu,equalStrict:()=>gu,erf:()=>oc,exp:()=>ac,expandDims:()=>wr,expm1:()=>sc,eye:()=>xr,fft:()=>jd,fill:()=>Vn,findBackend:()=>sn,findBackendFactory:()=>cn,floor:()=>cc,floorDiv:()=>tu,frame:()=>Jd,fused:()=>Il,gather:()=>Du,gatherND:()=>qd,gather_util:()=>Kr,getBackend:()=>on,getGradient:()=>g,getKernel:()=>m,getKernelsForBackend:()=>v,grad:()=>si,grads:()=>ci,greater:()=>vu,greaterEqual:()=>yu,greaterEqualStrict:()=>bu,greaterStrict:()=>wu,hammingWindow:()=>Qd,hannWindow:()=>Yd,ifft:()=>Wd,imag:()=>Pn,image:()=>Sl,inTopKAsync:()=>tl,io:()=>Wp,irfft:()=>Ud,isFinite:()=>wc,isInf:()=>bc,isNaN:()=>yc,keep:()=>en,leakyRelu:()=>Cd,less:()=>xu,lessEqual:()=>_u,lessEqualStrict:()=>Su,lessStrict:()=>Ru,linalg:()=>gl,linspace:()=>Gn,localResponseNormalization:()=>Id,log:()=>uc,log1p:()=>dc,logSigmoid:()=>lc,logSoftmax:()=>mi,logSumExp:()=>vd,logicalAnd:()=>Uc,logicalNot:()=>Vc,logicalOr:()=>Gc,logicalXor:()=>qc,losses:()=>ll,matMul:()=>Hu,math:()=>Up,max:()=>yd,maxPool:()=>nd,maxPool3d:()=>od,maximum:()=>nu,maximumStrict:()=>ru,mean:()=>bd,memory:()=>Yt,min:()=>wd,minimum:()=>iu,minimumStrict:()=>ou,mod:()=>au,modStrict:()=>su,moments:()=>xd,movingAverage:()=>Fd,mul:()=>cu,mulStrict:()=>uu,multiRNNCell:()=>Ad,multinomial:()=>_r,neg:()=>pc,nextFrame:()=>ph,norm:()=>Md,notEqual:()=>Cu,notEqualStrict:()=>Eu,oneHot:()=>Sr,ones:()=>zn,onesLike:()=>Hn,op:()=>kn,outerProduct:()=>Xu,pad:()=>Rr,pad1d:()=>Cr,pad2d:()=>Er,pad3d:()=>kr,pad4d:()=>Tr,pool:()=>id,pow:()=>du,powStrict:()=>lu,prelu:()=>Ed,print:()=>hr,prod:()=>Sd,profile:()=>Qt,rand:()=>Dr,randomGamma:()=>Ir,randomNormal:()=>Pr,randomUniform:()=>Mr,range:()=>qn,ready:()=>rn,real:()=>Dn,reciprocal:()=>hc,registerBackend:()=>un,registerGradient:()=>b,registerKernel:()=>y,relu:()=>kd,relu6:()=>Td,removeBackend:()=>an,reshape:()=>Or,reverse:()=>$u,reverse1d:()=>Yu,reverse2d:()=>Qu,reverse3d:()=>Ju,reverse4d:()=>Zu,rfft:()=>zd,round:()=>fc,rsqrt:()=>mc,scalar:()=>On,scatterND:()=>Bd,scatter_util:()=>Jr,selu:()=>Dd,separableConv2d:()=>Vu,serialization:()=>Xp,setBackend:()=>nn,setPlatform:()=>ln,setdiff1dAsync:()=>Wr,sigmoid:()=>gc,sign:()=>vc,signal:()=>el,sin:()=>xc,sinh:()=>_c,slice:()=>sd,slice1d:()=>cd,slice2d:()=>ud,slice3d:()=>dd,slice4d:()=>ld,slice_util:()=>ai,softmax:()=>fi,softplus:()=>Sc,spaceToBatchND:()=>Ar,sparseToDense:()=>Gd,spectral:()=>Vd,split:()=>Zn,sqrt:()=>Rc,square:()=>qs,squaredDifference:()=>Ks,squaredDifferenceStrict:()=>pu,squeeze:()=>Fr,stack:()=>Nr,step:()=>Cc,stft:()=>Zd,stridedSlice:()=>Nd,sub:()=>hu,subStrict:()=>fu,sum:()=>_d,sumOutType:()=>Ie,tan:()=>Ec,tanh:()=>kc,tensor:()=>In,tensor1d:()=>An,tensor2d:()=>Fn,tensor3d:()=>Nn,tensor4d:()=>Ln,tensor5d:()=>Bn,tensor6d:()=>jn,tensor_util:()=>Ne,test_util:()=>Jp,tidy:()=>Jt,tile:()=>Lr,time:()=>tn,topk:()=>Ld,train:()=>dh,transpose:()=>Pd,truncatedNormal:()=>Br,unregisterGradient:()=>x,unregisterKernel:()=>w,unsortedSegmentSum:()=>Pu,unstack:()=>jr,util:()=>pe,valueAndGrad:()=>ui,valueAndGrads:()=>di,variable:()=>Wn,variableGrads:()=>li,version_core:()=>Zp,webgl:()=>eh,where:()=>Hc,whereAsync:()=>Kc,zeros:()=>Un,zerosLike:()=>Kn});var i={};n.r(i),n.d(i,{computeReshapedDimensions:()=>Ph,getCenterPoint:()=>Ih,isDimensions:()=>Dh,isEven:()=>kh,isFloat:()=>Eh,isTensor:()=>xh,isTensor1D:()=>_h,isTensor2D:()=>Sh,isTensor3D:()=>Rh,isTensor4D:()=>Ch,isValidNumber:()=>Oh,isValidProbablitiy:()=>Ah,range:()=>Mh,round:()=>Th});var o={};n.r(o),n.d(o,{AnchorPosition:()=>hf,DrawBox:()=>wf,DrawBoxOptions:()=>bf,DrawFaceLandmarks:()=>vm,DrawFaceLandmarksOptions:()=>gm,DrawTextField:()=>yf,DrawTextFieldOptions:()=>vf,drawContour:()=>hh,drawDetections:()=>xf,drawFaceExpressions:()=>hm,drawFaceLandmarks:()=>ym});var a=function(e,t){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function s(e,t){function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function c(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n((function(t){t(e.value)})).then(a,s)}c((r=r.apply(e,t||[])).next())}))}function u(e,t){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var d=function(){function e(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return e.prototype.setPlatform=function(e,t){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+t+"."),this.platformName=e,this.platform=t},e.prototype.registerFlag=function(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){var r=this.urlFlags[e];console.warn("Setting feature override from URL "+e+": "+r+"."),this.set(e,r)}},e.prototype.get=function(e){return e in this.flags||(this.flags[e]=this.evaluateFlag(e)),this.flags[e]},e.prototype.getNumber=function(e){return this.get(e)},e.prototype.getBool=function(e){return this.get(e)},e.prototype.getFlags=function(){return this.flags},Object.defineProperty(e.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),e.prototype.set=function(e,t){if(null==this.flagRegistry[e])throw new Error("Cannot set flag "+e+" as it has not been registered.");this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)},e.prototype.evaluateFlag=function(e){if(null==this.flagRegistry[e])throw new Error("Cannot evaluate flag '"+e+"': no evaluation function found.");return this.flagRegistry[e].evaluationFn()},e.prototype.setFlags=function(e){this.flags=Object.assign({},e)},e.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},e.prototype.populateURLFlags=function(){var e=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var t,n,r=(t=this.global.location.search,n={},t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(n,t[0],t[1]),t.join("=")})),n);"tfjsflags"in r&&r.tfjsflags.split(",").forEach((function(t){var n=t.split(":"),r=n[0],i=n[1];e.urlFlags[r]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error("Could not parse value flag value "+t+" for flag "+e+".")}(r,i)}))}},e}();function l(){return p}var p=null,h=new Map,f=new Map;function m(e,t){var n=_(e,t);return h.get(n)}function g(e){return f.get(e)}function v(e){for(var t=h.entries(),n=[];;){var r=t.next(),i=r.done,o=r.value;if(i)break;var a=o[0],s=o[1];a.split("_")[0]===e&&n.push(s)}return n}function y(e){var t=e.kernelName,n=e.backendName,r=_(t,n);if(h.has(r))throw new Error("The kernel '"+t+"' for backend '"+n+"' is already registered");h.set(r,e)}function b(e){var t=e.kernelName;f.has(t)&&console.warn("Overriding the gradient for '"+t+"'"),f.set(t,e)}function w(e,t){var n=_(e,t);if(!h.has(n))throw new Error("The kernel '"+e+"' for backend '"+t+"' is not registered");h.delete(n)}function x(e){if(!f.has(e))throw new Error("The gradient '"+e+"' for backend is not registered");f.delete(e)}function _(e,t){return t+"_"+e}function S(e){for(var t=e.length,n=0,r=0;t>0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function R(e,t,n){return Math.max(e,Math.min(t,n))}function C(e){return e%2==0?e:e+1}function E(e){for(var t=0,n=0;n<e.length;n++)t+=e[n];return t}function k(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function T(e,t,n){void 0===n&&(n=""),k(M(e,t),(function(){return n+" Shapes "+e+" and "+t+" must match"}))}function D(e){k(null!=e,(function(){return"The input to the tensor constructor must be a non-null value."}))}function P(e,t,n){if(void 0===t&&(t=[]),void 0===n&&(n=!1),null==t&&(t=[]),Array.isArray(e)||H(e)&&!n)for(var r=0;r<e.length;++r)P(e[r],t,n);else t.push(e);return t}function I(e){if(0===e.length)return 1;for(var t=e[0],n=1;n<e.length;n++)t*=e[n];return t}function M(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function O(e){return e%1==0}function A(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;var t=Math.exp(2*e);return(t-1)/(t+1)}function F(e){var t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function N(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function L(e,t,n){return void 0===t&&(t=function(e){return 0}),new Promise((function(r,i){var o=0,a=function(){if(e())r();else{o++;var s=t(o);null!=n&&o>=n?i():setTimeout(a,s)}};a()}))}function B(e,t){for(var n=1,r=-1,i=0;i<e.length;++i)if(e[i]>=0)n*=e[i];else if(-1===e[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(e[i]<0)throw Error("Shapes can not be < 0. Found "+e[i]+" at dim "+i);if(-1===r){if(t>0&&t!==n)throw Error("Size("+t+") must match the product of shape "+e);return e}if(0===n)throw Error("Cannot infer the missing size in ["+e+"] when there are 0 elements");if(t%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+n);var o=e.slice();return o[r]=t/n,o}function j(e,t){var n=t.length;return k((e=null==e?t.map((function(e,t){return t})):[].concat(e)).every((function(e){return e>=-n&&e<n})),(function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+e})),k(e.every((function(e){return O(e)})),(function(){return"All values in axis param must be integers but got axis "+e})),e.map((function(e){return e<0?n+e:e}))}function W(e,t){for(var n=[],r=[],i=null!=t&&Array.isArray(t)&&0===t.length,o=null==t||i?null:j(t,e).sort(),a=0,s=0;s<e.length;++s){if(null!=o){if(o[a]===s&&1!==e[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+e[s]+"' is not 1");(null==o[a]||o[a]>s)&&1===e[s]&&(n.push(e[s]),r.push(s)),o[a]<=s&&a++}1!==e[s]&&(n.push(e[s]),r.push(s))}return{newShape:n,keptDims:r}}function z(e,t){var n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);n=new Uint8Array(t)}return n}function U(e,t){var n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);n=new Array(t)}return n}function V(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+t+" being uploaded contains "+r+".")}}function G(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function q(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function H(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function K(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error("Unknown dtype "+e)}function X(e){if(null==e)return 0;var t=0;return e.forEach((function(e){return t+=e.length})),t}function $(e){return"string"==typeof e||e instanceof String}function Y(e){return"boolean"==typeof e}function Q(e){return"number"==typeof e}function J(e){return Array.isArray(e)?J(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":Q(e)?"float32":$(e)?"string":Y(e)?"bool":"float32"}function Z(e){return!!(e&&e.constructor&&e.call&&e.apply)}function ee(e,t){for(var n=t;n<e;++n)if(e%n==0)return n;return e}function te(e){var t=e.length;if(t<2)return[];var n=new Array(t-1);n[t-2]=e[t-1];for(var r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function ne(e,t,n){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=P(e)),n&&V(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){for(var r=new Uint8Array(e.length),i=0;i<r.length;++i)0!==Math.round(e[i])&&(r[i]=1);return r}throw new Error("Unknown data type "+t)}function re(e,t){if(0===e.length)return t[0];var n=e.reduce((function(e,t){return e*t}));if(0===n)return[];if(n!==t.length)throw new Error("["+e+"] does not match the input size.");return function e(t,n,r){var i=new Array;if(1===n.length)for(var o=n[0],a=0;a<o;a++)i[a]=r[t+a];else{o=n[0];var s=n.slice(1),c=s.reduce((function(e,t){return e*t}));for(a=0;a<o;a++)i[a]=e(t+a*c,s,r)}return i}(0,e,t)}function ie(e,t){for(var n=oe(e,t),r=0;r<n.length;r++)n[r]=1;return n}function oe(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error("Unknown data type "+t)}function ae(){return l().platform.now()}function se(e){e.forEach((function(t){k(Number.isInteger(t)&&t>=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+e+"]."}))}))}function ce(e,t){return void 0===t&&(t="utf-8"),t=t||"utf-8",l().platform.encode(e,t)}function ue(e,t){return void 0===t&&(t="utf-8"),t=t||"utf-8",l().platform.decode(e,t)}function de(e,t,n){if(0===t)return 0;if(1===t)return e[0];for(var r=e[e.length-1],i=0;i<e.length-1;++i)r+=n[i]*e[i];return r}function le(e,t,n){if(0===t)return[];if(1===t)return[e];for(var r=new Array(t),i=0;i<r.length-1;++i)r[i]=Math.floor(e/n[i]),e-=r[i]*n[i];return r[r.length-1]=e,r}var pe=Object.freeze({shuffle:S,clamp:R,nearestLargerEven:C,sum:E,randUniform:function(e,t){var n=Math.random();return t*n+(1-n)*e},distSquared:function(e,t){for(var n=0,r=0;r<e.length;r++){var i=Number(e[r])-Number(t[r]);n+=i*i}return n},assert:k,assertShapesMatch:T,assertNonNull:D,flatten:P,sizeFromShape:I,isScalarShape:function(e){return 0===e.length},arraysEqual:M,isInt:O,tanh:A,sizeToSquarishShape:F,createShuffledIndices:function(e){for(var t=new Uint32Array(e),n=0;n<e;++n)t[n]=n;return S(t),t},rightPad:N,repeatedTry:L,inferFromImplicitShape:B,parseAxisParam:j,squeezeShape:W,getTypedArrayFromDType:z,getArrayFromDType:U,checkConversionForErrors:V,isValidDtype:G,hasEncodingLoss:q,isTypedArray:H,bytesPerElement:K,bytesFromStringArray:X,isString:$,isBoolean:Y,isNumber:Q,inferDtype:J,isFunction:Z,nearestDivisor:ee,computeStrides:te,toTypedArray:ne,toNestedArray:re,makeOnesTypedArray:ie,makeZerosTypedArray:oe,now:ae,assertNonNegativeIntegerDimensions:se,fetch:function(e,t){return l().platform.fetch(e,t)},encodeString:ce,decodeString:ue,locToIndex:de,indexToLoc:le}),he=function(){function e(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new fe)}return e.prototype.profileKernel=function(e,t,n){var r,i=this,o=this.backendTimer.time((function(){r=n()}));return r.forEach((function(n){n.data().then((function(r){!function(e,t,n){if("float32"!==t)return!1;for(var r=0;r<e.length;r++){var i=e[r];if(isNaN(i)||!isFinite(i))return console.warn("Found "+i+" in the result of '"+n+"'"),!0}}(r,n.dtype,e),o.then((function(o){var a="";null!=o.getExtraProfileInfo&&(a=o.getExtraProfileInfo()),i.logger.logKernelProfile(e,n,r,o.kernelMs,t,a)}))}))})),r},e}(),fe=function(){function e(){}return e.prototype.logKernelProfile=function(e,t,n,r,i,o){var a="number"==typeof r?N(r+"ms",9):r.error,s=N(e,25),c=t.rank,u=t.size,d=N(t.shape.toString(),14),l="";for(var p in i){var h=i[p].shape||t.shape,f=h.length;l+=p+": "+f+"D "+(f>0?h:"")+" "}console.log("%c"+s+"\t%c"+a+"\t%c"+c+"D "+d+"\t%c"+u+"\t%c"+l+"\t%c"+o,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},e}();function me(e,t,n){return N(Array.isArray(e)?parseFloat(e[0].toFixed(7))+" + "+parseFloat(e[1].toFixed(7))+"j":$(e)?"'"+e+"'":"bool"===n?ge(e):parseFloat(e.toFixed(7)).toString(),t)}function ge(e){return 0===e?"false":"true"}function ve(e){for(var t=[],n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var ye=function(){function e(e,t,n){var r=this;if(this.dtype=t,this.shape=e.slice(),this.size=I(e),null!=n){var i=n.length;k(i===this.size,(function(){return"Length of values '"+i+"' does not match the size inferred by the shape '"+r.size+"'."}))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||U(t,this.size),this.strides=te(e)}return e.prototype.set=function(e){for(var t=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),k(n.length===this.rank,(function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+t.rank+")"}));var i=this.locToIndex(n);this.values[i]=e},e.prototype.get=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];0===e.length&&(e=[0]);for(var n=0,r=0,i=e;r<i.length;r++){var o=i[r];if(o<0||o>=this.shape[n]){var a="Requested out of range element at "+e+". Buffer shape="+this.shape;throw new Error(a)}n++}for(var s=e[e.length-1],c=0;c<e.length-1;++c)s+=this.strides[c]*e[c];return this.values[s]},e.prototype.locToIndex=function(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];for(var t=e[e.length-1],n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t},e.prototype.indexToLoc=function(e){if(0===this.rank)return[];if(1===this.rank)return[e];for(var t=new Array(this.shape.length),n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t},Object.defineProperty(e.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.toTensor=function(){return be().makeTensor(this.values,this.shape,this.dtype)},e}(),be=null,we=null,xe=null,_e=function(){function e(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=I(e),this.strides=te(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}return e.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},e.prototype.asScalar=function(){return this.throwIfDisposed(),k(1===this.size,(function(){return"The array must have only 1 element."})),this.reshape([])},e.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},e.prototype.as2D=function(e,t){return this.throwIfDisposed(),this.reshape([e,t])},e.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),this.reshape([e,t,n])},e.prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),this.reshape([e,t,n,r])},e.prototype.as5D=function(e,t,n,r,i){return this.throwIfDisposed(),this.reshape([e,t,n,r,i])},e.prototype.asType=function(e){return this.throwIfDisposed(),we.cast(this,e)},Object.defineProperty(e.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.buffer=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,we.buffer(this.shape,this.dtype,e)]}}))}))},e.prototype.bufferSync=function(){return we.buffer(this.shape,this.dtype,this.dataSync())},e.prototype.array=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,re(this.shape,e)]}}))}))},e.prototype.arraySync=function(){return re(this.shape,this.dataSync())},e.prototype.data=function(){return c(this,void 0,void 0,(function(){var e,t;return u(this,(function(n){switch(n.label){case 0:return this.throwIfDisposed(),e=be().read(this.dataId),"string"!==this.dtype?[3,2]:[4,e];case 1:t=n.sent();try{return[2,t.map((function(e){return ue(e)}))]}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}n.label=2;case 2:return[2,e]}}))}))},e.prototype.dataSync=function(){this.throwIfDisposed();var e=be().readSync(this.dataId);if("string"===this.dtype)try{return e.map((function(e){return ue(e)}))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e},e.prototype.bytes=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return this.throwIfDisposed(),[4,be().read(this.dataId)];case 1:return e=t.sent(),"string"===this.dtype?[2,e]:[2,new Uint8Array(e.buffer)]}}))}))},e.prototype.dispose=function(){this.isDisposed||(be().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),e.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},e.prototype.toFloat=function(){return this.asType("float32")},e.prototype.toInt=function(){return this.asType("int32")},e.prototype.toBool=function(){return this.asType("bool")},e.prototype.print=function(e){return void 0===e&&(e=!1),we.print(this,e)},e.prototype.reshape=function(e){return this.throwIfDisposed(),we.reshape(this,e)},e.prototype.reshapeAs=function(e){return this.throwIfDisposed(),this.reshape(e.shape)},e.prototype.expandDims=function(e){return void 0===e&&(e=0),we.expandDims(this,e)},e.prototype.cumsum=function(e,t,n){return void 0===e&&(e=0),void 0===t&&(t=!1),void 0===n&&(n=!1),we.cumsum(this,e,t,n)},e.prototype.squeeze=function(e){return this.throwIfDisposed(),we.squeeze(this,e)},e.prototype.clone=function(){return this.throwIfDisposed(),we.clone(this)},e.prototype.oneHot=function(e,t,n){return this.throwIfDisposed(),we.oneHot(this,e,t,n)},e.prototype.toString=function(e){return void 0===e&&(e=!1),function(e,t,n,r){var i=te(t),o=function(e,t,n,r){var i=I(t),o=r[r.length-1],a=new Array(o).fill(0),s=t.length,c="complex64"===n?ve(e):e;if(s>1)for(var u=0;u<i/o;u++)for(var d=u*o,l=0;l<o;l++)a[l]=Math.max(a[l],me(c[d+l],0,n).length);return a}(e,t,n,i),a=t.length,s=function e(t,n,r,i,o,a){void 0===a&&(a=!0);var s="complex64"===r?2:1,c=n[0],u=n.length;if(0===u)return"complex64"===r?[me(ve(t)[0],0,r)]:"bool"===r?[ge(t[0])]:[t[0].toString()];if(1===u){if(c>20){var d=3*s,l=Array.from(t.slice(0,d)),p=Array.from(t.slice((c-3)*s,c*s));return"complex64"===r&&(l=ve(l),p=ve(p)),["["+l.map((function(e,t){return me(e,o[t],r)})).join(", ")+", ..., "+p.map((function(e,t){return me(e,o[c-3+t],r)})).join(", ")+"]"]}return["["+("complex64"===r?ve(t):Array.from(t)).map((function(e,t){return me(e,o[t],r)})).join(", ")+"]"]}var h=n.slice(1),f=i.slice(1),m=i[0]*s,g=[];if(c>20){for(var v=0;v<3;v++){var y=(b=v*m)+m;g.push.apply(g,e(t.slice(b,y),h,r,f,o,!1))}for(g.push("..."),v=c-3;v<c;v++)y=(b=v*m)+m,g.push.apply(g,e(t.slice(b,y),h,r,f,o,v===c-1))}else for(v=0;v<c;v++){var b;y=(b=v*m)+m,g.push.apply(g,e(t.slice(b,y),h,r,f,o,v===c-1))}var w=2===u?",":"";for(g[0]="["+g[0]+w,v=1;v<g.length-1;v++)g[v]=" "+g[v]+w;var x=",\n";for(v=2;v<u;v++)x+="\n";return g[g.length-1]=" "+g[g.length-1]+"]"+(a?"":x),g}(e,t,n,i,o),c=["Tensor"];return r&&(c.push(" dtype: "+n),c.push(" rank: "+a),c.push(" shape: ["+t+"]"),c.push(" values:")),c.push(s.map((function(e){return" "+e})).join("\n")),c.join("\n")}(this.dataSync(),this.shape,this.dtype,e)},e.prototype.tile=function(e){return this.throwIfDisposed(),we.tile(this,e)},e.prototype.gather=function(e,t){return void 0===t&&(t=0),this.throwIfDisposed(),we.gather(this,e,t)},e.prototype.matMul=function(e,t,n){return void 0===t&&(t=!1),void 0===n&&(n=!1),this.throwIfDisposed(),we.matMul(this,e,t,n)},e.prototype.dot=function(e){return this.throwIfDisposed(),we.dot(this,e)},e.prototype.norm=function(e,t,n){return void 0===e&&(e="euclidean"),void 0===t&&(t=null),void 0===n&&(n=!1),this.throwIfDisposed(),we.norm(this,e,t,n)},e.prototype.slice=function(e,t){return this.throwIfDisposed(),we.slice(this,e,t)},e.prototype.reverse=function(e){return this.throwIfDisposed(),we.reverse(this,e)},e.prototype.concat=function(t,n){return void 0===n&&(n=0),this.throwIfDisposed(),t instanceof e&&(t=[t]),we.concat([this].concat(t),n)},e.prototype.split=function(e,t){return void 0===t&&(t=0),this.throwIfDisposed(),we.split(this,e,t)},e.prototype.stack=function(e,t){return void 0===t&&(t=0),we.stack([this,e],t)},e.prototype.unstack=function(e){return void 0===e&&(e=0),we.unstack(this,e)},e.prototype.pad=function(e,t){return void 0===t&&(t=0),we.pad(this,e,t)},e.prototype.batchNormalization=function(e,t,n,r,i){return void 0===n&&(n=.001),xe("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(e,t,i,r,n)},e.prototype.batchNorm=function(e,t,n,r,i){return void 0===i&&(i=.001),this.throwIfDisposed(),we.batchNorm(this,e,t,n,r,i)},e.prototype.all=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.all(this,e,t)},e.prototype.any=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.any(this,e,t)},e.prototype.logSumExp=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.logSumExp(this,e,t)},e.prototype.sum=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.sum(this,e,t)},e.prototype.prod=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.prod(this,e,t)},e.prototype.mean=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.mean(this,e,t)},e.prototype.min=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.min(this,e,t)},e.prototype.max=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),we.max(this,e,t)},e.prototype.argMin=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),we.argMin(this,e)},e.prototype.argMax=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),we.argMax(this,e)},e.prototype.cast=function(e){return this.throwIfDisposed(),we.cast(this,e)},e.prototype.add=function(e){return this.throwIfDisposed(),we.add(this,e)},e.prototype.addStrict=function(e){return this.throwIfDisposed(),we.addStrict(this,e)},e.prototype.atan2=function(e){return this.throwIfDisposed(),we.atan2(this,e)},e.prototype.sub=function(e){return this.throwIfDisposed(),we.sub(this,e)},e.prototype.subStrict=function(e){return this.throwIfDisposed(),we.subStrict(this,e)},e.prototype.pow=function(e){return this.throwIfDisposed(),we.pow(this,e)},e.prototype.powStrict=function(e){return this.throwIfDisposed(),we.powStrict(this,e)},e.prototype.mul=function(e){return this.throwIfDisposed(),we.mul(this,e)},e.prototype.mulStrict=function(e){return this.throwIfDisposed(),we.mulStrict(this,e)},e.prototype.div=function(e){return this.throwIfDisposed(),we.div(this,e)},e.prototype.divNoNan=function(e){return this.throwIfDisposed(),we.divNoNan(this,e)},e.prototype.floorDiv=function(e){return this.throwIfDisposed(),we.floorDiv(this,e)},e.prototype.divStrict=function(e){return this.throwIfDisposed(),we.divStrict(this,e)},e.prototype.minimum=function(e){return this.throwIfDisposed(),we.minimum(this,e)},e.prototype.minimumStrict=function(e){return this.throwIfDisposed(),we.minimumStrict(this,e)},e.prototype.maximum=function(e){return this.throwIfDisposed(),we.maximum(this,e)},e.prototype.maximumStrict=function(e){return this.throwIfDisposed(),we.maximumStrict(this,e)},e.prototype.mod=function(e){return this.throwIfDisposed(),we.mod(this,e)},e.prototype.modStrict=function(e){return this.throwIfDisposed(),we.modStrict(this,e)},e.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),we.squaredDifferenceStrict(this,e)},e.prototype.transpose=function(e){return this.throwIfDisposed(),we.transpose(this,e)},e.prototype.notEqual=function(e){return this.throwIfDisposed(),we.notEqual(this,e)},e.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),we.notEqualStrict(this,e)},e.prototype.less=function(e){return this.throwIfDisposed(),we.less(this,e)},e.prototype.lessStrict=function(e){return this.throwIfDisposed(),we.lessStrict(this,e)},e.prototype.equal=function(e){return this.throwIfDisposed(),we.equal(this,e)},e.prototype.equalStrict=function(e){return this.throwIfDisposed(),we.equalStrict(this,e)},e.prototype.lessEqual=function(e){return this.throwIfDisposed(),we.lessEqual(this,e)},e.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),we.lessEqualStrict(this,e)},e.prototype.greater=function(e){return this.throwIfDisposed(),we.greater(this,e)},e.prototype.greaterStrict=function(e){return this.throwIfDisposed(),we.greaterStrict(this,e)},e.prototype.greaterEqual=function(e){return this.throwIfDisposed(),we.greaterEqual(this,e)},e.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),we.greaterEqualStrict(this,e)},e.prototype.logicalAnd=function(e){return this.throwIfDisposed(),we.logicalAnd(this,e)},e.prototype.logicalOr=function(e){return this.throwIfDisposed(),we.logicalOr(this,e)},e.prototype.logicalNot=function(){return this.throwIfDisposed(),we.logicalNot(this)},e.prototype.logicalXor=function(e){return this.throwIfDisposed(),we.logicalXor(this,e)},e.prototype.where=function(e,t){return this.throwIfDisposed(),we.where(e,this,t)},e.prototype.neg=function(){return this.throwIfDisposed(),we.neg(this)},e.prototype.ceil=function(){return this.throwIfDisposed(),we.ceil(this)},e.prototype.floor=function(){return this.throwIfDisposed(),we.floor(this)},e.prototype.sign=function(){return this.throwIfDisposed(),we.sign(this)},e.prototype.isNaN=function(){return this.throwIfDisposed(),we.isNaN(this)},e.prototype.isInf=function(){return this.throwIfDisposed(),we.isInf(this)},e.prototype.isFinite=function(){return this.throwIfDisposed(),we.isFinite(this)},e.prototype.exp=function(){return this.throwIfDisposed(),we.exp(this)},e.prototype.expm1=function(){return this.throwIfDisposed(),we.expm1(this)},e.prototype.log=function(){return this.throwIfDisposed(),we.log(this)},e.prototype.log1p=function(){return this.throwIfDisposed(),we.log1p(this)},e.prototype.sqrt=function(){return this.throwIfDisposed(),we.sqrt(this)},e.prototype.rsqrt=function(){return this.throwIfDisposed(),we.rsqrt(this)},e.prototype.square=function(){return this.throwIfDisposed(),we.square(this)},e.prototype.reciprocal=function(){return this.throwIfDisposed(),we.reciprocal(this)},e.prototype.abs=function(){return this.throwIfDisposed(),we.abs(this)},e.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),we.clipByValue(this,e,t)},e.prototype.relu=function(){return this.throwIfDisposed(),we.relu(this)},e.prototype.relu6=function(){return this.throwIfDisposed(),we.relu6(this)},e.prototype.elu=function(){return this.throwIfDisposed(),we.elu(this)},e.prototype.selu=function(){return this.throwIfDisposed(),we.selu(this)},e.prototype.leakyRelu=function(e){return void 0===e&&(e=.2),this.throwIfDisposed(),we.leakyRelu(this,e)},e.prototype.prelu=function(e){return this.throwIfDisposed(),we.prelu(this,e)},e.prototype.sigmoid=function(){return this.throwIfDisposed(),we.sigmoid(this)},e.prototype.logSigmoid=function(){return this.throwIfDisposed(),we.logSigmoid(this)},e.prototype.softplus=function(){return this.throwIfDisposed(),we.softplus(this)},e.prototype.zerosLike=function(){return this.throwIfDisposed(),we.zerosLike(this)},e.prototype.onesLike=function(){return this.throwIfDisposed(),we.onesLike(this)},e.prototype.sin=function(){return this.throwIfDisposed(),we.sin(this)},e.prototype.cos=function(){return this.throwIfDisposed(),we.cos(this)},e.prototype.tan=function(){return this.throwIfDisposed(),we.tan(this)},e.prototype.asin=function(){return this.throwIfDisposed(),we.asin(this)},e.prototype.acos=function(){return this.throwIfDisposed(),we.acos(this)},e.prototype.atan=function(){return this.throwIfDisposed(),we.atan(this)},e.prototype.sinh=function(){return this.throwIfDisposed(),we.sinh(this)},e.prototype.cosh=function(){return this.throwIfDisposed(),we.cosh(this)},e.prototype.tanh=function(){return this.throwIfDisposed(),we.tanh(this)},e.prototype.asinh=function(){return this.throwIfDisposed(),we.asinh(this)},e.prototype.acosh=function(){return this.throwIfDisposed(),we.acosh(this)},e.prototype.atanh=function(){return this.throwIfDisposed(),we.atanh(this)},e.prototype.erf=function(){return this.throwIfDisposed(),we.erf(this)},e.prototype.round=function(){return this.throwIfDisposed(),we.round(this)},e.prototype.step=function(e){return void 0===e&&(e=0),this.throwIfDisposed(),we.step(this,e)},e.prototype.softmax=function(e){return void 0===e&&(e=-1),this.throwIfDisposed(),we.softmax(this,e)},e.prototype.logSoftmax=function(e){return void 0===e&&(e=-1),this.throwIfDisposed(),we.logSoftmax(this,e)},e.prototype.resizeBilinear=function(e,t){return void 0===t&&(t=!1),this.throwIfDisposed(),we.image.resizeBilinear(this,e,t)},e.prototype.resizeNearestNeighbor=function(e,t){return void 0===t&&(t=!1),this.throwIfDisposed(),we.image.resizeNearestNeighbor(this,e,t)},e.prototype.conv1d=function(e,t,n,r,i,o){return void 0===r&&(r="NWC"),void 0===i&&(i=1),this.throwIfDisposed(),we.conv1d(this,e,t,n,r,i,o)},e.prototype.conv2d=function(e,t,n,r,i,o){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),we.conv2d(this,e,t,n,r,i,o)},e.prototype.conv2dTranspose=function(e,t,n,r,i){return this.throwIfDisposed(),we.conv2dTranspose(this,e,t,n,r,i)},e.prototype.depthwiseConv2D=function(e,t,n,r,i,o){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),we.depthwiseConv2d(this,e,t,n,r,i,o)},e.prototype.separableConv2d=function(e,t,n,r,i,o){return void 0===i&&(i=[1,1]),void 0===o&&(o="NHWC"),this.throwIfDisposed(),we.separableConv2d(this,e,t,n,r,i,o)},e.prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),we.avgPool(this,e,t,n,r)},e.prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),we.maxPool(this,e,t,n,r)},e.prototype.localResponseNormalization=function(e,t,n,r){return void 0===e&&(e=5),void 0===t&&(t=1),void 0===n&&(n=1),void 0===r&&(r=.5),we.localResponseNormalization(this,e,t,n,r)},e.prototype.pool=function(e,t,n,r,i){return this.throwIfDisposed(),we.pool(this,e,t,n,r,i)},e.prototype.variable=function(e,t,n){return void 0===e&&(e=!0),this.throwIfDisposed(),be().makeVariable(this,e,t,n)},e.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),we.unsortedSegmentSum(this,e,t)},e.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),we.batchToSpaceND(this,e,t)},e.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),we.spaceToBatchND(this,e,t)},e.prototype.topk=function(e,t){return void 0===e&&(e=1),void 0===t&&(t=!0),this.throwIfDisposed(),we.topk(this,e,t)},e.prototype.stridedSlice=function(e,t,n,r,i,o,a,s){return void 0===r&&(r=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===s&&(s=0),this.throwIfDisposed(),we.stridedSlice(this,e,t,n,r,i,o,a,s)},e.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),we.depthToSpace(this,e,t)},e.prototype.fft=function(){return this.throwIfDisposed(),we.spectral.fft(this)},e.prototype.ifft=function(){return this.throwIfDisposed(),we.spectral.ifft(this)},e.prototype.rfft=function(){return this.throwIfDisposed(),we.spectral.rfft(this)},e.prototype.irfft=function(){return this.throwIfDisposed(),we.spectral.irfft(this)},e}();Object.defineProperty(_e,Symbol.hasInstance,{value:function(e){return!!e&&null!=e.dataId&&null!=e.shape&&null!=e.dtype}});var Se,Re,Ce,Ee,ke,Te=function(e){function t(t,n,r,i){var o=e.call(this,t.shape,t.dtype,t.dataId,i)||this;return o.trainable=n,o.name=r,o}return s(t,e),t.prototype.assign=function(e){if(e.dtype!==this.dtype)throw new Error("dtype of the new value ("+e.dtype+") and previous value ("+this.dtype+") must match");if(!M(e.shape,this.shape))throw new Error("shape of the new value ("+e.shape+") and previous value ("+this.shape+") must match");be().disposeTensor(this),this.dataId=e.dataId,be().incRef(this,null)},t.prototype.dispose=function(){be().disposeVariable(this),this.isDisposedInternal=!0},t}(_e);Object.defineProperty(Te,Symbol.hasInstance,{value:function(e){return e instanceof _e&&null!=e.assign&&e.assign instanceof Function}}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Se||(Se={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Re||(Re={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Ce||(Ce={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Ee||(Ee={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(ke||(ke={}));var De={float32:Ee,int32:Re,bool:Ce,complex64:ke};function Pe(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error("Can not upcast "+e+" with "+t)}return De[e][t]}function Ie(e){return Pe(e,"int32")}function Me(e,t){if(e.dtype===t.dtype)return[e,t];var n=Pe(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Oe(e,t){k(e.dtype===t.dtype,(function(){return"The dtypes of the first("+e.dtype+") and second("+t.dtype+") input must match"}))}function Ae(e){var t=[];return function e(t,n,r){if(null!=t)if(t instanceof _e)n.push(t);else if(i=t,Array.isArray(i)||"object"==typeof i){var i,o=t;for(var a in o){var s=o[a];r.has(s)||(r.add(s),e(s,n,r))}}}(e,t,new Set),t}var Fe,Ne=Object.freeze({makeTypesMatch:Me,assertTypesMatch:Oe,isTensorInList:function(e,t){return t.some((function(t){return t.id===e.id}))},getTensorsInContainer:Ae}),Le=function(){function e(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return e.prototype.dispose=function(){for(var e in this.registeredVariables)this.registeredVariables[e].dispose()},e}(),Be=function(){function e(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Le}return e.prototype.ready=function(){return c(this,void 0,void 0,(function(){var e,t,n;return u(this,(function(r){switch(r.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then((function(){}))];if(null!=this.backendInstance)return[2];e=this.getSortedBackends(),t=0,r.label=1;case 1:return t<e.length?(n=e[t],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return t++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}}))}))},Object.defineProperty(e.prototype,"backend",{get:function(){if(null!=this.pendingBackendInit)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");if(null==this.backendInstance){var e=this.initializeBackendsAndReturnBest(),t=e.name;if(e.asyncInit)throw new Error("The highest priority backend '"+t+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");this.setBackend(t)}return this.backendInstance},enumerable:!0,configurable:!0}),e.prototype.backendNames=function(){return Object.keys(this.registryFactory)},e.prototype.findBackend=function(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;if(this.initializeBackend(e).asyncInit)return null}return this.registry[e]},e.prototype.findBackendFactory=function(e){return e in this.registryFactory?this.registryFactory[e].factory:null},e.prototype.registerBackend=function(e,t,n){return void 0===n&&(n=1),e in this.registryFactory?(console.warn(e+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[e]={factory:t,priority:n},!0)},e.prototype.setBackend=function(e){return c(this,void 0,void 0,(function(){var t,n,r;return u(this,(function(i){switch(i.label){case 0:if(null==this.registryFactory[e])throw new Error("Backend name '"+e+"' not found in registry");return this.backendName=e,null!=this.registry[e]?[3,4]:(this.backendInstance=null,t=this.initializeBackend(e),n=t.success,t.asyncInit?[4,n]:[3,2]);case 1:return r=i.sent(),[3,3];case 2:r=n,i.label=3;case 3:if(!r)return[2,!1];i.label=4;case 4:return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new he(this.backendInstance),[2,!0]}}))}))},e.prototype.setupRegisteredKernels=function(){var e=this;v(this.backendName).forEach((function(t){null!=t.setupFunc&&t.setupFunc(e.backendInstance)}))},e.prototype.disposeRegisteredKernels=function(e){var t=this;v(e).forEach((function(n){null!=n.disposeFunc&&n.disposeFunc(t.registry[e])}))},e.prototype.initializeBackend=function(e){var t=this,n=this.registryFactory[e];if(null==n)throw new Error("Cannot initialize backend "+e+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var i=++this.pendingBackendInitId,o=r.then((function(n){return!(i<t.pendingBackendInitId||(t.registry[e]=n,t.pendingBackendInit=null,0))})).catch((function(n){return!(i<t.pendingBackendInitId||(t.pendingBackendInit=null,console.warn("Initialization of backend "+e+" failed"),console.warn(n.stack||n.message),1))}));return this.pendingBackendInit=o,{success:o,asyncInit:!0}}return this.registry[e]=r,{success:!0,asyncInit:!1}}catch(t){return console.warn("Initialization of backend "+e+" failed"),console.warn(t.stack||t.message),{success:!1,asyncInit:!1}}},e.prototype.removeBackend=function(e){if(!(e in this.registryFactory))throw new Error(e+" backend not found in registry");this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},e.prototype.getSortedBackends=function(){var e=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((function(t,n){return e.registryFactory[n].priority-e.registryFactory[t].priority}))},e.prototype.initializeBackendsAndReturnBest=function(){for(var e=this.getSortedBackends(),t=0;t<e.length;t++){var n=e[t],r=this.initializeBackend(n),i=r.success,o=r.asyncInit;if(o||i)return{name:n,asyncInit:o}}throw new Error("Could not initialize any backends, all backend initializations failed.")},e.prototype.moveData=function(e,t){var n=this.state.tensorInfo.get(t),r=n.backend,i=this.readSync(t);r.disposeData(t),n.backend=e,e.move(t,i,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},e.prototype.tidy=function(e,t){var n,r=this,i=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");i=e}return this.scopedRun((function(){return r.startScope(i)}),(function(){return r.endScope(n)}),(function(){return(n=t())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n}))},e.prototype.scopedRun=function(e,t,n){e();try{var r=n();return t(),r}catch(e){throw t(),e}},e.prototype.nextTensorId=function(){return e.nextTensorId++},e.prototype.nextVariableId=function(){return e.nextVariableId++},e.prototype.clone=function(e){var t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(function(e){return{x:function(){return e.toFloat()}}}),[]),t},e.prototype.runKernel=function(e,t,n,r,i){return this.runKernelFunc(null,t,null,e,n,r,i)},e.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},e.prototype.checkKernelForMemLeak=function(e,t,n){var r=this.backend.numDataIds(),i=0;n.forEach((function(e){i+="complex64"===e.dtype?3:1}));var o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-t-i-o;if(a>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+a+" data ids) after running '"+e+"'")},e.prototype.runKernelFunc=function(e,t,n,r,i,o,a){var s,c=this;void 0===o&&(o=[]),void 0===a&&(a=[]);var u=[],d=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var l,p=function(e){d&&(u=e.map((function(e){return c.keep(c.clone(e))})))},h=this.state.numBytes,f=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var g,v=m(r,this.backendName);return l=null!=v?function(){var e=c.backend.numDataIds();g=v.kernelFunc({inputs:t,attrs:i,backend:c.backend});var n=Array.isArray(g)?g:[g];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(r,e,n);var s=n.map((function(e){var t=e.dataId,n=e.shape,r=e.dtype;return c.makeTensorFromDataId(t,n,r)})),u=s.filter((function(e,t){return a[t]}));return p((o||[]).slice().concat(u)),s}:function(){var t=c.backend.numDataIds();g=c.tidy((function(){return e(c.backend,p)}));var n=Array.isArray(g)?g:[g];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(r,t,n),n},this.scopedRun((function(){return c.state.kernelDepth++}),(function(){return c.state.kernelDepth--}),(function(){s=c.ENV.getBool("DEBUG")?c.profiler.profileKernel(r,t,(function(){return l()})):l()})),d&&this.addTapeNode(r,t,s,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-h,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-f,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map((function(e){return t[e].shape})),outputShapes:s.map((function(e){return e.shape}))}),Array.isArray(g)?s:s[0]},e.prototype.makeTensor=function(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var i=e;"string"===n&&$(e[0])&&(i=e.map((function(e){return ce(e)})));var o=r.write(i,t,n),a=new _e(t,n,o,this.nextTensorId());if(this.incRef(a,r),"string"===n){var s=this.state.tensorInfo.get(o),c=X(i);this.state.numBytes+=c-s.bytes,s.bytes=c}return a},e.prototype.makeTensorFromDataId=function(e,t,n,r){var i=new _e(t,n=n||"float32",e,this.nextTensorId());return this.incRef(i,r),i},e.prototype.makeVariable=function(e,t,n,r){void 0===t&&(t=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.asType(r));var i=new Te(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[i.name])throw new Error("Variable with name "+i.name+" was already registered");return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i},e.prototype.incRef=function(e,t){var n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(r=e.size*K(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof Te||this.track(e)},e.prototype.disposeTensor=function(e){if(this.state.tensorInfo.has(e.dataId)){this.state.numTensors--,"string"===e.dtype&&this.state.numStringTensors--;var t=this.state.tensorInfo.get(e.dataId);t.refCount<=1?("complex64"!==e.dtype&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}},e.prototype.disposeVariables=function(){for(var e in this.state.registeredVariables){var t=this.state.registeredVariables[e];this.disposeVariable(t)}},e.prototype.disposeVariable=function(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e},e.prototype.profile=function(e){return c(this,void 0,void 0,(function(){var t,n;return u(this,(function(r){return this.state.profiling=!0,t=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(e){return e.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]}))}))},e.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},e.prototype.addTapeNode=function(e,t,n,r,i){var o=this,a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:i},s=g(e);null!=s&&(r=s.gradFunc),null!=r&&(a.gradient=function(e){return e=e.map((function(e,t){if(null==e){var r=n[t],i=oe(r.size,r.dtype);return o.makeTensor(i,r.shape,r.dtype)}return e})),r(e.length>1?e:e[0],i)}),this.state.activeTape.push(a)},e.prototype.keep=function(e){return e.kept=!0,e},e.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},e.prototype.endTape=function(){this.state.gradientDepth--},e.prototype.startScope=function(e){var t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t},e.prototype.endScope=function(e){for(var t=this,n=Ae(e),r=new Set(n.map((function(e){return e.id}))),i=0;i<this.state.activeScope.track.length;i++){var o=this.state.activeScope.track[i];o.kept||r.has(o.id)||o.dispose()}var a=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach((function(e){e.kept||e.scopeId!==a.id||t.track(e)}))},e.prototype.gradients=function(e,t,n,r){var i=this;if(void 0===r&&(r=!1),k(t.length>0,(function(){return"gradients() received an empty list of xs."})),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var o=this.scopedRun((function(){return i.startTape()}),(function(){return i.endTape()}),(function(){return i.tidy("forward",e)}));k(o instanceof _e,(function(){return"The result y returned by f() must be a tensor."}));var a=function(e,t,n){for(var r={},i={},o=0;o<t.length;o++)r[t[o].id]=!0;for(o=0;o<e.length;o++){var a=(f=e[o]).inputs;for(var s in a){for(var c=a[s],u=!1,d=0;d<t.length;d++)if(r[c.id]){f.outputs.forEach((function(e){return r[e.id]=!0})),u=!0,i[f.id]=!0;break}if(u)break}}var l={};l[n.id]=!0;var p={};for(o=e.length-1;o>=0;o--)for(a=(f=e[o]).inputs,d=0;d<f.outputs.length;d++)if(l[f.outputs[d].id]){for(var s in a)l[a[s].id]=!0,p[f.id]=!0;break}var h=[];for(o=0;o<e.length;o++){var f;if(i[(f=e[o]).id]&&p[f.id]){var m={};for(var s in f.inputs){var g=f.inputs[s];r[g.id]&&(m[s]=g)}var v=Object.assign({},f);v.inputs=m,v.outputs=f.outputs,h.push(v)}}return h}(this.state.activeTape,t,o);if(!r&&0===a.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(function(){var e,r,s={};s[o.id]=null==n?(r=ie(I(e=o.shape),"float32"),je.makeTensor(r,e,"float32")):n,function(e,t,n){for(var r=function(r){var i=t[r],o=[];if(i.outputs.forEach((function(t){var n=e[t.id];null!=n?o.push(n):o.push(null)})),null==i.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+i.kernelName+".");var a=i.gradient(o),s=function(t){if(!(t in a))throw new Error("Cannot backprop through input "+t+". Available gradients found: "+Object.keys(a)+".");var r=n((function(){return a[t]()}));if("float32"!==r.dtype)throw new Error("Error in gradient for op "+i.kernelName+". The gradient of input "+t+" must have 'float32' dtype, but has '"+r.dtype+"'");var o=i.inputs[t];if(!M(r.shape,o.shape))throw new Error("Error in gradient for op "+i.kernelName+". The gradient of input '"+t+"' has shape '"+r.shape+"', which does not match the shape of the input '"+o.shape+"'");if(null==e[o.id])e[o.id]=r;else{var s=e[o.id];e[o.id]=s.add(r),s.dispose()}};for(var c in i.inputs)s(c)},i=t.length-1;i>=0;i--)r(i)}(s,a,(function(e){return i.tidy(e)}));var c=t.map((function(e){return s[e.id]}));return 0===i.state.gradientDepth&&(i.state.activeTape.forEach((function(e){for(var t=0,n=e.saved;t<n.length;t++)n[t].dispose()})),i.state.activeTape=null),{value:o,grads:c}}))},e.prototype.customGrad=function(e){var t=this;return k(Z(e),(function(){return"The f passed in customGrad(f) must be a function."})),function(){for(var n,r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];k(r.every((function(e){return e instanceof _e})),(function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"}));var o={};return r.forEach((function(e,t){o[t]=e})),t.runKernelFunc((function(t,i){return k((n=e.apply(void 0,r.concat([i]))).value instanceof _e,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),k(Z(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),o,(function(e,t){var i=n.gradFunc(e,t),o=Array.isArray(i)?i:[i];k(o.length===r.length,(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."})),k(o.every((function(e){return e instanceof _e})),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}));var a={};return o.forEach((function(e,t){a[t]=function(){return e}})),a}))}},e.prototype.readSync=function(e){return this.state.tensorInfo.get(e).backend.readSync(e)},e.prototype.read=function(e){return this.state.tensorInfo.get(e).backend.read(e)},e.prototype.time=function(e){return c(this,void 0,void 0,(function(){var t,n;return u(this,(function(r){switch(r.label){case 0:return t=ae(),[4,this.backend.time(e)];case 1:return(n=r.sent()).wallMs=ae()-t,[2,n]}}))}))},e.prototype.track=function(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e},Object.defineProperty(e.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),e.prototype.reset=function(){for(var e in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Le,this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},e.nextTensorId=0,e.nextVariableId=0,e}(),je=function(){var e=function(){if(null==Fe){var e=void 0;if("undefined"!=typeof window)e=window;else if(void 0!==n.g)e=n.g;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Fe=e}return Fe}();if(null==e._tfengine){var t=new d(e);e._tfengine=new Be(t)}return function(e){p=e}(e._tfengine.ENV),be=function(){return e._tfengine},e._tfengine}();function We(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var ze=l();ze.registerFlag("DEBUG",(function(){return!1}),(function(e){e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),ze.registerFlag("IS_BROWSER",(function(){return We()})),ze.registerFlag("IS_NODE",(function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node})),ze.registerFlag("IS_CHROME",(function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),ze.registerFlag("PROD",(function(){return!1})),ze.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return ze.getBool("DEBUG")})),ze.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),ze.registerFlag("IS_TEST",(function(){return!1}));var Ue,Ve,Ge,qe={},He={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Ke(e,t){qe[e]=t}function Xe(e){e in qe||(qe[e]=function(e){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var t=function(e){if("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e);return t.addEventListener("webglcontextlost",(function(t){t.preventDefault(),delete qe[e]}),!1),1===e?t.getContext("webgl",He)||t.getContext("experimental-webgl",He):t.getContext("webgl2",He)}(e));var t=qe[e];return t.isContextLost()?(delete qe[e],Xe(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),qe[e])}function $e(e,t){return[t,e]}function Ye(e){var t=I(e);return F(Math.ceil(t/4))}function Qe(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Je(e,t){var n,r,i,o,a,s,c,u,d,p=e;return 2===l().getNumber("WEBGL_VERSION")?(n=p.R32F,r=p.R16F,i=p.RGBA16F,o=p.RGBA32F,a=p.RED,s=4,c=1,u=p.HALF_FLOAT,d=p.FLOAT):(n=e.RGBA,r=e.RGBA,i=e.RGBA,o=p.RGBA,a=e.RGBA,s=4,c=4,u=null!=t?t.HALF_FLOAT_OES:null,d=e.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:o,textureFormatFloat:a,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:c,textureTypeHalfFloat:u,textureTypeFloat:d}}function Ze(e,t,n){var r=n();return t&&function(e){var t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+tt(e,t))}(e),r}function et(e){return!!(l().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function tt(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+t}}function nt(e,t,n){return Ct(e,t,(function(){return e.getExtension(n)}),'Extension "'+n+'" not supported on this browser.')}function rt(e,t,n){var r=Ct(e,t,(function(){return e.createShader(e.VERTEX_SHADER)}),"Unable to create vertex WebGLShader.");if(Ze(e,t,(function(){return e.shaderSource(r,n)})),Ze(e,t,(function(){return e.compileShader(r)})),!1===e.getShaderParameter(r,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function it(e,t,n){var r=Ct(e,t,(function(){return e.createShader(e.FRAGMENT_SHADER)}),"Unable to create fragment WebGLShader.");if(Ze(e,t,(function(){return e.shaderSource(r,n)})),Ze(e,t,(function(){return e.compileShader(r)})),!1===e.getShaderParameter(r,e.COMPILE_STATUS))throw function(e,t){var n=st.exec(t);if(null==n)return console.log("Couldn't parse line number in error: "+t),void console.log(e);for(var r=+n[1],i=e.split("\n"),o=i.length.toString().length+2,a=i.map((function(e,t){return N((t+1).toString(),o)+e})),s=0,c=0;c<a.length;c++)s=Math.max(a[c].length,s);var u=a.slice(0,r-1),d=a.slice(r-1,r),l=a.slice(r);console.log(u.join("\n")),console.log(t.split("\n")[0]),console.log("%c "+N(d[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(l.join("\n"))}(n,e.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(Ue||(Ue={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(Ve||(Ve={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(Ge||(Ge={}));var ot,at,st=/ERROR: [0-9]+:([0-9]+):/g;function ct(e,t){return Ct(e,t,(function(){return e.createProgram()}),"Unable to create WebGLProgram.")}function ut(e,t,n){if(Ze(e,t,(function(){return e.linkProgram(n)})),!1===e.getProgramParameter(n,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(n)),new Error("Failed to link vertex and fragment shaders.")}function dt(e,t,n){if(Ze(e,t,(function(){return e.validateProgram(n)})),!1===e.getProgramParameter(n,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(n)),new Error("Shader program validation failed.")}function lt(e,t,n){var r=Ct(e,t,(function(){return e.createBuffer()}),"Unable to create WebGLBuffer");return Ze(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,r)})),Ze(e,t,(function(){return e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW)})),r}function pt(e,t,n){var r=Ct(e,t,(function(){return e.createBuffer()}),"Unable to create WebGLBuffer");return Ze(e,t,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,r)})),Ze(e,t,(function(){return e.bufferData(e.ELEMENT_ARRAY_BUFFER,n,e.STATIC_DRAW)})),r}function ht(e,t){return Ct(e,t,(function(){return e.createTexture()}),"Unable to create WebGLTexture.")}function ft(e,t){var n=l().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){var r="["+e+"x"+t+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(e>n||t>n)throw r="["+e+"x"+t+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function mt(e,t){return Ct(e,t,(function(){return e.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function gt(e,t,n,r,i,o,a,s){var c=e.getAttribLocation(n,r);return-1!==c&&(Ze(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,i)})),Ze(e,t,(function(){return e.vertexAttribPointer(c,o,e.FLOAT,!1,a,s)})),Ze(e,t,(function(){return e.enableVertexAttribArray(c)})),!0)}function vt(e,t,n,r){Et(e,r),Ze(e,t,(function(){return e.activeTexture(e.TEXTURE0+r)})),Ze(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)}))}function yt(e,t,n,r){return Ct(e,t,(function(){return e.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function bt(e,t,n){return e.getUniformLocation(t,n)}function wt(e,t,n,r,i,o){Ze(e,t,(function(){return vt(e,t,r,o)})),Ze(e,t,(function(){return e.uniform1i(i,o)}))}function xt(e,t,n,r){Ze(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,r)})),Ze(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}))}function _t(e,t,n){Ze(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)})),Ze(e,t,(function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)}))}function St(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Rt(e,t))}function Rt(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Ct(e,t,n,r){var i=Ze(e,t,(function(){return n()}));if(null==i)throw new Error(r);return i}function Et(e,t){var n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function kt(e,t){return void 0===t&&(t=2),I(e.slice(0,e.length-t))}function Tt(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function Dt(e){var t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[kt(e)].concat(Tt(e))),t}function Pt(e,t){var n;void 0===t&&(t=!1);var r=l().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(r*=2,1===(e=e.map((function(t,n){return n>=e.length-2?C(e[n]):e[n]}))).length&&(e=[2,e[0]])),2!==e.length){var i=W(e);e=i.newShape}var o=I(e);if(e.length<=1&&o<=r)return[1,o];if(2===e.length&&e[0]<=r&&e[1]<=r)return e;if(3===e.length&&e[0]*e[1]<=r&&e[2]<=r)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=r&&e[1]*e[2]<=r)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=r&&e[3]<=r)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=r&&e[1]*e[2]*e[3]<=r)return[e[0],e[1]*e[2]*e[3]];if(t){var a=kt(e),s=2,c=2;return e.length&&(s=(n=Tt(e))[0],c=n[1]),F(o=a*(s/2)*(c/2)).map((function(e){return 2*e}))}return F(o)}function It(e){return e%2==0}function Mt(e,t){if(M(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){var n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r)return!0;if(It(n)&&It(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&It(e[0])&&It(t[0])}function Ot(e){if(null==ot){var t=Xe(e);ot=t.getParameter(t.MAX_TEXTURE_SIZE)}return ot}function At(e){if(null==at){var t=Xe(e);at=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,at)}function Ft(e){if(0===e)return 0;var t=Xe(e);return Nt(t,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Nt(t,"EXT_disjoint_timer_query")?1:0}function Nt(e,t){return null!=e.getExtension(t)}function Lt(e){try{if(null!=Xe(e))return!0}catch(e){return!1}return!1}function Bt(e){if(0===e)return!1;var t=Xe(e);if(1===e){if(!Nt(t,"OES_texture_float"))return!1}else if(!Nt(t,"EXT_color_buffer_float"))return!1;return Wt(t)}function jt(e){if(0===e)return!1;var t=Xe(e);if(1!==e){if(Nt(t,"EXT_color_buffer_float"))return Wt(t);if(Nt(t,"EXT_color_buffer_half_float")){var n=t.getExtension("EXT_color_buffer_half_float");return function(e,t){var n=Je(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);var o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(i),o}(t,n)}return!1}return!!Nt(t,"OES_texture_float")&&!!Nt(t,"WEBGL_color_buffer_float")&&Wt(t)}function Wt(e){var t=Je(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);var i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),i}function zt(e){return 2===e&&null!=Xe(e).fenceSync}var Ut=Object.freeze({callAndCheck:Ze,canBeRepresented:et,getWebGLErrorMessage:tt,getExtensionOrThrow:nt,createVertexShader:rt,createFragmentShader:it,createProgram:ct,linkProgram:ut,validateProgram:dt,createStaticVertexBuffer:lt,createStaticIndexBuffer:pt,getNumChannels:function(){return 2===l().getNumber("WEBGL_VERSION")?1:4},createTexture:ht,validateTextureSize:ft,createFramebuffer:mt,bindVertexBufferToProgramAttribute:gt,bindTextureUnit:vt,unbindTextureUnit:function(e,t,n){Et(e,n),Ze(e,t,(function(){return e.activeTexture(e.TEXTURE0+n)})),Ze(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:yt,getProgramUniformLocation:bt,bindTextureToProgramUniformSampler:wt,bindCanvasToFramebuffer:function(e,t){Ze(e,t,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),Ze(e,t,(function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)})),Ze(e,t,(function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)}))},bindColorTextureToFramebuffer:xt,unbindColorTextureFromFramebuffer:_t,validateFramebuffer:St,getFramebufferErrorMessage:Rt,getBatchDim:kt,getRowsCols:Tt,getShapeAs3D:Dt,getTextureShapeFromLogicalShape:Pt,isReshapeFree:Mt,getWebGLMaxTextureSize:Ot,resetMaxTextureSize:function(){ot=null},resetMaxTexturesInShader:function(){at=null},getMaxTexturesInShader:At,getWebGLDisjointQueryTimerVersion:Ft,hasExtension:Nt,isWebGLVersionEnabled:Lt,isCapableOfRenderingToFloatTexture:Bt,isDownloadFloatTextureEnabled:jt,isWebGLFenceEnabled:zt}),Vt=l();function Gt(){l().set("PROD",!0)}function qt(){l().set("DEBUG",!0)}function Ht(){l().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Kt(e){l().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Xt(){je.disposeVariables()}function $t(){return je}function Yt(){return je.memory()}function Qt(e){return je.profile(e)}function Jt(e,t){return je.tidy(e,t)}function Zt(e){Ae(e).forEach((function(e){return e.dispose()}))}function en(e){return je.keep(e)}function tn(e){return je.time(e)}function nn(e){return je.setBackend(e)}function rn(){return je.ready()}function on(){return je.backendName}function an(e){je.removeBackend(e)}function sn(e){return je.findBackend(e)}function cn(e){return je.findBackendFactory(e)}function un(e,t,n){return void 0===n&&(n=1),je.registerBackend(e,t,n)}function dn(){return je.backend}function ln(e,t){l().setPlatform(e,t)}function pn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];l().getBool("IS_TEST")||console.warn.apply(console,e)}function hn(e,t){var n=e;if(H(e))return"string"===t?[]:[e.length];if(!Array.isArray(e))return[];for(var r=[];Array.isArray(n)||H(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&l().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function e(t,n,r){if(r=r||[],Array.isArray(t)||H(t)){k(n.length>0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+t.length+" elements"})),k(t.length===n[0],(function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+t.length+" elements"}));for(var i=n.slice(1),o=0;o<t.length;++o)e(t[o],i,r.concat(o))}else k(0===n.length,(function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"}))}(e,r,[]),r}function fn(e,t,n,r){if(null!=e&&("numeric"!==e&&e!==t||"numeric"===e&&"string"===t))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+e+" tensor, but got "+t+" tensor")}function mn(e,t,n,r){if(void 0===r&&(r="numeric"),e instanceof _e)return fn(r,e.dtype,t,n),e;var i=J(e);if("string"!==i&&["bool","int32","float32"].indexOf(r)>=0&&(i=r),fn(r,i,t,n),null==e||!H(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){var o=null==e?"null":e.constructor.name;throw new Error("Argument '"+t+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+o+"'")}var a=hn(e,i);H(e)||Array.isArray(e)||(e=[e]);var s="string"!==i?ne(e,i,l().getBool("DEBUG")):P(e,[],!0);return je.makeTensor(s,a,i)}function gn(e,t,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(e))throw new Error("Argument "+t+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return e.map((function(e,r){return mn(e,t+"["+r+"]",n)}),r)}function vn(e,t){for(var n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function yn(e,t,n){for(var r=e.length+t.length,i=[],o=0,a=0,s=0;s<r;s++)-1===n.indexOf(s)?i.push(e[o++]):i.push(t[a++]);return i}function bn(e,t){for(var n=[],r=e.length,i=0;i<r;i++)-1===t.indexOf(i)&&n.push(e[i]);return[n,t.map((function(t){return e[t]}))]}function wn(e,t){return yn(e,t.map((function(e){return 1})),t)}function xn(e,t,n){k(vn(t,n),(function(){return e+" supports only inner-most axes for now. Got axes "+t+" and rank-"+n+" input."}))}function _n(e,t){if(vn(e,t))return null;for(var n=[],r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach((function(e){return n.push(e)})),n}function Sn(e){return e.map((function(e,t){return[t,e]})).sort((function(e,t){return e[1]-t[1]})).map((function(e){return e[0]}))}function Rn(e,t){for(var n=[],r=t-e;r<t;++r)n.push(r);return n}function Cn(e,t){var n=e[0].length;e.forEach((function(e,t){k(e.length===n,(function(){return"Error in concat"+n+"D: rank of tensors["+t+"] must be the same as the rank of the rest ("+n+")"}))})),k(t>=0&&t<n,(function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."}));var r=e[0];e.forEach((function(e,i){for(var o=0;o<n;o++)k(o===t||e[o]===r[o],(function(){return"Error in concat"+n+"D: Shape of tensors["+i+"] ("+e+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+i+"."}))}))}function En(e,t){for(var n=e[0].slice(),r=1;r<e.length;r++)n[t]+=e[r][t];return n}function kn(e){var t=Object.keys(e);if(1!==t.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+t.length+" keys.");var n=t[0],r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var i=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];je.startScope(n);try{var i=r.apply(void 0,e);return i instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),je.endScope(i),i}catch(e){throw je.endScope(null),e}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}Vt.registerFlag("HAS_WEBGL",(function(){return Vt.getNumber("WEBGL_VERSION")>0})),Vt.registerFlag("WEBGL_VERSION",(function(){return Lt(2)?2:Lt(1)?1:0})),Vt.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===Vt.get("WEBGL_VERSION")})),Vt.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),Vt.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),Vt.registerFlag("WEBGL_PACK",(function(){return Vt.getBool("HAS_WEBGL")})),Vt.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_PACK_CLIP",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),Vt.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_PACK_REDUCE",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_CONV_IM2COL",(function(){return Vt.getBool("WEBGL_PACK")})),Vt.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Ot(Vt.getNumber("WEBGL_VERSION"))})),Vt.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return At(Vt.getNumber("WEBGL_VERSION"))})),Vt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var e=Vt.getNumber("WEBGL_VERSION");return 0===e?0:Ft(e)})),Vt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return Vt.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(e=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))));var e})),Vt.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return Bt(Vt.getNumber("WEBGL_VERSION"))})),Vt.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!Vt.getBool("WEBGL_FORCE_F16_TEXTURES")&&Vt.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),Vt.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return jt(Vt.getNumber("WEBGL_VERSION"))})),Vt.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return zt(Vt.getNumber("WEBGL_VERSION"))})),Vt.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return Vt.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),xe=Kt;var Tn=kn({complex_:function(e,t){var n=mn(e,"real","complex"),r=mn(t,"imag","complex");return T(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),je.runKernelFunc((function(e){return e.complex(n,r)}),{$real:n,$imag:r})}}),Dn=kn({real_:function(e){var t=mn(e,"input","real");return je.runKernelFunc((function(e){return e.real(t)}),{$input:t})}}),Pn=kn({imag_:function(e){var t=mn(e,"input","imag");return je.runKernelFunc((function(e){return e.imag(t)}),{$input:t})}});function In(e,t,n){return Mn(e,t,hn(e,n),n)}function Mn(e,t,n,r){if(null==r&&(r=J(e)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!H(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){se(t);var i=I(t),o=I(n);k(i===o,(function(){return"Based on the provided shape, ["+t+"], the tensor should have "+i+" values but has "+o}));for(var a=0;a<n.length;++a){var s=n[a],c=a!==n.length-1||s!==I(t.slice(a));k(n[a]===t[a]||!c,(function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+t+"). "}))}}return H(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?ne(e,r,l().getBool("DEBUG")):P(e,[],!0),je.makeTensor(e,t,r)}function On(e,t){if((H(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&H(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Mn(e,[],[],t)}function An(e,t){D(e);var n=hn(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Mn(e,null,n,t)}function Fn(e,t,n){if(D(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");var r=hn(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Mn(e,t,r,n)}function Nn(e,t,n){if(D(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");var r=hn(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Mn(e,t,r,n)}function Ln(e,t,n){if(D(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");var r=hn(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Mn(e,t,r,n)}function Bn(e,t,n){if(D(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");var r=hn(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Mn(e,t,r,n)}function jn(e,t,n){if(D(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");var r=hn(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Mn(e,t=t||r,r,n)}function Wn(e,t,n,r){return void 0===t&&(t=!0),je.makeVariable(e,t,n,r)}function zn(e,t){if(void 0===t&&(t="float32"),"complex64"===t){var n=zn(e,"float32"),r=Un(e,"float32");return Tn(n,r)}var i=ie(I(e),t);return je.makeTensor(i,e,t)}function Un(e,t){if(void 0===t&&(t="float32"),"complex64"===t){var n=Un(e,"float32"),r=Un(e,"float32");return Tn(n,r)}var i=oe(I(e),t);return je.makeTensor(i,e,t)}function Vn(e,t,n){return je.runKernelFunc((function(r){return r.fill(e,t,n)}),{})}function Gn(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");return je.runKernelFunc((function(r){return r.linspace(e,t,n)}),{})}function qn(e,t,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(e===t||e<t&&n<0||t<e&&n>1)return Un([0],r);var i=oe(Math.abs(Math.ceil((t-e)/n)),r);t<e&&1===n&&(n=-1),i[0]=e;for(var o=1;o<i.length;o++)i[o]=i[o-1]+n;return An(i,r)}var Hn=kn({onesLike_:function(e){var t=mn(e,"x","onesLike");if("complex64"===t.dtype){var n=Hn(Dn(t)),r=Kn(Pn(t));return Tn(n,r)}return je.runKernelFunc((function(e){return e.onesLike(t)}),{$x:t},(function(e,t){return{$x:function(){return Kn(e)}}}))}}),Kn=kn({zerosLike_:function(e){var t=mn(e,"x","zerosLike");return je.runKernelFunc((function(e){return e.zerosLike(t)}),{$x:t},(function(e,t){return{$x:function(){return Kn(e)}}}))}}),Xn=kn({concat_:function(e,t){void 0===t&&(t=0),k(e.length>=1,(function(){return"Pass at least one tensor to concat"}));var n=gn(e,"tensors","concat");"complex64"===n[0].dtype&&n.forEach((function(e){if("complex64"!==e.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+e.dtype+". ")})),t=j(t,n[0].shape)[0];var r=En(n.map((function(e){return e.shape})),t);if(0===I(r))return In([],r);if(1===(n=n.filter((function(e){return e.size>0}))).length)return n[0];var i=n.map((function(e){return e.shape}));Cn(i,t);var o=n,a={axis:t};return je.runKernelFunc((function(e){return e.concat(n,t)}),o,(function(e){var n=i.map((function(e){return e[t]}));return Zn(e,n,t).map((function(e){return function(){return e}}))}),"Concat",a)}}),$n=kn({concat1d_:function(e){return Xn(e,0)}}),Yn=kn({concat2d_:function(e,t){return Xn(e,t)}}),Qn=kn({concat3d_:function(e,t){return Xn(e,t)}}),Jn=kn({concat4d_:function(e,t){return Xn(e,t)}}),Zn=kn({split_:function(e,t,n){void 0===n&&(n=0);var r,i=mn(e,"x","split");return n=j(n,i.shape)[0],"number"==typeof t?(k(i.shape[n]%t==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(t).fill(i.shape[n]/t)):(k(i.shape[n]===t.reduce((function(e,t){return e+t})),(function(){return"The sum of sizes must match the size of the axis dimension."})),r=t),je.runKernelFunc((function(e){return e.split(i,r,n)}),{$x:i},(function(e){return{$x:function(){return Xn(e,n)}}}))}});function er(e,t){return e(t={exports:{}},t.exports),t.exports}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self&&self;var tr=er((function(e){!function(e,t,n){function r(e){var t,n=this,r=(t=4022871197,function(e){e=e.toString();for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function o(e,t){var n=new r(e),o=t&&t.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,o&&("object"==typeof o&&i(o,n),a.state=function(){return i(n,{})}),a}t&&t.exports?t.exports=o:this.alea=o}(0,e)})),nr=er((function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function o(e,t){var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&i(o,n),a.state=function(){return i(n,{})}),a}t&&t.exports?t.exports=o:this.xor128=o}(0,e)})),rr=er((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function o(e,t){var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&i(o,n),a.state=function(){return i(n,{})}),a}t&&t.exports?t.exports=o:this.xorwow=o}(0,e)})),ir=er((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,i=t.i;return e=r[i],n=(e^=e>>>7)^e<<24,n^=(e=r[i+1&7])^e>>>10,n^=(e=r[i+3&7])^e>>>3,n^=(e=r[i+4&7])^e<<7,e=r[i+7&7],n^=(e^=e<<13)^e<<9,r[i]=n,t.i=i+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function o(e,t){null==e&&(e=+new Date);var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&(o.x&&i(o,n),a.state=function(){return i(n,{})}),a}t&&t.exports?t.exports=o:this.xorshift7=o}(0,e)})),or=er((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,i=t.X,o=t.i;return t.w=r=r+1640531527|0,n=i[o+34&127],e=i[o=o+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=i[o]=n^e,t.i=o,n+(r^r>>>16)|0},function(e,t){var n,r,i,o,a,s=[],c=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,c=Math.max(c,t.length)),i=0,o=-32;o<c;++o)t&&(r^=t.charCodeAt((o+32)%t.length)),0===o&&(a=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,i=0==(n=s[127&o]^=r+a)?i+1:0);for(i>=128&&(s[127&(t&&t.length||0)]=-1),i=127,o=512;o>0;--o)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=a,e.X=s,e.i=i}(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function o(e,t){null==e&&(e=+new Date);var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&(o.X&&i(o,n),a.state=function(){return i(n,{})}),a}t&&t.exports?t.exports=o:this.xor4096=o}(0,e)})),ar=er((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function o(e,t){var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&i(o,n),a.state=function(){return i(n,{})}),a}t&&t.exports?t.exports=o:this.tychei=o}(0,e)})),sr=er((function(e){!function(t,r){var i,o=this,a=256,s="random",c=r.pow(a,6),u=r.pow(2,52),d=2*u,l=a-1;function p(e,n,l){var p=[],v=m(function e(t,n){var r,i=[],o=typeof t;if(n&&"object"==o)for(r in t)try{i.push(e(t[r],n-1))}catch(e){}return i.length?i:"string"==o?t:t+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[e,g(t)]:null==e?function(){try{var e;return i&&(e=i.randomBytes)?e=e(a):(e=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(e)),g(e)}catch(e){var n=o.navigator,r=n&&n.plugins;return[+new Date,o,r,o.screen,g(t)]}}():e,3),p),y=new h(p),b=function(){for(var e=y.g(6),t=c,n=0;e<u;)e=(e+n)*a,t*=a,n=y.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,m(g(y.S),t),(n.pass||l||function(e,t,n,i){return i&&(i.S&&f(i,y),e.state=function(){return f(y,{})}),n?(r[s]=e,t):e})(b,v,"global"in n?n.global:this==r,n.state)}function h(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=l&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=l&i+1],n=n*a+s[l&(s[i]=s[o=l&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function f(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function m(e,t){for(var n,r=e+"",i=0;i<r.length;)t[l&i]=l&(n^=19*t[l&i])+r.charCodeAt(i++);return g(t)}function g(e){return String.fromCharCode.apply(0,e)}if(r["seed"+s]=p,m(r.random(),t),e.exports){e.exports=p;try{i=n(4902)}catch(e){}}}([],Math)}));sr.alea=tr,sr.xor128=nr,sr.xorwow=rr,sr.xorshift7=ir,sr.xor4096=or,sr.tychei=ar;var cr=sr.alea,ur=function(){function e(e,t,n,r,i){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var o=i||Math.random();this.random=cr(o.toString())}return e.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var e=this.nextVal;return this.nextVal=NaN,e}for(var t,n,r=!1;!r;){var i=void 0,o=void 0,a=void 0;do{a=(i=2*this.random()-1)*i+(o=2*this.random()-1)*o}while(a>=1||0===a);var s=Math.sqrt(-2*Math.log(a)/a);t=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*o*s,this.truncated&&!this.isValidTruncated(t)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}(),dr=function(){function e(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;var i=r||Math.random();this.randu=cr(i.toString()),this.randn=new ur(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}return e.prototype.nextValue=function(){for(var e,t,n,r,i,o;;){do{r=this.randn.nextValue(),o=1+this.c*r}while(o<=0);if(o*=o*o,t=1-.331*(e=r*r)*e,n=.5*e+this.d*(1-o+Math.log(o)),(i=this.randu())<t||Math.log(i)<n)break}return o=1/this.beta*this.d*o,this.alpha<1&&(o*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(o)},e.prototype.convertValue=function(e){return"float32"===this.dtype?e:Math.round(e)},e}(),lr=function(){function e(e,t,n,r){var i=this;if(void 0===e&&(e=0),void 0===t&&(t=1),this.canReturnFloat=function(){return null==i.dtype||"float32"===i.dtype},this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+e+" - "+t+" <= 1 and dtype is not float");this.random=cr(r)}return e.prototype.convertValue=function(e){return this.canReturnFloat()?e:Math.round(e)},e.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},e}();function pr(e,t,n){return void 0===t&&(t="float32"),t=t||"float32",se(e),new ye(e,t,n)}function hr(e,t){void 0===t&&(t=!1),console.log(e.toString(t))}var fr=kn({batchToSpaceND_:function(e,t,n){var r=mn(e,"x","batchToSpaceND"),i=t.reduce((function(e,t){return e*t}));return k(r.rank>=1+t.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+t.length})),k(n.length===t.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+t.length})),k(r.shape[0]%i==0,(function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+t.join(" * ")+" === "+i})),je.runKernelFunc((function(e){return e.batchToSpaceND(r,t,n)}),{$x:r},(function(e){return{$x:function(){return e.spaceToBatchND(t,n)}}}))}}),mr=kn({broadcastTo_:function(e,t){var n=mn(e,"broadcastTo","x"),r=n.shape;if(t.some((function(e){return!(e>0)||e%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+t+"].");if(t.length<n.rank)throw new Error("broadcastTo(): shape.length="+t.length+" < input.rank="+n.rank+".");if(t.length>n.rank){for(var i=n.shape.slice();i.length<t.length;)i.unshift(1);n=n.reshape(i)}for(var o=Array.from(t),a=t.length-1;a>=0;a--)if(n.shape[a]===t[a])o[a]=1;else if(1!==n.shape[a])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+t+"].");var s=o.map((function(e,t){return e>1?t:-1})).filter((function(e){return e>=0}));return 0===s.length?n.clone():je.runKernelFunc((function(e){return e.tile(n,o)}),{input:n},(function(e){return{input:function(){return e.sum(s,!0)}}}))}}),gr=kn({cast_:function(e,t){var n=mn(e,"x","cast");if(!G(t))throw new Error("Failed to cast to unknown dtype "+t);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");var r={dtype:t};return je.runKernelFunc((function(e){return e.cast(n,t)}),{x:n},(function(e){return{x:function(){return e.clone()}}}),"Cast",r)}}),vr=kn({clone_:function(e){var t=mn(e,"x","clone",null);return je.runKernelFunc((function(){return je.makeTensorFromDataId(t.dataId,t.shape,t.dtype)}),{$x:t},(function(e){return{$x:function(){return e.toFloat()}}}))}}),yr=kn({cumsum_:function(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var i=mn(e,"x","cumsum"),o=_n([t|=0],i.rank),a=i;null!=o&&(a=i.transpose(o));var s=Rn(1,i.rank)[0],c=je.runKernelFunc((function(e){return e.cumsum(a,s,n,r)}),{permutedX:a},(function(e){return{permutedX:function(){return e.cumsum(t,n,!r)}}}));return null!=o&&(c=c.transpose(o)),c}}),br=kn({depthToSpace_:function(e,t,n){void 0===n&&(n="NHWC");var r=mn(e,"x","depthToSpace"),i="NHWC"===n?r.shape[1]:r.shape[2],o="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];return k(i*t>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+t+" for depthToSpace with input shape\n "+r.shape})),k(o*t>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+o+" and "+t+" for depthToSpace with input shape\n "+r.shape})),k(a%(t*t)==0,(function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+a+" for depthToSpace with input shape "+r.shape})),je.runKernelFunc((function(e){return e.depthToSpace(r,t,n)}),{$x:r})}}),wr=kn({expandDims_:function(e,t){void 0===t&&(t=0);var n=mn(e,"x","expandDims",null);k(t<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return t<0&&(k(-(n.rank+1)<=t,(function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"})),t=n.rank+t+1),r.splice(t,0,1),Or(n,r)}}),xr=kn({eye_:function(e,t,n,r){void 0===r&&(r="float32"),null==t&&(t=e);for(var i=pr([e,t],r),o=e<=t?e:t,a=0;a<o;++a)i.set(1,a,a);var s=i.toTensor().as2D(e,t);if(null==n)return s;if(1===n.length)return Lr(wr(s,0),[n[0],1,1]);if(2===n.length)return Lr(wr(wr(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return Lr(wr(wr(wr(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.")}}),_r=kn({multinomial_:function(e,t,n,r){void 0===r&&(r=!1);var i=mn(e,"logits","multinomial"),o=i.size,a=i.rank;if(o<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+o+".");if(a>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);n=n||Math.random();var s=1===a?i.as2D(1,-1):i,c=je.runKernelFunc((function(e){return e.multinomial(s,r,t,n)}),{logits2D:s});return 1===a?c.as1D():c}}),Sr=kn({oneHot_:function(e,t,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);var i=mn(e,"indices","oneHot","int32"),o=i.shape.concat([t]);return i=i.flatten(),je.runKernelFunc((function(e){return e.oneHot(i,t,n,r)}),{$indices:i},(function(e){return{$indices:function(){return Un(i.shape,"float32")}}})).reshape(o)}}),Rr=kn({pad_:function(e,t,n){void 0===n&&(n=0);var r=mn(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var i={paddings:t,constantValue:n};return je.runKernelFunc((function(e){return e.pad(r,t,n)}),{x:r},(function(e){var n=t.map((function(e){return e[0]}));return{x:function(){return e.slice(n,r.shape)}}}),"PadV2",i)}}),Cr=kn({pad1d_:function(e,t,n){return void 0===n&&(n=0),k(2===t.length,(function(){return"Invalid number of paddings. Must be length of 2."})),Rr(e,[t],n)}}),Er=kn({pad2d_:function(e,t,n){return void 0===n&&(n=0),k(2===t.length&&2===t[0].length&&2===t[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Rr(e,t,n)}}),kr=kn({pad3d_:function(e,t,n){return void 0===n&&(n=0),k(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Rr(e,t,n)}}),Tr=kn({pad4d_:function(e,t,n){return void 0===n&&(n=0),k(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Rr(e,t,n)}}),Dr=kn({rand_:function(e,t,n){var r=I(e),i=null;if(null==n||"float32"===n)i=new Float32Array(r);else if("int32"===n)i=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);i=new Uint8Array(r)}for(var o=0;o<r;o++)i[o]=t();return je.makeTensor(i,e,n)}}),Pr=kn({randomNormal_:function(e,t,n,r,i){if(void 0===t&&(t=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var o=new ur(t,n,r,!1,i),a=pr(e,r),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),Ir=kn({randomGamma_:function(e,t,n,r,i){if(void 0===n&&(n=1),void 0===r&&(r="float32"),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);for(var o=new dr(t,n,r,i),a=pr(e,r),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),Mr=kn({randomUniform_:function(e,t,n,r,i){void 0===t&&(t=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var o=pr(e,r),a=new lr(t,n,null,i),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),Or=kn({reshape_:function(e,t){var n=mn(e,"x","reshape",null);t=B(t,n.size),k(n.size===I(t),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:t};return je.runKernelFunc((function(e){return e.reshape(n,t)}),{x:n},(function(e){return{x:function(){return e.reshape(n.shape)}}}),"Reshape",r)}}),Ar=kn({spaceToBatchND_:function(e,t,n){var r=mn(e,"x","spaceToBatchND");return k(r.rank>=1+t.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+t.length})),k(n.length===t.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+t.length})),k(r.shape.reduce((function(e,r,i){return i>0&&i<=t.length?e&&(r+n[i-1][0]+n[i-1][1])%t[i-1]==0:e}),!0),(function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+t.toString()})),je.runKernelFunc((function(e){return e.spaceToBatchND(r,t,n)}),{$x:r},(function(e){return{$x:function(){return e.batchToSpaceND(t,n)}}}))}}),Fr=kn({squeeze_:function(e,t){var n=mn(e,"x","squeeze");return Or(n,W(n.shape,t).newShape)}}),Nr=kn({stack_:function(e,t){void 0===t&&(t=0);var n=gn(e,"tensors","stack");if(k(n.length>=1,(function(){return"Pass at least one tensor to tf.stack"})),1===n.length)return n[0].expandDims(t);var r=n[0].rank,i=n[0].shape,o=n[0].dtype;k(t<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(e){T(i,e.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(e){k(o===e.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var a=n.map((function(e){return e.expandDims(t)}));return Xn(a,t)}}),Lr=kn({tile_:function(e,t){var n=mn(e,"x","tile",null);k(n.rank===t.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+t+"."}));var r=[n],i={reps:t};return je.runKernelFunc((function(e,r){var i=e.tile(n,t);return r([n]),i}),{x:n},(function(e,n){var r=n[0];return{x:function(){var n=Kn(r);if(1===r.rank)for(var i=0;i<t[0];++i)n=n.add(e.slice([i*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(i=0;i<t[0];++i)for(var o=0;o<t[1];++o)n=n.add(e.slice([i*r.shape[0],o*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(i=0;i<t[0];++i)for(o=0;o<t[1];++o)for(var a=0;a<t[2];++a)n=n.add(e.slice([i*r.shape[0],o*r.shape[1],a*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(i=0;i<t[0];++i)for(o=0;o<t[1];++o)for(a=0;a<t[2];++a)for(var s=0;s<t[3];++s)n=n.add(e.slice([i*r.shape[0],o*r.shape[1],a*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}}),"Tile",i,r)}}),Br=kn({truncatedNormal_:function(e,t,n,r,i){if(void 0===t&&(t=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var o=new ur(t,n,r,!0,i),a=pr(e,r),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),jr=kn({unstack_:function(e,t){void 0===t&&(t=0),t=t||0;var n=mn(e,"x","unstack");k(t>=-n.shape.length&&t<n.shape.length,(function(){return"Axis = "+t+" is not in [-"+n.shape.length+", "+n.shape.length+")"})),t<0&&(t+=n.shape.length);var r={axis:t};return je.runKernelFunc((function(e){return e.unstack(n,t)}),{x:n},(function(e){return{x:function(){return Nr(e,t)}}}),"Unpack",r)}}),Wr=function(e,t){return c(this,void 0,void 0,(function(){var n,r,i,o,a,s,c,d,l,p;return u(this,(function(u){switch(u.label){case 0:return n=mn(e,"x","setdiff1d"),r=mn(t,"y","setdiff1d"),k(n.dtype===r.dtype,(function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."})),k(1===n.rank,(function(){return"x should be 1D tensor, but got x ("+n.shape+")."})),k(1===r.rank,(function(){return"y should be 1D tensor, but got y ("+r.shape+")."})),[4,n.data()];case 1:return i=u.sent(),[4,r.data()];case 2:for(o=u.sent(),a=new Set(o),s=0,l=0;l<i.length;l++)a.has(i[l])||s++;for(c=new ye([s],n.dtype),d=new ye([s],"int32"),l=0,p=0;l<i.length;l++)a.has(i[l])||(c.values[p]=i[l],d.values[p]=l,p++);return[2,[c.toTensor(),d.toTensor()]]}}))}))};function zr(e,t,n,r){void 0===r&&(r=!0);var i=[];if(r)(i=i.concat(t.slice(0))).push(e[0]/n),i=i.concat(e.slice(1));else{i=i.concat(e[0]);for(var o=t.length,a=0;a<o;++a)i=i.concat([e[a+1]/t[a],t[a]]);i=i.concat(e.slice(o+1))}return i}function Ur(e,t,n){void 0===n&&(n=!0);var r=[];if(n){r.push(t);for(var i=t+1;i<e;++i)i<=2*t?(r.push(i),r.push(i-(t+1))):r.push(i)}else{var o=[],a=[];for(i=1;i<e;++i)i>=2*t+1||i%2==1?a.push(i):o.push(i);r.push.apply(r,o),r.push(0),r.push.apply(r,a)}return r}function Vr(e,t,n,r){void 0===r&&(r=!0);var i=[];r?i.push(e[0]/n):i.push(e[0]*n);for(var o=1;o<e.length;++o)o<=t.length?r?i.push(t[o-1]*e[o]):i.push(e[o]/t[o-1]):i.push(e[o]);return i}function Gr(e,t){for(var n=[0],r=0;r<t;++r)n.push(e[r][0]);return n}function qr(e,t,n){for(var r=e.slice(0,1),i=0;i<n;++i)r.push(e[i+1]-t[i][0]-t[i][1]);return r}function Hr(e,t){if(e.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==t.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.shape[t.rank-1]>e.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+e.rank);if(0===e.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+e.shape+".");for(var n=t.shape,r=n[n.length-1],i=1,o=0;o<n.length-1;++o)i*=n[o];var a=e.shape,s=n.slice();s.pop();var c=1;for(o=r;o<e.rank;++o)c*=a[o],s.push(a[o]);var u=te(e.shape).map((function(e){return e/c})).concat([1]).slice(0,r);return[s,i,c,u]}var Kr=Object.freeze({prepareAndValidate:Hr});function Xr(e){return e<=30?e:ee(e,Math.floor(Math.sqrt(e)))}function $r(e,t,n){var r=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+t.shape+", shape: "+e+", sliceDim: "+r+", and batchDim: "+i+".";if(n.rank<i)throw new Error(o+" update.rank < "+i+". ");if(e.length<r+(n.rank-i))throw new Error(o+" Output shape length < "+(r+(n.rank-i)));if(n.rank!==i+e.length-r)throw new Error(o+" update.rank != "+(i+e.length-r));for(var a=0;a<i;++a)if(n.shape[a]!==t.shape[a])throw new Error(o+" updates.shape["+a+"] ("+n.shape[a]+") != indices.shape["+a+"] ("+t.shape[a]+").");for(a=0;a<n.rank-i;++a)if(n.shape[a+i]!==e[a+r])throw new Error(o+" updates.shape["+(a+i)+"] ("+n.shape[a+i]+") != shape["+(a+i)+"] ("+e[a+i]+")")}function Yr(e,t,n){if(t.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==t.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+t.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===t.size)throw new Error("Indices specified for empty output. indices shape: "+t.shape);if(0===e.size)throw new Error("Updates specified for empty output. updates shape: "+e.shape)}$r(n,t,e)}function Qr(e,t,n){for(var r=t.shape.length,i=r>1?t.shape[r-1]:1,o=n.length,a=1,s=i;s<o;++s)a*=n[s];var c=i<1?1:i;return{sliceRank:i,numUpdates:I(t.shape)/c,sliceSize:a,strides:te(n.slice(0,i)).concat([1]),outputSize:I(n)}}var Jr=Object.freeze({validateUpdateShape:$r,validateInput:Yr,calculateShapes:Qr});function Zr(e,t,n){k(e.rank===t.length,(function(){return"Error in slice"+e.rank+"D: Length of begin "+t+" must match the rank of the array ("+e.rank+")."})),k(e.rank===n.length,(function(){return"Error in slice"+e.rank+"D: Length of size "+n+" must match the rank of the array ("+e.rank+")."}));for(var r=function(r){k(t[r]+n[r]<=e.shape[r],(function(){return"Error in slice"+e.rank+"D: begin["+r+"] + size["+r+"] ("+(t[r]+n[r])+") would overflow input.shape["+r+"] ("+e.shape[r]+")"}))},i=0;i<e.rank;++i)r(i)}function ei(e){for(var t=[],n=0;e>0;)1&e&&t.push(n),e/=2,n++;return t}function ti(e,t,n){for(var r=[],i=0;i<e.length;i++)r[i]=Math.ceil((t[i]-e[i])/n[i]);return r}function ni(e,t,n,r,i){var o=t[i],a=n[i]||1;(e&1<<i||null==o)&&(o=a>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[i];return o<0&&(o+=s),R(0,o,s-1)}function ri(e,t,n,r,i){var o=t[i],a=n[i]||1;(e&1<<i||null==o)&&(o=a>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[i];return o<0&&(o+=s),a>0?R(0,o,s):R(-1,o,s-1)}function ii(e,t,n){for(var r=n.length,i=0;i<n.length;i++)if(n[i]>1){r=i;break}for(i=r+1;i<n.length;i++)if(t[i]>0||n[i]!==e[i])return!1;return!0}function oi(e,t){for(var n=e.length>0?e[e.length-1]:1,r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}var ai=Object.freeze({assertParamsValid:Zr,maskToAxes:ei,computeOutShape:ti,startForAxis:ni,stopForAxis:ri,isSliceContinous:ii,computeFlatOffset:oi});function si(e){return k(Z(e),(function(){return"The f passed in grad(f) must be a function"})),function(t,n){var r=mn(t,"x","tf.grad",null),i=null!=n?mn(n,"dy","tf.grad"):null;return je.tidy((function(){var t=je.gradients((function(){return e(r)}),[r],i),n=t.value,o=t.grads;return null!=i&&T(n.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),hi(o),o[0]}))}}function ci(e){return k(Z(e),(function(){return"The f passed in grads(f) must be a function"})),function(t,n){k(Array.isArray(t),(function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"}));var r=gn(t,"args","tf.grads",null),i=null!=n?mn(n,"dy","tf.grads"):null;return je.tidy((function(){var t=je.gradients((function(){return e.apply(void 0,r)}),r,i),n=t.value,o=t.grads;return null!=i&&T(n.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),hi(o),o}))}}function ui(e){return k(Z(e),(function(){return"The f passed in valueAndGrad(f) must be a function"})),function(t,n){k(t instanceof _e,(function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"})),k(null==n||n instanceof _e,(function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"}));var r=je.gradients((function(){return e(t)}),[t],n),i=r.grads,o=r.value;return hi(i),{grad:i[0],value:o}}}function di(e){return k(Z(e),(function(){return"The f passed in valueAndGrads(f) must be a function"})),function(t,n){k(Array.isArray(t)&&t.every((function(e){return e instanceof _e})),(function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"})),k(null==n||n instanceof _e,(function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"}));var r=je.gradients((function(){return e.apply(void 0,t)}),t,n);return null!=n&&T(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),hi(r.grads),r}}function li(e,t){k(Z(e),(function(){return"The f passed in variableGrads(f) must be a function"})),k(null==t||Array.isArray(t)&&t.every((function(e){return e instanceof Te})),(function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"}));var n=null!=t;if(!n)for(var r in t=[],je.registeredVariables)t.push(je.registeredVariables[r]);var i=n?t.filter((function(e){return!e.trainable})):null,o=t.length;k((t=t.filter((function(e){return e.trainable}))).length>0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+o+" variables is trainable."}));var a=je.gradients(e,t,null,!0),s=a.value,c=a.grads;k(c.some((function(e){return null!=e})),(function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."})),k(0===s.rank,(function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"}));var u={};return t.forEach((function(e,t){null!=c[t]&&(u[e.name]=c[t])})),null!=i&&i.forEach((function(e){return u[e.name]=null})),{value:s,grads:u}}function pi(e){return je.customGrad(e)}function hi(e){if(e.filter((function(e){return null==e})).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var fi=kn({softmax_:function(e,t){void 0===t&&(t=-1);var n=mn(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+t);return je.runKernelFunc((function(e,r){var i=e.softmax(n,t);return r([i]),i}),{logits:n},(function(e,n){var r=n[0],i=e.mul(r);return{logits:function(){return i.sub(i.sum([t],!0).mul(r))}}}),"Softmax",{dim:t},[],[!0])}}),mi=kn({logSoftmax_:function(e,t){void 0===t&&(t=-1);var n=mn(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+t);return pi((function(e,n){var r=e.max(t,!0),i=e.sub(r),o=i.toFloat().sub(i.exp().sum(t,!0).log());return n([o]),{value:o,gradFunc:function(e,n){var r=n[0].exp();return e.sub(e.sum(t,!0).mul(r))}}}))(n)}}),gi=function(){function e(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}return e.prototype.get=function(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)},e.prototype.set=function(e,t){this.dataIdsCount++,this.data.set(e,t)},e.prototype.has=function(e){return this.data.has(e)},e.prototype.delete=function(e){return this.dataIdsCount--,this.data.delete(e)},e.prototype.numDataIds=function(){return this.dataIdsCount},e}(),vi=function(){function e(){}return e.prototype.time=function(e){return yi("time")},e.prototype.read=function(e){return yi("read")},e.prototype.readSync=function(e){return yi("readSync")},e.prototype.numDataIds=function(){return yi("numDataIds")},e.prototype.disposeData=function(e){return yi("disposeData")},e.prototype.write=function(e,t,n){return yi("write")},e.prototype.move=function(e,t,n,r){return yi("move")},e.prototype.memory=function(){return yi("memory")},e.prototype.floatPrecision=function(){return yi("floatPrecision")},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.batchMatMul=function(e,t,n,r){return yi("batchMatMul")},e.prototype.fusedBatchMatMul=function(e){return e.a,e.b,e.transposeA,e.transposeB,e.bias,e.activation,e.preluActivationWeights,yi("fusedBatchMatMul")},e.prototype.slice=function(e,t,n){return yi("slice")},e.prototype.stridedSlice=function(e,t,n,r){return yi("stridedSlice")},e.prototype.unstack=function(e,t){return yi("unstack")},e.prototype.reverse=function(e,t){return yi("reverse")},e.prototype.concat=function(e,t){return yi("concat")},e.prototype.neg=function(e){return yi("neg")},e.prototype.add=function(e,t){return yi("add")},e.prototype.addN=function(e){return yi("addN")},e.prototype.subtract=function(e,t){return yi("subtract")},e.prototype.multiply=function(e,t){return yi("multiply")},e.prototype.realDivide=function(e,t){return yi("realDivide")},e.prototype.floorDiv=function(e,t){return yi("floorDiv")},e.prototype.sum=function(e,t){return yi("sum")},e.prototype.prod=function(e,t){return yi("prod")},e.prototype.unsortedSegmentSum=function(e,t,n){return yi("unsortedSegmentSum")},e.prototype.argMin=function(e,t){return yi("argMin")},e.prototype.argMax=function(e,t){return yi("argMax")},e.prototype.equal=function(e,t){return yi("equal")},e.prototype.notEqual=function(e,t){return yi("notEqual")},e.prototype.less=function(e,t){return yi("less")},e.prototype.lessEqual=function(e,t){return yi("lessEqual")},e.prototype.greater=function(e,t){return yi("greater")},e.prototype.greaterEqual=function(e,t){return yi("greaterEqual")},e.prototype.logicalNot=function(e){return yi("logicalNot")},e.prototype.logicalAnd=function(e,t){return yi("logicalAnd")},e.prototype.logicalOr=function(e,t){return yi("logicalOr")},e.prototype.where=function(e){return yi("where")},e.prototype.select=function(e,t,n){return yi("select")},e.prototype.topk=function(e,t,n){return yi("topk")},e.prototype.min=function(e,t){return yi("min")},e.prototype.minimum=function(e,t){return yi("minimum")},e.prototype.mod=function(e,t){return yi("mod")},e.prototype.max=function(e,t){return yi("max")},e.prototype.maximum=function(e,t){return yi("maximum")},e.prototype.all=function(e,t){return yi("all")},e.prototype.any=function(e,t){return yi("any")},e.prototype.squaredDifference=function(e,t){return yi("squaredDifference")},e.prototype.ceil=function(e){return yi("ceil")},e.prototype.floor=function(e){return yi("floor")},e.prototype.round=function(e){return yi("round")},e.prototype.sign=function(e){return yi("sign")},e.prototype.isNaN=function(e){return yi("isNaN")},e.prototype.isInf=function(e){return yi("isInf")},e.prototype.isFinite=function(e){return yi("isFinite")},e.prototype.pow=function(e,t){return yi("pow")},e.prototype.exp=function(e){return yi("exp")},e.prototype.expm1=function(e){return yi("expm1")},e.prototype.softmax=function(e,t){return yi("softmax")},e.prototype.log=function(e){return yi("log")},e.prototype.log1p=function(e){return yi("log1p")},e.prototype.sqrt=function(e){return yi("sqrt")},e.prototype.rsqrt=function(e){return yi("rsqrt")},e.prototype.square=function(e){return yi("square")},e.prototype.reciprocal=function(e){return yi("reciprocal")},e.prototype.relu=function(e){return yi("relu")},e.prototype.relu6=function(e){return yi("relu6")},e.prototype.prelu=function(e,t){return yi("prelu")},e.prototype.elu=function(e){return yi("elu")},e.prototype.eluDer=function(e,t){return yi("eluDer")},e.prototype.selu=function(e){return yi("selu")},e.prototype.int=function(e){return yi("int")},e.prototype.clip=function(e,t,n){return yi("clip")},e.prototype.abs=function(e){return yi("abs")},e.prototype.complexAbs=function(e){return yi("complexAbs")},e.prototype.sigmoid=function(e){return yi("sigmoid")},e.prototype.softplus=function(e){return yi("softplus")},e.prototype.sin=function(e){return yi("sin")},e.prototype.cos=function(e){return yi("cos")},e.prototype.tan=function(e){return yi("tan")},e.prototype.asin=function(e){return yi("asin")},e.prototype.acos=function(e){return yi("acos")},e.prototype.atan=function(e){return yi("atan")},e.prototype.atan2=function(e,t){return yi("atan2")},e.prototype.sinh=function(e){return yi("sinh")},e.prototype.cosh=function(e){return yi("cosh")},e.prototype.tanh=function(e){return yi("tanh")},e.prototype.asinh=function(e){return yi("asinh")},e.prototype.acosh=function(e){return yi("acosh")},e.prototype.atanh=function(e){return yi("atanh")},e.prototype.erf=function(e){return yi("erf")},e.prototype.step=function(e,t){return yi("step")},e.prototype.fusedConv2d=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,yi("fusedConv2d")},e.prototype.conv2d=function(e,t,n){return yi("conv2d")},e.prototype.conv2dDerInput=function(e,t,n){return yi("conv2dDerInput")},e.prototype.conv2dDerFilter=function(e,t,n){return yi("conv2dDerFilter")},e.prototype.fusedDepthwiseConv2D=function(e){return e.input,e.filter,e.convInfo,e.bias,e.activation,e.preluActivationWeights,yi("fusedDepthwiseConv2D")},e.prototype.depthwiseConv2D=function(e,t,n){return yi("depthwiseConv2D")},e.prototype.depthwiseConv2DDerInput=function(e,t,n){return yi("depthwiseConv2DDerInput")},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){return yi("depthwiseConv2DDerFilter")},e.prototype.conv3d=function(e,t,n){return yi("conv3d")},e.prototype.conv3dDerInput=function(e,t,n){return yi("conv3dDerInput")},e.prototype.conv3dDerFilter=function(e,t,n){return yi("conv3dDerFilter")},e.prototype.maxPool=function(e,t){return yi("maxPool")},e.prototype.maxPoolBackprop=function(e,t,n,r){return yi("maxPoolBackprop")},e.prototype.avgPool=function(e,t){return yi("avgPool")},e.prototype.avgPoolBackprop=function(e,t,n){return yi("avgPoolBackprop")},e.prototype.avgPool3d=function(e,t){return yi("avgPool3d")},e.prototype.avgPool3dBackprop=function(e,t,n){return yi("avgPool3dBackprop")},e.prototype.maxPool3d=function(e,t){return yi("maxPool3d")},e.prototype.maxPool3dBackprop=function(e,t,n,r){return yi("maxPool3dBackprop")},e.prototype.reshape=function(e,t){return yi("reshape")},e.prototype.cast=function(e,t){return yi("cast")},e.prototype.tile=function(e,t){return yi("tile")},e.prototype.pad=function(e,t,n){return yi("pad")},e.prototype.transpose=function(e,t){return yi("transpose")},e.prototype.gather=function(e,t,n){return yi("gather")},e.prototype.gatherND=function(e,t){return yi("gatherND")},e.prototype.scatterND=function(e,t,n){return yi("scatterND")},e.prototype.batchToSpaceND=function(e,t,n){return yi("batchToSpaceND")},e.prototype.spaceToBatchND=function(e,t,n){return yi("spaceToBatchND")},e.prototype.resizeBilinear=function(e,t,n,r){return yi("resizeBilinear")},e.prototype.resizeBilinearBackprop=function(e,t,n){return yi("resizeBilinearBackprop")},e.prototype.resizeNearestNeighbor=function(e,t,n,r){return yi("resizeNearestNeighbor")},e.prototype.resizeNearestNeighborBackprop=function(e,t,n){return yi("resizeNearestNeighborBackprop")},e.prototype.batchNormalization=function(e,t,n,r,i,o){return yi("batchNormalization")},e.prototype.localResponseNormalization4D=function(e,t,n,r,i){return yi("localResponseNormalization4D")},e.prototype.LRNGrad=function(e,t,n,r,i,o,a){return yi("LRNGrad")},e.prototype.multinomial=function(e,t,n,r){return yi("multinomial")},e.prototype.oneHot=function(e,t,n,r){return yi("oneHot")},e.prototype.cumsum=function(e,t,n,r){return yi("cumsum")},e.prototype.nonMaxSuppression=function(e,t,n,r,i){return yi("nonMaxSuppression")},e.prototype.fft=function(e){return yi("fft")},e.prototype.ifft=function(e){return yi("ifft")},e.prototype.complex=function(e,t){return yi("complex")},e.prototype.real=function(e){return yi("real")},e.prototype.imag=function(e){return yi("imag")},e.prototype.cropAndResize=function(e,t,n,r,i,o){return yi("cropAndResize")},e.prototype.depthToSpace=function(e,t,n){return yi("depthToSpace")},e.prototype.split=function(e,t,n){return yi("split")},e.prototype.sparseToDense=function(e,t,n,r){return yi("sparseToDense")},e.prototype.diag=function(e){return yi("diag")},e.prototype.fill=function(e,t,n){return yi("fill")},e.prototype.onesLike=function(e){return yi("onesLike")},e.prototype.zerosLike=function(e){return yi("zerosLike")},e.prototype.linspace=function(e,t,n){return yi("linspace")},e.prototype.dispose=function(){return yi("dispose")},e}();function yi(e){throw new Error("'"+e+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function bi(e,t){for(var n=e.length,r=[],i=0;i<n;i++){var o=n-1-i,a=e[o]||1;(t[t.length-1-i]||1)>1&&1===a&&r.unshift(o)}return r}function wi(e,t){for(var n=[],r=0;r<t.length;r++){var i=e[e.length-r-1],o=t.length-r-1,a=t[o];(null==i||1===i&&a>1)&&n.unshift(o)}return n}function xi(e,t){for(var n=[],r=Math.max(e.length,t.length),i=0;i<r;i++){var o=e[e.length-i-1];null==o&&(o=1);var a=t[t.length-i-1];if(null==a&&(a=1),1===o)n.unshift(a);else if(1===a)n.unshift(o);else{if(o!==a)throw Error("Operands could not be broadcast together with shapes "+e+" and "+t+".");n.unshift(o)}}return n}function _i(e,t,n,r,i,o,a){void 0===a&&(a="channelsLast");var s,c=ki(t),u=c[0],d=c[1];if("channelsLast"===a)s=[u,d,e[3],e[3]];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);s=[u,d,e[1],e[1]]}return Ri(e,s,n,r,i,o,!1,a)}function Si(e,t,n,r,i,o,a){void 0===a&&(a="NDHWC");var s,c,u=Ti(t),d=u[0],l=u[1],p=u[2];if("NDHWC"===a)c="channelsLast",s=[d,l,p,e[4],e[4]];else{if("NCDHW"!==a)throw new Error("Unknown dataFormat "+a);c="channelsFirst",s=[d,l,p,e[1],e[1]]}return Ci(e,s,n,r,i,!1,c,o)}function Ri(e,t,n,r,i,o,a,s){void 0===a&&(a=!1),void 0===s&&(s="channelsLast");var c=[-1,-1,-1,-1],u=c[0],d=c[1],l=c[2],p=c[3];if("channelsLast"===s)u=e[0],d=e[1],l=e[2],p=e[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);u=e[0],p=e[1],d=e[2],l=e[3]}var h,f=t[0],m=t[1],g=t[3],v=ki(n),y=v[0],b=v[1],w=ki(r),x=w[0],_=w[1],S=Di(f,x),R=Di(m,_),C=function(e,t,n,r,i,o,a,s){var c,u,d;if("number"==typeof e){c={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};var l=function(e,t,n,r,i){null==r&&(r=Ei(e,t,n));var o=e[1],a=Pi((e[0]-t+2*r)/n+1,i);k(O(a),(function(){return"The output # of rows ("+a+") must be an integer. Change the stride and/or zero pad parameters"}));var s=Pi((o-t+2*r)/n+1,i);return k(O(s),(function(){return"The output # of columns ("+s+") must be an integer. Change the stride and/or zero pad parameters"})),[a,s]}([t,n],o,r,e,s);u=l[0],d=l[1]}else if("same"===e){u=Math.ceil(t/r),d=Math.ceil(n/i);var p=Math.max(0,(u-1)*r+o-t),h=Math.max(0,(d-1)*i+a-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2);c={top:f,bottom:m,left:g,right:h-g,type:"SAME"}}else{if("valid"!==e)throw Error("Unknown padding parameter: "+e);c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-o+1)/r),d=Math.ceil((n-a+1)/i)}return{padInfo:c,outHeight:u,outWidth:d}}(i,d,l,y,b,S,R,o),E=C.padInfo,T=C.outHeight,D=C.outWidth,P=a?g*p:g;return"channelsFirst"===s?h=[u,P,T,D]:"channelsLast"===s&&(h=[u,T,D,P]),{batchSize:u,dataFormat:s,inHeight:d,inWidth:l,inChannels:p,outHeight:T,outWidth:D,outChannels:P,padInfo:E,strideHeight:y,strideWidth:b,filterHeight:f,filterWidth:m,effectiveFilterHeight:S,effectiveFilterWidth:R,dilationHeight:x,dilationWidth:_,inShape:e,outShape:h,filterShape:t}}function Ci(e,t,n,r,i,o,a,s){void 0===o&&(o=!1),void 0===a&&(a="channelsLast");var c=[-1,-1,-1,-1,-1],u=c[0],d=c[1],l=c[2],p=c[3],h=c[4];if("channelsLast"===a)u=e[0],d=e[1],l=e[2],p=e[3],h=e[4];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);u=e[0],h=e[1],d=e[2],l=e[3],p=e[4]}var f,m=t[0],g=t[1],v=t[2],y=t[4],b=Ti(n),w=b[0],x=b[1],_=b[2],S=Ti(r),R=S[0],C=S[1],E=S[2],T=Di(m,R),D=Di(g,C),P=Di(v,E),I=function(e,t,n,r,i,o,a,s,c,u,d){var l,p,h,f;if("number"==typeof e){l={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};var m=function(e,t,n,r,i,o){null==i&&(i=Ei(e,t,r));var a=e[1],s=e[2],c=Pi((e[0]-t+2*i)/r+1,o);k(O(c),(function(){return"The output # of depths ("+c+") must be an integer. Change the stride and/or zero pad parameters"}));var u=Pi((a-t+2*i)/r+1,o);k(O(u),(function(){return"The output # of rows ("+u+") must be an integer. Change the stride and/or zero pad parameters"}));var d=Pi((s-t+2*i)/r+1,o);return k(O(d),(function(){return"The output # of columns ("+d+") must be an integer. Change the stride and/or zero pad parameters"})),[c,u,d,1]}([t,n,r,1],s,0,i,e,d);p=m[0],h=m[1],f=m[2]}else if("same"===e){var g=((p=Math.ceil(t/i))-1)*i+s-t,v=((h=Math.ceil(n/o))-1)*o+c-n,y=((f=Math.ceil(r/a))-1)*a+u-r,b=Math.floor(g/2),w=g-b,x=Math.floor(v/2),_=v-x,S=Math.floor(y/2);l={top:x,bottom:_,left:S,right:y-S,front:b,back:w,type:"SAME"}}else{if("valid"!==e)throw Error("Unknown padding parameter: "+e);l={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-s+1)/i),h=Math.ceil((n-c+1)/o),f=Math.ceil((r-u+1)/a)}return{padInfo:l,outDepth:p,outHeight:h,outWidth:f}}(i,d,l,p,w,x,_,T,D,P,s),M=I.padInfo,A=I.outDepth,F=I.outHeight,N=I.outWidth,L=o?y*h:y;return"channelsFirst"===a?f=[u,L,A,F,N]:"channelsLast"===a&&(f=[u,A,F,N,L]),{batchSize:u,dataFormat:a,inDepth:d,inHeight:l,inWidth:p,inChannels:h,outDepth:A,outHeight:F,outWidth:N,outChannels:L,padInfo:M,strideDepth:w,strideHeight:x,strideWidth:_,filterDepth:m,filterHeight:g,filterWidth:v,effectiveFilterDepth:T,effectiveFilterHeight:D,effectiveFilterWidth:P,dilationDepth:R,dilationHeight:C,dilationWidth:E,inShape:e,outShape:f,filterShape:t}}function Ei(e,t,n,r){void 0===r&&(r=1);var i=Di(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)}function ki(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Ti(e){return"number"==typeof e?[e,e,e]:e}function Di(e,t){return t<=1?e:e+(e-1)*(t-1)}function Pi(e,t){if(!t)return e;switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error("Unknown roundingMode "+t)}}function Ii(e){var t=ki(e),n=t[0],r=t[1],i=t[2];return 1===n&&1===r&&1===i}function Mi(e,t){return Ii(e)||Ii(t)}function Oi(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error("Unknown dataFormat "+e)}function Ai(e,t,n){if("complex64"===t){if("complex64"===e.dtype)return e.clone();var r=Un(e.shape),i=e.toFloat(),o=n.complex(i,r);return r.dispose(),i.dispose(),o}if(!q(e.dtype,t))return je.makeTensorFromDataId(e.dataId,e.shape,t);if("complex64"===e.dtype){var a=n.real(e);return o=a.cast(t),a.dispose(),o}if("int32"===t)return n.int(e);if("bool"===t){var s=On(0,e.dtype);return o=n.notEqual(e,s),s.dispose(),o}throw new Error("Error in Cast: failed to cast "+e.dtype+" to "+t)}function Fi(e,t){return je.makeTensorFromDataId(e.dataId,t,e.dtype)}function Ni(e,t,n){var r=(t-e)/(n-1),i=oe(n,"float32");i[0]=e;for(var o=1;o<i.length;o++)i[o]=i[o-1]+r;return An(i,"float32")}var Li=Object.freeze({castTensor:Ai,reshapeTensor:Fi,linspaceImpl:Ni,upcastType:Pe,axesAreInnerMostDims:vn,combineLocations:yn,computeOutAndReduceShapes:bn,expandShapeToKeepDim:wn,assertAxesAreInnerMostDims:xn,getAxesPermutation:_n,getUndoAxesPermutation:Sn,getInnerMostAxes:Rn,getBroadcastDims:bi,getReductionAxes:wi,assertAndGetBroadcastShape:xi,assertParamsConsistent:Cn,computeOutShape:En,computePool2DInfo:_i,computePool3DInfo:Si,computeConv2DInfo:Ri,computeConv3DInfo:Ci,computeDefaultPad:Ei,tupleValuesAreOne:Ii,eitherStridesOrDilationsAreOne:Mi,convertConv2DDataFormat:Oi,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:Xr});function Bi(e,t){if(e.length!==t.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+e.length+", imag: "+t.length+".");for(var n=new Float32Array(2*e.length),r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function ji(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Wi(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function zi(e,t,n){var r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}function Ui(e,t,n){var r=function(e,t,n){return function(e,t,n){for(var r=0,i=e.length,o=0,a=!1;r<i;){var s=n(t,e[o=r+(i-r>>>1)]);s>0?r=o+1:(i=o,a=!s)}return a?r:-r-1}(e,t,n||Vi)}(e,t,n),i=r<0?-(r+1):r;e.splice(i,0,t)}function Vi(e,t){return e>t?1:e<t?-1:0}function Gi(e,t,n,r,i){return Hi(e,t,n,r,i,0).selectedIndices}function qi(e,t,n,r,i,o){var a=Hi(e,t,n,r,i,o,!0);return a.numValidOutputs.dispose(),{selectedIndices:a.selectedIndices,selectedScores:a.selectedScores}}function Hi(e,t,n,r,i,o,a,s){void 0===a&&(a=!1),void 0===s&&(s=!1);for(var c=Array.from(t).map((function(e,t){return{score:e,boxIndex:t,suppressBeginIndex:0}})).filter((function(e){return e.score>i})).sort($i),u=o>0?-.5/o:0,d=[],l=[];d.length<n&&c.length>0;){var p=c.pop(),h=p.score,f=p.boxIndex,m=p.suppressBeginIndex;if(h<i)break;for(var g=!1,v=d.length-1;v>=m;--v){var y=Ki(e,f,d[v]);if(y>=r){g=!0;break}if(p.score=p.score*Xi(r,u,y),p.score<=i)break}p.suppressBeginIndex=d.length,g||(p.score===h?(d.push(f),l.push(p.score)):p.score>i&&Ui(c,p,$i))}var b=d.length;return s&&(d.fill(0,b),l.fill(0,b)),{selectedIndices:An(d,"int32"),selectedScores:An(l,"float32"),numValidOutputs:On(b,"int32")}}function Ki(e,t,n){var r=e.subarray(4*t,4*t+4),i=e.subarray(4*n,4*n+4),o=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),u=Math.min(i[0],i[2]),d=Math.min(i[1],i[3]),l=Math.max(i[0],i[2]),p=Math.max(i[1],i[3]),h=(s-o)*(c-a),f=(l-u)*(p-d);if(h<=0||f<=0)return 0;var m=Math.max(o,u),g=Math.max(a,d),v=Math.min(s,l),y=Math.min(c,p),b=Math.max(v-m,0)*Math.max(y-g,0);return b/(h+f-b)}function Xi(e,t,n){var r=Math.exp(t*n*n);return n<=e?r:0}function $i(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}function Yi(e,t,n){var r=new Array(e.rank).fill(0),i=e.shape.slice();return t.map((function(t){i[n]=t;var o=e.slice(r,i);return r[n]+=t,o}))}function Qi(e,t){for(var n=new Array(e.rank),r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];var i=pr(n,e.dtype);for(r=0;r<i.values.length;++r){for(var o=i.indexToLoc(r),a=new Array(e.rank),s=0;s<a.length;s++)a[s]=o[s]%e.shape[s];var c=e.locToIndex(a);i.values[r]=e.values[c]}return i.toTensor()}function Ji(e,t,n,r,i){for(var o=t[t.length-1],a=[e.length/o,o],s=a[0],c=a[1],u=z(n,s*r),d=z("int32",s*r),l=0;l<s;l++){for(var p=l*c,h=e.subarray(p,p+c),f=[],m=0;m<h.length;m++)f.push({value:h[m],index:m});f.sort((function(e,t){return t.value-e.value}));var g=l*r,v=u.subarray(g,g+r),y=d.subarray(g,g+r);for(m=0;m<r;m++)v[m]=f[m].value,y[m]=f[m].index}var b=t.slice();return b[b.length-1]=r,[In(u,b,n),In(d,b,"int32")]}function Zi(e,t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(r);var i=pr(e,"int32"),o=pr([n.length,e.length],"int32");for(r=0;r<n.length;r++){var a=i.indexToLoc(n[r]),s=r*e.length;o.values.set(a,s)}return o.toTensor()}var eo=function(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((function(e,t){return"T"+t}));var n=[];this.variableNames.forEach((function(e){n.push("float v"+e+" = get"+e+"AtOutCoords();")}));var r=this.variableNames.map((function(e){return"v"+e})).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n float result = "+r+";\n setOutput(result);\n }\n "},to=function(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((function(e,t){return"T"+t}));var n=[];this.variableNames.forEach((function(e){n.push("vec4 v"+e+" = get"+e+"AtOutCoords();")}));var r=this.variableNames.map((function(e){return"v"+e})).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n vec4 result = "+r+";\n setOutput(result);\n }\n "},no=function(e,t,n){this.variableNames=["A"];var r=e.windowSize,i=e.batchSize,o=e.inSize,a=Math.ceil(o/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[i,a];var s="max"===t?">":"<",c=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+c+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function ro(e,t){return["x","y","z","w","u","v"].slice(0,t).map((function(t){return e+"."+t}))}function io(e,t){return 1===t?[e]:ro(e,t)}function oo(){var e,t,n,r,i,o,a,s,c,u;return 2===l().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",i="texture",o="outputColor",a="out vec4 outputColor;",s="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",c="",u="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",r="varying",i="texture2D",o="gl_FragColor",a="",s="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",c="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",u="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:i,output:o,defineOutput:a,defineSpecialNaN:s,defineSpecialInf:c,defineRound:u}}function ao(e,t,n){void 0===n&&(n="index");var r=te(t);return r.map((function(t,i){return"int "+e[i]+" = "+n+" / "+t+"; "+(i===r.length-1?"int "+e[i+1]+" = "+n+" - "+e[i]+" * "+t:"index -= "+e[i]+" * "+t)+";"})).join("")}function so(e){var t=te(e).map((function(e){return e.toString()}));return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+t[0]+" + coords.y * "+t[1]+" + coords.z;\n }\n"}var co="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function uo(e,t,n,r){var i=[];e.forEach((function(e){var t=I(e.shapeInfo.logicalShape);e.shapeInfo.isUniform?i.push("uniform float "+e.name+(t>1?"["+t+"]":"")+";"):(i.push("uniform sampler2D "+e.name+";"),i.push("uniform int offset"+e.name+";"))}));var o,a,s=i.join("\n"),c=e.map((function(e){return function(e,t,n){void 0===n&&(n=!1);var r="";r+=n?po(e):lo(e);var i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(r+=n?function(e,t){var n,r,i=e.name,o=i.charAt(0).toUpperCase()+i.slice(1),a="get"+o+"AtOutCoords",s=e.shapeInfo.logicalShape.length,c=t.logicalShape.length,u=bi(e.shapeInfo.logicalShape,t.logicalShape),d=bo(c),l=c-s,p=["x","y","z","w","u","v"];n=0===s?"":c<2&&u.length>=1?"coords = 0;":u.map((function(e){return"coords."+p[e+l]+" = 0;"})).join("\n"),r=c<2&&s>0?"coords":e.shapeInfo.logicalShape.map((function(e,t){return"coords."+p[t+l]})).join(", ");var h="return outputValue;",f=1===I(e.shapeInfo.logicalShape),m=1===I(t.logicalShape);if(1!==s||f||m){if(f&&!m)h=1===c?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var g=s-2,v=s-1;u.indexOf(g)>-1&&u.indexOf(v)>-1?h="return vec4(outputValue.x);":u.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}}else h="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+d+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+o+"("+r+");\n "+h+"\n }\n "}(e,t):function(e,t){var n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),i="get"+r+"AtOutCoords",o=t.texShape,a=e.shapeInfo.texShape,s=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&s===c&&null==e.shapeInfo.flatOffset&&M(a,o))return"\n float "+i+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var u,d,l=bo(c),p=bi(e.shapeInfo.logicalShape,t.logicalShape),h=c-s,f=["x","y","z","w","u","v"];return u=0===s?"":c<2&&p.length>=1?"coords = 0;":p.map((function(e){return"coords."+f[e+h]+" = 0;"})).join("\n"),d=c<2&&s>0?"coords":e.shapeInfo.logicalShape.map((function(e,t){return"coords."+f[t+h]})).join(", "),"\n float "+i+"() {\n "+l+" coords = getOutputCoords();\n "+u+"\n return get"+r+"("+d+");\n }\n "}(e,t)),r}(e,t,r)})).join("\n"),u=t.texShape,d=oo(),l=function(e){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+e.texture2D+"(textureSampler, uv).r;\n }\n "}(d),p=function(e){return e.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+e.varyingFs+" vec2 resultUV;\n "+e.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+e.defineSpecialNaN+"\n "+e.defineSpecialInf+"\n "+e.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+ho+"\n "+fo+"\n "+mo+"\n "}(d);return t.isPacked?(o=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,t);case 2:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(M(e,t))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(e[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(e,t);case 3:return n=e,r=t,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=(o=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+i[0]+", "+i[1]+"));\n int index = resTexRC.x * "+i[1]+" + resTexRC.y;\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+o+");\n int c = imod(index, "+o+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(e,t){for(var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),i=r*Math.ceil(e[e.length-2]/2),o=i,a="",s="b, r, c",c=2;c<e.length-1;c++)a="\n int b"+c+" = index / "+(o*=e[e.length-c-1])+";\n index -= b"+c+" * "+o+";\n "+a,s="b"+c+", "+s;return"\n ivec"+e.length+" getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n "+a+"\n\n int b = index / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec"+e.length+"("+s+");\n }\n "}(e,t)}var n,r,i,o,a}(t.logicalShape,u),a=function(e){return"\n void setOutput(vec4 val) {\n "+e.output+" = val;\n }\n "}(d)):(o=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n "}(0,t);case 2:return function(e,t){return M(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n "}(e,t);case 3:return n=t,r=ao(["r","c","d"],e),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n "+r+"\n return ivec3(r, c, d);\n }\n ";case 4:return function(e,t){var n=ao(["r","c","d","d2"],e);return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n "+n+"\n return ivec4(r, c, d, d2);\n }\n "}(e,t);case 5:return function(e,t){var n=ao(["r","c","d","d2","d3"],e);return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n "+t[1]+"));\n\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(e,t);case 6:return function(e,t){var n=ao(["r","c","d","d2","d3","d4"],e);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}var n,r}(t.logicalShape,u),a=function(e){return"\n void setOutput(float val) {\n "+e.output+" = vec4(val, 0, 0, 0);\n }\n "}(d)),r&&(p+=go),[p,l,a,s,o,c,n].join("\n")}function lo(e){var t=e.shapeInfo.logicalShape;switch(t.length){case 0:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return"float "+n+"() {return "+t+";}";var r=e.shapeInfo.texShape,i=r[0],o=r[1];if(1===i&&1===o)return"\n float "+n+"() {\n return sampleTexture("+t+", halfCR);\n }\n ";var a=e.shapeInfo.texShape;return"\n float "+n+"() {\n vec2 uv = uvFromFlat("+a[0]+", "+a[1]+", "+vo(t)+");\n return sampleTexture("+t+", uv);\n }\n "}(e);case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return"\n float "+n+"(int index) {\n "+yo(e)+"\n }\n ";var r=e.shapeInfo.texShape,i=r[0],o=r[1];if(1===o&&1===i)return"\n float "+n+"(int index) {\n return sampleTexture("+t+", halfCR);\n }\n ";var a=vo(t);return 1===o?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index + "+a+") + 0.5) / "+i+".0);\n return sampleTexture("+t+", uv);\n }\n ":1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index + "+a+") + 0.5) / "+o+".0, 0.5);\n return sampleTexture("+t+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = uvFromFlat("+i+", "+o+", index + "+a+");\n return sampleTexture("+t+", uv);\n }\n "}(e);case 2:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(null!=i&&M(t,i)){var o=i[0];return"\n float "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i[1]+".0, "+o+".0);\n return sampleTexture("+n+", uv);\n }\n "}var a=W(t),s=a.newShape,c=a.keptDims,u=s;if(u.length<t.length)return"\n "+lo(wo(e,u))+"\n float "+r+"(int row, int col) {\n return "+r+"("+xo(["row","col"],c)+");\n }\n ";if(e.shapeInfo.isUniform)return"\n float "+r+"(int row, int col) {\n int index = round(dot(vec2(row, col), vec2("+t[1]+", 1)));\n "+yo(e)+"\n }\n ";var d=i[0],l=i[1],p=vo(n);return 1===l?"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+p+"), vec3("+t[1]+", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ":1===d?"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+p+"), vec3("+t[1]+", 1, 1));\n vec2 uv = vec2((index + 0.5) / "+l+".0, 0.5);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+t[1]+" + col + "+p+";\n vec2 uv = uvFromFlat("+d+", "+l+", index);\n return sampleTexture("+n+", uv);\n }\n"}(e);case 3:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[1]*t[2],o=t[2],a=W(t),s=a.newShape,c=a.keptDims,u=s;if(u.length<t.length)return"\n "+lo(wo(e,u))+"\n float "+r+"(int row, int col, int depth) {\n return "+r+"("+xo(["row","col","depth"],c)+");\n }\n ";if(e.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3("+i+", "+o+", 1)));\n "+yo(e)+"\n }\n ";var d=e.shapeInfo.texShape,l=d[0],p=d[1],h=e.shapeInfo.flatOffset;return p===i&&null==h?"\n float "+r+"(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2("+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+p+".0, "+l+".0);\n return sampleTexture("+n+", uv);\n }\n ":p===o&&null==h?"\n float "+r+"(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2("+t[1]+", 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+p+".0, "+l+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+i+" + col * "+o+" + depth + "+vo(n)+";\n vec2 uv = uvFromFlat("+l+", "+p+", index);\n return sampleTexture("+n+", uv);\n }\n "}(e);case 4:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[3],o=t[2]*i,a=t[1]*o,s=W(t),c=s.newShape,u=s.keptDims;if(c.length<t.length)return"\n "+lo(wo(e,c))+"\n float "+r+"(int row, int col, int depth, int depth2) {\n return "+r+"("+xo(["row","col","depth","depth2"],u)+");\n }\n ";if(e.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4("+a+", "+o+", "+i+", 1)));\n "+yo(e)+"\n }\n ";var d=e.shapeInfo.flatOffset,l=e.shapeInfo.texShape,p=l[0],h=l[1];return h===a&&null==d?"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3("+o+", "+i+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+h+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ":h===i&&null==d?"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3("+t[1]*t[2]+", "+t[2]+", 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+h+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+a+" + col * "+o+" +\n depth * "+i+" + depth2;\n vec2 uv = uvFromFlat("+p+", "+h+", index + "+vo(n)+");\n return sampleTexture("+n+", uv);\n }\n "}(e);case 5:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[4],o=t[3]*i,a=t[2]*o,s=t[1]*a,c=W(t),u=c.newShape,d=c.keptDims;if(u.length<t.length)return"\n "+lo(wo(e,u))+"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n return "+r+"("+xo(["row","col","depth","depth2","depth3"],d)+");\n }\n ";if(e.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4("+s+", "+a+", "+o+", "+i+")) +\n depth3;\n "+yo(e)+"\n }\n ";var l=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];return f===s&&null==l?"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+a+", "+o+", "+i+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+f+".0, "+h+".0);\n return sampleTexture("+n+", uv);\n }\n ":f===i&&null==l?"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4("+t[1]*t[2]*t[3]+",\n "+t[2]*t[3]+", "+t[3]+", 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+f+".0, "+h+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+s+" + col * "+a+" + depth * "+o+" +\n depth2 * "+i+" + depth3 + "+vo(n)+";\n vec2 uv = uvFromFlat("+h+", "+f+", index);\n return sampleTexture("+n+", uv);\n }\n "}(e);case 6:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=W(t),o=i.newShape,a=i.keptDims;if(o.length<t.length)return"\n "+lo(wo(e,o))+"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return "+r+"("+xo(["row","col","depth","depth2","depth3","depth4"],a)+");\n }\n ";var s=t[5],c=t[4]*s,u=t[3]*c,d=t[2]*u,l=t[1]*d;if(e.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4("+l+", "+d+", "+u+", "+c+")) +\n dot(\n vec2(depth3, depth4),\n vec2("+s+", 1)));\n "+yo(e)+"\n }\n ";var p=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,f=h[0],m=h[1];return m===l&&null==p?"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+d+", "+u+", "+c+", "+s+")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ":m===s&&null==p?"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4("+t[1]*t[2]*t[3]*t[4]+",\n "+t[2]*t[3]*t[4]+",\n "+t[3]*t[4]+",\n "+t[4]+")) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+l+" + col * "+d+" + depth * "+u+" +\n depth2 * "+c+" + depth3 * "+s+" + depth4 + "+vo(n)+";\n vec2 uv = uvFromFlat("+f+", "+m+", index);\n return sampleTexture("+n+", uv);\n }\n "}(e);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function po(e){var t;switch(e.shapeInfo.logicalShape.length){case 0:return"\n vec4 get"+(t=e.name).charAt(0).toUpperCase()+t.slice(1)+"() {\n return "+oo().texture2D+"("+t+", halfCR);\n }\n ";case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=e.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=oo();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+i[0]+", "+i[1]+", index);\n return "+o.texture2D+"("+t+", uv);\n }\n "}(e);case 2:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=i[0],a=i[1],s=oo();if(null!=i&&M(t,i))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+a+".0, "+o+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(t[1]/2)+", "+c[0]+", "+c[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(e);case 3:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(1===t[0])return"\n "+po(wo(e,t.slice(1)))+"\n vec4 "+r+"(int b, int row, int col) {\n return "+r+"("+xo(["b","row","col"],[1,2])+");\n }\n ";var a=o[0],s=o[1],c=Math.ceil(t[2]/2);return"\n vec4 "+r+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+a+", "+s+", "+c*Math.ceil(t[1]/2)+", "+c+", b, row, col);\n return "+oo().texture2D+"("+n+", uv);\n }\n "}(e);default:return function(e){for(var t=e.shapeInfo.logicalShape,n=t.length,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),o=e.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],s=a[0],c=a[1],u=Math.ceil(t[n-1]/2),d=u*Math.ceil(t[n-2]/2),l="int b, int row, int col",p="b * "+d+" + (row / 2) * "+u+" + (col / 2)",h=2;h<n-1;h++)l="int b"+h+", "+l,p="b"+h+" * "+(d*=t[n-h-1])+" + "+p;return"\n vec4 "+i+"("+l+") {\n int index = "+p+";\n int texR = index / "+c+";\n int texC = index - texR * "+c+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+c+", "+s+");\n return "+oo().texture2D+"("+r+", uv);\n }\n "}(e)}}var ho="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",fo="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",mo="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",go="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function vo(e){return"offset"+e}function yo(e){var t=e.name,n=I(e.shapeInfo.logicalShape);return n<2?"return "+t+";":"\n for (int i = 0; i < "+n+"; i++) {\n if (i == index) {\n return "+t+"[i];\n }\n }\n "}function bo(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function wo(e,t){var n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function xo(e,t){return t.map((function(t){return e[t]})).join(", ")}var _o=function(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k(e.length>2,(function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."}));var i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),r||this.variableNames.push("bestIndicesA");var a,s,c=this.outputShape,u=c.length,d=bo(u),l=io("coords",u);if(1===o){var p=bo(s=u+1);a="\n "+p+" sourceLocR = "+p+"("+l.join()+", 0);\n ++"+l[u-1]+";\n "+p+" sourceLocG = "+p+"("+l.join()+", 0);\n ++"+l[u-2]+";\n "+p+" sourceLocA = "+p+"("+l.join()+", 0);\n --"+l[u-1]+";\n "+p+" sourceLocB = "+p+"("+l.join()+", 0);\n --"+l[u-2]+";"}else s=u,a="\n "+d+" sourceLocR = coords;\n ++"+l[u-1]+";\n "+d+" sourceLocG = coords;\n ++"+l[u-2]+";\n "+d+" sourceLocA = coords;\n --"+l[u-1]+";\n "+d+" sourceLocB = coords;\n --"+l[u-2]+";";var h=["x","y","z","w","u","v"].slice(0,s),f="."+h[s-1],m=h.map((function(e){return"int "+e})),g=io("sourceLocR",s-1).concat("inIdx.r"),v=io("sourceLocG",s-1).concat("inIdx.g"),y=io("sourceLocB",s-1).concat("inIdx.b"),b=io("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",x=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+b.join()+")));",_="vec4(\n getAChannel("+g.join()+"),\n hasNextCol ? getAChannel("+v.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",S=r?"":"\n float getBestIndicesAChannel("+m.join()+") {\n return getChannel(getBestIndicesA("+h.join()+"),\n vec2("+h.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+m.join()+") {\n return getChannel(getA("+h.join()+"),\n vec2("+h.slice(-2).join()+"));\n }\n "+S+"\n void main() {\n "+d+" coords = getOutputCoords();\n bool hasNextCol = "+l[u-1]+" < "+(c[u-1]-1)+";\n bool hasNextRow = "+l[u-2]+" < "+(c[u-2]-1)+";\n "+a+"\n ivec4 srcIdx = ivec4(sourceLocR"+f+", sourceLocG"+f+",\n sourceLocB"+f+", sourceLocA"+f+") * "+t+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+_+";\n\n for (int i = 0; i < "+t+"; i++) {\n inIdx = srcIdx;\n "+x+"\n vec4 candidate = "+_+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+w+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},So=function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=s-1-e.padInfo.top,d=c-1-e.padInfo.left,l=1/(t*n);this.userCode="\n const ivec2 pads = ivec2("+u+", "+d+");\n const float avgMultiplier = float("+l+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+c+";\n wC+= "+a+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},Ro=function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,s=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,d=e.effectiveFilterDepth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=d-1-e.padInfo.front,f=l-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode="\n const ivec3 pads = ivec3("+h+", "+f+", "+m+");\n const float avgMultiplier = float("+g+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+d+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+i+".0;\n\n if (dyD < 0.0 || dyD >= "+e.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+l+";\n wR += "+c+") {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+p+";\n wC += "+u+") {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Co=function(e,t,n,r,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],xi(e,t),xi(e,n);var a="0.0";null!=r&&(xi(e,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="1.0";null!=i&&(xi(e,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=e,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+a+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+o+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},Eo=function(e,t,n,r,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],xi(e,t),xi(e,n);var a="vec4(0.0)";null!=r&&(xi(e,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=i&&(xi(e,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=e,this.userCode="\n void main() {\n vec4 offset = "+a+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},ko=function(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=xi(t,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+e+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},To="return a + b;",Do="return a - b;",Po="return a * b;",Io="return (a < 0.) ? b * a : a;",Mo=function(e,t,n){this.variableNames=["A","B"],this.outputShape=xi(t,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+e+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},Oo="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Ao=function(e,t,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=xi(t,n);var i=this.outputShape.length,o="";if(r)if(0===i||1===I(this.outputShape))o="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(o="\n "+bo(i)+" coords = getOutputCoords();\n ",1===i)o+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var a=io("coords",i);o+="\n bool nextRowOutOfBounds =\n ("+a[i-2]+" + 1) >= "+this.outputShape[i-2]+";\n bool nextColOutOfBounds =\n ("+a[i-1]+" + 1) >= "+this.outputShape[i-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+e+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+o+"\n\n setOutput(result);\n }\n "},Fo=function(){function e(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return e.prototype.getCustomSetupFunc=function(e,t){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,e),r.gl.uniform1f(n.maxLoc,t)}},e}(),No=function(){function e(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return e.prototype.getCustomSetupFunc=function(e,t){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,e),r.gl.uniform1f(n.maxLoc,t)}},e}(),Lo=function(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},Bo=function(e){this.outputShape=[],this.outputShape=En(e,1),this.variableNames=e.map((function(e,t){return"T"+t}));var t=new Array(e.length-1);t[0]=e[0][1];for(var n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];var r=["if (yC < "+t[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<t.length;n++){var i=t[n-1];r.push("else if (yC < "+t[n]+") setOutput(getT"+n+"(yR, yC-"+i+"));")}var o=t.length,a=t[t.length-1];r.push("else setOutput(getT"+o+"(yR, yC-"+a+"));"),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n "+r.join("\n ")+"\n }\n "},jo=function(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=En(e,t);var n=this.outputShape,r=n.length,i=bo(r),o=io("coords",r),a=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((function(e,t){return"T"+t}));var s=new Array(e.length-1);s[0]=e[0][t];for(var c=1;c<s.length;c++)s[c]=s[c-1]+e[c][t];var u=a[t],d=a.slice(-2),l=a.join(),p="if ("+u+" < "+s[0]+") {\n return getChannel(\n getT0("+l+"), vec2("+d.join()+"));\n }";for(c=1;c<s.length;c++){var h=s[c-1];p+="\n if ("+u+" < "+s[c]+" && "+u+" >= "+s[c-1]+") {\n return getChannel(\n getT"+c+"("+Wo(a,u,h)+"),\n vec2("+Wo(d,u,h)+"));\n }"}var f=s.length,m=s[s.length-1];p+="\n return getChannel(\n getT"+f+"("+Wo(a,u,m)+"),\n vec2("+Wo(d,u,m)+"));",this.userCode="\n float getValue("+a.map((function(e){return"int "+e}))+") {\n "+p+"\n }\n\n void main() {\n "+i+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+o+"), 0., 0., 0.);\n\n "+o[r-1]+" = "+o[r-1]+" + 1;\n if ("+o[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+o+");\n }\n\n "+o[r-2]+" = "+o[r-2]+" + 1;\n if ("+o[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+o+");\n }\n\n "+o[r-1]+" = "+o[r-1]+" - 1;\n if ("+o[r-2]+" < "+n[r-2]+" &&\n "+o[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+o+");\n }\n setOutput(result);\n }\n "};function Wo(e,t,n){var r=e.indexOf(t);return e.map((function(e,t){return t===r?e+" - "+n:e})).join()}var zo=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,i=e.padInfo.left,o="channelsLast"===e.dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+r+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n if ("+o+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Uo=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,i=e.strideWidth,o="channelsLast"===e.dataFormat,a=t-1-e.padInfo.top,s=n-1-e.padInfo.left,c=o?1:2,u=o?2:3,d=o?3:1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+d+"];\n\n ivec2 dyCorner = ivec2(coords["+c+"], coords["+u+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n\n if ("+o+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Vo=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,i=e.padInfo.front,o=e.padInfo.top,a=e.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yF = 0; yF < "+e.outDepth+"; yF++) {\n int xF = wF + yF * "+t+" - "+i+";\n\n if (xF < 0 || xF >= "+e.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+o+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Go=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,s=t-1-e.padInfo.front,c=n-1-e.padInfo.top,u=r-1-e.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+c+", "+u+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+t+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+i+".0;\n\n if (dyF < 0.0 || dyF >= "+e.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+t+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},qo=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,i=e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+r+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ho=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.top,a=n-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ko=function(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=e.outShape;var i=e.padInfo.top,o=e.padInfo.left,a=e.strideHeight,s=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,l=e.filterWidth,p=4*Math.floor(e.inChannels/4),h=e.inChannels%4,f="channelsLast"===e.dataFormat,m=f?1:2,g=f?2:3,v=f?3:1,y="",b="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",b="result = activation(result);");var w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+a+", "+s+");\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+v+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+m+"], coords["+g+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+d+"; wR++) {\n int xR = xRCorner + wR * "+c+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+p+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+f+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===h)+") {\n\n if ("+f+") {\n dotProd +=\n getX(batch, xR, xC, "+p+") *\n getW(wR, wC, "+p+", d2);\n } else {\n dotProd +=\n getX(batch, "+p+", xR, xC) *\n getW(wR, wC, "+p+", d2);\n }\n\n } else if ("+(2===h)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+p+", d2),\n getW(wR, wC, "+p+" + 1, d2)\n );\n\n if ("+f+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+p+"),\n getX(batch, xR, xC, "+p+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+p+", xR, xC),\n getX(batch, "+p+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===h)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+p+", d2),\n getW(wR, wC, "+p+" + 1, d2),\n getW(wR, wC, "+p+" + 2, d2)\n );\n\n if ("+f+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+p+"),\n getX(batch, xR, xC, "+p+" + 1),\n getX(batch, xR, xC, "+p+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+p+", xR, xC),\n getX(batch, "+p+" + 1, xR, xC),\n getX(batch, "+p+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+w+"\n "+b+"\n setOutput(result);\n }\n "},Xo=function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,s=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,d=e.filterDepth,l=e.filterHeight,p=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+i+", "+o+", "+a+");\n const ivec3 pads = ivec3("+t+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+d+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+e.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+c+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===f)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+h+") *\n getW(wF, wR, wC, "+h+", d2);\n } else if ("+(2===f)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+h+"),\n getX(batch, xF, xR, xC, "+h+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+h+", d2),\n getW(wF, wR, wC, "+h+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===f)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+h+"),\n getX(batch, xF, xR, xC, "+h+" + 1),\n getX(batch, xF, xR, xC, "+h+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+h+", d2),\n getW(wF, wR, wC, "+h+" + 1, d2),\n getW(wF, wR, wC, "+h+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},$o=function(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=e.outShape;var i=e.inHeight,o=e.inWidth,a=e.padInfo.top,s=e.padInfo.left,c=e.strideHeight,u=e.strideWidth,d=e.dilationHeight,l=e.dilationWidth,p=e.filterHeight,h=e.filterWidth,f=e.outChannels/e.inChannels,m="",g="";n&&(m=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",g="result = activation(result);");var v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+m+"\n\n const ivec2 strides = ivec2("+c+", "+u+");\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+f+";\n int q = d2 - d1 * "+f+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+d+";\n\n if (xR < 0 || xR >= "+i+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+o+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+v+"\n "+g+"\n setOutput(result);\n }\n "},Yo=function(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;for(var i=e.inHeight,o=e.inWidth,a=e.padInfo.top,s=e.padInfo.left,c=e.strideHeight,u=e.strideWidth,d=e.dilationHeight,l=e.dilationWidth,p=e.filterHeight,h=e.filterWidth,f=h,m="int xR; int xC; int xCOffset;",g=0;g<p;g++)for(var v=0;v<h;v++)m+="\n vec4 xTexelR"+g+"C"+2*v+" = vec4(0.);\n vec4 wR"+g+"C"+v+" = vec4(0.);\n vec4 xR"+g+"C"+v+" = vec4(0.);";for(g=0;g<p;g++)for(var y=0;y<f;y++){if(m+="\n xR = xRCorner + "+g*d+";\n xC = xCCorner + "+(v=2*y)*l+";\n ",1===u){if(v<h&&(m+=s%2==1?"\n xCOffset = xC + 1;\n if(xR >= 0 && xR < "+i+" && xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+o+") {\n xTexelR"+g+"C"+v+".zw = vec2(0.);\n }\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+i+" && xCOffset >= 0 && xCOffset < "+o+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+o+") {\n previous.zw = vec2(0.);\n }\n\n xR"+g+"C"+v+" = vec4(previous.zw, xTexelR"+g+"C"+v+".xy);\n } else {\n xR"+g+"C"+v+" = vec4(0, 0, xTexelR"+g+"C"+v+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+i+" && xC >= 0 && xC < "+o+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = xTexelR"+g+"C"+v+";\n ",v+1<h)){var b=s%2==0?C(l):l;l%2==0&&s%2==1||l%2!=0&&s%2!=1?(m+="\n xCOffset = xC + "+s%2+" + "+b+";\n\n if(xR >= 0 && xR < "+i+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",l>1&&(m+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+i+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n "),m+="\n xR"+g+"C"+(v+1)+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".xy);\n "):m+="\n xCOffset = xC + "+b+";\n\n if(xR >= 0 && xR < "+i+" &&\n xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+g+"C"+(v+1)+" = xTexelR"+g+"C"+(v+2)+";\n "}}else v<h&&(m+="\n if(xR >= 0 && xR < "+i+") {\n ",s%2==1?(m+="\n xCOffset = xC + 1 - "+u+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+o+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+g+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".zw);\n ",v+1<h&&(m+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+u+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+g+"C"+(v+1)+" = vec4(xTexelR"+g+"C"+(v+2)+".xy, final.xy);\n ")):(m+="\n if(xC >= 0 && xC < "+o+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + "+u+";\n if(xCOffset >= 0 && xCOffset < "+o+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = vec4(\n xTexelR"+g+"C"+v+".xy, xTexelR"+g+"C"+(v+2)+".xy);\n ",v+1<h&&(m+="\n xR"+g+"C"+(v+1)+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".zw);\n ")),m+="}");v<h&&(m+="\n vec4 wTexelR"+g+"C"+v+" = getW("+g+", "+v+", d1, q);\n wR"+g+"C"+v+" = vec4(wTexelR"+g+"C"+v+".xz, wTexelR"+g+"C"+v+".xz);\n ",v+1<h&&(m+="\n vec4 wTexelR"+g+"C"+(v+1)+" = getW("+g+", "+(v+1)+", d1, q);\n wR"+g+"C"+(v+1)+" =\n vec4(wTexelR"+g+"C"+(v+1)+".xz, wTexelR"+g+"C"+(v+1)+".xz);"))}for(g=0;g<p;g++)for(v=0;v<h;v++)m+="dotProd += xR"+g+"C"+v+" * wR"+g+"C"+v+";";var w="",x="";n&&(w=r?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"vec4 activation(vec4 x) {\n "+n+"\n }",x="result = activation(result);");var _=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+w+"\n\n const ivec2 strides = ivec2("+c+", "+u+");\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2;\n int q = 0;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n vec4 dotProd = vec4(0.);\n\n "+m+"\n\n vec4 result = dotProd;\n "+_+"\n "+x+"\n setOutput(result);\n }\n "},Qo=function(e,t,n,r,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=e[0],a=e[1],s=e[2],c=e[3],u=t[0],d=n[0],l=n[1];this.outputShape=[u,d,l,c];var p="bilinear"===r?1:0,h=[a-1+".0",s-1+".0"],f=h[0],m=h[1],g=d>1?[""+(a-1)/(d-1),"(y2-y1) * height_ratio","y1*"+f+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+f],v=g[0],y=g[1],b=g[2],w=l>1?[""+(s-1)/(l-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],_=w[1],S=w[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+x+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+o+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+_+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+f+" ) {\n setOutput(float("+i+"));\n return;\n }\n float in_x = "+S+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+i+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},Jo=function(e,t,n){this.variableNames=["x"],this.outputShape=e;var r=e.length,i=e[e.length-1],o=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+i+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+bo(r)+" coords = getOutputCoords();\n int end = "+Zo(r,"coords")+";\n float val = 0.0;\n for (int i = "+i+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+Zo(r,"coords")+" = idx;\n val += getX("+function(e,t){if(1===e)return""+t;if(2===e)return t+".x, "+t+".y";if(3===e)return t+".x, "+t+".y, "+t+".z";if(4===e)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "};function Zo(e,t){if(1===e)return""+t;if(2===e)return t+".y";if(3===e)return t+".z";if(4===e)return t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}var ea=function(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ue.DENSE;var t=Ye(e),n=oo();this.outputShape=e,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ao(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = 4 * (resTexRC.x * "+t[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n "},ta=function(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ue.DENSE;var t=Ye(e),n=oo();this.outputShape=e,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ao(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = 4 * (resTexRC.x * "+t[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n "},na=function(){function e(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+t+";\n int offset_h = imod(h, "+t+");\n int in_w = w / "+t+";\n int offset_w = imod(w, "+t+");\n int offset_d = (offset_h * "+t+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}(),ra=function(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},ia=function(e){this.variableNames=["A"],this.outTexUsage=Ve.DOWNLOAD;var t=oo();this.outputShape=e,this.userCode="\n "+co+"\n\n void main() {\n float x = getAAtOutCoords();\n "+t.output+" = encode_float(x);\n }\n "},oa=function(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ve.DOWNLOAD;var t=oo();this.outputShape=e,this.userCode="\n "+co+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+t.output+" = encode_float(x);\n }\n "},aa=function(e,t,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=oo(),i=t[0],o=t[1];this.outputShape=e;var a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode="\n "+so(e)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+o+";\n int c = imod(flatIndex, "+o+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+i+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+a+", 0., 0., 0.);\n }\n "},sa=function(e,t,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=oo(),i=t[0],o=t[1];this.outputShape=e;var a="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var c=0;c<=1;c++)for(var u=0;u<=1;u++){var d=2*c+u;a+="\n localCoords = coords;\n if(localCoords[2] + "+u+" < "+e[2]+") {\n localCoords[2] += "+u+";\n if(localCoords[1] + "+c+" < "+e[1]+") {\n localCoords[1] += "+c+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+o+";\n c = imod(flatIndex, "+o+");\n uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+i+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+d+"] = values[0];\n } else if(offset == 1) {\n result["+d+"] = values[1];\n } else if(offset == 2) {\n result["+d+"] = values[2];\n } else {\n result["+d+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+so(e)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n "+a+"\n\n "+r.output+" = "+s+";\n }\n "},ca=function(e,t,n){this.variableNames=["real","imag"];var r=t[1];this.outputShape=t;var i=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,o=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+i+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+e+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+o+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},ua=function(){function e(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){null==t.valueLoc&&(t.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(t.valueLoc,e)}},e}(),da=function(e,t,n){this.variableNames=["A","indices"];var r=e.slice();r[n]=t,this.outputShape=r,this.rank=r.length;var i=bo(this.rank),o=function(e,t){var n=e.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],o=0;o<e.length;o++)o===t?i.push("int(getIndices("+r[o]+"))"):i.push(""+r[o]);return i.join()}(e,n);this.userCode="\n void main() {\n "+i+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "},la=function(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;var r=bo(t.length),i=bo(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+i+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+o+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function pa(e,t){var n=oo();return rt(e,t,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function ha(e,t){return lt(e,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function fa(e,t){return pt(e,t,new Uint16Array([0,1,2,2,1,3]))}function ma(e,t,n,r,i,o,a){ft(n,r);var s=ht(e,t),c=e.TEXTURE_2D;return Ze(e,t,(function(){return e.bindTexture(c,s)})),Ze(e,t,(function(){return e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)})),Ze(e,t,(function(){return e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)})),Ze(e,t,(function(){return e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)})),Ze(e,t,(function(){return e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)})),Ze(e,t,(function(){return e.texImage2D(c,0,i,n,r,0,o,a,null)})),Ze(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)})),s}function ga(e,t,n,r,i){var o=$e(n,r);return ma(e,t,o[0],o[1],i.internalFormatFloat,i.textureFormatFloat,e.FLOAT)}function va(e,t,n,r,i){var o=$e(n,r);return ma(e,t,o[0],o[1],i.internalFormatHalfFloat,i.textureFormatFloat,i.textureTypeHalfFloat)}function ya(e,t,n,r,i){var o=$e(n,r);return ma(e,t,o[0],o[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function ba(e,t,n,r,i){var o=Qe(n,r);return ma(e,t,o[0],o[1],i.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function wa(e,t,n,r,i){var o=Qe(n,r);return ma(e,t,o[0],o[1],i.internalFormatPackedHalfFloat,e.RGBA,i.textureTypeHalfFloat)}function xa(e,t,n,r){return Ze(e,t,(function(){return e.bindBuffer(e.ARRAY_BUFFER,r)})),gt(e,t,n,"clipSpacePos",r,3,20,0)&&gt(e,t,n,"uv",r,2,20,12)}function _a(e,t,n,r,i,o,a){var s,c,u;Ze(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)})),o instanceof Uint8Array?(s=new Uint8Array(r*i*4),c=e.UNSIGNED_BYTE,u=e.RGBA):(s=new Float32Array(r*i*4),c=e.FLOAT,u=a.internalFormatPackedFloat),s.set(o),Ze(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,u,r,i,0,e.RGBA,c,s)})),Ze(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function Sa(e,t,n,r){Ze(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,n)})),r.data instanceof Uint8Array?Ze(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r.width,r.height,0,e.RGBA,e.UNSIGNED_BYTE,r.data)})):Ze(e,t,(function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)})),Ze(e,t,(function(){return e.bindTexture(e.TEXTURE_2D,null)}))}function Ra(e,t,n,r,i){var o=e.createBuffer();Ze(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,o)}));var a=16*n*r;return Ze(e,t,(function(){return e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ)})),Ze(e,t,(function(){return e.readPixels(0,0,r,n,e.RGBA,e.FLOAT,0)})),Ze(e,t,(function(){return e.bindBuffer(e.PIXEL_PACK_BUFFER,null)})),o}function Ca(e,t,n){var r=e,i=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function Ea(e,t,n,r,i){var o=$e(n,r),a=o[0],s=o[1],c=new Uint8Array(n*r*4);return Ze(e,t,(function(){return e.readPixels(0,0,a,s,i.downloadTextureFormat,e.UNSIGNED_BYTE,c)})),new Float32Array(c.buffer)}function ka(e,t,n,r,i,o,a,s){var c=e,u=new Float32Array(function(e,t){var n=Qe(e,t);return n[0]*n[1]*4}(o,a));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,u),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),u}function Ta(e,t,n,r){var i=new Float32Array(n*r*4);return Ze(e,t,(function(){return e.readPixels(0,0,r,n,e.RGBA,e.FLOAT,i)})),i}var Da=Object.freeze({createVertexShader:pa,createVertexBuffer:ha,createIndexBuffer:fa,createFloat32MatrixTexture:ga,createFloat16MatrixTexture:va,createUnsignedBytesMatrixTexture:ya,createPackedMatrixTexture:ba,createFloat16PackedMatrixTexture:wa,bindVertexProgramAttributeStreams:xa,uploadDenseMatrixToTexture:_a,uploadPixelDataToTexture:Sa,createBufferFromOutputTexture:Ra,downloadFloat32MatrixFromBuffer:Ca,downloadByteEncodedFloatMatrixFromOutputTexture:Ea,downloadPackedMatrixFromBuffer:ka,downloadMatrixFromPackedOutputTexture:Ta}),Pa=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var t=l().getNumber("WEBGL_VERSION");null!=e?(this.gl=e,Ke(t,e)):this.gl=Xe(t);var n="WEBGL_color_buffer_float";if(1===l().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=nt(this.gl,this.debug,"OES_texture_float"),Nt(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=nt(this.gl,this.debug,"OES_texture_half_float");else if(l().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Nt(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=nt(this.gl,this.debug,"EXT_color_buffer_half_float");else if(l().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Nt(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Nt(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=ha(this.gl,this.debug),this.indexBuffer=fa(this.gl,this.debug),this.framebuffer=mt(this.gl,this.debug),this.textureConfig=Je(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,"debug",{get:function(){return l().getBool("DEBUG")},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var e=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var t=this.gl;Ze(t,this.debug,(function(){return t.finish()})),Ze(t,this.debug,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),Ze(t,this.debug,(function(){return t.deleteFramebuffer(e.framebuffer)})),Ze(t,this.debug,(function(){return t.bindBuffer(t.ARRAY_BUFFER,null)})),Ze(t,this.debug,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)})),Ze(t,this.debug,(function(){return t.deleteBuffer(e.indexBuffer)})),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(e,t){return this.throwIfDisposed(),ga(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(e,t){return this.throwIfDisposed(),va(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(e,t){return this.throwIfDisposed(),ya(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(e,t){this.throwIfDisposed(),Sa(this.gl,this.debug,e,t)},e.prototype.uploadDenseMatrixToTexture=function(e,t,n,r){this.throwIfDisposed(),_a(this.gl,this.debug,e,t,n,r,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(e,t){return this.throwIfDisposed(),wa(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(e,t){return this.throwIfDisposed(),ba(this.gl,this.debug,e,t,this.textureConfig)},e.prototype.deleteMatrixTexture=function(e){var t=this;this.throwIfDisposed(),this.outputTexture===e&&(_t(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Ze(this.gl,this.debug,(function(){return t.gl.deleteTexture(e)}))},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,(function(){return Ea(r.gl,r.debug,t,n,r.textureConfig)}))},e.prototype.downloadPackedMatrixFromBuffer=function(e,t,n,r,i,o){return ka(this.gl,e,0,0,0,i,o,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(e,t){return Ca(this.gl,e,t)},e.prototype.createBufferFromTexture=function(e,t,n){this.bindTextureToFrameBuffer(e);var r=Ra(this.gl,this.debug,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},e.prototype.createAndWaitForFence=function(){var e=this.createFence(this.gl);return this.pollFence(e)},e.prototype.createFence=function(e){var t,n,r=this;if(l().getBool("WEBGL_FENCE_API_ENABLED")){var i=e,o=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=function(){var e=i.clientWaitSync(o,0,0);return e===i.ALREADY_SIGNALED||e===i.CONDITION_SATISFIED},t=o}else l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(t,l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:t,isFencePassed:n}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,(function(){return Ta(r.gl,r.debug,t,n)}))},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=it(t,this.debug,e),r=pa(t,this.debug),i=ct(t,this.debug);return Ze(t,this.debug,(function(){return t.attachShader(i,r)})),Ze(t,this.debug,(function(){return t.attachShader(i,n)})),ut(t,this.debug,i),this.debug&&dt(t,this.debug,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=xa(t,this.debug,this.program,this.vertexBuffer)),i},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&Ze(this.gl,this.debug,(function(){return t.gl.deleteProgram(e)}))},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&dt(this.gl,this.debug,this.program),Ze(this.gl,this.debug,(function(){return t.gl.useProgram(e)}))},e.prototype.getUniformLocation=function(e,t,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?yt(this.gl,this.debug,e,t):bt(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),Ze(this.gl,this.debug,(function(){return n.gl.getAttribLocation(e,t)}))},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),wt(this.gl,this.debug,this.program,e,t,n)},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=Qe(t,n),i=r[0],o=r[1];this.setOutputMatrixTextureDriver(e,i,o)},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&dt(this.gl,this.debug,this.program),St(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.debug&&this.debugValidate(),Ze(e,this.debug,(function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)}))},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),Ze(this.gl,this.debug,(function(){return e.gl.finish()}))},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=nt(this.gl,this.debug,2===l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),i=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,i),i},e.prototype.endQuery=function(){if(2!==l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return c(this,void 0,void 0,(function(){var t=this;return u(this,(function(n){switch(n.label){case 0:return[4,L((function(){return t.disposed||t.isQueryAvailable(e,l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(e,l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}}))}))},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise((function(n){t.addItemToPoll((function(){return e.isFencePassed()}),(function(){return n()}))}))},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map((function(e){return e.isDoneFn}))),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var n=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||L((function(){return n.pollItems(),0===n.itemsToPoll.length}))},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),xt(this.gl,this.debug,e,this.framebuffer),this.debug&&St(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(xt(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&St(this.gl)):_t(this.gl,this.debug,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var n=t();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;xt(r,this.debug,e,this.framebuffer),this.debug&&St(r),this.outputTexture=e,Ze(r,this.debug,(function(){return r.viewport(0,0,t,n)})),Ze(r,this.debug,(function(){return r.scissor(0,0,t,n)}))},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var i=this;this.throwIfDisposed(),Ze(this.gl,this.debug,(function(){return i.gl.scissor(e,t,n,r)}))},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function Ia(e,t){if(e.length!==t.length)throw Error("Binary was compiled with "+e.length+" inputs, but was executed with "+t.length+" inputs");e.forEach((function(e,n){var r=e.logicalShape,i=t[n],o=i.shape;if(!M(r,o))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+o+" must match");if(!e.isUniform||!i.isUniform){var a=e.texShape,s=i.isUniform?null:i.texData.texShape;if(!M(a,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+s+" must match")}}))}var Ma=function(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;for(var r=n.filterWidth,i=n.inChannels,o=n.strideWidth,a=n.strideHeight,s=n.padInfo,c=n.outWidth,u=n.dilationWidth,d=n.dilationHeight,l=n.dataFormat,p=s.left,h=s.top,f=i*r,m=oo(),g="channelsLast"===l,v=g?0:1,y=g?1:2,b="",w=0;w<=1;w++)for(var x=0;x<=1;x++)b+="\n blockIndex = rc.y + "+x+";\n pos = rc.x + "+w+";\n\n if(blockIndex < "+e[1]+" && pos < "+e[0]+") {\n offsetY = int(blockIndex / ("+c+")) * "+a+" - "+h+";\n d0 = offsetY + "+d+" * (pos / "+f+");\n\n if(d0 < "+t[v]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+c+".) * "+o+". - "+p+".);\n d1 = offsetX + "+u+" * (int(mod(float(pos), "+f+".) / "+i+".));\n\n if(d1 < "+t[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+i+".));\n\n if ("+g+") {\n innerDims = vec2(d1, ch);\n result["+(2*w+x)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*w+x)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+b+"\n\n "+m.output+" = result;\n }\n "},Oa=function(e,t,n,r,i){this.variableNames=["x"],this.outputShape=[];var o,a=t,s=e[3]-1;this.outputShape=e;var c="float("+n+") + float("+r+") * sum";o=.5===i?"inversesqrt("+c+")":1===i?"1.0/("+c+")":"exp(log("+c+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+a+"; j <= "+a+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+o+";\n setOutput(val);\n }\n "},Aa=function(e,t,n,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=i,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+t+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+t+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+i+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+i+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},Fa=function(e,t,n,r,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var o,a=t,s=e[3]-1;this.outputShape=e;var c="float("+n+") + float("+r+") * sum";o=.5===i?"inversesqrt("+c+")":1===i?"1.0/("+c+")":"exp(log("+c+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+a+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+a+"; j <= "+a+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+o+";\n setOutput(result);\n }\n "},Na=function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,i=e.effectiveFilterHeight,o=e.effectiveFilterWidth,a=i-1-e.padInfo.top,s=o-1-e.padInfo.left,c=i*o-1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+t+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+o+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+c+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+o+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},La=function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,i=e.dilationDepth,o=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterDepth,c=e.effectiveFilterHeight,u=e.effectiveFilterWidth,d=s-1-e.padInfo.front,l=c-1-e.padInfo.top,p=u-1-e.padInfo.left,h=s*c*u-1;this.userCode="\n const ivec3 pads = ivec3("+d+", "+l+", "+p+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+i+") {\n float dyD = float(dyDCorner + wD) / "+t+".0;\n\n if (dyD < 0.0 || dyD >= "+e.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+c+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC += "+a+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+h+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+c+" * "+u+" +\n wR * "+u+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ba=function(e,t,n,r,i,o,a){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i=!1),void 0===o&&(o=null),void 0===a&&(a=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;var s=n?e[1]:e[2],c=Math.ceil(s/2),u=n?"i * 2, rc.y":"rc.y, i * 2",d=r?"rc.z, i * 2":"i * 2, rc.z",l=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],h="",f="";o&&(h=a?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+o+"\n }":"vec4 activation(vec4 x) {\n "+o+"\n }",f="result = activation(result);");var m=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+h+"\n\n const float sharedDimension = "+c+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+c+"; i++) {\n vec4 a = getMatrixA(rc.x, "+u+");\n vec4 b = getMatrixB(rc.x, "+d+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+l[0]+" * "+p[0]+");\n result += ("+l[1]+" * "+p[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+m+"\n\n "+f+"\n\n setOutput(result);\n }\n "},ja=function(){function e(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(t-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(t-1)+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){null==t.seedLoc&&(t.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(t.seedLoc,e)}},e}(),Wa=function(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "},za=function(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;var t=e.length;if(0===t)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=io("rc",t),r=bo(t),i=function(e,t,n){if(1===e)return"rc > "+t[0];for(var r="",i=e-2;i<e;i++)r+=n[i]+" >= "+t[i],i<e-1&&(r+="||");return r}(t,e,n),o=function(e,t,n,r){if(1===e)return"";var i=r.slice(-2);return"\n int r = "+i[0]+";\n int c = "+i[1]+";\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+t+";\n bool rEdge = rp1 >= "+n+";\n "}(t,e[e.length-1],e[e.length-2],n),a=function(e,t){var n=e.length,r=function(e,t){for(var n=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var o=(0===r?"r":"rp1")+", "+(0===i?"c":"cp1"),a=2;a<e;a++)o=t[t.length-1-a]+","+o;n.push(o)}return n}(n,t);return 1===n?"getA(rc),\n rc + 1 >= "+e[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(e,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+i+") {\n setOutput(vec4(0));\n } else {\n "+o+"\n\n setOutput(vec4("+a+"));\n }\n }\n "}},Ua=function(e,t,n){this.variableNames=["x"],this.outputShape=t.map((function(t,n){return t[0]+e[n]+t[1]}));var r=e.length,i=bo(r),o=t.map((function(e){return e[0]})).join(","),a=t.map((function(t,n){return t[0]+e[n]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+i+" start = "+i+"("+o+");\n "+i+" end = "+i+"("+a+");\n\n void main() {\n "+i+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+i+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+o+";\n int end = "+a+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Va=function(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((function(t,n){return t[0]+e[n]+t[1]}));for(var r=e.length,i=bo(r),o=t.map((function(e){return e[0]})).join(","),a=t.map((function(t,n){return t[0]+e[n]})).join(","),s=io("rc",r),c=io("source",r),u=s[r-1]+" < "+this.outputShape[r-1],d=1===r?"source":"vec2("+c.slice(-2).join()+")",l=[i+" rc = outputLoc;",s[r-1]+" += 1;\n if("+u+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+u+") {"],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="",f=0,m=1===r?2:4;f<m;f++)h+="\n "+l[f]+"\n if ("+p+") {\n result["+f+"] = float("+n+");\n } else {\n "+i+" source = rc - start;\n result["+f+"] = getChannel(getX("+c.join()+"), "+d+");\n }\n ";h+=1===r?"} ":"}}",this.userCode="\n const "+i+" start = "+i+"("+o+");\n const "+i+" end = "+i+"("+a+");\n\n void main() {\n "+i+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+h+"\n setOutput(result);\n }\n "},Ga=function(e,t,n){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");var r=e.filterWidth,i=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,s=e.dilationWidth,c=e.effectiveFilterHeight,u=e.effectiveFilterWidth,d=e.padInfo.top,l=e.padInfo.left;this.outputShape=e.outShape;var p="avg"===t,h="0.0";if(p||(h="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+d+", "+l+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+c+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+u+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var f=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(f="avgValue / count");var m=4*Math.floor(r/4),g=r%4,v="\n if ("+p+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+d+", "+l+");\n const float initializationValue = "+h+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+e.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+h+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+c+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+v+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+v+"\n }\n }\n setOutput("+f+");\n }\n "}},qa=function(e,t,n){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");var r=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,s=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,d=e.effectiveFilterDepth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,m=e.padInfo.left;this.outputShape=e.outShape;var g="avg"===t,v="0.0";if(g||(v="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+o+", "+a+");\n const ivec3 pads = ivec3("+h+", "+f+", "+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+d+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+e.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+l+";\n wR += "+c+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+";\n wC += "+u+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+l+" * "+p+" +\n wR * "+p+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(y="avgValue / count");var b=4*Math.floor(r/4),w=r%4,x="\n if ("+g+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+o+", "+a+");\n const ivec3 pads = ivec3("+h+", "+f+", "+m+");\n const float initializationValue = "+v+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+e.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+v+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+d+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+e.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+l+";\n wR += "+c+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+b+"; wC += 4) {\n int xC = xCCorner + wC * "+u+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+u+", ch),\n getValue(batch, xD, xR, xC + 2 * "+u+", ch),\n getValue(batch, xD, xR, xC + 3 * "+u+", ch)\n );\n\n "+x+"\n }\n\n int xC = xCCorner + "+b+";\n if ("+(1===w)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+x+"\n } else if ("+(2===w)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+u+", ch),\n initializationValue,\n initializationValue\n );\n\n "+x+"\n } else if ("+(3===w)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+u+", ch),\n getValue(batch, xD, xR, xC + 2 * "+u+", ch),\n initializationValue\n );\n\n "+x+"\n }\n }\n setOutput("+y+");\n }\n }\n "}},Ha=function(e,t){this.variableNames=["x"];var n=e.windowSize,r=e.batchSize,i=e.inSize,o=Math.ceil(i/n);this.outputShape=[r,o];var a="0.0",s="";"prod"===t?a="1.0":"min"===t?(a="1.0 / 1e-20",s="min"):"max"===t&&(a="-1.0 / 1e-20",s="max");var c=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===t?c="sumValue":"prod"===t?c="prodValue":"all"===t?c="allValue":"any"===t&&(c="anyValue");var u=4*Math.floor(n/4),d=n%4,l="\n if ("+("sum"===t)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===t)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",p="vec4";"all"===t?(a="1.0",l="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(a="0.0",l="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");var h="";i%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+a+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+h+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+a+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+u+"; i += 4) {\n int inIdx = inOffset + i;\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+l+"\n }\n\n int inIdx = inOffset + "+u+";\n if ("+(1===d)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+l+"\n } else if ("+(2===d)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+l+"\n } else if ("+(3===d)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+l+"\n }\n setOutput("+c+");\n }\n "},Ka=function(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;for(var n="",r=0;r<4;r++){var i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),n+="\n "+i+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+ao(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n \n "+so(e)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+e[1]+";\n int cols = "+e[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "},Xa=function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,i=r[1],o=r[2],a=e.shape,s=a[1],c=a[2],u=[n&&s>1?i-1:i,n&&c>1?o-1:o],d=[n&&s>1?s-1:s,n&&c>1?c-1:c],l=u[0]/d[0],p=u[1]/d[1],h=1/l,f=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(f)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+l+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+f+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+c+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(i-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(o-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},$a=function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var i=e[0],o=e[1],a=e[2],s=e[3];this.outputShape=[i,t,n,s];var c=[r&&t>1?o-1:o,r&&n>1?a-1:a],u=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+c[0]/u[0]+",\n "+c[1]/u[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+a+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},Ya=function(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var i=e[0],o=e[1],a=e[2],s=e[3];this.outputShape=[i,t,n,s];var c=[r&&t>1?o-1:o,r&&n>1?a-1:a],u=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+c[0]/u[0]+",\n "+c[1]/u[1]+",\n "+c[1]/u[1]+");\n const vec3 inputShapeRC = vec3("+o+".0, "+a+".0,\n "+a+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+";\n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},Qa=function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,i=r[1],o=r[2],a=e.shape,s=a[1],c=a[2],u=[n&&s>1?i-1:i,n&&c>1?o-1:o],d=[n&&s>1?s-1:s,n&&c>1?c-1:c],l=u[0]/d[0],p=u[1]/d[1],h=1/l,f=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(f)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+l+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+f+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+c+") {\n continue;\n }\n\n float sourceFracRow =\n float("+u[0]+") *\n (float(dyR) / float("+d[0]+"));\n\n float sourceFracCol =\n float("+u[1]+") *\n (float(dyC) / float("+d[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+i+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Ja=function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var i=e[0],o=e[1],a=e[2],s=e[3];this.outputShape=[i,t,n,s];var c=[r&&t>1?o-1:o,r&&n>1?a-1:a],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+c[0]/u[0]+",\n "+c[1]/u[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+a+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+d+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},Za=function(e,t){this.variableNames=["x"];var n=e.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=e,1!==n){var r=e.map((function(n,r){return function(n){return-1!==t.indexOf(n)&&1!==e[n]?e[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)})).join(","),i=bo(n);this.userCode="\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "},es=function(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var n=e.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=e;var r=io("rc",n),i=r[n-1]+" + 1 < "+this.outputShape[n-1],o=r[n-2]+" + 1 < "+this.outputShape[n-2],a=bo(n);function s(n){var r=e.map((function(r,i){return function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?e[n]+" - "+r[n]+" - 1":""+r[n]}(i,n)}));return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+e[0]+" - rc - 1),\n "+e[0]+" - rc - 1);\n if("+i+"){\n result.g = getChannel(getX("+e[0]+" - (rc + 1) - 1),\n "+e[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+a+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(e){return s(e)}(r.slice())+";\n if("+i+"){\n result.g = "+function(e){return e[n-1]="("+e[n-1]+" + 1)",s(e)}(r.slice())+";\n }\n if("+o+") {\n result.b = "+function(e){return e[n-2]="("+e[n-2]+" + 1)",s(e)}(r.slice())+";\n if("+i+") {\n result.a = "+function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",s(e)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "},ts=function(e,t,n,r,i,o,a){void 0===a&&(a=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var s=bo(i.length),c=bo(o.length),u="";1===n?u="i":2===n&&(u="i, j");var d="getIndices("+u+")",l="";1===r?l="i":2===r&&(l="i, coords[1]");var p="getUpdates("+l+")",h=t>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+i+");\n\n void main() {\n "+c+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+e+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+t+"; j++) {\n int index = round("+d+");\n flattenedIndex += index * "+h+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+p+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},ns=function(e,t){this.variableNames=["x","segmentIds"];var n=e.windowSize,r=e.batchSize,i=e.inSize,o=e.numSegments,a=o*Math.ceil(i/n);this.outputShape=[r,a];var s=4*Math.floor(n/4),c=n%4,u="\n sumValue += dot(values, segFilter);\n ",d="";i%n>0&&(d="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n ");var l="";i%n>0&&(l="\n if (inIdx < 0 || inIdx >= "+i+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+d+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+l+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+o+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+u+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===c)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+u+"\n } else if ("+(2===c)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+u+"\n } else if ("+(3===c)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+u+"\n }\n setOutput(sumValue);\n }\n "},rs=function(e,t,n){var r,i;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)i="resRC",r="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],s=[],c=0;c<t.length;c++)s.push(""+o[c]),c<e&&a.push(""+o[c]);r=a.join(),i=s.join()}var u=bo(n);this.userCode="\n void main() {\n "+u+" resRC = getOutputCoords();\n float cVal = getC("+r+");\n if (cVal >= 1.0) {\n setOutput(getA("+i+"));\n } else {\n setOutput(getB("+i+"));\n }\n }\n "},is=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t,n=bo(this.rank),r="uniform int start["+this.rank+"];",i=function(e){if(1===e)return"sourceLoc";if(e<=6)return os.slice(0,e).map((function(e){return"sourceLoc."+e})).join(",");throw Error("Slicing for rank "+e+" is not yet supported")}(this.rank);t="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+e.map((function(e,t){return"sourceLoc."+os[t]+" = start["+t+"] + coords."+os[t]+";"})).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+t+"\n setOutput(getSource("+i+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(n,r){null==t.startLoc&&(t.startLoc=n.getUniformLocationNoThrow(r,"start"),null==t.startLoc)||n.gl.uniform1iv(t.startLoc,e)}},e}(),os=["x","y","z","w","u","v"],as=function(){function e(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;var t=bo(this.rank),n=io("coords",this.rank),r=io("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",o="getChannel(getSource("+r.join()+"), "+i+")",a="\n result.x = "+o+";\n if (++"+n[this.rank-1]+" < "+e[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+o+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+e[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+o+";\n if (++"+n[this.rank-1]+" < "+e[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+o+";\n }\n }\n ",c=this.rank<=4?"sourceLoc = coords +\n "+t+"("+e.map((function(e,t){return"start["+t+"]"})).join()+");":e.map((function(e,t){return r[t]+" = "+n[t]+" + start["+t+"];"})).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+t+" coords = getOutputCoords();\n "+t+" sourceLoc;\n "+c+"\n vec4 result = vec4(0.);\n "+a+"\n "+s+"\n setOutput(result);\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(n,r){null==t.startLoc&&(t.startLoc=n.getUniformLocationNoThrow(r,"start"),null==t.startLoc)||n.gl.uniform1iv(t.startLoc,e)}},e}(),ss=function(e,t,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,i=bo(n.length),o=bo(n.length),a="";if(1===r)a="coords * strides + begin";else{var s=0;a=n.map((function(e,t){return s++,1===n.length?"coords * strides["+t+"] + begin["+t+"]":"coords["+(s-1)+"] * strides["+t+"] + begin["+t+"]"})).join(",")}this.userCode="\n "+i+" begin = "+i+"("+e+");\n "+i+" strides = "+i+"("+t+");\n\n void main() {\n "+o+" coords = getOutputCoords();\n setOutput(getX("+a+"));\n }\n "},cs=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t,n){var r,i=us(t,n),o=ds(e,i,n);if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var a=this.freeTextures[o].shift();return this.usedTextures[o].push(a),a}return this.numUsedTextures++,this.log(),i===Ge.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):i===Ge.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):i===Ge.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):i===Ge.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):i===Ge.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[o].push(r),r},e.prototype.releaseTexture=function(e,t,n,r){if(null!=this.freeTextures){var i=ds(t,us(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(e),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[i],a=o.indexOf(e);if(a<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(a,1),this.log()}},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach((function(t){e.gpgpu.deleteMatrixTexture(t)}));for(var t in this.usedTextures)this.usedTextures[t].forEach((function(t){e.gpgpu.deleteMatrixTexture(t)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function us(e,t){if(e===Ve.UPLOAD)return Ge.PACKED_2X2_FLOAT32;if(e===Ve.RENDER||null==e)return function(e){return l().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Ge.PACKED_2X2_FLOAT32:Ge.UNPACKED_FLOAT32:e?Ge.PACKED_2X2_FLOAT16:Ge.UNPACKED_FLOAT16}(t);if(e===Ve.DOWNLOAD||e===Ve.PIXELS)return Ge.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+e)}function ds(e,t,n){return e[0]+"_"+e[1]+"_"+t+"_"+n}var ls=function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r<n.length;r++)n[r]=e[r]*t[r];this.outputShape=n,this.rank=n.length;var i=bo(this.rank),o=function(e){var t=e.length;if(t>5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],i=0;i<e.length;i++)r.push("imod("+n[i]+", "+e[i]+")");return r.join()}(e);this.userCode="\n void main() {\n "+i+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "},ps=function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.rank=n.length;var i=bo(this.rank),o=function(e){var t=e.length;if(t>6)throw Error("Transpose for rank "+t+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t),i=0;i<e.length;i++)r[e[i]]=n[i];return r.join()}(t);this.userCode="\n void main() {\n "+i+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "},hs=function(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var n=new Array(e.length),r=0;r<n.length;r++)n[r]=e[t[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var i=bo(this.rank),o=ro("rc",this.rank),a=new Array(this.rank);for(r=0;r<t.length;r++)a[t[r]]=o[r];var s="vec2("+a.slice(-2).join()+")",c="++"+o[this.rank-1]+" < "+n[this.rank-1],u="getChannel(getA("+a.join()+"), "+s+")";this.userCode="\n void main() {\n "+i+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = "+u+";\n if("+c+") {\n result[1] = "+u+";\n }\n --"+o[this.rank-1]+";\n if(++"+o[this.rank-2]+" < "+n[this.rank-2]+") {\n result[2] = "+u+";\n if("+c+") {\n result[3] = "+u+";\n }\n }\n setOutput(result);\n }\n "},fs=1.7580993408473768,ms=1.0507009873554805,gs=function(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode="\n float unaryOperation(float x) {\n "+t+"\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n "},vs="if (isnan(x)) return x;",ys="return abs(x);",bs=vs+"\n return (x < 0.0) ? 0.0 : x;\n",ws=vs+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",xs="return (x >= 0.0) ? x : (exp(x) - 1.0);",_s="\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = "+fs+";\n float scale = "+ms+";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n",Ss="return -x;",Rs="return ceil(x);",Cs="return floor(x);",Es="return exp(x);",ks="return exp(x) - 1.0;",Ts=vs+"\n return sin(x);\n",Ds=vs+"\n return cos(x);\n",Ps=vs+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n",Is=vs+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n",Ms=vs+"\n return atan(x);\n",Os=vs+"return log(x + sqrt(x * x + 1.0));",As=vs+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",Fs=vs+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Ns="return x;",Ls="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Bs="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",js="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",Ws=function(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+t+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "},zs=function(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;var t=e.length,n=io("rc",t),r=bo(t),i=function(e,t){if(1===e)return"rc";for(var n="",r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(t,n),o=n.slice(-2),a=t<=1?"rc":"vec2("+o.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+i+");\n\n setOutput(getChannel(packedInput, "+a+"));\n }\n "},Us={};function Vs(e,t){if(void 0===t&&(t=!1),"linear"===e)return"return x;";if("relu"===e)return t?Ls:bs;if("elu"===e)return t?js:xs;if("relu6"===e)return t?Bs:ws;if("prelu"===e)return t?Oo:Io;throw new Error("Activation "+e+" has not been implemented for the WebGL backend.")}var Gs=function(e){function t(t){var n,r=e.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!l().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==t){var i=Xe(l().getNumber("WEBGL_VERSION"));r.binaryCache=((n=l().getNumber("WEBGL_VERSION"))in Us||(Us[n]={}),Us[n]),r.gpgpu=new Pa(i),r.canvas=i.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=t,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=t.gl.canvas;return r.textureManager=new cs(r.gpgpu),r.numMBBeforeWarning=null==l().global.screen?1024:l().global.screen.height*l().global.screen.width*window.devicePixelRatio*600/1024/1024,r.texData=new gi(r,je),r}return s(t,e),t.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},t.prototype.write=function(e,t,n){if(l().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var r={};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:Ve.UPLOAD}),r},t.prototype.move=function(e,t,n,r){if(l().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:Ve.UPLOAD})},t.prototype.readSync=function(e){var t=this.texData.get(e),n=t.values,r=t.dtype,i=t.complexTensors,o=t.slice,a=t.shape,s=t.isPacked;if(null!=o){var c;c=s?new Ws(a,Ns):new gs(a,Ns);var u=this.runWebGLProgram(c,[{dataId:e,shape:a,dtype:r}],r),d=this.readSync(u.dataId);return this.disposeData(u.dataId),d}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===r)return n;var l,p,h=null!=this.activeTimers;return h&&(l=ae()),p="complex64"===r?Bi(i.real.dataSync(),i.imag.dataSync()):this.getValuesFromTexture(e),h&&(this.downloadWaitMs+=ae()-l),this.convertAndCacheOnCPU(e,p)},t.prototype.read=function(e){return c(this,void 0,void 0,(function(){var t,n,r,i,o,a,s,c,d,p,h,f,m,g,v,y,b,w,x,_,S,R;return u(this,(function(u){switch(u.label){case 0:if(this.pendingRead.has(e))return t=this.pendingRead.get(e),[2,new Promise((function(e){return t.push(e)}))];if(n=this.texData.get(e),r=n.values,i=n.shape,o=n.slice,a=n.dtype,s=n.complexTensors,c=n.isPacked,null!=o)return d=c?new Ws(i,Ns):new gs(i,Ns),p=this.runWebGLProgram(d,[{dataId:e,shape:i,dtype:a}],a),h=this.read(p.dataId),this.disposeData(p.dataId),[2,h];if(null!=r)return[2,this.convertAndCacheOnCPU(e)];if(!l().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===l().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=null,"complex64"!==a&&l().get("WEBGL_BUFFER_SUPPORTED")&&(m=this.decode(e),g=this.texData.get(m.dataId),f=(R=this.gpgpu).createBufferFromTexture.apply(R,[g.texture].concat(Ye(i)))),this.pendingRead.set(e,[]),"complex64"===a?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:u.sent(),u.label=2;case 2:return"complex64"!==a?[3,4]:[4,Promise.all([s.real.data(),s.imag.data()])];case 3:return y=u.sent(),b=y[0],w=y[1],v=Bi(b,w),[3,5];case 4:null==f?v=this.getValuesFromTexture(e):(x=I(i),v=this.gpgpu.downloadFloat32MatrixFromBuffer(f,x)),u.label=5;case 5:return null!=m&&this.disposeData(m.dataId),_=this.convertAndCacheOnCPU(e,v),S=this.pendingRead.get(e),this.pendingRead.delete(e),S.forEach((function(e){return e(_)})),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),[2,_]}}))}))},t.prototype.checkNumericalProblems=function(e){if(null!=e)for(var t=0;t<e.length;t++){var n=e[t];if(!et(n)){if(l().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+n+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+n+" cannot be represented on this device.")}}},t.prototype.getValuesFromTexture=function(e){var t,n=this.texData.get(e),r=n.shape,i=n.dtype,o=n.isPacked,a=I(r);if(l().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var s=this.decode(e),c=this.texData.get(s.dataId),u=(t=this.gpgpu).downloadMatrixFromPackedTexture.apply(t,[c.texture].concat(Ye(r))).subarray(0,a);return this.disposeData(s.dataId),u}var d=l().getBool("WEBGL_PACK")&&!0===o,p=d?Dt(r):r,h=d?new oa(p):new ia(p),f=this.runWebGLProgram(h,[{shape:p,dtype:i,dataId:e}],"float32"),m=this.texData.get(f.dataId),g=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(m.texture,m.texShape[0],m.texShape[1]).subarray(0,a);return this.disposeData(f.dataId),g},t.prototype.time=function(e){return c(this,void 0,void 0,(function(){var t,n,r,i,o,a,s;return u(this,(function(c){switch(c.label){case 0:return t=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),i=P(this.activeTimers.map((function(e){return e.query}))).filter((function(e){return null!=e})),o=P(this.activeTimers.map((function(e){return e.name}))).filter((function(e){return null!=e})),this.activeTimers=t,r&&(this.programTimersStack=null),a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(i)]:[3,2];case 1:return s=c.sent(),a.kernelMs=E(s),a.getExtraProfileInfo=function(){return s.map((function(e,t){return{name:o[t],ms:e}})).map((function(e){return e.name+": "+e.ms})).join(", ")},[3,3];case 2:a.kernelMs={error:"WebGL query timers are not supported in this environment."},c.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,a]}}))}))},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:ae(),endMs:null}},t.prototype.endTimer=function(e){return l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=ae(),e)},t.prototype.getQueryTime=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){return l().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]}))}))},t.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var t=this.texData.get(e).complexTensors;null!=t&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}}},t.prototype.releaseGPUData=function(e){var t=this.texData.get(e),n=t.texture,r=t.dtype,i=t.texShape,o=t.usage,a=t.isPacked,s=t.slice,c=s&&s.origDataId||e,u=this.dataRefCount.get(c);u>1?this.dataRefCount.set(c,u-1):(this.dataRefCount.delete(c),null!=n&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(n,i,o,a)));var d=this.texData.get(e);d.texture=null,d.texShape=null,d.isPacked=!1,d.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return l().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=je.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,t){var n=this;return void 0===t&&(t=128),null!=this.getCPUBackend()&&e.every((function(e){return null==n.texData.get(e.dataId).texture&&e.size<t}))},t.prototype.getGPGPUContext=function(){return this.gpgpu},t.prototype.complex=function(e,t){var n=this.makeOutput(e.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:je.keep(e.clone()),imag:je.keep(t.clone())},n},t.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,t,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.slice(e,t,n);if(0===I(n))return In([],n,e.dtype);var r=this.texData.get(e.dataId).isPacked,i=ii(e.shape,t,n);if(r||!i){var o=l().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new as(n):new is(n),a=o.getCustomSetupFunc(t);return this.compileAndRun(o,[e],null,a)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,n)},t.prototype.shallowSlice=function(e,t,n){var r=this.texData.get(e.dataId),i=this.makeOutput(n,e.dtype),o=this.texData.get(i.dataId);Object.assign(o,r),o.shape=n,o.dtype=e.dtype;var a=oi(t,e.strides);r.slice&&(a+=r.slice.flatOffset),o.slice={flatOffset:a,origDataId:r.slice&&r.slice.origDataId||e.dataId};var s=this.dataRefCount.get(o.slice.origDataId)||1;return this.dataRefCount.set(o.slice.origDataId,s+1),i},t.prototype.stridedSlice=function(e,t,n,r){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.stridedSlice(e,t,n,r);var i=ti(t,n,r);if(i.some((function(e){return 0===e})))return In([],i);var o=new ss(t,r,i);return this.compileAndRun(o,[e])},t.prototype.reverse=function(e,t){var n=l().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new es(e.shape,t):new Za(e.shape,t);return this.compileAndRun(n,[e])},t.prototype.concat=function(e,t){if("complex64"===e[0].dtype){var n=e.map((function(e){return Dn(e)})),r=e.map((function(e){return Pn(e)}));return Tn(this.concat(n,t),this.concat(r,t))}if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,t);if(1===e.length)return e[0];if(e.length>l().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(e.length/2),o=this.concat(e.slice(0,i),t),a=this.concat(e.slice(i),t);return this.concat([o,a],t)}if(l().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var s=new jo(e.map((function(e){return e.shape})),t);return this.compileAndRun(s,e)}var c=En(e.map((function(e){return e.shape})),t),u=e.map((function(e){return e.as2D(-1,I(e.shape.slice(t)))})),d=new Bo(u.map((function(e){return e.shape})));return this.compileAndRun(d,u).reshape(c)},t.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ss,e.dtype);var t=new gs(e.shape,Ss);return this.compileAndRun(t,[e])},t.prototype.batchMatMul=function(e,t,n,r){var i=n?e.shape[2]:e.shape[1],o=r?t.shape[1]:t.shape[2],a=n?e.shape[1]:e.shape[2],s=e.shape[0];if((1===i||1===o)&&a>1e3){n&&(e=e.transpose([0,2,1])),r&&(t=t.transpose([0,2,1]));var c=1===o?e:e.as3D(s,a,1),u=1===o?2:1,d=1===o?t.as3D(s,1,a):t;return this.multiply(c,d).sum(u,!0)}var l=Pe(e.dtype,t.dtype),p=new Ba(e.shape,[s,i,o],n,r);return this.compileAndRun(p,[e,t],l)},t.prototype.fusedBatchMatMul=function(e){var t=e.a,n=e.b,r=e.transposeA,i=e.transposeB,o=e.bias,a=e.activation,s=e.preluActivationWeights,c=r?t.shape[2]:t.shape[1],u=i?n.shape[1]:n.shape[2],d=t.shape[0],l=Pe(t.dtype,n.dtype),p=null!=o,h=null!=s,f=a?Vs(a,!0):null,m=new Ba(t.shape,[d,c,u],r,i,p,f,h),g=[t,n];return o&&g.push(o),s&&g.push(s),this.compileAndRun(m,g,l)},t.prototype.multiply=function(e,t){if("complex64"===e.dtype){var n=this.texData.get(e.dataId),r=this.texData.get(t.dataId),i=new ko("return areal * breal - aimag * bimag;",e.shape,t.shape),o=new ko("return areal * bimag + aimag * breal;",e.shape,t.shape),a=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag),this.makeComplexComponentTensorInfo(t,r.complexTensors.real),this.makeComplexComponentTensorInfo(t,r.complexTensors.imag)],s=this.compileAndRun(i,a),c=this.compileAndRun(o,a),u=this.complex(s,c);return s.dispose(),c.dispose(),u}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Po,e.dtype);var d=new Mo(Po,e.shape,t.shape);return this.compileAndRun(d,[e,t],e.dtype)},t.prototype.batchNormalization=function(e,t,n,r,i,o){var a=[e,t,n],s=null;null!=o&&(s=o.shape,a.push(o));var c=null;if(null!=i&&(c=i.shape,a.push(i)),l().getBool("WEBGL_PACK_NORMALIZATION")){var u=new Eo(e.shape,t.shape,n.shape,s,c,r);return this.compileAndRun(u,a)}var d=new Co(e.shape,t.shape,n.shape,s,c,r);return this.compileAndRun(d,a)},t.prototype.localResponseNormalization4D=function(e,t,n,r,i){var o=l().getBool("WEBGL_PACK_NORMALIZATION")?new Fa(e.shape,t,n,r,i):new Oa(e.shape,t,n,r,i);return this.compileAndRun(o,[e])},t.prototype.LRNGrad=function(e,t,n,r,i,o,a){var s=new Aa(t.shape,r,i,o,a);return this.compileAndRun(s,[t,n,e])},t.prototype.tile=function(e,t){if("string"===e.dtype){var n=this.readSync(e.dataId).map((function(e){return ue(e)}));return Qi(pr(e.shape,e.dtype,n),t)}var r=new ls(e.shape,t);return this.compileAndRun(r,[e])},t.prototype.pad=function(e,t,n){var r=l().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Va(e.shape,t,n):new Ua(e.shape,t,n);return this.compileAndRun(r,[e])},t.prototype.transpose=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,t);var n=l().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new hs(e.shape,t):new ps(e.shape,t);return this.compileAndRun(n,[e])},t.prototype.gather=function(e,t,n){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.gather(e,t,n);var r=new da(e.shape,t.size,n);return this.compileAndRun(r,[e,t])},t.prototype.batchToSpaceND=function(e,t,n){k(e.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var r=t.reduce((function(e,t){return e*t})),i=zr(e.shape,t,r),o=Ur(i.length,t.length),a=Vr(e.shape,t,r),s=Gr(n,t.length),c=qr(a,n,t.length);return e.reshape(i).transpose(o).reshape(a).slice(s,c)},t.prototype.spaceToBatchND=function(e,t,n){k(e.rank<=4,(function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"}));var r=t.reduce((function(e,t){return e*t})),i=[[0,0]];i.push.apply(i,n);for(var o=1+t.length;o<e.shape.length;++o)i.push([0,0]);var a=e.pad(i),s=zr(a.shape,t,r,!1),c=Ur(s.length,t.length,!1),u=Vr(a.shape,t,r,!1);return a.reshape(s).transpose(c).reshape(u)},t.prototype.reduce=function(e,t,n){var r=e.shape[0],i=e.shape[1],o=Xr(i),a=new Ha({windowSize:o,inSize:i,batchSize:r},t),s=this.compileAndRun(a,[e],n);return 1===s.shape[1]?s:this.reduce(s,t,n)},t.prototype.argReduce=function(e,t,n){void 0===n&&(n=null);var r=e.shape[0],i=e.shape[1];null!=n&&(r=n.shape[0],i=n.shape[1]);var o=Xr(i),a=new no({windowSize:o,inSize:i,batchSize:r},t,null==n),s=[e];null!=n&&s.push(n);var c=this.compileAndRun(a,s,"int32");return 1===c.shape[1]?c:this.argReduce(e,t,c)},t.prototype.argReducePacked=function(e,t,n){void 0===n&&(n=null);var r=null!=n?n.shape:e.shape,i=Xr(r[r.length-1]),o=new _o(r,i,t,null==n),a=null==n?[e]:[e,n],s=this.compileAndRun(o,a,"int32");return s.rank===e.rank?this.argReducePacked(e,t,s):s},t.prototype.sum=function(e,t){xn("sum",t,e.rank);var n=bn(e.shape,t),r=n[0],i=I(n[1]),o=e.as2D(-1,i),a=Ie(e.dtype);return this.reduce(o,"sum",a).reshape(r)},t.prototype.prod=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.prod(e,t);var n=bn(e.shape,t),r=n[0],i=I(n[1]),o=e.as2D(-1,i),a=Ie(e.dtype);return this.reduce(o,"prod",a).reshape(r)},t.prototype.unsortedSegmentSum=function(e,t,n){var r=0,i=_n([r],e.rank),o=e;null!=i&&(o=e.transpose(i),r=Rn(1,e.rank)[0]);var a=function(e,t,n){for(var r=[],i=e.length,o=0;o<i;o++)o!==t?r.push(e[o]):r.push(n);return r}(o.shape,r,n),s=I([o.shape[r]]),c=o.as2D(-1,s),u=Ie(e.dtype),d=this.segOpCompute(c,"unsortedSegmentSum",t,u,n).reshape(a);return null!=i&&(d=d.transpose(Sn(i))),d},t.prototype.segOpCompute=function(e,t,n,r,i){var o=e.shape[0],a=e.shape[1],s=function(e,t){var n,r=!1;for(e<=30?(n=e,r=!0):n=ee(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=ee(e,n+1);return n}(a,i),c=new ns({windowSize:s,inSize:a,batchSize:o,numSegments:i},t),u=this.compileAndRun(c,[e,n],r);return u.shape[1]===i?u:(n=qn(0,i).tile([a/s]),this.segOpCompute(u,t,n,r,i))},t.prototype.argMinMaxReduce=function(e,t,n){var r=[t];if(xn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,e.rank),!l().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var i=bn(e.shape,r),o=i[0],a=I(i[1]),s=e.as2D(-1,a);return this.argReduce(s,n).reshape(o)}return this.argReducePacked(e,n)},t.prototype.argMin=function(e,t){return this.argMinMaxReduce(e,t,"min")},t.prototype.argMax=function(e,t){return this.argMinMaxReduce(e,t,"max")},t.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var i=new Jo(e.shape,n,r);return this.compileAndRun(i,[e])},t.prototype.equal=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(equal(a, b));\n","bool");var n=new Mo("return float(a == b);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.notEqual=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(notEqual(a, b));\n","bool");var n=new Mo("return float(a != b);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.less=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.less(e,t);if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(lessThan(a, b));\n","bool");var n=new Mo("return float(a < b);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.lessEqual=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Mo("return float(a <= b);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.greater=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.greater(e,t);if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Mo("return float(a > b);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.greaterEqual=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Mo("return float(a >= b);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.logicalNot=function(e){var t=new gs(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},t.prototype.logicalAnd=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new Mo("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.logicalOr=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new Mo("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")},t.prototype.select=function(e,t,n){var r=new rs(e.rank,t.shape,t.rank);return this.compileAndRun(r,[e,t,n],Pe(t.dtype,n.dtype))},t.prototype.where=function(e){pn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return Zi(e.shape,t)},t.prototype.topk=function(e,t,n){return Ji(e.dataSync(),e.shape,e.dtype,t)},t.prototype.min=function(e,t){xn("min",t,e.rank);var n=bn(e.shape,t),r=n[0],i=I(n[1]),o=e.as2D(-1,i);return this.reduce(o,"min",o.dtype).reshape(r)},t.prototype.minimum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.minimum(e,t);var n=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new Mo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.mod=function(e,t){var n=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new Mo("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.max=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,t);xn("max",t,e.rank);var n=bn(e.shape,t),r=n[0],i=I(n[1]),o=e.as2D(-1,i);return this.reduce(o,"max",o.dtype).reshape(r)},t.prototype.maximum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.maximum(e,t);var n=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new Mo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.all=function(e,t){xn("all",t,e.rank);var n=bn(e.shape,t),r=n[0],i=I(n[1]),o=e.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(r)},t.prototype.any=function(e,t){xn("any",t,e.rank);var n=bn(e.shape,t),r=n[0],i=I(n[1]),o=e.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(r)},t.prototype.realDivide=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0);var n=new Mo("\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",e.shape,t.shape);return this.compileAndRun(n,[e,t],"float32")},t.prototype.floorDiv=function(e,t){if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var n=new Mo("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",e.shape,t.shape);return this.compileAndRun(n,[e,t],"int32")},t.prototype.add=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,To);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.add(e,t);var n=Pe(e.dtype,t.dtype);if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,To,n);var r=new Mo(To,e.shape,t.shape);return this.compileAndRun(r,[e,t],n)},t.prototype.packedUnaryOp=function(e,t,n){var r=new Ws(e.shape,t);return this.compileAndRun(r,[e],n)},t.prototype.packedBinaryOp=function(e,t,n,r,i){void 0===i&&(i=!1);var o=new Ao(n,e.shape,t.shape,i);return this.compileAndRun(o,[e,t],r)},t.prototype.complexSeparableBinaryOp=function(e,t,n){var r=this,i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),a=[[i.complexTensors.real,o.complexTensors.real],[i.complexTensors.imag,o.complexTensors.imag]].map((function(i){var o=i[0],a=i[1],s=r.makeComplexComponentTensorInfo(e,o),c=r.makeComplexComponentTensorInfo(t,a),u=new Mo(n,e.shape,t.shape);return r.compileAndRun(u,[s,c],Pe(o.dtype,a.dtype))})),s=a[0],c=a[1],u=this.complex(s,c);return s.dispose(),c.dispose(),u},t.prototype.makeComplexComponentTensorInfo=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},t.prototype.addN=function(e){if(1===e.length)return e[0];if(e.length>l().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var t=Math.floor(e.length/2),n=this.addN(e.slice(0,t)),r=this.addN(e.slice(t));return this.addN([n,r])}var i=e.map((function(e){return e.dtype})).reduce((function(e,t){return Pe(e,t)})),o=e.map((function(e){return e.shape})),a=l().getBool("WEBGL_PACK")?new to(e[0].shape,o):new eo(e[0].shape,o);return this.compileAndRun(a,e,i)},t.prototype.subtract=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,Do);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.subtract(e,t);var n=Pe(e.dtype,t.dtype);if(l().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Do,e.dtype);var r=new Mo(Do,e.shape,t.shape);return this.compileAndRun(r,[e,t],n)},t.prototype.pow=function(e,t){var n=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new Mo("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",e.shape,t.shape),r=Pe(e.dtype,t.dtype);return this.compileAndRun(n,[e,t],r)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Rs,e.dtype);var t=new gs(e.shape,Rs);return this.compileAndRun(t,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Cs,e.dtype);var t=new gs(e.shape,Cs);return this.compileAndRun(t,[e])},t.prototype.sign=function(e){var t=new gs(e.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(t,[e])},t.prototype.isNaN=function(e){var t=new gs(e.shape,"return float(isnan(x));");return this.compileAndRun(t,[e],"bool")},t.prototype.isInf=function(e){var t=new gs(e.shape,"return float(isinf(x));");return this.compileAndRun(t,[e],"bool")},t.prototype.isFinite=function(e){var t=new gs(e.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(t,[e],"bool")},t.prototype.round=function(e){var t=new gs(e.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(t,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Es,e.dtype);var t=new gs(e.shape,Es);return this.compileAndRun(t,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ks,e.dtype);var t=new gs(e.shape,ks);return this.compileAndRun(t,[e])},t.prototype.softmax=function(e,t){var n=j([t],e.shape),r=this.max(e,n),i=wn(r.shape,n),o=this.subtract(e,r.reshape(i)),a=this.exp(o),s=this.sum(a,n).reshape(i);return this.realDivide(a,s)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",e.dtype);var t=new gs(e.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(t,[e])},t.prototype.log1p=function(e){var t=new gs(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},t.prototype.sqrt=function(e){var t=new gs(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var t=new gs(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},t.prototype.reciprocal=function(e){var t=new gs(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},t.prototype.relu=function(e){var t;return t=l().getBool("WEBGL_PACK")?new Ws(e.shape,Ls):new gs(e.shape,bs),this.compileAndRun(t,[e])},t.prototype.relu6=function(e){var t;return t=l().getBool("WEBGL_PACK")?new Ws(e.shape,Bs):new gs(e.shape,ws),this.compileAndRun(t,[e])},t.prototype.prelu=function(e,t){var n=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao(Oo,e.shape,t.shape):new Mo(Io,e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.elu=function(e){if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,js,e.dtype);var t=new gs(e.shape,xs);return this.compileAndRun(t,[e])},t.prototype.eluDer=function(e,t){var n=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",e.shape,t.shape):new Mo("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.selu=function(e){var t=new gs(e.shape,_s);return this.compileAndRun(t,[e])},t.prototype.int=function(e){var t=new gs(e.shape,"return float(int(x));");return this.compileAndRun(t,[e],"int32")},t.prototype.clip=function(e,t,n){var r,i=(r=l().getBool("WEBGL_PACK_CLIP")?new No(e.shape):new Fo(e.shape)).getCustomSetupFunc(t,n);return this.compileAndRun(r,[e],null,i)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(l().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ys,e.dtype);var t=new gs(e.shape,ys);return this.compileAndRun(t,[e])},t.prototype.complexAbs=function(e){var t=this.texData.get(e.dataId),n=new Lo(e.shape),r=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(n,r)},t.prototype.sigmoid=function(e){var t=new gs(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},t.prototype.softplus=function(e){var t=new gs(e.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(t,[e])},t.prototype.sin=function(e){var t=new gs(e.shape,Ts);return this.compileAndRun(t,[e])},t.prototype.cos=function(e){var t=new gs(e.shape,Ds);return this.compileAndRun(t,[e])},t.prototype.tan=function(e){var t=new gs(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},t.prototype.asin=function(e){var t=new gs(e.shape,Ps);return this.compileAndRun(t,[e])},t.prototype.acos=function(e){var t=new gs(e.shape,Is);return this.compileAndRun(t,[e])},t.prototype.atan=function(e){var t=new gs(e.shape,Ms);return this.compileAndRun(t,[e])},t.prototype.atan2=function(e,t){var n=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,t.shape):new Mo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},t.prototype.sinh=function(e){var t=new gs(e.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},t.prototype.cosh=function(e){var t=new gs(e.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},t.prototype.tanh=function(e){var t=new gs(e.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[e])},t.prototype.asinh=function(e){var t=new gs(e.shape,Os);return this.compileAndRun(t,[e])},t.prototype.acosh=function(e){var t=new gs(e.shape,As);return this.compileAndRun(t,[e])},t.prototype.atanh=function(e){var t=new gs(e.shape,Fs);return this.compileAndRun(t,[e])},t.prototype.erf=function(e){var t=new gs(e.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(t,[e])},t.prototype.step=function(e,t){var n=new gs(e.shape,function(e){return void 0===e&&(e=0),vs+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}(t));return this.compileAndRun(n,[e])},t.prototype.conv2dByMatMul=function(e,t,n,r,i,o){var a=e.shape,s=this.texData.get(e.dataId),c=n.inChannels,u=a[0]*a[1]*a[2],d=n.outChannels,p="channelsLast"===n.dataFormat,h=(1===u||1===d)&&c>1e3,f=a[2]%2!=0&&!!s.isPacked;if(h||!l().getBool("WEBGL_LAZILY_UNPACK")||!l().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!f){var m=p?a[0]*a[1]*a[2]:a[0]*a[2]*a[3],g=this.reshape(e,[1,m,n.inChannels]),v=this.reshape(t,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:v,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:o}),n.outShape)}var y=p?a[0]*a[1]*(a[2]+1):a[0]*a[2]*(a[3]+1),b={dataId:e.dataId,shape:[1,y,n.inChannels],dtype:e.dtype},w=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,k(Mt(s.shape,b.shape),(function(){return"packed reshape "+s.shape+" to "+b.shape+" isn't free"}));var x=this.reshape(t,[1,n.inChannels,n.outChannels]),_=this.fusedBatchMatMul({a:b,b:x,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:o}),S=this.texData.get(_.dataId);return k(S.isPacked,(function(){return"batchMatMul result is expected to be packed"})),s.shape=w,S.shape=n.outShape,je.makeTensorFromDataId(_.dataId,n.outShape,_.dtype)},t.prototype.conv2dWithIm2Row=function(e,t,n,r,i,o){var a=n.filterWidth,s=n.filterHeight,c=n.inChannels,u=n.outWidth,d=n.outHeight,l="channelsLast"===n.dataFormat,p=a*s*c,h=d*u,f=[p,h],m=e.squeeze([0]),g=t.reshape([1,p,-1]),v=new Ma(f,m.shape,n),y=this.compileAndRun(v,[m]).reshape([1,f[0],f[1]]),b=null!=r,w=null!=o,x=i?Vs(i,!0):null,_=new Ba(y.shape,[1,h,n.outChannels],!0,!1,b,x,w),S=[y,g];r&&S.push(r),w&&S.push(o);var R=this.compileAndRun(_,S);return l?R.reshape([1,d,u,n.outChannels]):R.reshape([1,n.outChannels,d,u])},t.prototype.fusedConv2d=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,o=e.activation,a=e.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(t,n,r,i,o,a);if(l().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,n,r,i,o,a);var s=null!=i,c=null!=a,u=o?Vs(o,!1):null,d=new Ko(r,s,u,c),p=[t,n];return i&&p.push(i),a&&p.push(a),this.compileAndRun(d,p)},t.prototype.conv2d=function(e,t,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(e,t,n);if(l().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,t,n);var r=new Ko(n);return this.compileAndRun(r,[e,t])},t.prototype.conv2dDerInput=function(e,t,n){var r=new Uo(n);return this.compileAndRun(r,[e,t])},t.prototype.conv2dDerFilter=function(e,t,n){var r=new zo(n);return this.compileAndRun(r,[e,t])},t.prototype.fusedDepthwiseConv2D=function(e){var t,n=e.input,r=e.filter,i=e.convInfo,o=e.bias,a=e.activation,s=e.preluActivationWeights,c=l().getBool("WEBGL_PACK_DEPTHWISECONV")&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,u=a?Vs(a,c):null,d=[n,r],p=null!=o,h=null!=s;return p&&d.push(o),h&&d.push(s),c?(t=new Yo(i,p,u,h),this.compileAndRun(t,d)):(t=new $o(i,p,u,h),this.compileAndRun(t,d))},t.prototype.depthwiseConv2D=function(e,t,n){var r;return l().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Yo(n),this.compileAndRun(r,[e,t])):(r=new $o(n),this.compileAndRun(r,[e,t]))},t.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new Ho(n);return this.compileAndRun(r,[e,t])},t.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new qo(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3d=function(e,t,n){var r=new Xo(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3dDerInput=function(e,t,n){var r=new Go(n);return this.compileAndRun(r,[e,t])},t.prototype.conv3dDerFilter=function(e,t,n){var r=new Vo(n);return this.compileAndRun(r,[e,t])},t.prototype.maxPool=function(e,t){var n=new Ga(t,"max",!1);return this.compileAndRun(n,[e])},t.prototype.avgPool=function(e,t){var n=new Ga(t,"avg",!1);return this.compileAndRun(n,[e],"float32")},t.prototype.maxPoolBackprop=function(e,t,n,r){var i=new Ga(r,"max",!0),o=this.compileAndRun(i,[t]),a=new Na(r),s=this.compileAndRun(a,[e,o],t.dtype);return o.dispose(),s},t.prototype.avgPoolBackprop=function(e,t,n){var r=new So(n);return this.compileAndRun(r,[e],t.dtype)},t.prototype.cast=function(e,t){return Ai(e,t,this)},t.prototype.unstack=function(e,t){for(var n=e.shape[t],r=new Array(e.rank-1),i=0,o=0;o<e.rank;o++)o!==t&&(r[i++]=e.shape[o]);var a=new Array(e.rank).fill(0),s=e.shape.slice();s[t]=1;var c=new Array(n);for(o=0;o<c.length;o++)a[t]=o,c[o]=this.slice(e,a,s).reshape(r);return c},t.prototype.avgPool3d=function(e,t){var n=new qa(t,"avg",!1);return this.compileAndRun(n,[e],"float32")},t.prototype.avgPool3dBackprop=function(e,t,n){var r=new Ro(n);return this.compileAndRun(r,[e],t.dtype)},t.prototype.maxPool3d=function(e,t){var n=new qa(t,"max",!1);return this.compileAndRun(n,[e],"float32")},t.prototype.maxPool3dBackprop=function(e,t,n,r){var i=new qa(r,"max",!0),o=this.compileAndRun(i,[t]),a=new La(r),s=this.compileAndRun(a,[e,o],t.dtype);return o.dispose(),s},t.prototype.reshape=function(e,t){var n=this.texData.get(e.dataId);if(n.isPacked&&!Mt(e.shape,t)&&(null===n.texture||!Mt(n.shape,t))){var r=this.packedReshape(e,t);return je.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return Fi(e,t)},t.prototype.resizeBilinear=function(e,t,n,r){var i=l().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Ya(e.shape,t,n,r):new $a(e.shape,t,n,r);return this.compileAndRun(i,[e],"float32")},t.prototype.resizeBilinearBackprop=function(e,t,n){var r=new Xa(e,t,n);return this.compileAndRun(r,[e])},t.prototype.resizeNearestNeighbor=function(e,t,n,r){var i=new Ja(e.shape,t,n,r);return this.compileAndRun(i,[e])},t.prototype.resizeNearestNeighborBackprop=function(e,t,n){var r=new Qa(e,t,n);return this.compileAndRun(r,[e])},t.prototype.multinomial=function(e,t,n,r){var i=t?e:fi(e),o=i.shape[0],a=i.shape[1],s=new ja(o,a,n),c=s.getCustomSetupFunc(r);return this.compileAndRun(s,[i],"int32",c)},t.prototype.oneHot=function(e,t,n,r){var i=new Wa(e.size,t,n,r);return this.compileAndRun(i,[e])},t.prototype.diag=function(e){var t=new ra(e.size);return this.compileAndRun(t,[e])},t.prototype.nonMaxSuppression=function(e,t,n,r,i){return pn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Gi(e.dataSync(),t.dataSync(),n,r,i)},t.prototype.cropAndResize=function(e,t,n,r,i,o){var a=new Qo(e.shape,t.shape,r,i,o);return this.compileAndRun(a,[e,t,n],"float32")},t.prototype.depthToSpace=function(e,t,n){k(t>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+t}));var r=e.shape[0],i="NHWC"===n?e.shape[1]:e.shape[2],o="NHWC"===n?e.shape[2]:e.shape[3],a="NHWC"===n?e.shape[3]:e.shape[1],s=i*t,c=o*t,u=a/(t*t),d=new na("NHWC"===n?[r,s,c,u]:[r,u,s,c],t,n);return this.compileAndRun(d,[e])},t.prototype.split=function(e,t,n){return Yi(e,t,n)},t.prototype.scatterND=function(e,t,n){var r=Qr(0,e,n),i=r.sliceRank,o=r.numUpdates,a=r.sliceSize,s=r.strides,c=r.outputSize,u=[c/a,a],d=e.reshape([o,i]),l=t.reshape([o,a]);if(0===c)return Fi(In([]),n);var p=On(0),h=new ts(o,i,d.rank,l.rank,s,u);return this.compileAndRun(h,[l,d,p]).reshape(n)},t.prototype.sparseToDense=function(e,t,n,r){var i=Qr(0,e,n),o=i.sliceRank,a=i.numUpdates,s=i.strides,c=i.outputSize,u=new ts(a,o,e.rank,t.rank,s,[c,1],!1);return this.compileAndRun(u,[t,e,r]).reshape(n)},t.prototype.fft=function(e){return this.fftImpl(e,!1)},t.prototype.ifft=function(e){return this.fftImpl(e,!0)},t.prototype.fftImpl=function(e,t){var n=this.texData.get(e.dataId),r=new ca("return real * expR - imag * expI;",e.shape,t),i=new ca("return real * expI + imag * expR;",e.shape,t),o=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)],a=this.compileAndRun(r,o),s=this.compileAndRun(i,o),c=this.complex(a,s).as2D(e.shape[0],e.shape[1]);return a.dispose(),s.dispose(),c},t.prototype.gatherND=function(e,t){var n=t.shape,r=n[n.length-1],i=Hr(e,t),o=i[0],a=i[1],s=i[2],c=i[3],u=t.reshape([a,r]),d=e.reshape([e.size/s,s]),l=new la(r,c,[a,s]);return this.compileAndRun(l,[d,u]).reshape(o)},t.prototype.fill=function(e,t,n){if("string"===(n=n||J(t))){var r=U(n,I(e));return r.fill(t),je.makeTensor(r,e,n,this)}var i=new ua(e,t),o=i.getCustomSetupFunc(t);return this.compileAndRun(i,[],n,o)},t.prototype.onesLike=function(e){if("string"===e.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,"string"===e.dtype?"":0,e.dtype)},t.prototype.linspace=function(e,t,n){return Ni(e,t,n)},t.prototype.makeTensorInfo=function(e,t){var n=this.write(null,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}},t.prototype.makeOutput=function(e,t){var n=this.makeTensorInfo(e,t).dataId;return je.makeTensorFromDataId(n,e,t,this)},t.prototype.unpackTensor=function(e){var t=new zs(e.shape);return this.runWebGLProgram(t,[e],e.dtype)},t.prototype.packTensor=function(e){var t=new za(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)},t.prototype.packedReshape=function(e,t){var n=[kt(e.shape)].concat(Tt(e.shape)),r={dtype:e.dtype,shape:n,dataId:e.dataId},i=[kt(t)].concat(Tt(t)),o=new Ka(i,n),a=this.runWebGLProgram(o,[r],e.dtype,null,!0);return{dataId:a.dataId,shape:t,dtype:a.dtype}},t.prototype.decode=function(e){var t,n=this.texData.get(e),r=n.isPacked,i=n.shape,o=n.dtype,a=Dt(i);return t=r?new ta(a):new ea(a),{dtype:o,shape:i,dataId:this.runWebGLProgram(t,[{shape:a,dtype:o,dataId:e}],o,null,!0).dataId}},t.prototype.runWebGLProgram=function(e,t,n,r,i){var o=this;void 0===i&&(i=!1);var a=this.makeTensorInfo(e.outputShape,n),s=this.texData.get(a.dataId);if(e.packedOutput&&(s.isPacked=!0),e.outPackingScheme===Ue.DENSE){var c=Ye(e.outputShape);s.texShape=c.map((function(e){return 2*e}))}if(null!=e.outTexUsage&&(s.usage=e.outTexUsage),0===I(a.shape))return s.values=z(a.dtype,0),a;var u=[],d=t.map((function(t){if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=o.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&I(t.shape)<=l().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}else if(!!n.isPacked!=!!e.packedInputs)t=n.isPacked?o.unpackTensor(t):o.packTensor(t),u.push(t),n=o.texData.get(t.dataId);else if(n.isPacked&&!Mt(n.shape,t.shape)){var r=t,i=t.shape;t.shape=n.shape,t=o.packedReshape(t,i),u.push(t),n=o.texData.get(t.dataId),r.shape=i}return o.uploadToGPU(t.dataId),{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(a.dataId);var p,h={shape:a.shape,texData:s,isUniform:!1},f=function(e,t,n){var r="";t.concat(n).forEach((function(e){var t=null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0,n=e.isUniform?"uniform":e.texData.texShape;r+=e.shape+"_"+n+"_"+t}));var i=e.userCode;return e.constructor.name+"_"+r+"_"+i}(e,d,h),m=this.getAndSaveBinary(f,(function(){return function(e,t,n,r){var i=t.userCode,o=n.map((function(e,n){var r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),a=o.map((function(e){return e.shapeInfo})),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},c=uo(o,s,i,t.packedInputs),u=e.createProgram(c),d=null,p=e.getUniformLocation(u,"NAN",!1);1===l().getNumber("WEBGL_VERSION")&&(d=e.getUniformLocation(u,"INFINITY",!1));for(var h={},f=0;f<t.variableNames.length;f++){var m=t.variableNames[f];h[m]=e.getUniformLocation(u,m,!1),h["offset"+m]=e.getUniformLocation(u,"offset"+m,!1)}return{program:t,source:c,webGLProgram:u,uniformLocations:h,inShapeInfos:a,outShapeInfo:s,infLoc:d,nanLoc:p}}(o.gpgpu,e,d,h)})),g=null!=this.activeTimers;if(g&&(p=this.startTimer()),function(e,t,n,r,i){Ia(t.inShapeInfos,n),Ia([t.outShapeInfo],[r]);var o=r.texData.texture,a=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(o,a[0],a[1]):e.setOutputMatrixTexture(o,a[0],a[1]),e.setProgram(t.webGLProgram),1===l().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((function(n,r){var i=t.program.variableNames[r],o=t.uniformLocations[i],a=t.uniformLocations["offset"+i];if(null!=o)if(n.isUniform)if(I(n.shape)<2)e.gl.uniform1f(o,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),e.gl.uniform1fv(o,s)}else null!=n.texData.slice&&null!=a&&e.gl.uniform1i(a,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture,o,r)})),null!=i&&i(e,t.webGLProgram),e.executeProgram()}(this.gpgpu,m,d,h,r),u.forEach((function(e){return o.disposeData(e.dataId)})),g&&(p=this.endTimer(p),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(p)})),!l().getBool("WEBGL_LAZILY_UNPACK")&&s.isPacked&&!1===i){var v=this.unpackTensor(a);return this.disposeData(a.dataId),v}return a},t.prototype.compileAndRun=function(e,t,n,r,i){void 0===i&&(i=!1),n=n||t[0].dtype;var o=this.runWebGLProgram(e,t,n,r,i);return je.makeTensorFromDataId(o.dataId,o.shape,o.dtype)},t.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){var e=this;this.disposed||(l().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((function(t){e.gpgpu.deleteProgram(e.binaryCache[t].webGLProgram),delete e.binaryCache[t]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},t.prototype.floatPrecision=function(){var e=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Jt((function(){if(!l().get("WEBGL_RENDER_FLOAT32_ENABLED")){var t=l().getBool("DEBUG");l().set("DEBUG",!1);var n=e.abs(On(1e-8)).dataSync()[0];if(l().set("DEBUG",t),n>0)return 32}return 16}))),this.floatPrecisionValue},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.uploadToGPU=function(e){var t,n=this.texData.get(e),r=n.shape,i=n.dtype,o=n.values,a=n.texture,s=n.usage,c=n.isPacked;if(null==a){var u,d=null!=this.activeTimers;d&&(u=ae());var l=n.texShape;if(null==l&&(l=Pt(r,c),n.texShape=l),null!=o){var p=Dt(r),h=void 0,f=l[1],m=l[0],g=o instanceof Uint8Array;c?(f=(t=Qe(l[0],l[1]))[0],m=t[1],h=new sa(p,[m,f],g)):h=new aa(p,[m,f],g);var v=this.makeTensorInfo([m,f],i);this.texData.get(v.dataId).usage=g?Ve.PIXELS:Ve.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),f,m,o);var y=this.runWebGLProgram(h,[v],i,null,!0),b=this.texData.get(y.dataId);n.texture=b.texture,n.texShape=b.texShape,n.isPacked=b.isPacked,n.usage=b.usage,this.disposeData(v.dataId),this.texData.delete(y.dataId),n.values=null,d&&(this.uploadWaitMs+=ae()-u)}else{var w=this.acquireTexture(l,s,i,c);n.texture=w}}},t.prototype.convertAndCacheOnCPU=function(e,t){var n=this.texData.get(e),r=n.dtype;return this.releaseGPUData(e),null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){for(var n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),r=0;r<n.length;++r)n[r]=Math.round(e[r]);return n}throw new Error("Unknown dtype "+t)}(t,r)),n.values},t.prototype.acquireTexture=function(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+i+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(e,t,r)},t.prototype.computeBytes=function(e,t){return e[0]*e[1]*K(t)},t}(vi);We()&&je.registerBackend("webgl",(function(){return new Gs}),2);var qs=kn({square_:function(e){var t=mn(e,"x","square"),n=[t];return je.runKernelFunc((function(e,n){return n([t]),e.square(t)}),{x:t},null,"Square",{},n,[])}}),Hs="SquaredDifference",Ks=kn({squaredDifference_:function(e,t){var n,r=mn(e,"a","squaredDifference"),i=mn(t,"b","squaredDifference");n=Me(r,i),r=n[0],i=n[1],xi(r.shape,i.shape);var o={a:r,b:i},a=[r,i];return je.runKernelFunc((function(e,t){var n=e.squaredDifference(r,i);return t([r,i]),n}),o,(function(e,t){var n=t[0],r=t[1],i=On(2);return{a:function(){return e.mul(n.sub(r).mul(i))},b:function(){return e.mul(r.sub(n).mul(i))}}}),Hs,{},a,[])}}),Xs=kn({abs_:function(e){var t=mn(e,"x","abs");return"complex64"===t.dtype?je.runKernelFunc((function(e){return e.complexAbs(t)}),{$x:t}):je.runKernelFunc((function(e,n){var r=e.abs(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mul(n.toFloat().step(-1))}}}),"Abs")}}),$s=kn({acos_:function(e){var t=mn(e,"x","acos");return je.runKernelFunc((function(e,n){var r=e.acos(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(On(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),Ys=kn({acosh_:function(e){var t=mn(e,"x","acosh");return je.runKernelFunc((function(e,n){var r=e.acosh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(n.toFloat().square().sub(1).sqrt())}}}))}}),Qs=kn({asin_:function(e){var t=mn(e,"x","asin");return je.runKernelFunc((function(e,n){var r=e.asin(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(On(1).sub(n.toFloat().square()).sqrt())}}}))}}),Js=kn({asinh_:function(e){var t=mn(e,"x","asinh");return je.runKernelFunc((function(e,n){var r=e.asinh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.divStrict(On(1).add(n.toFloat().square()).sqrt())}}}))}}),Zs=kn({atan_:function(e){var t=mn(e,"x","atan");return je.runKernelFunc((function(e,n){var r=e.atan(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.toFloat().square().add(1))}}}))}}),ec=kn({atanh_:function(e){var t=mn(e,"x","atanh");return je.runKernelFunc((function(e,n){var r=e.atanh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(On(1).sub(n.toFloat().square()))}}}))}}),tc=kn({ceil_:function(e){var t=mn(e,"x","ceil");return je.runKernelFunc((function(e){return e.ceil(t)}),{$x:t},(function(e){return{$x:function(){return Kn(e)}}}))}}),nc=kn({clipByValue_:function(e,t,n){var r=mn(e,"x","clipByValue");k(t<=n,(function(){return"Error in clip: min ("+t+") must be less than or equal to max ("+n+")."}));var i=[r],o={min:t,max:n};return je.runKernelFunc((function(e,i){var o=e.clip(r,t,n);return i([r]),o}),{x:r},(function(e,r){var i=r[0];return{x:function(){return e.where(i.greaterEqual(t).logicalAnd(i.lessEqual(n)),Kn(e))}}}),"ClipByValue",o,i)}}),rc=kn({cos_:function(e){var t=mn(e,"x","cos"),n=[t];return je.runKernelFunc((function(e,n){var r=e.cos(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return n.toFloat().sin().neg().mul(e)}}}),"Cos",{},n)}}),ic=kn({cosh_:function(e){var t=mn(e,"x","cosh");return je.runKernelFunc((function(e,n){var r=e.cosh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return n.toFloat().sinh().mulStrict(e)}}}))}}),oc=kn({erf_:function(e){var t=mn(e,"x","erf");return k("int32"===t.dtype||"float32"===t.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===t.dtype&&(t=t.toFloat()),je.runKernelFunc((function(e,n){var r=e.erf(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}}))}}),ac=kn({exp_:function(e){var t=mn(e,"x","exp");return je.runKernelFunc((function(e,n){var r=e.exp(t);return n([r]),r}),{x:t},(function(e,t){return{x:function(){return e.mulStrict(t[0])}}}),"Exp",{},[],[!0])}}),sc=kn({expm1_:function(e){var t=mn(e,"x","expm1");return je.runKernelFunc((function(e,n){var r=e.expm1(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.exp())}}}))}}),cc=kn({floor_:function(e){var t=mn(e,"x","floor");return je.runKernelFunc((function(e){return e.floor(t)}),{$x:t},(function(e){return{$x:function(){return Kn(e)}}}))}}),uc=kn({log_:function(e){var t=mn(e,"x","log"),n=[t];return je.runKernelFunc((function(e,n){var r=e.log(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.div(n.toFloat())}}}),"Log",{},n)}}),dc=kn({log1p_:function(e){var t=mn(e,"x","log1p");return je.runKernelFunc((function(e,n){var r=e.log1p(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.add(1))}}}))}}),lc=kn({logSigmoid_:function(e){var t=mn(e,"x","logSigmoid");return je.runKernelFunc((function(e,n){var r=e.softplus(t.neg()).neg();return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.neg().sigmoid())}}}))}}),pc=kn({neg_:function(e){var t=mn(e,"x","neg"),n=[t];return je.runKernelFunc((function(e){return e.neg(t)}),{x:t},(function(e){return{x:function(){return e.neg()}}}),"Neg",{},n)}}),hc=kn({reciprocal_:function(e){var t=mn(e,"x","reciprocal");return je.runKernelFunc((function(e,n){var r=e.reciprocal(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.square().neg())}}}))}}),fc=kn({round_:function(e){var t=mn(e,"x","round");return je.runKernelFunc((function(e){return e.round(t)}),{$x:t},(function(e){return{$x:function(){return Kn(e)}}}))}}),mc=kn({rsqrt_:function(e){var t=mn(e,"x","rsqrt"),n=[t];return je.runKernelFunc((function(e,n){var r=e.rsqrt(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.div(n.pow(1.5).mul(2)).neg()}}}),"Rsqrt",{},n)}}),gc=kn({sigmoid_:function(e){var t=mn(e,"x","sigmoid");return je.runKernelFunc((function(e,n){var r=e.sigmoid(t);return n([r]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mul(n.mul(On(1).sub(n)))}}}),"Sigmoid")}}),vc=kn({sign_:function(e){var t=mn(e,"x","sign");return je.runKernelFunc((function(e){return e.sign(t)}),{$x:t},(function(e){return{$x:function(){return Kn(e)}}}))}}),yc=kn({isNaN_:function(e){var t=mn(e,"x","isNaN");return je.runKernelFunc((function(e){return e.isNaN(t)}),{$x:t},(function(e){return{$x:function(){return Kn(e)}}}))}}),bc=kn({isInf_:function(e){var t=mn(e,"x","isInf");return je.runKernelFunc((function(e){return e.isInf(t)}),{$x:t},(function(e){return{$x:function(){return Kn(e)}}}))}}),wc=kn({isFinite_:function(e){var t=mn(e,"x","isFinite");return je.runKernelFunc((function(e){return e.isFinite(t)}),{$x:t},(function(e){return{$x:function(){return Kn(e)}}}))}}),xc=kn({sin_:function(e){var t=mn(e,"x","sin"),n=[t];return je.runKernelFunc((function(e,n){var r=e.sin(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return n.toFloat().cos().mul(e)}}}),"Sin",{},n)}}),_c=kn({sinh_:function(e){var t=mn(e,"x","sinh");return je.runKernelFunc((function(e,n){var r=e.sinh(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return n.toFloat().cosh().mulStrict(e)}}}))}}),Sc=kn({softplus_:function(e){var t=mn(e,"x","softplus");return je.runKernelFunc((function(e,n){var r=e.softplus(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.mul(n.sigmoid())}}}))}}),Rc=kn({sqrt_:function(e){var t=mn(e,"x","sqrt");return je.runKernelFunc((function(e,n){var r=e.sqrt(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.toFloat().sqrt().mul(2))}}}))}}),Cc=kn({step_:function(e,t){void 0===t&&(t=0);var n=mn(e,"x","step");return je.runKernelFunc((function(e){return e.step(n,t)}),{$x:n},(function(e){return{$x:function(){return Kn(e)}}}))}}),Ec=kn({tan_:function(e){var t=mn(e,"x","tan");return je.runKernelFunc((function(e,n){var r=e.tan(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return e.div(n.cos().square())}}}))}}),kc=kn({tanh_:function(e){var t=mn(e,"x","tanh");return je.runKernelFunc((function(e,n){var r=e.tanh(t);return n([r]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return On(1).sub(n.square()).mulStrict(e)}}}),"Tanh",{},null,[!0])}});function Tc(e,t,n,r,i,o){var a,s,c=mn(e,"x","batchNorm"),u=mn(t,"mean","batchNorm"),d=mn(n,"variance","batchNorm");return null!=i&&(a=mn(i,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),k(2===c.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+c.rank+"."})),k(2===u.rank||1===u.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+u.rank+"."})),k(2===d.rank||1===d.rank,(function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+d.rank+"."})),null!=a&&k(2===a.rank||1===a.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+a.rank+"."})),null!=s&&k(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),Ic(c,u,d,s,a,o)}function Dc(e,t,n,r,i,o){var a,s,c=mn(e,"x","batchNorm"),u=mn(t,"mean","batchNorm"),d=mn(n,"variance","batchNorm");return null!=i&&(a=mn(i,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),k(3===c.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+c.rank+"."})),k(3===u.rank||1===u.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+u.rank+"."})),k(3===d.rank||1===d.rank,(function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+d.rank+"."})),null!=a&&k(3===a.rank||1===a.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+a.rank+"."})),null!=s&&k(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),Ic(c,u,d,s,a,o)}function Pc(e,t,n,r,i,o){var a,s,c=mn(e,"x","batchNorm"),u=mn(t,"mean","batchNorm"),d=mn(n,"variance","batchNorm");return null!=i&&(a=mn(i,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),k(4===c.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+c.rank+"."})),k(4===u.rank||1===u.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+u.rank+"."})),k(4===d.rank||1===d.rank,(function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+d.rank+"."})),null!=a&&k(4===a.rank||1===a.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+a.rank+"."})),null!=s&&k(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),Ic(c,u,d,s,a,o)}function Ic(e,t,n,r,i,o){null==o&&(o=.001);var a,s,c,u=mn(e,"x","batchNorm"),d=mn(t,"mean","batchNorm"),l=mn(n,"variance","batchNorm");null!=i&&(a=mn(i,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),k(d.rank===l.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),k(null==s||d.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),k(null==a||d.rank===a.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."})),c=0===u.rank||1===u.rank?u.as4D(1,1,1,u.size):2===u.rank?u.as4D(1,1,u.shape[0],u.shape[1]):3===u.rank?u.as4D(1,u.shape[0],u.shape[1],u.shape[2]):u;var p=[u,d,l,a];return je.runKernelFunc((function(e,t){var n=e.batchNormalization(c,Mc(d),Mc(l),o,Mc(a),Mc(s));return t([u,d,l,a]),n}),{x:u,mean:d,variance:l,scale:a,offset:s},(function(e,t){var n=t,r=n[0],i=n[1],a=n[2],s=n[3],u=null==s?On(1):s,d=wi(i.shape,c.shape),l=[];if(1===i.rank){for(var p=0;p<c.shape.length-1;++p)l.push(c.shape[p]);l.push(1)}var h=r.sub(i),f=e.mul(u),m=mc(a.add(On(o))),g=m.mul(m).mul(m).mul(On(-.5));return{x:function(){return 1===i.rank?e.mul(Lr(m.as4D(1,1,1,i.shape[0]),l)).mul(u).reshape(r.shape):e.mul(m).mul(u).reshape(r.shape)},mean:function(){var e=m.mul(On(-1)).mul(f);return 1===i.rank&&(e=e.sum(d)),e.reshape(i.shape)},variance:function(){var e=g.mul(h).mul(f);return 1===i.rank&&(e=e.sum(d)),e.reshape(i.shape)},scale:function(){var t=h.mul(m),n=e.mul(t);return 1===i.rank&&(n=n.sum(d)),n.reshape(i.shape)},offset:function(){var t=e;return 1===i.rank&&(t=t.sum(d)),t.reshape(i.shape)}}}),"BatchNormalization",{varianceEpsilon:o},p).reshape(u.shape)}function Mc(e){return null==e?null:0===e.rank?e.as1D():1===e.rank?e:2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}function Oc(){Kt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var Ac=kn({batchNormalization2d_:function(e,t,n,r,i,o){return void 0===r&&(r=.001),Oc(),Tc(e,t,n,o,i,r)}}),Fc=kn({batchNormalization3d_:function(e,t,n,r,i,o){return void 0===r&&(r=.001),Oc(),Dc(e,t,n,o,i,r)}}),Nc=kn({batchNormalization4d_:function(e,t,n,r,i,o){return void 0===r&&(r=.001),Oc(),Pc(e,t,n,o,i,r)}}),Lc=kn({batchNormalization_:function(e,t,n,r,i,o){return void 0===r&&(r=.001),Oc(),Ic(e,t,n,o,i,r)}}),Bc=kn({batchNorm_:Ic}),jc=kn({batchNorm2d_:Tc}),Wc=kn({batchNorm3d_:Dc}),zc=kn({batchNorm4d_:Pc}),Uc=kn({logicalAnd_:function(e,t){var n=mn(e,"a","logicalAnd","bool"),r=mn(t,"b","logicalAnd","bool");return xi(n.shape,r.shape),je.runKernelFunc((function(e){return e.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),Vc=kn({logicalNot_:function(e){var t=mn(e,"x","logicalNot","bool");return je.runKernelFunc((function(e){return e.logicalNot(t)}),{$x:t})}}),Gc=kn({logicalOr_:function(e,t){var n=mn(e,"a","logicalOr","bool"),r=mn(t,"b","logicalOr","bool");return xi(n.shape,r.shape),je.runKernelFunc((function(e){return e.logicalOr(n,r)}),{$a:n,$b:r})}}),qc=kn({logicalXor_:function(e,t){var n=mn(e,"a","logicalXor","bool"),r=mn(t,"b","logicalXor","bool");return xi(n.shape,r.shape),Gc(e,t).logicalAnd(Uc(e,t).logicalNot())}}),Hc=kn({where_:function(e,t,n){var r=mn(t,"a","where"),i=mn(n,"b","where"),o=mn(e,"condition","where","bool");return T(r.shape,i.shape,"Error in where: "),1===o.rank?k(o.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):T(o.shape,i.shape,"Error in where: "),je.runKernelFunc((function(e,t){var n=e.select(o,r,i);return t([o]),n}),{$condition:o,$a:r,$b:i},(function(e,t){var n=t[0];return{$condition:function(){return Kn(n).toFloat()},$a:function(){return e.mul(n.cast(e.dtype))},$b:function(){return e.mul(n.logicalNot().cast(e.dtype))}}}))}}),Kc=function(e){return c(this,void 0,void 0,(function(){var t,n,r;return u(this,(function(i){switch(i.label){case 0:return[4,(t=mn(e,"condition","whereAsync","bool")).data()];case 1:return n=i.sent(),r=Zi(t.shape,n),e!==t&&t.dispose(),[2,r]}}))}))},Xc=kn({add_:function(e,t){var n,r=mn(e,"a","add"),i=mn(t,"b","add");n=Me(r,i),r=n[0],i=n[1];var o=xi(r.shape,i.shape);return je.runKernelFunc((function(e){return e.add(r,i)}),{a:r,b:i},(function(e){return{a:function(){var t=e,n=wi(r.shape,o);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)},b:function(){var t=e,n=wi(i.shape,o);return n.length>0&&(t=t.sum(n)),t.reshape(i.shape)}}}),"Add")}}),$c=kn({addN_:function(e){k(Array.isArray(e),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),k(e.length>=1,(function(){return"Must pass at least one tensor to tf.addN(), but got "+e.length}));var t=e.map((function(e,t){return mn(e,"tensors"+t,"addN")})),n=t[0];t.forEach((function(e){if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((function(e){if(!M(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=t;return je.runKernelFunc((function(e){return e.addN(t)}),r,(function(e){var n={};return t.forEach((function(t,r){n[r]=function(){return e.clone()}})),n}),"AddN")}}),Yc=kn({addStrict_:function(e,t){var n=mn(e,"a","addStrict"),r=mn(t,"b","addStrict");return T(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),Qc=kn({atan2_:function(e,t){var n,r=mn(e,"a","atan2"),i=mn(t,"b","atan2");n=Me(r,i),r=n[0],i=n[1];var o=xi(r.shape,i.shape);return je.runKernelFunc((function(e,t){var n=e.atan2(r,i);return t([r,i]),n}),{$a:r,$b:i},(function(e,t){var n=t[0],r=t[1];return{$a:function(){var t=Xc(n.square(),r.square()),i=e.mul(r.div(t)),a=wi(n.shape,o);return a.length>0&&(i=i.sum(a)),i.reshape(n.shape)},$b:function(){var t=Xc(n.square(),r.square()),i=pc(e.mul(n.div(t))),a=wi(r.shape,o);return a.length>0&&(i=i.sum(a)),i.reshape(r.shape)}}}))}}),Jc=kn({div_:function(e,t){var n,r=mn(e,"a","div"),i=mn(t,"b","div");if(n=Me(r,i),r=n[0],i=n[1],"int32"===r.dtype&&"int32"===i.dtype)return tu(r,i);var o=xi(r.shape,i.shape);return je.runKernelFunc((function(e,t){var n=e.realDivide(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.div(r.toFloat()),i=wi(n.shape,o);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=wi(r.shape,o);i.length>0&&(t=t.sum(i).reshape(r.shape));var a=r.square();return t.div(a.toFloat()).neg()}}}),"Div")}}),Zc=kn({divNoNan_:function(e,t){var n,r=mn(e,"a","div"),i=mn(t,"b","div");r=(n=Me(r,i))[0],i=n[1];var o=Jc(r,i),a=Kn(o),s=i.equal(a);return Hc(s,a,o)}}),eu=kn({divStrict_:function(e,t){var n=mn(e,"a","div"),r=mn(t,"b","div");return T(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),tu=kn({floorDiv_:function(e,t){var n,r=mn(e,"a","floorDiv"),i=mn(t,"b","floorDiv");n=Me(r,i),r=n[0],i=n[1];var o=xi(r.shape,i.shape);return je.runKernelFunc((function(e,t){var n=e.floorDiv(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.div(r.toFloat()),i=wi(n.shape,o);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=wi(r.shape,o);i.length>0&&(t=t.sum(i).reshape(r.shape));var a=r.square();return t.div(a.toFloat()).neg()}}}),"FloorDiv")}}),nu=kn({maximum_:function(e,t){var n,r=mn(e,"a","maximum"),i=mn(t,"b","maximum");return n=Me(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),xi(r.shape,i.shape),je.runKernelFunc((function(e,t){var n=e.maximum(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return e.mul(n.greaterEqual(r).toFloat())},b:function(){return e.mul(n.less(r).toFloat())}}}),"Maximum")}}),ru=kn({maximumStrict_:function(e,t){var n=mn(e,"a","maximumStrict"),r=mn(t,"b","maximumStrict");return T(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),iu=kn({minimum_:function(e,t){var n,r=mn(e,"a","minimum"),i=mn(t,"b","minimum");return n=Me(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),xi(r.shape,i.shape),je.runKernelFunc((function(e,t){var n=e.minimum(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return e.mul(n.lessEqual(r).toFloat())},b:function(){return e.mul(n.greater(r).toFloat())}}}),"Minimum")}}),ou=kn({minimumStrict_:function(e,t){var n=mn(e,"a","minimumStrict"),r=mn(t,"b","minimumStrict");return T(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),au=kn({mod_:function(e,t){var n,r=mn(e,"a","mod"),i=mn(t,"b","mod");n=Me(r,i),r=n[0],i=n[1];var o=xi(r.shape,i.shape);return je.runKernelFunc((function(e,t){var n=e.mod(r,i);return t([r,i]),n}),{$a:r,$b:i},(function(e,t){var n=t[0],r=t[1];return{$a:function(){var t=wi(n.shape,o);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(r).floor().neg()),i=wi(r.shape,o);return i.length>0?t.sum(i).reshape(r.shape):t}}}))}}),su=kn({modStrict_:function(e,t){var n=mn(e,"a","modStrict"),r=mn(t,"b","modStrict");return T(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),cu=kn({mul_:function(e,t){var n,r=mn(e,"a","mul"),i=mn(t,"b","mul");n=Me(r,i),r=n[0],i=n[1];var o=xi(r.shape,i.shape);return je.runKernelFunc((function(e,t){var n=e.multiply(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){var t=e.mul(r.toFloat()),i=wi(n.shape,o);return i.length>0?t.sum(i).reshape(n.shape):t},b:function(){var t=e.mul(n.toFloat()),i=wi(r.shape,o);return i.length>0?t.sum(i).reshape(r.shape):t}}}),"Mul")}}),uu=kn({mulStrict_:function(e,t){var n=mn(e,"a","mul"),r=mn(t,"b","mul");return T(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),du=kn({pow_:function(e,t){var n,r=mn(e,"base","pow"),i=mn(t,"exp","pow");n=Me(r,i),r=n[0],i=n[1];var o=xi(r.shape,i.shape),a=[r,i];return je.runKernelFunc((function(e,t){var n=e.pow(r,i);return t([r,i,n]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1],i=t[2];return{a:function(){var t=r.toFloat(),i=e.mul(t.mul(n.pow(t.sub(On(1))))),a=wi(n.shape,o);return a.length>0&&(i=i.sum(a)),i.reshape(n.shape)},b:function(){var t=n.greater(0),a=n.log().where(t,Kn(n)),s=e.mul(i.mul(a)),c=wi(r.shape,o);return c.length>0&&(s=s.sum(c)),s.reshape(r.shape)}}}),"Pow",{},a,[!0])}}),lu=kn({powStrict_:function(e,t){return T(e.shape,t.shape,"Error in powStrict: "),e.pow(t)}}),pu=kn({squaredDifferenceStrict_:function(e,t){var n=mn(e,"a","squaredDifferenceStrict"),r=mn(t,"b","squaredDifferenceStrict");return T(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),hu=kn({sub_:function(e,t){var n,r=mn(e,"a","sub"),i=mn(t,"b","sub");n=Me(r,i),r=n[0],i=n[1];var o=xi(r.shape,i.shape);return je.runKernelFunc((function(e){return e.subtract(r,i)}),{a:r,b:i},(function(e){return{a:function(){var t=e,n=wi(r.shape,o);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)},b:function(){var t=e,n=wi(i.shape,o);return n.length>0&&(t=t.sum(n)),t.neg().reshape(i.shape)}}}),"Sub")}}),fu=kn({subStrict_:function(e,t){var n=mn(e,"a","subStrict"),r=mn(t,"b","subStrict");return T(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),mu=kn({equal_:function(e,t){var n,r=mn(e,"a","equal"),i=mn(t,"b","equal");return n=Me(r,i),r=n[0],i=n[1],xi(r.shape,i.shape),je.runKernelFunc((function(e){return e.equal(r,i)}),{$a:r,$b:i})}}),gu=kn({equalStrict_:function(e,t){var n=mn(e,"a","equalStrict"),r=mn(t,"b","equalStrict");return T(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),vu=kn({greater_:function(e,t){var n,r=mn(e,"a","greater"),i=mn(t,"b","greater");return n=Me(r,i),r=n[0],i=n[1],xi(r.shape,i.shape),je.runKernelFunc((function(e){return e.greater(r,i)}),{a:r,b:i},null,"Greater")}}),yu=kn({greaterEqual_:function(e,t){var n,r=mn(e,"a","greaterEqual"),i=mn(t,"b","greaterEqual");return n=Me(r,i),r=n[0],i=n[1],xi(r.shape,i.shape),je.runKernelFunc((function(e,t){var n=e.greaterEqual(r,i);return t([r,i]),n}),{a:r,b:i},(function(e,t){var n=t[0],r=t[1];return{a:function(){return Kn(n)},b:function(){return Kn(r)}}}),"GreaterEqual")}}),bu=kn({greaterEqualStrict_:function(e,t){var n=mn(e,"a","greaterEqualStrict"),r=mn(t,"b","greaterEqualStrict");return T(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),wu=kn({greaterStrict_:function(e,t){var n=mn(e,"a","greaterStrict"),r=mn(t,"b","greaterStrict");return T(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),xu=kn({less_:function(e,t){var n,r=mn(e,"a","less"),i=mn(t,"b","less");return n=Me(r,i),r=n[0],i=n[1],xi(r.shape,i.shape),je.runKernelFunc((function(e){return e.less(r,i)}),{a:r,b:i},null,"Less")}}),_u=kn({lessEqual_:function(e,t){var n,r=mn(e,"a","lessEqual"),i=mn(t,"b","lessEqual");return n=Me(r,i),r=n[0],i=n[1],xi(r.shape,i.shape),je.runKernelFunc((function(e,t){var n=e.lessEqual(r,i);return t([r,i]),n}),{a:r,b:i},null,"LessEqual")}}),Su=kn({lessEqualStrict_:function(e,t){var n=mn(e,"a","lessEqualStrict"),r=mn(t,"b","lessEqualStrict");return T(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),Ru=kn({lessStrict_:function(e,t){var n=mn(e,"a","lessStrict"),r=mn(t,"b","lessStrict");return T(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Cu=kn({notEqual_:function(e,t){var n,r=mn(e,"a","notEqual"),i=mn(t,"b","notEqual");return n=Me(r,i),r=n[0],i=n[1],xi(r.shape,i.shape),je.runKernelFunc((function(e){return e.notEqual(r,i)}),{a:r,b:i},null,"NotEqual")}}),Eu=kn({notEqualStrict_:function(e,t){var n=mn(e,"a","notEqualStrict"),r=mn(t,"b","notEqualStrict");return T(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function ku(e,t){for(var n=[],r=e;r<t;++r)n.push(r);return n}function Tu(e){for(var t=[],n=0;n<e.length;++n)for(var r=0;r<e[n].length;++r)t.push(e[n][r]);return t}var Du=kn({gather_:function(e,t,n){void 0===n&&(n=0);var r=mn(e,"x","gather"),i=mn(t,"indices","gather","int32");n=j(n,r.shape)[0];var o=function(e,t,n){for(var r=e.shape[n],i=[],o=1,a=1,s=0;s<n;s++)i.push(e.shape[s]),o*=e.shape[s];for(s=0;s<t.rank;s++)i.push(t.shape[s]);for(s=n+1;s<e.rank;s++)i.push(e.shape[s]),a*=e.shape[s];return{batchSize:o,sliceSize:a,dimSize:r,outputShape:i}}(r,i,n);return je.runKernelFunc((function(e,t){var o=e.gather(r,i.flatten(),n);return t([i]),o}),{x:r,indices:i},(function(e,t){var i=t[0];return{x:function(){var t=r.shape,o=i.size,a=t.slice(0,n),s=a.length,c=t.slice(n,t.length).slice(1),u=c.length,d=ku(0,s),l=ku(s+1,s+1+u),p=Tu([a,[o],c]),h=e.reshape(p),f=i.reshape([o]),m=Tu([[s],d,l]),g=h.transpose(m),v=Pu(g,f,r.shape[n]),y=Sn(m);return v.transpose(y)},indices:function(){return i}}}),"Gather",{axis:n}).reshape(o.outputShape)}}),Pu=kn({unsortedSegmentSum_:function(e,t,n){var r=mn(e,"x","unsortedSegmentSum"),i=mn(t,"segmentIds","unsortedSegmentSum","int32");return k(O(n),(function(){return"numSegments must be of dtype int"})),je.runKernelFunc((function(e,t){var o=e.unsortedSegmentSum(r,i,n);return t([i]),o}),{$x:r},(function(e,t){var n=t[0];return{$x:function(){return function(e,t){for(var n=nu(t,Kn(t)),r=Du(e,n),i=yu(t,On(0,"int32")),o=r.rank-i.rank,a=0;a<o;++a)i=wr(i,a+1);i=Uc(i,zn(r.shape,"bool"));var s=Kn(r);return Hc(i,r,s)}(e,n)}}}))}}),Iu=function(e,t,n){return c(this,void 0,void 0,(function(){var r,i,o,a,s,c,d,l,p,h,f,m,g;return u(this,(function(u){switch(u.label){case 0:for(r=mn(e,"tensor","boolMask"),i=mn(t,"mask","boolMask","bool"),o=null==n?0:n,a=i.rank,s=r.shape,k(a>0,(function(){return"mask cannot be scalar"})),T(s.slice(o,o+a),i.shape,"mask's shape must match the first K dimensions of tensor's shape,"),c=1,d=o;d<o+a;d++)c*=s[d];return l=s.slice(0,o).concat([c],s.slice(o+a)),p=r.reshape(l),h=i.reshape([-1]),[4,Kc(h)];case 1:return f=u.sent(),m=f.squeeze([1]),g=Du(p,m,o),e!==r&&r.dispose(),t!==i&&i.dispose(),m.dispose(),p.dispose(),h.dispose(),f.dispose(),[2,g]}}))}))};function Mu(e,t,n,r,i,o,a){void 0===o&&(o="NHWC"),k(e.length===t.rank,(function(){return"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match"}));var s=e,c=t,u=!1;3===t.rank&&(u=!0,c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),s=[1,e[0],e[1],e[2]]),k(4===s.length,(function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."})),k(4===c.rank,(function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+c.rank})),k(4===n.rank,(function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}));var d="NHWC"===o?s[3]:s[1],l="NHWC"===o?c.shape[3]:c.shape[1];k(d===n.shape[2],(function(){return"Error in conv2dDerInput: depth of input ("+d+") must match input depth for filter "+n.shape[2]+"."})),k(l===n.shape[3],(function(){return"Error in conv2dDerInput: depth of output ("+l+") must match output depth for filter "+n.shape[3]+"."})),null!=a&&k(O(i),(function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."}));var p=Oi(o),h=Ri(s,n.shape,r,1,i,a,!1,p),f=je.runKernelFunc((function(e,t){var r=e.conv2dDerInput(c,n,h);return t([n,c]),r}),{dy4D:c,filter:n},(function(e,t){var n=t[0],s=t[1];return{dy4D:function(){return Nu(e,n,r,i,o,1,a)},filter:function(){return Bu(e,s,n.shape,r,i,o,a)}}}));return u?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}function Ou(e){var t=function(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}(e),n=t[0],r=t[1],i=t[2];return 1===n&&1===r&&1===i}function Au(e,t,n,r,i){k(e.length===t.rank,(function(){return"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match"}));var o=e,a=t,s=!1;4===t.rank&&(s=!0,a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]),o=[1,e[0],e[1],e[2],e[3]]);var c=o[4],u=a.shape[4];k(5===o.length,(function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+o.length+"."})),k(5===a.rank,(function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+a.rank})),k(5===n.rank,(function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank})),k(c===n.shape[3],(function(){return"Error in conv3dDerInput: depth of input ("+c+") must match input depth for filter "+n.shape[3]+"."})),k(u===n.shape[4],(function(){return"Error in conv3dDerInput: depth of output ("+u+") must match output depth for filter "+n.shape[4]+"."}));var d=Ci(o,n.shape,r,1,i),l=je.runKernelFunc((function(e){return e.conv3dDerInput(a,n,d)}),{dy5D:a});return s?l.as4D(l.shape[1],l.shape[2],l.shape[3],l.shape[4]):l}var Fu=kn({conv1d_:function(e,t,n,r,i,o,a){void 0===i&&(i="NWC"),void 0===o&&(o=1);var s=mn(e,"x","conv1d"),c=mn(t,"filter","conv1d"),u=s,d=!1;2===s.rank&&(d=!0,u=s.as3D(1,s.shape[0],s.shape[1])),k(3===u.rank,(function(){return"Error in conv1d: input must be rank 3, but got rank "+u.rank+"."})),k(3===c.rank,(function(){return"Error in conv1d: filter must be rank 3, but got rank "+c.rank+"."})),null!=a&&k(O(r),(function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."})),k(u.shape[2]===c.shape[1],(function(){return"Error in conv1d: depth of input ("+u.shape[2]+") must match input depth for filter "+c.shape[1]+"."})),k(Mi(n,o),(function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+o+"'"})),k("NWC"===i,(function(){return"Error in conv1d: got dataFormat of "+i+" but only NWC is currently supported."}));var l=c.as4D(1,c.shape[0],c.shape[1],c.shape[2]),p=u.as4D(u.shape[0],1,u.shape[1],u.shape[2]),h=Nu(p,l,[1,n],r,"NHWC",[1,o],a);return d?h.as2D(h.shape[2],h.shape[3]):h.as3D(h.shape[0],h.shape[2],h.shape[3])}}),Nu=kn({conv2d_:function(e,t,n,r,i,o,a){void 0===i&&(i="NHWC"),void 0===o&&(o=[1,1]);var s=mn(e,"x","conv2d"),c=mn(t,"filter","conv2d"),u=s,d=!1;3===s.rank&&(d=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),k(4===u.rank,(function(){return"Error in conv2d: input must be rank 4, but got rank "+u.rank+"."})),k(4===c.rank,(function(){return"Error in conv2d: filter must be rank 4, but got rank "+c.rank+"."})),null!=a&&k(O(r),(function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var l="NHWC"===i?u.shape[3]:u.shape[1];k(l===c.shape[2],(function(){return"Error in conv2d: depth of input ("+l+") must match input depth for filter "+c.shape[2]+"."})),k(Mi(n,o),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}));var p=Oi(i),h=Ri(u.shape,c.shape,n,o,r,a,!1,p),f=[c,u],m=je.runKernelFunc((function(e,t){var n=e.conv2d(u,c,h);return t([c,u]),n}),{x:u,filter:c},(function(e,t){var a=t,s=a[0],c=a[1];return k(Ii(o),(function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"})),{x:function(){return ju(c.shape,e,s,n,r,i)},filter:function(){return Bu(c,e,s.shape,n,r,i)}}}),"Conv2D",h,f);return d?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Lu=kn({conv3d_:function(e,t,n,r,i,o){void 0===i&&(i="NDHWC"),void 0===o&&(o=[1,1,1]);var a=mn(e,"x","conv3d"),s=mn(t,"filter","conv3d"),c=a,u=!1;4===a.rank&&(u=!0,c=a.as5D(1,a.shape[0],a.shape[1],a.shape[2],a.shape[3])),k(5===c.rank,(function(){return"Error in conv3d: input must be rank 5, but got rank "+c.rank+"."})),k(5===s.rank,(function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."})),k(c.shape[4]===s.shape[3],(function(){return"Error in conv3d: depth of input ("+c.shape[4]+") must match input depth for filter "+s.shape[3]+"."})),k(function(e,t){return Ou(e)||Ou(t)}(n,o),(function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),k("NDHWC"===i,(function(){return"Error in conv3d: got dataFormat of "+i+" but only NDHWC is currently supported."}));var d=Ci(c.shape,s.shape,n,o,r),l=je.runKernelFunc((function(e,t){var n=e.conv3d(c,s,d);return t([c,s]),n}),{x:c,$filter:s},(function(e,t){k(Ou(o),(function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"}));var i=t[0],a=t[1];return{x:function(){return Au(i.shape,e,a,n,r)},$filter:function(){return function(e,t,n,r,i){var o=e;4===e.rank&&(o=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]));var a=t;4===a.rank&&(a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3])),k(5===o.rank,(function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+o.shape+"."})),k(5===a.rank,(function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+a.shape+"."})),k(5===n.length,(function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."})),k(o.shape[4]===n[3],(function(){return"Error in conv3dDerFilter: depth of input "+o.shape[4]+") must match input depth in filter ("+n[3]+"."})),k(a.shape[4]===n[4],(function(){return"Error in conv3dDerFilter: depth of dy ("+a.shape[4]+") must match output depth for filter ("+n[4]+")."}));var s=Ci(o.shape,n,r,1,i);return je.runKernelFunc((function(e){return e.conv3dDerFilter(o,a,s)}),{x5D:o,dy5D:a})}(i,e,a.shape,n,r)}}}));return u?l.as4D(l.shape[1],l.shape[2],l.shape[3],l.shape[4]):l}}),Bu=kn({conv2dDerFilter_:function(e,t,n,r,i,o,a){void 0===o&&(o="NHWC");var s=e;3===e.rank&&(s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var c=t;3===c.rank&&(c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),k(4===s.rank,(function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."})),k(4===c.rank,(function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+c.shape+"."})),k(4===n.length,(function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}));var u="NHWC"===o?s.shape[3]:s.shape[1],d="NHWC"===o?c.shape[3]:c.shape[1];k(u===n[2],(function(){return"Error in conv2dDerFilter: depth of input "+u+") must match input depth in filter ("+n[2]+"."})),k(d===n[3],(function(){return"Error in conv2dDerFilter: depth of dy ("+d+") must match output depth for filter ("+n[3]+")."})),null!=a&&k(O(i),(function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."}));var l=Oi(o),p=Ri(s.shape,n,r,1,i,a,!1,l);return je.runKernelFunc((function(e){return e.conv2dDerFilter(s,c,p)}),{x4D:s,dy4D:c})}}),ju=kn({conv2dDerInput_:Mu}),Wu=kn({depthwiseConv2d_:function(e,t,n,r,i,o,a){void 0===i&&(i="NHWC"),void 0===o&&(o=[1,1]);var s=mn(e,"x","depthwiseConv2d"),c=mn(t,"filter","depthwiseConv2d"),u=s,d=!1;3===s.rank&&(d=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),k(4===u.rank,(function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+u.rank+"."})),k(4===c.rank,(function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+c.rank+"."})),k(u.shape[3]===c.shape[2],(function(){return"Error in depthwiseConv2d: number of input channels ("+u.shape[3]+") must match the inChannels dimension in filter "+c.shape[2]+"."})),null==o&&(o=[1,1]),k(Mi(n,o),(function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),null!=a&&k(O(r),(function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var l=Ri(u.shape,c.shape,n,o,r,a,!0),p=[u,c],h=je.runKernelFunc((function(e,t){var n=e.depthwiseConv2D(u,c,l);return t([u,c]),n}),{x:u,filter:c},(function(e,t){k(Ii(o),(function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"}));var n=t[0],r=t[1];return{x:function(){return zu(n.shape,e,r,l)},filter:function(){return Uu(n,e,r.shape,l)}}}),"DepthwiseConv2dNative",l,p);return d?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),zu=kn({depthwiseConv2dDerInput_:function(e,t,n,r){var i=t,o=!1;3===t.rank&&(o=!0,i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var a=je.runKernelFunc((function(e){return e.depthwiseConv2DDerInput(i,n,r)}),{dy4D:i});return o?a.as3D(a.shape[1],a.shape[2],a.shape[3]):a}}),Uu=kn({depthwiseConv2dDerFilter_:function(e,t,n,r){var i=e;3===e.rank&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var o=t;return 3===o.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),je.runKernelFunc((function(e){return e.depthwiseConv2DDerFilter(i,o,r)}),{x4D:i,dy4D:o})}}),Vu=kn({separableConv2d_:function(e,t,n,r,i,o,a){void 0===o&&(o=[1,1]),void 0===a&&(a="NHWC");var s=mn(e,"x","separableConv2d"),c=mn(t,"depthwiseFilter","separableConv2d"),u=mn(n,"pointwiseFilter","separableConv2d"),d=s,l=!1;if(3===s.rank&&(l=!0,d=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===a)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");k(4===d.rank,(function(){return"Error in separableConv2d: input must be rank 4, but got rank "+d.rank+"."})),k(4===c.rank,(function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+c.rank+"."})),k(4===u.rank,(function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+c.rank+"."})),k(1===u.shape[0],(function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+u.shape[0]+"."})),k(1===u.shape[1],(function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+u.shape[1]+"."}));var p=c.shape[2],h=c.shape[3];k(u.shape[2]===p*h,(function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+p*h+", but got "+u.shape[2]+"."}));var f=Wu(d,c,r,i,a,o),m=Nu(f,u,1,"valid",a);return l?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Gu=kn({conv2dTranspose_:function(e,t,n,r,i,o){return Mu(n,mn(e,"x","conv2dTranspose"),mn(t,"filter","conv2dTranspose"),r,i,"NHWC",o)}}),qu=kn({conv3dTranspose_:function(e,t,n,r,i){return Au(n,mn(e,"x","conv3dTranspose"),mn(t,"filter","conv3dTranspose"),r,i)}}),Hu=kn({matMul_:function(e,t,n,r){var i;void 0===n&&(n=!1),void 0===r&&(r=!1);var o=mn(e,"a","matMul"),a=mn(t,"b","matMul");i=Me(o,a),o=i[0],a=i[1];var s=n?o.shape[o.rank-2]:o.shape[o.rank-1],c=r?a.shape[a.rank-1]:a.shape[a.rank-2],u=n?o.shape[o.rank-1]:o.shape[o.rank-2],d=r?a.shape[a.rank-2]:a.shape[a.rank-1],l=o.shape.slice(0,-2),p=a.shape.slice(0,-2),h=I(l),f=I(p);k(o.rank>=2&&a.rank>=2&&o.rank===a.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+a.rank+"."})),k(M(l,p),(function(){return"Error in matMul: outer dimensions ("+l+") and ("+p+") of Tensors with shapes "+o.shape+" and "+a.shape+" must match."})),k(s===c,(function(){return"Error in matMul: inner shapes ("+s+") and ("+c+") of Tensors with shapes "+o.shape+" and "+a.shape+" and transposeA="+n+" and transposeB="+r+" must match."}));var m=o.shape.slice(0,-2).concat([u,d]),g=n?o.as3D(h,s,u):o.as3D(h,u,s),v=r?a.as3D(f,d,c):a.as3D(f,c,d),y={transposeA:n,transposeB:r};return je.runKernelFunc((function(e,t){var i=e.batchMatMul(g,v,n,r);return t([g,v]),i}),{a:g,b:v},(function(e,t){var i=t,o=i[0],a=i[1];return n||r?!n&&r?{a:function(){return e.matMul(a,!1,!1)},b:function(){return e.matMul(o,!0,!1)}}:n&&!r?{a:function(){return a.matMul(e,!1,!0)},b:function(){return o.matMul(e,!1,!1)}}:{a:function(){return a.matMul(e,!0,!0)},b:function(){return e.matMul(o,!0,!0)}}:{a:function(){return e.matMul(a,!1,!0)},b:function(){return o.matMul(e,!0,!1)}}}),"BatchMatMul",y).reshape(m)}}),Ku=kn({dot_:function(e,t){var n=mn(e,"t1","dot"),r=mn(t,"t2","dot");k(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."}));var i=1===n.rank?n.size:n.shape[1],o=1===r.rank?r.size:r.shape[0];return k(i===o,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+i+" and "+o+"."})),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),Xu=kn({outerProduct_:function(e,t){var n=mn(e,"v1","outerProduct"),r=mn(t,"v2","outerProduct");return k(1===n.rank&&1===r.rank,(function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."})),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),$u=kn({reverse_:function(e,t){var n=mn(e,"x","reverse");if(0===n.rank)return n.clone();var r=j(t,n.shape);return je.runKernelFunc((function(e){return e.reverse(n,r)}),{$x:n},(function(e){return{$x:function(){return e.reverse(r)}}})).reshapeAs(n)}}),Yu=kn({reverse1d_:function(e){var t=mn(e,"x","reverse");return k(1===t.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+t.rank+"."})),$u(t,0)}}),Qu=kn({reverse2d_:function(e,t){var n=mn(e,"x","reverse");return k(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),$u(n,t)}}),Ju=kn({reverse3d_:function(e,t){var n=mn(e,"x","reverse");return k(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),$u(n,t)}}),Zu=kn({reverse4d_:function(e,t){var n=mn(e,"x","reverse");return k(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),$u(n,t)}});function ed(e,t,n,r,i,o){var a=mn(e,"x","maxPool"),s=a,c=!1;3===a.rank&&(c=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==r&&(r=[1,1]),k(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),k(Mi(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=o&&k(O(i),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."}));var u=_i(s.shape,t,n,r,i,o);if(1===u.filterWidth&&1===u.filterHeight&&M(u.inShape,u.outShape))return a.clone();var d=[s],l=je.runKernelFunc((function(e,t){var n=e.maxPool(s,u);return t([s,n]),n}),{x:s},(function(e,o){var a=o[0],s=o[1];return{x:function(){return function(e,t,n,r,i,o,a,s){var c=mn(e,"dy","maxPoolBackprop"),u=mn(t,"input","maxPoolBackprop"),d=mn(n,"output","maxPoolBackprop");k(u.rank===c.rank,(function(){return"Rank of input ("+u.rank+") does not match rank of dy ("+c.rank+")"})),null==o&&(o=[1,1]),k(Mi(i,o),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"})),k(4===c.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."})),k(4===u.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var l=_i(u.shape,r,i,o,a,void 0);return je.runKernelFunc((function(e){return e.maxPoolBackprop(c,u,d,l)}),{$dy:c,$input:u})}(e,a,s,t,n,r,i)}}}),"MaxPool",u,d);return c?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function td(e,t,n,r,i,o){var a=mn(e,"x","avgPool","float32");null==r&&(r=[1,1]),k(Mi(n,r),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}));var s=a,c=!1;3===a.rank&&(c=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),k(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=o&&k(O(i),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."}));var u=_i(s.shape,t,n,r,i,o);if(1===u.filterWidth&&1===u.filterHeight&&M(u.inShape,u.outShape))return a.clone();var d=je.runKernelFunc((function(e){return e.avgPool(s,u)}),{x:s},(function(e){return{x:function(){return function(e,t,n,r,i,o){var a=mn(e,"dy","avgPoolBackprop"),s=mn(t,"input","avgPoolBackprop");k(s.rank===a.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"})),null==i&&(i=[1,1]),k(Mi(r,i),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"}));var c=s,u=a,d=!1;3===s.rank&&(d=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),u=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),k(4===u.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),k(4===c.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+c.rank+"."}));var l=_i(c.shape,n,r,i,o),p=je.runKernelFunc((function(e){return e.avgPoolBackprop(u,c,l)}),{dy4D:u,input4D:c});return d?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}(e,s,t,n,r,i)}}}),"AvgPool",u);return d=d.cast(a.dtype),c?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}var nd=kn({maxPool_:function(e,t,n,r,i){return ed(e,t,n,1,r,i)}}),rd=kn({avgPool_:function(e,t,n,r,i){return td(e,t,n,1,r,i)}}),id=kn({pool_:function(e,t,n,r,i,o){null==i&&(i=[1,1]),null==o&&(o=1),0===r&&(r="valid");var a=mn(e,"x","maxPool"),s=a,c=!1;3===a.rank&&(c=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),k(Mi(o,i),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+i+"'"}));var u,d=_i(s.shape,t,o,i,r),l=[d.dilationHeight,d.dilationWidth];u="same"===r?function(e,t){var n=e.map((function(e,n){return e+(e-1)*(t[n]-1)})).map((function(e){return e-1})),r=n.map((function(e){return Math.floor(e/2)})),i=n.map((function(e,t){return e-r[t]}));return n.map((function(e,t){return[r[t],i[t]]}))}([d.filterHeight,d.filterWidth],l):[[0,0],[0,0]];var p=1===l[0]&&1===l[1],h=function(e,t,n){var r=n.map((function(e){return e[0]})),i=n.map((function(e){return e[1]})),o=e.concat(r,i),a=t.map((function(e,t){return(e-o[t]%e)%e})),s=i.map((function(e,t){return e+a[t]}));return[t.map((function(e,t){return[r[t],s[t]]})),t.map((function(e,t){return[0,a[t]]}))]}([d.inHeight,d.inWidth],l,u),f=h[0],m=h[1],g=p?r:"valid",v=p?s:Ar(s,l,f),y=("avg"===n?function(){return td(v,t,o,1,g)}:function(){return ed(v,t,o,1,g)})(),b=p?y:fr(y,l,m);return c?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),od=kn({maxPool3d_:function(e,t,n,r,i,o,a){void 0===o&&(o="NDHWC");var s=mn(e,"x","maxPool3d"),c=s,u=!1;4===s.rank&&(u=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==a&&(a=[1,1,1]),k(5===c.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+c.rank+"."})),k("NDHWC"===o,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+o})),k(Mi(n,a),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),null!=i&&k(O(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var d=Si(c.shape,t,n,a,r,i,o),l=je.runKernelFunc((function(e,t){var n=e.maxPool3d(c,d);return t([c,n]),n}),{x:c},(function(e,o){var s=o[0],c=o[1];return{x:function(){return function(e,t,n,r,i,o,a,s){var c=mn(e,"dy","maxPool3dBackprop"),u=mn(t,"input","maxPool3dBackprop"),d=mn(n,"output","maxPool3dBackprop"),l=c,p=u,h=d,f=!1;4===u.rank&&(f=!0,l=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),h=d.as5D(1,d.shape[0],d.shape[1],d.shape[2],d.shape[3])),k(5===l.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."})),k(5===p.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+p.rank+"."})),k(5===h.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+h.rank+"."})),null==o&&(o=[1,1,1]),k(Mi(i,o),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"})),null!=s&&k(O(a),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+"."}));var m=Si(p.shape,r,i,o,a,s),g=je.runKernelFunc((function(e){return e.maxPool3dBackprop(l,p,h,m)}),{dy5D:l,input5D:p});return f?g.as4D(g.shape[1],g.shape[2],g.shape[3],g.shape[4]):g}(e,s,c,t,n,a,r,i)}}}));return u?l.as4D(l.shape[1],l.shape[2],l.shape[3],l.shape[4]):l}}),ad=kn({avgPool3d_:function(e,t,n,r,i,o,a){void 0===o&&(o="NDHWC");var s=mn(e,"x","avgPool3d","float32"),c=s,u=!1;4===s.rank&&(u=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==a&&(a=[1,1,1]),k(5===c.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+c.rank+"."})),k("NDHWC"===o,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+o})),k(Mi(n,a),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),null!=i&&k(O(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var d=Si(c.shape,t,n,a,r,i,o),l=je.runKernelFunc((function(e){return e.avgPool3d(c,d)}),{x:c},(function(e){return{x:function(){return function(e,t,n,r,i,o,a){var s=mn(e,"dy","avgPool3dBackprop"),c=mn(t,"input","avgPool3dBackprop"),u=s,d=c,l=!1;4===c.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),k(5===u.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+u.rank+"."})),k(5===d.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+d.rank+"."})),null==i&&(i=[1,1,1]),k(Mi(r,i),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"})),null!=a&&k(O(o),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var p=Si(d.shape,n,r,i,o,a),h=je.runKernelFunc((function(e){return e.avgPool3dBackprop(u,d,p)}),{dy5D:u,input5D:d});return l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}(e,c,t,n,a,r,i)}}}));return l=l.cast(c.dtype),u?l.as4D(l.shape[1],l.shape[2],l.shape[3],l.shape[4]):l}}),sd=kn({slice_:function(e,t,n){var r,i,o=mn(e,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof t?[t].concat(new Array(o.rank-1).fill(0)):t.length<o.rank?t.concat(new Array(o.rank-t.length).fill(0)):t.slice()).forEach((function(e){k(-1!==e,(function(){return"slice() does not support negative begin indexing."}))})),i=(i=null==n?new Array(o.rank).fill(-1):"number"==typeof n?[n].concat(new Array(o.rank-1).fill(-1)):n.length<o.rank?n.concat(new Array(o.rank-n.length).fill(-1)):n).map((function(e,t){return e>=0?e:(k(-1===e,(function(){return"Negative size values should be exactly -1 but got "+e+" for the slice() size at index "+t+"."})),o.shape[t]-r[t])})),Zr(o,r,i);var a=o.shape,s={begin:r,size:i};return je.runKernelFunc((function(e){return e.slice(o,r,i)}),{x:o},(function(e){for(var t=[],n=0;n<e.rank;n++)t.push([r[n],a[n]-r[n]-i[n]]);return{x:function(){return e.pad(t)}}}),"Slice",s)}}),cd=kn({slice1d_:function(e,t,n){var r=mn(e,"x","slice1d");return k(1===r.rank,(function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"})),sd(r,[t],[n])}}),ud=kn({slice2d_:function(e,t,n){var r=mn(e,"x","slice2d");return k(2===r.rank,(function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"})),sd(r,t,n)}}),dd=kn({slice3d_:function(e,t,n){var r=mn(e,"x","slice3d");return k(3===r.rank,(function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"})),sd(r,t,n)}}),ld=kn({slice4d_:function(e,t,n){var r=mn(e,"x","slice4d");return k(4===r.rank,(function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"})),sd(r,t,n)}});function pd(e,t,n,r,i){return t.rank<n.rank&&(t=t.reshape(wn(t.shape,r))),e.rank<n.rank&&(e=e.reshape(wn(e.shape,r))),{x:function(){var r=e.mul(n.equal(t).cast(e.dtype));return null==i?r:r.transpose(i)}}}var hd=kn({all_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","all","bool"),i=j(t,r.shape),o=i,a=_n(o,r.rank);null!=a&&(r=r.transpose(a),o=Rn(o.length,r.rank));var s=je.runKernelFunc((function(e){return e.all(r,o)}),{$x:r});if(n){var c=wn(s.shape,i);return s.reshape(c)}return s}}),fd=kn({any_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","any","bool"),i=j(t,r.shape),o=i,a=_n(o,r.rank);null!=a&&(r=r.transpose(a),o=Rn(o.length,r.rank));var s=je.runKernelFunc((function(e){return e.any(r,o)}),{$x:r});if(n){var c=wn(s.shape,i);return s.reshape(c)}return s}}),md=kn({argMax_:function(e,t){void 0===t&&(t=0);var n=mn(e,"x","argMax");null==t&&(t=0);var r=j(t,n.shape),i=_n(r,n.rank);null!=i&&(n=n.transpose(i),r=Rn(r.length,n.rank));var o={axis:r[0]},a=[n];return je.runKernelFunc((function(e,t){var i=e.argMax(n,r[0]);return t([n]),i}),{x:n},(function(e,t){var n=t[0];return{x:function(){return Kn(n)}}}),"ArgMax",o,a)}}),gd=kn({argMin_:function(e,t){void 0===t&&(t=0);var n=mn(e,"x","argMin");null==t&&(t=0);var r=j(t,n.shape),i=_n(r,n.rank);return null!=i&&(n=n.transpose(i),r=Rn(r.length,n.rank)),je.runKernelFunc((function(e,t){var i=e.argMin(n,r[0]);return t([n]),i}),{$x:n},(function(e,t){var n=t[0];return{$x:function(){return Kn(n)}}}))}}),vd=kn({logSumExp_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","logSumExp"),i=j(t,r.shape),o=r.max(i,!0),a=r.sub(o).exp().sum(i).log(),s=o.reshape(a.shape).add(a);if(n){var c=wn(s.shape,i);return s.reshape(c)}return s}}),yd=kn({max_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","max"),i=r,o=j(t,r.shape),a=o,s=_n(a,r.rank);null!=s&&(r=r.transpose(s),a=Rn(a.length,r.rank));var c=[r],u=je.runKernelFunc((function(e,t){var n=e.max(r,a);return t([i,n]),n}),{x:r},(function(e,t){return pd(e,t[1],t[0],o,s)}),"Max",{axes:a},c,[!0]);if(n){var d=wn(u.shape,o);u=u.reshape(d)}return u}}),bd=kn({mean_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","mean"),i=j(t,r.shape),o=I(bn(r.shape,i)[1]);return pi((function(e){var r=On(o);return{value:(r.dtype===e.dtype?e:e.cast(r.dtype)).div(r).sum(t,n),gradFunc:function(t){var n=e.shape.slice();return i.forEach((function(e){n[e]=1})),t.reshape(n).mul(zn(e.shape,"float32")).div(o)}}}))(r)}}),wd=kn({min_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","min"),i=r,o=j(t,r.shape),a=o,s=_n(a,r.rank);null!=s&&(r=r.transpose(s),a=Rn(a.length,r.rank));var c=[r],u=je.runKernelFunc((function(e,t){var n=e.min(r,a);return t([i,n]),n}),{x:r},(function(e,t){return pd(e,t[1],t[0],o,s)}),"Min",{axes:a},c,[!0]);if(n){var d=wn(u.shape,o);u=u.reshape(d)}return u}}),xd=kn({moments_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=j(t,(e=mn(e,"x","moments")).shape),i=e.mean(r,n),o=i.shape;n||(o=wn(i.shape,r));var a=e.toFloat().sub(i.reshape(o)).square();return{mean:i,variance:a.mean(r,n)}}}),_d=kn({sum_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","sum");"bool"===r.dtype&&(r=r.toInt());var i=j(t,r.shape);return pi((function(e){var t=_n(i,e.rank),r=i,o=e;null!=t&&(o=e.transpose(t),r=Rn(r.length,e.rank));var a=function(t){var n=e.shape.slice();return i.forEach((function(e){n[e]=1})),t.reshape(n).mul(zn(e.shape,"float32"))},s={axes:r},c=je.runKernelFunc((function(e){return e.sum(o,r)}),{x:o},(function(e){return{x:function(){return a(e)}}}),"Sum",s);if(n){var u=wn(c.shape,i);c=c.reshape(u)}return{value:c,gradFunc:a}}))(r)}}),Sd=kn({prod_:function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var r=mn(e,"x","prod");"bool"===r.dtype&&(r=r.toInt());var i=j(t,r.shape),o=_n(i,r.rank),a=i,s=r;null!=o&&(s=r.transpose(o),a=Rn(a.length,r.rank));var c=je.runKernelFunc((function(e){return e.prod(s,a)}),{permutedX:s});if(n){var u=wn(c.shape,i);c=c.reshape(u)}return c}}),Rd=kn({elu_:function(e){var t=mn(e,"x","elu");return je.runKernelFunc((function(e,n){var r=e.elu(t);return n([r]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){return je.runKernelFunc((function(t){return t.eluDer(e,n)}),{dy:e,y:n})}}}))}}),Cd=kn({leakyRelu_:function(e,t){void 0===t&&(t=.2);var n=mn(e,"x","leakyRelu");return nu(On(t).mul(n),n)}}),Ed=kn({prelu_:function(e,t){var n=mn(e,"x","prelu"),r=mn(t,"alpha","prelu");return je.runKernelFunc((function(e,t){var i=e.prelu(n,r);return t([n,r]),i}),{x:n,alpha:r},(function(e,t){var n=t[0],r=t[1],i=n.greater(0);return{x:function(){return Hc(i,e,e.mul(r))},alpha:function(){var t=Hc(i,Kn(e),e.mul(n)),o=wi(r.shape,e.shape);return o.length>0&&(t=t.sum(o)),t.reshape(r.shape)}}}),"Prelu")}}),kd=kn({relu_:function(e){var t=mn(e,"x","relu");return"bool"===t.dtype?t.toInt():je.runKernelFunc((function(e,n){var r=e.relu(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0];return{x:function(){return e.mulStrict(n.step().toFloat())}}}),"Relu")}}),Td=kn({relu6_:function(e){var t=mn(e,"x","relu6");return"bool"===t.dtype?t.toInt():je.runKernelFunc((function(e,n){var r=e.relu6(t);return n([t]),r}),{x:t},(function(e,t){var n=t[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return e.mulStrict(r.toFloat())}}}),"Relu6")}}),Dd=kn({selu_:function(e){var t=mn(e,"x","selu");return je.runKernelFunc((function(e,n){var r=e.selu(t);return n([t]),r}),{$x:t},(function(e,t){var n=t[0];return{$x:function(){var t=n.greater(On(0)),r=On(fs),i=On(ms),o=e.mul(i),a=e.mul(r).mul(n.toFloat().exp());return Hc(t,o,a)}}}))}}),Pd=kn({transpose_:function(e,t){var n=mn(e,"x","transpose");if(null==t&&(t=n.shape.map((function(e,t){return t})).reverse()),k(n.rank===t.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+t+"."})),t.forEach((function(e){k(e>=0&&e<n.rank,(function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+t}))})),n.rank<=1)return n.clone();var r={perm:t};return je.runKernelFunc((function(e){return e.transpose(n,t)}),{x:n},(function(e){var n=Sn(t);return{x:function(){return e.transpose(n)}}}),"Transpose",r)}}),Id=kn({localResponseNormalization_:function(e,t,n,r,i){void 0===t&&(t=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===i&&(i=.5);var o=mn(e,"x","localResponseNormalization");k(4===o.rank||3===o.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+o.rank+"."})),k(O(t),(function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+t+"."}));var a=o,s=!1;3===o.rank&&(s=!0,a=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]));var c=je.runKernelFunc((function(e,o){var s=e.localResponseNormalization4D(a,t,n,r,i);return o([a,s]),s}),{x4D:a},(function(e,o){var a=o[0],s=o[1];return{x4D:function(){return je.runKernelFunc((function(o){return o.LRNGrad(e,a,s,t,n,r,i)}),{})}}}));return s?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),Md=kn({norm_:function(e,t,n,r){void 0===t&&(t="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var i=function e(t,n,r){if(void 0===r&&(r=null),0===t.rank)return t.abs();if(1!==t.rank&&null===r)return e(t.reshape([-1]),n,r);if(1===t.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return t.abs().sum(r);if(n===1/0)return t.abs().max(r);if(n===-1/0)return t.abs().min(r);if("euclidean"===n||2===n)return t.abs().pow(On(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return t.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return t.abs().sum(r[1]).max(r[0]);if(n===-1/0)return t.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return t.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(e=mn(e,"x","norm"),t,n),o=i.shape;if(r){var a=j(n,e.shape);o=wn(i.shape,a)}return i.reshape(o)}}),Od=kn({basicLSTMCell_:function(e,t,n,r,i,o){var a=mn(e,"forgetBias","basicLSTMCell"),s=mn(t,"lstmKernel","basicLSTMCell"),c=mn(n,"lstmBias","basicLSTMCell"),u=mn(r,"data","basicLSTMCell"),d=mn(i,"c","basicLSTMCell"),l=mn(o,"h","basicLSTMCell"),p=u.concat(l,1).matMul(s).add(c),h=p.shape[0],f=p.shape[1]/4,m=[h,f],g=p.slice([0,0],m),v=p.slice([0,f],m),y=p.slice([0,2*f],m),b=p.slice([0,3*f],m),w=g.sigmoid().mulStrict(v.tanh()).addStrict(d.mulStrict(a.add(y).sigmoid())),x=w.tanh().mulStrict(b.sigmoid());return[w,x]}}),Ad=kn({multiRNNCell_:function(e,t,n,r){for(var i=mn(t,"data","multiRNNCell"),o=gn(n,"c","multiRNNCell"),a=gn(r,"h","multiRNNCell"),s=i,c=[],u=0;u<e.length;u++){var d=e[u](s,o[u],a[u]);c.push(d[0]),c.push(d[1]),s=d[1]}var l=[],p=[];for(u=0;u<c.length;u+=2)l.push(c[u]),p.push(c[u+1]);return[l,p]}}),Fd=kn({movingAverage_:function(e,t,n,r,i){void 0===i&&(i=!0);var o=mn(e,"v","movingAverage"),a=mn(t,"x","movingAverage"),s=mn(n,"decay","movingAverage");Oe(o,a),k(M(o.shape,a.shape),(function(){return"Shape mismatch in v and x"}));var c=On(1),u=c.sub(s),d=a.sub(o).mul(u);if(i){k(null!=r,(function(){return"When using zeroDebias: true, step is required."}));var l=mn(r,"step","movingAverage");d=d.div(c.sub(du(s,l)))}return o.add(d)}}),Nd=kn({stridedSlice_:function(e,t,n,r,i,o,a,s,c){if(void 0===i&&(i=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===s&&(s=0),void 0===c&&(c=0),null==r&&(r=new Array(t.length)),0!==a)throw new Error("ellipsis mask is not yet supported");var u=mn(e,"x","stridedSlice"),d=ei(s),l=u.shape.slice();d.forEach((function(e){t[e]=0,n[e]=1,l.splice(e,0,1)})),u=u.reshape(l);for(var p=0;p<u.rank;p++)t[p]=ni(i,t,r,u.shape,p),n[p]=ri(o,n,r,u.shape,p),r[p]=r[p]||1;var h=ei(c);h.forEach((function(e){n[e]=t[e]+1,r[e]=1}));var f=ti(t,n,r),m=f.filter((function(e,t){return-1===h.indexOf(t)}));return r.every((function(e){return 1===e}))?sd(u,t,f).reshape(m):je.runKernelFunc((function(e){return e.stridedSlice(u,t,n,r)}),{$x:u}).reshape(m)}}),Ld=kn({topk_:function(e,t,n){void 0===t&&(t=1),void 0===n&&(n=!0);var r=mn(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var i=r.shape[r.shape.length-1];if(t>i)throw new Error("'k' passed to topk() must be <= the last dimension ("+i+") but got "+t);var o=je.runKernelFunc((function(e){return e.topk(r,t,n)}),{$x:r});return{values:o[0],indices:o[1]}}}),Bd=kn({scatterND_:function(e,t,n){var r=mn(e,"indices","scatterND","int32"),i=mn(t,"updates","scatterND");return Yr(i,r,n),je.runKernelFunc((function(e){return e.scatterND(r,i,n)}),{indices:r,updates:i},null,"ScatterNd",{shape:n})}}),jd=kn({fft_:function(e){k("complex64"===e.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+e.dtype+"."}));var t=e.shape[e.shape.length-1],n=e.size/t,r=e.as2D(n,t);return je.runKernelFunc((function(e){return e.fft(r)}),{input:e}).reshape(e.shape)}}),Wd=kn({ifft_:function(e){k("complex64"===e.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+e.dtype+"."}));var t=e.shape[e.shape.length-1],n=e.size/t,r=e.as2D(n,t);return je.runKernelFunc((function(e){return e.ifft(r)}),{input:e}).reshape(e.shape)}}),zd=kn({rfft_:function(e,t){k("float32"===e.dtype,(function(){return"The dtype for rfft() must be real value but got "+e.dtype}));var n,r=e.shape[e.shape.length-1],i=e.size/r;if(null!=t&&t<r){var o=e.shape.map((function(e){return 0})),a=e.shape.map((function(e){return e}));a[e.shape.length-1]=t,n=e.slice(o,a),r=t}else if(null!=t&&t>r){var s=e.shape.map((function(e){return e}));s[e.shape.length-1]=t-r,n=e.concat(Un(s),e.shape.length-1),r=t}else n=e;var c=n.zerosLike(),u=Tn(n,c).as2D(i,r),d=jd(u),l=Math.floor(r/2)+1,p=Dn(d),h=Pn(d),f=p.split([l,r-l],p.shape.length-1),m=h.split([l,r-l],h.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=l,Tn(f[0],m[0]).reshape(g)}}),Ud=kn({irfft_:function(e){var t=e.shape[e.shape.length-1],n=e.size/t;if(t<=2){var r=e.as2D(n,t),i=Wd(r);return Dn(i)}var o=[n,2*(t-1)],a=Dn(e).as2D(n,t),s=Pn(e).as2D(n,t),c=a.slice([0,1],[n,t-2]).reverse(1),u=s.slice([0,1],[n,t-2]).reverse(1).mul(On(-1)),d=a.concat(c,1),l=s.concat(u,1);return r=Tn(d,l).as2D(o[0],o[1]),i=Wd(r),Dn(i)}}),Vd=Object.freeze({fft:jd,ifft:Wd,rfft:zd,irfft:Ud}),Gd=kn({sparseToDense_:function(e,t,n,r){void 0===r&&(r=0);var i=mn(e,"sparseIndices","sparseToDense","int32"),o=mn(t,"sparseValues","sparseToDense"),a=mn(r,"defaultValue","sparseToDense",o.dtype);return function(e,t,n,r){if("int32"!==e.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+e.shape+".");var i=e.rank>0?e.shape[0]:1,o=e.rank>1?e.shape[1]:1;if(n.length!==o)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+o+".");var a=t.size;if(0!==t.rank&&(1!==t.rank||a!==i))throw new Error("sparseValues has incorrect shape "+t.shape+", should be [] or ["+i+"]");if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(i,o,n,a),je.runKernelFunc((function(e){return e.sparseToDense(i,o,n,a)}),{$sparseIndices:i,$sparseValues:o,$defaultValue:a})}}),qd=kn({gatherND_:function(e,t){var n=mn(t,"indices","gatherND","int32"),r=mn(e,"x","gatherND");return je.runKernelFunc((function(e){return e.gatherND(r,n)}),{x:r,indices:n},null,"GatherNd")}}),Hd=kn({diag_:function(e){var t=mn(e,"x","diag").flatten(),n=e.shape.concat(e.shape);return je.runKernelFunc((function(e){return e.diag(t)}),{$x:t}).reshape(n)}}),Kd=kn({dropout_:function(e,t,n,r){var i=mn(e,"x","dropout");if(k("float32"===i.dtype,(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+i.dtype+" tensor instead."})),k(t>=0&&t<1,(function(){return"rate must be a float in the range [0, 1), but got "+t+"."})),0===t)return e instanceof _e?i.clone():i;var o=function(e,t){if(null==t)return e.shape.slice();if(M(e.shape,t))return t;if(e.shape.length===t.length){for(var n=[],r=0;r<e.shape.length;r++)null==t[r]&&null!=e.shape[r]?n.push(e.shape[r]):n.push(t[r]);return n}return t}(i,n),a=1-t,s=Mr(o,0,1,"float32",r).add(a).floor().div(a);return i.mul(s)}});function Xd(e,t,n){for(var r=1-e%2,i=new Float32Array(e),o=0;o<e;++o){var a=2*Math.PI*o/(e+r-1);i[o]=t-n*Math.cos(a)}return An(i,"float32")}var $d,Yd=kn({hannWindow_:function(e){return Xd(e,.5,.5)}}),Qd=kn({hammingWindow_:function(e){return Xd(e,.54,.46)}}),Jd=kn({frame_:function(e,t,n,r,i){void 0===r&&(r=!1),void 0===i&&(i=0);for(var o=0,a=[];o+t<=e.size;)a.push(sd(e,o,t)),o+=n;if(r)for(;o<e.size;){var s=o+t-e.size,c=Xn([sd(e,o,t-s),Vn([s],i)]);a.push(c),o+=n}return 0===a.length?Fn([],[0,t]):Xn(a).as2D(a.length,t)}}),Zd=kn({stft_:function(e,t,n,r,i){var o;void 0===i&&(i=Yd),null==r&&(o=t,r=Math.floor(Math.pow(2,Math.ceil(Math.log(o)/Math.log(2)))));for(var a=Jd(e,t,n),s=cu(a,i(t)),c=[],u=0;u<a.shape[0];u++)c.push(zd(s.slice([u,0],[1,t]),r));return Xn(c)}}),el=Object.freeze({hannWindow:Yd,hammingWindow:Qd,frame:Jd,stft:Zd}),tl=function(e,t,n){return void 0===n&&(n=1),c(this,void 0,void 0,(function(){var r,i,o,a,s,c,d,l,p,h,f,m,g,v;return u(this,(function(u){switch(u.label){case 0:return r=mn(e,"predictions","inTopK"),i=mn(t,"targets","inTopK"),k(r.rank>1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank})),k(r.rank-1===i.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+i.rank})),T(r.shape.slice(0,r.shape.length-1),i.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),o=r.shape[r.shape.length-1],k(n>0&&n<=o,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+o+"), but got "+n})),[4,r.data()];case 1:return a=u.sent(),[4,i.data()];case 2:for(s=u.sent(),c=[a.length/o,o],l=c[1],p=z("bool",d=c[0]),h=0;h<d;h++){for(f=h*l,m=a.subarray(f,f+l),g=[],v=0;v<m.length;v++)g.push({value:m[v],index:v});for(g.sort((function(e,t){return t.value-e.value})),p[h]=0,v=0;v<n;v++)if(g[v].index===s[h]){p[h]=1;break}}return e!==r&&r.dispose(),t!==i&&i.dispose(),[2,In(p,i.shape,"bool")]}}))}))};!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}($d||($d={}));var nl=kn({absoluteDifference_:function(e,t,n,r){void 0===r&&(r=$d.SUM_BY_NONZERO_WEIGHTS);var i=mn(e,"labels","absoluteDifference"),o=mn(t,"predictions","absoluteDifference"),a=null;null!=n&&(a=mn(n,"weights","absoluteDifference")),T(i.shape,o.shape,"Error in absoluteDifference: ");var s=i.sub(o).abs();return rl(s,a,r)}}),rl=kn({computeWeightedLoss_:function(e,t,n){void 0===n&&(n=$d.SUM_BY_NONZERO_WEIGHTS);var r=mn(e,"losses","computeWeightedLoss"),i=null;null!=t&&(i=mn(t,"weights","computeWeightedLoss"));var o=null==i?r:r.mul(i);if(n===$d.NONE)return o;if(n===$d.SUM)return o.sum();if(n===$d.MEAN){if(null==i)return o.mean();var a=r.size/i.size,s=o.sum().div(i.sum());return a>1?s.div(On(a)):s}if(n===$d.SUM_BY_NONZERO_WEIGHTS){if(null==i)return o.sum().div(On(r.size));var c=i.mul(zn(r.shape)).notEqual(On(0)).sum().toFloat();return o.sum().div(c)}throw Error("Unknown reduction: "+n)}}),il=kn({cosineDistance_:function(e,t,n,r,i){void 0===i&&(i=$d.SUM_BY_NONZERO_WEIGHTS);var o=mn(e,"labels","cosineDistance"),a=mn(t,"predictions","cosineDistance"),s=null;null!=r&&(s=mn(r,"weights","cosineDistance")),T(o.shape,a.shape,"Error in cosineDistance: ");var c=On(1).sub(o.mul(a).sum(n,!0));return rl(c,s,i)}}),ol=kn({hingeLoss_:function(e,t,n,r){void 0===r&&(r=$d.SUM_BY_NONZERO_WEIGHTS);var i=mn(e,"labels","hingeLoss"),o=mn(t,"predictions","hingeLoss"),a=null;null!=n&&(a=mn(n,"weights","hingeLoss")),T(i.shape,o.shape,"Error in hingeLoss: ");var s=On(1);i=On(2).mul(i).sub(s);var c=s.sub(i.mul(o)).relu();return rl(c,a,r)}}),al=kn({huberLoss_:function(e,t,n,r,i){void 0===r&&(r=1),void 0===i&&(i=$d.SUM_BY_NONZERO_WEIGHTS);var o=mn(e,"labels","huberLoss"),a=mn(t,"predictions","huberLoss"),s=null;null!=n&&(s=mn(n,"weights","huberLoss")),T(o.shape,a.shape,"Error in huberLoss: ");var c=On(r),u=a.sub(o).abs(),d=iu(u,c),l=u.sub(d),p=On(.5).mul(d.square()).add(c.mul(l));return rl(p,s,i)}}),sl=kn({logLoss_:function(e,t,n,r,i){void 0===r&&(r=1e-7),void 0===i&&(i=$d.SUM_BY_NONZERO_WEIGHTS);var o=mn(e,"labels","logLoss"),a=mn(t,"predictions","logLoss"),s=null;null!=n&&(s=mn(n,"weights","logLoss")),T(o.shape,a.shape,"Error in logLoss: ");var c=On(1),u=On(r),d=o.mul(a.add(u).log()).neg().sub(c.sub(o).mul(c.sub(a).add(u).log()));return rl(d,s,i)}}),cl=kn({meanSquaredError_:function(e,t,n,r){void 0===r&&(r=$d.SUM_BY_NONZERO_WEIGHTS);var i=mn(e,"labels","meanSquaredError"),o=mn(t,"predictions","meanSquaredError"),a=null;null!=n&&(a=mn(n,"weights","meanSquaredError")),T(i.shape,o.shape,"Error in meanSquaredError: ");var s=i.squaredDifference(o);return rl(s,a,r)}}),ul=kn({sigmoidCrossEntropy_:function(e,t,n,r,i){void 0===r&&(r=0),void 0===i&&(i=$d.SUM_BY_NONZERO_WEIGHTS);var o=mn(e,"multiClassLabels","sigmoidCrossEntropy"),a=mn(t,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=mn(n,"weights","sigmoidCrossEntropy")),T(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){var c=On(r),u=On(1),d=On(.5);o=o.mul(u.sub(c)).add(d.mul(c))}var l=function(e,t){var n=mn(e,"labels","sigmoidCrossEntropyWithLogits"),r=mn(t,"logits","sigmoidCrossEntropyWithLogits");T(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var i=r.relu(),o=r.mul(n),a=r.abs().neg().exp().log1p();return i.sub(o).add(a)}(o,a);return rl(l,s,i)}}),dl=kn({softmaxCrossEntropy_:function(e,t,n,r,i){void 0===r&&(r=0),void 0===i&&(i=$d.SUM_BY_NONZERO_WEIGHTS);var o=mn(e,"onehotLabels","softmaxCrossEntropy"),a=mn(t,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=mn(n,"weights","softmaxCrossEntropy")),T(o.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){var c=On(r),u=On(1),d=On(o.shape[1]);o=o.mul(u.sub(c)).add(c.div(d))}var l=function(e,t,n){if(void 0===n&&(n=-1),-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+t.rank+" and dim was "+n);return pi((function(e,t,r){var i=t.logSumExp([n],!0),o=t.toFloat().sub(i);return r([e,o]),{value:o.mul(e).neg().sum([n]),gradFunc:function(e,t){var r=t[0],i=t[1],o=wn(e.shape,[n]);return[e.reshape(o).mul(r.toFloat().sub(i.exp())),e.reshape(o).mul(i.exp().sub(r.toFloat()))]}}}))(e,t)}(o,a);return rl(l,s,i)}}),ll=Object.freeze({get Reduction(){return $d},absoluteDifference:nl,computeWeightedLoss:rl,cosineDistance:il,hingeLoss:ol,huberLoss:al,logLoss:sl,meanSquaredError:cl,sigmoidCrossEntropy:ul,softmaxCrossEntropy:dl});function pl(e,t){return void 0===t&&(t=!1),je.tidy((function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var n=e.shape[0],r=e.shape[1],i=xr(n),o=e.clone(),a=Fn([[1]],[1,1]),s=a.clone(),c=n>=r?r:n,u=function(e){var t,c=o,u=s,d=i;t=je.tidy((function(){var t=o.slice([e,e],[n-e,1]),c=t.norm(),u=o.slice([e,e],[1,1]),d=Fn([[-1]]).where(u.greater(0),Fn([[1]])),l=u.sub(d.mul(c)),p=t.div(l);s=1===p.shape[0]?a.clone():a.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var h=d.matMul(l).div(c).neg(),f=o.slice([e,0],[n-e,r]),m=h.mul(s);if(0===e)o=f.sub(m.matMul(s.transpose().matMul(f)));else{var g=f.sub(m.matMul(s.transpose().matMul(f)));o=o.slice([0,0],[e,r]).concat(g,0)}var v=i.slice([0,e],[n,i.shape[1]-e]);if(0===e)i=v.sub(v.matMul(s).matMul(m.transpose()));else{var y=v.sub(v.matMul(s).matMul(m.transpose()));i=i.slice([0,0],[n,e]).concat(y,1)}return[s,o,i]})),s=t[0],o=t[1],i=t[2],Zt([c,u,d])},d=0;d<c;++d)u(d);return!t&&n>r&&(i=i.slice([0,0],[n,r]),o=o.slice([0,0],[r,r])),[i,o]}))}var hl=kn({bandPart_:function(e,t,n){if(t%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+t+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var r=mn(e,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var i=r.shape,o=r.shape.slice(-2),a=o[0],s=o[1];if(!(t<=a))throw new Error("bandPart(): numLower ("+t+") must not be greater than the number of rows ("+a+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");t<0&&(t=a),n<0&&(n=s);var c=qn(0,a,1,"int32").reshape([-1,1]),u=qn(0,s,1,"int32"),d=hu(c,u),l=Uc(d.lessEqual(On(+t,"int32")),d.greaterEqual(On(-n,"int32"))),p=Un([a,s],r.dtype);return Nr(jr(r.reshape([-1,a,s])).map((function(e){return Hc(l,e,p)}))).reshape(i)}}),fl=kn({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,k(null!=e&&e.length>0,(function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"}));for(var n=e[0].shape[0],r=function(t){k(e[t].shape[0]===n,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+e[t].shape[0]+" vs. "+n+")"}))},i=1;i<e.length;++i)r(i)}else t=!0,e=Zn(e,e.shape[0],0).map((function(e){return Fr(e,[0])}));k(e.length<=e[0].shape[0],(function(){return"Gram-Schmidt: Number of vectors ("+e.length+") exceeds number of dimensions ("+e[0].shape[0]+")."}));var o=[],a=e,s=function(e){o.push(je.tidy((function(){var t=a[e];if(e>0)for(var n=0;n<e;++n){var r=_d(o[n].mulStrict(t)).mul(o[n]);t=t.sub(r)}return t.div(Md(t,"euclidean"))})))};for(i=0;i<e.length;++i)s(i);return t?Nr(o,0):o}}),ml=kn({qr_:function(e,t){if(void 0===t&&(t=!1),e.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+e.rank);if(2===e.rank)return pl(e,t);var n=e.shape.slice(0,e.shape.length-2).reduce((function(e,t){return e*t})),r=jr(e.reshape([n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],o=[];return r.forEach((function(e){var n=pl(e,t),r=n[0],a=n[1];i.push(r),o.push(a)})),[Nr(i,0).reshape(e.shape),Nr(o,0).reshape(e.shape)]}}),gl=Object.freeze({bandPart:hl,gramSchmidt:fl,qr:ml});function vl(e,t,n,r,i,o){null==r&&(r=.5),null==i&&(i=Number.NEGATIVE_INFINITY),null==o&&(o=0);var a=e.shape[0];return n=Math.min(n,a),k(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),k(2===e.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+e.rank+"'"})),k(4===e.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]})),k(1===t.rank,(function(){return"scores must be a 1D tensor"})),k(t.shape[0]===a,(function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+t.shape[0]})),k(0<=o&&o<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+o+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i,softNmsSigma:o}}var yl=kn({resizeBilinear_:function(e,t,n){void 0===n&&(n=!1);var r=mn(e,"images","resizeBilinear");k(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),k(2===t.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+t+"."}));var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=t[0],s=t[1],c=je.runKernelFunc((function(e,t){return t([i]),e.resizeBilinear(i,a,s,n)}),{x:i},(function(e,t){return{x:function(){return je.runKernelFunc((function(r){return r.resizeBilinearBackprop(e,t[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:a,newWidth:s});return o?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),bl=kn({resizeNearestNeighbor_:function(e,t,n){void 0===n&&(n=!1);var r=mn(e,"images","resizeNearestNeighbor");k(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),k(2===t.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."})),k("float32"===r.dtype||"int32"===r.dtype,(function(){return"`images` must have `int32` or `float32` as dtype"}));var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=t[0],s=t[1],c=je.runKernelFunc((function(e,t){return t([i]),e.resizeNearestNeighbor(i,a,s,n)}),{batchImages:i},(function(e,t){return{batchImages:function(){return je.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(e,t[0],n)}),{})}}}));return o?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}}),wl=kn({nonMaxSuppression_:function(e,t,n,r,i){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY);var o=mn(e,"boxes","nonMaxSuppression"),a=mn(t,"scores","nonMaxSuppression"),s=vl(o,a,n,r,i);n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold;var c={maxOutputSize:n,iouThreshold:r,scoreThreshold:i};return je.runKernelFunc((function(e){return e.nonMaxSuppression(o,a,n,r,i)}),{boxes:o,scores:a},null,"NonMaxSuppressionV3",c)}}),xl=kn({nonMaxSuppressionWithScore_:function(e,t,n,r,i,o){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),void 0===o&&(o=0);var a=mn(e,"boxes","nonMaxSuppression"),s=mn(t,"scores","nonMaxSuppression"),c=vl(a,s,n,r,i,o),u={maxOutputSize:n=c.maxOutputSize,iouThreshold:r=c.iouThreshold,scoreThreshold:i=c.scoreThreshold,softNmsSigma:o=c.softNmsSigma},d=je.runKernel("NonMaxSuppressionV5",{boxes:a,scores:s},u);return{selectedIndices:d[0],selectedScores:d[1]}}}),_l=kn({cropAndResize_:function(e,t,n,r,i,o){var a=mn(e,"image","cropAndResize"),s=mn(t,"boxes","cropAndResize","float32"),c=mn(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;var u=s.shape[0];return k(4===a.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."})),k(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+u+",4] but had shape "+s.shape+"."})),k(1===c.rank&&c.shape[0]===u,(function(){return"Error in cropAndResize: boxInd must be have size ["+u+"] but had shape "+s.shape+"."})),k(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),k(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),k("bilinear"===i||"nearest"===i,(function(){return"method must be bilinear or nearest, but was "+i})),je.runKernelFunc((function(e,t){return e.cropAndResize(a,s,c,r,i,o)}),{images:a,boxes:s,boxInd:c},null,"CropAndResize",{method:i,extrapolationValue:o,cropSize:r})}}),Sl=Object.freeze({resizeBilinear:yl,resizeNearestNeighbor:bl,nonMaxSuppression:wl,nonMaxSuppressionAsync:function(e,t,n,r,i){return void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),c(this,void 0,void 0,(function(){var o,a,s,c,d,l,p;return u(this,(function(u){switch(u.label){case 0:return o=mn(e,"boxes","nonMaxSuppressionAsync"),a=mn(t,"scores","nonMaxSuppressionAsync"),s=vl(o,a,n,r,i),n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,[4,Promise.all([o.data(),a.data()])];case 1:return c=u.sent(),d=c[0],l=c[1],p=Gi(d,l,n,r,i),o!==e&&o.dispose(),a!==t&&a.dispose(),[2,p]}}))}))},nonMaxSuppressionWithScore:xl,nonMaxSuppressionWithScoreAsync:function(e,t,n,r,i,o){return void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),void 0===o&&(o=0),c(this,void 0,void 0,(function(){var a,s,c,d,l,p,h;return u(this,(function(u){switch(u.label){case 0:return a=mn(e,"boxes","nonMaxSuppressionAsync"),s=mn(t,"scores","nonMaxSuppressionAsync"),c=vl(a,s,n,r,i,o),n=c.maxOutputSize,r=c.iouThreshold,i=c.scoreThreshold,o=c.softNmsSigma,[4,Promise.all([a.data(),s.data()])];case 1:return d=u.sent(),l=d[0],p=d[1],h=qi(l,p,n,r,i,o),a!==e&&a.dispose(),s!==t&&s.dispose(),[2,h]}}))}))},cropAndResize:_l}),Rl=function(e,t){return!(e>0)||"linear"===t},Cl=function(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return e.mul(t.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},El=function(e,t){var n=t,r=wi(e.shape,t.shape);return r.length>0&&(n=n.sum(r)),n.reshape(e.shape)},kl=function(e,t,n){if("linear"===t)return e;if("relu"===t)return kd(e);if("elu"===t)return Rd(e);if("relu6"===t)return Td(e);if("prelu"===t)return Ed(e,n);throw new Error("Unknown fused activation "+t+".")},Tl=kn({fusedMatMul_:function(e){var t,n=e.a,r=e.b,i=e.transposeA,o=void 0!==i&&i,a=e.transposeB,s=void 0!==a&&a,c=e.bias,u=e.activation,d=void 0===u?"linear":u,l=e.preluActivationWeights;if(!1===Rl(je.state.gradientDepth,d)){var p=Hu(n,r,o,s);return null!=c&&(p=Xc(p,c)),kl(p,d,l)}var h=mn(n,"a","fused matMul"),f=mn(r,"b","fused matMul");t=Me(h,f),h=t[0],f=t[1];var m=o?h.shape[h.rank-2]:h.shape[h.rank-1],g=s?f.shape[f.rank-1]:f.shape[f.rank-2],v=o?h.shape[h.rank-1]:h.shape[h.rank-2],y=s?f.shape[f.rank-2]:f.shape[f.rank-1],b=h.shape.slice(0,-2),w=f.shape.slice(0,-2),x=I(b),_=I(w);k(h.rank>=2&&f.rank>=2&&h.rank===f.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+h.rank+" and "+f.rank+"."})),k(M(b,w),(function(){return"Error in fused matMul: outer dimensions ("+b+") and ("+w+") of Tensors with shapes "+h.shape+" and "+f.shape+" must match."})),k(m===g,(function(){return"Error in fused matMul: inner shapes ("+m+") and ("+g+") of Tensors with shapes "+h.shape+" and "+f.shape+" and transposeA="+o+" and transposeB="+s+" must match."}));var S,R,C=h.shape.slice(0,-2).concat([v,y]),E=o?h.as3D(x,m,v):h.as3D(x,v,m),T=s?f.as3D(_,y,g):f.as3D(_,g,y);null!=c&&xi(C,(S=Me(S=mn(c,"bias","fused matMul"),h)[0]).shape),null!=l&&(R=mn(l,"prelu weights","fused matMul"));var D={a:E,b:T};null!=c&&(D.bias=S),null!=l&&(D.preluActivationWeights=R);var P=[E,T];return je.runKernelFunc((function(e,t){var n=e.fusedBatchMatMul({a:E,b:T,transposeA:o,transposeB:s,bias:S,activation:d,preluActivationWeights:R});return t([E,T,n]),n}),D,(function(e,t){var n=t[0],r=t[1],i=t[2],a=Cl(e,i,d),u={};return null!=c&&(u={bias:function(){return El(S,a)}}),o||s?!o&&s?Object.assign({a:function(){return a.matMul(r,!1,!1)},b:function(){return a.matMul(n,!0,!1)}},u):o&&!s?Object.assign({a:function(){return r.matMul(a,!1,!0)},b:function(){return n.matMul(a,!1,!1)}},u):Object.assign({a:function(){return r.matMul(a,!0,!0)},b:function(){return a.matMul(n,!0,!0)}},u):Object.assign({a:function(){return a.matMul(r,!1,!0)},b:function(){return n.matMul(a,!0,!1)}},u)}),"_FusedMatMul",{transposeA:o,transposeB:s,activation:d},P,[!0]).reshape(C)}}),Dl=kn({fusedConv2d_:function(e){var t=e.x,n=e.filter,r=e.strides,i=e.pad,o=e.dataFormat,a=void 0===o?"NHWC":o,s=e.dilations,c=void 0===s?[1,1]:s,u=e.dimRoundingMode,d=e.bias,l=e.activation,p=void 0===l?"linear":l,h=e.preluActivationWeights;if(p=p||"linear",!1===Rl(je.state.gradientDepth,p)){var f=Nu(t,n,r,i,a,c,u);return null!=d&&(f=Xc(f,d)),kl(f,p,h)}var m=mn(t,"x","conv2d"),g=mn(n,"filter","conv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),k(4===v.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+v.rank+"."})),k(4===g.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."})),null!=u&&k(O(i),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+u+" but got pad "+i+"."})),k(v.shape[3]===g.shape[2],(function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match input depth for filter "+g.shape[2]+"."})),k(Mi(r,c),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+c+"'"})),k("NHWC"===a,(function(){return"Error in conv2d: got dataFormat of "+a+" but only NHWC is currently supported."}));var b,w,x=Ri(v.shape,g.shape,r,c,i,u);null!=d&&(b=Me(b=mn(d,"bias","fused conv2d"),m)[0],xi(x.outShape,b.shape)),null!=h&&(w=mn(h,"prelu weights","fused conv2d"));var _={x:v,filter:g};null!=d&&(_.bias=b),null!=h&&(_.preluActivationWeights=w);var S=[g,v],R=je.runKernelFunc((function(e,t){var n=e.fusedConv2d({input:v,filter:g,convInfo:x,bias:b,activation:p,preluActivationWeights:w});return t([g,v,n]),n}),_,(function(e,t){var n=t,o=n[0],a=n[1],s=n[2],u=Cl(e,s,p);k(Ii(c),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+c+"'"}));var l={};return null!=d&&(l={bias:function(){return El(b,u)}}),Object.assign({x:function(){return ju(a.shape,u,o,r,i)},filter:function(){return Bu(a,u,o.shape,r,i)}},l)}),"FusedConv2D",{convInfo:x,activation:p},S,[!0]);return y?R.as3D(R.shape[1],R.shape[2],R.shape[3]):R}}),Pl=kn({fusedDepthwiseConv2d_:function(e){var t=e.x,n=e.filter,r=e.strides,i=e.pad,o=e.dataFormat,a=void 0===o?"NHWC":o,s=e.dilations,c=void 0===s?[1,1]:s,u=e.dimRoundingMode,d=e.bias,l=e.activation,p=void 0===l?"linear":l,h=e.preluActivationWeights;if(!1===Rl(je.state.gradientDepth,p)){var f=Wu(t,n,r,i,a,c,u);return null!=d&&(f=Xc(f,d)),kl(f,p,h)}var m=mn(t,"x","depthwiseConv2d"),g=mn(n,"filter","depthwiseConv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),k(4===v.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+v.rank+"."})),k(4===g.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+g.rank+"."})),k(v.shape[3]===g.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+v.shape[3]+") must match the inChannels dimension in filter "+g.shape[2]+"."})),null==c&&(c=[1,1]),k(Mi(r,c),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+c+"'"})),null!=u&&k(O(i),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+u+" but got pad "+i+"."}));var b,w,x=Ri(v.shape,g.shape,r,c,i,u,!0);null!=d&&(b=Me(b=mn(d,"bias","fused conv2d"),m)[0],xi(x.outShape,b.shape)),null!=h&&(w=mn(h,"prelu weights","fused depthwiseConv2d"));var _={x:v,filter:g};null!=d&&(_.bias=b),null!=h&&(_.preluActivationWeights=w);var S=[g,v],R=je.runKernelFunc((function(e,t){var n=e.fusedDepthwiseConv2D({input:v,filter:g,convInfo:x,bias:b,activation:p,preluActivationWeights:w});return t([g,v,n]),n}),_,(function(e,t){k(Ii(c),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+c+"'"}));var n=t[0],r=t[1],i=t[2],o=Cl(e,i,p),a={};return null!=d&&(a={bias:function(){return El(b,o)}}),Object.assign({x:function(){return zu(r.shape,o,n,x)},filter:function(){return Uu(r,o,n.shape,x)}},a)}),"FusedDepthwiseConv2D",{convInfo:x,activation:p},S,[!0]);return y?R.as3D(R.shape[1],R.shape[2],R.shape[3]):R}}),Il=Object.freeze({matMul:Tl,conv2d:Dl,depthwiseConv2d:Pl}),Ml=Object.freeze({image:Sl,linalg:gl,losses:ll,spectral:Vd,fused:Il,signal:el,square:qs,squaredDifference:Ks,conv1d:Fu,conv2d:Nu,conv3d:Lu,depthwiseConv2d:Wu,separableConv2d:Vu,conv2dTranspose:Gu,conv3dTranspose:qu,op:kn,batchNormalization2d:Ac,batchNormalization3d:Fc,batchNormalization4d:Nc,batchNormalization:Lc,batchNorm:Bc,batchNorm2d:jc,batchNorm3d:Wc,batchNorm4d:zc,booleanMaskAsync:Iu,complex:Tn,real:Dn,imag:Pn,concat:Xn,concat1d:$n,concat2d:Yn,concat3d:Qn,concat4d:Jn,split:Zn,matMul:Hu,dot:Ku,outerProduct:Xu,reverse:$u,reverse1d:Yu,reverse2d:Qu,reverse3d:Ju,reverse4d:Zu,maxPool:nd,avgPool:rd,pool:id,maxPool3d:od,avgPool3d:ad,slice:sd,slice1d:cd,slice2d:ud,slice3d:dd,slice4d:ld,abs:Xs,acos:$s,acosh:Ys,asin:Qs,asinh:Js,atan:Zs,atanh:ec,ceil:tc,clipByValue:nc,cos:rc,cosh:ic,erf:oc,exp:ac,expm1:sc,floor:cc,log:uc,log1p:dc,logSigmoid:lc,neg:pc,reciprocal:hc,round:fc,rsqrt:mc,sigmoid:gc,sign:vc,isNaN:yc,isInf:bc,isFinite:wc,sin:xc,sinh:_c,softplus:Sc,sqrt:Rc,step:Cc,tan:Ec,tanh:kc,all:hd,any:fd,argMax:md,argMin:gd,logSumExp:vd,max:yd,mean:bd,min:wd,moments:xd,sum:_d,prod:Sd,equal:mu,equalStrict:gu,greater:vu,greaterEqual:yu,greaterEqualStrict:bu,greaterStrict:wu,less:xu,lessEqual:_u,lessEqualStrict:Su,lessStrict:Ru,notEqual:Cu,notEqualStrict:Eu,add:Xc,addN:$c,addStrict:Yc,atan2:Qc,div:Jc,divNoNan:Zc,divStrict:eu,floorDiv:tu,maximum:nu,maximumStrict:ru,minimum:iu,minimumStrict:ou,mod:au,modStrict:su,mul:cu,mulStrict:uu,pow:du,powStrict:lu,squaredDifferenceStrict:pu,sub:hu,subStrict:fu,elu:Rd,leakyRelu:Cd,prelu:Ed,relu:kd,relu6:Td,selu:Dd,logicalAnd:Uc,logicalNot:Vc,logicalOr:Gc,logicalXor:qc,where:Hc,whereAsync:Kc,buffer:pr,print:hr,batchToSpaceND:fr,broadcastTo:mr,cast:gr,clone:vr,cumsum:yr,depthToSpace:br,expandDims:wr,eye:xr,multinomial:_r,oneHot:Sr,pad:Rr,pad1d:Cr,pad2d:Er,pad3d:kr,pad4d:Tr,rand:Dr,randomNormal:Pr,randomGamma:Ir,randomUniform:Mr,reshape:Or,spaceToBatchND:Ar,squeeze:Fr,stack:Nr,tile:Lr,truncatedNormal:Br,unstack:jr,setdiff1dAsync:Wr,fill:Vn,linspace:Gn,ones:zn,range:qn,scalar:On,tensor:In,tensor1d:An,tensor2d:Fn,tensor3d:Nn,tensor4d:Ln,tensor5d:Bn,tensor6d:jn,variable:Wn,zeros:Un,onesLike:Hn,zerosLike:Kn,transpose:Pd,softmax:fi,logSoftmax:mi,localResponseNormalization:Id,norm:Md,gather:Du,unsortedSegmentSum:Pu,basicLSTMCell:Od,multiRNNCell:Ad,movingAverage:Fd,stridedSlice:Nd,topk:Ld,scatterND:Bd,fft:jd,ifft:Wd,rfft:zd,irfft:Ud,sparseToDense:Gd,gatherND:qd,diag:Hd,dropout:Kd,hannWindow:Yd,hammingWindow:Qd,frame:Jd,stft:Zd,inTopKAsync:tl});function Ol(e,t){Array.isArray(e)||(e=[e]),e.forEach((function(e){null!=e&&k("complex64"!==e.dtype,(function(){return t+" does not support complex64 tensors."}))}))}function Al(e,t,n,r){if("linear"===n)return e.linear(t);if("relu"===n)return e.relu(t);if("elu"===n)return e.elu(t);if("relu6"===n)return e.relu6(t);if("prelu"===n)return e.prelu(t,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var Fl=function(e){function t(){var t=e.call(this)||this;return t.blockSize=48,t.firstUse=!0,t.data=new gi(t,je),t}return s(t,e),t.prototype.write=function(e,t,n){this.firstUse&&(this.firstUse=!1,l().get("IS_NODE")&&pn("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));var r={};return this.data.set(r,{values:e,dtype:n}),r},t.prototype.move=function(e,t,n,r){this.data.set(e,{values:t,dtype:r})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(t){return[2,this.readSync(e)]}))}))},t.prototype.readSync=function(e){var t=this.data.get(e),n=t.dtype,r=t.complexTensors;return"complex64"===n?Bi(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(e).values},t.prototype.bufferSync=function(e){var t=this.readSync(e.dataId),n=t;if("string"===e.dtype)try{n=t.map((function(e){return ue(e)}))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return pr(e.shape,e.dtype,n)},t.prototype.makeOutput=function(e,t,n){var r=this.write(e,t,n);return je.makeTensorFromDataId(r,t,n,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var t=this.data.get(e).complexTensors;null!=t&&(t.real.dispose(),t.imag.dispose()),this.data.delete(e)}},t.prototype.time=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){return t=ae(),e(),[2,{kernelMs:ae()-t}]}))}))},t.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},t.prototype.complex=function(e,t){var n=this.makeOutput(null,e.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:je.keep(e.clone()),imag:je.keep(t.clone())},n},t.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},t.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},t.prototype.slice=function(e,t,n){if(Ol(e,"slice"),ii(e.shape,t,n)){var r=oi(t,e.strides),i=I(n);return In(this.readSync(e.dataId).subarray(r,r+i),n,e.dtype)}for(var o=pr(n,e.dtype),a=this.bufferSync(e),s=0;s<o.size;++s){var c=o.indexToLoc(s).map((function(e,n){return e+t[n]}));o.values[s]=a.get.apply(a,c)}return o.toTensor()},t.prototype.stridedSlice=function(e,t,n,r){Ol(e,"stridedSlice");var i=ti(t,n,r);if(i.some((function(e){return 0===e})))return In([],i);for(var o=pr(i,e.dtype),a=this.bufferSync(e),s=0;s<o.size;s++){for(var c=o.indexToLoc(s),u=new Array(c.length),d=0;d<u.length;d++)u[d]=c[d]*r[d]+t[d];o.set.apply(o,[a.get.apply(a,u)].concat(c))}return o.toTensor()},t.prototype.diag=function(e){for(var t=this.readSync(e.dataId),n=pr([e.size,e.size],e.dtype),r=n.values,i=0;i<t.length;i++)r[i*e.size+i]=t[i];return n.toTensor()},t.prototype.unstack=function(e,t){for(var n=e.shape[t],r=new Array(e.rank-1),i=0,o=0;o<e.rank;o++)o!==t&&(r[i++]=e.shape[o]);var a=new Array(e.rank).fill(0),s=e.shape.slice();s[t]=1;var c=new Array(n);for(o=0;o<c.length;o++)a[t]=o,c[o]=this.slice(e,a,s).reshape(r);return c},t.prototype.reverse=function(e,t){Ol(e,"reverse");for(var n=pr(e.shape,e.dtype),r=this.bufferSync(e),i=function(i){var o=n.indexToLoc(i),a=o.slice();t.forEach((function(t){return a[t]=e.shape[t]-1-a[t]})),n.set.apply(n,[r.get.apply(r,a)].concat(o))},o=0;o<n.size;o++)i(o);return n.toTensor()},t.prototype.concat=function(e,t){var n=this;if("complex64"===e[0].dtype){var r=e.map((function(e){return Dn(e)})),i=e.map((function(e){return Pn(e)}));return Tn(this.concat(r,t),this.concat(i,t))}var o=e.map((function(e){var n=I(e.shape.slice(t));return e.as2D(-1,n)})),a=En(o.map((function(e){return e.shape})),1),s=pr(a,e[0].dtype).values;if(1===o[0].shape[0]){var c=0;o.forEach((function(e){s.set(n.readSync(e.dataId),c),c+=e.size}))}else{var u=0;o.forEach((function(e){for(var t=n.readSync(e.dataId),r=0,i=0;i<e.shape[0];++i)for(var o=i*a[1]+u,c=0;c<e.shape[1];++c)s[o+c]=t[r++];u+=e.shape[1]}))}var d=En(e.map((function(e){return e.shape})),t);return In(s,d,e[0].dtype)},t.prototype.neg=function(e){return Ol(e,"neg"),this.multiply(On(-1),e)},t.prototype.add=function(e,t){return"complex64"===e.dtype||"complex64"===t.dtype?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),(function(e,t,n,r){return{real:e+n,imag:t+r}})):this.broadcastedBinaryOp(e,t,Pe(e.dtype,t.dtype),(function(e,t){return e+t}))},t.prototype.addN=function(e){var t=this;Ol(e,"addN");for(var n=e.map((function(e){return t.readSync(e.dataId)})),r=pr(e[0].shape,e[0].dtype),i=r.values,o=0;o<e.length;o++)for(var a=n[o],s=0;s<i.length;s++)i[s]+=a[s];return r.toTensor()},t.prototype.softmax=function(e,t){var n=j([t],e.shape),r=this.max(e,n),i=wn(r.shape,n),o=this.subtract(e,r.reshape(i)),a=this.exp(o),s=this.sum(a,n).reshape(i);return this.realDivide(a,s)},t.prototype.subtract=function(e,t){return"complex64"===e.dtype||"complex64"===t.dtype?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),(function(e,t,n,r){return{real:e-n,imag:t-r}})):this.broadcastedBinaryOp(e,t,Pe(e.dtype,t.dtype),(function(e,t){return e-t}))},t.prototype.pow=function(e,t){return Ol([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.pow(e,t)}))},t.prototype.batchMatMul=function(e,t,n,r){Ol([e,t],"matMul");for(var i=n?e.shape[1]:e.shape[2],o=n?e.shape[2]:e.shape[1],a=r?t.shape[1]:t.shape[2],s=e.shape[0],c=this.readSync(e.dataId),u=this.readSync(t.dataId),d=n?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],l=d[0],p=d[1],h=d[2],f=r?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],m=f[0],g=f[1],v=f[2],y=o*a,b=pr([s,o,a],e.dtype),w=b.values,x=this.blockSize,_=0;_<s;_++)for(var S=0;S<o;S+=x)for(var R=0;R<a;R+=x)for(var C=0;C<i;C+=x)for(var E=Math.min(S+x,o),k=Math.min(R+x,a),T=Math.min(C+x,i),D=S;D<E;D++)for(var P=R;P<k;P++){for(var I=0,M=C;M<T;M++)I+=c[_*l+D*p+M*h]*u[M*m+P*g+_*v];w[_*y+(D*a+P)]+=I}return b.toTensor()},t.prototype.fusedBatchMatMul=function(e){var t=e.a,n=e.b,r=e.transposeA,i=e.transposeB,o=e.bias,a=e.activation,s=e.preluActivationWeights,c=this.batchMatMul(t,n,r,i);return o&&(c=this.add(c,o)),a&&(c=Al(this,c,a,s)),c},t.prototype.multiply=function(e,t){return"complex64"===e.dtype||"complex64"===t.dtype?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),(function(e,t,n,r){return{real:e*n-t*r,imag:e*r+t*n}})):this.broadcastedBinaryOp(e,t,Pe(e.dtype,t.dtype),(function(e,t){return e*t}))},t.prototype.realDivide=function(e,t){return Ol([e,t],"realDivide"),this.broadcastedBinaryOp(e,t,"float32",(function(e,t){return e/t}))},t.prototype.floorDiv=function(e,t){return Ol([e,t],"floorDiv"),this.broadcastedBinaryOp(e,t,"int32",(function(e,t){return Math.floor(e/t)}))},t.prototype.sum=function(e,t){Ol(e,"sum"),xn("sum",t,e.rank);for(var n=bn(e.shape,t),r=n[0],i=n[1],o=Un(r,Pe(e.dtype,"int32")),a=I(i),s=this.readSync(o.dataId),c=this.readSync(e.dataId),u=0;u<s.length;++u){for(var d=u*a,l=0,p=0;p<a;++p)l+=c[d+p];s[u]=l}return o},t.prototype.prod=function(e,t){Ol(e,"sum");for(var n=bn(e.shape,t),r=n[0],i=n[1],o=Un(r,Pe(e.dtype,"int32")),a=I(i),s=this.readSync(o.dataId),c=this.readSync(e.dataId),u=0;u<s.length;++u){for(var d=u*a,l=1,p=0;p<a;++p)l*=c[d+p];s[u]=l}return o},t.prototype.unsortedSegmentSum=function(e,t,n){Ol(e,"unsortedSegmentSum");for(var r=[],i=e.rank-t.rank,o=0;o<i;++o)t=t.expandDims(o+1);for(o=0;o<n;++o){var a=On(o,"int32"),s=mu(a,t).asType("float32").mul(e).sum(0);r.push(s)}return Nr(r)},t.prototype.argMin=function(e,t){Ol(e,"argMin");var n=[t];xn("argMin",n,e.rank);for(var r=bn(e.shape,n),i=r[0],o=r[1],a=Un(i,"int32"),s=I(o),c=this.readSync(a.dataId),u=this.readSync(e.dataId),d=0;d<c.length;++d){for(var l=d*s,p=u[l],h=0,f=0;f<s;++f){var m=u[l+f];m<p&&(p=m,h=f)}c[d]=h}return a},t.prototype.argMax=function(e,t){Ol(e,"argMax");var n=[t];xn("argMax",n,e.rank);for(var r=bn(e.shape,n),i=r[0],o=r[1],a=Un(i,"int32"),s=I(o),c=this.readSync(a.dataId),u=this.readSync(e.dataId),d=0;d<c.length;++d){for(var l=d*s,p=u[l],h=0,f=0;f<s;++f){var m=u[l+f];m>p&&(p=m,h=f)}c[d]=h}return a},t.prototype.cumsum=function(e,t,n,r){if(Ol(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var i=Pe(e.dtype,"int32"),o=Un(e.shape,i),a=this.readSync(o.dataId),s=this.readSync(e.dataId),c=e.shape[e.rank-1],u=r?function(e,t){return e+c-t-1}:function(e,t){return e+t},d=0;d<s.length;d+=c)for(var l=0;l<c;l++){var p=u(d,l);if(0===l)a[p]=n?0:s[p];else{var h=u(d,l-1);a[p]=n?s[h]+a[h]:s[p]+a[h]}}return o},t.prototype.equal=function(e,t){return Ol([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e===t?1:0}))},t.prototype.notEqual=function(e,t){return Ol([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e!==t?1:0}))},t.prototype.less=function(e,t){return Ol([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e<t?1:0}))},t.prototype.lessEqual=function(e,t){return Ol([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e<=t?1:0}))},t.prototype.greater=function(e,t){return Ol([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e>t?1:0}))},t.prototype.greaterEqual=function(e,t){return Ol([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e>=t?1:0}))},t.prototype.logicalNot=function(e){Ol(e,"logicalNot");for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)n[r]=t[r]?0:1;return this.makeOutput(n,e.shape,"bool")},t.prototype.logicalAnd=function(e,t){return Ol([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e&&t}))},t.prototype.logicalOr=function(e,t){return Ol([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",(function(e,t){return e||t}))},t.prototype.select=function(e,t,n){Ol([e,t,n],"select");for(var r=this.readSync(e.dataId),i=this.readSync(t.dataId),o=this.readSync(n.dataId),a=Un(t.shape,Pe(t.dtype,n.dtype)),s=this.readSync(a.dataId),c=0,u=0===e.rank||e.rank>1||1===t.rank?1:I(t.shape.slice(1)),d=0;d<r.length;d++)for(var l=0;l<u;l++)1===r[d]?s[c++]=i[d]:s[c++]=o[d];return a},t.prototype.where=function(e){Ol([e],"where");var t=this.readSync(e.dataId);return Zi(e.shape,t)},t.prototype.topk=function(e,t,n){return Ol(e,"topk"),Ji(this.readSync(e.dataId),e.shape,e.dtype,t)},t.prototype.min=function(e,t){Ol(e,"min"),xn("min",t,e.rank);for(var n=bn(e.shape,t),r=n[0],i=n[1],o=Un(r,e.dtype),a=I(i),s=this.readSync(o.dataId),c=this.readSync(e.dataId),u=0;u<s.length;++u){for(var d=u*a,l=c[d],p=0;p<a;++p){var h=c[d+p];h<l&&(l=h)}s[u]=l}return o},t.prototype.minimum=function(e,t){return Ol([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.min(e,t)}))},t.prototype.mod=function(e,t){return Ol([e,t],"mod"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){var n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}))},t.prototype.max=function(e,t){Ol(e,"max"),xn("max",t,e.rank);for(var n=bn(e.shape,t),r=n[0],i=n[1],o=Un(r,e.dtype),a=I(i),s=this.readSync(o.dataId),c=this.readSync(e.dataId),u=0;u<s.length;++u){for(var d=u*a,l=c[d],p=0;p<a;++p){var h=c[d+p];h>l&&(l=h)}s[u]=l}return o},t.prototype.maximum=function(e,t){return Ol([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.max(e,t)}))},t.prototype.all=function(e,t){Ol(e,"all"),xn("all",t,e.rank);for(var n=bn(e.shape,t),r=n[0],i=n[1],o=Un(r,e.dtype),a=I(i),s=this.readSync(o.dataId),c=this.readSync(e.dataId),u=0;u<s.length;++u){for(var d=u*a,l=c[d],p=0;p<a;++p){var h=c[d+p];l=l&&h}s[u]=l}return o},t.prototype.any=function(e,t){Ol(e,"any"),xn("any",t,e.rank);for(var n=bn(e.shape,t),r=n[0],i=n[1],o=Un(r,e.dtype),a=I(i),s=this.readSync(o.dataId),c=this.readSync(e.dataId),u=0;u<s.length;++u){for(var d=u*a,l=c[d],p=0;p<a;++p){var h=c[d+p];l=l||h}s[u]=l}return o},t.prototype.squaredDifference=function(e,t){return Ol([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){var n=e-t;return n*n}))},t.prototype.ceil=function(e){Ol(e,"ceil");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.ceil(t[r]);return this.makeOutput(n,e.shape,"float32")},t.prototype.floor=function(e){Ol(e,"floor");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.floor(t[r]);return this.makeOutput(n,e.shape,"float32")},t.prototype.sign=function(e){Ol(e,"x");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)t[r]<0?n[r]=-1:t[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,e.shape,"float32")},t.prototype.isNaN=function(e){Ol(e,"x");for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Number.isNaN(t[r])&&(n[r]=1);return this.makeOutput(n,e.shape,"bool")},t.prototype.isInf=function(e){Ol(e,"x");for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Math.abs(t[r])===1/0&&(n[r]=1);return this.makeOutput(n,e.shape,"bool")},t.prototype.isFinite=function(e){Ol(e,"x");for(var t=this.readSync(e.dataId),n=new Uint8Array(t.length),r=0;r<t.length;++r)Number.isFinite(t[r])&&(n[r]=1);return this.makeOutput(n,e.shape,"bool")},t.prototype.round=function(e){Ol(e,"round");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=Math.floor(t[r]);t[r]-i<.5?n[r]=Math.floor(t[r]):t[r]-i>.5?n[r]=Math.ceil(t[r]):n[r]=i%2==0?i:i+1}return this.makeOutput(n,e.shape,"float32")},t.prototype.exp=function(e){Ol(e,"exp");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.exp(t[r]);return this.makeOutput(n,e.shape,"float32")},t.prototype.expm1=function(e){Ol(e,"expm1");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=Math.expm1(t[r]);return this.makeOutput(n,e.shape,"float32")},t.prototype.log=function(e){Ol(e,"log");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.log(i)}return this.makeOutput(n,e.shape,"float32")},t.prototype.log1p=function(e){Ol(e,"log1p");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.log1p(i)}return this.makeOutput(n,e.shape,"float32")},t.prototype.sqrt=function(e){Ol(e,"sqrt");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=Math.sqrt(i)}return this.makeOutput(n,e.shape,"float32")},t.prototype.rsqrt=function(e){Ol(e,"rsqrt");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r){var i=t[r];n[r]=1/Math.sqrt(i)}return this.makeOutput(n,e.shape,"float32")},t.prototype.reciprocal=function(e){Ol(e,"reciprocal");for(var t=this.readSync(e.dataId),n=new Float32Array(t.length),r=0;r<t.length;++r)n[r]=1/t[r];return this.makeOutput(n,e.shape,"float32")},t.prototype.linear=function(e){return e},t.prototype.relu=function(e){Ol(e,"relu");for(var t=Un(e.shape,e.dtype),n=this.readSync(t.dataId),r=this.readSync(e.dataId),i=0;i<r.length;++i)n[i]=Math.max(0,r[i]);return t},t.prototype.relu6=function(e){Ol(e,"relu");for(var t=Un(e.shape,e.dtype),n=this.readSync(t.dataId),r=this.readSync(e.dataId),i=0;i<r.length;++i)n[i]=Math.min(Math.max(0,r[i]),6);return t},t.prototype.prelu=function(e,t){return Ol([e,t],"prelu"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return e<0?t*e:e}))},t.prototype.elu=function(e){Ol(e,"elu");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r){var i=n[r];t[r]=i>=0?i:Math.exp(i)-1}return this.makeOutput(t,e.shape,"float32")},t.prototype.eluDer=function(e,t){Ol([e,t],"eluDer");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),i=this.readSync(e.dataId),o=0;o<r.length;++o){var a=r[o];n[o]=a>=1?i[o]:i[o]*(a+1)}return this.makeOutput(n,t.shape,"float32")},t.prototype.selu=function(e){Ol(e,"selu");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r){var i=n[r];t[r]=i>=0?1.0507009873554805*i:1.7580993408473768*(Math.exp(i)-1)}return this.makeOutput(t,e.shape,"float32")},t.prototype.clip=function(e,t,n){Ol(e,"clip");for(var r=new Float32Array(e.size),i=this.readSync(e.dataId),o=0;o<i.length;++o){var a=i[o];r[o]=a>n?n:a<t?t:a}return this.makeOutput(r,e.shape,"float32")},t.prototype.abs=function(e){for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.abs(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.complexAbs=function(e){for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<e.size;++r){var i=n[2*r],o=n[2*r+1];t[r]=Math.hypot(i,o)}return this.makeOutput(t,e.shape,"float32")},t.prototype.int=function(e){Ol(e,"int");for(var t=new Int32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=n[r];return this.makeOutput(t,e.shape,"int32")},t.prototype.sigmoid=function(e){Ol(e,"sigmoid");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(t,e.shape,"float32")},t.prototype.softplus=function(e){Ol(e,"softplus");for(var t=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(e.size),r=this.readSync(e.dataId),i=0;i<r.length;++i){var o,a=r[i]>-t,s=r[i]<t,c=Math.exp(r[i]);o=s?c:a?r[i]:Math.log(1+c),n[i]=o}return this.makeOutput(n,e.shape,"float32")},t.prototype.sin=function(e){Ol(e,"sin");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.sin(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.cos=function(e){Ol(e,"cos");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.cos(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.tan=function(e){Ol(e,"tan");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.tan(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.asin=function(e){Ol(e,"asin");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.asin(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.acos=function(e){Ol(e,"acos");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.acos(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.atan=function(e){Ol(e,"atan");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.atan(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.atan2=function(e,t){return Ol([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,(function(e,t){return Math.atan2(e,t)}))},t.prototype.sinh=function(e){Ol(e,"sinh");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.sinh(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.cosh=function(e){Ol(e,"cosh");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.cosh(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.tanh=function(e){Ol(e,"tanh");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=A(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.asinh=function(e){Ol(e,"asinh");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.asinh(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.acosh=function(e){Ol(e,"acosh");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.acosh(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.atanh=function(e){Ol(e,"atanh");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r)t[r]=Math.atanh(n[r]);return this.makeOutput(t,e.shape,"float32")},t.prototype.erf=function(e){Ol(e,"erf");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0;r<n.length;++r){var i=Math.sign(n[r]),o=Math.abs(n[r]),a=1/(1+.3275911*o);t[r]=i*(1-((((1.061405429*a-1.453152027)*a+1.421413741)*a-.284496736)*a+.254829592)*a*Math.exp(-o*o))}return this.makeOutput(t,e.shape,"float32")},t.prototype.step=function(e,t){void 0===t&&(t=0),Ol(e,"step");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),i=0;i<r.length;++i){var o=r[i];isNaN(o)?n[i]=NaN:n[i]=o>0?1:t}return this.makeOutput(n,e.shape,"float32")},t.prototype.fusedConv2d=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,o=e.activation,a=e.preluActivationWeights,s=this.conv2d(t,n,r);return i&&(s=this.add(s,i)),o&&(s=Al(this,s,o,a)),s},t.prototype.conv2d=function(e,t,n){Ol([e,t],"conv2d");for(var r=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,c=n.padInfo.top,u="channelsLast"===n.dataFormat,d=pr(n.outShape,e.dtype),l=e.strides[0],p=u?e.strides[1]:e.strides[2],h=u?e.strides[2]:1,f=u?1:e.strides[1],m=d.strides[0],g=u?d.strides[1]:d.strides[2],v=u?d.strides[2]:1,y=u?1:d.strides[1],b=this.readSync(e.dataId),w=this.readSync(t.dataId),x=d.values,_=0;_<n.batchSize;++_)for(var S=_*l,R=_*m,C=0;C<n.outHeight;++C)for(var E=R+C*g,k=C*n.strideHeight-c,T=0;T<r;T++){var D=k+T*o;if(!(D<0||D>=n.inHeight))for(var P=T*t.strides[0],I=S+D*p,M=0;M<n.outWidth;++M)for(var O=E+M*v,A=M*n.strideWidth-s,F=0;F<i;F++){var N=A+F*a;if(!(N<0||N>=n.inWidth))for(var L=I+N*h,B=P+F*t.strides[1],j=0;j<n.inChannels;++j){for(var W=b[L+j*f],z=0;z<n.outChannels;++z)x[O+z*y]+=W*w[B+z];B+=n.outChannels}}}return d.toTensor()},t.prototype.conv3d=function(e,t,n){for(var r=n.filterDepth,i=n.filterHeight,o=n.filterWidth,a=n.dilationDepth,s=n.dilationHeight,c=n.dilationWidth,u=n.padInfo.front,d=n.padInfo.left,l=n.padInfo.top,p=pr(n.outShape,e.dtype),h=this.readSync(e.dataId),f=this.readSync(t.dataId),m=p.values,g=0;g<n.batchSize;++g)for(var v=g*e.strides[0],y=g*p.strides[0],b=0;b<n.outDepth;++b)for(var w=y+b*p.strides[1],x=b*n.strideDepth-u,_=0;_<r;_++){var S=x+_*a;if(!(S<0||S>=n.inDepth))for(var R=_*t.strides[0],C=v+S*e.strides[1],E=0;E<n.outHeight;++E)for(var k=w+E*p.strides[2],T=E*n.strideHeight-l,D=0;D<i;D++){var P=T+D*s;if(!(P<0||P>=n.inHeight))for(var I=R+D*t.strides[1],M=C+P*e.strides[2],O=0;O<n.outWidth;++O)for(var A=k+O*n.outChannels,F=O*n.strideWidth-d,N=0;N<o;N++){var L=F+N*c;if(!(L<0||L>=n.inWidth))for(var B=I+N*t.strides[2],j=M+L*n.inChannels,W=B,z=0;z<n.inChannels;++z){for(var U=h[j+z],V=0;V<n.outChannels;++V)m[A+V]+=U*f[W+V];W+=n.outChannels}}}}return p.toTensor()},t.prototype.conv2dDerInput=function(e,t,n){Ol([e,t],"conv2dDerInput");for(var r=pr(n.inShape,"float32"),i=r.values,o=this.readSync(e.dataId),a=this.readSync(t.dataId),s=t.strides,c=s[0],u=s[1],d=s[2],l=n.batchSize,p=n.filterHeight,h=n.filterWidth,f=n.inChannels,m=n.inHeight,g=n.inWidth,v=n.outChannels,y=n.outHeight,b=n.outWidth,w=n.strideHeight,x=n.strideWidth,_=n.dataFormat,S=p-1-n.padInfo.top,R=h-1-n.padInfo.left,C="channelsLast"===_,E=r.strides[0],k=C?r.strides[1]:r.strides[2],T=C?r.strides[2]:1,D=C?1:r.strides[1],P=e.strides[0],I=C?e.strides[1]:e.strides[2],M=C?e.strides[2]:1,O=C?1:e.strides[1],A=0;A<l;++A)for(var F=0;F<f;++F)for(var N=0;N<m;++N)for(var L=N-S,B=Math.max(0,Math.ceil(L/w)),j=Math.min(y,(p+L)/w),W=0;W<g;++W){for(var z=W-R,U=Math.max(0,Math.ceil(z/x)),V=Math.min(b,(h+z)/x),G=0,q=B;q<j;++q)for(var H=q*w-L,K=U;K<V;++K)for(var X=P*A+I*q+M*K,$=c*(p-1-H)+u*(h-1-(K*x-z))+d*F,Y=0;Y<v;++Y)G+=o[X+O*Y]*a[$+Y];i[E*A+k*N+T*W+D*F]=G}return r.toTensor()},t.prototype.conv3dDerInput=function(e,t,n){for(var r=pr(n.inShape,"float32"),i=r.values,o=r.strides,a=o[0],s=o[1],c=o[2],u=o[3],d=this.readSync(e.dataId),l=e.strides,p=l[0],h=l[1],f=l[2],m=l[3],g=this.readSync(t.dataId),v=t.strides,y=v[0],b=v[1],w=v[2],x=v[3],_=n.batchSize,S=n.filterDepth,R=n.filterHeight,C=n.filterWidth,E=n.inChannels,k=n.inDepth,T=n.inHeight,D=n.inWidth,P=n.outChannels,I=n.outDepth,M=n.outHeight,O=n.outWidth,A=n.strideDepth,F=n.strideHeight,N=n.strideWidth,L=S-1-n.padInfo.front,B=R-1-n.padInfo.top,j=C-1-n.padInfo.left,W=0;W<_;++W)for(var z=0;z<E;++z)for(var U=0;U<k;++U)for(var V=U-L,G=Math.max(0,Math.ceil(V/A)),q=Math.min(I,(S+V)/A),H=0;H<T;++H)for(var K=H-B,X=Math.max(0,Math.ceil(K/F)),$=Math.min(M,(R+K)/F),Y=0;Y<D;++Y){for(var Q=Y-j,J=Math.max(0,Math.ceil(Q/N)),Z=Math.min(O,(C+Q)/N),ee=0,te=G;te<q;++te)for(var ne=te*A-V,re=X;re<$;++re)for(var ie=re*F-K,oe=J;oe<Z;++oe)for(var ae=p*W+h*te+f*re+m*oe,se=y*(S-1-ne)+b*(R-1-ie)+w*(C-1-(oe*N-Q))+x*z,ce=0;ce<P;++ce)ee+=d[ae+ce]*g[se+ce];i[a*W+s*U+c*H+u*Y+z]=ee}return r.toTensor()},t.prototype.conv2dDerFilter=function(e,t,n){Ol([e,t],"conv2dDerFilter");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s="channelsLast"===n.dataFormat,c=pr(n.filterShape,"float32"),u=n.padInfo.left,d=n.padInfo.top,l=this.bufferSync(e),p=this.bufferSync(t),h=0;h<o;++h)for(var f=Math.max(0,Math.ceil((d-h)/r)),m=Math.min(n.outHeight,(n.inHeight+d-h)/r),g=0;g<a;++g)for(var v=Math.max(0,Math.ceil((u-g)/i)),y=Math.min(n.outWidth,(n.inWidth+u-g)/i),b=0;b<n.inChannels;++b)for(var w=0;w<n.outChannels;++w){for(var x=0,_=0;_<n.batchSize;++_)for(var S=f;S<m;++S)for(var R=h+S*r-d,C=v;C<y;++C){var E=g+C*i-u;x+=s?l.get(_,R,E,b)*p.get(_,S,C,w):l.get(_,b,R,E)*p.get(_,w,S,C)}c.set(x,h,g,b,w)}return c.toTensor()},t.prototype.conv3dDerFilter=function(e,t,n){for(var r=n.strideDepth,i=n.strideHeight,o=n.strideWidth,a=n.filterDepth,s=n.filterHeight,c=n.filterWidth,u=pr(n.filterShape,"float32"),d=u.values,l=u.strides,p=l[0],h=l[1],f=l[2],m=l[3],g=this.readSync(t.dataId),v=t.strides,y=v[0],b=v[1],w=v[2],x=v[3],_=this.readSync(e.dataId),S=e.strides,R=S[0],C=S[1],E=S[2],k=S[3],T=n.padInfo.front,D=n.padInfo.left,P=n.padInfo.top,I=0;I<a;++I)for(var M=Math.max(0,Math.ceil((T-I)/r)),O=Math.min(n.outDepth,(n.inDepth+T-I)/r),A=I*p,F=0;F<s;++F)for(var N=Math.max(0,Math.ceil((P-F)/i)),L=Math.min(n.outHeight,(n.inHeight+P-F)/i),B=F*h+A,j=0;j<c;++j)for(var W=Math.max(0,Math.ceil((D-j)/o)),z=Math.min(n.outWidth,(n.inWidth+D-j)/o),U=j*f+B,V=0;V<n.inChannels;++V)for(var G=V*m+U,q=0;q<n.outChannels;++q){for(var H=0,K=0;K<n.batchSize;++K)for(var X=K*R,$=K*y,Y=M;Y<O;++Y)for(var Q=(I+Y*r-T)*C+X,J=Y*b+$,Z=N;Z<L;++Z)for(var ee=(F+Z*i-P)*E+Q,te=Z*w+J,ne=W;ne<z;++ne){var re=ne*x+te;H+=_[(j+ne*o-D)*k+ee+V]*g[re+q]}d[G+q]=H}return u.toTensor()},t.prototype.fusedDepthwiseConv2D=function(e){var t=e.input,n=e.filter,r=e.convInfo,i=e.bias,o=e.activation,a=e.preluActivationWeights,s=this.depthwiseConv2D(t,n,r);return i&&(s=this.add(s,i)),o&&(s=Al(this,s,o,a)),s},t.prototype.depthwiseConv2D=function(e,t,n){Ol([e,t],"depthwiseConv2D");for(var r=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,c=n.padInfo.top,u=n.outChannels/n.inChannels,d=pr(n.outShape,e.dtype),l=this.readSync(e.dataId),p=this.readSync(t.dataId),h=d.values,f=0;f<n.batchSize;++f)for(var m=f*e.strides[0],g=f*d.strides[0],v=0;v<n.outHeight;++v)for(var y=g+v*d.strides[1],b=v*n.strideHeight-s,w=0;w<r;++w){var x=b+w*o;if(!(x<0||x>=n.inHeight))for(var _=w*t.strides[0],S=m+x*e.strides[1],R=0;R<n.outWidth;++R)for(var C=y+R*d.strides[2],E=R*n.strideWidth-c,k=0;k<i;++k){var T=E+k*a;if(!(T<0||T>=n.inWidth))for(var D=_+k*t.strides[1],P=S+T*n.inChannels,I=C,M=D,O=0;O<n.inChannels;++O){for(var A=l[P+O],F=0;F<u;++F)h[I+F]+=A*p[M+F];I+=u,M+=u}}}return d.toTensor()},t.prototype.depthwiseConv2DDerInput=function(e,t,n){Ol([e,t],"depthwiseConv2DDerInput");for(var r=pr(n.inShape,"float32"),i=r.values,o=r.strides,a=o[0],s=o[1],c=o[2],u=this.readSync(e.dataId),d=e.strides,l=d[0],p=d[1],h=d[2],f=this.readSync(t.dataId),m=t.strides,g=m[0],v=m[1],y=m[2],b=n.batchSize,w=n.filterHeight,x=n.filterWidth,_=n.inChannels,S=n.inHeight,R=n.inWidth,C=n.outChannels,E=n.outHeight,k=n.outWidth,T=n.strideHeight,D=n.strideWidth,P=w-1-n.padInfo.top,I=x-1-n.padInfo.left,M=C/_,O=0;O<b;++O)for(var A=0;A<_;++A)for(var F=0;F<S;++F)for(var N=F-P,L=Math.max(0,Math.ceil(N/T)),B=Math.min(E,(w+N)/T),j=0;j<R;++j){for(var W=j-I,z=Math.max(0,Math.ceil(W/D)),U=Math.min(k,(x+W)/D),V=0,G=L;G<B;++G)for(var q=G*T-N,H=z;H<U;++H)for(var K=l*O+p*G+h*H,X=g*(w-1-q)+v*(x-1-(H*D-W))+y*A,$=0;$<M;++$)V+=u[K+(A*M+$)]*f[X+$];i[a*O+s*F+c*j+A]=V}return r.toTensor()},t.prototype.depthwiseConv2DDerFilter=function(e,t,n){Ol([e,t],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s=pr(n.filterShape,"float32"),c=n.padInfo.left,u=n.padInfo.top,d=n.outChannels/n.inChannels,l=this.bufferSync(e),p=this.bufferSync(t),h=0;h<o;++h)for(var f=Math.max(0,Math.ceil((u-h)/r)),m=Math.min(n.outHeight,(n.inHeight+u-h)/r),g=0;g<a;++g)for(var v=Math.max(0,Math.ceil((c-g)/i)),y=Math.min(n.outWidth,(n.inWidth+c-g)/i),b=0;b<n.outChannels;++b){for(var w=Math.trunc(b/d),x=b%d,_=0,S=0;S<n.batchSize;++S)for(var R=f;R<m;++R)for(var C=h+R*r-u,E=v;E<y;++E){var k=g+E*i-c;_+=l.get(S,C,k,w)*p.get(S,R,E,b)}s.set(_,h,g,w,x)}return s.toTensor()},t.prototype.tile=function(e,t){return Ol(e,"tile"),Qi(this.bufferSync(e),t)},t.prototype.pad=function(e,t,n){Ol(e,"pad");var r=t.map((function(t,n){return t[0]+e.shape[n]+t[1]})),i=t.map((function(e){return e[0]})),o=this.bufferSync(e),a=pr(r,e.dtype);0!==n&&a.values.fill(n);for(var s=0;s<e.size;s++){var c=o.indexToLoc(s),u=c.map((function(e,t){return e+i[t]}));a.set.apply(a,[o.get.apply(o,c)].concat(u))}return a.toTensor()},t.prototype.transpose=function(e,t){Ol(e,"transpose");for(var n=new Array(e.rank),r=0;r<n.length;r++)n[r]=e.shape[t[r]];var i=this.readSync(e.dataId),o=pr(n,e.dtype),a=this.bufferSync(e);for(r=0;r<e.size;++r){for(var s=a.indexToLoc(r),c=new Array(s.length),u=0;u<c.length;u++)c[u]=s[t[u]];var d=o.locToIndex(c);o.values[d]=i[r]}return o.toTensor()},t.prototype.gather=function(e,t,n){Ol([e,t],"gather");var r=e.shape.slice(),i=this.readSync(t.dataId);r[n]=i.length;for(var o=pr(r,e.dtype),a=this.bufferSync(e),s=0;s<o.size;++s){var c=o.indexToLoc(s),u=c.slice();u[n]=i[c[n]];var d=a.locToIndex(u);o.values[s]=a.values[d]}return o.toTensor()},t.prototype.batchToSpaceND=function(e,t,n){Ol([e],"batchToSpaceND");var r=t.reduce((function(e,t){return e*t})),i=zr(e.shape,t,r),o=Ur(i.length,t.length),a=Vr(e.shape,t,r),s=Gr(n,t.length),c=qr(a,n,t.length);return e.reshape(i).transpose(o).reshape(a).slice(s,c)},t.prototype.spaceToBatchND=function(e,t,n){Ol([e],"spaceToBatchND");var r=t.reduce((function(e,t){return e*t})),i=[[0,0]];i.push.apply(i,n);for(var o=1+t.length;o<e.shape.length;++o)i.push([0,0]);var a=e.pad(i),s=zr(a.shape,t,r,!1),c=Ur(s.length,t.length,!1),u=Vr(a.shape,t,r,!1);return a.reshape(s).transpose(c).reshape(u)},t.prototype.pool=function(e,t,n){Ol(e,"pool");for(var r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterHeight,c=t.effectiveFilterWidth,u=t.padInfo.top,d=t.padInfo.left,l="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,p=this.readSync(e.dataId),h=pr(t.outShape,e.dtype),f=h.values,m=t.outShape[1]*t.outShape[2]*t.outShape[3],g=t.outShape[2]*t.outShape[3],v=t.outShape[3],y=0;y<t.batchSize;++y)for(var b=y*m,w=y*e.strides[0],x=0;x<t.inChannels;++x)for(var _=0;_<t.outHeight;++_)for(var S=_*r-u,R=Math.max(0,S),C=Math.min(t.inHeight,s+S),E=b+_*g,k=0;k<t.outWidth;++k){for(var T=k*i-d,D=Math.max(0,T),P=Math.min(t.inWidth,c+T),I=l,M=0,O=0,A=R;A<C;A+=o){for(var F=w+A*e.strides[1],N=D;N<P;N+=a){var L=p[F+N*e.strides[2]+x];"max"===n&&L>I?I=L:"avg"===n&&(M+=L,O++)}if(isNaN(I))break}f[E+k*v+x]="avg"===n?M/O:I}return h.toTensor()},t.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},t.prototype.maxPoolPositions=function(e,t){for(var n=pr(t.outShape,"int32"),r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterHeight,c=t.effectiveFilterWidth,u=t.padInfo.top,d=t.padInfo.left,l=this.bufferSync(e),p=0;p<t.batchSize;++p)for(var h=0;h<t.inChannels;++h)for(var f=0;f<t.outHeight;++f){for(var m=f*r-u,g=m;g<0;)g+=o;for(var v=Math.min(t.inHeight,s+m),y=0;y<t.outWidth;++y){for(var b=y*i-d,w=b;w<0;)w+=a;for(var x=Math.min(t.inWidth,c+b),_=Number.NEGATIVE_INFINITY,S=-1,R=g;R<v;R+=o)for(var C=R-m,E=w;E<x;E+=a){var k=E-b,T=l.get(p,R,E,h);T>_&&(_=T,S=C*c+k)}n.set(S,p,f,y,h)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(e,t,n,r){Ol([t,n],"maxPoolBackprop");for(var i=this.maxPoolPositions(t,r),o=r.strideHeight,a=r.strideWidth,s=r.dilationHeight,c=r.dilationWidth,u=r.effectiveFilterHeight,d=r.effectiveFilterWidth,l=d-1-r.padInfo.left,p=u-1-r.padInfo.top,h=pr(t.shape,"float32"),f=this.bufferSync(i),m=this.bufferSync(e),g=0;g<r.batchSize;++g)for(var v=0;v<r.inChannels;++v)for(var y=0;y<r.inHeight;++y)for(var b=0;b<r.inWidth;++b){for(var w=y-p,x=b-l,_=0,S=0;S<u;S+=s){var R=(w+S)/o;if(!(R<0||R>=r.outHeight||Math.floor(R)!==R))for(var C=0;C<d;C+=c){var E=(x+C)/a;if(!(E<0||E>=r.outWidth||Math.floor(E)!==E)){var k=u*d-1-f.get(g,R,E,v)===S*d+C?1:0;0!==k&&(_+=m.get(g,R,E,v)*k)}}}h.set(_,g,y,b,v)}return h.toTensor()},t.prototype.avgPoolBackprop=function(e,t,n){Ol([e,t],"avgPoolBackprop");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s=n.dilationHeight,c=n.dilationWidth,u=n.effectiveFilterHeight,d=n.effectiveFilterWidth,l=d-1-n.padInfo.left,p=u-1-n.padInfo.top,h=pr(t.shape,"float32"),f=1/(o*a),m=this.bufferSync(e),g=0;g<n.batchSize;++g)for(var v=0;v<n.inChannels;++v)for(var y=0;y<n.inHeight;++y)for(var b=0;b<n.inWidth;++b){for(var w=y-p,x=b-l,_=0,S=0;S<u;S+=s){var R=(w+S)/r;if(!(R<0||R>=n.outHeight||Math.floor(R)!==R))for(var C=0;C<d;C+=c){var E=(x+C)/i;E<0||E>=n.outWidth||Math.floor(E)!==E||(_+=m.get(g,R,E,v))}}h.set(_*f,g,y,b,v)}return h.toTensor()},t.prototype.pool3d=function(e,t,n){Ol(e,"pool3d");for(var r=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,s=t.dilationHeight,c=t.dilationWidth,u=t.effectiveFilterDepth,d=t.effectiveFilterHeight,l=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left,m="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(e.dataId),v=pr(t.outShape,e.dtype),y=v.values,b=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],w=t.outShape[2]*t.outShape[3]*t.outShape[4],x=t.outShape[3]*t.outShape[4],_=t.outShape[4],S=0;S<t.batchSize;++S)for(var R=S*b,C=S*e.strides[0],E=0;E<t.inChannels;++E)for(var k=0;k<t.outDepth;++k){for(var T=k*r-p,D=T;D<0;)D+=a;for(var P=Math.min(t.inDepth,u+T),I=R+k*w,M=0;M<t.outHeight;++M){for(var O=M*i-h,A=O;A<0;)A+=s;for(var F=Math.min(t.inHeight,d+O),N=I+M*x,L=0;L<t.outWidth;++L){for(var B=L*o-f,j=B;j<0;)j+=c;for(var W=Math.min(t.inWidth,l+B),z=N+L*_,U=m,V=0,G=0,q=D;q<P;q+=a){for(var H=C+q*e.strides[1],K=A;K<F;K+=s){for(var X=H+K*e.strides[2],$=j;$<W;$+=c){var Y=g[X+$*e.strides[3]+E];if("max"===n&&Y>U?U=Y:"avg"===n&&(V+=Y,G++),isNaN(U))break}if(isNaN(U))break}if(isNaN(U))break}y[z+E]="avg"===n?V/G:U}}}return v.toTensor()},t.prototype.avgPool3d=function(e,t){return Ol(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(e,t,n){Ol([e,t],"avgPool3dBackprop");for(var r=n.strideDepth,i=n.strideHeight,o=n.strideWidth,a=n.filterDepth,s=n.filterHeight,c=n.filterWidth,u=n.dilationDepth,d=n.dilationHeight,l=n.dilationWidth,p=n.effectiveFilterDepth,h=n.effectiveFilterHeight,f=n.effectiveFilterWidth,m=p-1-n.padInfo.front,g=f-1-n.padInfo.left,v=h-1-n.padInfo.top,y=pr(t.shape,"float32"),b=1/(a*s*c),w=this.bufferSync(e),x=0;x<n.batchSize;++x)for(var _=0;_<n.inChannels;++_)for(var S=0;S<n.inDepth;++S)for(var R=0;R<n.inHeight;++R)for(var C=0;C<n.inWidth;++C){for(var E=S-m,k=R-v,T=C-g,D=0,P=0;P<p;P+=u){var I=(E+P)/r;if(!(I<0||I>=n.outDepth||Math.floor(I)!==I))for(var M=0;M<h;M+=d){var O=(k+M)/i;if(!(O<0||O>=n.outHeight||Math.floor(O)!==O))for(var A=0;A<f;A+=l){var F=(T+A)/o;F<0||F>=n.outWidth||Math.floor(F)!==F||(D+=w.get(x,I,O,F,_))}}}y.set(D*b,x,S,R,C,_)}return y.toTensor()},t.prototype.maxPool3d=function(e,t){return Ol(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()},t.prototype.maxPool3dPositions=function(e,t){for(var n=pr(t.outShape,"int32"),r=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,s=t.dilationHeight,c=t.dilationWidth,u=t.effectiveFilterDepth,d=t.effectiveFilterHeight,l=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left,m=this.bufferSync(e),g=0;g<t.batchSize;++g)for(var v=0;v<t.inChannels;++v)for(var y=0;y<t.outDepth;++y){for(var b=y*r-p,w=b;w<0;)w+=a;for(var x=Math.min(t.inDepth,u+b),_=0;_<t.outHeight;++_){for(var S=_*i-h,R=S;R<0;)R+=s;for(var C=Math.min(t.inHeight,d+S),E=0;E<t.outWidth;++E){for(var k=E*o-f,T=k;T<0;)T+=c;for(var D=Math.min(t.inWidth,l+k),P=Number.NEGATIVE_INFINITY,I=-1,M=w;M<x;M+=a)for(var O=M-b,A=R;A<C;A+=s)for(var F=A-S,N=T;N<D;N+=c){var L=N-k,B=m.get(g,M,A,N,v);B>=P&&(P=B,I=O*d*l+F*d+L)}n.set(I,g,y,_,E,v)}}}return n.toTensor()},t.prototype.maxPool3dBackprop=function(e,t,n,r){Ol([t,n],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(t,r),o=r.strideDepth,a=r.strideHeight,s=r.strideWidth,c=r.dilationDepth,u=r.dilationHeight,d=r.dilationWidth,l=r.effectiveFilterDepth,p=r.effectiveFilterHeight,h=r.effectiveFilterWidth,f=l-1-r.padInfo.front,m=h-1-r.padInfo.left,g=p-1-r.padInfo.top,v=pr(t.shape,"float32"),y=this.bufferSync(i),b=this.bufferSync(e),w=0;w<r.batchSize;++w)for(var x=0;x<r.inChannels;++x)for(var _=0;_<r.inDepth;++_)for(var S=0;S<r.inHeight;++S)for(var R=0;R<r.inWidth;++R){for(var C=_-f,E=S-g,k=R-m,T=0,D=0;D<l;D+=c){var P=(C+D)/o;if(!(P<0||P>=r.outDepth||Math.floor(P)!==P))for(var I=0;I<p;I+=u){var M=(E+I)/a;if(!(M<0||M>=r.outHeight||Math.floor(M)!==M))for(var O=0;O<h;O+=d){var A=(k+O)/s;if(!(A<0||A>=r.outWidth||Math.floor(A)!==A)){var F=l*p*h-1-y.get(w,P,M,A,x)===D*p*h+I*h+O?1:0;0!==F&&(T+=b.get(w,P,M,A,x)*F)}}}}v.set(T,w,_,S,R,x)}return v.toTensor()},t.prototype.cast=function(e,t){return Ai(e,t,this)},t.prototype.reshape=function(e,t){return Fi(e,t)},t.prototype.avgPool=function(e,t){return Ol(e,"avgPool"),this.pool(e,t,"avg").toFloat()},t.prototype.resizeBilinear=function(e,t,n,r){Ol(e,"resizeBilinear");for(var i=e.shape,o=i[0],a=i[1],s=i[2],c=i[3],u=this.readSync(e.dataId),d=new Float32Array(I([o,t,n,c])),l=[r&&t>1?a-1:a,r&&n>1?s-1:s],p=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=0,f=l[0]/p[0],m=l[1]/p[1],g=0;g<o;g++)for(var v=0;v<t;v++)for(var y=f*v,b=Math.floor(y),w=y-b,x=Math.min(a-1,Math.ceil(y)),_=g*e.strides[0]+b*e.strides[1],S=g*e.strides[0]+x*e.strides[1],R=0;R<n;R++)for(var C=m*R,E=Math.floor(C),k=C-E,T=Math.min(s-1,Math.ceil(C)),D=_+E*e.strides[2],P=S+E*e.strides[2],M=_+T*e.strides[2],O=S+T*e.strides[2],A=0;A<c;A++){var F=u[D+A],N=u[P+A],L=F+(u[M+A]-F)*k,B=L+(N+(u[O+A]-N)*k-L)*w;d[h++]=B}return In(d,[o,t,n,c])},t.prototype.resizeBilinearBackprop=function(e,t,n){Ol([e,t],"resizeBilinearBackprop");for(var r=t.shape,i=r[0],o=r[1],a=r[2],s=r[3],c=e.shape,u=c[1],d=c[2],l=new Float32Array(i*o*a*s),p=[n&&u>1?o-1:o,n&&d>1?a-1:a],h=[n&&u>1?u-1:u,n&&d>1?d-1:d],f=p[0]/h[0],m=p[1]/h[1],g=this.readSync(e.dataId),v=0,y=0;y<i;y++)for(var b=y*t.strides[0],w=0;w<u;w++)for(var x=w*f,_=Math.floor(x),S=Math.min(Math.ceil(x),o-1),R=b+_*t.strides[1],C=b+S*t.strides[1],E=x-_,k=1-E,T=0;T<d;T++)for(var D=T*m,P=Math.floor(D),I=Math.min(Math.ceil(D),a-1),M=D-P,O=1-M,A=R+P*t.strides[2],F=R+I*t.strides[2],N=C+P*t.strides[2],L=C+I*t.strides[2],B=k*O,j=k*M,W=E*O,z=E*M,U=0;U<s;U++){var V=g[v++];l[A+U]+=V*B,l[F+U]+=V*j,l[N+U]+=V*W,l[L+U]+=V*z}return Ln(l,[i,a,o,s],t.dtype)},t.prototype.resizeNearestNeighbor=function(e,t,n,r){Ol(e,"resizeNearestNeighbor");for(var i=e.shape,o=i[0],a=i[1],s=i[2],c=i[3],u=this.readSync(e.dataId),d=new Float32Array(o*t*n*c),l=[r&&t>1?a-1:a,r&&n>1?s-1:s],p=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=l[0]/p[0],f=l[1]/p[1],m=0,g=0;g<o;g++)for(var v=g*e.strides[0],y=0;y<t;y++)for(var b=h*y,w=v+Math.min(a-1,r?Math.round(b):Math.floor(b))*e.strides[1],x=0;x<n;x++)for(var _=f*x,S=w+Math.min(s-1,r?Math.round(_):Math.floor(_))*e.strides[2],R=0;R<c;R++){var C=u[S+R];d[m++]=C}return In(d,[o,t,n,c],e.dtype)},t.prototype.resizeNearestNeighborBackprop=function(e,t,n){Ol([e,t],"resizeNearestNeighborBackprop");for(var r=t.shape,i=r[0],o=r[1],a=r[2],s=r[3],c=e.shape,u=c[1],d=c[2],l=new Float32Array(i*o*a*s),p=this.readSync(e.dataId),h=[n&&u>1?o-1:o,n&&d>1?a-1:a],f=[n&&u>1?u-1:u,n&&d>1?d-1:d],m=h[0]/f[0],g=h[1]/f[1],v=1/m,y=1/g,b=2*Math.ceil(v)+2,w=2*Math.ceil(y)+2,x=0;x<i;x++)for(var _=x*t.strides[0],S=0;S<o;S++)for(var R=_+S*t.strides[1],C=Math.floor(S*v),E=Math.floor(C-b/2),k=0;k<a;k++)for(var T=R+k*t.strides[2],D=Math.floor(k*y),P=Math.floor(D-w/2),I=0;I<s;I++){for(var M=0,O=0;O<b;O++){var A=O+E;if(!(A<0||A>=u)){var F=_+A*e.strides[1],N=A*m;if(S===Math.min(o-1,n?Math.round(N):Math.floor(N)))for(var L=0;L<w;L++){var B=L+P;if(!(B<0||B>=d)){var j=F+B*e.strides[2],W=B*g;k===Math.min(a-1,n?Math.round(W):Math.floor(W))&&(M+=p[j+I])}}}}l[T+I]=M}return Ln(l,t.shape,t.dtype)},t.prototype.batchNormalization=function(e,t,n,r,i,o){Ol([e,t,n,i,o],"batchNorm");for(var a=this.readSync(e.dataId),s=this.readSync(t.dataId),c=this.readSync(n.dataId),u=i?this.readSync(i.dataId):new Float32Array([1]),d=o?this.readSync(o.dataId):new Float32Array([0]),l=new Float32Array(a.length),p=d.length,h=u.length,f=c.length,m=s.length,g=0,v=0,y=0,b=0,w=0;w<a.length;++w)l[w]=d[g++]+(a[w]-s[v++])*u[y++]/Math.sqrt(c[b++]+r),g>=p&&(g=0),v>=m&&(v=0),y>=h&&(y=0),b>=f&&(b=0);return Ln(l,e.shape)},t.prototype.localResponseNormalization4D=function(e,t,n,r,i){Ol(e,"localResponseNormalization4D");var o=e.shape[3],a=o-1,s=this.readSync(e.dataId),c=e.size,u=new Float32Array(c);function d(e){for(var n=e%o,r=e-n+Math.max(0,n-t),i=e-n+Math.min(n+t,a),c=0;r<=i;r++){var u=s[r];c+=u*u}return c}for(var l=0;l<c;l++){var p=d(l),h=s[l]*Math.pow(n+r*p,-i);u[l]=h}return Ln(u,e.shape)},t.prototype.LRNGrad=function(e,t,n,r,i,o,a){Ol(e,"LRNGrad");for(var s=e.shape[3],c=this.readSync(e.dataId),u=this.readSync(t.dataId),d=this.readSync(n.dataId),l=new Float32Array(e.size),p=e.size,h=0;h<p;h++){for(var f=h%s,m=h-f+Math.max(0,f-r),g=h-f+Math.min(s,f+r+1),v=0,y=m;y<g;y++)v+=Math.pow(u[y],2);for(v=o*v+i,y=m;y<g;y++){var b=-2*o*a*u[y]*d[h]/v;h===y&&(b+=Math.pow(v,-a)),b*=c[h],l[y]+=b}}return Ln(l,e.shape)},t.prototype.multinomial=function(e,t,n,r){Ol(e,"multinomial");for(var i=t?e:fi(e),o=i.shape[0],a=i.shape[1],s=Un([o,n],"int32"),c=this.readSync(s.dataId),u=this.readSync(i.dataId),d=0;d<o;++d){var l=d*a,p=new Float32Array(a-1);p[0]=u[l];for(var h=1;h<p.length;++h)p[h]=p[h-1]+u[l+h];for(var f=cr(r.toString()),m=d*n,g=0;g<n;++g){var v=f();c[m+g]=p.length;for(var y=0;y<p.length;y++)if(v<p[y]){c[m+g]=y;break}}}return s},t.prototype.oneHot=function(e,t,n,r){Ol(e,"oneHot");var i=new Float32Array(e.size*t);i.fill(r);for(var o=this.readSync(e.dataId),a=0;a<e.size;++a)o[a]>=0&&o[a]<t&&(i[a*t+o[a]]=n);return Fn(i,[e.size,t],"int32")},t.prototype.nonMaxSuppression=function(e,t,n,r,i){return Ol(e,"nonMaxSuppression"),Gi(this.readSync(e.dataId),this.readSync(t.dataId),n,r,i)},t.prototype.fft=function(e){return this.fftBatch(e,!1)},t.prototype.ifft=function(e){return this.fftBatch(e,!0)},t.prototype.fftBatch=function(e,t){for(var n=e.shape[0],r=e.shape[1],i=pr(e.shape,"float32"),o=pr(e.shape,"float32"),a=Dn(e).as2D(n,r),s=Pn(e).as2D(n,r),c=0;c<n;c++)for(var u=a.slice([c,0],[1,r]),d=s.slice([c,0],[1,r]),l=Tn(u,d),p=this.readSync(this.fftImpl(l,t).dataId),h=0;h<r;h++){var f=ji(p,h);i.values[c*r+h]=f.real,o.values[c*r+h]=f.imag}return Tn(i.toTensor(),o.toTensor()).as2D(n,r)},t.prototype.fftImpl=function(e,t){var n=e.as1D(),r=n.size;if(this.isExponentOf2(r)){var i=this.fftRadix2(n,r,t).as2D(e.shape[0],e.shape[1]);return t&&(i=Tn(Dn(i).div(On(r)),Pn(i).div(On(r)))),i}var o=this.readSync(e.dataId),a=function(e){for(var t=new Float32Array(e.length/2),n=new Float32Array(e.length/2),r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}(this.fourierTransformByMatmul(o,r,t));return Tn(a.real,a.imag).as2D(e.shape[0],e.shape[1])},t.prototype.isExponentOf2=function(e){return!(e&e-1)},t.prototype.fftRadix2=function(e,t,n){if(1===t)return e;var r=this.readSync(e.dataId),i=t/2,o=function(e){for(var t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t),i=0;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],r[Math.floor(i/4)]=e[i+1];return{real:n,imag:r}}(r),a=Tn(o.real,o.imag).as1D(),s=function(e){for(var t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t),i=2;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],r[Math.floor(i/4)]=e[i+1];return{real:n,imag:r}}(r),c=Tn(s.real,s.imag).as1D();a=this.fftRadix2(a,i,n),c=this.fftRadix2(c,i,n);var u=function(e,t){for(var n=new Float32Array(e/2),r=new Float32Array(e/2),i=0;i<Math.ceil(e/2);i++){var o=(t?2:-2)*Math.PI*(i/e);n[i]=Math.cos(o),r[i]=Math.sin(o)}return{real:n,imag:r}}(t,n),d=Tn(u.real,u.imag).mul(c),l=a.add(d),p=a.sub(d),h=Dn(l).concat(Dn(p)),f=Pn(l).concat(Pn(p));return Tn(h,f).as1D()},t.prototype.fourierTransformByMatmul=function(e,t,n){for(var r=new Float32Array(2*t),i=0;i<t;i++){for(var o=0,a=0,s=0;s<t;s++){var c=zi(i*s,t,n),u=ji(e,s);o+=u.real*c.real-u.imag*c.imag,a+=u.real*c.imag+u.imag*c.real}n&&(o/=t,a/=t),Wi(r,o,a,i)}return r},t.prototype.depthToSpace=function(e,t,n){k("NHWC"===n,(function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n})),k(t>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+t}));for(var r=e.shape[0],i=e.shape[1],o=e.shape[2],a=e.shape[3],s=i*t,c=o*t,u=a/(t*t),d=this.readSync(e.dataId),l=new Float32Array(r*s*c*u),p=0,h=0;h<r;++h)for(var f=0;f<s;++f)for(var m=Math.floor(f/t),g=f%t,v=0;v<c;++v)for(var y=Math.floor(v/t),b=(g*t+v%t)*u,w=0;w<u;++w){var x=w+b+a*(y+o*(m+i*h));l[p++]=d[x]}return Ln(l,[r,s,c,u])},t.prototype.broadcastedBinaryOp=function(e,t,n,r){var i=xi(e.shape,t.shape),o=pr(i,n),a=this.readSync(e.dataId),s=this.readSync(t.dataId),c=bi(e.shape,i),u=bi(t.shape,i),d=o.values;if(c.length+u.length===0)for(var l=0;l<d.length;++l)d[l]=r(a[l%a.length],s[l%s.length]);else{var p=this.bufferSync(e),h=this.bufferSync(t),f=function(n){var i=o.indexToLoc(n),l=i.slice(-e.rank);c.forEach((function(e){return l[e]=0}));var f=p.locToIndex(l),m=i.slice(-t.rank);u.forEach((function(e){return m[e]=0}));var g=h.locToIndex(m);d[n]=r(a[f],s[g])};for(l=0;l<d.length;++l)f(l)}return o.toTensor()},t.prototype.broadcastedBinaryComplexOp=function(e,t,n){var r=xi(e.shape,t.shape),i=pr(r,"float32"),o=pr(r,"float32"),a=this.readSync(e.dataId),s=this.readSync(t.dataId),c=bi(e.shape,r),u=bi(t.shape,r),d=i.values,l=o.values;if(c.length+u.length===0)for(var p=0;p<d.length;p++){var h=p%a.length,f=p%s.length,m=n(a[2*h],a[2*h+1],s[2*f],s[2*f+1]);d[p]=m.real,l[p]=m.imag}else{var g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),v=this.bufferSync(this.data.get(t.dataId).complexTensors.real),y=function(r){var o=i.indexToLoc(r),p=o.slice(-e.rank);c.forEach((function(e){return p[e]=0}));var h=g.locToIndex(p),f=o.slice(-t.rank);u.forEach((function(e){return f[e]=0}));var m=v.locToIndex(f),y=n(a[2*h],a[2*h+1],s[2*m],s[2*m+1]);d[r]=y.real,l[r]=y.imag};for(p=0;p<d.length;p++)y(p)}return this.complex(i.toTensor(),o.toTensor())},t.prototype.split=function(e,t,n){return Yi(e,t,n)},t.prototype.dispose=function(){},t.prototype.floatPrecision=function(){return 32},t.prototype.epsilon=function(){return 1e-7},t.prototype.cropAndResize=function(e,t,n,r,i,o){for(var a=e.shape,s=a[0],c=a[1],u=a[2],d=a[3],l=t.shape[0],p=r[0],h=r[1],f=pr([l,p,h,d],"float32"),m=this.readSync(t.dataId),g=this.readSync(n.dataId),v=this.readSync(e.dataId),y=e.strides,b=f.strides,w=0;w<l;w++){var x=4*w,_=m[x],S=m[x+1],R=m[x+2],C=m[x+3],E=g[w];if(!(E>=s))for(var k=p>1?(R-_)*(c-1)/(p-1):0,T=h>1?(C-S)*(u-1)/(h-1):0,D=0;D<p;D++){var P=p>1?_*(c-1)+D*k:.5*(_+R)*(c-1);if(P<0||P>c-1)for(var I=0;I<h;I++)for(var M=0;M<d;M++){var O=M+I*b[2]+D*b[1]+w*b[0];f.values[O]=o}else if("bilinear"===i){var A=Math.floor(P),F=Math.ceil(P),N=P-A;for(I=0;I<h;I++)if((q=h>1?S*(u-1)+I*T:.5*(S+C)*(u-1))<0||q>u-1)for(M=0;M<d;M++)O=M+I*b[2]+D*b[1]+w*b[0],f.values[O]=o;else{var L=Math.floor(q),B=Math.ceil(q),j=q-L;for(M=0;M<d;M++){var W=v[O=M+L*y[2]+A*y[1]+E*y[0]],z=v[O=M+B*y[2]+A*y[1]+E*y[0]],U=v[O=M+L*y[2]+F*y[1]+E*y[0]],V=W+(z-W)*j,G=U+(v[O=M+B*y[2]+F*y[1]+E*y[0]]-U)*j;O=M+I*b[2]+D*b[1]+w*b[0],f.values[O]=V+(G-V)*N}}}else for(I=0;I<h;++I){var q;if((q=h>1?S*(u-1)+I*T:.5*(S+C)*(u-1))<0||q>u-1)for(M=0;M<d;M++)O=M+I*b[2]+D*b[1]+w*b[0],f.values[O]=o;else{var H=Math.round(q),K=Math.round(P);for(M=0;M<d;M++){var X=M+H*y[2]+K*y[1]+E*y[0],$=M+I*b[2]+D*b[1]+w*b[0];f.values[$]=v[X]}}}}}return f.toTensor()},t.prototype.sparseToDense=function(e,t,n,r){var i=Qr(0,e,n),o=i.sliceRank,a=i.numUpdates,s=i.sliceSize,c=i.strides,u=i.outputSize;return this.scatter(e,t,n,u,s,a,o,c,r,!1)},t.prototype.gatherND=function(e,t){var n=t.shape,r=n[n.length-1],i=Hr(e,t),o=i[0],a=i[1],s=i[2],c=i[3];if(0===a)return In([],o,e.dtype);for(var u=new ye([a,s],e.dtype),d=this.readSync(t.dataId),l=this.readSync(e.dataId),p=0;p<a;p++){for(var h=[],f=0,m=0;m<r;m++){var g=d[p*r+m];f+=g*c[m],h.push(g)}if(f<0||f>=e.size/s)throw new Error("Invalid indices: "+h+" does not index into "+e.shape);for(var v=0;v<s;v++)u.values[p*s+v]=l[f*s+v]}return u.toTensor().reshape(o)},t.prototype.scatterND=function(e,t,n){var r=Qr(0,e,n),i=r.sliceRank,o=r.numUpdates,a=r.sliceSize,s=r.strides,c=r.outputSize,u=On(0);return this.scatter(e,t,n,c,a,o,i,s,u,!0)},t.prototype.fill=function(e,t,n){var r=U(n=n||J(t),I(e));return r.fill(t),je.makeTensor(r,e,n,this)},t.prototype.onesLike=function(e){if("string"===e.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){var t=U(e.dtype,I(e.shape));return this.makeOutput(t,e.shape,e.dtype)},t.prototype.linspace=function(e,t,n){return Ni(e,t,n)},t.prototype.scatter=function(e,t,n,r,i,o,a,s,c,u){var d=[r/i,i],l=this.readSync(e.dataId),p=this.readSync(t.dataId);if(0===r)return In([],n,t.dtype);var h=new ye(d,t.dtype);h.values.fill(this.readSync(c.dataId)[0]);for(var f=0;f<o;f++){for(var m=[],g=0,v=0;v<a;v++){var y=l[f*a+v];m.push(y),g+=y*s[v]}if(g<0||g>=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b<i;b++)u?h.values[g*i+b]+=p[f*i+b]:h.values[g*i+b]=0===t.rank?p[0]:p[f*i+b]}return h.toTensor().reshape(n)},t}(vi);je.registerBackend("cpu",(function(){return new Fl}),1);for(var Nl=0,Ll=[{kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs,i=t,o=i.boxes,a=i.scores,s=r,c=s.maxOutputSize,u=s.iouThreshold,d=s.scoreThreshold,l=s.softNmsSigma,p=n;Ol(o,"NonMaxSuppressionWithScore");var h=qi(p.data.get(o.dataId).values,p.data.get(a.dataId).values,c,u,d,l);return[h.selectedIndices,h.selectedScores]}},{kernelName:"Square",backendName:"cpu",kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t.x,i=n;Ol(r,"square");for(var o=i.data.get(r.dataId).values,a=new Float32Array(o.length),s=0;s<o.length;++s){var c=o[s];a[s]=c*c}return{dataId:i.write(a,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},{kernelName:Hs,backendName:"cpu",kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t,i=r.a,o=r.b,a=n;Ol([i,o],Hs);var s=a.data.get(i.dataId).values,c=a.data.get(o.dataId).values,u=function(e,t,n,r,i,o){var a=xi(e,t),s=a.length,c=te(a),u=z(i,I(a)),d=e.length,l=t.length,p=te(e),h=te(t),f=bi(e,a),m=bi(t,a);if(f.length+m.length===0)for(var g=0;g<u.length;++g)u[g]=o(n[g%n.length],r[g%r.length]);else{var v=function(e){var t=le(e,s,c),i=t.slice(-d);f.forEach((function(e){return i[e]=0}));var a=de(i,d,p),g=t.slice(-l);m.forEach((function(e){return g[e]=0}));var v=de(g,l,h);u[e]=o(n[a],r[v])};for(g=0;g<u.length;++g)v(g)}return[u,a]}(i.shape,o.shape,s,c,i.dtype,(function(e,t){var n=e-t;return n*n})),d=u[0],l=u[1];return{dataId:a.write(d,l,i.dtype),shape:l,dtype:i.dtype}}}];Nl<Ll.length;Nl++)y(Ll[Nl]);for(var Bl,jl=function(e){this.variableNames=["A"];var t=oo(),n=e[0],r=e[1];this.outputShape=e,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+t.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},Wl=function(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var t=oo(),n=e[0],r=e[1];this.outputShape=e,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+r+".0, "+n+".0);\n vec4 values = "+t.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+t.output+" = result;\n }\n "},zl=0,Ul=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs,i=t.pixels,o=r.numChannels,a="undefined"!=typeof HTMLVideoElement&&i instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&i instanceof HTMLImageElement,c=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],u=c[0],d=c[1],p=[d,u],h=[d,u,o];(s||a)&&(null==Bl&&(Bl=document.createElement("canvas").getContext("2d")),Bl.canvas.width=u,Bl.canvas.height=d,Bl.drawImage(i,0,0,u,d),i=Bl.canvas);var f=n.makeTensorInfo(p,"int32");n.texData.get(f.dataId).usage=Ve.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(f.dataId),i);var m=l().getBool("WEBGL_PACK")?new Wl(h):new jl(h),g=n.runWebGLProgram(m,[f],"int32");return n.disposeData(f.dataId),g}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(e){var t=e.inputs,n=e.backend,r=e.attrs;pn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var i=t,o=i.boxes,a=i.scores,s=r,c=s.maxOutputSize,u=s.iouThreshold,d=s.scoreThreshold,l=s.softNmsSigma,p=n,h=qi(p.readSync(o.dataId),p.readSync(a.dataId),c,u,d,l);return[h.selectedIndices,h.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t.x,i=n,o=new gs(r.shape,"return x * x;");return i.runWebGLProgram(o,[r],r.dtype)}},{kernelName:Hs,backendName:"webgl",kernelFunc:function(e){var t=e.inputs,n=e.backend,r=t,i=r.a,o=r.b,a=n,s=l().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ao("return (a - b) * (a - b);",i.shape,o.shape):new Mo("return (a - b) * (a - b);",i.shape,o.shape);return a.compileAndRun(s,[i,o])}}];zl<Ul.length;zl++)y(Ul[zl]);for(var Vl=0,Gl=[{kernelName:"Square",gradFunc:function(e,t){var n=t[0];return{x:function(){return e.mul(n.toFloat().mul(2))}}}},{kernelName:Hs,gradFunc:function(e,t){var n=t[0],r=t[1],i=On(2);return{a:function(){return cu(e,cu(i,hu(n,r)))},b:function(){return cu(e,cu(i,hu(r,n)))}}}}];Vl<Gl.length;Vl++)b(Gl[Vl]);var ql=function(){function e(){}return e.prototype.fetch=function(e,t){return fetch(e,t)},e.prototype.now=function(){return performance.now()},e.prototype.encode=function(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Browser's encoder only supports utf-8, but got "+t);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)},e.prototype.decode=function(e,t){return new TextDecoder(t).decode(e)},e}();l().get("IS_BROWSER")&&l().setPlatform("browser",new ql);var Hl,Kl=function(){function e(){this.util=n(753),this.textEncoder=new this.util.TextEncoder}return e.prototype.fetch=function(e,t){return null!=l().global.fetch?l().global.fetch(e,t):(null==Hl&&(Hl=n(522)),Hl(e,t))},e.prototype.now=function(){var e=process.hrtime();return 1e3*e[0]+e[1]/1e6},e.prototype.encode=function(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Node built-in encoder only supports utf-8, but got "+t);return this.textEncoder.encode(e)},e.prototype.decode=function(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)},e}();l().get("IS_NODE")&&l().setPlatform("node",new Kl);var Xl={float32:4,int32:4,uint16:2,uint8:1,bool:1},$l=4;function Yl(e,t){for(var n={},r=0,i=function(t){var i=t.name,o=t.dtype,a=t.shape,s=I(a),c=void 0;if("quantization"in t){var u=t.quantization;if("uint8"!==u.dtype&&"uint16"!==u.dtype)throw new Error("Weight "+t.name+" has unknown quantization dtype "+u.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var d=Xl[u.dtype],l=e.slice(r,r+s*d),p="uint8"===u.dtype?new Uint8Array(l):new Uint16Array(l);if("float32"===o)c=Float32Array.from(p,(function(e){return e*u.scale+u.min}));else{if("int32"!==o)throw new Error("Unsupported dtype in weight '"+i+"': "+o);c=Int32Array.from(p,(function(e){return Math.round(e*u.scale+u.min)}))}r+=s*d}else if("string"===o){var h=I(t.shape);c=[];for(var f=0;f<h;f++){var m=new Uint32Array(e.slice(r,r+$l))[0];r+=$l;var g=new Uint8Array(e.slice(r,r+m));c.push(g),r+=m}}else{var v=Xl[o];if(l=e.slice(r,r+s*v),"float32"===o)c=new Float32Array(l);else if("int32"===o)c=new Int32Array(l);else{if("bool"!==o)throw new Error("Unsupported dtype in weight '"+i+"': "+o);c=new Uint8Array(l)}r+=s*v}n[i]=In(c,a,o)},o=0,a=t;o<a.length;o++)i(a[o]);return n}function Ql(e){if(null===e)throw new Error("Invalid input value: "+JSON.stringify(e));var t=0,n=[];e.forEach((function(e){if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+e.constructor.name)}));var r=new Uint8Array(t),i=0;return n.forEach((function(e){r.set(new Uint8Array(e.buffer),i),i+=e.byteLength})),r.buffer}var Jl="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Zl(e){return Jl?Buffer.byteLength(e):new Blob([e]).size}function ep(e){var t=0;e.forEach((function(e){t+=e.byteLength}));var n=new Uint8Array(t),r=0;return e.forEach((function(e){n.set(new Uint8Array(e),r),r+=e.byteLength})),n.buffer}function tp(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);var t=e.split("/");return t[t.length-1]}function np(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:Zl(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Zl(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}var rp=function(){function e(){this.saveRouters=[],this.loadRouters=[]}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e.registerSaveRouter=function(t){e.getInstance().saveRouters.push(t)},e.registerLoadRouter=function(t){e.getInstance().loadRouters.push(t)},e.getSaveHandlers=function(t){return e.getHandlers(t,"save")},e.getLoadHandlers=function(t,n){return e.getHandlers(t,"load",n)},e.getHandlers=function(t,n,r){var i=[];return("load"===n?e.getInstance().loadRouters:e.getInstance().saveRouters).forEach((function(e){var n=e(t,r);null!==n&&i.push(n)})),i},e}(),ip="://",op=function(){function e(){this.managers={}}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e.registerManager=function(t,n){k(null!=t,(function(){return"scheme must not be undefined or null."})),t.endsWith(ip)&&(t=t.slice(0,t.indexOf(ip))),k(t.length>0,(function(){return"scheme must not be an empty string."}));var r=e.getInstance();k(null==r.managers[t],(function(){return"A model store manager is already registered for scheme '"+t+"'."})),r.managers[t]=n},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function ap(e){if(-1===e.indexOf(ip))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+op.getSchemes().join(","));return{scheme:e.split(ip)[0],path:e.split(ip)[1]}}function sp(e,t,n){return void 0===n&&(n=!1),c(this,void 0,void 0,(function(){var r,i,o,a,s,c,d,l,p;return u(this,(function(u){switch(u.label){case 0:return k(e!==t,(function(){return"Old path and new path are the same: '"+e+"'"})),k((r=rp.getLoadHandlers(e)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+e+"."})),k(r.length<2,(function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+e+"."})),i=r[0],k((o=rp.getSaveHandlers(t)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+t+"."})),k(o.length<2,(function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+t+"."})),a=o[0],s=ap(e).scheme,c=ap(e).path,d=s===ap(e).scheme,[4,i.load()];case 1:return l=u.sent(),n&&d?[4,op.getManager(s).removeModel(c)]:[3,3];case 2:u.sent(),u.label=3;case 3:return[4,a.save(l)];case 4:return p=u.sent(),!n||d?[3,6]:[4,op.getManager(s).removeModel(c)];case 5:u.sent(),u.label=6;case 6:return[2,p.modelArtifactsInfo]}}))}))}var cp="models_store",up="model_info_store";function dp(){if(!l().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=window||self,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function lp(e){var t=e.result;t.createObjectStore(cp,{keyPath:"modelPath"}),t.createObjectStore(up,{keyPath:"modelPath"})}var pp=function(){function e(e){if(this.indexedDB=dp(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return e.prototype.save=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(t){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]}))}))},e.prototype.load=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){return[2,this.databaseAction(this.modelPath)]}))}))},e.prototype.databaseAction=function(e,t){var n=this;return new Promise((function(e,r){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return lp(i)},i.onsuccess=function(){var o=i.result;if(null==t){var a=o.transaction(cp,"readonly"),s=a.objectStore(cp).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return o.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));e(s.result.modelArtifacts)},s.onerror=function(e){return o.close(),r(s.error)},a.oncomplete=function(){return o.close()}}else{var c,u=np(t),d=o.transaction(up,"readwrite"),l=d.objectStore(up),p=l.put({modelPath:n.modelPath,modelArtifactsInfo:u});p.onsuccess=function(){var i=(c=o.transaction(cp,"readwrite")).objectStore(cp).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:u});i.onsuccess=function(){return e({modelArtifactsInfo:u})},i.onerror=function(e){var t=(l=d.objectStore(up)).delete(n.modelPath);t.onsuccess=function(){return o.close(),r(i.error)},t.onerror=function(e){return o.close(),r(i.error)}}},p.onerror=function(e){return o.close(),r(p.error)},d.oncomplete=function(){null==c?o.close():c.oncomplete=function(){return o.close()}}}},i.onerror=function(e){return r(i.error)}}))},e.URL_SCHEME="indexeddb://",e}(),hp=function(e){return l().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(pp.URL_SCHEME)?(t=e.slice(pp.URL_SCHEME.length),new pp(t)):null;var t};rp.registerSaveRouter(hp),rp.registerLoadRouter(hp);var fp=function(){function e(){this.indexedDB=dp()}return e.prototype.listModels=function(){return c(this,void 0,void 0,(function(){var e=this;return u(this,(function(t){return[2,new Promise((function(t,n){var r=e.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return lp(r)},r.onsuccess=function(){var e=r.result,i=e.transaction(up,"readonly"),o=i.objectStore(up).getAll();o.onsuccess=function(){for(var e={},n=0,r=o.result;n<r.length;n++){var i=r[n];e[i.modelPath]=i.modelArtifactsInfo}t(e)},o.onerror=function(t){return e.close(),n(o.error)},i.oncomplete=function(){return e.close()}},r.onerror=function(e){return n(r.error)}}))]}))}))},e.prototype.removeModel=function(e){return c(this,void 0,void 0,(function(){var t=this;return u(this,(function(n){var r;return e=(r=e).startsWith(pp.URL_SCHEME)?r.slice(pp.URL_SCHEME.length):r,[2,new Promise((function(n,r){var i=t.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return lp(i)},i.onsuccess=function(){var t,o=i.result,a=o.transaction(up,"readwrite"),s=a.objectStore(up),c=s.get(e);c.onsuccess=function(){if(null==c.result)return o.close(),r(new Error("Cannot find model with path '"+e+"' in IndexedDB."));var i=s.delete(e),a=function(){var i=(t=o.transaction(cp,"readwrite")).objectStore(cp).delete(e);i.onsuccess=function(){return n(c.result.modelArtifactsInfo)},i.onerror=function(e){return r(c.error)}};i.onsuccess=a,i.onerror=function(e){return a(),o.close(),r(c.error)}},c.onerror=function(e){return o.close(),r(c.error)},a.oncomplete=function(){null==t?o.close():t.oncomplete=function(){return o.close()}}},i.onerror=function(e){return r(i.error)}}))]}))}))},e}();if(l().getBool("IS_BROWSER"))try{op.registerManager(pp.URL_SCHEME,new fp)}catch(a){}var mp="/",gp="tensorflowjs_models",vp="info",yp="model_topology",bp="weight_specs",wp="weight_data",xp="model_metadata";function _p(e){return{info:[gp,e,vp].join(mp),topology:[gp,e,yp].join(mp),weightSpecs:[gp,e,bp].join(mp),weightData:[gp,e,wp].join(mp),modelMetadata:[gp,e,xp].join(mp)}}function Sp(e){var t=e.split(mp);if(t.length<3)throw new Error("Invalid key format: "+e);return t.slice(1,t.length-1).join(mp)}var Rp=function(){function e(e){if(!l().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=_p(this.modelPath)}return e.prototype.save=function(e){return c(this,void 0,void 0,(function(){var t,n,r;return u(this,(function(i){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=np(e);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Jl)return Buffer.from(e).toString("base64");for(var t=new Uint8Array(e),n="",r=0,i=t.length;r<i;r++)n+=String.fromCharCode(t[r]);return btoa(n)}(e.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata})),[2,{modelArtifactsInfo:r}]}catch(e){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+r.modelTopologyBytes+", weightSpecsBytes="+r.weightSpecsBytes+", weightDataBytes="+r.weightDataBytes+".")}return[2]}))}))},e.prototype.load=function(){return c(this,void 0,void 0,(function(){var e,t,n,r,i,o,a;return u(this,(function(s){if(null==(e=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(t={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(t.modelTopology=n,null==(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(t.weightSpecs=r,null!=(i=this.LS.getItem(this.keys.modelMetadata))&&(o=JSON.parse(i),t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,t.userDefinedMetadata=o.userDefinedMetadata),null==(a=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return t.weightData=function(e){if(Jl){var t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}for(var n=atob(e),r=new Uint8Array(n.length),i=0;i<n.length;++i)r.set([n.charCodeAt(i)],i);return r.buffer}(a),[2,t]}))}))},e.URL_SCHEME="localstorage://",e}(),Cp=function(e){return l().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Rp.URL_SCHEME)?(t=e.slice(Rp.URL_SCHEME.length),new Rp(t)):null;var t};rp.registerSaveRouter(Cp),rp.registerLoadRouter(Cp);var Ep=function(){function e(){k(l().getBool("IS_BROWSER"),(function(){return"Current environment is not a web browser"})),k("undefined"==typeof window||void 0!==window.localStorage,(function(){return"Current browser does not appear to support localStorage"})),this.LS=window.localStorage}return e.prototype.listModels=function(){return c(this,void 0,void 0,(function(){var e,t,n,r,i,o;return u(this,(function(a){for(e={},t=gp+mp,n=mp+vp,r=0;r<this.LS.length;++r)(i=this.LS.key(r)).startsWith(t)&&i.endsWith(n)&&(o=Sp(i),e[o]=JSON.parse(this.LS.getItem(i)));return[2,e]}))}))},e.prototype.removeModel=function(e){return c(this,void 0,void 0,(function(){var t,n;return u(this,(function(r){var i;if(e=(i=e).startsWith(Rp.URL_SCHEME)?i.slice(Rp.URL_SCHEME.length):i,t=_p(e),null==this.LS.getItem(t.info))throw new Error("Cannot find model at path '"+e+"'");return n=JSON.parse(this.LS.getItem(t.info)),this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),[2,n]}))}))},e}();if(l().getBool("IS_BROWSER"))try{op.registerManager(Rp.URL_SCHEME,new Ep)}catch(a){}function kp(e){return new Promise((function(e){return setTimeout(e)})).then(e)}var Tp=function(){function e(t){if(!l().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(e.URL_SCHEME)&&(t=t.slice(e.URL_SCHEME.length)),null!=t&&0!==t.length||(t="model"),this.modelTopologyFileName=t+".json",this.weightDataFileName=t+".weights.bin"}return e.prototype.save=function(e){return c(this,void 0,void 0,(function(){var t,n,r,i,o,a;return u(this,(function(s){switch(s.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"})),!(e.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},i=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(o=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,o.href=i,[4,kp((function(){return o.dispatchEvent(new MouseEvent("click"))}))];case 2:return s.sent(),null==e.weightData?[3,4]:((a=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,a.href=t,[4,kp((function(){return a.dispatchEvent(new MouseEvent("click"))}))]);case 3:s.sent(),s.label=4;case 4:return[2,{modelArtifactsInfo:np(e)}]}}))}))},e.URL_SCHEME="downloads://",e}(),Dp=function(){function e(e){if(null==e||e.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+e);this.files=e}return e.prototype.load=function(){return c(this,void 0,void 0,(function(){var e,t,n=this;return u(this,(function(r){return e=this.files[0],t=this.files.slice(1),[2,new Promise((function(r,i){var o=new FileReader;o.onload=function(o){var a=JSON.parse(o.target.result),s=a.modelTopology;if(null!=s){0===t.length&&r({modelTopology:s});var c=a.weightsManifest;if(null!=c){var u;try{u=n.checkManifestAndWeightFiles(c,t)}catch(e){return void i(e)}var d=[],l=[],p=[];c.forEach((function(e){e.paths.forEach((function(e){l.push(e),p.push(null)})),d.push.apply(d,e.weights)})),c.forEach((function(e){e.paths.forEach((function(e){var t=new FileReader;t.onload=function(t){var n=t.target.result,i=l.indexOf(e);p[i]=n,-1===p.indexOf(null)&&r({modelTopology:s,weightSpecs:d,weightData:ep(p),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},t.onerror=function(t){return i("Failed to weights data from file of path '"+e+"'.")},t.readAsArrayBuffer(u[e])}))}))}else i(new Error("weightManifest field is missing from file "+e.name))}else i(new Error("modelTopology field is missing from file "+e.name))},o.onerror=function(t){return i("Failed to read model topology and weights manifest JSON from file '"+e.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},o.readAsText(e)}))]}))}))},e.prototype.checkManifestAndWeightFiles=function(e,t){for(var n=[],r=t.map((function(e){return tp(e.name)})),i={},o=0,a=e;o<a.length;o++)a[o].paths.forEach((function(e){var o=tp(e);if(-1!==n.indexOf(o))throw new Error("Duplicate file basename found in weights manifest: '"+o+"'");if(n.push(o),-1===r.indexOf(o))throw new Error("Weight file with basename '"+o+"' is not provided.");i[e]=t[r.indexOf(o)]}));if(n.length!==t.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+t.length+").");return i},e}();function Pp(e,t,n,r){!function(e){k(null!=e&&Array.isArray(e)&&e.length>0,(function(){return"promises must be a none empty array"}))}(e),function(e,t){k(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+e})),k(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+t})),k(t>=e,(function(){return"startFraction must be no more than endFraction, but got startFraction "+e+" and endFraction "+t}))}(n=null==n?0:n,r=null==r?1:r);var i=0;return Promise.all(e.map((function(o){return o.then((function(o){var a=n+ ++i/e.length*(r-n);return t(a),o})),o})))}function Ip(e,t){return c(this,void 0,void 0,(function(){var n,r,i,o,a,s,c,d,p;return u(this,(function(u){switch(u.label){case 0:return null==t&&(t={}),n=null==t.fetchFunc?l().platform.fetch:t.fetchFunc,r=e.map((function(e){return n(e,t.requestInit,{isBinary:!0})})),i=0,o=.5,null!=t.onProgress?[3,2]:[4,Promise.all(r)];case 1:return a=u.sent(),[3,4];case 2:return[4,Pp(r,t.onProgress,i,o)];case 3:a=u.sent(),u.label=4;case 4:return s=a.map((function(e){return e.arrayBuffer()})),c=.5,d=1,null!=t.onProgress?[3,6]:[4,Promise.all(s)];case 5:return p=u.sent(),[3,8];case 6:return[4,Pp(s,t.onProgress,c,d)];case 7:p=u.sent(),u.label=8;case 8:return[2,p]}}))}))}function Mp(e){var t=this;return function(n,r,i){return void 0===r&&(r=""),c(t,void 0,void 0,(function(){var t,o,a,s,c,d,l,p,h,f;return u(this,(function(u){switch(u.label){case 0:if(t=n.map((function(){return!1})),o={},a=null!=i?i.map((function(){return!1})):[],s=[],n.forEach((function(e,n){var r=0;e.weights.forEach((function(e){var c="quantization"in e?e.quantization.dtype:e.dtype,u=Xl[c]*I(e.shape),d=function(){t[n]=!0,null==o[n]&&(o[n]=[]),o[n].push({manifestEntry:e,groupOffset:r,sizeBytes:u})};null!=i?i.forEach((function(t,n){t===e.name&&(d(),a[n]=!0)})):d(),s.push(e.name),r+=u}))})),!a.every((function(e){return e})))throw c=i.filter((function(e,t){return!a[t]})),new Error("Could not find weights in manifest with names: "+c.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return d=t.reduce((function(e,t,n){return t&&e.push(n),e}),[]),l=[],d.forEach((function(e){n[e].paths.forEach((function(e){var t=r+(r.endsWith("/")?"":"/")+e;l.push(t)}))})),[4,e(l)];case 1:return p=u.sent(),h={},f=0,d.forEach((function(e){for(var t=n[e].paths.length,r=0,i=0;i<t;i++)r+=p[f+i].byteLength;for(var a=new ArrayBuffer(r),s=new Uint8Array(a),c=0,u=0;u<t;u++){var d=new Uint8Array(p[f+u]);s.set(d,c),c+=d.byteLength}o[e].forEach((function(e){var t=Yl(a.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(var n in t)h[n]=t[n]})),f+=t})),[2,h]}}))}))}}rp.registerSaveRouter((function(e){return l().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Tp.URL_SCHEME)?function(e){return void 0===e&&(e="model"),new Tp(e)}(e.slice(Tp.URL_SCHEME.length)):null}));var Op=function(){function e(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,null!=t.fetchFunc?(k("function"==typeof t.fetchFunc,(function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"})),this.fetch=t.fetchFunc):this.fetch=l().platform.fetch,k(null!=e&&e.length>0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(e)&&k(2===e.length,(function(){return"URL paths for http must have a length of 2, (actual length is "+e.length+")."})),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}return e.prototype.save=function(e){return c(this,void 0,void 0,(function(){var t,n,r,i;return u(this,(function(o){switch(o.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n},t.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,t)];case 1:if((i=o.sent()).ok)return[2,{modelArtifactsInfo:np(e),responses:[i]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+i.status+".")}}))}))},e.prototype.load=function(){return c(this,void 0,void 0,(function(){var e,t,n,r,i,o,a,s,c,d,l,p;return u(this,(function(u){switch(u.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(e=u.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+e.status+". Please verify this URL points to the model JSON of the model to load.");u.label=2;case 2:return u.trys.push([2,4,,5]),[4,e.json()];case 3:return t=u.sent(),[3,5];case 4:throw u.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=t.modelTopology,i=t.weightsManifest,o=t.generatedBy,a=t.convertedBy,s=t.format,c=t.userDefinedMetadata,null==r&&null==i)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==i?[3,7]:[4,this.loadWeights(i)];case 6:p=u.sent(),d=p[0],l=p[1],u.label=7;case 7:return[2,{modelTopology:r,weightSpecs:d,weightData:l,userDefinedMetadata:c,generatedBy:o,convertedBy:a,format:s}]}}))}))},e.prototype.loadWeights=function(e){return c(this,void 0,void 0,(function(){var t,n,r,i,o,a,s,c,d,l,p;return u(this,(function(u){switch(u.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,n=function(e){var t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),r=n[0],i=n[1],o=this.weightPathPrefix||r,a=[],s=0,c=e;s<c.length;s++)d=c[s],a.push.apply(a,d.weights);return l=[],e.forEach((function(e){e.paths.forEach((function(e){l.push(o+e+i)}))})),[4,Ip(l,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return p=u.sent(),[2,[a,ep(p)]]}}))}))},e.URL_SCHEME_REGEX=/^https?:\/\//,e}();function Ap(e){return null!=e.match(Op.URL_SCHEME_REGEX)}var Fp=function(e,t){return"undefined"==typeof fetch?null:(Array.isArray(e)?e.every((function(e){return Ap(e)})):Ap(e))?Np(e,{onProgress:t}):null};function Np(e,t){return new Op(e,t)}rp.registerSaveRouter(Fp),rp.registerLoadRouter(Fp);var Lp,Bp=function(){function e(e){this.modelArtifacts=e}return e.prototype.load=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){return[2,this.modelArtifacts]}))}))},e}(),jp=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(t){return[2,this.saveHandler(e)]}))}))},e}(),Wp=Object.freeze({browserFiles:function(e){return new Dp(e)},browserHTTPRequest:function(e,t){return Np(e,t)},concatenateArrayBuffers:ep,decodeWeights:Yl,encodeWeights:function(e,t){return c(this,void 0,void 0,(function(){var n,r,i,o,a,s=this;return u(this,(function(d){switch(d.label){case 0:for(n=[],r=[],i=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e),o=function(o){var a=i[o],d=Array.isArray(e)?e[o].tensor:e[a];if("float32"!==d.dtype&&"int32"!==d.dtype&&"bool"!==d.dtype&&"string"!==d.dtype)throw new Error("Unsupported dtype in weight '"+a+"': "+d.dtype);var l={name:a,shape:d.shape,dtype:d.dtype};if("string"===d.dtype){var p=new Promise((function(e){return c(s,void 0,void 0,(function(){var t,n,r,i,o,a,s;return u(this,(function(c){switch(c.label){case 0:return[4,d.bytes()];case 1:for(t=c.sent(),n=t.reduce((function(e,t){return e+t.length}),0)+$l*t.length,r=new Uint8Array(n),i=0,o=0;o<t.length;o++)a=t[o],s=new Uint8Array(new Uint32Array([a.length]).buffer),r.set(s,i),i+=$l,r.set(a,i),i+=a.length;return e(r),[2]}}))}))}));r.push(p)}else r.push(d.data());null!=t&&(l.group=t),n.push(l)},a=0;a<i.length;++a)o(a);return[4,Promise.all(r)];case 1:return[2,{data:Ql(d.sent()),specs:n}]}}))}))},fromMemory:function(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new Bp(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Bp({modelTopology:e})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Bp({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))},getLoadHandlers:function(e,t){return rp.getLoadHandlers(e,t)},getModelArtifactsInfoForJSON:np,getSaveHandlers:function(e){return rp.getSaveHandlers(e)},http:Np,isHTTPScheme:Ap,loadWeights:function(e,t,n,r){return void 0===t&&(t=""),c(this,void 0,void 0,(function(){return u(this,(function(i){return[2,Mp((function(e){return Ip(e,{requestInit:r})}))(e,t,n)]}))}))},registerLoadRouter:function(e){return rp.registerLoadRouter(e)},registerSaveRouter:function(e){return rp.registerSaveRouter(e)},weightsLoaderFactory:Mp,withSaveHandler:function(e){return new jp(e)},copyModel:function(e,t){return c(this,void 0,void 0,(function(){return u(this,(function(n){return[2,sp(e,t,!1)]}))}))},listModels:function(){return c(this,void 0,void 0,(function(){var e,t,n,r,i,o,a;return u(this,(function(s){switch(s.label){case 0:e=op.getSchemes(),t={},n=0,r=e,s.label=1;case 1:return n<r.length?(i=r[n],[4,op.getManager(i).listModels()]):[3,4];case 2:for(a in o=s.sent())t[i+ip+a]=o[a];s.label=3;case 3:return n++,[3,1];case 4:return[2,t]}}))}))},moveModel:function(e,t){return c(this,void 0,void 0,(function(){return u(this,(function(n){return[2,sp(e,t,!0)]}))}))},removeModel:function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){return t=ap(e),[2,op.getManager(t.scheme).removeModel(t.path)]}))}))}}),zp=kn({confusionMatrix_:function(e,t,n){var r=mn(e,"labels","confusionMatrix"),i=mn(t,"predictions","confusionMatrix");k(null==n||n>0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),k(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),k(1===i.rank,(function(){return"Expected the rank of predictions to be 1, but got "+i.rank})),k(r.shape[0]===i.shape[0],(function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+i.shape[0]+". Labels and predictions should have the same number of elements."})),k(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var o=Sr(r.asType("int32"),n),a=Sr(i.asType("int32"),n);return o.transpose().matMul(a).asType("int32")}}),Up=Object.freeze({confusionMatrix:zp}),Vp=kn({fromPixels_:function(e,t){if(void 0===t&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,i=!1,o=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)i=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)o=!0;else{if(null==e.getContext)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+e.constructor.name);a=!0}if(i&&i&&e.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(null!=m("FromPixels",je.backendName))return je.runKernel("FromPixels",{pixels:e},{numChannels:t});var s,c,u=i?[e.videoWidth,e.videoHeight]:[e.width,e.height],d=u[0],l=u[1];if(a?s=e.getContext("2d").getImageData(0,0,d,l).data:r||n?s=e.data:(o||i)&&(null==Lp&&(Lp=document.createElement("canvas").getContext("2d")),Lp.canvas.width=d,Lp.canvas.height=l,Lp.drawImage(e,0,0,d,l),s=Lp.getImageData(0,0,d,l).data),4===t)c=new Int32Array(s);else{var p=d*l;c=new Int32Array(p*t);for(var h=0;h<p;h++)for(var f=0;f<t;++f)c[h*t+f]=s[4*h+f]}return Nn(c,[l,d,t],"int32")}}),Gp=Object.freeze({toPixels:function(e,t){return c(this,void 0,void 0,(function(){var n,r,i,o,a,s,c,d,l,p,h,f,m,g,v,y,b,w,x,_,S,R,C;return u(this,(function(u){switch(u.label){case 0:if(n=mn(e,"img","toPixels"),e instanceof _e||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),i=r[0],o=r[1],(a=2===n.rank?1:n.shape[2])>4||2===a)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+a);return[4,n.data()];case 1:return s=u.sent(),c=n.min(),d=n.max(),[4,Promise.all([c.data(),d.data()])];case 2:if(l=u.sent(),p=l[0],h=l[1],f=p[0],m=h[0],c.dispose(),d.dispose(),"float32"===n.dtype){if(f<0||m>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+f+" - "+m+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(f<0||m>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+f+" - "+m+"].")}for(g="float32"===n.dtype?255:1,v=new Uint8ClampedArray(o*i*4),y=0;y<i*o;++y)b=void 0,w=void 0,x=void 0,_=void 0,1===a?(b=s[y]*g,w=s[y]*g,x=s[y]*g,_=255):3===a?(b=s[3*y]*g,w=s[3*y+1]*g,x=s[3*y+2]*g,_=255):4===a&&(b=s[4*y]*g,w=s[4*y+1]*g,x=s[4*y+2]*g,_=s[4*y+3]*g),v[0+(S=4*y)]=Math.round(b),v[S+1]=Math.round(w),v[S+2]=Math.round(x),v[S+3]=Math.round(_);return null!=t&&(t.width=o,t.height=i,R=t.getContext("2d"),C=new ImageData(v,o,i),R.putImageData(C,0,0)),n!==e&&n.dispose(),[2,v]}}))}))},fromPixels:Vp}),qp=function(){function e(){}return e.prototype.getClassName=function(){return this.constructor.className},e.fromConfig=function(e,t){return new e(t)},e}(),Hp=function(){function e(){this.classNameMap={}}return e.getMap=function(){return null==e.instance&&(e.instance=new e),e.instance},e.register=function(t){e.getMap().classNameMap[t.className]=[t,t.fromConfig]},e}();function Kp(e){k(null!=e.className,(function(){return"Class being registered does not have the static className property defined."})),k("string"==typeof e.className,(function(){return"className is required to be a string, but got type "+typeof e.className})),k(e.className.length>0,(function(){return"Class being registered has an empty-string as its className, which is disallowed."})),Hp.register(e)}var Xp=Object.freeze({Serializable:qp,SerializationMap:Hp,registerClass:Kp});function $p(){return 32===je.backend.floatPrecision()?.001:.1}function Yp(e,t,n){var r=!0;if((H(e)||H(t))&&(r=!1),H(e)&&H(t)&&(r=!0),r){var i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error("Arrays are of different type. Actual: "+i+". Expected: "+o)}if(Array.isArray(e)&&Array.isArray(t)){var a=hn(e),s=hn(t);if(!M(a,s))throw new Error("Arrays have different shapes. Actual: ["+a+"]. Expected: ["+s+"]")}var c=H(e)?e:P(e),u=H(t)?t:P(t);if(c.length!==u.length)throw new Error("Arrays have different lengths actual: "+c.length+" vs expected: "+u.length+".\nActual: "+c+".\nExpected: "+u+".");for(var d=0;d<u.length;++d){var l=c[d],p=u[d];if(!n(l,p))throw new Error("Arrays differ: actual["+d+"] = "+l+", expected["+d+"] = "+p+".\nActual: "+c+".\nExpected: "+u+".")}}function Qp(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}var Jp=Object.freeze({TEST_EPSILON_FLOAT16:.1,expectArraysClose:function(e,t,n){return null==n&&(n=$p()),Yp(e,t,(function(e,t){return Qp(e,t,n)}))},testEpsilon:$p,expectPromiseToFail:function(e,t){e().then((function(){return t.fail()}),(function(){return t()}))},expectArraysEqual:function(e,t){var n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return $(e)||$(e[0])||$(t)||$(t[0])?Yp(e,n,(function(e,t){return e==t})):Yp(e,t,(function(e,t){return Qp(e,t,0)}))},expectNumbersClose:function(e,t,n){if(null==n&&(n=$p()),!Qp(e,t,n))throw new Error("Numbers differ: actual === "+e+", expected === "+t)},expectValuesInRange:function(e,t,n){for(var r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error("Value out of range:"+e[r]+" low: "+t+", high: "+n)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}}),Zp="1.7.0",eh=Object.freeze({gpgpu_util:Da,webgl_util:Ut,forceHalfFloat:function(){l().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Gs,setWebGLContext:Ke,GPGPUContext:Pa}),th=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype.minimize=function(e,t,n){void 0===t&&(t=!1);var r=this.computeGradients(e,n),i=r.value,o=r.grads;if(null!=n){var a=n.map((function(e){return{name:e.name,tensor:o[e.name]}}));this.applyGradients(a)}else this.applyGradients(o);return Zt(o),t?i:(i.dispose(),null)},Object.defineProperty(t.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),t.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},t.prototype.computeGradients=function(e,t){return li(e,t)},t.prototype.dispose=function(){null!=this.iterations_&&Zt(this.iterations_)},t.prototype.saveIterations=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:On(this.iterations_,"int32")}]}))}))},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){throw new Error("getWeights() is not implemented for this optimizer yet.")}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(e){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())}))}))},t.prototype.extractIterations=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){switch(n.label){case 0:return t=this,[4,e[0].tensor.data()];case 1:return t.iterations_=n.sent()[0],[2,e.slice(1)]}}))}))},t}(qp);Object.defineProperty(th,Symbol.hasInstance,{value:function(e){return null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients}});var nh=function(e){function t(t,n,r){void 0===r&&(r=null);var i=e.call(this)||this;return i.learningRate=t,i.rho=n,i.epsilon=r,i.accumulatedGrads=[],i.accumulatedUpdates=[],null==r&&(i.epsilon=je.backend.epsilon()),i}return s(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=je.registeredVariables[n];null==t.accumulatedGrads[r]&&(t.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Jt((function(){return Kn(i).variable(!1)}))}),null==t.accumulatedUpdates[r]&&(t.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Jt((function(){return Kn(i).variable(!1)}))});var o=Array.isArray(e)?e[r].tensor:e[n];if(null!=o){var a=t.accumulatedGrads[r].variable,s=t.accumulatedUpdates[r].variable;Jt((function(){var e=a.mul(t.rho).add(o.square().mul(1-t.rho)),n=s.add(t.epsilon).sqrt().div(a.add(t.epsilon).sqrt()).mul(o),r=s.mul(t.rho).add(n.square().mul(1-t.rho));a.assign(e),s.assign(r);var c=n.mul(-t.learningRate).add(i);i.assign(c)}))}})),this.incrementIterations()},t.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Zt(this.accumulatedGrads.map((function(e){return e.variable}))),Zt(this.accumulatedUpdates.map((function(e){return e.variable}))))},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return e=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),t=e.length/2,this.accumulatedGrads=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedUpdates=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className="Adadelta",t}(th);Kp(nh);var rh=function(e){function t(t,n){void 0===n&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return s(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=je.registeredVariables[n];null==t.accumulatedGrads[r]&&(t.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Jt((function(){return Vn(i.shape,t.initialAccumulatorValue).variable(!1)}))});var o=Array.isArray(e)?e[r].tensor:e[n];if(null!=o){var a=t.accumulatedGrads[r].variable;Jt((function(){var e=a.add(o.square());a.assign(e);var n=o.div(e.add(je.backend.epsilon()).sqrt()).mul(-t.learningRate).add(i);i.assign(n)}))}})),this.incrementIterations()},t.prototype.dispose=function(){null!=this.accumulatedGrads&&Zt(this.accumulatedGrads.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulatedGrads=e.map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className="Adagrad",t}(th);Kp(rh);var ih=function(e){function t(t,n,r,i){void 0===i&&(i=null);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=i,o.accumulatedFirstMoment=[],o.accumulatedSecondMoment=[],Jt((function(){o.accBeta1=On(n).variable(),o.accBeta2=On(r).variable()})),null==i&&(o.epsilon=je.backend.epsilon()),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e);Jt((function(){var r=hu(1,t.accBeta1),i=hu(1,t.accBeta2);n.forEach((function(n,o){var a=je.registeredVariables[n];null==t.accumulatedFirstMoment[o]&&(t.accumulatedFirstMoment[o]={originalName:n+"/m",variable:Jt((function(){return Kn(a).variable(!1)}))}),null==t.accumulatedSecondMoment[o]&&(t.accumulatedSecondMoment[o]={originalName:n+"/v",variable:Jt((function(){return Kn(a).variable(!1)}))});var s=Array.isArray(e)?e[o].tensor:e[n];if(null!=s){var c=t.accumulatedFirstMoment[o].variable,u=t.accumulatedSecondMoment[o].variable,d=c.mul(t.beta1).add(s.mul(1-t.beta1)),l=u.mul(t.beta2).add(s.square().mul(1-t.beta2)),p=d.div(r),h=l.div(i);c.assign(d),u.assign(l);var f=p.div(h.sqrt().add(t.epsilon)).mul(-t.learningRate).add(a);a.assign(f)}})),t.accBeta1.assign(t.accBeta1.mul(t.beta1)),t.accBeta2.assign(t.accBeta2.mul(t.beta2))})),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Zt(this.accumulatedFirstMoment.map((function(e){return e.variable}))),null!=this.accumulatedSecondMoment&&Zt(this.accumulatedSecondMoment.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return e=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){var t,n=this;return u(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(e)];case 1:return e=r.sent(),Jt((function(){n.accBeta1.assign(du(n.beta1,n.iterations_+1)),n.accBeta2.assign(du(n.beta2,n.iterations_+1))})),t=e.length/2,this.accumulatedFirstMoment=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedSecondMoment=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className="Adam",t}(th);Kp(ih);var oh=function(e){function t(t,n,r,i,o){void 0===i&&(i=null),void 0===o&&(o=0);var a=e.call(this)||this;return a.learningRate=t,a.beta1=n,a.beta2=r,a.epsilon=i,a.decay=o,a.accumulatedFirstMoment=[],a.accumulatedWeightedInfNorm=[],Jt((function(){a.iteration=On(0).variable(),a.accBeta1=On(n).variable()})),null==i&&(a.epsilon=je.backend.epsilon()),a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e);Jt((function(){var r=hu(1,t.accBeta1),i=Jc(-t.learningRate,t.iteration.mul(t.decay).add(1));n.forEach((function(n,o){var a=je.registeredVariables[n];null==t.accumulatedFirstMoment[o]&&(t.accumulatedFirstMoment[o]={originalName:n+"/m",variable:Kn(a).variable(!1)}),null==t.accumulatedWeightedInfNorm[o]&&(t.accumulatedWeightedInfNorm[o]={originalName:n+"/v",variable:Kn(a).variable(!1)});var s=Array.isArray(e)?e[o].tensor:e[n];if(null!=s){var c=t.accumulatedFirstMoment[o].variable,u=t.accumulatedWeightedInfNorm[o].variable,d=c.mul(t.beta1).add(s.mul(1-t.beta1)),l=u.mul(t.beta2),p=s.abs(),h=l.maximum(p);c.assign(d),u.assign(h);var f=i.div(r).mul(d.div(h.add(t.epsilon))).add(a);a.assign(f)}})),t.iteration.assign(t.iteration.add(1)),t.accBeta1.assign(t.accBeta1.mul(t.beta1))})),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Zt(this.accumulatedFirstMoment.map((function(e){return e.variable}))),null!=this.accumulatedWeightedInfNorm&&Zt(this.accumulatedWeightedInfNorm.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){throw new Error("getWeights() is not implemented for Adamax yet.")}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(e){throw new Error("setWeights() is not implemented for Adamax yet.")}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className="Adamax",t}(th);Kp(oh);var ah=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n}return s(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=Array.isArray(e)?e[r].tensor:e[n];if(null!=i){var o=je.registeredVariables[n];Jt((function(){var e=t.c.mul(i).add(o);o.assign(e)}))}})),this.incrementIterations()},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=en(On(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]]}}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:if(0!==(e=t.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className="SGD",t}(th);Kp(ah);var sh=function(e){function t(t,n,r){void 0===r&&(r=!1);var i=e.call(this,t)||this;return i.learningRate=t,i.momentum=n,i.useNesterov=r,i.accumulations=[],i.m=On(i.momentum),i}return s(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=je.registeredVariables[n];null==t.accumulations[r]&&(t.accumulations[r]={originalName:n+"/momentum",variable:Jt((function(){return Kn(i).variable(!1)}))});var o=t.accumulations[r].variable,a=Array.isArray(e)?e[r].tensor:e[n];null!=a&&Jt((function(){var e,n=t.m.mul(o).add(a);e=t.useNesterov?t.c.mul(a.add(n.mul(t.m))).add(i):t.c.mul(n).add(i),o.assign(n),i.assign(e)}))})),this.incrementIterations()},t.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Zt(this.accumulations.map((function(e){return e.variable})))},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){return u(this,(function(t){switch(t.label){case 0:return[4,this.extractIterations(e)];case 1:return e=t.sent(),this.accumulations=e.map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className="Momentum",t}(ah);Kp(sh);var ch=function(e){function t(t,n,r,i,o){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===i&&(i=null),void 0===o&&(o=!1);var a=e.call(this)||this;if(a.learningRate=t,a.decay=n,a.momentum=r,a.epsilon=i,a.accumulatedMeanSquares=[],a.accumulatedMoments=[],a.accumulatedMeanGrads=[],a.centered=o,null==i&&(a.epsilon=je.backend.epsilon()),null==t)throw new Error("learningRate for RMSPropOptimizer must be defined.");return a}return s(t,e),t.prototype.applyGradients=function(e){var t=this;(Array.isArray(e)?e.map((function(e){return e.name})):Object.keys(e)).forEach((function(n,r){var i=je.registeredVariables[n];null==t.accumulatedMeanSquares[r]&&(t.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Jt((function(){return Kn(i).variable(!1)}))}),null==t.accumulatedMoments[r]&&(t.accumulatedMoments[r]={originalName:n+"/momentum",variable:Jt((function(){return Kn(i).variable(!1)}))}),null==t.accumulatedMeanGrads[r]&&t.centered&&(t.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Jt((function(){return Kn(i).variable(!1)}))});var o=Array.isArray(e)?e[r].tensor:e[n];if(null!=o){var a=t.accumulatedMeanSquares[r].variable,s=t.accumulatedMoments[r].variable;Jt((function(){var e=a.mul(t.decay).add(o.square().mul(1-t.decay));if(t.centered){var n=t.accumulatedMeanGrads[r].variable,c=n.mul(t.decay).add(o.mul(1-t.decay)),u=s.mul(t.momentum).add(o.mul(t.learningRate).div(e.sub(c.square().add(t.epsilon)).sqrt()));a.assign(e),n.assign(c),s.assign(u);var d=i.sub(u);i.assign(d)}else{var l=a.mul(t.decay).add(o.square().mul(1-t.decay));u=s.mul(t.momentum).add(o.mul(t.learningRate).div(l.add(t.epsilon).sqrt())),a.assign(l),s.assign(u),d=i.sub(u),i.assign(d)}}))}})),this.incrementIterations()},t.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Zt(this.accumulatedMeanSquares.map((function(e){return e.variable}))),null!=this.accumulatedMeanGrads&&this.centered&&Zt(this.accumulatedMeanGrads.map((function(e){return e.variable}))),null!=this.accumulatedMoments&&Zt(this.accumulatedMoments.map((function(e){return e.variable})))},t.prototype.getWeights=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return e=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&e.push.apply(e,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(e.map((function(e){return{name:e.originalName,tensor:e.variable}})))]}}))}))},t.prototype.setWeights=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(e)];case 1:return e=n.sent(),t=this.centered?e.length/3:e.length/2,this.accumulatedMeanSquares=e.slice(0,t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.accumulatedMoments=e.slice(t,2*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}))),[2]}}))}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className="RMSProp",t}(th);Kp(ch);var uh=function(){function e(){}return e.sgd=function(e){return new ah(e)},e.momentum=function(e,t,n){return void 0===n&&(n=!1),new sh(e,t,n)},e.rmsprop=function(e,t,n,r,i){return void 0===t&&(t=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===i&&(i=!1),new ch(e,t,n,r,i)},e.adam=function(e,t,n,r){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new ih(e,t,n,r)},e.adadelta=function(e,t,n){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===n&&(n=null),new nh(e,t,n)},e.adamax=function(e,t,n,r,i){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===i&&(i=0),new oh(e,t,n,r,i)},e.adagrad=function(e,t){return void 0===t&&(t=.1),new rh(e,t)},e}(),dh={sgd:uh.sgd,momentum:uh.momentum,adadelta:uh.adadelta,adagrad:uh.adagrad,rmsprop:uh.rmsprop,adamax:uh.adamax,adam:uh.adam},lh="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(e){return e()};function ph(){return new Promise((function(e){return lh((function(){return e()}))}))}function hh(e,t,n){if(void 0===n&&(n=!1),e.beginPath(),t.slice(1).forEach((function(n,r){var i=n.x,o=n.y,a=t[r];e.moveTo(a.x,a.y),e.lineTo(i,o)})),n){var r=t[t.length-1],i=t[0];if(!r||!i)return;e.moveTo(r.x,r.y),e.lineTo(i.x,i.y)}e.stroke()}_e.prototype.squaredDifference=function(e){return Ks(this,e)},we=Ml;var fh=function(e,t){return fh=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},fh(e,t)};function mh(e,t){function n(){this.constructor=e}fh(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var gh=function(){return gh=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},gh.apply(this,arguments)};function vh(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))}function yh(e,t){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function bh(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),i=0;for(t=0;t<n;t++)for(var o=arguments[t],a=0,s=o.length;a<s;a++,i++)r[i]=o[a];return r}var wh=function(){function e(e,t){if(!Oh(e)||!Oh(t))throw new Error("Dimensions.constructor - expected width and height to be valid numbers, instead have "+JSON.stringify({width:e,height:t}));this._width=e,this._height=t}return Object.defineProperty(e.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),e.prototype.reverse=function(){return new e(1/this.width,1/this.height)},e}();function xh(e,t){return e instanceof _e&&e.shape.length===t}function _h(e){return xh(e,1)}function Sh(e){return xh(e,2)}function Rh(e){return xh(e,3)}function Ch(e){return xh(e,4)}function Eh(e){return e%1!=0}function kh(e){return e%2==0}function Th(e,t){void 0===t&&(t=2);var n=Math.pow(10,t);return Math.floor(e*n)/n}function Dh(e){return e&&e.width&&e.height}function Ph(e,t){var n=e.width,r=e.height,i=t/Math.max(r,n);return new wh(Math.round(n*i),Math.round(r*i))}function Ih(e){return e.reduce((function(e,t){return e.add(t)}),new Fh(0,0)).div(new Fh(e.length,e.length))}function Mh(e,t,n){return Array(e).fill(0).map((function(e,r){return t+r*n}))}function Oh(e){return!!e&&e!==1/0&&e!==-1/0&&!isNaN(e)||0===e}function Ah(e){return Oh(e)&&0<=e&&e<=1}var Fh=function(){function e(e,t){this._x=e,this._y=t}return Object.defineProperty(e.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.sub=function(t){return new e(this.x-t.x,this.y-t.y)},e.prototype.mul=function(t){return new e(this.x*t.x,this.y*t.y)},e.prototype.div=function(t){return new e(this.x/t.x,this.y/t.y)},e.prototype.abs=function(){return new e(Math.abs(this.x),Math.abs(this.y))},e.prototype.magnitude=function(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y))},e}(),Nh=function(){function e(t,n){void 0===n&&(n=!0);var r=t||{},i=[r.left,r.top,r.right,r.bottom].every(Oh),o=[r.x,r.y,r.width,r.height].every(Oh);if(!o&&!i)throw new Error("Box.constructor - expected box to be IBoundingBox | IRect, instead have "+JSON.stringify(r));var a=o?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top],s=a[0],c=a[1],u=a[2],d=a[3];e.assertIsValidBox({x:s,y:c,width:u,height:d},"Box.constructor",n),this._x=s,this._y=c,this._width=u,this._height=d}return e.isRect=function(e){return!!e&&[e.x,e.y,e.width,e.height].every(Oh)},e.assertIsValidBox=function(t,n,r){if(void 0===r&&(r=!1),!e.isRect(t))throw new Error(n+" - invalid box: "+JSON.stringify(t)+", expected object with properties x, y, width, height");if(!r&&(t.width<0||t.height<0))throw new Error(n+" - width ("+t.width+") and height ("+t.height+") must be positive numbers")},Object.defineProperty(e.prototype,"x",{get:function(){return this._x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this._width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this._height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"left",{get:function(){return this.x},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"top",{get:function(){return this.y},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"right",{get:function(){return this.x+this.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bottom",{get:function(){return this.y+this.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"area",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"topLeft",{get:function(){return new Fh(this.left,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"topRight",{get:function(){return new Fh(this.right,this.top)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bottomLeft",{get:function(){return new Fh(this.left,this.bottom)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bottomRight",{get:function(){return new Fh(this.right,this.bottom)},enumerable:!0,configurable:!0}),e.prototype.round=function(){var t=[this.x,this.y,this.width,this.height].map((function(e){return Math.round(e)}));return new e({x:t[0],y:t[1],width:t[2],height:t[3]})},e.prototype.floor=function(){var t=[this.x,this.y,this.width,this.height].map((function(e){return Math.floor(e)}));return new e({x:t[0],y:t[1],width:t[2],height:t[3]})},e.prototype.toSquare=function(){var t=this,n=t.x,r=t.y,i=t.width,o=t.height,a=Math.abs(i-o);return i<o&&(n-=a/2,i+=a),o<i&&(r-=a/2,o+=a),new e({x:n,y:r,width:i,height:o})},e.prototype.rescale=function(t){var n=Dh(t)?t.width:t,r=Dh(t)?t.height:t;return new e({x:this.x*n,y:this.y*r,width:this.width*n,height:this.height*r})},e.prototype.pad=function(t,n){var r=[this.x-t/2,this.y-n/2,this.width+t,this.height+n];return new e({x:r[0],y:r[1],width:r[2],height:r[3]})},e.prototype.clipAtImageBorders=function(t,n){var r=this,i=r.x,o=r.y,a=r.right,s=r.bottom,c=Math.max(i,0),u=Math.max(o,0),d=a-c,l=s-u;return new e({x:c,y:u,width:Math.min(d,t-c),height:Math.min(l,n-u)}).floor()},e.prototype.shift=function(t,n){var r=this.width,i=this.height;return new e({x:this.x+t,y:this.y+n,width:r,height:i})},e.prototype.padAtBorders=function(e,t){var n=this.width+1,r=this.height+1,i=n,o=r,a=this.left,s=this.top,c=this.right,u=this.bottom;return c>t&&(i=-c+t+n,c=t),u>e&&(o=-u+e+r,u=e),a<1&&(o=2-a,a=1),s<1&&(o=2-s,s=1),{dy:1,edy:o,dx:1,edx:i,y:s,ey:u,x:a,ex:c,w:n,h:r}},e.prototype.calibrate=function(t){return new e({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()},e}(),Lh=function(e){function t(t,n,r,i,o){return void 0===o&&(o=!1),e.call(this,{left:t,top:n,right:r,bottom:i},o)||this}return mh(t,e),t}(Nh),Bh=function(){function e(e,t,n,r,i){this._imageDims=new wh(i.width,i.height),this._score=e,this._classScore=t,this._className=n,this._box=new Nh(r).rescale(this._imageDims)}return Object.defineProperty(e.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"className",{get:function(){return this._className},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"box",{get:function(){return this._box},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageDims",{get:function(){return this._imageDims},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageWidth",{get:function(){return this.imageDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageHeight",{get:function(){return this.imageDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"relativeBox",{get:function(){return new Nh(this._box).rescale(this.imageDims.reverse())},enumerable:!0,configurable:!0}),e.prototype.forSize=function(t,n){return new e(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})},e}(),jh=function(e){function t(t,n,r){return e.call(this,t,t,"",n,r)||this}return mh(t,e),t.prototype.forSize=function(n,r){var i=e.prototype.forSize.call(this,n,r);return new t(i.score,i.relativeBox,i.imageDims)},t}(Bh);function Wh(e,t,n){void 0===n&&(n=!0);var r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left))*Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top));return n?r/(e.area+t.area-r):r/Math.min(e.area,t.area)}function zh(e){var t=e.map((function(e){return e.x})),n=e.map((function(e){return e.y})),r=t.reduce((function(e,t){return t<e?t:e}),1/0),i=n.reduce((function(e,t){return t<e?t:e}),1/0),o=t.reduce((function(e,t){return e<t?t:e}),0),a=n.reduce((function(e,t){return e<t?t:e}),0);return new Lh(r,i,o,a)}function Uh(e,t,n,r){void 0===r&&(r=!0);for(var i=t.map((function(e,t){return{score:e,boxIndex:t}})).sort((function(e,t){return e.score-t.score})).map((function(e){return e.boxIndex})),o=[],a=function(){var t=i.pop();o.push(t);for(var a=i,s=[],c=0;c<a.length;c++){var u=a[c],d=e[t],l=e[u];s.push(Wh(d,l,r))}i=i.filter((function(e,t){return s[t]<=n}))};i.length>0;)a();return o}function Vh(e,t){return Jt((function(){var n=t[0],r=t[1],i=t[2],o=Vn(bh(e.shape.slice(0,3),[1]),n),a=Vn(bh(e.shape.slice(0,3),[1]),r),s=Vn(bh(e.shape.slice(0,3),[1]),i),c=Xn([o,a,s],3);return hu(e,c)}))}function Gh(e,t){return void 0===t&&(t=!1),Jt((function(){var n=e.shape.slice(1),r=n[0],i=n[1];if(r===i)return e;var o=Math.abs(r-i),a=Math.round(o*(t?.5:1)),s=r>i?2:1,c=function(t){var n=e.shape.slice();return n[s]=t,Vn(n,0)},u=c(a),d=o-u.shape[s],l=[t&&d?c(d):null,e,u].filter((function(e){return!!e})).map((function(e){return e.toFloat()}));return Xn(l,s)}))}function qh(e){for(var t=e.slice(),n=t.length-1;n>0;n--){var r=Math.floor(Math.random()*(n+1)),i=t[n];t[n]=t[r],t[r]=i}return t}function Hh(e){return 1/(1+Math.exp(-e))}function Kh(e){return Math.log(e/(1-e))}var Xh,$h=function(e){function t(t,n,r,i,o){return void 0===o&&(o=!1),e.call(this,{x:t,y:n,width:r,height:i},o)||this}return mh(t,e),t}(Nh),Yh=function(){function e(e,t,n){void 0===n&&(n=new Fh(0,0));var r=t.width,i=t.height;this._imgDims=new wh(r,i),this._shift=n,this._positions=e.map((function(e){return e.mul(new Fh(r,i)).add(n)}))}return Object.defineProperty(e.prototype,"shift",{get:function(){return new Fh(this._shift.x,this._shift.y)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageWidth",{get:function(){return this._imgDims.width},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageHeight",{get:function(){return this._imgDims.height},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"positions",{get:function(){return this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"relativePositions",{get:function(){var e=this;return this._positions.map((function(t){return t.sub(e._shift).div(new Fh(e.imageWidth,e.imageHeight))}))},enumerable:!0,configurable:!0}),e.prototype.forSize=function(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})},e.prototype.shiftBy=function(e,t){return new this.constructor(this.relativePositions,this._imgDims,new Fh(e,t))},e.prototype.shiftByPoint=function(e){return this.shiftBy(e.x,e.y)},e.prototype.align=function(e,t){if(void 0===t&&(t={}),e){var n=e instanceof jh?e.box.floor():new Nh(e);return this.shiftBy(n.x,n.y).align(null,t)}var r=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t),i=r.useDlibAlignment,o=r.minBoxPadding;return i?this.alignDlib():this.alignMinBbox(o)},e.prototype.alignDlib=function(){var e=this.getRefPointsForAlignment(),t=e[0],n=e[1],r=e[2],i=function(e){return r.sub(e).magnitude()},o=(i(t)+i(n))/2,a=Math.floor(o/.45),s=Ih(e),c=Math.floor(Math.max(0,s.x-.5*a)),u=Math.floor(Math.max(0,s.y-.43*a));return new $h(c,u,Math.min(a,this.imageWidth+c),Math.min(a,this.imageHeight+u))},e.prototype.alignMinBbox=function(e){var t=zh(this.positions);return t.pad(t.width*e,t.height*e)},e.prototype.getRefPointsForAlignment=function(){throw new Error("getRefPointsForAlignment not implemented by base class")},e}(),Qh=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.getRefPointsForAlignment=function(){var e=this.positions;return[e[0],e[1],Ih([e[3],e[4]])]},t}(Yh),Jh=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.getJawOutline=function(){return this.positions.slice(0,17)},t.prototype.getLeftEyeBrow=function(){return this.positions.slice(17,22)},t.prototype.getRightEyeBrow=function(){return this.positions.slice(22,27)},t.prototype.getNose=function(){return this.positions.slice(27,36)},t.prototype.getLeftEye=function(){return this.positions.slice(36,42)},t.prototype.getRightEye=function(){return this.positions.slice(42,48)},t.prototype.getMouth=function(){return this.positions.slice(48,68)},t.prototype.getRefPointsForAlignment=function(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(Ih)},t}(Yh),Zh=function(){function e(e,t){this._label=e,this._distance=t}return Object.defineProperty(e.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"distance",{get:function(){return this._distance},enumerable:!0,configurable:!0}),e.prototype.toString=function(e){return void 0===e&&(e=!0),this.label+(e?" ("+Th(this.distance)+")":"")},e}(),ef=function(e){function t(t,n){var r=e.call(this,t)||this;return r._label=n,r}return mh(t,e),t.assertIsValidLabeledBox=function(e,t){if(Nh.assertIsValidBox(e,t),!Oh(e.label))throw new Error(t+" - expected property label ("+e.label+") to be a number")},Object.defineProperty(t.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),t}(Nh),tf=function(){function e(e,t){if("string"!=typeof e)throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(t)||t.some((function(e){return!(e instanceof Float32Array)})))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=e,this._descriptors=t}return Object.defineProperty(e.prototype,"label",{get:function(){return this._label},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"descriptors",{get:function(){return this._descriptors},enumerable:!0,configurable:!0}),e.prototype.toJSON=function(){return{label:this.label,descriptors:this.descriptors.map((function(e){return Array.from(e)}))}},e.fromJSON=function(t){var n=t.descriptors.map((function(e){return new Float32Array(e)}));return new e(t.label,n)},e}(),nf=function(e){function t(t,n,r,i){var o=e.call(this,t,n)||this;return o._score=r,o._classScore=i,o}return mh(t,e),t.assertIsValidPredictedBox=function(e,t){if(ef.assertIsValidLabeledBox(e,t),!Ah(e.score)||!Ah(e.classScore))throw new Error(t+" - expected properties score ("+e.score+") and ("+e.classScore+") to be a number between [0, 1]")},Object.defineProperty(t.prototype,"score",{get:function(){return this._score},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"classScore",{get:function(){return this._classScore},enumerable:!0,configurable:!0}),t}(ef);function rf(e){return e.detection instanceof jh}function of(e,t){var n={detection:t};return Object.assign({},e,n)}function af(){var e=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:function(){return document.createElement("canvas")},createImageElement:function(){return document.createElement("img")},fetch:e,readFile:function(){throw new Error("readFile - filesystem not available for browser environment")}}}function sf(e){var t="";if(!e)try{e=n(8730)}catch(e){t=e.toString()}return{readFile:e?function(t){return new Promise((function(n,r){e.readFile(t,(function(e,t){return e?r(e):n(t)}))}))}:function(){throw new Error("readFile - failed to require fs in nodejs environment with error: "+t)}}}function cf(){var e=n.g.Canvas||n.g.HTMLCanvasElement,t=n.g.Image||n.g.HTMLImageElement,r=n.g.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},i=sf();return gh({Canvas:e||function(){},CanvasRenderingContext2D:n.g.CanvasRenderingContext2D||function(){},Image:t||function(){},ImageData:n.g.ImageData||function(){},Video:n.g.HTMLVideoElement||function(){},createCanvasElement:function(){if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},createImageElement:function(){if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},fetch:r},i)}function uf(){return"object"==typeof window&&"undefined"!=typeof document&&"undefined"!=typeof HTMLImageElement&&"undefined"!=typeof HTMLCanvasElement&&"undefined"!=typeof HTMLVideoElement&&"undefined"!=typeof ImageData&&"undefined"!=typeof CanvasRenderingContext2D}function df(){return"object"==typeof n.g&&"undefined"!=typeof process&&!!process.version}function lf(e){Xh=e}function pf(){uf()&&lf(af()),df()&&lf(cf())}var hf,ff={getEnv:function(){if(!Xh)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Xh},setEnv:lf,initialize:pf,createBrowserEnv:af,createFileSystem:sf,createNodejsEnv:cf,monkeyPatch:function(e){if(Xh||pf(),!Xh)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");var t=e.Canvas,n=void 0===t?Xh.Canvas:t,r=e.Image,i=void 0===r?Xh.Image:r;Xh.Canvas=n,Xh.Image=i,Xh.createCanvasElement=e.createCanvasElement||function(){return new n},Xh.createImageElement=e.createImageElement||function(){return new i},Xh.ImageData=e.ImageData||Xh.ImageData,Xh.Video=e.Video||Xh.Video,Xh.fetch=e.fetch||Xh.fetch,Xh.readFile=e.readFile||Xh.readFile},isBrowser:uf,isNodejs:df};function mf(e){return ff.isNodejs()||"string"!=typeof e?e:document.getElementById(e)}function gf(e){var t=ff.getEnv(),n=t.Canvas;if(e instanceof t.CanvasRenderingContext2D)return e;var r=mf(e);if(!(r instanceof n))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");var i=r.getContext("2d");if(!i)throw new Error("resolveContext2d - canvas 2d context is null");return i}pf(),function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"}(hf||(hf={}));var vf=function(e){void 0===e&&(e={});var t=e.anchorPosition,n=e.backgroundColor,r=e.fontColor,i=e.fontSize,o=e.fontStyle,a=e.padding;this.anchorPosition=t||hf.TOP_LEFT,this.backgroundColor=n||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=i||14,this.fontStyle=o||"Georgia",this.padding=a||4},yf=function(){function e(t,n,r){void 0===r&&(r={}),this.text="string"==typeof t?[t]:t instanceof e?t.text:t,this.anchor=n,this.options=new vf(r)}return e.prototype.measureWidth=function(e){var t=this.options.padding;return this.text.map((function(t){return e.measureText(t).width})).reduce((function(e,t){return e<t?t:e}),0)+2*t},e.prototype.measureHeight=function(){var e=this.options,t=e.fontSize,n=e.padding;return this.text.length*t+2*n},e.prototype.getUpperLeft=function(e,t){var n=this.options.anchorPosition,r=n===hf.BOTTOM_RIGHT||n===hf.TOP_RIGHT,i=n===hf.BOTTOM_LEFT||n===hf.BOTTOM_RIGHT,o=this.measureWidth(e),a=this.measureHeight(),s=r?this.anchor.x-o:this.anchor.x,c=i?this.anchor.y-a:this.anchor.y;if(t){var u=t.width,d=t.height;return{x:Math.max(Math.min(s,u-o),0),y:Math.max(Math.min(c,d-a),0)}}return{x:s,y:c}},e.prototype.draw=function(e){var t=mf(e),n=gf(t),r=this.options,i=r.backgroundColor,o=r.fontColor,a=r.fontSize,s=r.fontStyle,c=r.padding;n.font=a+"px "+s;var u=this.measureWidth(n),d=this.measureHeight();n.fillStyle=i;var l=this.getUpperLeft(n,t);n.fillRect(l.x,l.y,u,d),n.fillStyle=o,this.text.forEach((function(e,t){var r=c+l.x,i=c+l.y+(t+1)*a;n.fillText(e,r,i)}))},e}(),bf=function(e){void 0===e&&(e={});var t=e.boxColor,n=e.lineWidth,r=e.label,i=e.drawLabelOptions;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=n||2,this.label=r;var o={anchorPosition:hf.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new vf(Object.assign({},o,i))},wf=function(){function e(e,t){void 0===t&&(t={}),this.box=new Nh(e),this.options=new bf(t)}return e.prototype.draw=function(e){var t=gf(e),n=this.options,r=n.boxColor,i=n.lineWidth,o=this.box,a=o.x,s=o.y,c=o.width,u=o.height;t.strokeStyle=r,t.lineWidth=i,t.strokeRect(a,s,c,u);var d=this.options.label;d&&new yf([d],{x:a-i/2,y:s},this.options.drawLabelOptions).draw(e)},e}();function xf(e,t){(Array.isArray(t)?t:[t]).forEach((function(t){var n=t instanceof jh?t.score:rf(t)?t.detection.score:void 0,r=t instanceof jh?t.box:rf(t)?t.detection.box:new Nh(t),i=n?""+Th(n):void 0;new wf(r,{label:i}).draw(e)}))}function _f(e){var t=ff.getEnv(),n=t.Image,r=t.Video;return e instanceof n&&e.complete||e instanceof r&&e.readyState>=3}function Sf(e){return new Promise((function(t,n){if(e instanceof ff.getEnv().Canvas||_f(e))return t();function r(e){e.currentTarget&&(e.currentTarget.removeEventListener("load",r),e.currentTarget.removeEventListener("error",i),t(e))}function i(e){e.currentTarget&&(e.currentTarget.removeEventListener("load",r),e.currentTarget.removeEventListener("error",i),n(e))}e.addEventListener("load",r),e.addEventListener("error",i)}))}function Rf(e){return new Promise((function(t,n){if(!(e instanceof Blob))return n("bufferToImage - expected buf to be of type: Blob");var r=new FileReader;r.onload=function(){if("string"!=typeof r.result)return n("bufferToImage - expected reader.result to be a string, in onload");var e=ff.getEnv().createImageElement();e.onload=function(){return t(e)},e.onerror=n,e.src=r.result},r.onerror=n,r.readAsDataURL(e)}))}function Cf(e){var t=ff.getEnv(),n=t.Image,r=t.Video;return e instanceof n?new wh(e.naturalWidth,e.naturalHeight):e instanceof r?new wh(e.videoWidth,e.videoHeight):new wh(e.width,e.height)}function Ef(e){var t=e.width,n=e.height,r=(0,ff.getEnv().createCanvasElement)();return r.width=t,r.height=n,r}function kf(e,t){var n=ff.getEnv().ImageData;if(!(e instanceof n||_f(e)))throw new Error("createCanvasFromMedia - media has not finished loading yet");var r=t||Cf(e),i=r.width,o=r.height,a=Ef({width:i,height:o});return e instanceof n?gf(a).putImageData(e,0,0):gf(a).drawImage(e,0,0,i,o),a}function Tf(e,t){return vh(this,void 0,void 0,(function(){var n,r,i,o,a,s;return yh(this,(function(c){switch(c.label){case 0:return n=t||ff.getEnv().createCanvasElement(),r=e.shape.slice(Ch(e)?1:0),i=r[0],o=r[1],a=r[2],s=Jt((function(){return e.as3D(i,o,a).toInt()})),[4,Gp.toPixels(s,n)];case 1:return c.sent(),s.dispose(),[2,n]}}))}))}function Df(e){var t=ff.getEnv(),n=t.Image,r=t.Canvas,i=t.Video;return e instanceof n||e instanceof r||e instanceof i}function Pf(e,t,n){void 0===n&&(n=!1);var r=ff.getEnv(),i=r.Image,o=r.Canvas;if(!(e instanceof i||e instanceof o))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");var a=Cf(e),s=t/Math.max(a.height,a.width),c=s*a.width,u=s*a.height,d=Ef({width:t,height:t}),l=e instanceof o?e:kf(e),p=Math.abs(c-u)/2,h=n&&c<u?p:0,f=n&&u<c?p:0;return gf(d).drawImage(l,h,f,c,u),d}var If=function(){function e(e,t){var n=this;if(void 0===t&&(t=!1),this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw new Error("NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have "+e);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach((function(e,t){if(Rh(e))return n._imageTensors[t]=e,void(n._inputDimensions[t]=e.shape);if(Ch(e)){var r=e.shape[0];if(1!==r)throw new Error("NetInput - tf.Tensor4D with batchSize "+r+" passed, but not supported in input array");return n._imageTensors[t]=e,void(n._inputDimensions[t]=e.shape.slice(1))}var i=e instanceof ff.getEnv().Canvas?e:kf(e);n._canvases[t]=i,n._inputDimensions[t]=[i.height,i.width,3]}))}return Object.defineProperty(e.prototype,"imageTensors",{get:function(){return this._imageTensors},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"canvases",{get:function(){return this._canvases},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isBatchInput",{get:function(){return this.batchSize>1||this._treatAsBatchInput},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"batchSize",{get:function(){return this._batchSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputDimensions",{get:function(){return this._inputDimensions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"reshapedInputDimensions",{get:function(){var e=this;return Mh(this.batchSize,0,1).map((function(t,n){return e.getReshapedInputDimensions(n)}))},enumerable:!0,configurable:!0}),e.prototype.getInput=function(e){return this.canvases[e]||this.imageTensors[e]},e.prototype.getInputDimensions=function(e){return this._inputDimensions[e]},e.prototype.getInputHeight=function(e){return this._inputDimensions[e][0]},e.prototype.getInputWidth=function(e){return this._inputDimensions[e][1]},e.prototype.getReshapedInputDimensions=function(e){if("number"!=typeof this.inputSize)throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");return Ph({width:this.getInputWidth(e),height:this.getInputHeight(e)},this.inputSize)},e.prototype.toBatchTensor=function(e,t){var n=this;return void 0===t&&(t=!0),this._inputSize=e,Jt((function(){var r=Mh(n.batchSize,0,1).map((function(r){var i=n.getInput(r);if(i instanceof _e){var o=Ch(i)?i:i.expandDims();return(o=Gh(o,t)).shape[1]===e&&o.shape[2]===e||(o=Sl.resizeBilinear(o,[e,e])),o.as3D(e,e,3)}if(i instanceof ff.getEnv().Canvas)return Gp.fromPixels(Pf(i,e,t));throw new Error("toBatchTensor - at batchIdx "+r+", expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have "+i)})),i=Nr(r.map((function(e){return e.toFloat()}))).as4D(n.batchSize,e,e,3);return i}))},e}();function Mf(e){return vh(this,void 0,void 0,(function(){var t,n,r;return yh(this,(function(i){switch(i.label){case 0:if(e instanceof If)return[2,e];if(!(t=Array.isArray(e)?e:[e]).length)throw new Error("toNetInput - empty array passed as input");return n=function(t){return Array.isArray(e)?" at input index "+t+":":""},(r=t.map(mf)).forEach((function(e,r){if(!Df(e)&&!Rh(e)&&!Ch(e)){if("string"==typeof t[r])throw new Error("toNetInput -"+n(r)+" string passed, but could not resolve HTMLElement for element id "+t[r]);throw new Error("toNetInput -"+n(r)+" expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id")}if(Ch(e)){var i=e.shape[0];if(1!==i)throw new Error("toNetInput -"+n(r)+" tf.Tensor4D with batchSize "+i+" passed, but not supported in input array")}})),[4,Promise.all(r.map((function(e){return Df(e)&&Sf(e)})))];case 1:return i.sent(),[2,new If(r,Array.isArray(e))]}}))}))}function Of(e,t){return vh(this,void 0,void 0,(function(){var n,r,i,o,a,s;return yh(this,(function(c){switch(c.label){case 0:return n=ff.getEnv().Canvas,r=e,e instanceof n?[3,5]:[4,Mf(e)];case 1:if((i=c.sent()).batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");return(o=i.getInput(0))instanceof n?(a=o,[3,4]):[3,2];case 2:return[4,Tf(o)];case 3:a=c.sent(),c.label=4;case 4:r=a,c.label=5;case 5:return s=gf(r),[2,t.map((function(e){return e instanceof jh?e.forSize(r.width,r.height).box.floor():e})).map((function(e){return e.clipAtImageBorders(r.width,r.height)})).map((function(e){var t=e.x,n=e.y,r=e.width,i=e.height,o=Ef({width:r,height:i});return gf(o).putImageData(s.getImageData(t,n,r,i),0,0),o}))]}}))}))}function Af(e,t){return vh(this,void 0,void 0,(function(){return yh(this,(function(n){if(!Rh(e)&&!Ch(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Ch(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return[2,Jt((function(){var n=e.shape.slice(Ch(e)?1:0),r=n[0],i=n[1],o=n[2],a=t.map((function(e){return e instanceof jh?e.forSize(i,r).box:e})).map((function(e){return e.clipAtImageBorders(i,r)})).map((function(t){var n=t.x,a=t.y,s=t.width,c=t.height;return dd(e.as3D(r,i,o),[a,n,0],[c,s,o])}));return a}))]}))}))}function Ff(e,t){return vh(this,void 0,void 0,(function(){var n;return yh(this,(function(r){switch(r.label){case 0:return[4,(0,ff.getEnv().fetch)(e,t)];case 1:if(!((n=r.sent()).status<400))throw new Error("failed to fetch: ("+n.status+") "+n.statusText+", from url: "+n.url);return[2,n]}}))}))}function Nf(e){return vh(this,void 0,void 0,(function(){var t,n;return yh(this,(function(r){switch(r.label){case 0:return[4,Ff(e)];case 1:return[4,(t=r.sent()).blob()];case 2:if(!(n=r.sent()).type.startsWith("image/"))throw new Error("fetchImage - expected blob type to be of type image/*, instead have: "+n.type+", for url: "+t.url);return[2,Rf(n)]}}))}))}function Lf(e){return vh(this,void 0,void 0,(function(){return yh(this,(function(t){switch(t.label){case 0:return[4,Ff(e)];case 1:return[2,t.sent().json()]}}))}))}function Bf(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=Float32Array.bind,[4,Ff(e)];case 1:return[4,n.sent().arrayBuffer()];case 2:return[2,new(t.apply(Float32Array,[void 0,n.sent()]))]}}))}))}function jf(e,t){var n=t+"-weights_manifest.json";if(!e)return{modelBaseUri:"",manifestUri:n};if("/"===e)return{modelBaseUri:"/",manifestUri:"/"+n};var r=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"",i=(e=e.replace(r,"")).split("/").filter((function(e){return e})),o=e.endsWith(".json")?i[i.length-1]:n,a=r+(e.endsWith(".json")?i.slice(0,i.length-1):i).join("/");return{modelBaseUri:a=e.startsWith("/")?"/"+a:a,manifestUri:"/"===a?"/"+o:a+"/"+o}}function Wf(e,t){return vh(this,void 0,void 0,(function(){var n,r,i,o;return yh(this,(function(a){switch(a.label){case 0:return n=jf(e,t),r=n.manifestUri,i=n.modelBaseUri,[4,Lf(r)];case 1:return o=a.sent(),[2,Wp.loadWeights(o,i)]}}))}))}function zf(e,t,n){void 0===n&&(n=!1);var r=n?Cf(t):t,i=r.width,o=r.height;return e.width=i,e.height=o,{width:i,height:o}}var Uf=function(){function e(e){this._name=e,this._params=void 0,this._paramMappings=[]}return Object.defineProperty(e.prototype,"params",{get:function(){return this._params},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"paramMappings",{get:function(){return this._paramMappings},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isLoaded",{get:function(){return!!this.params},enumerable:!0,configurable:!0}),e.prototype.getParamFromPath=function(e){var t=this.traversePropertyPath(e);return t.obj[t.objProp]},e.prototype.reassignParamFromPath=function(e,t){var n=this.traversePropertyPath(e),r=n.obj,i=n.objProp;r[i].dispose(),r[i]=t},e.prototype.getParamList=function(){var e=this;return this._paramMappings.map((function(t){var n=t.paramPath;return{path:n,tensor:e.getParamFromPath(n)}}))},e.prototype.getTrainableParams=function(){return this.getParamList().filter((function(e){return e.tensor instanceof Te}))},e.prototype.getFrozenParams=function(){return this.getParamList().filter((function(e){return!(e.tensor instanceof Te)}))},e.prototype.variable=function(){var e=this;this.getFrozenParams().forEach((function(t){var n=t.path,r=t.tensor;e.reassignParamFromPath(n,r.variable())}))},e.prototype.freeze=function(){var e=this;this.getTrainableParams().forEach((function(t){var n=t.path,r=t.tensor,i=In(r.dataSync());r.dispose(),e.reassignParamFromPath(n,i)}))},e.prototype.dispose=function(e){void 0===e&&(e=!0),this.getParamList().forEach((function(t){if(e&&t.tensor.isDisposed)throw new Error("param tensor has already been disposed for path "+t.path);t.tensor.dispose()})),this._params=void 0},e.prototype.serializeParams=function(){return new Float32Array(this.getParamList().map((function(e){var t=e.tensor;return Array.from(t.dataSync())})).reduce((function(e,t){return e.concat(t)})))},e.prototype.load=function(e){return vh(this,void 0,void 0,(function(){return yh(this,(function(t){switch(t.label){case 0:return e instanceof Float32Array?(this.extractWeights(e),[2]):[4,this.loadFromUri(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.loadFromUri=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:if(e&&"string"!=typeof e)throw new Error(this._name+".loadFromUri - expected model uri");return[4,Wf(e,this.getDefaultModelName())];case 1:return t=n.sent(),this.loadFromWeightMap(t),[2]}}))}))},e.prototype.loadFromDisk=function(e){return vh(this,void 0,void 0,(function(){var t,n,r,i,o,a,s,c,u,d;return yh(this,(function(l){switch(l.label){case 0:if(e&&"string"!=typeof e)throw new Error(this._name+".loadFromDisk - expected model file path");return t=ff.getEnv().readFile,n=jf(e,this.getDefaultModelName()),r=n.manifestUri,i=n.modelBaseUri,o=function(e){return Promise.all(e.map((function(e){return t(e).then((function(e){return e.buffer}))})))},a=Wp.weightsLoaderFactory(o),u=(c=JSON).parse,[4,t(r)];case 1:return s=u.apply(c,[l.sent().toString()]),[4,a(s,i)];case 2:return d=l.sent(),this.loadFromWeightMap(d),[2]}}))}))},e.prototype.loadFromWeightMap=function(e){var t=this.extractParamsFromWeigthMap(e),n=t.paramMappings,r=t.params;this._paramMappings=n,this._params=r},e.prototype.extractWeights=function(e){var t=this.extractParams(e),n=t.paramMappings,r=t.params;this._paramMappings=n,this._params=r},e.prototype.traversePropertyPath=function(e){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");var t=e.split("/").reduce((function(t,n){if(!t.nextObj.hasOwnProperty(n))throw new Error("traversePropertyPath - object does not have property "+n+", for path "+e);return{obj:t.nextObj,objProp:n,nextObj:t.nextObj[n]}}),{nextObj:this.params}),n=t.obj,r=t.objProp;if(!(n&&r&&n[r]instanceof _e))throw new Error("traversePropertyPath - parameter is not a tensor, for path "+e);return{obj:n,objProp:r}},e}();function Vf(e,t,n){return Jt((function(){var r=Vu(e,t.depthwise_filter,t.pointwise_filter,n,"same");return Xc(r,t.bias)}))}function Gf(e,t,n){return void 0===n&&(n=!1),Jt((function(){var r=kd(n?Xc(Nu(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):Vf(e,t.conv0,[2,2])),i=Vf(r,t.conv1,[1,1]),o=Vf(kd(Xc(r,i)),t.conv2,[1,1]);return kd(Xc(r,Xc(i,o)))}))}function qf(e,t,n,r){return void 0===n&&(n=!1),void 0===r&&(r=!0),Jt((function(){var i=kd(n?Xc(Nu(e,t.conv0.filters,r?[2,2]:[1,1],"same"),t.conv0.bias):Vf(e,t.conv0,r?[2,2]:[1,1])),o=Vf(i,t.conv1,[1,1]),a=Vf(kd(Xc(i,o)),t.conv2,[1,1]),s=Vf(kd(Xc(i,Xc(o,a))),t.conv3,[1,1]);return kd(Xc(i,Xc(o,Xc(a,s))))}))}function Hf(e,t,n,r){return void 0===n&&(n="same"),void 0===r&&(r=!1),Jt((function(){var i=Xc(Nu(e,t.filters,[1,1],n),t.bias);return r?kd(i):i}))}function Kf(e,t){Object.keys(e).forEach((function(n){t.some((function(e){return e.originalPath===n}))||e[n].dispose()}))}function Xf(e,t){return function(n,r,i,o){var a=Ln(e(n*r*i*i),[i,i,n,r]),s=An(e(r));return t.push({paramPath:o+"/filters"},{paramPath:o+"/bias"}),{filters:a,bias:s}}}function $f(e,t){return function(n,r,i){var o=Fn(e(n*r),[n,r]),a=An(e(r));return t.push({paramPath:i+"/weights"},{paramPath:i+"/bias"}),{weights:o,bias:a}}}var Yf=function(e,t,n){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=n};function Qf(e,t){return function(n,r,i){var o=Ln(e(9*n),[3,3,n,1]),a=Ln(e(n*r),[1,1,n,r]),s=An(e(r));return t.push({paramPath:i+"/depthwise_filter"},{paramPath:i+"/pointwise_filter"},{paramPath:i+"/bias"}),new Yf(o,a,s)}}function Jf(e){return function(t){var n=e(t+"/depthwise_filter",4),r=e(t+"/pointwise_filter",4),i=e(t+"/bias",1);return new Yf(n,r,i)}}function Zf(e,t){return function(n,r,i){var o=e[n];if(!xh(o,r))throw new Error("expected weightMap["+n+"] to be a Tensor"+r+"D, instead have "+o);return t.push({originalPath:n,paramPath:i||n}),o}}function em(e){var t=e;return{extractWeights:function(e){var n=t.slice(0,e);return t=t.slice(e),n},getRemainingWeights:function(){return t}}}function tm(e,t){var n=Xf(e,t),r=Qf(e,t);function i(e,t,i,o){return void 0===o&&(o=!1),{conv0:o?n(e,t,3,i+"/conv0"):r(e,t,i+"/conv0"),conv1:r(t,t,i+"/conv1"),conv2:r(t,t,i+"/conv2")}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:function(e,t,n,o){void 0===o&&(o=!1);var a=i(e,t,n,o);return{conv0:a.conv0,conv1:a.conv1,conv2:a.conv2,conv3:r(t,t,n+"/conv3")}}}}function nm(e){return function(t){return{filters:e(t+"/filters",4),bias:e(t+"/bias",1)}}}function rm(e,t){var n=Zf(e,t),r=nm(n),i=Jf(n);return{extractDenseBlock3Params:function(e,t){return void 0===t&&(t=!1),{conv0:t?r(e+"/conv0"):i(e+"/conv0"),conv1:i(e+"/conv1"),conv2:i(e+"/conv2")}},extractDenseBlock4Params:function(e,t){return void 0===t&&(t=!1),{conv0:t?r(e+"/conv0"):i(e+"/conv0"),conv1:i(e+"/conv1"),conv2:i(e+"/conv2"),conv3:i(e+"/conv3")}}}}var im=function(e){function t(){return e.call(this,"FaceFeatureExtractor")||this}return mh(t,e),t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return Jt((function(){var n=qf(Vh(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(On(255)),t.dense0,!0);return n=qf(n,t.dense1),n=qf(n,t.dense2),n=qf(n,t.dense3),rd(n,[7,7],[2,2],"valid")}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.getDefaultModelName=function(){return"face_feature_extractor_model"},t.prototype.extractParamsFromWeigthMap=function(e){return function(e){var t=[],n=rm(e,t).extractDenseBlock4Params,r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return Kf(e,t),{params:r,paramMappings:t}}(e)},t.prototype.extractParams=function(e){return function(e){var t=[],n=em(e),r=n.extractWeights,i=n.getRemainingWeights,o=tm(r,t).extractDenseBlock4Params,a=o(3,32,"dense0",!0),s=o(32,64,"dense1"),c=o(64,128,"dense2"),u=o(128,256,"dense3");if(0!==i().length)throw new Error("weights remaing after extract: "+i().length);return{paramMappings:t,params:{dense0:a,dense1:s,dense2:c,dense3:u}}}(e)},t}(Uf);function om(e,t){return Jt((function(){return Xc(Hu(e,t.weights),t.bias)}))}function am(e){var t={},n={};return Object.keys(e).forEach((function(r){(r.startsWith("fc")?n:t)[r]=e[r]})),{featureExtractorMap:t,classifierMap:n}}var sm=function(e){function t(t,n){var r=e.call(this,t)||this;return r._faceFeatureExtractor=n,r}return mh(t,e),Object.defineProperty(t.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var t=this,n=this.params;if(!n)throw new Error(this._name+" - load model before inference");return Jt((function(){var r=e instanceof If?t.faceFeatureExtractor.forwardInput(e):e;return om(r.as2D(r.shape[0],-1),n.fc)}))},t.prototype.dispose=function(t){void 0===t&&(t=!0),this.faceFeatureExtractor.dispose(t),e.prototype.dispose.call(this,t)},t.prototype.loadClassifierParams=function(e){var t=this.extractClassifierParams(e),n=t.params,r=t.paramMappings;this._params=n,this._paramMappings=r},t.prototype.extractClassifierParams=function(e){return function(e,t,n){var r=[],i=em(e),o=i.extractWeights,a=i.getRemainingWeights,s=$f(o,r)(t,n,"fc");if(0!==a().length)throw new Error("weights remaing after extract: "+a().length);return{paramMappings:r,params:{fc:s}}}(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())},t.prototype.extractParamsFromWeigthMap=function(e){var t=am(e),n=t.featureExtractorMap,r=t.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),function(e){var t=[],n=Zf(e,t),r={fc:{weights:n("fc/weights",2),bias:n("fc/bias",1)}};return Kf(e,t),{params:r,paramMappings:t}}(r)},t.prototype.extractParams=function(e){var t=this.getClassifierChannelsIn(),n=this.getClassifierChannelsOut(),r=n*t+n,i=e.slice(0,e.length-r),o=e.slice(e.length-r);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(o)},t}(Uf),cm=["neutral","happy","sad","angry","fearful","disgusted","surprised"],um=function(){function e(e){var t=this;if(7!==e.length)throw new Error("FaceExpressions.constructor - expected probabilities.length to be 7, have: "+e.length);cm.forEach((function(n,r){t[n]=e[r]}))}return e.prototype.asSortedArray=function(){var e=this;return cm.map((function(t){return{expression:t,probability:e[t]}})).sort((function(e,t){return t.probability-e.probability}))},e}(),dm=function(e){function t(t){return void 0===t&&(t=new im),e.call(this,"FaceExpressionNet",t)||this}return mh(t,e),t.prototype.forwardInput=function(e){var t=this;return Jt((function(){return fi(t.runNet(e))}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.predictExpressions=function(e){return vh(this,void 0,void 0,(function(){var t,n,r,i,o=this;return yh(this,(function(a){switch(a.label){case 0:return[4,Mf(e)];case 1:return t=a.sent(),[4,this.forwardInput(t)];case 2:return n=a.sent(),[4,Promise.all(jr(n).map((function(e){return vh(o,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return[4,e.data()];case 1:return t=n.sent(),e.dispose(),[2,t]}}))}))})))];case 3:return r=a.sent(),n.dispose(),i=r.map((function(e){return new um(e)})),[2,t.isBatchInput?i:i[0]]}}))}))},t.prototype.getDefaultModelName=function(){return"face_expression_model"},t.prototype.getClassifierChannelsIn=function(){return 256},t.prototype.getClassifierChannelsOut=function(){return 7},t}(sm);function lm(e){return e.expressions instanceof um}function pm(e,t){var n={expressions:t};return Object.assign({},e,n)}function hm(e,t,n,r){void 0===n&&(n=.1),(Array.isArray(t)?t:[t]).forEach((function(t){var i=t instanceof um?t:lm(t)?t.expressions:void 0;if(!i)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");var o=i.asSortedArray().filter((function(e){return e.probability>n})),a=rf(t)?t.detection.box.bottomLeft:r||new Fh(0,0),s=new yf(o.map((function(e){return e.expression+" ("+Th(e.probability)+")"})),a);s.draw(e)}))}function fm(e){return rf(e)&&e.landmarks instanceof Yh&&e.unshiftedLandmarks instanceof Yh&&e.alignedRect instanceof jh}function mm(e,t){var n=e.detection.box,r=t.shiftBy(n.x,n.y),i=r.align(),o=e.detection.imageDims,a={landmarks:r,unshiftedLandmarks:t,alignedRect:new jh(e.detection.score,i.rescale(o.reverse()),o)};return Object.assign({},e,a)}var gm=function(e){void 0===e&&(e={});var t=e.drawLines,n=void 0===t||t,r=e.drawPoints,i=void 0===r||r,o=e.lineWidth,a=e.lineColor,s=e.pointSize,c=e.pointColor;this.drawLines=n,this.drawPoints=i,this.lineWidth=o||1,this.pointSize=s||2,this.lineColor=a||"rgba(0, 255, 255, 1)",this.pointColor=c||"rgba(255, 0, 255, 1)"},vm=function(){function e(e,t){void 0===t&&(t={}),this.faceLandmarks=e,this.options=new gm(t)}return e.prototype.draw=function(e){var t=gf(e),n=this.options,r=n.drawLines,i=n.drawPoints,o=n.lineWidth,a=n.lineColor,s=n.pointSize,c=n.pointColor;r&&this.faceLandmarks instanceof Jh&&(t.strokeStyle=a,t.lineWidth=o,hh(t,this.faceLandmarks.getJawOutline()),hh(t,this.faceLandmarks.getLeftEyeBrow()),hh(t,this.faceLandmarks.getRightEyeBrow()),hh(t,this.faceLandmarks.getNose()),hh(t,this.faceLandmarks.getLeftEye(),!0),hh(t,this.faceLandmarks.getRightEye(),!0),hh(t,this.faceLandmarks.getMouth(),!0)),i&&(t.strokeStyle=c,t.fillStyle=c,this.faceLandmarks.positions.forEach((function(e){t.beginPath(),t.arc(e.x,e.y,s,0,2*Math.PI),t.fill()})))},e}();function ym(e,t){(Array.isArray(t)?t:[t]).forEach((function(t){var n=t instanceof Yh?t:fm(t)?t.landmarks:void 0;if(!n)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new vm(n).draw(e)}))}function bm(e,t,n){return Xc(Nu(e,t.filters,n,"same"),t.bias)}function wm(e,t,n){void 0===n&&(n=!0);var r=n?kd(e):e;return r=Vf(r,t.separable_conv0,[1,1]),r=Vf(kd(r),t.separable_conv1,[1,1]),r=nd(r,[3,3],[2,2],"same"),Xc(r,bm(e,t.expansion_conv,[2,2]))}var xm,_m=function(e){function t(t){var n=e.call(this,"TinyXception")||this;return n._numMainBlocks=t,n}return mh(t,e),t.prototype.forwardInput=function(e){var t=this,n=this.params;if(!n)throw new Error("TinyXception - load model before inference");return Jt((function(){var r=Vh(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(On(256)),i=kd(bm(r,n.entry_flow.conv_in,[2,2]));return i=wm(i,n.entry_flow.reduction_block_0,!1),i=wm(i,n.entry_flow.reduction_block_1),Mh(t._numMainBlocks,0,1).forEach((function(e){i=function(e,t){var n=Vf(kd(e),t.separable_conv0,[1,1]);return n=Vf(kd(n),t.separable_conv1,[1,1]),n=Vf(kd(n),t.separable_conv2,[1,1]),Xc(n,e)}(i,n.middle_flow["main_block_"+e])})),i=wm(i,n.exit_flow.reduction_block),i=kd(Vf(i,n.exit_flow.separable_conv,[1,1]))}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.getDefaultModelName=function(){return"tiny_xception_model"},t.prototype.extractParamsFromWeigthMap=function(e){return function(e,t){var n=[],r=function(e,t){var n=Zf(e,t),r=nm(n),i=Jf(n);return{extractConvParams:r,extractSeparableConvParams:i,extractReductionBlockParams:function(e){return{separable_conv0:i(e+"/separable_conv0"),separable_conv1:i(e+"/separable_conv1"),expansion_conv:r(e+"/expansion_conv")}},extractMainBlockParams:function(e){return{separable_conv0:i(e+"/separable_conv0"),separable_conv1:i(e+"/separable_conv1"),separable_conv2:i(e+"/separable_conv2")}}}}(e,n),i=r.extractConvParams,o=r.extractSeparableConvParams,a=r.extractReductionBlockParams,s=r.extractMainBlockParams,c={conv_in:i("entry_flow/conv_in"),reduction_block_0:a("entry_flow/reduction_block_0"),reduction_block_1:a("entry_flow/reduction_block_1")},u={};Mh(t,0,1).forEach((function(e){u["main_block_"+e]=s("middle_flow/main_block_"+e)}));var d={reduction_block:a("exit_flow/reduction_block"),separable_conv:o("exit_flow/separable_conv")};return Kf(e,n),{params:{entry_flow:c,middle_flow:u,exit_flow:d},paramMappings:n}}(e,this._numMainBlocks)},t.prototype.extractParams=function(e){return function(e,t){var n=[],r=em(e),i=r.extractWeights,o=r.getRemainingWeights,a=function(e,t){var n=Xf(e,t),r=Qf(e,t);return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:function(e,t,i){return{separable_conv0:r(e,t,i+"/separable_conv0"),separable_conv1:r(t,t,i+"/separable_conv1"),expansion_conv:n(e,t,1,i+"/expansion_conv")}},extractMainBlockParams:function(e,t){return{separable_conv0:r(e,e,t+"/separable_conv0"),separable_conv1:r(e,e,t+"/separable_conv1"),separable_conv2:r(e,e,t+"/separable_conv2")}}}}(i,n),s=a.extractConvParams,c=a.extractSeparableConvParams,u=a.extractReductionBlockParams,d=a.extractMainBlockParams,l={conv_in:s(3,32,3,"entry_flow/conv_in"),reduction_block_0:u(32,64,"entry_flow/reduction_block_0"),reduction_block_1:u(64,128,"entry_flow/reduction_block_1")},p={};Mh(t,0,1).forEach((function(e){p["main_block_"+e]=d(128,"middle_flow/main_block_"+e)}));var h={reduction_block:u(128,256,"exit_flow/reduction_block"),separable_conv:c(256,512,"exit_flow/separable_conv")};if(0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{paramMappings:n,params:{entry_flow:l,middle_flow:p,exit_flow:h}}}(e,this._numMainBlocks)},t}(Uf);!function(e){e.FEMALE="female",e.MALE="male"}(xm||(xm={}));var Sm=function(e){function t(t){void 0===t&&(t=new _m(2));var n=e.call(this,"AgeGenderNet")||this;return n._faceFeatureExtractor=t,n}return mh(t,e),Object.defineProperty(t.prototype,"faceFeatureExtractor",{get:function(){return this._faceFeatureExtractor},enumerable:!0,configurable:!0}),t.prototype.runNet=function(e){var t=this,n=this.params;if(!n)throw new Error(this._name+" - load model before inference");return Jt((function(){var r=e instanceof If?t.faceFeatureExtractor.forwardInput(e):e,i=rd(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1);return{age:om(i,n.fc.age).as1D(),gender:om(i,n.fc.gender)}}))},t.prototype.forwardInput=function(e){var t=this;return Jt((function(){var n=t.runNet(e),r=n.age,i=n.gender;return{age:r,gender:fi(i)}}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.predictAgeAndGender=function(e){return vh(this,void 0,void 0,(function(){var t,n,r,i,o,a,s=this;return yh(this,(function(c){switch(c.label){case 0:return[4,Mf(e)];case 1:return t=c.sent(),[4,this.forwardInput(t)];case 2:return n=c.sent(),r=jr(n.age),i=jr(n.gender),o=r.map((function(e,t){return{ageTensor:e,genderTensor:i[t]}})),[4,Promise.all(o.map((function(e){var t=e.ageTensor,n=e.genderTensor;return vh(s,void 0,void 0,(function(){var e,r,i,o,a;return yh(this,(function(s){switch(s.label){case 0:return[4,t.data()];case 1:return e=s.sent()[0],[4,n.data()];case 2:return r=s.sent()[0],o=(i=r>.5)?xm.MALE:xm.FEMALE,a=i?r:1-r,t.dispose(),n.dispose(),[2,{age:e,gender:o,genderProbability:a}]}}))}))})))];case 3:return a=c.sent(),n.age.dispose(),n.gender.dispose(),[2,t.isBatchInput?a:a[0]]}}))}))},t.prototype.getDefaultModelName=function(){return"age_gender_model"},t.prototype.dispose=function(t){void 0===t&&(t=!0),this.faceFeatureExtractor.dispose(t),e.prototype.dispose.call(this,t)},t.prototype.loadClassifierParams=function(e){var t=this.extractClassifierParams(e),n=t.params,r=t.paramMappings;this._params=n,this._paramMappings=r},t.prototype.extractClassifierParams=function(e){return function(e){var t=[],n=em(e),r=n.extractWeights,i=n.getRemainingWeights,o=$f(r,t),a=o(512,1,"fc/age"),s=o(512,2,"fc/gender");if(0!==i().length)throw new Error("weights remaing after extract: "+i().length);return{paramMappings:t,params:{fc:{age:a,gender:s}}}}(e)},t.prototype.extractParamsFromWeigthMap=function(e){var t=am(e),n=t.featureExtractorMap,r=t.classifierMap;return this.faceFeatureExtractor.loadFromWeightMap(n),function(e){var t=[],n=Zf(e,t);function r(e){return{weights:n(e+"/weights",2),bias:n(e+"/bias",1)}}var i={fc:{age:r("fc/age"),gender:r("fc/gender")}};return Kf(e,t),{params:i,paramMappings:t}}(r)},t.prototype.extractParams=function(e){var t=e.slice(0,e.length-1539),n=e.slice(e.length-1539);return this.faceFeatureExtractor.extractWeights(t),this.extractClassifierParams(n)},t}(Uf),Rm=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.postProcess=function(e,t,n){var r=n.map((function(e){var n=e.width,r=e.height,i=t/Math.max(r,n);return{width:n*i,height:r*i}})),i=r.length;return Jt((function(){var n=function(e,t){return Nr([Vn([68],e),Vn([68],t)],1).as2D(1,136).as1D()},o=function(e,t){var n=r[e],i=n.width,o=n.height;return t(i,o)?Math.abs(i-o)/2:0};return e.mul(Vn([i,136],t)).sub(Nr(Array.from(Array(i),(function(e,t){return n(function(e){return o(e,(function(e,t){return e<t}))}(t),function(e){return o(e,(function(e,t){return t<e}))}(t))})))).div(Nr(Array.from(Array(i),(function(e,t){return n(r[t].width,r[t].height)}))))}))},t.prototype.forwardInput=function(e){var t=this;return Jt((function(){var n=t.runNet(e);return t.postProcess(n,e.inputSize,e.inputDimensions.map((function(e){return{height:e[0],width:e[1]}})))}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.detectLandmarks=function(e){return vh(this,void 0,void 0,(function(){var t,n,r,i=this;return yh(this,(function(o){switch(o.label){case 0:return[4,Mf(e)];case 1:return t=o.sent(),n=Jt((function(){return jr(i.forwardInput(t))})),[4,Promise.all(n.map((function(e,n){return vh(i,void 0,void 0,(function(){var r,i,o,a,s;return yh(this,(function(c){switch(c.label){case 0:return o=(i=Array).from,[4,e.data()];case 1:return r=o.apply(i,[c.sent()]),a=r.filter((function(e,t){return kh(t)})),s=r.filter((function(e,t){return!kh(t)})),[2,new Jh(Array(68).fill(0).map((function(e,t){return new Fh(a[t],s[t])})),{height:t.getInputHeight(n),width:t.getInputWidth(n)})]}}))}))})))];case 2:return r=o.sent(),n.forEach((function(e){return e.dispose()})),[2,t.isBatchInput?r:r[0]]}}))}))},t.prototype.getClassifierChannelsOut=function(){return 136},t}(sm),Cm=function(e){function t(t){return void 0===t&&(t=new im),e.call(this,"FaceLandmark68Net",t)||this}return mh(t,e),t.prototype.getDefaultModelName=function(){return"face_landmark_68_model"},t.prototype.getClassifierChannelsIn=function(){return 256},t}(Rm),Em=function(e){function t(){return e.call(this,"TinyFaceFeatureExtractor")||this}return mh(t,e),t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return Jt((function(){var n=Gf(Vh(e.toBatchTensor(112,!0),[122.782,117.001,104.298]).div(On(255)),t.dense0,!0);return n=Gf(n,t.dense1),n=Gf(n,t.dense2),rd(n,[14,14],[2,2],"valid")}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.getDefaultModelName=function(){return"face_feature_extractor_tiny_model"},t.prototype.extractParamsFromWeigthMap=function(e){return function(e){var t=[],n=rm(e,t).extractDenseBlock3Params,r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return Kf(e,t),{params:r,paramMappings:t}}(e)},t.prototype.extractParams=function(e){return function(e){var t=[],n=em(e),r=n.extractWeights,i=n.getRemainingWeights,o=tm(r,t).extractDenseBlock3Params,a=o(3,32,"dense0",!0),s=o(32,64,"dense1"),c=o(64,128,"dense2");if(0!==i().length)throw new Error("weights remaing after extract: "+i().length);return{paramMappings:t,params:{dense0:a,dense1:s,dense2:c}}}(e)},t}(Uf),km=function(e){function t(t){return void 0===t&&(t=new Em),e.call(this,"FaceLandmark68TinyNet",t)||this}return mh(t,e),t.prototype.getDefaultModelName=function(){return"face_landmark_68_tiny_model"},t.prototype.getClassifierChannelsIn=function(){return 128},t}(Rm),Tm=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t}(Cm);function Dm(e,t,n,r,i){void 0===i&&(i="same");var o=t.conv,a=o.filters,s=o.bias,c=Nu(e,a,n,i);return c=function(e,t){return Xc(cu(e,t.weights),t.biases)}(c=Xc(c,s),t.scale),r?kd(c):c}function Pm(e,t){return Dm(e,t,[1,1],!1)}function Im(e,t){return Dm(e,t,[2,2],!0,"valid")}function Mm(e,t){var n=function(e,t){return Dm(e,t,[1,1],!0)}(e,t.conv1);return n=Pm(n,t.conv2),n=Xc(n,e),kd(n)}function Om(e,t){var n=Im(e,t.conv1);n=Pm(n,t.conv2);var r=rd(e,2,2,"valid"),i=Un(r.shape),o=r.shape[3]!==n.shape[3];if(r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2]){var a=bh(n.shape);a[1]=1;var s=Un(a),c=bh((n=Xn([n,s],1)).shape);c[2]=1;var u=Un(c);n=Xn([n,u],2)}return r=o?Xn([r,i],3):r,n=Xc(r,n),kd(n)}var Am=function(e){function t(){return e.call(this,"FaceRecognitionNet")||this}return mh(t,e),t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return Jt((function(){var n=Im(Vh(e.toBatchTensor(150,!0).toFloat(),[122.782,117.001,104.298]).div(On(256)),t.conv32_down);n=Mm(n=nd(n,3,2,"valid"),t.conv32_1),n=Mm(n,t.conv32_2),n=Mm(n,t.conv32_3),n=Mm(n=Om(n,t.conv64_down),t.conv64_1),n=Mm(n,t.conv64_2),n=Mm(n,t.conv64_3),n=Mm(n=Om(n,t.conv128_down),t.conv128_1),n=Mm(n,t.conv128_2),n=Mm(n=Om(n,t.conv256_down),t.conv256_1);var r=(n=Om(n=Mm(n,t.conv256_2),t.conv256_down_out)).mean([1,2]);return Hu(r,t.fc)}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.computeFaceDescriptor=function(e){return vh(this,void 0,void 0,(function(){var t,n,r,i=this;return yh(this,(function(o){switch(o.label){case 0:return[4,Mf(e)];case 1:return t=o.sent(),n=Jt((function(){return jr(i.forwardInput(t))})),[4,Promise.all(n.map((function(e){return e.data()})))];case 2:return r=o.sent(),n.forEach((function(e){return e.dispose()})),[2,t.isBatchInput?r:r[0]]}}))}))},t.prototype.getDefaultModelName=function(){return"face_recognition_model"},t.prototype.extractParamsFromWeigthMap=function(e){return function(e){var t=[],n=function(e,t){var n=Zf(e,t);function r(e){var t=n(e+"/conv/filters",4),r=n(e+"/conv/bias",1),i=function(e){return{weights:n(e+"/scale/weights",1),biases:n(e+"/scale/biases",1)}}(e);return{conv:{filters:t,bias:r},scale:i}}return{extractConvLayerParams:r,extractResidualLayerParams:function(e){return{conv1:r(e+"/conv1"),conv2:r(e+"/conv2")}}}}(e,t),r=n.extractConvLayerParams,i=n.extractResidualLayerParams,o=r("conv32_down"),a=i("conv32_1"),s=i("conv32_2"),c=i("conv32_3"),u=i("conv64_down"),d=i("conv64_1"),l=i("conv64_2"),p=i("conv64_3"),h=i("conv128_down"),f=i("conv128_1"),m=i("conv128_2"),g=i("conv256_down"),v=i("conv256_1"),y=i("conv256_2"),b=i("conv256_down_out"),w=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!Sh(w))throw new Error("expected weightMap[fc] to be a Tensor2D, instead have "+w);var x={conv32_down:o,conv32_1:a,conv32_2:s,conv32_3:c,conv64_down:u,conv64_1:d,conv64_2:l,conv64_3:p,conv128_down:h,conv128_1:f,conv128_2:m,conv256_down:g,conv256_1:v,conv256_2:y,conv256_down_out:b,fc:w};return Kf(e,t),{params:x,paramMappings:t}}(e)},t.prototype.extractParams=function(e){return function(e){var t=em(e),n=t.extractWeights,r=t.getRemainingWeights,i=[],o=function(e,t){function n(n,r,i,o){var a=function(n,r,i,o){var a=function(t,n,r){var i=e(t),o=i.length/(n*r*r);if(Eh(o))throw new Error("depth has to be an integer: "+o+", weights.length: "+i.length+", numFilters: "+n+", filterSize: "+r);return Jt((function(){return Pd(Ln(i,[n,o,r,r]),[2,3,1,0])}))}(n,r,i),s=An(e(r));return t.push({paramPath:o+"/filters"},{paramPath:o+"/bias"}),{filters:a,bias:s}}(n,r,i,o+"/conv"),s=function(n,r){var i=An(e(n)),o=An(e(n));return t.push({paramPath:r+"/weights"},{paramPath:r+"/biases"}),{weights:i,biases:o}}(r,o+"/scale");return{conv:a,scale:s}}return{extractConvLayerParams:n,extractResidualLayerParams:function(e,t,r,i,o){return void 0===o&&(o=!1),{conv1:n((o?.5:1)*e,t,r,i+"/conv1"),conv2:n(e,t,r,i+"/conv2")}}}}(n,i),a=o.extractConvLayerParams,s=o.extractResidualLayerParams,c=a(4704,32,7,"conv32_down"),u=s(9216,32,3,"conv32_1"),d=s(9216,32,3,"conv32_2"),l=s(9216,32,3,"conv32_3"),p=s(36864,64,3,"conv64_down",!0),h=s(36864,64,3,"conv64_1"),f=s(36864,64,3,"conv64_2"),m=s(36864,64,3,"conv64_3"),g=s(147456,128,3,"conv128_down",!0),v=s(147456,128,3,"conv128_1"),y=s(147456,128,3,"conv128_2"),b=s(589824,256,3,"conv256_down",!0),w=s(589824,256,3,"conv256_1"),x=s(589824,256,3,"conv256_2"),_=s(589824,256,3,"conv256_down_out"),S=Jt((function(){return Pd(Fn(n(32768),[128,256]),[1,0])}));if(i.push({paramPath:"fc"}),0!==r().length)throw new Error("weights remaing after extract: "+r().length);return{params:{conv32_down:c,conv32_1:u,conv32_2:d,conv32_3:l,conv64_down:p,conv64_1:h,conv64_2:f,conv64_3:m,conv128_down:g,conv128_1:v,conv128_2:y,conv256_down:b,conv256_1:w,conv256_2:x,conv256_down_out:_,fc:S},paramMappings:i}}(e)},t}(Uf);function Fm(e){var t=new Am;return t.extractWeights(e),t}function Nm(e,t){var n={descriptor:t};return Object.assign({},e,n)}function Lm(e){return"number"==typeof e.age}function Bm(e,t){var n={age:t};return Object.assign({},e,n)}function jm(e){return(e.gender===xm.MALE||e.gender===xm.FEMALE)&&Ah(e.genderProbability)}function Wm(e,t,n){var r={gender:t,genderProbability:n};return Object.assign({},e,r)}var zm=function(){function e(e){var t=void 0===e?{}:e,n=t.minFaceSize,r=t.scaleFactor,i=t.maxNumScales,o=t.scoreThresholds,a=t.scaleSteps;if(this._name="MtcnnOptions",this._minFaceSize=n||20,this._scaleFactor=r||.709,this._maxNumScales=i||10,this._scoreThresholds=o||[.6,.7,.7],this._scaleSteps=a,"number"!=typeof this._minFaceSize||this._minFaceSize<0)throw new Error(this._name+" - expected minFaceSize to be a number > 0");if("number"!=typeof this._scaleFactor||this._scaleFactor<=0||this._scaleFactor>=1)throw new Error(this._name+" - expected scaleFactor to be a number between 0 and 1");if("number"!=typeof this._maxNumScales||this._maxNumScales<0)throw new Error(this._name+" - expected maxNumScales to be a number > 0");if(!Array.isArray(this._scoreThresholds)||3!==this._scoreThresholds.length||this._scoreThresholds.some((function(e){return"number"!=typeof e})))throw new Error(this._name+" - expected scoreThresholds to be an array of numbers of length 3");if(this._scaleSteps&&(!Array.isArray(this._scaleSteps)||this._scaleSteps.some((function(e){return"number"!=typeof e}))))throw new Error(this._name+" - expected scaleSteps to be an array of numbers")}return Object.defineProperty(e.prototype,"minFaceSize",{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scaleFactor",{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxNumScales",{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scoreThresholds",{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scaleSteps",{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),e}();function Um(e,t,n){return Jt((function(){var r=Nu(e,t.filters,n,"same");return r=Xc(r,t.batch_norm_offset),nc(r,0,6)}))}function Vm(e,t,n){var r=e.arraySync(),i=Math.min(r[t][0],r[t][2]),o=Math.min(r[t][1],r[t][3]),a=Math.max(r[t][0],r[t][2]),s=Math.max(r[t][1],r[t][3]),c=Math.min(r[n][0],r[n][2]),u=Math.min(r[n][1],r[n][3]),d=Math.max(r[n][0],r[n][2]),l=Math.max(r[n][1],r[n][3]),p=(a-i)*(s-o),h=(d-c)*(l-u);if(p<=0||h<=0)return 0;var f=Math.max(i,c),m=Math.max(o,u),g=Math.min(a,d),v=Math.min(s,l),y=Math.max(g-f,0)*Math.max(v-m,0);return y/(p+h-y)}function Gm(e,t){return Jt((function(){var n=e.shape[0];return{boxPredictionEncoding:Or(Hf(e,t.box_encoding_predictor),[n,-1,1,4]),classPrediction:Or(Hf(e,t.class_predictor),[n,-1,3])}}))}var qm=function(){function e(e){var t=void 0===e?{}:e,n=t.minConfidence,r=t.maxResults;if(this._name="SsdMobilenetv1Options",this._minConfidence=n||.5,this._maxResults=r||100,"number"!=typeof this._minConfidence||this._minConfidence<=0||this._minConfidence>=1)throw new Error(this._name+" - expected minConfidence to be a number between 0 and 1");if("number"!=typeof this._maxResults)throw new Error(this._name+" - expected maxResults to be a number")}return Object.defineProperty(e.prototype,"minConfidence",{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxResults",{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),e}(),Hm=function(e){function t(){return e.call(this,"SsdMobilenetv1")||this}return mh(t,e),t.prototype.forwardInput=function(e){var t=this.params;if(!t)throw new Error("SsdMobilenetv1 - load model before inference");return Jt((function(){var n=e.toBatchTensor(512,!1).toFloat(),r=function(e,t){return Jt((function(){var n=null,r=Um(e,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach((function(e,t){var i=t+1,o=function(e){return[2,4,6,12].some((function(t){return t===e}))?[2,2]:[1,1]}(i);r=function(e,t,n){return Jt((function(){var r=Wu(e,t.filters,n,"same");return r=Bc(r,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,.0010000000474974513),nc(r,0,6)}))}(r,e.depthwise_conv,o),r=Um(r,e.pointwise_conv,[1,1]),11===i&&(n=r)})),null===n)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:r,conv11:n}}))}(hu(cu(n,On(.007843137718737125)),On(1)),t.mobilenetv1),i=function(e,t,n){return Jt((function(){var r=Um(e,n.conv_0,[1,1]),i=Um(r,n.conv_1,[2,2]),o=Um(i,n.conv_2,[1,1]),a=Um(o,n.conv_3,[2,2]),s=Um(a,n.conv_4,[1,1]),c=Um(s,n.conv_5,[2,2]),u=Um(c,n.conv_6,[1,1]),d=Um(u,n.conv_7,[2,2]),l=Gm(t,n.box_predictor_0),p=Gm(e,n.box_predictor_1),h=Gm(i,n.box_predictor_2),f=Gm(a,n.box_predictor_3),m=Gm(c,n.box_predictor_4),g=Gm(d,n.box_predictor_5);return{boxPredictions:Xn([l.boxPredictionEncoding,p.boxPredictionEncoding,h.boxPredictionEncoding,f.boxPredictionEncoding,m.boxPredictionEncoding,g.boxPredictionEncoding],1),classPredictions:Xn([l.classPrediction,p.classPrediction,h.classPrediction,f.classPrediction,m.classPrediction,g.classPrediction],1)}}))}(r.out,r.conv11,t.prediction_layer);return function(e,t,n){return Jt((function(){var r=e.shape[0],i=function(e,t){var n=function(e){var t=jr(Pd(e,[1,0])),n=[hu(t[2],t[0]),hu(t[3],t[1])];return{sizes:n,centers:[Xc(t[0],Jc(n[0],On(2))),Xc(t[1],Jc(n[1],On(2)))]}}(e),r=n.sizes,i=n.centers,o=jr(Pd(t,[1,0])),a=Jc(cu(ac(Jc(o[2],On(5))),r[0]),On(2)),s=Xc(cu(Jc(o[0],On(10)),r[0]),i[0]),c=Jc(cu(ac(Jc(o[3],On(5))),r[1]),On(2)),u=Xc(cu(Jc(o[1],On(10)),r[1]),i[1]);return Pd(Nr([hu(s,a),hu(u,c),Xc(s,a),Xc(u,c)]),[1,0])}(Or(Lr(n.extra_dim,[r,1,1]),[-1,4]),Or(e,[-1,4]));i=Or(i,[r,i.shape[0]/r,4]);var o=gc(sd(t,[0,0,1],[-1,-1,-1])),a=sd(o,[0,0,0],[-1,-1,1]);return a=Or(a,[r,a.shape[1]]),{boxes:jr(i),scores:jr(a)}}))}(i.boxPredictions,i.classPredictions,t.output_layer)}))},t.prototype.forward=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=this.forwardInput,[4,Mf(e)];case 1:return[2,t.apply(this,[n.sent()])]}}))}))},t.prototype.locateFaces=function(e,t){return void 0===t&&(t={}),vh(this,void 0,void 0,(function(){var n,r,i,o,a,s,c,u,d,l,p,h,f,m,g,v,y,b,w,x;return yh(this,(function(_){switch(_.label){case 0:return n=new qm(t),r=n.maxResults,i=n.minConfidence,[4,Mf(e)];case 1:for(o=_.sent(),a=this.forwardInput(o),s=a.boxes,c=a.scores,u=s[0],d=c[0],l=1;l<s.length;l++)s[l].dispose(),c[l].dispose();return f=(h=Array).from,[4,d.data()];case 2:return p=f.apply(h,[_.sent()]),m=function(e,t,n,r,i){var o=e.shape[0],a=Math.min(n,o),s=t.map((function(e,t){return{score:e,boxIndex:t}})).filter((function(e){return e.score>i})).sort((function(e,t){return t.score-e.score})),c=function(e){return e<=.5?1:0},u=[];return s.forEach((function(t){if(!(u.length>=a)){for(var n=t.score,r=u.length-1;r>=0;--r){var o=Vm(e,t.boxIndex,u[r]);if(0!==o&&(t.score*=c(o),t.score<=i))break}n===t.score&&u.push(t.boxIndex)}})),u}(u,p,r,0,i),g=o.getReshapedInputDimensions(0),v=o.inputSize,y=v/g.width,b=v/g.height,w=u.arraySync(),x=m.map((function(e){var t=[Math.max(0,w[e][0]),Math.min(1,w[e][2])].map((function(e){return e*b})),n=t[0],r=t[1],i=[Math.max(0,w[e][1]),Math.min(1,w[e][3])].map((function(e){return e*y})),a=i[0],s=i[1];return new jh(p[e],new $h(a,n,s-a,r-n),{height:o.getInputHeight(0),width:o.getInputWidth(0)})})),u.dispose(),d.dispose(),[2,x]}}))}))},t.prototype.getDefaultModelName=function(){return"ssd_mobilenetv1_model"},t.prototype.extractParamsFromWeigthMap=function(e){return function(e){var t=[],n=function(e,t){var n=Zf(e,t);function r(e,t,r){return{filters:n(e+"/Conv2d_"+t+"_pointwise/weights",4,r+"/filters"),batch_norm_offset:n(e+"/Conv2d_"+t+"_pointwise/convolution_bn_offset",1,r+"/batch_norm_offset")}}function i(e){var t="mobilenetv1/conv_"+e,i="MobilenetV1/Conv2d_"+e+"_depthwise",o=t+"/depthwise_conv",a=t+"/pointwise_conv";return{depthwise_conv:{filters:n(i+"/depthwise_weights",4,o+"/filters"),batch_norm_scale:n(i+"/BatchNorm/gamma",1,o+"/batch_norm_scale"),batch_norm_offset:n(i+"/BatchNorm/beta",1,o+"/batch_norm_offset"),batch_norm_mean:n(i+"/BatchNorm/moving_mean",1,o+"/batch_norm_mean"),batch_norm_variance:n(i+"/BatchNorm/moving_variance",1,o+"/batch_norm_variance")},pointwise_conv:r("MobilenetV1",e,a)}}function o(e,t){return{filters:n(e+"/weights",4,t+"/filters"),bias:n(e+"/biases",1,t+"/bias")}}function a(e){return{box_encoding_predictor:o("Prediction/BoxPredictor_"+e+"/BoxEncodingPredictor","prediction_layer/box_predictor_"+e+"/box_encoding_predictor"),class_predictor:o("Prediction/BoxPredictor_"+e+"/ClassPredictor","prediction_layer/box_predictor_"+e+"/class_predictor")}}return{extractMobilenetV1Params:function(){return{conv_0:r("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:i(1),conv_2:i(2),conv_3:i(3),conv_4:i(4),conv_5:i(5),conv_6:i(6),conv_7:i(7),conv_8:i(8),conv_9:i(9),conv_10:i(10),conv_11:i(11),conv_12:i(12),conv_13:i(13)}},extractPredictionLayerParams:function(){return{conv_0:r("Prediction",0,"prediction_layer/conv_0"),conv_1:r("Prediction",1,"prediction_layer/conv_1"),conv_2:r("Prediction",2,"prediction_layer/conv_2"),conv_3:r("Prediction",3,"prediction_layer/conv_3"),conv_4:r("Prediction",4,"prediction_layer/conv_4"),conv_5:r("Prediction",5,"prediction_layer/conv_5"),conv_6:r("Prediction",6,"prediction_layer/conv_6"),conv_7:r("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:a(0),box_predictor_1:a(1),box_predictor_2:a(2),box_predictor_3:a(3),box_predictor_4:a(4),box_predictor_5:a(5)}}}}(e,t),r=n.extractMobilenetV1Params,i=n.extractPredictionLayerParams,o=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Rh(o))throw new Error("expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have "+o);var a={mobilenetv1:r(),prediction_layer:i(),output_layer:{extra_dim:o}};return Kf(e,t),{params:a,paramMappings:t}}(e)},t.prototype.extractParams=function(e){return function(e){var t=[],n=em(e),r=n.extractWeights,i=n.getRemainingWeights,o=function(e,t){function n(n,r,i,o,a){var s=Ln(e(n*r*i*i),[i,i,n,r]),c=An(e(r));return t.push({paramPath:o+"/filters"},{paramPath:o+"/"+(a?"batch_norm_offset":"bias")}),{filters:s,bias:c}}function r(e,t,r,i){var o=n(e,t,r,i,!0);return{filters:o.filters,batch_norm_offset:o.bias}}function i(n,i,o){var a=function(n,r){var i=Ln(e(9*n),[3,3,n,1]),o=An(e(n)),a=An(e(n)),s=An(e(n)),c=An(e(n));return t.push({paramPath:r+"/filters"},{paramPath:r+"/batch_norm_scale"},{paramPath:r+"/batch_norm_offset"},{paramPath:r+"/batch_norm_mean"},{paramPath:r+"/batch_norm_variance"}),{filters:i,batch_norm_scale:o,batch_norm_offset:a,batch_norm_mean:s,batch_norm_variance:c}}(n,o+"/depthwise_conv");return{depthwise_conv:a,pointwise_conv:r(n,i,1,o+"/pointwise_conv")}}return{extractMobilenetV1Params:function(){return{conv_0:r(3,32,3,"mobilenetv1/conv_0"),conv_1:i(32,64,"mobilenetv1/conv_1"),conv_2:i(64,128,"mobilenetv1/conv_2"),conv_3:i(128,128,"mobilenetv1/conv_3"),conv_4:i(128,256,"mobilenetv1/conv_4"),conv_5:i(256,256,"mobilenetv1/conv_5"),conv_6:i(256,512,"mobilenetv1/conv_6"),conv_7:i(512,512,"mobilenetv1/conv_7"),conv_8:i(512,512,"mobilenetv1/conv_8"),conv_9:i(512,512,"mobilenetv1/conv_9"),conv_10:i(512,512,"mobilenetv1/conv_10"),conv_11:i(512,512,"mobilenetv1/conv_11"),conv_12:i(512,1024,"mobilenetv1/conv_12"),conv_13:i(1024,1024,"mobilenetv1/conv_13")}},extractPredictionLayerParams:function(){return{conv_0:r(1024,256,1,"prediction_layer/conv_0"),conv_1:r(256,512,3,"prediction_layer/conv_1"),conv_2:r(512,128,1,"prediction_layer/conv_2"),conv_3:r(128,256,3,"prediction_layer/conv_3"),conv_4:r(256,128,1,"prediction_layer/conv_4"),conv_5:r(128,256,3,"prediction_layer/conv_5"),conv_6:r(256,64,1,"prediction_layer/conv_6"),conv_7:r(64,128,3,"prediction_layer/conv_7"),box_predictor_0:{box_encoding_predictor:n(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),class_predictor:n(512,9,1,"prediction_layer/box_predictor_0/class_predictor")},box_predictor_1:{box_encoding_predictor:n(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),class_predictor:n(1024,18,1,"prediction_layer/box_predictor_1/class_predictor")},box_predictor_2:{box_encoding_predictor:n(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),class_predictor:n(512,18,1,"prediction_layer/box_predictor_2/class_predictor")},box_predictor_3:{box_encoding_predictor:n(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),class_predictor:n(256,18,1,"prediction_layer/box_predictor_3/class_predictor")},box_predictor_4:{box_encoding_predictor:n(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),class_predictor:n(256,18,1,"prediction_layer/box_predictor_4/class_predictor")},box_predictor_5:{box_encoding_predictor:n(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),class_predictor:n(128,18,1,"prediction_layer/box_predictor_5/class_predictor")}}}}}(r,t),a=o.extractMobilenetV1Params,s=o.extractPredictionLayerParams,c=a(),u=s(),d={extra_dim:Nn(r(20472),[1,5118,4])};if(t.push({paramPath:"output_layer/extra_dim"}),0!==i().length)throw new Error("weights remaing after extract: "+i().length);return{params:{mobilenetv1:c,prediction_layer:u,output_layer:d},paramMappings:t}}(e)},t}(Uf);function Km(e){var t=new Hm;return t.extractWeights(e),t}function Xm(e){return Km(e)}var $m,Ym=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t}(Hm),Qm=[new Fh(.738768,.874946),new Fh(2.42204,2.65704),new Fh(4.30971,7.04493),new Fh(10.246,4.59428),new Fh(12.6868,11.8741)],Jm=[new Fh(1.603231,2.094468),new Fh(6.041143,7.080126),new Fh(2.882459,3.518061),new Fh(4.266906,5.178857),new Fh(9.041765,10.66308)],Zm=[117.001,114.697,97.404],eg=function(e){return"number"==typeof e};function tg(e){if(!e)throw new Error("invalid config: "+e);if("boolean"!=typeof e.withSeparableConvs)throw new Error("config.withSeparableConvs has to be a boolean, have: "+e.withSeparableConvs);if(!eg(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new Error("config.iouThreshold has to be a number between [0, 1], have: "+e.iouThreshold);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every((function(e){return"string"==typeof e})))throw new Error("config.classes has to be an array class names: string[], have: "+JSON.stringify(e.classes));if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map((function(e){return e||{}})).every((function(e){return eg(e.x)&&eg(e.y)})))throw new Error("config.anchors has to be an array of { x: number, y: number }, have: "+JSON.stringify(e.anchors));if(e.meanRgb&&(!Array.isArray(e.meanRgb)||3!==e.meanRgb.length||!e.meanRgb.every(eg)))throw new Error("config.meanRgb has to be an array of shape [number, number, number], have: "+JSON.stringify(e.meanRgb))}function ng(e){return Jt((function(){var t=cu(e,On(.10000000149011612));return Xc(kd(hu(e,t)),t)}))}function rg(e,t){return Jt((function(){var n=Rr(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Nu(n,t.conv.filters,[1,1],"valid"),n=hu(n,t.bn.sub),n=cu(n,t.bn.truediv),ng(n=Xc(n,t.conv.bias))}))}function ig(e,t){return Jt((function(){var n=Rr(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Vu(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),ng(n=Xc(n,t.bias))}))}!function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"}($m||($m={}));var og=function(){function e(e){var t=void 0===e?{}:e,n=t.inputSize,r=t.scoreThreshold;if(this._name="TinyYolov2Options",this._inputSize=n||416,this._scoreThreshold=r||.5,"number"!=typeof this._inputSize||this._inputSize%32!=0)throw new Error(this._name+" - expected inputSize to be a number divisible by 32");if("number"!=typeof this._scoreThreshold||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(this._name+" - expected scoreThreshold to be a number between 0 and 1")}return Object.defineProperty(e.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scoreThreshold",{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),e}(),ag=function(e){function t(t){var n=e.call(this,"TinyYolov2")||this;return tg(t),n._config=t,n}return mh(t,e),Object.defineProperty(t.prototype,"config",{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"withClassScores",{get:function(){return this.config.withClassScores||this.config.classes.length>1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"boxEncodingSize",{get:function(){return 5+(this.withClassScores?this.config.classes.length:0)},enumerable:!0,configurable:!0}),t.prototype.runTinyYolov2=function(e,t){var n=rg(e,t.conv0);return n=rg(n=nd(n,[2,2],[2,2],"same"),t.conv1),n=rg(n=nd(n,[2,2],[2,2],"same"),t.conv2),n=rg(n=nd(n,[2,2],[2,2],"same"),t.conv3),n=rg(n=nd(n,[2,2],[2,2],"same"),t.conv4),n=rg(n=nd(n,[2,2],[2,2],"same"),t.conv5),n=rg(n=nd(n,[2,2],[1,1],"same"),t.conv6),Hf(n=rg(n,t.conv7),t.conv8,"valid",!1)},t.prototype.runMobilenet=function(e,t){var n=this.config.isFirstLayerConv2d?ng(Hf(e,t.conv0,"valid",!1)):ig(e,t.conv0);return n=ig(n=nd(n,[2,2],[2,2],"same"),t.conv1),n=ig(n=nd(n,[2,2],[2,2],"same"),t.conv2),n=ig(n=nd(n,[2,2],[2,2],"same"),t.conv3),n=ig(n=nd(n,[2,2],[2,2],"same"),t.conv4),n=ig(n=nd(n,[2,2],[2,2],"same"),t.conv5),n=nd(n,[2,2],[1,1],"same"),n=t.conv6?ig(n,t.conv6):n,Hf(n=t.conv7?ig(n,t.conv7):n,t.conv8,"valid",!1)},t.prototype.forwardInput=function(e,t){var n=this,r=this.params;if(!r)throw new Error("TinyYolov2 - load model before inference");return Jt((function(){var i=e.toBatchTensor(t,!1).toFloat();return i=(i=n.config.meanRgb?Vh(i,n.config.meanRgb):i).div(On(256)),n.config.withSeparableConvs?n.runMobilenet(i,r):n.runTinyYolov2(i,r)}))},t.prototype.forward=function(e,t){return vh(this,void 0,void 0,(function(){var n;return yh(this,(function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Mf(e)];case 1:return[4,n.apply(this,[r.sent(),t])];case 2:return[2,r.sent()]}}))}))},t.prototype.detect=function(e,t){return void 0===t&&(t={}),vh(this,void 0,void 0,(function(){var n,r,i,o,a,s,c,u,d,l,p,h,f=this;return yh(this,(function(m){switch(m.label){case 0:return n=new og(t),r=n.inputSize,i=n.scoreThreshold,[4,Mf(e)];case 1:return o=m.sent(),[4,this.forwardInput(o,r)];case 2:return a=m.sent(),s=Jt((function(){return jr(a)[0].expandDims()})),c={width:o.getInputWidth(0),height:o.getInputHeight(0)},[4,this.extractBoxes(s,o.getReshapedInputDimensions(0),i)];case 3:return u=m.sent(),a.dispose(),s.dispose(),d=u.map((function(e){return e.box})),l=u.map((function(e){return e.score})),p=u.map((function(e){return e.classScore})),h=u.map((function(e){return f.config.classes[e.label]})),[2,Uh(d.map((function(e){return e.rescale(r)})),l,this.config.iouThreshold,!0).map((function(e){return new Bh(l[e],p[e],h[e],d[e],c)}))]}}))}))},t.prototype.getDefaultModelName=function(){return""},t.prototype.extractParamsFromWeigthMap=function(e){return function(e,t){var n,r=[],i=function(e,t){var n=Zf(e,t);function r(e){return{filters:n(e+"/filters",4),bias:n(e+"/bias",1)}}return{extractConvParams:r,extractConvWithBatchNormParams:function(e){var t=r(e+"/conv"),i=function(e){return{sub:n(e+"/sub",1),truediv:n(e+"/truediv",1)}}(e+"/bn");return{conv:t,bn:i}},extractSeparableConvParams:Jf(n)}}(e,r),o=i.extractConvParams,a=i.extractConvWithBatchNormParams,s=i.extractSeparableConvParams;if(t.withSeparableConvs){var c=t.filterSizes&&t.filterSizes.length||9;n={conv0:t.isFirstLayerConv2d?o("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:c>7?s("conv6"):void 0,conv7:c>8?s("conv7"):void 0,conv8:o("conv8")}}else n={conv0:a("conv0"),conv1:a("conv1"),conv2:a("conv2"),conv3:a("conv3"),conv4:a("conv4"),conv5:a("conv5"),conv6:a("conv6"),conv7:a("conv7"),conv8:o("conv8")};return Kf(e,r),{params:n,paramMappings:r}}(e,this.config)},t.prototype.extractParams=function(e){var n=this.config.filterSizes||t.DEFAULT_FILTER_SIZES,r=n?n.length:void 0;if(7!==r&&8!==r&&9!==r)throw new Error("TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found "+r+" filterSizes in config");return function(e,t,n,r){var i,o=em(e),a=o.extractWeights,s=o.getRemainingWeights,c=[],u=function(e,t){var n=Xf(e,t),r=Qf(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:function(r,i,o){var a=n(r,i,3,o+"/conv"),s=function(n,r){var i=An(e(n)),o=An(e(n));return t.push({paramPath:r+"/sub"},{paramPath:r+"/truediv"}),{sub:i,truediv:o}}(i,o+"/bn");return{conv:a,bn:s}},extractSeparableConvParams:r}}(a,c),d=u.extractConvParams,l=u.extractConvWithBatchNormParams,p=u.extractSeparableConvParams;if(t.withSeparableConvs){var h=r[0],f=r[1],m=r[2],g=r[3],v=r[4],y=r[5],b=r[6],w=r[7],x=r[8];i={conv0:t.isFirstLayerConv2d?d(h,f,3,"conv0"):p(h,f,"conv0"),conv1:p(f,m,"conv1"),conv2:p(m,g,"conv2"),conv3:p(g,v,"conv3"),conv4:p(v,y,"conv4"),conv5:p(y,b,"conv5"),conv6:w?p(b,w,"conv6"):void 0,conv7:x?p(w,x,"conv7"):void 0,conv8:d(x||w||b,5*n,1,"conv8")}}else h=r[0],f=r[1],m=r[2],g=r[3],v=r[4],y=r[5],b=r[6],w=r[7],x=r[8],i={conv0:l(h,f,"conv0"),conv1:l(f,m,"conv1"),conv2:l(m,g,"conv2"),conv3:l(g,v,"conv3"),conv4:l(v,y,"conv4"),conv5:l(y,b,"conv5"),conv6:l(b,w,"conv6"),conv7:l(w,x,"conv7"),conv8:d(x,5*n,1,"conv8")};if(0!==s().length)throw new Error("weights remaing after extract: "+s().length);return{params:i,paramMappings:c}}(e,this.config,this.boxEncodingSize,n)},t.prototype.extractBoxes=function(e,t,n){return vh(this,void 0,void 0,(function(){var r,i,o,a,s,c,u,d,l,p,h,f,m,g,v,y,b,w,x,_,S,R,C,E,k,T,D,P,I,M=this;return yh(this,(function(O){switch(O.label){case 0:return r=t.width,i=t.height,o=Math.max(r,i),a=o/r,s=o/i,c=e.shape[1],u=this.config.anchors.length,d=Jt((function(){var t=e.reshape([c,c,u,M.boxEncodingSize]);return[t.slice([0,0,0,0],[c,c,u,4]),t.slice([0,0,0,4],[c,c,u,1]),M.withClassScores?fi(t.slice([0,0,0,5],[c,c,u,M.config.classes.length]),3):On(0)]})),l=d[0],p=d[1],h=d[2],f=[],[4,p.array()];case 1:return m=O.sent(),[4,l.array()];case 2:g=O.sent(),v=0,O.label=3;case 3:if(!(v<c))return[3,12];y=0,O.label=4;case 4:if(!(y<c))return[3,11];b=0,O.label=5;case 5:return b<u?(w=Hh(m[v][y][b][0]),!n||w>n?(x=(y+Hh(g[v][y][b][0]))/c*a,_=(v+Hh(g[v][y][b][1]))/c*s,S=Math.exp(g[v][y][b][2])*this.config.anchors[b].x/c*a,R=Math.exp(g[v][y][b][3])*this.config.anchors[b].y/c*s,C=x-S/2,E=_-R/2,k={row:v,col:y,anchor:b},this.withClassScores?[4,this.extractPredictedClass(h,k)]:[3,7]):[3,9]):[3,10];case 6:return I=O.sent(),[3,8];case 7:I={classScore:1,label:0},O.label=8;case 8:D=(T=I).classScore,P=T.label,f.push(gh({box:new Lh(C,E,C+S,E+R),score:w,classScore:w*D,label:P},k)),O.label=9;case 9:return b++,[3,5];case 10:return y++,[3,4];case 11:return v++,[3,3];case 12:return l.dispose(),p.dispose(),h.dispose(),[2,f]}}))}))},t.prototype.extractPredictedClass=function(e,t){return vh(this,void 0,void 0,(function(){var n,r,i,o;return yh(this,(function(a){switch(a.label){case 0:return n=t.row,r=t.col,i=t.anchor,[4,e.array()];case 1:return o=a.sent(),[2,Array(this.config.classes.length).fill(0).map((function(e,t){return o[n][r][i][t]})).map((function(e,t){return{classScore:e,label:t}})).reduce((function(e,t){return e.classScore>t.classScore?e:t}))]}}))}))},t.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024],t}(Uf),sg=function(e){function t(t){void 0===t&&(t=!0);var n=Object.assign({},{withSeparableConvs:t,iouThreshold:.4,classes:["face"]},t?{anchors:Jm,meanRgb:Zm}:{anchors:Qm,withClassScores:!0});return e.call(this,n)||this}return mh(t,e),Object.defineProperty(t.prototype,"withSeparableConvs",{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,t){return vh(this,void 0,void 0,(function(){return yh(this,(function(n){switch(n.label){case 0:return[4,this.detect(e,t)];case 1:return[2,n.sent().map((function(e){return new jh(e.score,e.relativeBox,{width:e.imageWidth,height:e.imageHeight})}))]}}))}))},t.prototype.getDefaultModelName=function(){return this.withSeparableConvs?"tiny_yolov2_separable_conv_model":"tiny_yolov2_model"},t.prototype.extractParamsFromWeigthMap=function(t){return e.prototype.extractParamsFromWeigthMap.call(this,t)},t}(ag);function cg(e,t){void 0===t&&(t=!0);var n=new sg(t);return n.extractWeights(e),n}var ug=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._name="TinyFaceDetectorOptions",t}return mh(t,e),t}(og),dg=function(){function e(){}return e.prototype.then=function(e){return vh(this,void 0,void 0,(function(){var t;return yh(this,(function(n){switch(n.label){case 0:return t=e,[4,this.run()];case 1:return[2,t.apply(void 0,[n.sent()])]}}))}))},e.prototype.run=function(){return vh(this,void 0,void 0,(function(){return yh(this,(function(e){throw new Error("ComposableTask - run is not implemented")}))}))},e}();function lg(e,t,n,r,i){return void 0===i&&(i=function(e){return e.alignedRect}),vh(this,void 0,void 0,(function(){var o,a,s,c,u;return yh(this,(function(d){switch(d.label){case 0:return o=e.map((function(e){return fm(e)?i(e):e.detection})),(s=r)?[3,5]:t instanceof _e?[4,Af(t,o)]:[3,2];case 1:return c=d.sent(),[3,4];case 2:return[4,Of(t,o)];case 3:c=d.sent(),d.label=4;case 4:s=c,d.label=5;case 5:return[4,n(a=s)];case 6:return u=d.sent(),a.forEach((function(e){return e instanceof _e&&e.dispose()})),[2,u]}}))}))}function pg(e,t,n,r,i){return vh(this,void 0,void 0,(function(){var o=this;return yh(this,(function(a){return[2,lg([e],t,(function(e){return vh(o,void 0,void 0,(function(){return yh(this,(function(t){return[2,n(e[0])]}))}))}),r,i)]}))}))}function hg(e,t){var n=t[0],r=t[1];return{height:Math.floor(n*e),width:Math.floor(r*e)}}var fg=function(e){function t(t,n,r,i){return e.call(this,{left:t,top:n,right:r,bottom:i},!0)||this}return mh(t,e),t}(Nh);function mg(e){return Jt((function(){return cu(hu(e,On(127.5)),On(.0078125))}))}function gg(e,t){return Jt((function(){return Xc(kd(e),cu(t,pc(kd(pc(e)))))}))}function vg(e,t,n){return void 0===n&&(n=!1),Jt((function(){var r=Hf(e,t.conv1,"valid");return r=gg(r,t.prelu1_alpha),r=gg(r=Hf(r=nd(r,n?[2,2]:[3,3],[2,2],"same"),t.conv2,"valid"),t.prelu2_alpha),gg(r=Hf(r=n?r:nd(r,[3,3],[2,2],"valid"),t.conv3,"valid"),t.prelu3_alpha)}))}function yg(e,t,n,r,i){i.stage1=[];var o=t.map((function(t){return Jt((function(){var n={scale:t},i=function(e,t){return Jt((function(){var n=hg(t,e.shape.slice(1)),r=n.height,i=n.width,o=mg(Sl.resizeBilinear(e,[r,i]));return Pd(o,[0,2,1,3])}))}(e,t),o=Date.now(),a=function(e,t){return Jt((function(){var n=vg(e,t,!0),r=Hf(n,t.conv4_1,"valid"),i=wr(yd(r,3),3);return{prob:fi(hu(r,i),3),regions:Hf(n,t.conv4_2,"valid")}}))}(i,r),s=a.prob,c=a.regions;return n.pnet=Date.now()-o,{scoresTensor:jr(jr(s,3)[1])[0],regionsTensor:jr(c)[0],scale:t,statsForScale:n}}))})),a=o.map((function(e){var t=e.scoresTensor,r=e.regionsTensor,o=e.scale,a=e.statsForScale,s=function(e,t,n,r){for(var i=[],o=e.arraySync(),a=0;a<e.shape[0];a++)for(var s=0;s<e.shape[1];s++)o[a][s]>=r&&i.push(new Fh(s,a));return i.map((function(e){var r=new Lh(Math.round((2*e.y+1)/n),Math.round((2*e.x+1)/n),Math.round((2*e.y+12)/n),Math.round((2*e.x+12)/n)),i=o[e.y][e.x],a=t.arraySync();return{cell:r,score:i,region:new fg(a[e.y][e.x][0],a[e.y][e.x][1],a[e.y][e.x][2],a[e.y][e.x][3])}}))}(t,r,o,n);if(t.dispose(),r.dispose(),!s.length)return i.stage1.push(a),[];var c=Date.now(),u=Uh(s.map((function(e){return e.cell})),s.map((function(e){return e.score})),.5);return a.nms=Date.now()-c,a.numBoxes=u.length,i.stage1.push(a),u.map((function(e){return s[e]}))})),s=a.reduce((function(e,t){return e.concat(t)}),[]),c=[],u=[];if(s.length>0){var d=Date.now(),l=Uh(s.map((function(e){return e.cell})),s.map((function(e){return e.score})),.7);i.stage1_nms=Date.now()-d,u=l.map((function(e){return s[e].score})),c=l.map((function(e){return s[e]})).map((function(e){var t=e.cell,n=e.region;return new Lh(t.left+n.left*t.width,t.top+n.top*t.height,t.right+n.right*t.width,t.bottom+n.bottom*t.height).toSquare().round()}))}return{boxes:c,scores:u}}function bg(e,t,n){var r=n.width,i=n.height;return vh(this,void 0,void 0,(function(){var n,o,a,s=this;return yh(this,(function(c){switch(c.label){case 0:return n=gf(e),[4,Promise.all(t.map((function(t){return vh(s,void 0,void 0,(function(){var r,i,o,a,s,c,u,d;return yh(this,(function(l){return r=t.padAtBorders(e.height,e.width),i=r.y,o=r.ey,a=r.x,s=r.ex,c=a-1,u=i-1,d=n.getImageData(c,u,s-c,o-u),[2,ff.isNodejs()?kf(d):createImageBitmap(d)]}))}))})))];case 1:return o=c.sent(),a=[],o.forEach((function(e){var t=gf(Ef({width:r,height:i}));t.drawImage(e,0,0,r,i);for(var n=t.getImageData(0,0,r,i).data,o=[],s=0;s<n.length;s+=4)o.push(n[s+2]),o.push(n[s+1]),o.push(n[s]);a.push(o)})),[2,a.map((function(e){return Jt((function(){return mg(Pd(Ln(e,[1,r,i,3]),[0,2,1,3]).toFloat())}))}))]}}))}))}function wg(e,t,n,r,i){return vh(this,void 0,void 0,(function(){var o,a,s,c,u,d,l,p,h,f,m,g,v,y;return yh(this,(function(b){switch(b.label){case 0:return o=Date.now(),[4,bg(e,t,{width:24,height:24})];case 1:return a=b.sent(),i.stage2_extractImagePatches=Date.now()-o,o=Date.now(),s=a.map((function(e){var t=function(e,t){return Jt((function(){var n=vg(e,t),r=gg(om(Or(n,[n.shape[0],t.fc1.weights.shape[0]]),t.fc1),t.prelu4_alpha),i=om(r,t.fc2_1),o=wr(yd(i,1),1),a=fi(hu(i,o),1),s=om(r,t.fc2_2);return{scores:jr(a,1)[1],regions:s}}))}(e,r);return e.dispose(),t})),i.stage2_rnet=Date.now()-o,c=s.length>1?Xn(s.map((function(e){return e.scores}))):s[0].scores,l=(d=Array).from,[4,c.data()];case 2:return u=l.apply(d,[b.sent()]),c.dispose(),p=u.map((function(e,t){return{score:e,idx:t}})).filter((function(e){return e.score>n})).map((function(e){return e.idx})),h=p.map((function(e){return t[e]})),f=p.map((function(e){return u[e]})),m=[],g=[],h.length>0&&(o=Date.now(),v=Uh(h,f,.7),i.stage2_nms=Date.now()-o,y=v.map((function(e){var t=s[p[e]].regions.arraySync();return new fg(t[0][0],t[0][1],t[0][2],t[0][3])})),g=v.map((function(e){return f[e]})),m=v.map((function(e,t){return h[e].calibrate(y[t])}))),s.forEach((function(e){e.regions.dispose(),e.scores.dispose()})),[2,{boxes:m,scores:g}]}}))}))}function xg(e,t,n,r,i){return vh(this,void 0,void 0,(function(){var o,a,s,c,u,d,l,p,h,f,m,g,v,y,b;return yh(this,(function(w){switch(w.label){case 0:return o=Date.now(),[4,bg(e,t,{width:48,height:48})];case 1:return a=w.sent(),i.stage3_extractImagePatches=Date.now()-o,o=Date.now(),s=a.map((function(e){var t=function(e,t){return Jt((function(){var n=vg(e,t);n=gg(n=Hf(n=nd(n,[2,2],[2,2],"same"),t.conv4,"valid"),t.prelu4_alpha);var r=gg(om(Or(n,[n.shape[0],t.fc1.weights.shape[0]]),t.fc1),t.prelu5_alpha),i=om(r,t.fc2_1),o=wr(yd(i,1),1),a=fi(hu(i,o),1),s=om(r,t.fc2_2),c=om(r,t.fc2_3);return{scores:jr(a,1)[1],regions:s,points:c}}))}(e,r);return e.dispose(),t})),i.stage3_onet=Date.now()-o,c=s.length>1?Xn(s.map((function(e){return e.scores}))):s[0].scores,l=(d=Array).from,[4,c.data()];case 2:return u=l.apply(d,[w.sent()]),c.dispose(),p=u.map((function(e,t){return{score:e,idx:t}})).filter((function(e){return e.score>n})).map((function(e){return e.idx})),h=p.map((function(e){var t=s[e].regions.arraySync();return new fg(t[0][0],t[0][1],t[0][2],t[0][3])})),f=p.map((function(e,n){return t[e].calibrate(h[n])})),m=p.map((function(e){return u[e]})),g=[],v=[],y=[],f.length>0&&(o=Date.now(),b=Uh(f,m,.7,!1),i.stage3_nms=Date.now()-o,g=b.map((function(e){return f[e]})),v=b.map((function(e){return m[e]})),y=b.map((function(e,t){return Array(5).fill(0).map((function(n,r){var i=s[e].points.arraySync();return new Fh(i[0][r]*(g[t].width+1)+g[t].left,i[0][r+5]*(g[t].height+1)+g[t].top)}))}))),s.forEach((function(e){e.regions.dispose(),e.scores.dispose(),e.points.dispose()})),[2,{boxes:g,scores:v,points:y}]}}))}))}var _g=function(e){function t(){return e.call(this,"Mtcnn")||this}return mh(t,e),t.prototype.load=function(t){return vh(this,void 0,void 0,(function(){return yh(this,(function(n){return console.warn("mtcnn is deprecated and will be removed soon"),[2,e.prototype.load.call(this,t)]}))}))},t.prototype.loadFromDisk=function(t){return vh(this,void 0,void 0,(function(){return yh(this,(function(n){return console.warn("mtcnn is deprecated and will be removed soon"),[2,e.prototype.loadFromDisk.call(this,t)]}))}))},t.prototype.forwardInput=function(e,t){return void 0===t&&(t={}),vh(this,void 0,void 0,(function(){var n,r,i,o,a,s,c,u,d,l,p,h,f,m,g,v,y,b,w,x,_;return yh(this,(function(S){switch(S.label){case 0:if(!(n=this.params))throw new Error("Mtcnn - load model before inference");if(!(r=e.canvases[0]))throw new Error("Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.");return i={},o=Date.now(),a=Jt((function(){return e=wr(Gp.fromPixels(r)).toFloat(),Jt((function(){return Nr(jr(e,3).reverse(),3)}));var e})),s=function(e){return a.dispose(),i.total=Date.now()-o,e},c=a.shape.slice(1),u=c[0],d=c[1],l=new zm(t),p=l.minFaceSize,h=l.scaleFactor,f=l.maxNumScales,m=l.scoreThresholds,g=l.scaleSteps,v=(g||function(e,t,n){for(var r=n[0],i=n[1],o=12/e,a=[],s=Math.min(r,i)*o,c=0;s>=12;)a.push(o*Math.pow(t,c)),s*=t,c+=1;return a}(p,h,[u,d])).filter((function(e){var t=hg(e,[u,d]);return Math.min(t.width,t.height)>12})).slice(0,f),i.scales=v,i.pyramid=v.map((function(e){return hg(e,[u,d])})),y=Date.now(),[4,yg(a,v,m[0],n.pnet,i)];case 1:return b=S.sent(),i.total_stage1=Date.now()-y,b.boxes.length?(i.stage2_numInputBoxes=b.boxes.length,y=Date.now(),[4,wg(r,b.boxes,m[1],n.rnet,i)]):[2,s({results:[],stats:i})];case 2:return w=S.sent(),i.total_stage2=Date.now()-y,w.boxes.length?(i.stage3_numInputBoxes=w.boxes.length,y=Date.now(),[4,xg(r,w.boxes,m[2],n.onet,i)]):[2,s({results:[],stats:i})];case 3:return x=S.sent(),i.total_stage3=Date.now()-y,_=x.boxes.map((function(e,t){return mm(of({},new jh(x.scores[t],new $h(e.left/d,e.top/u,e.width/d,e.height/u),{height:u,width:d})),new Qh(x.points[t].map((function(t){return t.sub(new Fh(e.left,e.top)).div(new Fh(e.width,e.height))})),{width:e.width,height:e.height}))})),[2,s({results:_,stats:i})]}}))}))},t.prototype.forward=function(e,t){return void 0===t&&(t={}),vh(this,void 0,void 0,(function(){var n;return yh(this,(function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Mf(e)];case 1:return[4,n.apply(this,[r.sent(),t])];case 2:return[2,r.sent().results]}}))}))},t.prototype.forwardWithStats=function(e,t){return void 0===t&&(t={}),vh(this,void 0,void 0,(function(){var n;return yh(this,(function(r){switch(r.label){case 0:return n=this.forwardInput,[4,Mf(e)];case 1:return[2,n.apply(this,[r.sent(),t])]}}))}))},t.prototype.getDefaultModelName=function(){return"mtcnn_model"},t.prototype.extractParamsFromWeigthMap=function(e){return function(e){var t=[],n=function(e,t){var n=Zf(e,t);function r(e){return{filters:n(e+"/weights",4,e+"/filters"),bias:n(e+"/bias",1)}}function i(e){return{weights:n(e+"/weights",2),bias:n(e+"/bias",1)}}function o(e){return n(e,1)}function a(e){return{conv1:r(e+"/conv1"),prelu1_alpha:o(e+"/prelu1_alpha"),conv2:r(e+"/conv2"),prelu2_alpha:o(e+"/prelu2_alpha"),conv3:r(e+"/conv3"),prelu3_alpha:o(e+"/prelu3_alpha")}}return{extractPNetParams:function(){var e=a("pnet"),t=r("pnet/conv4_1"),n=r("pnet/conv4_2");return gh(gh({},e),{conv4_1:t,conv4_2:n})},extractRNetParams:function(){var e=a("rnet"),t=i("rnet/fc1"),n=o("rnet/prelu4_alpha"),r=i("rnet/fc2_1"),s=i("rnet/fc2_2");return gh(gh({},e),{fc1:t,prelu4_alpha:n,fc2_1:r,fc2_2:s})},extractONetParams:function(){var e=a("onet"),t=r("onet/conv4"),n=o("onet/prelu4_alpha"),s=i("onet/fc1"),c=o("onet/prelu5_alpha"),u=i("onet/fc2_1"),d=i("onet/fc2_2"),l=i("onet/fc2_3");return gh(gh({},e),{conv4:t,prelu4_alpha:n,fc1:s,prelu5_alpha:c,fc2_1:u,fc2_2:d,fc2_3:l})}}}(e,t),r=n.extractPNetParams,i=n.extractRNetParams,o=n.extractONetParams,a=r(),s=i(),c=o();return Kf(e,t),{params:{pnet:a,rnet:s,onet:c},paramMappings:t}}(e)},t.prototype.extractParams=function(e){return function(e){var t=em(e),n=t.extractWeights,r=t.getRemainingWeights,i=[],o=function(e,t){var n=Xf(e,t),r=$f(e,t);function i(n,r){var i=An(e(n));return t.push({paramPath:r}),i}function o(e,t,r){return void 0===r&&(r=!1),{conv1:n(e[0],e[1],3,t+"/conv1"),prelu1_alpha:i(e[1],t+"/prelu1_alpha"),conv2:n(e[1],e[2],3,t+"/conv2"),prelu2_alpha:i(e[2],t+"/prelu2_alpha"),conv3:n(e[2],e[3],r?2:3,t+"/conv3"),prelu3_alpha:i(e[3],t+"/prelu3_alpha")}}return{extractPNetParams:function(){var e=o([3,10,16,32],"pnet"),t=n(32,2,1,"pnet/conv4_1"),r=n(32,4,1,"pnet/conv4_2");return gh(gh({},e),{conv4_1:t,conv4_2:r})},extractRNetParams:function(){var e=o([3,28,48,64],"rnet",!0),t=r(576,128,"rnet/fc1"),n=i(128,"rnet/prelu4_alpha"),a=r(128,2,"rnet/fc2_1"),s=r(128,4,"rnet/fc2_2");return gh(gh({},e),{fc1:t,prelu4_alpha:n,fc2_1:a,fc2_2:s})},extractONetParams:function(){var e=o([3,32,64,64],"onet"),t=n(64,128,2,"onet/conv4"),a=i(128,"onet/prelu4_alpha"),s=r(1152,256,"onet/fc1"),c=i(256,"onet/prelu5_alpha"),u=r(256,2,"onet/fc2_1"),d=r(256,4,"onet/fc2_2"),l=r(256,10,"onet/fc2_3");return gh(gh({},e),{conv4:t,prelu4_alpha:a,fc1:s,prelu5_alpha:c,fc2_1:u,fc2_2:d,fc2_3:l})}}}(n,i),a=o.extractPNetParams,s=o.extractRNetParams,c=o.extractONetParams,u=a(),d=s(),l=c();if(0!==r().length)throw new Error("weights remaing after extract: "+r().length);return{params:{pnet:u,rnet:d,onet:l},paramMappings:i}}(e)},t}(Uf),Sg=[new Fh(1.603231,2.094468),new Fh(6.041143,7.080126),new Fh(2.882459,3.518061),new Fh(4.266906,5.178857),new Fh(9.041765,10.66308)],Rg=[117.001,114.697,97.404],Cg=function(e){function t(){var t={withSeparableConvs:!0,iouThreshold:.4,classes:["face"],anchors:Sg,meanRgb:Rg,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return e.call(this,t)||this}return mh(t,e),Object.defineProperty(t.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,t){return vh(this,void 0,void 0,(function(){return yh(this,(function(n){switch(n.label){case 0:return[4,this.detect(e,t)];case 1:return[2,n.sent().map((function(e){return new jh(e.score,e.relativeBox,{width:e.imageWidth,height:e.imageHeight})}))]}}))}))},t.prototype.getDefaultModelName=function(){return"tiny_face_detector_model"},t.prototype.extractParamsFromWeigthMap=function(t){return e.prototype.extractParamsFromWeigthMap.call(this,t)},t}(ag),Eg={ssdMobilenetv1:new Hm,tinyFaceDetector:new Cg,tinyYolov2:new sg,mtcnn:new _g,faceLandmark68Net:new Cm,faceLandmark68TinyNet:new km,faceRecognitionNet:new Am,faceExpressionNet:new dm,ageGenderNet:new Sm},kg=function(e,t){return Eg.ssdMobilenetv1.locateFaces(e,t)},Tg=function(e,t){return Eg.tinyFaceDetector.locateFaces(e,t)},Dg=function(e,t){return Eg.tinyYolov2.locateFaces(e,t)},Pg=function(e,t){return Eg.mtcnn.forward(e,t)},Ig=function(e){return Eg.faceLandmark68Net.detectLandmarks(e)},Mg=function(e){return Eg.faceLandmark68TinyNet.detectLandmarks(e)},Og=function(e){return Eg.faceRecognitionNet.computeFaceDescriptor(e)},Ag=function(e){return Eg.faceExpressionNet.predictExpressions(e)},Fg=function(e){return Eg.ageGenderNet.predictAgeAndGender(e)},Ng=function(e){return Eg.ssdMobilenetv1.load(e)},Lg=function(e){return Eg.tinyFaceDetector.load(e)},Bg=function(e){return Eg.mtcnn.load(e)},jg=function(e){return Eg.tinyYolov2.load(e)},Wg=function(e){return Eg.faceLandmark68Net.load(e)},zg=function(e){return Eg.faceLandmark68TinyNet.load(e)},Ug=function(e){return Eg.faceRecognitionNet.load(e)},Vg=function(e){return Eg.faceExpressionNet.load(e)},Gg=function(e){return Eg.ageGenderNet.load(e)},qg=Ng,Hg=kg,Kg=Ig,Xg=function(e){function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.extractedFaces=r,i}return mh(t,e),t}(dg),$g=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t,n=this;return yh(this,(function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return[4,lg(e=r.sent(),this.input,(function(e){return vh(n,void 0,void 0,(function(){return yh(this,(function(t){switch(t.label){case 0:return[4,Promise.all(e.map((function(e){return Eg.faceExpressionNet.predictExpressions(e)})))];case 1:return[2,t.sent()]}}))}))}),this.extractedFaces)];case 2:return t=r.sent(),[2,e.map((function(e,n){return pm(e,t[n])}))]}}))}))},t.prototype.withAgeAndGender=function(){return new ev(this,this.input)},t}(Xg),Yg=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t;return yh(this,(function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return(e=n.sent())?[4,pg(e,this.input,(function(e){return Eg.faceExpressionNet.predictExpressions(e)}),this.extractedFaces)]:[2];case 2:return t=n.sent(),[2,pm(e,t)]}}))}))},t.prototype.withAgeAndGender=function(){return new tv(this,this.input)},t}(Xg),Qg=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.withAgeAndGender=function(){return new nv(this,this.input)},t.prototype.withFaceDescriptors=function(){return new ov(this,this.input)},t}($g),Jg=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.withAgeAndGender=function(){return new rv(this,this.input)},t.prototype.withFaceDescriptor=function(){return new av(this,this.input)},t}(Yg),Zg=function(e){function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.extractedFaces=r,i}return mh(t,e),t}(dg),ev=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t,n=this;return yh(this,(function(r){switch(r.label){case 0:return[4,this.parentTask];case 1:return[4,lg(e=r.sent(),this.input,(function(e){return vh(n,void 0,void 0,(function(){return yh(this,(function(t){switch(t.label){case 0:return[4,Promise.all(e.map((function(e){return Eg.ageGenderNet.predictAgeAndGender(e)})))];case 1:return[2,t.sent()]}}))}))}),this.extractedFaces)];case 2:return t=r.sent(),[2,e.map((function(e,n){var r=t[n],i=r.age;return Bm(Wm(e,r.gender,r.genderProbability),i)}))]}}))}))},t.prototype.withFaceExpressions=function(){return new $g(this,this.input)},t}(Zg),tv=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t,n,r,i;return yh(this,(function(o){switch(o.label){case 0:return[4,this.parentTask];case 1:return(e=o.sent())?[4,pg(e,this.input,(function(e){return Eg.ageGenderNet.predictAgeAndGender(e)}),this.extractedFaces)]:[2];case 2:return t=o.sent(),n=t.age,r=t.gender,i=t.genderProbability,[2,Bm(Wm(e,r,i),n)]}}))}))},t.prototype.withFaceExpressions=function(){return new Yg(this,this.input)},t}(Zg),nv=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.withFaceExpressions=function(){return new Qg(this,this.input)},t.prototype.withFaceDescriptors=function(){return new ov(this,this.input)},t}(ev),rv=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.withFaceExpressions=function(){return new Jg(this,this.input)},t.prototype.withFaceDescriptor=function(){return new av(this,this.input)},t}(tv),iv=function(e){function t(t,n){var r=e.call(this)||this;return r.parentTask=t,r.input=n,r}return mh(t,e),t}(dg),ov=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e;return yh(this,(function(t){switch(t.label){case 0:return[4,this.parentTask];case 1:return[4,lg(e=t.sent(),this.input,(function(e){return Promise.all(e.map((function(e){return Eg.faceRecognitionNet.computeFaceDescriptor(e)})))}),null,(function(e){return e.landmarks.align(null,{useDlibAlignment:!0})}))];case 2:return[2,t.sent().map((function(t,n){return Nm(e[n],t)}))]}}))}))},t.prototype.withFaceExpressions=function(){return new Qg(this,this.input)},t.prototype.withAgeAndGender=function(){return new nv(this,this.input)},t}(iv),av=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t;return yh(this,(function(n){switch(n.label){case 0:return[4,this.parentTask];case 1:return(e=n.sent())?[4,pg(e,this.input,(function(e){return Eg.faceRecognitionNet.computeFaceDescriptor(e)}),null,(function(e){return e.landmarks.align(null,{useDlibAlignment:!0})}))]:[2];case 2:return t=n.sent(),[2,Nm(e,t)]}}))}))},t.prototype.withFaceExpressions=function(){return new Jg(this,this.input)},t.prototype.withAgeAndGender=function(){return new rv(this,this.input)},t}(iv),sv=function(e){function t(t,n,r){var i=e.call(this)||this;return i.parentTask=t,i.input=n,i.useTinyLandmarkNet=r,i}return mh(t,e),Object.defineProperty(t.prototype,"landmarkNet",{get:function(){return this.useTinyLandmarkNet?Eg.faceLandmark68TinyNet:Eg.faceLandmark68Net},enumerable:!0,configurable:!0}),t}(dg),cv=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t,n,r,i,o=this;return yh(this,(function(a){switch(a.label){case 0:return[4,this.parentTask];case 1:return e=a.sent(),t=e.map((function(e){return e.detection})),this.input instanceof _e?[4,Af(this.input,t)]:[3,3];case 2:return r=a.sent(),[3,5];case 3:return[4,Of(this.input,t)];case 4:r=a.sent(),a.label=5;case 5:return n=r,[4,Promise.all(n.map((function(e){return o.landmarkNet.detectLandmarks(e)})))];case 6:return i=a.sent(),n.forEach((function(e){return e instanceof _e&&e.dispose()})),[2,e.map((function(e,t){return mm(e,i[t])}))]}}))}))},t.prototype.withFaceExpressions=function(){return new Qg(this,this.input)},t.prototype.withAgeAndGender=function(){return new nv(this,this.input)},t.prototype.withFaceDescriptors=function(){return new ov(this,this.input)},t}(sv),uv=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t,n,r,i;return yh(this,(function(o){switch(o.label){case 0:return[4,this.parentTask];case 1:return(e=o.sent())?(t=e.detection,this.input instanceof _e?[4,Af(this.input,[t])]:[3,3]):[2];case 2:return r=o.sent(),[3,5];case 3:return[4,Of(this.input,[t])];case 4:r=o.sent(),o.label=5;case 5:return n=r,[4,this.landmarkNet.detectLandmarks(n[0])];case 6:return i=o.sent(),n.forEach((function(e){return e instanceof _e&&e.dispose()})),[2,mm(e,i)]}}))}))},t.prototype.withFaceExpressions=function(){return new Jg(this,this.input)},t.prototype.withAgeAndGender=function(){return new rv(this,this.input)},t.prototype.withFaceDescriptor=function(){return new av(this,this.input)},t}(sv),dv=function(e){function t(t,n){void 0===n&&(n=new qm);var r=e.call(this)||this;return r.input=t,r.options=n,r}return mh(t,e),t}(dg),lv=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t,n,r;return yh(this,(function(i){switch(i.label){case 0:return t=(e=this).input,(n=e.options)instanceof zm?[4,Eg.mtcnn.forward(t,n)]:[3,2];case 1:return[2,i.sent().map((function(e){return e.detection}))];case 2:if(r=n instanceof ug?function(e){return Eg.tinyFaceDetector.locateFaces(e,n)}:n instanceof qm?function(e){return Eg.ssdMobilenetv1.locateFaces(e,n)}:n instanceof og?function(e){return Eg.tinyYolov2.locateFaces(e,n)}:null,!r)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return[2,r(t)]}}))}))},t.prototype.runAndExtendWithFaceDetections=function(){var e=this;return new Promise((function(t){return vh(e,void 0,void 0,(function(){var e;return yh(this,(function(n){switch(n.label){case 0:return[4,this.run()];case 1:return e=n.sent(),[2,t(e.map((function(e){return of({},e)})))]}}))}))}))},t.prototype.withFaceLandmarks=function(e){return void 0===e&&(e=!1),new cv(this.runAndExtendWithFaceDetections(),this.input,e)},t.prototype.withFaceExpressions=function(){return new $g(this.runAndExtendWithFaceDetections(),this.input)},t.prototype.withAgeAndGender=function(){return new ev(this.runAndExtendWithFaceDetections(),this.input)},t}(dv),pv=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return mh(t,e),t.prototype.run=function(){return vh(this,void 0,void 0,(function(){var e,t;return yh(this,(function(n){switch(n.label){case 0:return[4,new lv(this.input,this.options)];case 1:return e=n.sent(),t=e[0],e.forEach((function(e){e.score>t.score&&(t=e)})),[2,t]}}))}))},t.prototype.runAndExtendWithFaceDetection=function(){var e=this;return new Promise((function(t){return vh(e,void 0,void 0,(function(){var e;return yh(this,(function(n){switch(n.label){case 0:return[4,this.run()];case 1:return e=n.sent(),[2,t(e?of({},e):void 0)]}}))}))}))},t.prototype.withFaceLandmarks=function(e){return void 0===e&&(e=!1),new uv(this.runAndExtendWithFaceDetection(),this.input,e)},t.prototype.withFaceExpressions=function(){return new Yg(this.runAndExtendWithFaceDetection(),this.input)},t.prototype.withAgeAndGender=function(){return new tv(this.runAndExtendWithFaceDetection(),this.input)},t}(dv);function hv(e,t){return void 0===t&&(t=new qm),new pv(e,t)}function fv(e,t){return void 0===t&&(t=new qm),new lv(e,t)}function mv(e,t){return vh(this,void 0,void 0,(function(){return yh(this,(function(n){switch(n.label){case 0:return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),[4,fv(e,new qm(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,n.sent()]}}))}))}function gv(e,t){return void 0===t&&(t={}),vh(this,void 0,void 0,(function(){return yh(this,(function(n){switch(n.label){case 0:return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),[4,fv(e,new og(t)).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,n.sent()]}}))}))}function vv(e,t){return void 0===t&&(t={}),vh(this,void 0,void 0,(function(){return yh(this,(function(n){switch(n.label){case 0:return console.warn("allFacesMtcnn is deprecated and will be removed soon, use the high level api instead"),[4,fv(e,new zm(t)).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,n.sent()]}}))}))}var yv=mv;function bv(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");var n=Array.from(e),r=Array.from(t);return Math.sqrt(n.map((function(e,t){return e-r[t]})).reduce((function(e,t){return e+Math.pow(t,2)}),0))}var wv=function(){function e(e,t){void 0===t&&(t=.6),this._distanceThreshold=t;var n=Array.isArray(e)?e:[e];if(!n.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");var r=1,i=function(){return"person "+r++};this._labeledDescriptors=n.map((function(e){if(e instanceof tf)return e;if(e instanceof Float32Array)return new tf(i(),[e]);if(e.descriptor&&e.descriptor instanceof Float32Array)return new tf(i(),[e.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")}))}return Object.defineProperty(e.prototype,"labeledDescriptors",{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"distanceThreshold",{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),e.prototype.computeMeanDistance=function(e,t){return t.map((function(t){return bv(t,e)})).reduce((function(e,t){return e+t}),0)/(t.length||1)},e.prototype.matchDescriptor=function(e){var t=this;return this.labeledDescriptors.map((function(n){var r=n.descriptors,i=n.label;return new Zh(i,t.computeMeanDistance(e,r))})).reduce((function(e,t){return e.distance<t.distance?e:t}))},e.prototype.findBestMatch=function(e){var t=this.matchDescriptor(e);return t.distance<this.distanceThreshold?t:new Zh("unknown",t.distance)},e.prototype.toJSON=function(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map((function(e){return e.toJSON()}))}},e.fromJSON=function(t){var n=t.labeledDescriptors.map((function(e){return tf.fromJSON(e)}));return new e(n,t.distanceThreshold)},e}();function xv(e){var t=new _g;return t.extractWeights(e),t}function _v(e){var t=new Cg;return t.extractWeights(e),t}function Sv(e,t){var n=new wh(t.width,t.height),r=n.width,i=n.height;if(r<=0||i<=0)throw new Error("resizeResults - invalid dimensions: "+JSON.stringify({width:r,height:i}));if(Array.isArray(e))return e.map((function(e){return Sv(e,{width:r,height:i})}));if(fm(e)){var o=e.detection.forSize(r,i),a=e.unshiftedLandmarks.forSize(o.box.width,o.box.height);return mm(of(e,o),a)}return rf(e)?of(e,e.detection.forSize(r,i)):e instanceof Yh||e instanceof jh?e.forSize(r,i):e}},7855:(e,t,n)=>{const r=n(1227)("h264-profile-level-id");r.log=console.info.bind(console),t.ProfileConstrainedBaseline=1,t.ProfileBaseline=2,t.ProfileMain=3,t.ProfileConstrainedHigh=4,t.ProfileHigh=5,t.Level1_b=0,t.Level1=10,t.Level1_1=11,t.Level1_2=12,t.Level1_3=13,t.Level2=20,t.Level2_1=21,t.Level2_2=22,t.Level3=30,t.Level3_1=31,t.Level3_2=32,t.Level4=40,t.Level4_1=41,t.Level4_2=42,t.Level5=50,t.Level5_1=51,t.Level5_2=52;class i{constructor(e,t){this.profile=e,this.level=t}}t.ProfileLevelId=i;const o=new i(1,31);class a{constructor(e){this._mask=~u("x",e),this._maskedValue=u("1",e)}isMatch(e){return this._maskedValue===(e&this._mask)}}class s{constructor(e,t,n){this.profile_idc=e,this.profile_iop=t,this.profile=n}}const c=[new s(66,new a("x1xx0000"),1),new s(77,new a("1xxx0000"),1),new s(88,new a("11xx0000"),1),new s(66,new a("x0xx0000"),2),new s(88,new a("10xx0000"),2),new s(77,new a("0x0x0000"),3),new s(100,new a("00000000"),5),new s(100,new a("00001100"),4)];function u(e,t){return(t[0]===e)<<7|(t[1]===e)<<6|(t[2]===e)<<5|(t[3]===e)<<4|(t[4]===e)<<3|(t[5]===e)<<2|(t[6]===e)<<1|t[7]===e}function d(e={}){const t=e["level-asymmetry-allowed"];return 1===t||"1"===t}t.parseProfileLevelId=function(e){if("string"!=typeof e||6!==e.length)return null;const t=parseInt(e,16);if(0===t)return null;const n=255&t,o=t>>8&255,a=t>>16&255;let s;switch(n){case 11:s=16&o?0:11;break;case 10:case 12:case 13:case 20:case 21:case 22:case 30:case 31:case 32:case 40:case 41:case 42:case 50:case 51:case 52:s=n;break;default:return r("parseProfileLevelId() | unrecognized level_idc:%s",n),null}for(const e of c)if(a===e.profile_idc&&e.profile_iop.isMatch(o))return new i(e.profile,s);return r("parseProfileLevelId() | unrecognized profile_idc/profile_iop combination"),null},t.profileLevelIdToString=function(e){if(0==e.level)switch(e.profile){case 1:return"42f00b";case 2:return"42100b";case 3:return"4d100b";default:return r("profileLevelIdToString() | Level 1_b not is allowed for profile:%s",e.profile),null}let t;switch(e.profile){case 1:t="42e0";break;case 2:t="4200";break;case 3:t="4d00";break;case 4:t="640c";break;case 5:t="6400";break;default:return r("profileLevelIdToString() | unrecognized profile:%s",e.profile),null}let n=e.level.toString(16);return 1===n.length&&(n=`0${n}`),`${t}${n}`},t.parseSdpProfileLevelId=function(e={}){const n=e["profile-level-id"];return n?t.parseProfileLevelId(n):o},t.isSameProfile=function(e={},n={}){const r=t.parseSdpProfileLevelId(e),i=t.parseSdpProfileLevelId(n);return Boolean(r&&i&&r.profile===i.profile)},t.generateProfileLevelIdForAnswer=function(e={},n={}){if(!e["profile-level-id"]&&!n["profile-level-id"])return r("generateProfileLevelIdForAnswer() | no profile-level-id in local and remote params"),null;const o=t.parseSdpProfileLevelId(e),a=t.parseSdpProfileLevelId(n);if(!o)throw new TypeError("invalid local_profile_level_id");if(!a)throw new TypeError("invalid remote_profile_level_id");if(o.profile!==a.profile)throw new TypeError("H264 Profile mismatch");const s=d(e)&&d(n),c=o.level,u=function(e,t){return 0===e?10!==t&&0!==t:0===t?10!==e:e<t}(l=c,p=a.level)?l:p;var l,p;const h=s?c:u;return r("generateProfileLevelIdForAnswer() | result: [profile:%s, level:%s]",o.profile,h),t.profileLevelIdToString(new i(o.profile,h))}},9514:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Consumer=void 0;const r=n(8562),i=n(4493),o=n(9992),a=new r.Logger("Consumer");class s extends i.EnhancedEventEmitter{constructor({id:e,localId:t,producerId:n,rtpReceiver:r,track:o,rtpParameters:s,appData:c}){super(),this._closed=!1,this._observer=new i.EnhancedEventEmitter,a.debug("constructor()"),this._id=e,this._localId=t,this._producerId=n,this._rtpReceiver=r,this._track=o,this._rtpParameters=s,this._paused=!o.enabled,this._appData=c||{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}get observer(){return this._observer}close(){this._closed||(a.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(a.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new o.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){a.debug("pause()"),this._closed?a.error("pause() | Consumer closed"):this._paused?a.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){a.debug("resume()"),this._closed?a.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):a.debug("resume() | Consumer is already resumed")}onTrackEnded(){a.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}t.Consumer=s},1623:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DataConsumer=void 0;const r=n(8562),i=n(4493),o=new r.Logger("DataConsumer");class a extends i.EnhancedEventEmitter{constructor({id:e,dataProducerId:t,dataChannel:n,sctpStreamParameters:r,appData:a}){super(),this._closed=!1,this._observer=new i.EnhancedEventEmitter,o.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=n,this._sctpStreamParameters=r,this._appData=a||{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}get observer(){return this._observer}close(){this._closed||(o.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(o.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(o.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?o.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):o.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(o.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(e=>{this._closed||this.safeEmit("message",e.data)}))}}t.DataConsumer=a},5504:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DataProducer=void 0;const r=n(8562),i=n(4493),o=n(9992),a=new r.Logger("DataProducer");class s extends i.EnhancedEventEmitter{constructor({id:e,dataChannel:t,sctpStreamParameters:n,appData:r}){super(),this._closed=!1,this._observer=new i.EnhancedEventEmitter,a.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=n,this._appData=r||{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}get observer(){return this._observer}close(){this._closed||(a.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(a.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(a.debug("send()"),this._closed)throw new o.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(a.debug('DataChannel "open" event'),this.safeEmit("open"))})),this._dataChannel.addEventListener("error",(e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?a.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):a.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(a.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||a.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}t.DataProducer=s},3120:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Device=t.detectDevice=void 0;const s=a(n(1206)),c=n(8562),u=n(4493),d=n(9992),l=o(n(3347)),p=o(n(5280)),h=n(5202),f=n(2960),m=n(6656),g=n(5372),v=n(5697),y=n(564),b=n(1419),w=n(9862),x=n(2205),_=n(7392),S=n(3433),R=n(4770),C=new c.Logger("Device");function E(){if("object"==typeof navigator&&"ReactNative"===navigator.product)return"undefined"==typeof RTCPeerConnection?void C.warn("this._detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?"):"undefined"!=typeof RTCRtpTransceiver?(C.debug("this._detectDevice() | ReactNative UnifiedPlan handler chosen"),"ReactNativeUnifiedPlan"):(C.debug("this._detectDevice() | ReactNative PlanB handler chosen"),"ReactNative");if("object"!=typeof navigator||"string"!=typeof navigator.userAgent)C.warn("this._detectDevice() | unknown device");else{const e=navigator.userAgent,t=s.default.getParser(e),n=t.getEngine();if(t.satisfies({chrome:">=111",chromium:">=111","microsoft edge":">=111"}))return"Chrome111";if(t.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(t.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(t.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(t.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";if(t.satisfies({firefox:">=60"}))return"Firefox60";if(t.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}}))return"Safari12";if(t.satisfies({safari:">=12.0"})&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(t.satisfies({safari:">=11"}))return"Safari11";if(t.satisfies({"microsoft edge":">=11"})&&t.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(n.name&&"blink"===n.name.toLowerCase()){const t=e.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(t){const e=Number(t[1]);return e>=111?"Chrome111":e>=74?"Chrome74":e>=70?"Chrome70":e>=67?"Chrome67":"Chrome55"}return"Chrome111"}C.warn("this._detectDevice() | browser not supported [name:%s, version:%s]",t.getBrowserName(),t.getBrowserVersion())}}t.detectDevice=E,t.Device=class{constructor({handlerName:e,handlerFactory:t,Handler:n}={}){if(this._loaded=!1,this._observer=new u.EnhancedEventEmitter,C.debug("constructor()"),n){if(C.warn("constructor() | Handler option is DEPRECATED, use handlerName or handlerFactory instead"),"string"!=typeof n)throw new TypeError("non string Handler option no longer supported, use handlerFactory instead");e=n}if(e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)C.debug("constructor() | handler given: %s",e);else{if(!(e=E()))throw new d.UnsupportedError("device not supported");C.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=f.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=m.Chrome74.createFactory();break;case"Chrome70":this._handlerFactory=g.Chrome70.createFactory();break;case"Chrome67":this._handlerFactory=v.Chrome67.createFactory();break;case"Chrome55":this._handlerFactory=y.Chrome55.createFactory();break;case"Firefox60":this._handlerFactory=b.Firefox60.createFactory();break;case"Safari12":this._handlerFactory=w.Safari12.createFactory();break;case"Safari11":this._handlerFactory=x.Safari11.createFactory();break;case"Edge11":this._handlerFactory=_.Edge11.createFactory();break;case"ReactNativeUnifiedPlan":this._handlerFactory=S.ReactNativeUnifiedPlan.createFactory();break;case"ReactNative":this._handlerFactory=R.ReactNative.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const r=this._handlerFactory();this._handlerName=r.name,r.close(),this._extendedRtpCapabilities=void 0,this._recvRtpCapabilities=void 0,this._canProduceByKind={audio:!1,video:!1},this._sctpCapabilities=void 0}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){if(!this._loaded)throw new d.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new d.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e}){let t;C.debug("load() [routerRtpCapabilities:%o]",e),e=l.clone(e,void 0);try{if(this._loaded)throw new d.InvalidStateError("already loaded");p.validateRtpCapabilities(e),t=this._handlerFactory();const n=await t.getNativeRtpCapabilities();C.debug("load() | got native RTP capabilities:%o",n),p.validateRtpCapabilities(n),this._extendedRtpCapabilities=p.getExtendedRtpCapabilities(n,e),C.debug("load() | got extended RTP capabilities:%o",this._extendedRtpCapabilities),this._canProduceByKind.audio=p.canSend("audio",this._extendedRtpCapabilities),this._canProduceByKind.video=p.canSend("video",this._extendedRtpCapabilities),this._recvRtpCapabilities=p.getRecvRtpCapabilities(this._extendedRtpCapabilities),p.validateRtpCapabilities(this._recvRtpCapabilities),C.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._sctpCapabilities=await t.getNativeSctpCapabilities(),C.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),p.validateSctpCapabilities(this._sctpCapabilities),C.debug("load() succeeded"),this._loaded=!0,t.close()}catch(e){throw t&&t.close(),e}}canProduce(e){if(!this._loaded)throw new d.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,appData:u}){return C.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,appData:u})}createRecvTransport({id:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,appData:u}){return C.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,appData:u})}createTransport({direction:e,id:t,iceParameters:n,iceCandidates:r,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:s,additionalSettings:c,proprietaryConstraints:u,appData:l}){if(!this._loaded)throw new d.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof n)throw new TypeError("missing iceParameters");if(!Array.isArray(r))throw new TypeError("missing iceCandidates");if("object"!=typeof i)throw new TypeError("missing dtlsParameters");if(o&&"object"!=typeof o)throw new TypeError("wrong sctpParameters");if(l&&"object"!=typeof l)throw new TypeError("if given, appData must be an object");const p=new h.Transport({direction:e,id:t,iceParameters:n,iceCandidates:r,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:s,additionalSettings:c,proprietaryConstraints:u,appData:l,handlerFactory:this._handlerFactory,extendedRtpCapabilities:this._extendedRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",p),p}}},4493:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EnhancedEventEmitter=void 0;const r=n(7187),i=new(n(8562).Logger)("EnhancedEventEmitter");class o extends r.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){const n=super.listenerCount(e);try{return super.emit(e,...t)}catch(t){return i.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t),Boolean(n)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}}t.EnhancedEventEmitter=o},8562:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;const i=r(n(1227)),o="mediasoup-client";t.Logger=class{constructor(e){e?(this._debug=(0,i.default)(`${o}:${e}`),this._warn=(0,i.default)(`${o}:WARN:${e}`),this._error=(0,i.default)(`${o}:ERROR:${e}`)):(this._debug=(0,i.default)(o),this._warn=(0,i.default)(`${o}:WARN`),this._error=(0,i.default)(`${o}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}},6569:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Producer=void 0;const r=n(8562),i=n(4493),o=n(9992),a=new r.Logger("Producer");class s extends i.EnhancedEventEmitter{constructor({id:e,localId:t,rtpSender:n,track:r,rtpParameters:o,stopTracks:s,disableTrackOnPause:c,zeroRtpOnPause:u,appData:d}){super(),this._closed=!1,this._observer=new i.EnhancedEventEmitter,a.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=n,this._track=r,this._kind=r.kind,this._rtpParameters=o,this._paused=!!c&&!r.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=c,this._zeroRtpOnPause=u,this._appData=d||{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}get observer(){return this._observer}close(){this._closed||(a.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(a.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new o.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){a.debug("pause()"),this._closed?a.error("pause() | Producer closed"):(this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@pause",e,t)})).catch((()=>{})),this._observer.safeEmit("pause"))}resume(){a.debug("resume()"),this._closed?a.error("resume() | Producer closed"):(this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise(((e,t)=>{this.safeEmit("@resume",e,t)})).catch((()=>{})),this._observer.safeEmit("resume"))}async replaceTrack({track:e}){if(a.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new o.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new o.InvalidStateError("track ended");e!==this._track?(await new Promise(((t,n)=>{this.safeEmit("@replacetrack",e,t,n)})),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()):a.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new o.InvalidStateError("closed");if("video"!==this._kind)throw new o.UnsupportedError("not a video Producer");if("number"!=typeof e)throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise(((t,n)=>{this.safeEmit("@setmaxspatiallayer",e,t,n)})).catch((()=>{})),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new o.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,n)=>{this.safeEmit("@setrtpencodingparameters",e,t,n)}))}onTrackEnded(){a.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch(e){}}}t.Producer=s},4879:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},7669:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5202:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Transport=void 0;const s=n(2186),c=a(n(4375)),u=n(8562),d=n(4493),l=n(9992),p=o(n(3347)),h=o(n(5280)),f=n(6569),m=n(9514),g=n(5504),v=n(1623),y=new u.Logger("Transport");class b{constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class w extends d.EnhancedEventEmitter{constructor({direction:e,id:t,iceParameters:n,iceCandidates:r,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,proprietaryConstraints:l,appData:h,handlerFactory:f,extendedRtpCapabilities:m,canProduceByKind:g}){super(),this._closed=!1,this._connectionState="new",this._producers=new Map,this._consumers=new Map,this._dataProducers=new Map,this._dataConsumers=new Map,this._probatorConsumerCreated=!1,this._awaitQueue=new s.AwaitQueue,this._pendingConsumerTasks=[],this._consumerCreationInProgress=!1,this._pendingPauseConsumers=new Map,this._consumerPauseInProgress=!1,this._pendingResumeConsumers=new Map,this._consumerResumeInProgress=!1,this._pendingCloseConsumers=new Map,this._consumerCloseInProgress=!1,this._observer=new d.EnhancedEventEmitter,y.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._extendedRtpCapabilities=m,this._canProduceByKind=g,this._maxSctpMessageSize=o?o.maxMessageSize:null,delete(u=p.clone(u,{})).iceServers,delete u.iceTransportPolicy,delete u.bundlePolicy,delete u.rtcpMuxPolicy,delete u.sdpSemantics,this._handler=f(),this._handler.run({direction:e,iceParameters:n,iceCandidates:r,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,proprietaryConstraints:l,extendedRtpCapabilities:m}),this._appData=h||{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}get observer(){return this._observer}close(){if(!this._closed){y.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close();for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close")}}async getStats(){if(this._closed)throw new l.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(y.debug("restartIce()"),this._closed)throw new l.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push((async()=>this._handler.restartIce(e)),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(y.debug("updateIceServers()"),this._closed)throw new l.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push((async()=>this._handler.updateIceServers(e)),"transport.updateIceServers()")}async produce({track:e,encodings:t,codecOptions:n,codec:r,stopTracks:i=!0,disableTrackOnPause:o=!0,zeroRtpOnPause:a=!1,appData:s={}}={}){if(y.debug("produce() [track:%o]",e),this._closed)throw new l.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new l.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new l.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new l.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push((async()=>{let c;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?c=void 0:t&&(c=t.map((e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t})));const{localId:u,rtpParameters:d,rtpSender:l}=await this._handler.send({track:e,encodings:c,codecOptions:n,codec:r});try{h.validateRtpParameters(d);const{id:t}=await new Promise(((t,n)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:d,appData:s},t,n)})),n=new f.Producer({id:t,localId:u,rtpSender:l,track:e,rtpParameters:d,stopTracks:i,disableTrackOnPause:o,zeroRtpOnPause:a,appData:s});return this._producers.set(n.id,n),this.handleProducer(n),this._observer.safeEmit("newproducer",n),n}catch(e){throw this._handler.stopSending(u).catch((()=>{})),e}}),"transport.produce()").catch((t=>{if(i)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:n,rtpParameters:r,streamId:i,appData:o={}}){if(y.debug("consume()"),r=p.clone(r,void 0),this._closed)throw new l.InvalidStateError("closed");if("recv"!==this._direction)throw new l.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==n&&"video"!==n)throw new TypeError(`invalid kind '${n}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");if(!h.canReceive(r,this._extendedRtpCapabilities))throw new l.UnsupportedError("cannot consume this Producer");const a=new b({id:e,producerId:t,kind:n,rtpParameters:r,streamId:i,appData:o});return this._pendingConsumerTasks.push(a),(0,c.default)((()=>{if(this._closed)throw new l.InvalidStateError("closed");!1===this._consumerCreationInProgress&&this.createPendingConsumers()})),a.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:n,label:r="",protocol:i="",appData:o={}}={}){if(y.debug("produceData()"),this._closed)throw new l.InvalidStateError("closed");if("send"!==this._direction)throw new l.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new l.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");return(t||n)&&(e=!1),this._awaitQueue.push((async()=>{const{dataChannel:a,sctpStreamParameters:s}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i});h.validateSctpStreamParameters(s);const{id:c}=await new Promise(((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:s,label:r,protocol:i,appData:o},e,t)})),u=new g.DataProducer({id:c,dataChannel:a,sctpStreamParameters:s,appData:o});return this._dataProducers.set(u.id,u),this.handleDataProducer(u),this._observer.safeEmit("newdataproducer",u),u}),"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:n,label:r="",protocol:i="",appData:o={}}){if(y.debug("consumeData()"),n=p.clone(n,void 0),this._closed)throw new l.InvalidStateError("closed");if("recv"!==this._direction)throw new l.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new l.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");return h.validateSctpStreamParameters(n),this._awaitQueue.push((async()=>{const{dataChannel:a}=await this._handler.receiveDataChannel({sctpStreamParameters:n,label:r,protocol:i}),s=new v.DataConsumer({id:e,dataProducerId:t,dataChannel:a,sctpStreamParameters:n,appData:o});return this._dataConsumers.set(s.id,s),this.handleDataConsumer(s),this._observer.safeEmit("newdataconsumer",s),s}),"transport.consumeData()")}async createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingConsumerTasks.length)return void y.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const n=[];for(const t of e){const{id:e,kind:r,rtpParameters:i,streamId:o}=t.consumerOptions;n.push({trackId:e,kind:r,rtpParameters:i,streamId:o})}try{const r=await this._handler.receive(n);for(let n=0;n<r.length;n++){const i=e[n],o=r[n],{id:a,producerId:s,kind:c,rtpParameters:u,appData:d}=i.consumerOptions,{localId:l,rtpReceiver:p,track:h}=o,f=new m.Consumer({id:a,localId:l,producerId:s,rtpReceiver:p,track:h,rtpParameters:u,appData:d});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),i.resolve(f)}}catch(t){for(const n of e)n.reject(t)}if(t)try{const e=h.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),y.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){y.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}}),"transport.createPendingConsumers()").then((()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()})).catch((()=>{}))}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingPauseConsumers.size)return void y.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.pauseReceiving(t)}catch(e){y.error("pausePendingConsumers() | failed to pause Consumers:",e)}}),"transport.pausePendingConsumers").then((()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()})).catch((()=>{}))}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingResumeConsumers.size)return void y.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map((e=>e.localId));await this._handler.resumeReceiving(t)}catch(e){y.error("resumePendingConsumers() | failed to resume Consumers:",e)}}),"transport.resumePendingConsumers").then((()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()})).catch((()=>{}))}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push((async()=>{if(0===this._pendingCloseConsumers.size)return void y.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map((e=>e.localId)))}catch(e){y.error("closePendingConsumers() | failed to close Consumers:",e)}}),"transport.closePendingConsumers").then((()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()})).catch((()=>{}))}handleHandler(){const e=this._handler;e.on("@connect",(({dtlsParameters:e},t,n)=>{this._closed?n(new l.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,n)})),e.on("@connectionstatechange",(e=>{e!==this._connectionState&&(y.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))}))}handleProducer(e){e.on("@close",(()=>{this._producers.delete(e.id),this._closed||this._awaitQueue.push((async()=>this._handler.stopSending(e.localId)),"producer @close event").catch((e=>y.warn("producer.close() failed:%o",e)))})),e.on("@pause",((t,n)=>{this._awaitQueue.push((async()=>this._handler.pauseSending(e.localId)),"producer @pause event").then(t).catch(n)})),e.on("@resume",((t,n)=>{this._awaitQueue.push((async()=>this._handler.resumeSending(e.localId)),"producer @resume event").then(t).catch(n)})),e.on("@replacetrack",((t,n,r)=>{this._awaitQueue.push((async()=>this._handler.replaceTrack(e.localId,t)),"producer @replacetrack event").then(n).catch(r)})),e.on("@setmaxspatiallayer",((t,n,r)=>{this._awaitQueue.push((async()=>this._handler.setMaxSpatialLayer(e.localId,t)),"producer @setmaxspatiallayer event").then(n).catch(r)})),e.on("@setrtpencodingparameters",((t,n,r)=>{this._awaitQueue.push((async()=>this._handler.setRtpEncodingParameters(e.localId,t)),"producer @setrtpencodingparameters event").then(n).catch(r)})),e.on("@getstats",((t,n)=>{if(this._closed)return n(new l.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(n)}))}handleConsumer(e){e.on("@close",(()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),this._closed||(this._pendingCloseConsumers.set(e.id,e),!1===this._consumerCloseInProgress&&this.closePendingConsumers())})),e.on("@pause",(()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),(0,c.default)((()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()}))})),e.on("@resume",(()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),(0,c.default)((()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()}))})),e.on("@getstats",((t,n)=>{if(this._closed)return n(new l.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(n)}))}handleDataProducer(e){e.on("@close",(()=>{this._dataProducers.delete(e.id)}))}handleDataConsumer(e){e.on("@close",(()=>{this._dataConsumers.delete(e.id)}))}}t.Transport=w},9992:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidStateError=t.UnsupportedError=void 0;class n extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,n):this.stack=new Error(e).stack}}t.UnsupportedError=n;class r extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}}t.InvalidStateError=r},2960:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome111=void 0;const a=o(n(766)),s=n(8562),c=o(n(3347)),u=o(n(5280)),d=o(n(2267)),l=o(n(9072)),p=o(n(8954)),h=n(9316),f=n(7910),m=n(2770),g=new s.Logger("Chrome111"),v={OS:1024,MIS:1024};class y extends h.HandlerInterface{static createFactory(){return()=>new y}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome111"}close(){if(g.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){g.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const n=a.parse(t.sdp),r=d.extractRtpCapabilities({sdpObject:n});return p.addNackSuppportForOpus(r),r}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return g.debug("getNativeSctpCapabilities()"),{numStreams:v}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:d}){g.debug("run()"),this._direction=e,this._remoteSdp=new f.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i}),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",d),video:u.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:u.getSendingRemoteRtpParameters("audio",d),video:u.getSendingRemoteRtpParameters("video",d)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):(g.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})))}async updateIceServers(e){g.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(g.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});g.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();g.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;if(this.assertSendDirection(),g.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){t.forEach(((e,t)=>{e.rid=`r${t}`}));let e=1,n=1;for(const e of t){const t=e.scalabilityMode?(0,m.parse)(e.scalabilityMode).temporalLayers:3;t>n&&(n=t)}for(const r of t)r.rid="r"+e++,r.scalabilityMode=`L1T${n}`}const o=c.clone(this._sendingRtpParametersByKind[e.kind],{});o.codecs=u.reduceCodecs(o.codecs,r);const s=c.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});s.codecs=u.reduceCodecs(s.codecs,r);const p=this._remoteSdp.getNextMediaSectionIdx(),h=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t}),f=await this._pc.createOffer();let v=a.parse(f.sdp);this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:v}),g.debug("send() | calling pc.setLocalDescription() [offer:%o]",f),await this._pc.setLocalDescription(f);const y=h.mid;o.mid=y,v=a.parse(this._pc.localDescription.sdp);const b=v.media[p.idx];if(o.rtcp.cname=d.getCname({offerMediaObject:b}),t)if(1===t.length){const e=l.getRtpEncodings({offerMediaObject:b});Object.assign(e[0],t[0]),o.encodings=e}else o.encodings=t;else o.encodings=l.getRtpEncodings({offerMediaObject:b});this._remoteSdp.send({offerMediaObject:b,reuseMid:p.reuseMid,offerRtpParameters:o,answerRtpParameters:s,codecOptions:n,extmapAllowMixed:!0});const w={type:"answer",sdp:this._remoteSdp.getSdp()};return g.debug("send() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w),this._mapMidTransceiver.set(y,h),{localId:y,rtpParameters:o,rtpSender:h.sender}}async stopSending(e){this.assertSendDirection(),g.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const n=await this._pc.createOffer();g.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertSendDirection(),g.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const n=await this._pc.createOffer();g.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async resumeSending(e){this.assertSendDirection(),g.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const n=await this._pc.createOffer();g.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async replaceTrack(e,t){this.assertSendDirection(),t?g.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):g.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),g.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),g.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:i};g.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%v.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),g.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:o}=t;g.debug("receive() [trackId:%s, kind:%s]",e,n);const a=i.mid||String(this._mapMidTransceiver.size);r.set(e,a),this._remoteSdp.receive({mid:a,kind:n,offerRtpParameters:i,streamId:o||i.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let o=await this._pc.createAnswer();const s=a.parse(o.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));d.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}o={type:"answer",sdp:a.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:s}),g.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),await this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,i=r.get(e),o=this._pc.getTransceivers().find((e=>e.mid===i));if(!o)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,o),n.push({localId:i,track:o.receiver.track,rtpReceiver:o.receiver})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c,protocol:n};g.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=d.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Chrome111=y},564:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome55=void 0;const a=o(n(766)),s=n(8562),c=n(9992),u=o(n(3347)),d=o(n(5280)),l=o(n(2267)),p=o(n(9875)),h=n(9316),f=n(7910),m=new s.Logger("Chrome55"),g={OS:1024,MIS:1024};class v extends h.HandlerInterface{static createFactory(){return()=>new v}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome55"}close(){if(m.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){m.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const n=a.parse(t.sdp);return l.extractRtpCapabilities({sdpObject:n})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return m.debug("getNativeSctpCapabilities()"),{numStreams:g}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:u}){m.debug("run()"),this._direction=e,this._remoteSdp=new f.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:d.getSendingRtpParameters("audio",u),video:d.getSendingRtpParameters("video",u)},this._sendingRemoteRtpParametersByKind={audio:d.getSendingRemoteRtpParameters("audio",u),video:d.getSendingRemoteRtpParameters("video",u)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(m.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){m.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(m.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});m.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();m.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),m.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),r&&m.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let o,s=await this._pc.createOffer(),c=a.parse(s.sdp);const h=u.clone(this._sendingRtpParametersByKind[e.kind],{});h.codecs=d.reduceCodecs(h.codecs);const f=u.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});if(f.codecs=d.reduceCodecs(f.codecs),this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:c}),"video"===e.kind&&t&&t.length>1&&(m.debug("send() | enabling simulcast"),c=a.parse(s.sdp),o=c.media.find((e=>"video"===e.type)),p.addLegacySimulcast({offerMediaObject:o,track:e,numStreams:t.length}),s={type:"offer",sdp:a.write(c)}),m.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),c=a.parse(this._pc.localDescription.sdp),o=c.media.find((t=>t.type===e.kind)),h.rtcp.cname=l.getCname({offerMediaObject:o}),h.encodings=p.getRtpEncodings({offerMediaObject:o,track:e}),t)for(let e=0;e<h.encodings.length;++e)t[e]&&Object.assign(h.encodings[e],t[e]);if(h.encodings.length>1&&"video/vp8"===h.codecs[0].mimeType.toLowerCase())for(const e of h.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:o,offerRtpParameters:h,answerRtpParameters:f,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g);const v=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(v,e),{localId:v,rtpParameters:h}}async stopSending(e){this.assertSendDirection(),m.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const n=await this._pc.createOffer();m.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n);try{await this._pc.setLocalDescription(n)}catch(e){if(0===this._sendStream.getTracks().length)return void m.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const r={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new c.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new c.UnsupportedError(" not implemented")}async setRtpEncodingParameters(e,t){throw new c.UnsupportedError("not supported")}async getSenderStats(e){throw new c.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:n,protocol:i};m.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%g.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),m.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[];for(const t of e){const{trackId:e,kind:n,rtpParameters:r,streamId:i}=t;m.debug("receive() [trackId:%s, kind:%s]",e,n);const o=n;this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:r,streamId:i||r.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const o=a.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:n}=t,r=e,i=o.media.find((e=>String(e.mid)===r));l.applyCodecParameters({offerRtpParameters:n,answerMediaObject:i})}i={type:"answer",sdp:a.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:o}),m.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const t of e){const{kind:e,trackId:r,rtpParameters:i}=t,o=e,a=r,s=t.streamId||i.rtcp.cname,c=this._pc.getRemoteStreams().find((e=>e.id===s)).getTrackById(a);if(!c)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(a,{mid:o,rtpParameters:i}),n.push({localId:a,track:c})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){m.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:n}=this._mapRecvLocalIdInfo.get(t)||{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:n})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();m.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new c.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:c,protocol:n};m.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}m.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=l.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Chrome55=v},5697:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome67=void 0;const a=o(n(766)),s=n(8562),c=o(n(3347)),u=o(n(5280)),d=o(n(2267)),l=o(n(9875)),p=n(9316),h=n(7910),f=new s.Logger("Chrome67"),m={OS:1024,MIS:1024};class g extends p.HandlerInterface{static createFactory(){return()=>new g}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome67"}close(){if(f.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){f.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const n=a.parse(t.sdp);return d.extractRtpCapabilities({sdpObject:n})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return f.debug("getNativeSctpCapabilities()"),{numStreams:m}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:d}){f.debug("run()"),this._direction=e,this._remoteSdp=new h.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",d),video:u.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:u.getSendingRemoteRtpParameters("audio",d),video:u.getSendingRemoteRtpParameters("video",d)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(f.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){f.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(f.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});f.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();f.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),f.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),r&&f.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let o,s=await this._pc.createOffer(),p=a.parse(s.sdp);const h=c.clone(this._sendingRtpParametersByKind[e.kind],{});h.codecs=u.reduceCodecs(h.codecs);const m=c.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});if(m.codecs=u.reduceCodecs(m.codecs),this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:p}),"video"===e.kind&&t&&t.length>1&&(f.debug("send() | enabling simulcast"),p=a.parse(s.sdp),o=p.media.find((e=>"video"===e.type)),l.addLegacySimulcast({offerMediaObject:o,track:e,numStreams:t.length}),s={type:"offer",sdp:a.write(p)}),f.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),p=a.parse(this._pc.localDescription.sdp),o=p.media.find((t=>t.type===e.kind)),h.rtcp.cname=d.getCname({offerMediaObject:o}),h.encodings=l.getRtpEncodings({offerMediaObject:o,track:e}),t)for(let e=0;e<h.encodings.length;++e)t[e]&&Object.assign(h.encodings[e],t[e]);if(h.encodings.length>1&&"video/vp8"===h.codecs[0].mimeType.toLowerCase())for(const e of h.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:o,offerRtpParameters:h,answerRtpParameters:m,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g);const v=String(this._nextSendLocalId);this._nextSendLocalId++;const y=this._pc.getSenders().find((t=>t.track===e));return this._mapSendLocalIdRtpSender.set(v,y),{localId:v,rtpParameters:h,rtpSender:y}}async stopSending(e){this.assertSendDirection(),f.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");this._pc.removeTrack(t),t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const n=await this._pc.createOffer();f.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n);try{await this._pc.setLocalDescription(n)}catch(e){if(0===this._sendStream.getTracks().length)return void f.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const r={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?f.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):f.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapSendLocalIdRtpSender.get(e);if(!n)throw new Error("associated RTCRtpSender not found");const r=n.track;await n.replaceTrack(t),r&&this._sendStream.removeTrack(r),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),f.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapSendLocalIdRtpSender.get(e);if(!n)throw new Error("associated RTCRtpSender not found");const r=n.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.setParameters(r)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),f.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapSendLocalIdRtpSender.get(e);if(!n)throw new Error("associated RTCRtpSender not found");const r=n.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.setParameters(r)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:n,protocol:i};f.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%m.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),f.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[];for(const t of e){const{trackId:e,kind:n,rtpParameters:r,streamId:i}=t;f.debug("receive() [trackId:%s, kind:%s]",e,n);const o=n;this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:r,streamId:i||r.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const o=a.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:n}=t,r=e,i=o.media.find((e=>String(e.mid)===r));d.applyCodecParameters({offerRtpParameters:n,answerMediaObject:i})}i={type:"answer",sdp:a.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:o}),f.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const t of e){const{kind:e,trackId:r,rtpParameters:i}=t,o=r,a=e,s=this._pc.getReceivers().find((e=>e.track&&e.track.id===o));if(!s)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(o,{mid:a,rtpParameters:i,rtpReceiver:s}),n.push({localId:o,track:s.track,rtpReceiver:s})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){f.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:n}=this._mapRecvLocalIdInfo.get(t)||{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:n})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();f.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)||{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:c,protocol:n};f.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}f.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=d.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Chrome67=g},5372:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome70=void 0;const a=o(n(766)),s=n(8562),c=o(n(3347)),u=o(n(5280)),d=o(n(2267)),l=o(n(9072)),p=n(9316),h=n(7910),f=n(2770),m=new s.Logger("Chrome70"),g={OS:1024,MIS:1024};class v extends p.HandlerInterface{static createFactory(){return()=>new v}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome70"}close(){if(m.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){m.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const n=a.parse(t.sdp);return d.extractRtpCapabilities({sdpObject:n})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return m.debug("getNativeSctpCapabilities()"),{numStreams:g}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:d}){m.debug("run()"),this._direction=e,this._remoteSdp=new h.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i}),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",d),video:u.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:u.getSendingRemoteRtpParameters("audio",d),video:u.getSendingRemoteRtpParameters("video",d)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(m.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){m.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(m.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});m.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();m.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),m.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const o=c.clone(this._sendingRtpParametersByKind[e.kind],{});o.codecs=u.reduceCodecs(o.codecs,r);const s=c.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});s.codecs=u.reduceCodecs(s.codecs,r);const p=this._remoteSdp.getNextMediaSectionIdx(),h=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let g,v=await this._pc.createOffer(),y=a.parse(v.sdp);this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:y}),t&&t.length>1&&(m.debug("send() | enabling legacy simulcast"),y=a.parse(v.sdp),g=y.media[p.idx],l.addLegacySimulcast({offerMediaObject:g,numStreams:t.length}),v={type:"offer",sdp:a.write(y)});let b=!1;const w=(0,f.parse)((t||[{}])[0].scalabilityMode);if(t&&1===t.length&&w.spatialLayers>1&&"video/vp9"===o.codecs[0].mimeType.toLowerCase()&&(m.debug("send() | enabling legacy simulcast for VP9 SVC"),b=!0,y=a.parse(v.sdp),g=y.media[p.idx],l.addLegacySimulcast({offerMediaObject:g,numStreams:w.spatialLayers}),v={type:"offer",sdp:a.write(y)}),m.debug("send() | calling pc.setLocalDescription() [offer:%o]",v),await this._pc.setLocalDescription(v),t){m.debug("send() | applying given encodings");const e=h.sender.getParameters();for(let n=0;n<(e.encodings||[]).length;++n){const r=e.encodings[n],i=t[n];if(!i)break;e.encodings[n]=Object.assign(r,i)}await h.sender.setParameters(e)}const x=h.mid;if(o.mid=x,y=a.parse(this._pc.localDescription.sdp),g=y.media[p.idx],o.rtcp.cname=d.getCname({offerMediaObject:g}),o.encodings=l.getRtpEncodings({offerMediaObject:g}),t)for(let e=0;e<o.encodings.length;++e)t[e]&&Object.assign(o.encodings[e],t[e]);if(b&&(o.encodings=[o.encodings[0]]),o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,reuseMid:p.reuseMid,offerRtpParameters:o,answerRtpParameters:s,codecOptions:n});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return m.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(x,h),{localId:x,rtpParameters:o,rtpSender:h.sender}}async stopSending(e){this.assertSendDirection(),m.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const n=await this._pc.createOffer();m.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._mapMidTransceiver.delete(e)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?m.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):m.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),m.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();m.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),m.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();m.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:n,protocol:i};m.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%g.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),m.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:o}=t;m.debug("receive() [trackId:%s, kind:%s]",e,n);const a=i.mid||String(this._mapMidTransceiver.size);r.set(e,a),this._remoteSdp.receive({mid:a,kind:n,offerRtpParameters:i,streamId:o||i.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let o=await this._pc.createAnswer();const s=a.parse(o.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));d.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}o={type:"answer",sdp:a.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:s}),m.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),await this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,i=r.get(e),o=this._pc.getTransceivers().find((e=>e.mid===i));if(!o)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,o),n.push({localId:i,track:o.receiver.track,rtpReceiver:o.receiver})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){m.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();m.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:c,protocol:n};m.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}m.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=d.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Chrome70=v},6656:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Chrome74=void 0;const a=o(n(766)),s=n(8562),c=o(n(3347)),u=o(n(5280)),d=o(n(2267)),l=o(n(9072)),p=o(n(8954)),h=n(9316),f=n(7910),m=n(2770),g=new s.Logger("Chrome74"),v={OS:1024,MIS:1024};class y extends h.HandlerInterface{static createFactory(){return()=>new y}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome74"}close(){if(g.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){g.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const n=a.parse(t.sdp),r=d.extractRtpCapabilities({sdpObject:n});return p.addNackSuppportForOpus(r),r}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return g.debug("getNativeSctpCapabilities()"),{numStreams:v}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:d}){g.debug("run()"),this._direction=e,this._remoteSdp=new f.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i}),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",d),video:u.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:u.getSendingRemoteRtpParameters("audio",d),video:u.getSendingRemoteRtpParameters("video",d)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):(g.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})))}async updateIceServers(e){g.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(g.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});g.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();g.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),g.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const o=c.clone(this._sendingRtpParametersByKind[e.kind],{});o.codecs=u.reduceCodecs(o.codecs,r);const s=c.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});s.codecs=u.reduceCodecs(s.codecs,r);const p=this._remoteSdp.getNextMediaSectionIdx(),h=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let f,v=await this._pc.createOffer(),y=a.parse(v.sdp);this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:y});let b=!1;const w=(0,m.parse)((t||[{}])[0].scalabilityMode);t&&1===t.length&&w.spatialLayers>1&&"video/vp9"===o.codecs[0].mimeType.toLowerCase()&&(g.debug("send() | enabling legacy simulcast for VP9 SVC"),b=!0,y=a.parse(v.sdp),f=y.media[p.idx],l.addLegacySimulcast({offerMediaObject:f,numStreams:w.spatialLayers}),v={type:"offer",sdp:a.write(y)}),g.debug("send() | calling pc.setLocalDescription() [offer:%o]",v),await this._pc.setLocalDescription(v);const x=h.mid;if(o.mid=x,y=a.parse(this._pc.localDescription.sdp),f=y.media[p.idx],o.rtcp.cname=d.getCname({offerMediaObject:f}),t)if(1===t.length){let e=l.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),b&&(e=[e[0]]),o.encodings=e}else o.encodings=t;else o.encodings=l.getRtpEncodings({offerMediaObject:f});if(o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${w.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,reuseMid:p.reuseMid,offerRtpParameters:o,answerRtpParameters:s,codecOptions:n,extmapAllowMixed:!0});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return g.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(x,h),{localId:x,rtpParameters:o,rtpSender:h.sender}}async stopSending(e){this.assertSendDirection(),g.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const n=await this._pc.createOffer();g.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertSendDirection(),g.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const n=await this._pc.createOffer();g.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async resumeSending(e){this.assertSendDirection(),g.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const n=await this._pc.createOffer();g.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async replaceTrack(e,t){this.assertSendDirection(),t?g.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):g.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),g.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),g.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:i};g.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%v.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),g.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:o}=t;g.debug("receive() [trackId:%s, kind:%s]",e,n);const a=i.mid||String(this._mapMidTransceiver.size);r.set(e,a),this._remoteSdp.receive({mid:a,kind:n,offerRtpParameters:i,streamId:o||i.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let o=await this._pc.createAnswer();const s=a.parse(o.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));d.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}o={type:"answer",sdp:a.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:s}),g.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),await this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,i=r.get(e),o=this._pc.getTransceivers().find((e=>e.mid===i));if(!o)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,o),n.push({localId:i,track:o.receiver.track,rtpReceiver:o.receiver})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c,protocol:n};g.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=d.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Chrome74=y},7392:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Edge11=void 0;const a=n(8562),s=n(9992),c=o(n(3347)),u=o(n(5280)),d=o(n(3635)),l=n(9316),p=new a.Logger("Edge11");class h extends l.HandlerInterface{static createFactory(){return()=>new h}constructor(){super(),this._rtpSenders=new Map,this._rtpReceivers=new Map,this._nextSendLocalId=0,this._transportReady=!1}get name(){return"Edge11"}close(){p.debug("close()");try{this._iceGatherer.close()}catch(e){}try{this._iceTransport.stop()}catch(e){}try{this._dtlsTransport.stop()}catch(e){}for(const e of this._rtpSenders.values())try{e.stop()}catch(e){}for(const e of this._rtpReceivers.values())try{e.stop()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){return p.debug("getNativeRtpCapabilities()"),d.getCapabilities()}async getNativeSctpCapabilities(){return p.debug("getNativeSctpCapabilities()"),{numStreams:{OS:0,MIS:0}}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:d,extendedRtpCapabilities:l}){p.debug("run()"),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",l),video:u.getSendingRtpParameters("video",l)},this._remoteIceParameters=t,this._remoteIceCandidates=n,this._remoteDtlsParameters=r,this._cname=`CNAME-${c.generateRandomNumber()}`,this.setIceGatherer({iceServers:o,iceTransportPolicy:a}),this.setIceTransport(),this.setDtlsTransport()}async updateIceServers(e){throw new s.UnsupportedError("not supported")}async restartIce(e){if(p.debug("restartIce()"),this._remoteIceParameters=e,this._transportReady){p.debug("restartIce() | calling iceTransport.start()"),this._iceTransport.start(this._iceGatherer,e,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({})}}async getTransportStats(){return this._iceTransport.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){p.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),p.debug("send() | calling new RTCRtpSender()");const i=new RTCRtpSender(e,this._dtlsTransport),o=c.clone(this._sendingRtpParametersByKind[e.kind],{});o.codecs=u.reduceCodecs(o.codecs,r);const a=o.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));t||(t=[{}]);for(const e of t)e.ssrc=c.generateRandomNumber(),a&&(e.rtx={ssrc:c.generateRandomNumber()});o.encodings=t,o.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const s=d.mangleRtpParameters(o);p.debug("send() | calling rtpSender.send() [params:%o]",s),await i.send(s);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._rtpSenders.set(l,i),{localId:l,rtpParameters:o,rtpSender:i}}async stopSending(e){p.debug("stopSending() [localId:%s]",e);const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");this._rtpSenders.delete(e);try{p.debug("stopSending() | calling rtpSender.stop()"),t.stop()}catch(e){throw p.warn("stopSending() | rtpSender.stop() failed:%o",e),e}}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){t?p.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):p.debug("replaceTrack() [localId:%s, no track]",e);const n=this._rtpSenders.get(e);if(!n)throw new Error("RTCRtpSender not found");n.setTrack(t)}async setMaxSpatialLayer(e,t){p.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._rtpSenders.get(e);if(!n)throw new Error("RTCRtpSender not found");const r=n.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.setParameters(r)}async setRtpEncodingParameters(e,t){p.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._rtpSenders.get(e);if(!n)throw new Error("RTCRtpSender not found");const r=n.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.setParameters(r)}async getSenderStats(e){const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");return t.getStats()}async sendDataChannel(e){throw new s.UnsupportedError("not implemented")}async receive(e){const t=[];for(const t of e){const{trackId:e,kind:n}=t;p.debug("receive() [trackId:%s, kind:%s]",e,n)}this._transportReady||await this.setupTransport({localDtlsRole:"server"});for(const n of e){const{trackId:e,kind:r,rtpParameters:i}=n;p.debug("receive() | calling new RTCRtpReceiver()");const o=new RTCRtpReceiver(this._dtlsTransport,r);o.addEventListener("error",(e=>{p.error('rtpReceiver "error" event [event:%o]',e)}));const a=d.mangleRtpParameters(i);p.debug("receive() | calling rtpReceiver.receive() [params:%o]",a),await o.receive(a);const s=e;this._rtpReceivers.set(s,o),t.push({localId:s,track:o.track,rtpReceiver:o})}return t}async stopReceiving(e){for(const t of e){p.debug("stopReceiving() [localId:%s]",t);const n=this._rtpReceivers.get(t);if(!n)throw new Error("RTCRtpReceiver not found");this._rtpReceivers.delete(t);try{p.debug("stopReceiving() | calling rtpReceiver.stop()"),n.stop()}catch(e){p.warn("stopReceiving() | rtpReceiver.stop() failed:%o",e)}}}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){const t=this._rtpReceivers.get(e);if(!t)throw new Error("RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel(e){throw new s.UnsupportedError("not implemented")}setIceGatherer({iceServers:e,iceTransportPolicy:t}){const n=new RTCIceGatherer({iceServers:e||[],gatherPolicy:t||"all"});n.addEventListener("error",(e=>{p.error('iceGatherer "error" event [event:%o]',e)}));try{n.gather()}catch(e){p.debug("setIceGatherer() | iceGatherer.gather() failed: %s",e.toString())}this._iceGatherer=n}setIceTransport(){const e=new RTCIceTransport(this._iceGatherer);e.addEventListener("statechange",(()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})),e.addEventListener("icestatechange",(()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})),e.addEventListener("candidatepairchange",(e=>{p.debug('iceTransport "candidatepairchange" event [pair:%o]',e.pair)})),this._iceTransport=e}setDtlsTransport(){const e=new RTCDtlsTransport(this._iceTransport);e.addEventListener("statechange",(()=>{p.debug('dtlsTransport "statechange" event [state:%s]',e.state)})),e.addEventListener("dtlsstatechange",(()=>{p.debug('dtlsTransport "dtlsstatechange" event [state:%s]',e.state),"closed"===e.state&&this.emit("@connectionstatechange","closed")})),e.addEventListener("error",(e=>{p.error('dtlsTransport "error" event [event:%o]',e)})),this._dtlsTransport=e}async setupTransport({localDtlsRole:e}){p.debug("setupTransport()");const t=this._dtlsTransport.getLocalParameters();t.role=e,await new Promise(((e,n)=>{this.safeEmit("@connect",{dtlsParameters:t},e,n)})),this._iceTransport.start(this._iceGatherer,this._remoteIceParameters,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({}),this._remoteDtlsParameters.fingerprints=this._remoteDtlsParameters.fingerprints.filter((e=>"sha-256"===e.algorithm||"sha-384"===e.algorithm||"sha-512"===e.algorithm)),this._dtlsTransport.start(this._remoteDtlsParameters),this._transportReady=!0}}t.Edge11=h},1419:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Firefox60=void 0;const a=o(n(766)),s=n(8562),c=n(9992),u=o(n(3347)),d=o(n(5280)),l=o(n(2267)),p=o(n(9072)),h=n(9316),f=n(7910),m=n(2770),g=new s.Logger("Firefox60"),v={OS:16,MIS:2048};class y extends h.HandlerInterface{static createFactory(){return()=>new y}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox60"}close(){if(g.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){g.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const n=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"});const r=e.addTransceiver(n,{direction:"sendrecv"}),i=r.sender.getParameters(),o=[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}];i.encodings=o,await r.sender.setParameters(i);const s=await e.createOffer();try{t.remove()}catch(e){}try{n.stop()}catch(e){}try{e.close()}catch(e){}const c=a.parse(s.sdp);return l.extractRtpCapabilities({sdpObject:c})}catch(r){try{t.remove()}catch(e){}try{n.stop()}catch(e){}try{e.close()}catch(e){}throw r}}async getNativeSctpCapabilities(){return g.debug("getNativeSctpCapabilities()"),{numStreams:v}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:u}){g.debug("run()"),this._direction=e,this._remoteSdp=new f.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i}),this._sendingRtpParametersByKind={audio:d.getSendingRtpParameters("audio",u),video:d.getSendingRtpParameters("video",u)},this._sendingRemoteRtpParametersByKind={audio:d.getSendingRemoteRtpParameters("audio",u),video:d.getSendingRemoteRtpParameters("video",u)},this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(g.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){throw new c.UnsupportedError("not supported")}async restartIce(e){if(g.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});g.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();g.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){this.assertSendDirection(),g.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&(t=u.clone(t,[])).length>1&&(t.forEach(((e,t)=>{e.rid=`r${t}`})),t.reverse());const i=u.clone(this._sendingRtpParametersByKind[e.kind],{});i.codecs=d.reduceCodecs(i.codecs,r);const o=u.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});o.codecs=d.reduceCodecs(o.codecs,r);const s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});if(t){const e=s.sender.getParameters();e.encodings=t,await s.sender.setParameters(e)}const c=await this._pc.createOffer();let h=a.parse(c.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:h});const f=(0,m.parse)((t||[{}])[0].scalabilityMode);g.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);const v=s.mid;i.mid=v,h=a.parse(this._pc.localDescription.sdp);const y=h.media[h.media.length-1];if(i.rtcp.cname=l.getCname({offerMediaObject:y}),t)if(1===t.length){const e=p.getRtpEncodings({offerMediaObject:y});Object.assign(e[0],t[0]),i.encodings=e}else i.encodings=t.reverse();else i.encodings=p.getRtpEncodings({offerMediaObject:y});if(i.encodings.length>1&&("video/vp8"===i.codecs[0].mimeType.toLowerCase()||"video/h264"===i.codecs[0].mimeType.toLowerCase()))for(const e of i.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,offerRtpParameters:i,answerRtpParameters:o,codecOptions:n,extmapAllowMixed:!0});const b={type:"answer",sdp:this._remoteSdp.getSdp()};return g.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),this._mapMidTransceiver.set(v,s),{localId:v,rtpParameters:i,rtpSender:s.sender}}async stopSending(e){g.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const n=await this._pc.createOffer();g.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertSendDirection(),g.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const n=await this._pc.createOffer();g.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async resumeSending(e){this.assertSendDirection(),g.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const n=await this._pc.createOffer();g.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async replaceTrack(e,t){this.assertSendDirection(),t?g.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):g.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),g.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated transceiver not found");const r=n.sender.getParameters();t=r.encodings.length-1-t,r.encodings.forEach(((e,n)=>{e.active=n>=t})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),g.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){this.assertSendDirection();const o={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:i};g.debug("sendDataChannel() [options:%o]",o);const s=this._pc.createDataChannel(r,o);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%v.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),g.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:s,sctpStreamParameters:{streamId:o.id,ordered:o.ordered,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],n=new Map;for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:o}=t;g.debug("receive() [trackId:%s, kind:%s]",e,r);const a=i.mid||String(this._mapMidTransceiver.size);n.set(e,a),this._remoteSdp.receive({mid:a,kind:r,offerRtpParameters:i,streamId:o||i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const o=a.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:r}=t,s=n.get(e),c=o.media.find((e=>String(e.mid)===s));l.applyCodecParameters({offerRtpParameters:r,answerMediaObject:c}),i={type:"answer",sdp:a.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),g.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{trackId:e}=r,i=n.get(e),o=this._pc.getTransceivers().find((e=>e.mid===i));if(!o)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,o),t.push({localId:i,track:o.receiver.track,rtpReceiver:o.receiver})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){this.assertRecvDirection();const{streamId:r,ordered:i,maxPacketLifeTime:o,maxRetransmits:s}=e,c={negotiated:!0,id:r,ordered:i,maxPacketLifeTime:o,maxRetransmits:s,protocol:n};g.debug("receiveDataChannel() [options:%o]",c);const u=this._pc.createDataChannel(t,c);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:u}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=l.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Firefox60=y},9316:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HandlerInterface=void 0;const r=n(4493);class i extends r.EnhancedEventEmitter{constructor(){super()}}t.HandlerInterface=i},4770:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ReactNative=void 0;const a=o(n(766)),s=n(8562),c=n(9992),u=o(n(3347)),d=o(n(5280)),l=o(n(2267)),p=o(n(9875)),h=n(9316),f=n(7910),m=new s.Logger("ReactNative"),g={OS:1024,MIS:1024};class v extends h.HandlerInterface{static createFactory(){return()=>new v}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNative"}close(){if(m.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){m.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const n=a.parse(t.sdp);return l.extractRtpCapabilities({sdpObject:n})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return m.debug("getNativeSctpCapabilities()"),{numStreams:g}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:u}){m.debug("run()"),this._direction=e,this._remoteSdp=new f.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:d.getSendingRtpParameters("audio",u),video:d.getSendingRtpParameters("video",u)},this._sendingRemoteRtpParametersByKind={audio:d.getSendingRemoteRtpParameters("audio",u),video:d.getSendingRemoteRtpParameters("video",u)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(m.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){m.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(m.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});m.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();m.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),m.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),r&&m.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let o,s=await this._pc.createOffer(),c=a.parse(s.sdp);const h=u.clone(this._sendingRtpParametersByKind[e.kind],{});h.codecs=d.reduceCodecs(h.codecs);const f=u.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});if(f.codecs=d.reduceCodecs(f.codecs),this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:c}),"video"===e.kind&&t&&t.length>1&&(m.debug("send() | enabling simulcast"),c=a.parse(s.sdp),o=c.media.find((e=>"video"===e.type)),p.addLegacySimulcast({offerMediaObject:o,track:e,numStreams:t.length}),s={type:"offer",sdp:a.write(c)}),m.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),c=a.parse(this._pc.localDescription.sdp),o=c.media.find((t=>t.type===e.kind)),h.rtcp.cname=l.getCname({offerMediaObject:o}),h.encodings=p.getRtpEncodings({offerMediaObject:o,track:e}),t)for(let e=0;e<h.encodings.length;++e)t[e]&&Object.assign(h.encodings[e],t[e]);if(h.encodings.length>1&&("video/vp8"===h.codecs[0].mimeType.toLowerCase()||"video/h264"===h.codecs[0].mimeType.toLowerCase()))for(const e of h.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:o,offerRtpParameters:h,answerRtpParameters:f,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g);const v=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(v,e),{localId:v,rtpParameters:h}}async stopSending(e){this.assertSendDirection(),m.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const n=await this._pc.createOffer();m.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n);try{await this._pc.setLocalDescription(n)}catch(e){if(0===this._sendStream.getTracks().length)return void m.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const r={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new c.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new c.UnsupportedError("not implemented")}async setRtpEncodingParameters(e,t){throw new c.UnsupportedError("not implemented")}async getSenderStats(e){throw new c.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:n,protocol:i};m.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%g.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),m.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};m.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i}=t;m.debug("receive() [trackId:%s, kind:%s]",e,n);const o=n;let a=t.streamId||i.rtcp.cname;m.debug("receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc"),a+=`-hack-${u.generateRandomNumber()}`,r.set(e,a),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:a,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let o=await this._pc.createAnswer();const s=a.parse(o.sdp);for(const t of e){const{kind:e,rtpParameters:n}=t,r=e,i=s.media.find((e=>String(e.mid)===r));l.applyCodecParameters({offerRtpParameters:n,answerMediaObject:i})}o={type:"answer",sdp:a.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:s}),m.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),await this._pc.setLocalDescription(o);for(const t of e){const{kind:e,trackId:i,rtpParameters:o}=t,a=i,s=e,c=r.get(i),u=this._pc.getRemoteStreams().find((e=>e.id===c)).getTrackById(a);if(!u)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(a,{mid:s,rtpParameters:o}),n.push({localId:a,track:u})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){m.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:n}=this._mapRecvLocalIdInfo.get(t)||{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:n})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();m.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new c.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:c,protocol:n};m.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};m.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}m.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=l.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.ReactNative=v},3433:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ReactNativeUnifiedPlan=void 0;const a=o(n(766)),s=n(8562),c=o(n(3347)),u=o(n(5280)),d=o(n(2267)),l=o(n(9072)),p=o(n(8954)),h=n(9316),f=n(7910),m=n(2770),g=new s.Logger("ReactNativeUnifiedPlan"),v={OS:1024,MIS:1024};class y extends h.HandlerInterface{static createFactory(){return()=>new y}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNativeUnifiedPlan"}close(){if(g.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){g.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const n=a.parse(t.sdp),r=d.extractRtpCapabilities({sdpObject:n});return p.addNackSuppportForOpus(r),r}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return g.debug("getNativeSctpCapabilities()"),{numStreams:v}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:d}){g.debug("run()"),this._direction=e,this._remoteSdp=new f.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i}),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",d),video:u.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:u.getSendingRemoteRtpParameters("audio",d),video:u.getSendingRemoteRtpParameters("video",d)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(g.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){g.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(g.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});g.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();g.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),g.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const o=c.clone(this._sendingRtpParametersByKind[e.kind],{});o.codecs=u.reduceCodecs(o.codecs,r);const s=c.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});s.codecs=u.reduceCodecs(s.codecs,r);const p=this._remoteSdp.getNextMediaSectionIdx(),h=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let f,v=await this._pc.createOffer(),y=a.parse(v.sdp);this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:y});let b=!1;const w=(0,m.parse)((t||[{}])[0].scalabilityMode);t&&1===t.length&&w.spatialLayers>1&&"video/vp9"===o.codecs[0].mimeType.toLowerCase()&&(g.debug("send() | enabling legacy simulcast for VP9 SVC"),b=!0,y=a.parse(v.sdp),f=y.media[p.idx],l.addLegacySimulcast({offerMediaObject:f,numStreams:w.spatialLayers}),v={type:"offer",sdp:a.write(y)}),g.debug("send() | calling pc.setLocalDescription() [offer:%o]",v),await this._pc.setLocalDescription(v);const x=h.mid;if(o.mid=x,y=a.parse(this._pc.localDescription.sdp),f=y.media[p.idx],o.rtcp.cname=d.getCname({offerMediaObject:f}),t)if(1===t.length){let e=l.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),b&&(e=[e[0]]),o.encodings=e}else o.encodings=t;else o.encodings=l.getRtpEncodings({offerMediaObject:f});if(o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${w.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,reuseMid:p.reuseMid,offerRtpParameters:o,answerRtpParameters:s,codecOptions:n,extmapAllowMixed:!0});const _={type:"answer",sdp:this._remoteSdp.getSdp()};return g.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(x,h),{localId:x,rtpParameters:o,rtpSender:h.sender}}async stopSending(e){this.assertSendDirection(),g.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const n=await this._pc.createOffer();g.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertSendDirection(),g.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const n=await this._pc.createOffer();g.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async resumeSending(e){this.assertSendDirection(),g.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const n=await this._pc.createOffer();g.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async replaceTrack(e,t){this.assertSendDirection(),t?g.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):g.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),g.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),g.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:i};g.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%v.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),g.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:o}=t;g.debug("receive() [trackId:%s, kind:%s]",e,n);const a=i.mid||String(this._mapMidTransceiver.size);r.set(e,a),this._remoteSdp.receive({mid:a,kind:n,offerRtpParameters:i,streamId:o||i.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let o=await this._pc.createAnswer();const s=a.parse(o.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));d.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}o={type:"answer",sdp:a.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:s}),g.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),await this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,i=r.get(e),o=this._pc.getTransceivers().find((e=>e.mid===i));if(!o)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,o),n.push({localId:i,track:o.receiver.track,rtpReceiver:o.receiver})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c,protocol:n};g.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=d.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.ReactNativeUnifiedPlan=y},2205:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Safari11=void 0;const a=o(n(766)),s=n(8562),c=o(n(3347)),u=o(n(5280)),d=o(n(2267)),l=o(n(9875)),p=n(9316),h=n(7910),f=new s.Logger("Safari11"),m={OS:1024,MIS:1024};class g extends p.HandlerInterface{static createFactory(){return()=>new g}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari11"}close(){if(f.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){f.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const n=a.parse(t.sdp);return d.extractRtpCapabilities({sdpObject:n})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return f.debug("getNativeSctpCapabilities()"),{numStreams:m}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:d}){f.debug("run()"),this._direction=e,this._remoteSdp=new h.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",d),video:u.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:u.getSendingRemoteRtpParameters("audio",d),video:u.getSendingRemoteRtpParameters("video",d)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(f.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){f.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(f.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});f.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();f.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),f.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),r&&f.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let o,s=await this._pc.createOffer(),p=a.parse(s.sdp);const h=c.clone(this._sendingRtpParametersByKind[e.kind],{});h.codecs=u.reduceCodecs(h.codecs);const m=c.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});if(m.codecs=u.reduceCodecs(m.codecs),this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:p}),"video"===e.kind&&t&&t.length>1&&(f.debug("send() | enabling simulcast"),p=a.parse(s.sdp),o=p.media.find((e=>"video"===e.type)),l.addLegacySimulcast({offerMediaObject:o,track:e,numStreams:t.length}),s={type:"offer",sdp:a.write(p)}),f.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),p=a.parse(this._pc.localDescription.sdp),o=p.media.find((t=>t.type===e.kind)),h.rtcp.cname=d.getCname({offerMediaObject:o}),h.encodings=l.getRtpEncodings({offerMediaObject:o,track:e}),t)for(let e=0;e<h.encodings.length;++e)t[e]&&Object.assign(h.encodings[e],t[e]);if(h.encodings.length>1&&"video/vp8"===h.codecs[0].mimeType.toLowerCase())for(const e of h.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:o,offerRtpParameters:h,answerRtpParameters:m,codecOptions:n});const g={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g);const v=String(this._nextSendLocalId);this._nextSendLocalId++;const y=this._pc.getSenders().find((t=>t.track===e));return this._mapSendLocalIdRtpSender.set(v,y),{localId:v,rtpParameters:h,rtpSender:y}}async stopSending(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const n=await this._pc.createOffer();f.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n);try{await this._pc.setLocalDescription(n)}catch(e){if(0===this._sendStream.getTracks().length)return void f.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const r={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?f.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):f.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapSendLocalIdRtpSender.get(e);if(!n)throw new Error("associated RTCRtpSender not found");const r=n.track;await n.replaceTrack(t),r&&this._sendStream.removeTrack(r),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),f.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapSendLocalIdRtpSender.get(e);if(!n)throw new Error("associated RTCRtpSender not found");const r=n.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.setParameters(r)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),f.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapSendLocalIdRtpSender.get(e);if(!n)throw new Error("associated RTCRtpSender not found");const r=n.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.setParameters(r)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:i};f.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%m.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),f.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};f.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[];for(const t of e){const{trackId:e,kind:n,rtpParameters:r,streamId:i}=t;f.debug("receive() [trackId:%s, kind:%s]",e,n);const o=n;this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:r,streamId:i||r.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const o=a.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:n}=t,r=e,i=o.media.find((e=>String(e.mid)===r));d.applyCodecParameters({offerRtpParameters:n,answerMediaObject:i})}i={type:"answer",sdp:a.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:o}),f.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const t of e){const{kind:e,trackId:r,rtpParameters:i}=t,o=e,a=r,s=this._pc.getReceivers().find((e=>e.track&&e.track.id===a));if(!s)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(a,{mid:o,rtpParameters:i,rtpReceiver:s}),n.push({localId:a,track:s.track,rtpReceiver:s})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){f.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:n}=this._mapRecvLocalIdInfo.get(t)||{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:n})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();f.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)||{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async pauseReceiving(e){}async resumeReceiving(e){}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c,protocol:n};f.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};f.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}f.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=d.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Safari11=g},9862:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Safari12=void 0;const a=o(n(766)),s=n(8562),c=o(n(3347)),u=o(n(5280)),d=o(n(2267)),l=o(n(9072)),p=o(n(8954)),h=n(9316),f=n(7910),m=n(2770),g=new s.Logger("Safari12"),v={OS:1024,MIS:1024};class y extends h.HandlerInterface{static createFactory(){return()=>new y}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari12"}close(){if(g.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){g.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const n=a.parse(t.sdp),r=d.extractRtpCapabilities({sdpObject:n});return p.addNackSuppportForOpus(r),r}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return g.debug("getNativeSctpCapabilities()"),{numStreams:v}}run({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:s,proprietaryConstraints:c,extendedRtpCapabilities:d}){g.debug("run()"),this._direction=e,this._remoteSdp=new f.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:r,sctpParameters:i}),this._sendingRtpParametersByKind={audio:u.getSendingRtpParameters("audio",d),video:u.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:u.getSendingRemoteRtpParameters("audio",d),video:u.getSendingRemoteRtpParameters("video",d)},r.role&&"auto"!==r.role&&(this._forcedLocalDtlsRole="server"===r.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o||[],iceTransportPolicy:a||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...s},c),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",(()=>{this.emit("@connectionstatechange",this._pc.connectionState)})):this._pc.addEventListener("iceconnectionstatechange",(()=>{switch(g.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){g.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(g.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});g.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();g.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:n,codec:r}){var i;this.assertSendDirection(),g.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const o=c.clone(this._sendingRtpParametersByKind[e.kind],{});o.codecs=u.reduceCodecs(o.codecs,r);const s=c.clone(this._sendingRemoteRtpParametersByKind[e.kind],{});s.codecs=u.reduceCodecs(s.codecs,r);const p=this._remoteSdp.getNextMediaSectionIdx(),h=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let f,v=await this._pc.createOffer(),y=a.parse(v.sdp);this._transportReady||await this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:y});const b=(0,m.parse)((t||[{}])[0].scalabilityMode);t&&t.length>1&&(g.debug("send() | enabling legacy simulcast"),y=a.parse(v.sdp),f=y.media[p.idx],l.addLegacySimulcast({offerMediaObject:f,numStreams:t.length}),v={type:"offer",sdp:a.write(y)}),g.debug("send() | calling pc.setLocalDescription() [offer:%o]",v),await this._pc.setLocalDescription(v);const w=h.mid;if(o.mid=w,y=a.parse(this._pc.localDescription.sdp),f=y.media[p.idx],o.rtcp.cname=d.getCname({offerMediaObject:f}),o.encodings=l.getRtpEncodings({offerMediaObject:f}),t)for(let e=0;e<o.encodings.length;++e)t[e]&&Object.assign(o.encodings[e],t[e]);if(o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${b.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,reuseMid:p.reuseMid,offerRtpParameters:o,answerRtpParameters:s,codecOptions:n});const x={type:"answer",sdp:this._remoteSdp.getSdp()};return g.debug("send() | calling pc.setRemoteDescription() [answer:%o]",x),await this._pc.setRemoteDescription(x),this._mapMidTransceiver.set(w,h),{localId:w,rtpParameters:o,rtpSender:h.sender}}async stopSending(e){this.assertSendDirection(),g.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const n=await this._pc.createOffer();g.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertSendDirection(),g.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const n=await this._pc.createOffer();g.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async resumeSending(e){this.assertSendDirection(),g.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const n=await this._pc.createOffer();g.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}async replaceTrack(e,t){this.assertSendDirection(),t?g.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):g.debug("replaceTrack() [localId:%s, no track]",e);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),g.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{e.active=n<=t})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),g.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach(((e,n)=>{r.encodings[n]={...e,...t}})),await n.sender.setParameters(r),this._remoteSdp.muxMediaSectionSimulcast(e,r.encodings);const i=await this._pc.createOffer();g.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const o={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:r,protocol:i}){var o;this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:i};g.debug("sendDataChannel() [options:%o]",s);const c=this._pc.createDataChannel(r,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%v.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=a.parse(e.sdp),n=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:null!==(o=this._forcedLocalDtlsRole)&&void 0!==o?o:"client",localSdpObject:t}),g.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:n});const r={type:"answer",sdp:this._remoteSdp.getSdp()};g.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r),this._hasDataChannelMediaSection=!0}return{dataChannel:c,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){var t;this.assertRecvDirection();const n=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:o}=t;g.debug("receive() [trackId:%s, kind:%s]",e,n);const a=i.mid||String(this._mapMidTransceiver.size);r.set(e,a),this._remoteSdp.receive({mid:a,kind:n,offerRtpParameters:i,streamId:o||i.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let o=await this._pc.createAnswer();const s=a.parse(o.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));d.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}o={type:"answer",sdp:a.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:null!==(t=this._forcedLocalDtlsRole)&&void 0!==t?t:"client",localSdpObject:s}),g.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),await this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,i=r.get(e),o=this._pc.getTransceivers().find((e=>e.mid===i));if(!o)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,o),n.push({localId:i,track:o.receiver.track,rtpReceiver:o.receiver})}return n}async stopReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertRecvDirection();for(const t of e){g.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const n=await this._pc.createAnswer();g.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){var r;this.assertRecvDirection();const{streamId:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c}=e,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:s,maxRetransmits:c,protocol:n};g.debug("receiveDataChannel() [options:%o]",u);const d=this._pc.createDataChannel(t,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=a.parse(t.sdp);await this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:e})}g.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=a.parse(this._pc.localDescription.sdp));const n=d.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise(((e,t)=>{this.safeEmit("@connect",{dtlsParameters:n},e,t)})),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}t.Safari12=y},3635:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.mangleRtpParameters=t.getCapabilities=void 0;const a=o(n(3347));t.getCapabilities=function(){const e=RTCRtpReceiver.getCapabilities(),t=a.clone(e,{});for(const e of t.codecs){if(e.channels=e.numChannels,delete e.numChannels,e.mimeType=e.mimeType||`${e.kind}/${e.name}`,e.parameters){const t=e.parameters;t.apt&&(t.apt=Number(t.apt)),t["packetization-mode"]&&(t["packetization-mode"]=Number(t["packetization-mode"]))}for(const t of e.rtcpFeedback||[])t.parameter||(t.parameter="")}return t},t.mangleRtpParameters=function(e){const t=a.clone(e,{});t.mid&&(t.muxId=t.mid,delete t.mid);for(const e of t.codecs)e.channels&&(e.numChannels=e.channels,delete e.channels),e.mimeType&&!e.name&&(e.name=e.mimeType.split("/")[1]),delete e.mimeType;return t}},8954:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addNackSuppportForOpus=void 0,t.addNackSuppportForOpus=function(e){var t;for(const n of e.codecs||[])"audio/opus"!==n.mimeType.toLowerCase()&&"audio/multiopus"!==n.mimeType.toLowerCase()||(null===(t=n.rtcpFeedback)||void 0===t?void 0:t.some((e=>"nack"===e.type&&!e.parameter)))||(n.rtcpFeedback||(n.rtcpFeedback=[]),n.rtcpFeedback.push({type:"nack"}))}},6698:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.OfferMediaSection=t.AnswerMediaSection=t.MediaSection=void 0;const a=o(n(766)),s=o(n(3347));class c{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,planB:r=!1}){if(this._mediaObject={},this._planB=r,e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={component:1};t.foundation=e.foundation,t.ip=e.ip,t.port=e.port,t.priority=e.priority,t.transport=e.protocol,t.type=e.type,e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}n&&this.setDtlsRole(n.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause(),delete this._mediaObject.ext,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}close(){this.disable(),this._mediaObject.port=0}}function u(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}t.MediaSection=c,t.AnswerMediaSection=class extends c{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:r,plainRtpParameters:i,planB:o=!1,offerMediaObject:a,offerRtpParameters:c,answerRtpParameters:d,codecOptions:l,extmapAllowMixed:p=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:n,planB:o}),this._mediaObject.mid=String(a.mid),this._mediaObject.type=a.type,this._mediaObject.protocol=a.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),a.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of d.codecs){const t={payload:e.payloadType,codec:u(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const n=s.clone(e.parameters,{});let r=s.clone(e.rtcpFeedback,[]);if(l){const{opusStereo:t,opusFec:i,opusDtx:o,opusMaxPlaybackRate:a,opusMaxAverageBitrate:s,opusPtime:u,opusNack:d,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=l,m=c.codecs.find((t=>t.payloadType===e.payloadType));switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,n.stereo=t?1:0),void 0!==i&&(m.parameters.useinbandfec=i?1:0,n.useinbandfec=i?1:0),void 0!==o&&(m.parameters.usedtx=o?1:0,n.usedtx=o?1:0),void 0!==a&&(n.maxplaybackrate=a),void 0!==s&&(n.maxaveragebitrate=s),void 0!==u&&(m.parameters.ptime=u,n.ptime=u),d||(m.rtcpFeedback=m.rtcpFeedback.filter((e=>"nack"!==e.type||e.parameter)),r=r.filter((e=>"nack"!==e.type||e.parameter)));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":void 0!==p&&(n["x-google-start-bitrate"]=p),void 0!==h&&(n["x-google-max-bitrate"]=h),void 0!==f&&(n["x-google-min-bitrate"]=f)}}const i={payload:e.payloadType,config:""};for(const e of Object.keys(n))i.config&&(i.config+=";"),i.config+=`${e}=${n[e]}`;i.config&&this._mediaObject.fmtp.push(i);for(const t of r)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=d.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of d.headerExtensions)(a.ext||[]).some((t=>t.uri===e.uri))&&this._mediaObject.ext.push({uri:e.uri,value:e.id});if(p&&"extmap-allow-mixed"===a.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),a.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:a.simulcast.list1},this._mediaObject.rids=[];for(const e of a.rids||[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(a.simulcast_03){this._mediaObject.simulcast_03={value:a.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of a.rids||[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize",this._planB&&"video"===this._mediaObject.type&&(this._mediaObject.xGoogleFlag="conference");break;case"application":"number"==typeof a.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=r.port,this._mediaObject.maxMessageSize=r.maxMessageSize):a.sctpmap&&(this._mediaObject.payloads=r.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:r.port,maxMessageSize:r.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){var t;if(!this._mediaObject.simulcast||!this._mediaObject.simulcast.list1)return;const n={};for(const t of e)t.rid&&(n[t.rid]=t);const r=this._mediaObject.simulcast.list1,i=a.parseSimulcastStreamList(r);for(const e of i)for(const r of e)r.paused=!(null===(t=n[r.scid])||void 0===t?void 0:t.active);this._mediaObject.simulcast.list1=i.map((e=>e.map((e=>`${e.paused?"~":""}${e.scid}`)).join(","))).join(";")}},t.OfferMediaSection=class extends c{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:r,plainRtpParameters:i,planB:o=!1,mid:a,kind:s,offerRtpParameters:c,streamId:d,trackId:l,oldDataChannelSpec:p=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:n,planB:o}),this._mediaObject.mid=String(a),this._mediaObject.type=s,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=r?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),s){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._planB||(this._mediaObject.msid=`${d||"-"} ${l}`);for(const e of c.codecs){const t={payload:e.payloadType,codec:u(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const n={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters))n.config&&(n.config+=";"),n.config+=`${t}=${e.parameters[t]}`;n.config&&this._mediaObject.fmtp.push(n);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map((e=>e.payloadType)).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=c.encodings[0],t=e.ssrc,n=e.rtx&&e.rtx.ssrc?e.rtx.ssrc:void 0;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],c.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:t,attribute:"msid",value:`${d||"-"} ${l}`}),n&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:n,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:n,attribute:"msid",value:`${d||"-"} ${l}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${n}`}));break}case"application":p?(this._mediaObject.payloads=r.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:r.port,maxMessageSize:r.maxMessageSize}):(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=r.port,this._mediaObject.maxMessageSize=r.maxMessageSize)}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}planBReceive({offerRtpParameters:e,streamId:t,trackId:n}){const r=e.encodings[0],i=r.ssrc,o=r.rtx&&r.rtx.ssrc?r.rtx.ssrc:void 0,a=this._mediaObject.payloads.split(" ");for(const t of e.codecs){if(a.includes(String(t.payloadType)))continue;const e={payload:t.payloadType,codec:u(t),rate:t.clockRate};t.channels>1&&(e.encoding=t.channels),this._mediaObject.rtp.push(e);const n={payload:t.payloadType,config:""};for(const e of Object.keys(t.parameters))n.config&&(n.config+=";"),n.config+=`${e}=${t.parameters[e]}`;n.config&&this._mediaObject.fmtp.push(n);for(const e of t.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:t.payloadType,type:e.type,subtype:e.parameter})}this._mediaObject.payloads+=` ${e.codecs.filter((e=>!this._mediaObject.payloads.includes(e.payloadType))).map((e=>e.payloadType)).join(" ")}`,this._mediaObject.payloads=this._mediaObject.payloads.trim(),e.rtcp.cname&&this._mediaObject.ssrcs.push({id:i,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:i,attribute:"msid",value:`${t||"-"} ${n}`}),o&&(e.rtcp.cname&&this._mediaObject.ssrcs.push({id:o,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:o,attribute:"msid",value:`${t||"-"} ${n}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${i} ${o}`}))}planBStopReceiving({offerRtpParameters:e}){const t=e.encodings[0],n=t.ssrc,r=t.rtx&&t.rtx.ssrc?t.rtx.ssrc:void 0;this._mediaObject.ssrcs=this._mediaObject.ssrcs.filter((e=>e.id!==n&&e.id!==r)),r&&(this._mediaObject.ssrcGroups=this._mediaObject.ssrcGroups.filter((e=>e.ssrcs!==`${n} ${r}`)))}}},7910:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteSdp=void 0;const a=o(n(766)),s=n(8562),c=n(6698),u=new s.Logger("RemoteSdp");t.RemoteSdp=class{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:r,plainRtpParameters:i,planB:o=!1}){if(this._mediaSections=[],this._midToIndex=new Map,this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=n,this._sctpParameters=r,this._plainRtpParameters=i,this._planB=o,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:1e4,sessionVersion:0,username:"mediasoup-client"},name:"-",timing:{start:0,stop:0},media:[]},e&&e.iceLite&&(this._sdpObject.icelite="ice-lite"),n){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:n.fingerprints[e-1].algorithm,hash:n.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){u.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){u.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:n,answerRtpParameters:r,codecOptions:i,extmapAllowMixed:o=!1}){const a=new c.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,offerMediaObject:e,offerRtpParameters:n,answerRtpParameters:r,codecOptions:i,extmapAllowMixed:o});t?this._replaceMediaSection(a,t):this._midToIndex.has(a.mid)?this._replaceMediaSection(a):this._addMediaSection(a)}receive({mid:e,kind:t,offerRtpParameters:n,streamId:r,trackId:i}){const o=this._midToIndex.get(e);let a;if(void 0!==o&&(a=this._mediaSections[o]),a)a.planBReceive({offerRtpParameters:n,streamId:r,trackId:i}),this._replaceMediaSection(a);else{a=new c.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,mid:e,kind:t,offerRtpParameters:n,streamId:r,trackId:i});const o=this._mediaSections.find((e=>e.closed));o?this._replaceMediaSection(a,o.mid):this._addMediaSection(a)}}pauseMediaSection(e){this._findMediaSection(e).pause()}resumeSendingMediaSection(e){this._findMediaSection(e).resume()}resumeReceivingMediaSection(e){this._findMediaSection(e).resume()}disableMediaSection(e){this._findMediaSection(e).disable()}closeMediaSection(e){const t=this._findMediaSection(e);return e===this._firstMid?(u.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this._regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){const n=this._findMediaSection(e);n.muxSimulcastStreams(t),this._replaceMediaSection(n)}planBStopReceiving({mid:e,offerRtpParameters:t}){const n=this._findMediaSection(e);n.planBStopReceiving({offerRtpParameters:t}),this._replaceMediaSection(n)}sendSctpAssociation({offerMediaObject:e}){const t=new c.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this._addMediaSection(t)}receiveSctpAssociation({oldDataChannelSpec:e=!1}={}){const t=new c.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application",oldDataChannelSpec:e});this._addMediaSection(t)}getSdp(){return this._sdpObject.origin.sessionVersion++,a.write(this._sdpObject)}_addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this._regenerateBundleMids()}_replaceMediaSection(e,t){if("string"==typeof t){const n=this._midToIndex.get(t);if(void 0===n)throw new Error(`no media section found for reuseMid '${t}'`);const r=this._mediaSections[n];this._mediaSections[n]=e,this._midToIndex.delete(r.mid),this._midToIndex.set(e.mid,n),this._sdpObject.media[n]=e.getObject(),this._regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}_findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}_regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter((e=>!e.closed)).map((e=>e.mid)).join(" "))}}},2267:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.applyCodecParameters=t.getCname=t.extractDtlsParameters=t.extractRtpCapabilities=void 0;const a=o(n(766));t.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,n=[];let r=!1,i=!1;for(const o of e.media){const e=o.type;switch(e){case"audio":if(r)continue;r=!0;break;case"video":if(i)continue;i=!0;break;default:continue}for(const n of o.rtp){const r={kind:e,mimeType:`${e}/${n.codec}`,preferredPayloadType:n.payload,clockRate:n.rate,channels:n.encoding,parameters:{},rtcpFeedback:[]};t.set(r.preferredPayloadType,r)}for(const e of o.fmtp||[]){const n=a.parseParams(e.config),r=t.get(e.payload);r&&(n&&n.hasOwnProperty("profile-level-id")&&(n["profile-level-id"]=String(n["profile-level-id"])),r.parameters=n)}for(const n of o.rtcpFb||[]){const r={type:n.type,parameter:n.subtype};if(r.parameter||delete r.parameter,"*"!==n.payload){const e=t.get(n.payload);if(!e)continue;e.rtcpFeedback.push(r)}else for(const n of t.values())n.kind!==e||/.+\/rtx$/i.test(n.mimeType)||n.rtcpFeedback.push(r)}for(const t of o.ext||[]){if(t["encrypt-uri"])continue;const r={kind:e,uri:t.uri,preferredId:t.value};n.push(r)}}return{codecs:Array.from(t.values()),headerExtensions:n}},t.extractDtlsParameters=function({sdpObject:e}){const t=(e.media||[]).find((e=>e.iceUfrag&&0!==e.port));if(!t)throw new Error("no active media section found");const n=t.fingerprint||e.fingerprint;let r;switch(t.setup){case"active":r="client";break;case"passive":r="server";break;case"actpass":r="auto"}return{role:r,fingerprints:[{algorithm:n.type,value:n.hash}]}},t.getCname=function({offerMediaObject:e}){const t=(e.ssrcs||[]).find((e=>"cname"===e.attribute));return t?t.value:""},t.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const n of e.codecs){const e=n.mimeType.toLowerCase();if("audio/opus"!==e)continue;if(!(t.rtp||[]).find((e=>e.payload===n.payloadType)))continue;t.fmtp=t.fmtp||[];let r=t.fmtp.find((e=>e.payload===n.payloadType));r||(r={payload:n.payloadType,config:""},t.fmtp.push(r));const i=a.parseParams(r.config);switch(e){case"audio/opus":{const e=n.parameters["sprop-stereo"];void 0!==e&&(i.stereo=e?1:0);break}}r.config="";for(const e of Object.keys(i))r.config&&(r.config+=";"),r.config+=`${e}=${i[e]}`}}},9875:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addLegacySimulcast=t.getRtpEncodings=void 0,t.getRtpEncodings=function({offerMediaObject:e,track:t}){let n;const r=new Set;for(const i of e.ssrcs||[])if("msid"===i.attribute&&i.value.split(" ")[1]===t.id){const e=i.id;r.add(e),n||(n=e)}if(0===r.size)throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);const i=new Map;for(const t of e.ssrcGroups||[]){if("FID"!==t.semantics)continue;let[e,n]=t.ssrcs.split(/\s+/);e=Number(e),n=Number(n),r.has(e)&&(r.delete(e),r.delete(n),i.set(e,n))}for(const e of r)i.set(e,null);const o=[];for(const[e,t]of i){const n={ssrc:e};t&&(n.rtx={ssrc:t}),o.push(n)}return o},t.addLegacySimulcast=function({offerMediaObject:e,track:t,numStreams:n}){if(n<=1)throw new TypeError("numStreams must be greater than 1");let r,i,o;if(!(e.ssrcs||[]).find((e=>"msid"===e.attribute&&e.value.split(" ")[1]===t.id&&(r=e.id,o=e.value.split(" ")[0],!0))))throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);(e.ssrcGroups||[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===r&&(i=Number(t[1]),!0)}));const a=e.ssrcs.find((e=>"cname"===e.attribute&&e.id===r));if(!a)throw new Error(`a=ssrc line with cname information not found [track.id:${t.id}]`);const s=a.value,c=[],u=[];for(let e=0;e<n;++e)c.push(r+e),i&&u.push(i+e);e.ssrcGroups=e.ssrcGroups||[],e.ssrcs=e.ssrcs||[],e.ssrcGroups.push({semantics:"SIM",ssrcs:c.join(" ")});for(let n=0;n<c.length;++n){const r=c[n];e.ssrcs.push({id:r,attribute:"cname",value:s}),e.ssrcs.push({id:r,attribute:"msid",value:`${o} ${t.id}`})}for(let n=0;n<u.length;++n){const r=c[n],i=u[n];e.ssrcs.push({id:i,attribute:"cname",value:s}),e.ssrcs.push({id:i,attribute:"msid",value:`${o} ${t.id}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${i}`})}}},9072:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addLegacySimulcast=t.getRtpEncodings=void 0,t.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const n of e.ssrcs||[]){const e=n.id;t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const n=new Map;for(const r of e.ssrcGroups||[]){if("FID"!==r.semantics)continue;let[e,i]=r.ssrcs.split(/\s+/);e=Number(e),i=Number(i),t.has(e)&&(t.delete(e),t.delete(i),n.set(e,i))}for(const e of t)n.set(e,null);const r=[];for(const[e,t]of n){const n={ssrc:e};t&&(n.rtx={ssrc:t}),r.push(n)}return r},t.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const n=(e.ssrcs||[]).find((e=>"msid"===e.attribute));if(!n)throw new Error("a=ssrc line with msid information not found");const[r,i]=n.value.split(" "),o=n.id;let a;(e.ssrcGroups||[]).some((e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===o&&(a=Number(t[1]),!0)}));const s=e.ssrcs.find((e=>"cname"===e.attribute));if(!s)throw new Error("a=ssrc line with cname information not found");const c=s.value,u=[],d=[];for(let e=0;e<t;++e)u.push(o+e),a&&d.push(a+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:u.join(" ")});for(let t=0;t<u.length;++t){const n=u[t];e.ssrcs.push({id:n,attribute:"cname",value:c}),e.ssrcs.push({id:n,attribute:"msid",value:`${r} ${i}`})}for(let t=0;t<d.length;++t){const n=u[t],o=d[t];e.ssrcs.push({id:o,attribute:"cname",value:c}),e.ssrcs.push({id:o,attribute:"msid",value:`${r} ${i}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${n} ${o}`})}}},960:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.debug=t.parseScalabilityMode=t.detectDevice=t.Device=t.version=t.types=void 0;const s=a(n(1227));t.debug=s.default;const c=n(3120);Object.defineProperty(t,"Device",{enumerable:!0,get:function(){return c.Device}}),Object.defineProperty(t,"detectDevice",{enumerable:!0,get:function(){return c.detectDevice}});const u=o(n(53));t.types=u,t.version="3.6.82";var d=n(2770);Object.defineProperty(t,"parseScalabilityMode",{enumerable:!0,get:function(){return d.parse}})},5280:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.canReceive=t.canSend=t.generateProbatorRtpParameters=t.reduceCodecs=t.getSendingRemoteRtpParameters=t.getSendingRtpParameters=t.getRecvRtpCapabilities=t.getExtendedRtpCapabilities=t.validateSctpStreamParameters=t.validateSctpParameters=t.validateNumSctpStreams=t.validateSctpCapabilities=t.validateRtcpParameters=t.validateRtpEncodingParameters=t.validateRtpHeaderExtensionParameters=t.validateRtpCodecParameters=t.validateRtpParameters=t.validateRtpHeaderExtension=t.validateRtcpFeedback=t.validateRtpCodecCapability=t.validateRtpCapabilities=void 0;const a=o(n(7855)),s=o(n(3347));function c(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const n=t.exec(e.mimeType);if(!n)throw new TypeError("invalid codec.mimeType");if(e.kind=n[1].toLowerCase(),e.preferredPayloadType&&"number"!=typeof e.preferredPayloadType)throw new TypeError("invalid codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let n=e.parameters[t];if(void 0===n&&(e.parameters[t]="",n=""),"string"!=typeof n&&"number"!=typeof n)throw new TypeError(`invalid codec parameter [key:${t}s, value:${n}]`);if("apt"===t&&"number"!=typeof n)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)u(t)}function u(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function d(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function l(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)p(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)h(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)f(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),m(e.rtcp)}function p(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const n=t.exec(e.mimeType);if(!n)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===n[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let n=e.parameters[t];if(void 0===n&&(e.parameters[t]="",n=""),"string"!=typeof n&&"number"!=typeof n)throw new TypeError(`invalid codec parameter [key:${t}s, value:${n}]`);if("apt"===t&&"number"!=typeof n)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)u(t)}function h(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let n=e.parameters[t];if(void 0===n&&(e.parameters[t]="",n=""),"string"!=typeof n&&"number"!=typeof n)throw new TypeError("invalid header extension parameter")}}function f(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function m(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}function g(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}function v(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function y(e,t,{strict:n=!1,modify:r=!1}={}){const i=e.mimeType.toLowerCase();if(i!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(i){case"video/h264":if(n){if((e.parameters["packetization-mode"]||0)!==(t.parameters["packetization-mode"]||0))return!1;if(!a.isSameProfile(e.parameters,t.parameters))return!1;let n;try{n=a.generateProfileLevelIdForAnswer(e.parameters,t.parameters)}catch(e){return!1}r&&(n?(e.parameters["profile-level-id"]=n,t.parameters["profile-level-id"]=n):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(n&&(e.parameters["profile-id"]||0)!==(t.parameters["profile-id"]||0))return!1}return!0}function b(e,t){const n=[];for(const r of e.rtcpFeedback||[]){const e=(t.rtcpFeedback||[]).find((e=>e.type===r.type&&(e.parameter===r.parameter||!e.parameter&&!r.parameter)));e&&n.push(e)}return n}t.validateRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)c(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)d(t)},t.validateRtpCodecCapability=c,t.validateRtcpFeedback=u,t.validateRtpHeaderExtension=d,t.validateRtpParameters=l,t.validateRtpCodecParameters=p,t.validateRtpHeaderExtensionParameters=h,t.validateRtpEncodingParameters=f,t.validateRtcpParameters=m,t.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");g(e.numStreams)},t.validateNumSctpStreams=g,t.validateSctpParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.port)throw new TypeError("missing params.port");if("number"!=typeof e.OS)throw new TypeError("missing params.OS");if("number"!=typeof e.MIS)throw new TypeError("missing params.MIS");if("number"!=typeof e.maxMessageSize)throw new TypeError("missing params.maxMessageSize")},t.validateSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;if("boolean"==typeof e.ordered?t=!0:e.ordered=!0,e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1),e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},t.getExtendedRtpCapabilities=function(e,t){const n={codecs:[],headerExtensions:[]};for(const r of t.codecs||[]){if(v(r))continue;const t=(e.codecs||[]).find((e=>y(e,r,{strict:!0,modify:!0})));if(!t)continue;const i={mimeType:t.mimeType,kind:t.kind,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:r.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters,remoteParameters:r.parameters,rtcpFeedback:b(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find((e=>v(e)&&e.parameters.apt===r.localPayloadType)),i=t.codecs.find((e=>v(e)&&e.parameters.apt===r.remotePayloadType));n&&i&&(r.localRtxPayloadType=n.preferredPayloadType,r.remoteRtxPayloadType=i.preferredPayloadType)}for(const r of t.headerExtensions){const t=e.headerExtensions.find((e=>{return n=r,!((t=e).kind&&n.kind&&t.kind!==n.kind||t.uri!==n.uri);var t,n}));if(!t)continue;const i={kind:r.kind,uri:r.uri,sendId:t.preferredId,recvId:r.preferredId,encrypt:t.preferredEncrypt,direction:"sendrecv"};switch(r.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}n.headerExtensions.push(i)}return n},t.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const n of e.codecs){const e={mimeType:n.mimeType,kind:n.kind,preferredPayloadType:n.remotePayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(t.codecs.push(e),!n.remoteRtxPayloadType)continue;const r={mimeType:`${n.kind}/rtx`,kind:n.kind,preferredPayloadType:n.remoteRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.remotePayloadType},rtcpFeedback:[]};t.codecs.push(r)}for(const n of e.headerExtensions){if("sendrecv"!==n.direction&&"recvonly"!==n.direction)continue;const e={kind:n.kind,uri:n.uri,preferredId:n.recvId,preferredEncrypt:n.encrypt,direction:n.direction};t.headerExtensions.push(e)}return t},t.getSendingRtpParameters=function(e,t){const n={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const r of t.codecs){if(r.kind!==e)continue;const t={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(n.codecs.push(t),r.localRtxPayloadType){const e={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};n.codecs.push(e)}}for(const r of t.headerExtensions){if(r.kind&&r.kind!==e||"sendrecv"!==r.direction&&"sendonly"!==r.direction)continue;const t={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};n.headerExtensions.push(t)}return n},t.getSendingRemoteRtpParameters=function(e,t){const n={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const r of t.codecs){if(r.kind!==e)continue;const t={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.remoteParameters,rtcpFeedback:r.rtcpFeedback};if(n.codecs.push(t),r.localRtxPayloadType){const e={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};n.codecs.push(e)}}for(const r of t.headerExtensions){if(r.kind&&r.kind!==e||"sendrecv"!==r.direction&&"sendonly"!==r.direction)continue;const t={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};n.headerExtensions.push(t)}if(n.headerExtensions.some((e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri)))for(const e of n.codecs)e.rtcpFeedback=(e.rtcpFeedback||[]).filter((e=>"goog-remb"!==e.type));else if(n.headerExtensions.some((e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri)))for(const e of n.codecs)e.rtcpFeedback=(e.rtcpFeedback||[]).filter((e=>"transport-cc"!==e.type));else for(const e of n.codecs)e.rtcpFeedback=(e.rtcpFeedback||[]).filter((e=>"transport-cc"!==e.type&&"goog-remb"!==e.type));return n},t.reduceCodecs=function(e,t){const n=[];if(t){for(let r=0;r<e.length;++r)if(y(e[r],t)){n.push(e[r]),v(e[r+1])&&n.push(e[r+1]);break}if(0===n.length)throw new TypeError("no matching codec found")}else n.push(e[0]),v(e[1])&&n.push(e[1]);return n},t.generateProbatorRtpParameters=function(e){l(e=s.clone(e,{}));const t={mid:"probator",codecs:[],headerExtensions:[],encodings:[{ssrc:1234}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=127,t.headerExtensions=e.headerExtensions,t},t.canSend=function(e,t){return t.codecs.some((t=>t.kind===e))},t.canReceive=function(e,t){if(l(e),0===e.codecs.length)return!1;const n=e.codecs[0];return t.codecs.some((e=>e.remotePayloadType===n.payloadType))}},2770:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parse=void 0;const n=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");t.parse=function(e){const t=n.exec(e||"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}}},53:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(n(3120),t),i(n(5202),t),i(n(6569),t),i(n(9514),t),i(n(5504),t),i(n(1623),t),i(n(4879),t),i(n(7669),t),i(n(9316),t),i(n(9992),t)},3347:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.generateRandomNumber=t.clone=void 0,t.clone=function(e,t){return void 0===e?t:JSON.parse(JSON.stringify(e))},t.generateRandomNumber=function(){return Math.round(1e7*Math.random())}},7824:e=>{var t=1e3,n=60*t,r=60*n,i=24*r;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}e.exports=function(e,a){a=a||{};var s,c,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return 6048e5*a;case"days":case"day":case"d":return a*i;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*n;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(s=e,(c=Math.abs(s))>=i?o(s,c,i,"day"):c>=r?o(s,c,r,"hour"):c>=n?o(s,c,n,"minute"):c>=t?o(s,c,t,"second"):s+" ms"):function(e){var o=Math.abs(e);return o>=i?Math.round(e/i)+"d":o>=r?Math.round(e/r)+"h":o>=n?Math.round(e/n)+"m":o>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},4375:(e,t,n)=>{let r;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:n.g):e=>(r||(r=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},6692:e=>{var t=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(t).forEach((function(e){t[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))},766:(e,t,n)=>{var r=n(962),i=n(5776);t.write=i,t.parse=r.parse,t.parseParams=r.parseParams,t.parseFmtpConfig=r.parseFmtpConfig,t.parsePayloads=r.parsePayloads,t.parseRemoteCandidates=r.parseRemoteCandidates,t.parseImageAttributes=r.parseImageAttributes,t.parseSimulcastStreamList=r.parseSimulcastStreamList},962:(e,t,n)=>{var r=function(e){return String(Number(e))===e?Number(e):e},i=function(e,t,n){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var o=e.push?{}:i?t[e.name]:t;!function(e,t,n,i){if(i&&!n)t[i]=r(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(t[n[o]]=r(e[o+1]))}(n.match(e.reg),o,e.names,e.name),e.push&&t[e.push].push(o)},o=n(6692),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(e){var t={},n=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach((function(e){var t=e[0],a=e.slice(2);"m"===t&&(n.push({rtp:[],fmtp:[]}),r=n[n.length-1]);for(var s=0;s<(o[t]||[]).length;s+=1){var c=o[t][s];if(c.reg.test(a))return i(c,r,a)}})),t.media=n,t};var s=function(e,t){var n=t.split(/=(.+)/,2);return 2===n.length?e[n[0]]=r(n[1]):1===n.length&&t.length>1&&(e[n[0]]=void 0),e};t.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(e){return e.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(e){for(var t=[],n=e.split(" ").map(r),i=0;i<n.length;i+=3)t.push({component:n[i],ip:n[i+1],port:n[i+2]});return t},t.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})}))},t.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var t,n=!1;return"~"!==e[0]?t=r(e):(t=r(e.substring(1,e.length)),n=!0),{scid:t,paused:n}}))}))}},5776:(e,t,n)=>{var r=n(6692),i=/%[sdv%]/g,o=function(e){var t=1,n=arguments,r=n.length;return e.replace(i,(function(e){if(t>=r)return e;var i=n[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},a=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var a=t.names[i];t.name?r.push(n[t.name][a]):r.push(n[t.names[i]])}else r.push(n[t.name]);return o.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c=["i","c","b","a"];e.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||s,i=t.innerOrder||c,o=[];return n.forEach((function(t){r[t].forEach((function(n){n.name in e&&null!=e[n.name]?o.push(a(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){o.push(a(t,n,e))}))}))})),e.media.forEach((function(e){o.push(a("m",r.m[0],e)),i.forEach((function(t){r[t].forEach((function(n){n.name in e&&null!=e[n.name]?o.push(a(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){o.push(a(t,n,e))}))}))}))})),o.join("\r\n")+"\r\n"}},278:(e,t,n)=>{const r=n(5714);e.exports=class{constructor(){this.smilePots=[],this.unhappy=!1}async init(e){return this.options=new r.TinyFaceDetectorOptions({inputSize:224,scoreThreshold:.5}),new Promise((async(t,n)=>{try{await r.nets.tinyFaceDetector.load(e.replace("wss","https")),await r.loadFaceExpressionModel(e.replace("wss","https")),t()}catch(e){n(e)}}))}async detect(e){const t={face:!1,smile:!1},n=await r.detectSingleFace(e,this.options).withFaceExpressions();return n?(t.face=!0,t.smile=this.smile(n.expressions),t):null}smile(e){if(this.smilePots.push(e.happy),e.happy<.7&&!this.unhappy&&(this.unhappy=!0),this.unhappy&&e.happy>.7&&this.smilePots.length>4){const e=this.smilePots.slice(-4);for(const t of e)if(t<.7)return!1;return!0}return!1}isFaceDetectionModelLoaded(){return!!r.nets.tinyFaceDetector.params}}},8901:(e,t,n)=>{const r=n(278);e.exports=class{constructor(){this.eventListeners=new Map,this.results=!1,this.detected={face:!1,smile:!1},this.reason=null,this.engine=new r,["started","timeout","face","smile"].forEach(function(e){this.eventListeners.set(e,[])}.bind(this))}async init(e,t){return this.videoElement=t,new Promise((async(t,n)=>{try{await this.engine.init(e),t()}catch(e){n(e)}}))}async start(){return new Promise((async(e,t)=>{if(!this.engine.isFaceDetectionModelLoaded())return t("failed to load the models.");try{await this.sleep(1e3),await this.detect("face"),this.event("face"),await this.sleep(2e3),await this.detect("smile"),this.event("smile"),e(!0)}catch(t){return e(!1)}}))}async detect(e,t,n=!0,r=!1){return this.detected[e]=!1,new Promise((async(i,o)=>{this.inter=setInterval((async()=>{this.results=await this.engine.detect(this.videoElement),this.results&&this.results[e]&&(this.detected[e]=!0,i(),clearInterval(this.inter))}),200),setTimeout((()=>{this.detected[e]||(clearInterval(this.inter),n?r?o(e):(this.event("timeout",e),this.detect(e,!0,!0).then((()=>i())).catch((e=>o(e)))):o(e))}),t)}))}sleep(e){return new Promise((t=>setTimeout(t,e)))}event(e,t={}){this.eventListeners.has(e)&&this.eventListeners.get(e).forEach((e=>e(t)))}onDetect(e,t){t&&this.eventListeners.get(e).push(t)}}},9142:(e,t,n)=>{const{EventEmitter:r}=n(7187),i=n(8901),o=n(779);e.exports=class{constructor(){this.main=new o,this.socket=void 0,this.observer=new r,this.media=new i,this.results={},this.detecting={face:!1,smile:!1,head_left:!1,head_right:!1},this.mode=null,this.options={}}async createSession(e,t={}){return this.options=t,new Promise(((n,r)=>{this.main.connect(e,t).then((async e=>{this.socket=e,this.main.createSession().then((e=>{n(e)})).catch(r),this.socket.on("detect",(e=>{this.results=this.formatResults(e)})),this.main.on("error",(e=>this.observer.emit("error",e))),this.socket.on("start",(()=>{this.observer.emit("opened",!0)})),this.socket.on("issue",(e=>this.observer.emit("error",e)))})).catch((e=>{if("Authentication"===e.message)return r({code:"E01",message:"Authentication"});r(e)}))}))}async process(e,t=8e3){return this.detecting[e]=!0,this.socket.emit("setDetect",!0),new Promise((n=>{const r=setInterval((async()=>{"1"===this.results[e]&&(this.detecting[e]=!1,n(!0),this.socket.emit("setDetect",!1),clearInterval(r))}));setTimeout((()=>{this.detecting[e]&&(this.socket.emit("setDetect",!1),this.detecting[e]=!1,clearInterval(r),n(!1))}),t)}))}async detect(e,t={},n=!1){return new Promise(((r,i)=>{this.process(e,t.timeout||8e3).then((async o=>{if(o)r();else{if(!n&&t.retry)return t.onRepeat&&t.onRepeat(),this.detect(e,t,!0).then(r).catch(i);i()}}))}))}async close(){return new Promise(((e,t)=>{this.main.close(!1).then((()=>e())).catch((e=>t(e)))}))}formatResults(e){return{face:e[0],smile:e[1],head_right:e[2],head_left:e[3]}}}},6284:(e,t,n)=>{const r=n(9142);e.exports=r},779:(e,t,n)=>{const r=n(960),{io:i}=n(7046);e.exports=class{constructor(){this.socket=null,this.producerTransport=[],this.device=null,this.producerId=null,this.producers=new Map,this.producerLabel=new Map,this.eventListeners=new Map,this.engineTransport={},this.mode=null,["started","opened","closed","error"].forEach(function(e){this.eventListeners.set(e,[])}.bind(this))}async connect(e,t={}){return t.videoElement&&(this.localVideoEl=t.videoElement),this.mediaConstraints={},t.mediaConstraints&&(this.mediaConstraints=t.mediaConstraints),new Promise((async(n,r)=>{t.transports=["websocket"],this.socket=i(e,{...t,query:{recordOnly:!1},reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:5}),this.socket.request=async(e,t={})=>new Promise(((n,r)=>{this.socket.emit(e,t,(e=>{e&&e.error?r(e.error):n(e)}))})),this.socket.on("connect",(async()=>{n(this.socket)})),this.socket.on("connect_error",(e=>{r(e),this.socket.disconnect()})),this.socket.on("error",(e=>{r(e),this.socket.disconnect()})),window.onbeforeunload=()=>{this.socket&&this.socket.disconnect()}}))}async createSession(){return new Promise(((e,t)=>{this.socket.request("createSession").then((async n=>{try{const t=await this.socket.request("getRouterRtpCapabilities"),r=await this.loadDevice(t.rtpCapabilities);this.device=r,await this.getUserMedia(t.mediaConstraints),this.event("opened"),await this.createAndProducer(),this.initSockets(),await this.socket.request("start"),e(n)}catch(e){t(e)}})).catch(t)}))}async createAndProducer(){const e=await this.createTransports();await this.produce(e);const t=await this.createTransports(!0);await this.produce(t)}async loadDevice(e){let t;const n=window.navigator.userAgent,i={};n.includes("IONBanking-WBC")?n.includes("iPhone")?i.handlerName="Safari12":i.handlerName="Chrome74":(n.includes("like Mac OS X")||n.includes("AppleWebKit")||n.includes("(KHTML, like Gecko)"))&&(i.handlerName="Safari12");try{t=new r.Device(i)}catch(e){throw new Error(e)}return await t.load({routerRtpCapabilities:e}),t}initSockets(){}async createTransports(e){const t=await this.socket.request("createWebRtcTransport",{forceTcp:!1,rtpCapabilities:this.device.rtpCapabilities,isSecond:e});if(t.error)throw this.handleError(t.error),new Error(t.error);const n=this.device.createSendTransport(t);return n.on("connect",(async({dtlsParameters:n},r,i)=>{this.socket.request("connectTransport",{dtlsParameters:n,transport_id:t.id,isSecond:e}).then(r).catch(i)})),n.on("produce",(async({kind:t,rtpParameters:r},i,o)=>{try{const{producer_id:o}=await this.socket.request("produce",{producerTransportId:n.id,kind:t,rtpParameters:r,isSecond:e});i({id:o})}catch(e){o(e)}})),n.on("connectionstatechange",(e=>{"failed"===e&&n.close()})),this.producerTransport.push(n),n}async initProducerTransport(e){return e}async produce(e,t){if(!this.device.canProduce("video")){const e="Cannot produce video.";throw this.handleError(e),new Error(e)}try{const t=this.stream.getVideoTracks()[0],n=await e.produce({track:t});this.producers.set(n.id,n),this.producerEvent(n)}catch(e){throw this.handleError(e),new Error(e)}}producerEvent(e){e.on("trackended",(()=>{this.closeProducer(e)})),e.on("transportclose",(()=>{this.producers.delete(e.id)})),e.on("close",(()=>{this.producers.delete(e.id)}))}async getUserMedia(e){return this.stream=await navigator.mediaDevices.getUserMedia({audio:!1,video:{...this.mediaConstraints.video,...e.video}}),this.localVideoEl.paused&&(this.localVideoEl.srcObject=this.stream),this.stream}closeProducer(e){this.socket.emit("producerClosed",{producerId:e.id}),this.producers.get(e.id).close(),this.producers.delete(e.id)}async close(e){return new Promise((async(e,t)=>{if(this._isOpen=!1,this.producerTransport)for(const e of this.producerTransport)e.close();try{await this.socket.request("complete",null),e(),this.socket&&(this.socket.off("disconnect"),this.socket.disconnect()),this.event("closed")}catch(e){console.error(e),t(e)}}))}event(e,t={}){this.eventListeners.has(e)&&this.eventListeners.get(e).forEach((e=>e(t)))}on(e,t){t&&this.eventListeners.get(e).push(t)}handleError(e){console.error(e),this.event("error",e)}}},4902:()=>{},522:()=>{},753:()=>{},8730:()=>{},8419:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.hasCORS=void 0;let n=!1;try{n="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}t.hasCORS=n},5754:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=void 0,t.encode=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t},t.decode=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}},5222:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parse=void 0;const n=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.parse=function(e){const t=e,i=e.indexOf("["),o=e.indexOf("]");-1!=i&&-1!=o&&(e=e.substring(0,i)+e.substring(i,o).replace(/:/g,";")+e.substring(o,e.length));let a=n.exec(e||""),s={},c=14;for(;c--;)s[r[c]]=a[c]||"";return-1!=i&&-1!=o&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,s.path),s.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,r){t&&(n[t]=r)})),n}(0,s.query),s}},8726:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.yeast=t.decode=t.encode=void 0;const n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),r={};let i,o=0,a=0;function s(e){let t="";do{t=n[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}for(t.encode=s,t.decode=function(e){let t=0;for(a=0;a<e.length;a++)t=64*t+r[e.charAt(a)];return t},t.yeast=function(){const e=s(+new Date);return e!==i?(o=0,i=e):e+"."+s(o++)};a<64;a++)r[n[a]]=a},6242:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.globalThisShim=void 0,t.globalThisShim="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},4679:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.nextTick=t.parse=t.installTimerFunctions=t.transports=t.Transport=t.protocol=t.Socket=void 0;const r=n(3481);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return r.Socket}}),t.protocol=r.Socket.protocol;var i=n(9870);Object.defineProperty(t,"Transport",{enumerable:!0,get:function(){return i.Transport}});var o=n(7385);Object.defineProperty(t,"transports",{enumerable:!0,get:function(){return o.transports}});var a=n(9622);Object.defineProperty(t,"installTimerFunctions",{enumerable:!0,get:function(){return a.installTimerFunctions}});var s=n(5222);Object.defineProperty(t,"parse",{enumerable:!0,get:function(){return s.parse}});var c=n(5552);Object.defineProperty(t,"nextTick",{enumerable:!0,get:function(){return c.nextTick}})},3481:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;const i=n(7385),o=n(9622),a=n(5754),s=n(5222),c=r(n(1227)),u=n(5260),d=n(1373),l=(0,c.default)("engine.io-client:socket");class p extends u.Emitter{constructor(e,t={}){super(),this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=(0,s.parse)(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=(0,s.parse)(t.host).host),(0,o.installTimerFunctions)(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=(0,a.decode)(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){l('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=d.protocol,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return l("options: %j",n),new i.transports[e](n)}open(){let e;if(this.opts.rememberUpgrade&&p.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return l("error while creating transport: %s",e),this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){l("setting transport %s",e.name),this.transport&&(l("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){l('probing transport "%s"',e);let t=this.createTransport(e),n=!1;p.priorWebsocketSuccess=!1;const r=()=>{n||(l('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(r=>{if(!n)if("pong"===r.type&&"probe"===r.data){if(l('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;p.priorWebsocketSuccess="websocket"===t.name,l('pausing current transport "%s"',this.transport.name),this.transport.pause((()=>{n||"closed"!==this.readyState&&(l("changing transport and sending upgrade packet"),u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{l('probe transport "%s" failed',e);const n=new Error("probe error");n.transport=t.name,this.emitReserved("upgradeError",n)}})))};function i(){n||(n=!0,u(),t.close(),t=null)}const o=n=>{const r=new Error("probe error: "+n);r.transport=t.name,i(),l('probe transport "%s" failed because of error: %s',e,n),this.emitReserved("upgradeError",r)};function a(){o("transport closed")}function s(){o("socket closed")}function c(e){t&&e.name!==t.name&&(l('"%s" works - aborting "%s"',e.name,t.name),i())}const u=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",a),this.off("close",s),this.off("upgrading",c)};t.once("open",r),t.once("error",o),t.once("close",a),this.once("close",s),this.once("upgrading",c),t.open()}onOpen(){if(l("socket open"),this.readyState="open",p.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){l("starting upgrade probes");let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(l('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}else l('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();l("flushing %d packets in socket",e.length),this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=(0,o.byteLength)(n)),t>0&&e>this.maxPayload)return l("only send %d out of %d packets",t,this.writeBuffer.length),this.writeBuffer.slice(0,t);e+=2}return l("payload size is %d (max: %d)",e,this.maxPayload),this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this.onClose("forced close"),l("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?n():e()})):this.upgrading?n():e()),this}onError(e){l("socket error %j",e),p.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(l('socket close with reason: "%s"',e),this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const r=e.length;for(;n<r;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}t.Socket=p,p.protocol=d.protocol},9870:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Transport=void 0;const i=n(1373),o=n(5260),a=n(9622),s=(0,r(n(1227)).default)("engine.io-client:transport");class c extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class u extends o.Emitter{constructor(e){super(),this.writable=!1,(0,a.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new c(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState?this.write(e):s("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,i.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}}t.Transport=u},7385:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.transports=void 0;const r=n(484),i=n(1308);t.transports={websocket:i.WS,polling:r.Polling}},484:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Request=t.Polling=void 0;const i=n(9870),o=r(n(1227)),a=n(8726),s=n(5754),c=n(1373),u=n(6666),d=n(5260),l=n(9622),p=n(6242),h=(0,o.default)("engine.io-client:polling");function f(){}const m=null!=new u.XHR({xdomain:!1}).responseType;class g extends i.Transport{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=m&&!t}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{h("paused"),this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(h("we are currently polling - waiting to pause"),e++,this.once("pollComplete",(function(){h("pre-pause polling complete"),--e||t()}))),this.writable||(h("we are currently writing - waiting to pause"),e++,this.once("drain",(function(){h("pre-pause writing complete"),--e||t()})))}else t()}poll(){h("polling"),this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){h("polling got data %s",e),(0,c.decodePayload)(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState?this.poll():h('ignoring poll - transport state "%s"',this.readyState))}doClose(){const e=()=>{h("writing close packet"),this.write([{type:"close"}])};"open"===this.readyState?(h("transport open - closing"),e()):(h("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,c.encodePayload)(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let n="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=(0,a.yeast)()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(n=":"+this.opts.port);const r=(0,s.encode)(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(r.length?"?"+r:"")}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new v(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){h("xhr poll");const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}t.Polling=g;class v extends d.Emitter{constructor(e,t){super(),(0,l.installTimerFunctions)(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=(0,l.pick)(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new u.XHR(e);try{h("xhr open %s: %s",this.method,this.uri),t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof t.status?t.status:0)}),0))},h("xhr data %s",this.data),t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=v.requestsCount++,v.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=f,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete v.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(t.Request=v,v.requestsCount=0,v.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",y);else if("function"==typeof addEventListener){const e="onpagehide"in p.globalThisShim?"pagehide":"unload";addEventListener(e,y,!1)}function y(){for(let e in v.requests)v.requests.hasOwnProperty(e)&&v.requests[e].abort()}},5552:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultBinaryType=t.usingBrowserWebSocket=t.WebSocket=t.nextTick=void 0;const r=n(6242);t.nextTick="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),t.WebSocket=r.globalThisShim.WebSocket||r.globalThisShim.MozWebSocket,t.usingBrowserWebSocket=!0,t.defaultBinaryType="arraybuffer"},1308:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WS=void 0;const i=n(9870),o=n(5754),a=n(8726),s=n(9622),c=n(5552),u=r(n(1227)),d=n(1373),l=(0,u.default)("engine.io-client:websocket"),p="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class h extends i.Transport{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=p?{}:(0,s.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=c.usingBrowserWebSocket&&!p?t?new c.WebSocket(e,t):new c.WebSocket(e):new c.WebSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType||c.defaultBinaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;(0,d.encodePacket)(n,this.supportsBinary,(e=>{const t={};!c.usingBrowserWebSocket&&(n.options&&(t.compress=n.options.compress),this.opts.perMessageDeflate)&&("string"==typeof e?Buffer.byteLength(e):e.length)<this.opts.perMessageDeflate.threshold&&(t.compress=!1);try{c.usingBrowserWebSocket?this.ws.send(e):this.ws.send(e,t)}catch(e){l("websocket closed before onclose event")}r&&(0,c.nextTick)((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let n="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(n=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=(0,a.yeast)()),this.supportsBinary||(e.b64=1);const r=(0,o.encode)(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+n+this.opts.path+(r.length?"?"+r:"")}check(){return!!c.WebSocket}}t.WS=h},6666:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.XHR=void 0;const r=n(8419),i=n(6242);t.XHR=function(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||r.hasCORS))return new XMLHttpRequest}catch(e){}if(!t)try{return new(i.globalThisShim[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}},9622:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.byteLength=t.installTimerFunctions=t.pick=void 0;const r=n(6242);t.pick=function(e,...t){return t.reduce(((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t)),{})};const i=r.globalThisShim.setTimeout,o=r.globalThisShim.clearTimeout;t.installTimerFunctions=function(e,t){t.useNativeTimers?(e.setTimeoutFn=i.bind(r.globalThisShim),e.clearTimeoutFn=o.bind(r.globalThisShim)):(e.setTimeoutFn=r.globalThisShim.setTimeout.bind(r.globalThisShim),e.clearTimeoutFn=r.globalThisShim.clearTimeout.bind(r.globalThisShim))},t.byteLength=function(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}},3087:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_PACKET=t.PACKET_TYPES_REVERSE=t.PACKET_TYPES=void 0;const n=Object.create(null);t.PACKET_TYPES=n,n.open="0",n.close="1",n.ping="2",n.pong="3",n.message="4",n.upgrade="5",n.noop="6";const r=Object.create(null);t.PACKET_TYPES_REVERSE=r,Object.keys(n).forEach((e=>{r[n[e]]=e})),t.ERROR_PACKET={type:"error",data:"parser error"}},2469:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decode=t.encode=void 0;const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)r[n.charCodeAt(e)]=e;t.encode=e=>{let t,r=new Uint8Array(e),i=r.length,o="";for(t=0;t<i;t+=3)o+=n[r[t]>>2],o+=n[(3&r[t])<<4|r[t+1]>>4],o+=n[(15&r[t+1])<<2|r[t+2]>>6],o+=n[63&r[t+2]];return i%3==2?o=o.substring(0,o.length-1)+"=":i%3==1&&(o=o.substring(0,o.length-2)+"=="),o},t.decode=e=>{let t,n,i,o,a,s=.75*e.length,c=e.length,u=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const d=new ArrayBuffer(s),l=new Uint8Array(d);for(t=0;t<c;t+=4)n=r[e.charCodeAt(t)],i=r[e.charCodeAt(t+1)],o=r[e.charCodeAt(t+2)],a=r[e.charCodeAt(t+3)],l[u++]=n<<2|i>>4,l[u++]=(15&i)<<4|o>>2,l[u++]=(3&o)<<6|63&a;return d}},7572:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(3087),i=n(2469),o="function"==typeof ArrayBuffer,a=(e,t)=>{if(o){const n=(0,i.decode)(e);return s(n,t)}return{base64:!0,data:e}},s=(e,t)=>"blob"===t&&e instanceof ArrayBuffer?new Blob([e]):e;t.default=(e,t)=>{if("string"!=typeof e)return{type:"message",data:s(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:a(e.substring(1),t)}:r.PACKET_TYPES_REVERSE[n]?e.length>1?{type:r.PACKET_TYPES_REVERSE[n],data:e.substring(1)}:{type:r.PACKET_TYPES_REVERSE[n]}:r.ERROR_PACKET}},3908:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(3087),i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,a=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};t.default=({type:e,data:t},n,s)=>{return i&&t instanceof Blob?n?s(t):a(t,s):o&&(t instanceof ArrayBuffer||(c=t,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(c):c&&c.buffer instanceof ArrayBuffer))?n?s(t):a(new Blob([t]),s):s(r.PACKET_TYPES[e]+(t||""));var c}},1373:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decodePayload=t.decodePacket=t.encodePayload=t.encodePacket=t.protocol=void 0;const r=n(3908);t.encodePacket=r.default;const i=n(7572);t.decodePacket=i.default;const o=String.fromCharCode(30);t.encodePayload=(e,t)=>{const n=e.length,i=new Array(n);let a=0;e.forEach(((e,s)=>{(0,r.default)(e,!1,(e=>{i[s]=e,++a===n&&t(i.join(o))}))}))},t.decodePayload=(e,t)=>{const n=e.split(o),r=[];for(let e=0;e<n.length;e++){const o=(0,i.default)(n[e],t);if(r.push(o),"error"===o.type)break}return r},t.protocol=4},5159:(e,t)=>{function n(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Object.defineProperty(t,"__esModule",{value:!0}),t.Backoff=void 0,t.Backoff=n,n.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(e){this.ms=e},n.prototype.setMax=function(e){this.max=e},n.prototype.setJitter=function(e){this.jitter=e}},7046:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.connect=t.io=t.Socket=t.Manager=t.protocol=void 0;const i=n(3084),o=n(4168);Object.defineProperty(t,"Manager",{enumerable:!0,get:function(){return o.Manager}});const a=n(8312);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return a.Socket}});const s=r(n(1227)).default("socket.io-client"),c={};function u(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};const n=i.url(e,t.path||"/socket.io"),r=n.source,a=n.id,u=n.path,d=c[a]&&u in c[a].nsps;let l;return t.forceNew||t["force new connection"]||!1===t.multiplex||d?(s("ignoring socket cache for %s",r),l=new o.Manager(r,t)):(c[a]||(s("new io instance for %s",r),c[a]=new o.Manager(r,t)),l=c[a]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}t.io=u,t.connect=u,t.default=u,Object.assign(u,{Manager:o.Manager,Socket:a.Socket,io:u,connect:u});var d=n(4514);Object.defineProperty(t,"protocol",{enumerable:!0,get:function(){return d.protocol}}),e.exports=u},4168:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Manager=void 0;const s=n(4679),c=n(8312),u=o(n(4514)),d=n(7149),l=n(5159),p=n(5260),h=a(n(1227)).default("socket.io-client:manager");class f extends p.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,s.installTimerFunctions(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new l.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||u;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(h("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;h("opening %s",this.uri),this.engine=new s.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=d.on(t,"open",(function(){n.onopen(),e&&e()})),i=d.on(t,"error",(t=>{h("error"),n.cleanup(),n._readyState="closed",this.emitReserved("error",t),e?e(t):n.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;h("connect attempt will timeout after %d",e),0===e&&r();const n=this.setTimeoutFn((()=>{h("connect attempt timed out after %d",e),r(),t.close(),t.emit("error",new Error("timeout"))}),e);this.opts.autoUnref&&n.unref(),this.subs.push((function(){clearTimeout(n)}))}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){h("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(d.on(e,"ping",this.onping.bind(this)),d.on(e,"data",this.ondata.bind(this)),d.on(e,"error",this.onerror.bind(this)),d.on(e,"close",this.onclose.bind(this)),d.on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){s.nextTick((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){h("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new c.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return void h("socket %s is still active, skipping close",e);this._close()}_packet(e){h("writing packet %j",e);const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){h("cleanup"),this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){h("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){h("closed due to %s",e),this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)h("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();h("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn((()=>{e.skipReconnect||(h("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(h("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):(h("reconnect success"),e.onreconnect())})))}),t);this.opts.autoUnref&&n.unref(),this.subs.push((function(){clearTimeout(n)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}t.Manager=f},7149:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.on=void 0,t.on=function(e,t,n){return e.on(t,n),function(){e.off(t,n)}}},8312:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;const i=n(4514),o=n(7149),a=n(5260),s=r(n(1227)).default("socket.io-client:socket"),c=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class u extends a.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[o.on(e,"open",this.onopen.bind(this)),o.on(e,"packet",this.onpacket.bind(this)),o.on(e,"error",this.onerror.bind(this)),o.on(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(c.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:i.PacketType.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++;s("emitting packet with ack id %d",e);const r=t.pop();this._registerAckCallback(e,r),n.id=e}const r=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return!this.flags.volatile||r&&this.connected?this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n):s("discard packet as the transport is not currently writable"),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const i=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&(s("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(t,1));s("event with ack id %d has timed out after %d ms",e,r),t.call(this,new Error("operation has timed out"))}),r);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const n=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((r,i)=>{t.push(((e,t)=>n?e?i(e):r(t):r(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...r)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(s("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(e)):(s("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue()})),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(s("draining queue"),!this.connected||0===this._queue.length)return;const t=this._queue[0];!t.pending||e?(t.pending=!0,t.tryCount++,s("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)):s("packet [%d] has already been sent and is waiting for an ack",t.id)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){s("transport is open - connecting"),"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:i.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){s("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case i.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case i.PacketType.EVENT:case i.PacketType.BINARY_EVENT:this.onevent(e);break;case i.PacketType.ACK:case i.PacketType.BINARY_ACK:this.onack(e);break;case i.PacketType.DISCONNECT:this.ondisconnect();break;case i.PacketType.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];s("emitting event %j",t),null!=e.id&&(s("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,s("sending ack %j",r),t.packet({type:i.PacketType.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t?(s("calling ack %s with %j",e.id,e.data),t.apply(this,e.data),delete this.acks[e.id]):s("bad ack %s",e.id)}onconnect(e,t){s("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){s("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(s("performing disconnect (%s)",this.nsp),this.packet({type:i.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}t.Socket=u},3084:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.url=void 0;const i=n(4679),o=r(n(1227)).default("socket.io-client:url");t.url=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(o("protocol-less url %s",e),e=void 0!==n?n.protocol+"//"+e:"https://"+e),o("parse %s",e),r=i.parse(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const a=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+a+":"+r.port+t,r.href=r.protocol+"://"+a+(n&&n.port===r.port?"":":"+r.port),r}},4880:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reconstructPacket=t.deconstructPacket=void 0;const r=n(665);function i(e,t){if(!e)return e;if((0,r.isBinary)(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=i(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=i(e[r],t));return n}return e}function o(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=o(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=o(e[n],t));return e}t.deconstructPacket=function(e){const t=[],n=e.data,r=e;return r.data=i(n,t),r.attachments=t.length,{packet:r,buffers:t}},t.reconstructPacket=function(e,t){return e.data=o(e.data,t),delete e.attachments,e}},4514:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Decoder=t.Encoder=t.PacketType=t.protocol=void 0;const r=n(5260),i=n(4880),o=n(665),a=(0,n(1227).default)("socket.io-parser");var s;t.protocol=5,function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(s=t.PacketType||(t.PacketType={})),t.Encoder=class{constructor(e){this.replacer=e}encode(e){return a("encoding packet %j",e),e.type!==s.EVENT&&e.type!==s.ACK||!(0,o.hasBinary)(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===s.EVENT?s.BINARY_EVENT:s.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==s.BINARY_EVENT&&e.type!==s.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),a("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,i.deconstructPacket)(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}};class c extends r.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===s.BINARY_EVENT;n||t.type===s.BINARY_ACK?(t.type=n?s.EVENT:s.ACK,this.reconstructor=new u(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!(0,o.isBinary)(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===s[n.type])throw new Error("unknown packet type "+n.type);if(n.type===s.BINARY_EVENT||n.type===s.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(r,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!c.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return a("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case s.CONNECT:return"object"==typeof t;case s.DISCONNECT:return void 0===t;case s.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case s.EVENT:case s.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case s.ACK:case s.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}t.Decoder=c;class u{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=(0,i.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}},665:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.hasBinary=t.isBinary=void 0;const n="function"==typeof ArrayBuffer,r=Object.prototype.toString,i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===r.call(Blob),o="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===r.call(File);function a(e){return n&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||i&&e instanceof Blob||o&&e instanceof File}t.isBinary=a,t.hasBinary=function e(t,n){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(e(t[n]))return!0;return!1}if(a(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return e(t.toJSON(),!0);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return!0;return!1}},5260:(e,t,n)=>{function r(e){if(e)return function(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}(e)}n.r(t),n.d(t,{Emitter:()=>r}),r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<r.length;i++)if((n=r[i])===t||n.fn===t){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},r.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,t)}return this},r.prototype.emitReserved=r.prototype.emit,r.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},r.prototype.hasListeners=function(e){return!!this.listeners(e).length}}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}return n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n(6010)})(),window.Liveness=r();var u=function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))};const d=window.Liveness,l="#fff",p={width:90,height:125,scale:.75},h=(0,s.f)("ocrlabs",((e,t)=>u(void 0,void 0,void 0,(function*(){return f(e,t),{}})))),f=(e,t)=>{const{mountElement:n}=t,r=n.cloneNode(!0);n.parentNode.replaceChild(r,n),r.id="onesdk_idv_container",Object.assign(r.style,{position:"absolute",top:"0",left:"0",height:"100%",minHeight:"50px",width:"100%",overflow:"hidden"});const i=document.createElement("meta");i.name="viewport",i.content="width=device-width, initial-scale=1.0",document.head.appendChild(i),document.querySelector("body").style.margin="0";const o=document.createElement("div");o.id="onesdk_idv_loader",Object.assign(o.style,{position:"absolute",height:"100%",width:"100%",display:"flex",justifyContent:"center",paddingTop:"20px",fontFamily:'"Helvetica Neue", Helvetica, Arial, sans-serif',fontSize:"24px",color:"#fff",backgroundColor:"#000",zIndex:9}),o.innerText="Loading...",r.appendChild(o);const a=document.createElement("video");a.id="onesdk_idv_video",a.autoplay=!0,a.muted=!0,a.playsInline=!0,Object.assign(a.style,{position:"absolute",top:"0",left:"0",height:"100%",width:"100%",objectFit:"cover",transform:"scale(-1, 1)"}),r.appendChild(a);const s=document.createElement("div");s.id="onesdk_idv_overlay",Object.assign(s.style,{position:"absolute",top:"0",left:"0",height:"100%",width:"100%",display:"flex",justifyContent:"center",alignItems:"center"});const c=document.createElement("div");c.id="onesdk_idv_mask";const{width:u,height:d}=p,h=(({width:e,height:t})=>{const{width:n,height:r,scale:i}=p;return Math.min(e/n,t/r)*i})({width:r.offsetWidth,height:r.offsetHeight});Object.assign(c.style,{width:u*h+"px",height:d*h+"px",backgroundColor:"transparent",border:`${h}px solid ${l}`,borderRadius:"50% / 40% 40% 60% 60%",boxShadow:"0 0 0 9999px rgba(0, 0, 0, 0.75)"}),s.appendChild(c),r.appendChild(s);const f=document.createElement("div");return f.id="onesdk_idv_instructions",Object.assign(f.style,{position:"absolute",bottom:"20px",left:"50%",transform:"translate(-50%, 0)",color:"#fff",fontFamily:'"Helvetica Neue", Helvetica, Arial, sans-serif',fontSize:"24px",zIndex:"1"}),r.appendChild(f),g(e,t),a},m=(e,t)=>u(void 0,void 0,void 0,(function*(){const{recipe:n}=e,{eventHub:r,mountElement:i}=t,a=(0,o.M)(n),s=document.getElementById("onesdk_idv_container");s&&s.parentNode.replaceChild(i,s);try{yield d.close(),r.emit("session_closed")}catch(e){const{message:t}=e;return r.emit("error",a("DEFAULT",{message:t})),!1}return!0})),g=(e,t)=>u(void 0,void 0,void 0,(function*(){const{frankieClient:n,recipe:r}=e,{biometrics:{provider:a}}=r,{eventHub:s}=t,u=new c.Ns(n),l=(0,o.M)(r),p=yield(0,i.j)(u,s);if(!p)return;const{token:h}=p,f={session_id:h,tx_id:"ocrlabs"===a.name&&a.tx_id},g=document.getElementById("onesdk_idv_video"),y=document.getElementById("onesdk_idv_loader");d.observer.on("error",(n=>{const{message:r}=n;s.emit("error",l("DEFAULT",{message:r})),m(e,t)}));try{yield d.createSession("wss://engine.au.v3.liveness.idkit.io",{videoElement:g,auth:f}),y.remove(),s.emit("ready",{domElement:g}),yield v(e,t,u)}catch(n){s.emit("session_data_failed_loading",{code:n.code||null,message:n.message}),yield m(e,t)}})),v=(e,t,n)=>u(void 0,void 0,void 0,(function*(){const{recipe:r}=e,{eventHub:i}=t,s=(0,o.M)(r),c=document.getElementById("onesdk_idv_instructions"),p=document.getElementById("onesdk_idv_mask");c.style.display="block";const h=(n,r)=>u(void 0,void 0,void 0,(function*(){const o=d.delay||2e3;return new Promise(((a,s)=>u(void 0,void 0,void 0,(function*(){try{c.innerText=r,p.style.borderColor=l,yield d.detect(n,{retry:!0,timeout:7500}),c.innerText="Thanks!",p.style.borderColor="#14ffc0",setTimeout((()=>{a(!0)}),o)}catch(n){c.innerText="Something went wrong",p.style.borderColor="#ff4747",i.emit("detection_failed",{message:n&&n.message?n.message:null}),setTimeout((()=>{m(e,t),s(!1)}),o)}}))))}));yield h("face","Position your face within the frame"),yield h("smile","Please give us a BIG Smile!"),i.emit("detection_complete");try{if(!(yield m(e,t)))return;yield(0,a.W)({idvClient:n,recipe:r,eventHub:i})}catch(e){const{message:t}=e;i.emit("error",s("INIT_PROCESS",{message:t}))}}))},8016:(e,t,n)=>{n.d(t,{j:()=>r});const r=(e,t)=>{return n=void 0,r=void 0,o=function*(){t.emit("loading",!0,{message:"Loading biometrics vendor"});try{const{entityId:n,token:r,vendorParameters:i}=yield e.getToken();return t.emit("session_data_generated",{session:{entityId:n,token:r,vendorParameters:i}}),t.emit("loading",!1,{message:"Biometrics vendor has loaded"}),{entityId:n,token:r,vendorParameters:i}}catch(e){const{code:n=null,message:r=""}=e;return t.emit("session_data_failed_loading",{code:n,message:r}),t.emit("loading",!1,{message:"Biometrics vendor has not loaded"}),null}},new((i=void 0)||(i=Promise))((function(e,t){function a(e){try{c(o.next(e))}catch(e){t(e)}}function s(e){try{c(o.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i((function(e){e(n)}))).then(a,s)}c((o=o.apply(n,r||[])).next())}));var n,r,i,o}},2365:(e,t,n)=>{n.d(t,{M:()=>o});var r=n(4334),i=n(9188);const o=e=>{const{biometrics:{provider:{name:t}}}=e;return(e,...n)=>{return new r.OneSDKError((o=t,{DEFAULT:`Error from vendor SDK '${o}'`,INIT_PROCESS:"Error from biometrics submission",[i.Yt.PROVIDER_OFFLINE]:`Error initialising biometrics check with '${o}'. The service doesn't appear to be available.`,[i.Yt.WAITING_DOC_UPLOAD]:`Error initialising biometrics check with '${o}'. You might need to run the 'ocr' component before running 'biometrics'.`,[i.Yt.WAITING_SELFIE_UPLOAD]:`Error initialising biometrics check with '${o}'. You might need to capture selfie before running 'biometrics'.`})[e],n);var o}}},3655:(e,t,n)=>{n.d(t,{W:()=>o});var r=n(2365),i=n(9188);const o=e=>{return t=void 0,n=[e],a=function*({idvClient:e,recipe:t,eventHub:n}){n.emit("loading",!0,{message:"Evaluating results"});const{biometrics:{is_synchronous:o}}=t,a=(0,r.M)(t),{checkStatus:s,ocrDocument:c}=yield e.initProcess({isSynchronous:!!o});(0,i.q8)(s)||(0,i.tX)(s)?n.emit("error",a(s)):n.emit(o?"results":"processing",{checkStatus:s,document:c,entityId:e.entityId}),n.emit("loading",!1,{message:"Results have retrived"})},new((o=void 0)||(o=Promise))((function(e,r){function i(e){try{c(a.next(e))}catch(e){r(e)}}function s(e){try{c(a.throw(e))}catch(e){r(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o((function(e){e(n)}))).then(i,s)}c((a=a.apply(t,n||[])).next())}));var t,n,o,a}}}]);
2
- //# sourceMappingURL=biometrics-ocrlabs.js.map