@snap/camera-kit 0.13.2 → 0.14.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 (236) hide show
  1. package/README.md +1 -1
  2. package/docs/html/assets/search.js +1 -1
  3. package/docs/html/classes/CameraKit.html +4 -3
  4. package/docs/html/classes/CameraKitSession.html +4 -3
  5. package/docs/html/classes/CameraKitSource.html +4 -3
  6. package/docs/html/classes/LensPerformanceMeasurement.html +4 -3
  7. package/docs/html/classes/LensPerformanceMetrics.html +4 -3
  8. package/docs/html/classes/LensRepository.html +6 -5
  9. package/docs/html/classes/LensSources.html +4 -3
  10. package/docs/html/classes/Transform2D.html +4 -3
  11. package/docs/html/classes/TypedCustomEvent.html +4 -3
  12. package/docs/html/classes/TypedEventTarget.html +4 -3
  13. package/docs/html/functions/Injectable.html +4 -3
  14. package/docs/html/functions/bootstrapCameraKit.html +4 -3
  15. package/docs/html/functions/createExtension.html +4 -3
  16. package/docs/html/functions/createImageSource.html +4 -3
  17. package/docs/html/functions/createMediaStreamSource.html +4 -3
  18. package/docs/html/functions/createUserMediaSource.html +4 -3
  19. package/docs/html/functions/createVideoSource.html +4 -3
  20. package/docs/html/functions/estimateLensPerformance.html +4 -3
  21. package/docs/html/functions/getRequiredBootstrapURLs.html +4 -3
  22. package/docs/html/functions/lensSourcesFactory.html +4 -3
  23. package/docs/html/functions/remoteApiServicesFactory.html +4 -3
  24. package/docs/html/index.html +6 -5
  25. package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +16 -5
  26. package/docs/html/interfaces/CameraKitSourceSubscriber.html +5 -4
  27. package/docs/html/interfaces/ComputedFrameMetrics.html +4 -3
  28. package/docs/html/interfaces/CreateSessionOptions.html +4 -3
  29. package/docs/html/interfaces/EstimatedLensPerformance.html +4 -3
  30. package/docs/html/interfaces/Lens.html +13 -3
  31. package/docs/html/interfaces/LensSource.html +4 -3
  32. package/docs/html/interfaces/MediaStreamSourceOptions.html +4 -3
  33. package/docs/html/interfaces/Preview.html +4 -3
  34. package/docs/html/interfaces/RemoteApiRequest.html +4 -3
  35. package/docs/html/interfaces/RemoteApiResponse.html +4 -3
  36. package/docs/html/interfaces/RemoteApiService.html +4 -3
  37. package/docs/html/interfaces/Snapcode.html +4 -3
  38. package/docs/html/interfaces/UriCancelRequest.html +4 -3
  39. package/docs/html/interfaces/UriRequest.html +4 -3
  40. package/docs/html/interfaces/UriResponse.html +4 -3
  41. package/docs/html/interfaces/VideoSourceOptions.html +4 -3
  42. package/docs/html/modules.html +6 -4
  43. package/docs/html/types/AssetLoader.html +4 -3
  44. package/docs/html/types/AssetTiming.html +4 -3
  45. package/docs/html/types/BenchmarkError.html +4 -3
  46. package/docs/html/types/BootstrapError.html +4 -3
  47. package/docs/html/types/CacheKeyNotFoundError.html +4 -3
  48. package/docs/html/types/CameraKitDeviceInfo.html +4 -3
  49. package/docs/html/types/CameraKitDeviceOptions.html +4 -3
  50. package/docs/html/types/CameraKitSessionEventListener.html +4 -3
  51. package/docs/html/types/CameraKitSessionEvents.html +6 -5
  52. package/docs/html/types/CameraKitSourceError.html +4 -3
  53. package/docs/html/types/CameraKitSourceInfo.html +4 -3
  54. package/docs/html/types/CameraKitSourceOptions.html +4 -3
  55. package/docs/html/types/ConfigurationError.html +4 -3
  56. package/docs/html/types/Keyboard.html +4 -3
  57. package/docs/html/types/KeyboardEvents.html +4 -3
  58. package/docs/html/types/LegalError.html +4 -3
  59. package/docs/html/types/LensAbortError.html +119 -0
  60. package/docs/html/types/LensAssetError.html +4 -3
  61. package/docs/html/types/LensContentValidationError.html +4 -3
  62. package/docs/html/types/LensError.html +4 -3
  63. package/docs/html/types/LensExecutionError.html +4 -3
  64. package/docs/html/types/LensImagePickerError.html +4 -3
  65. package/docs/html/types/LensLaunchParams.html +4 -3
  66. package/docs/html/types/LensMetricsEvents.html +4 -3
  67. package/docs/html/types/LensPerformanceCluster.html +4 -3
  68. package/docs/html/types/LensView.html +4 -3
  69. package/docs/html/types/LensWait.html +4 -3
  70. package/docs/html/types/PersistentStoreError.html +4 -3
  71. package/docs/html/types/PlatformNotSupportedError.html +4 -3
  72. package/docs/html/types/PublicContainer.html +4 -3
  73. package/docs/html/types/RemoteApiRequestHandler.html +4 -3
  74. package/docs/html/types/RemoteApiServices.html +4 -3
  75. package/docs/html/types/RemoteApiStatus.html +4 -3
  76. package/docs/html/types/RenderTarget.html +4 -3
  77. package/docs/html/types/Uri.html +4 -3
  78. package/docs/html/types/WebGLError.html +4 -3
  79. package/docs/html/variables/extensionRequestContext.html +4 -3
  80. package/docs/md/README.md +1 -1
  81. package/docs/md/classes/CameraKit.md +1 -1
  82. package/docs/md/classes/CameraKitSession.md +1 -1
  83. package/docs/md/classes/CameraKitSource.md +1 -1
  84. package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
  85. package/docs/md/classes/LensPerformanceMetrics.md +1 -1
  86. package/docs/md/classes/LensRepository.md +3 -3
  87. package/docs/md/classes/LensSources.md +1 -1
  88. package/docs/md/classes/Transform2D.md +1 -1
  89. package/docs/md/classes/TypedCustomEvent.md +1 -1
  90. package/docs/md/classes/TypedEventTarget.md +1 -1
  91. package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +13 -2
  92. package/docs/md/interfaces/CameraKitSourceSubscriber.md +3 -3
  93. package/docs/md/interfaces/ComputedFrameMetrics.md +1 -1
  94. package/docs/md/interfaces/CreateSessionOptions.md +1 -1
  95. package/docs/md/interfaces/EstimatedLensPerformance.md +1 -1
  96. package/docs/md/interfaces/Lens.md +11 -1
  97. package/docs/md/interfaces/LensSource.md +1 -1
  98. package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
  99. package/docs/md/interfaces/Preview.md +1 -1
  100. package/docs/md/interfaces/RemoteApiRequest.md +1 -1
  101. package/docs/md/interfaces/RemoteApiResponse.md +1 -1
  102. package/docs/md/interfaces/RemoteApiService.md +1 -1
  103. package/docs/md/interfaces/Snapcode.md +1 -1
  104. package/docs/md/interfaces/UriCancelRequest.md +1 -1
  105. package/docs/md/interfaces/UriRequest.md +1 -1
  106. package/docs/md/interfaces/UriResponse.md +1 -1
  107. package/docs/md/interfaces/VideoSourceOptions.md +1 -1
  108. package/docs/md/modules.md +24 -4
  109. package/lib/CameraKit.d.ts +139 -7
  110. package/lib/CameraKit.js +19 -19
  111. package/lib/CameraKit.js.map +1 -1
  112. package/lib/__tests__/data.d.ts +9 -4
  113. package/lib/__tests__/data.js +19 -9
  114. package/lib/__tests__/data.js.map +1 -1
  115. package/lib/bootstrapCameraKit.js +2 -2
  116. package/lib/bootstrapCameraKit.js.map +1 -1
  117. package/lib/common/localization.js +7 -31
  118. package/lib/common/localization.js.map +1 -1
  119. package/lib/configuration.d.ts +7 -0
  120. package/lib/configuration.js +1 -0
  121. package/lib/configuration.js.map +1 -1
  122. package/lib/configurationOverrides.d.ts +2 -2
  123. package/lib/configurationOverrides.js +11 -6
  124. package/lib/configurationOverrides.js.map +1 -1
  125. package/lib/dependency-injection/RootServices.d.ts +2 -2
  126. package/lib/dependency-injection/RootServices.js.map +1 -1
  127. package/lib/environment.json +1 -1
  128. package/lib/extensions/extensionRequestContext.js +4 -4
  129. package/lib/extensions/extensionRequestContext.js.map +1 -1
  130. package/lib/extensions/uriHandlersRegister.d.ts +2 -2
  131. package/lib/extensions/uriHandlersRegister.js.map +1 -1
  132. package/lib/generated-proto/blizzard/cameraKitEvents.d.ts +272 -0
  133. package/lib/generated-proto/blizzard/cameraKitEvents.js +38 -24
  134. package/lib/generated-proto/blizzard/cameraKitEvents.js.map +1 -1
  135. package/lib/handlers/cameraKitServiceFetchHandlerFactory.js +2 -2
  136. package/lib/handlers/cameraKitServiceFetchHandlerFactory.js.map +1 -1
  137. package/lib/index.d.ts +2 -1
  138. package/lib/index.js +2 -1
  139. package/lib/index.js.map +1 -1
  140. package/lib/lens/Lens.d.ts +9 -1
  141. package/lib/lens/Lens.js +2 -1
  142. package/lib/lens/Lens.js.map +1 -1
  143. package/lib/lens/LensPersistenceStore.d.ts +2 -2
  144. package/lib/lens/LensPersistenceStore.js.map +1 -1
  145. package/lib/lens/LensRepository.d.ts +2 -2
  146. package/lib/lens/LensRepository.js +5 -4
  147. package/lib/lens/LensRepository.js.map +1 -1
  148. package/lib/lens/assets/LensAssetRepository.d.ts +4 -4
  149. package/lib/lens/assets/LensAssetRepository.js +1 -3
  150. package/lib/lens/assets/LensAssetRepository.js.map +1 -1
  151. package/lib/lens/assets/LensAssetsProvider.d.ts +9 -3
  152. package/lib/lens/assets/LensAssetsProvider.js +12 -5
  153. package/lib/lens/assets/LensAssetsProvider.js.map +1 -1
  154. package/lib/lens-client-interface/imagePicker.d.ts +2 -2
  155. package/lib/lens-client-interface/imagePicker.js.map +1 -1
  156. package/lib/lens-client-interface/lensClientInterface.d.ts +2 -2
  157. package/lib/lens-client-interface/lensClientInterface.js.map +1 -1
  158. package/lib/lens-core-module/generated-types.d.ts +4 -2
  159. package/lib/lens-core-module/generated-types.js.map +1 -1
  160. package/lib/lens-core-module/index.d.ts +1 -0
  161. package/lib/lens-core-module/index.js +1 -0
  162. package/lib/lens-core-module/index.js.map +1 -1
  163. package/lib/lens-core-module/lensCore.d.ts +41 -0
  164. package/lib/lens-core-module/lensCore.js +54 -0
  165. package/lib/lens-core-module/lensCore.js.map +1 -0
  166. package/lib/lens-core-module/lensCoreError.d.ts +15 -0
  167. package/lib/lens-core-module/lensCoreError.js +43 -0
  168. package/lib/lens-core-module/lensCoreError.js.map +1 -0
  169. package/lib/lens-core-module/loader/lensCoreFactory.d.ts +1 -2
  170. package/lib/lens-core-module/loader/lensCoreFactory.js +24 -26
  171. package/lib/lens-core-module/loader/lensCoreFactory.js.map +1 -1
  172. package/lib/lensCoreWasmVersions.json +3 -3
  173. package/lib/logger/registerLogEntriesSubscriber.js +2 -2
  174. package/lib/logger/registerLogEntriesSubscriber.js.map +1 -1
  175. package/lib/media-sources/CameraKitSource.d.ts +3 -3
  176. package/lib/media-sources/CameraKitSource.js +22 -31
  177. package/lib/media-sources/CameraKitSource.js.map +1 -1
  178. package/lib/media-sources/FunctionSource.js +33 -36
  179. package/lib/media-sources/FunctionSource.js.map +1 -1
  180. package/lib/media-sources/MediaStreamSource.js +11 -15
  181. package/lib/media-sources/MediaStreamSource.js.map +1 -1
  182. package/lib/metrics/businessEventsReporter.js +114 -108
  183. package/lib/metrics/businessEventsReporter.js.map +1 -1
  184. package/lib/metrics/reporters/reportGlobalException.js +25 -7
  185. package/lib/metrics/reporters/reportGlobalException.js.map +1 -1
  186. package/lib/metrics/reporters/reportHttpMetrics.js +2 -2
  187. package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -1
  188. package/lib/metrics/reporters/reportLensView.js +5 -3
  189. package/lib/metrics/reporters/reportLensView.js.map +1 -1
  190. package/lib/metrics/reporters/reportLensWait.js +8 -2
  191. package/lib/metrics/reporters/reportLensWait.js.map +1 -1
  192. package/lib/metrics/reporters/reportPlatformCapabilities.d.ts +12 -0
  193. package/lib/metrics/reporters/reportPlatformCapabilities.js +18 -0
  194. package/lib/metrics/reporters/reportPlatformCapabilities.js.map +1 -0
  195. package/lib/metrics/reporters/reporters.d.ts +2 -1
  196. package/lib/metrics/reporters/reporters.js +3 -1
  197. package/lib/metrics/reporters/reporters.js.map +1 -1
  198. package/lib/namedErrors.d.ts +17 -0
  199. package/lib/namedErrors.js +2 -0
  200. package/lib/namedErrors.js.map +1 -1
  201. package/lib/platform/assertPlatformSupported.d.ts +4 -0
  202. package/lib/platform/assertPlatformSupported.js +15 -0
  203. package/lib/platform/assertPlatformSupported.js.map +1 -0
  204. package/lib/platform/cameraKitUserAgent.d.ts +2 -0
  205. package/lib/platform/cameraKitUserAgent.js +20 -0
  206. package/lib/platform/cameraKitUserAgent.js.map +1 -0
  207. package/lib/platform/platformCapabilities.d.ts +50 -0
  208. package/lib/platform/platformCapabilities.js +122 -0
  209. package/lib/platform/platformCapabilities.js.map +1 -0
  210. package/lib/{common/cameraKitUserAgent.d.ts → platform/platformInfo.d.ts} +13 -10
  211. package/lib/{common/cameraKitUserAgent.js → platform/platformInfo.js} +94 -100
  212. package/lib/platform/platformInfo.js.map +1 -0
  213. package/lib/remote-configuration/cofHandler.js +2 -2
  214. package/lib/remote-configuration/cofHandler.js.map +1 -1
  215. package/lib/remote-configuration/preloadConfiguration.d.ts +2 -2
  216. package/lib/remote-configuration/preloadConfiguration.js.map +1 -1
  217. package/lib/session/CameraKitSession.d.ts +3 -3
  218. package/lib/session/CameraKitSession.js +23 -30
  219. package/lib/session/CameraKitSession.js.map +1 -1
  220. package/lib/session/CameraKitSessionEvents.d.ts +7 -3
  221. package/lib/session/CameraKitSessionEvents.js +17 -0
  222. package/lib/session/CameraKitSessionEvents.js.map +1 -1
  223. package/lib/session/LensPerformanceMetrics.d.ts +2 -2
  224. package/lib/session/LensPerformanceMetrics.js +4 -3
  225. package/lib/session/LensPerformanceMetrics.js.map +1 -1
  226. package/lib/session/lensState.d.ts +2 -2
  227. package/lib/session/lensState.js +36 -37
  228. package/lib/session/lensState.js.map +1 -1
  229. package/package.json +2 -2
  230. package/lib/assertPlatformSupported.d.ts +0 -6
  231. package/lib/assertPlatformSupported.js +0 -21
  232. package/lib/assertPlatformSupported.js.map +0 -1
  233. package/lib/common/cameraKitUserAgent.js.map +0 -1
  234. package/lib/common/locale.d.ts +0 -2
  235. package/lib/common/locale.js +0 -11
  236. package/lib/common/locale.js.map +0 -1
@@ -4,9 +4,7 @@ const getYUVImageData = (canvas, lensCore) => __awaiter(void 0, void 0, void 0,
4
4
  const { width, height } = canvas;
5
5
  // A YUV buffer has lower-res UV channels, so the total number of bytes works out like so:
6
6
  const outputBuffer = new ArrayBuffer((width * height * 3) / 2);
7
- yield new Promise((onSuccess, onFailure) => {
8
- lensCore.imageToYuvBuffer({ image: canvas, width, height, outputBuffer, onSuccess, onFailure });
9
- });
7
+ yield lensCore.imageToYuvBuffer({ image: canvas, width, height, outputBuffer });
10
8
  const pixels = new Uint8ClampedArray(outputBuffer);
11
9
  return new ImageData(pixels, width, height);
12
10
  });
@@ -65,6 +63,7 @@ export const createFunctionSource = (sourceFunction, options = {}) => {
65
63
  return;
66
64
  try {
67
65
  yield sourceFunction(({ format, imageData, timestampMillis }) => {
66
+ // TODO: with processFrame promisified, we don't really need to create a wrapper promise
68
67
  const frameOutput = new Promise((resolve, reject) => __awaiter(void 0, void 0, void 0, function* () {
69
68
  const inputFrame = yield getImageBitmap(imageData, format !== null && format !== void 0 ? format : "rgb");
70
69
  if (inputFrame.width !== width || inputFrame.height !== height) {
@@ -75,39 +74,37 @@ export const createFunctionSource = (sourceFunction, options = {}) => {
75
74
  // frame.
76
75
  source.setRenderSize(width, height);
77
76
  }
78
- lensCore.processFrame({
79
- inputFrame,
80
- timestampMillis,
81
- onSuccess: () => __awaiter(void 0, void 0, void 0, function* () {
82
- // Closing releases graphics resources associated with the frame, now that is
83
- // has been processed.
84
- inputFrame.close();
85
- switch (format !== null && format !== void 0 ? format : "rgb") {
86
- case "nv12":
87
- case "yuv":
88
- const [live, capture] = yield Promise.all([
89
- getYUVImageData(output.live, lensCore),
90
- getYUVImageData(output.capture, lensCore),
91
- ]).catch((error) => {
92
- reject(error);
93
- return [undefined, undefined];
94
- });
95
- // if either of these is undefined, we'll have already rejected
96
- // the promise, so we can return.
97
- if (!live || !capture)
98
- return;
99
- return resolve({ live, capture });
100
- case "rgb":
101
- return resolve({
102
- live: getRGBImageData(output.live, imageReader2D),
103
- capture: getRGBImageData(output.capture, imageReader2D),
104
- });
105
- }
106
- }),
107
- onFailure: (error) => {
108
- inputFrame.close();
109
- reject(error);
110
- },
77
+ lensCore
78
+ .processFrame({ inputFrame, timestampMillis })
79
+ .then(() => __awaiter(void 0, void 0, void 0, function* () {
80
+ // Closing releases graphics resources associated with the frame, now that is
81
+ // has been processed.
82
+ inputFrame.close();
83
+ switch (format !== null && format !== void 0 ? format : "rgb") {
84
+ case "nv12":
85
+ case "yuv":
86
+ const [live, capture] = yield Promise.all([
87
+ getYUVImageData(output.live, lensCore),
88
+ getYUVImageData(output.capture, lensCore),
89
+ ]).catch((error) => {
90
+ reject(error);
91
+ return [undefined, undefined];
92
+ });
93
+ // if either of these is undefined, we'll have already rejected
94
+ // the promise, so we can return.
95
+ if (!live || !capture)
96
+ return;
97
+ return resolve({ live, capture });
98
+ case "rgb":
99
+ return resolve({
100
+ live: getRGBImageData(output.live, imageReader2D),
101
+ capture: getRGBImageData(output.capture, imageReader2D),
102
+ });
103
+ }
104
+ }))
105
+ .catch((error) => {
106
+ inputFrame.close();
107
+ reject(error);
111
108
  });
112
109
  }));
113
110
  // Even if there's an error processing the frame, we do want to attempt to process the next
@@ -1 +1 @@
1
- {"version":3,"file":"FunctionSource.js","sourceRoot":"","sources":["../../src/media-sources/FunctionSource.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,eAAe,EAAqD,MAAM,mBAAmB,CAAC;AAEvG,MAAM,eAAe,GAAG,CAAO,MAAyB,EAAE,QAAwB,EAAsB,EAAE;IACtG,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IACjC,0FAA0F;IAC1F,MAAM,YAAY,GAAG,IAAI,WAAW,CAAC,CAAC,KAAK,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/D,MAAM,IAAI,OAAO,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE;QACvC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC,CAAC;IACpG,CAAC,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAAC;IACnD,OAAO,IAAI,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAChD,CAAC,CAAA,CAAC;AAEF,MAAM,eAAe,GAAG,CAAC,MAAyB,EAAE,aAA8C,EAAa,EAAE;IAC7G,IAAI,aAAa,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AAQ,EAAE,WAAW,CAAC,CAAC,CAAC;wBACvE,OAAO,WAAW,CAAC;oBACvB,CAAC,CAAC,CAAC;iBACN;gBAAC,OAAO,KAAK,EAAE;oBACZ,WAAW,CACP,IAAI,KAAK,CACL,kEAAkE;wBAC9D,uBAAuB,MAAA,cAAc,CAAC,IAAI,mCAAI,WAAW,GAAG,EAChE,EAAE,KAAK,EAAE,KAAK,EAAE,CACnB,CACJ,CAAC;iBACL;YACL,CAAC,CAAA,CAAC,CAAC;YACP,YAAY,CAAC,MAAM,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;QAChD,CAAC;QACD,QAAQ,EAAE,GAAG,EAAE;YACX,kBAAkB,GAAG,KAAK,CAAC;QAC/B,CAAC;KACJ,CAAC;IAEF,OAAO,IAAI,eAAe,CAAC,EAAE,wBAAwB,EAAE,IAAI,EAAE,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;AACxF,CAAC,CAAC","sourcesContent":["import { LensCoreModule } from \"../lens-core-module/generated-types\";\nimport { CameraKitSource, CameraKitSourceOptions, CameraKitSourceSubscriber } from \"./CameraKitSource\";\n\nconst getYUVImageData = async (canvas: HTMLCanvasElement, lensCore: LensCoreModule): Promise<ImageData> => {\n const { width, height } = canvas;\n // A YUV buffer has lower-res UV channels, so the total number of bytes works out like so:\n const outputBuffer = new ArrayBuffer((width * height * 3) / 2);\n await new Promise((onSuccess, onFailure) => {\n lensCore.imageToYuvBuffer({ image: canvas, width, height, outputBuffer, onSuccess, onFailure });\n });\n const pixels = new Uint8ClampedArray(outputBuffer);\n return new ImageData(pixels, width, height);\n};\n\nconst getRGBImageData = (output: HTMLCanvasElement, imageReader2D: CanvasRenderingContext2D | null): ImageData => {\n if (imageReader2D === null) return new ImageData(0, 0);\n imageReader2D.drawImage(output, 0, 0);\n return imageReader2D.getImageData(0, 0, output.width, output.height);\n};\n\nconst getImageBitmap = async (imageData: ImageData, format: FrameFormat): Promise<ImageBitmap> => {\n switch (format) {\n case \"nv12\":\n case \"yuv\":\n if (!window.VideoFrame)\n return Promise.reject(\n new Error(`Cannot process frame. ImageData in ${format} is not supported by this browser.`)\n );\n const frame = new VideoFrame(imageData.data.buffer, {\n format: \"NV12\",\n codedWidth: imageData.width,\n codedHeight: imageData.height,\n timestamp: 0,\n });\n return createImageBitmap(frame);\n case \"rgb\":\n return createImageBitmap(imageData);\n }\n};\n\n/** @internal */\nexport type FrameFormat = \"rgb\" | \"yuv\" | \"nv12\";\n\n/** @internal */\nexport interface FrameInput {\n format?: FrameFormat;\n imageData: ImageData;\n timestampMillis: number;\n}\n\n/** @internal */\nexport interface FrameOutput {\n live: ImageData;\n capture: ImageData;\n}\n\n/** @internal */\nexport interface MediaSourceFunction {\n (render: (frame: FrameInput) => Promise<FrameOutput>): Promise<void>;\n}\n\n/**\n * Creates a {@link CameraKitSource} from a function which provides per-frame pixel data to CameraKit.\n *\n * @param sourceFunction This function will be called in a requestAnimationFrame loop. Each time it is called, it is\n * passed a `render` function. It may call `render` and CameraKit will process the pixel data passed to `render` and\n * return a Promise of the processed pixels (along with rendering them to the normal output canvases).\n * @param options\n * @param options.cameraType By default we set this to 'user', which is the camera type most Lenses expect.\n *\n * @internal\n */\nexport const createFunctionSource = (\n sourceFunction: MediaSourceFunction,\n options: Omit<CameraKitSourceOptions, \"fpsLimit\"> = {}\n): CameraKitSource => {\n let width = 0;\n let height = 0;\n let shouldProcessFrame = true;\n\n // We require an auxiliary canvas that we can use to read back pixel data (unless we're in YUV mode, in which case\n // we use LensCore to convert between formats and we don't need this canvas).\n const imageReaderCanvas = document.createElement(\"canvas\");\n const imageReader2D = imageReaderCanvas.getContext(\"2d\");\n\n const subscriber: CameraKitSourceSubscriber = {\n onAttach: (source, lensCore, reportError) => {\n const outputs = lensCore.getOutputCanvases();\n const output = {\n live: outputs[lensCore.CanvasType.Preview.value],\n capture: outputs[lensCore.CanvasType.Capture.value],\n };\n\n const processFrame = (\n source: CameraKitSource,\n lensCore: LensCoreModule,\n reportError: (error: Error) => void\n ) =>\n requestAnimationFrame(async () => {\n if (!shouldProcessFrame) return;\n try {\n await sourceFunction(({ format, imageData, timestampMillis }) => {\n const frameOutput = new Promise<FrameOutput>(async (resolve, reject) => {\n const inputFrame = await getImageBitmap(imageData, format ?? \"rgb\");\n if (inputFrame.width !== width || inputFrame.height !== height) {\n width = imageReaderCanvas.width = inputFrame.width;\n height = imageReaderCanvas.height = inputFrame.height;\n // We don't await this promise, because we want to continue to process frames and\n // let LensCore manage the concurrency between setting resolution and processing a\n // frame.\n source.setRenderSize(width, height);\n }\n lensCore.processFrame({\n inputFrame,\n timestampMillis,\n onSuccess: async () => {\n // Closing releases graphics resources associated with the frame, now that is\n // has been processed.\n inputFrame.close();\n\n switch (format ?? \"rgb\") {\n case \"nv12\":\n case \"yuv\":\n const [live, capture] = await Promise.all([\n getYUVImageData(output.live, lensCore),\n getYUVImageData(output.capture, lensCore),\n ]).catch((error) => {\n reject(error);\n return [undefined, undefined] as const;\n });\n // if either of these is undefined, we'll have already rejected\n // the promise, so we can return.\n if (!live || !capture) return;\n return resolve({ live, capture });\n case \"rgb\":\n return resolve({\n live: getRGBImageData(output.live, imageReader2D),\n capture: getRGBImageData(output.capture, imageReader2D),\n });\n }\n },\n onFailure: (error) => {\n inputFrame.close();\n reject(error);\n },\n });\n });\n // Even if there's an error processing the frame, we do want to attempt to process the next\n // frame. We expect `sourceFunction` to handle a rejected `frameOutput` Promise.\n frameOutput.finally(() => processFrame(source, lensCore, reportError));\n return frameOutput;\n });\n } catch (error) {\n reportError(\n new Error(\n \"Failure to process frame, which was not handled by the provided \" +\n `MediaSourceFunction ${sourceFunction.name ?? \"anonymous\"}.`,\n { cause: error }\n )\n );\n }\n });\n processFrame(source, lensCore, reportError);\n },\n onDetach: () => {\n shouldProcessFrame = false;\n },\n };\n\n return new CameraKitSource({ useManualFrameProcessing: true }, subscriber, options);\n};\n"]}
1
+ {"version":3,"file":"FunctionSource.js","sourceRoot":"","sources":["../../src/media-sources/FunctionSource.ts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,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;AACxF,CAAC,CAAC","sourcesContent":["import { LensCore } from \"../lens-core-module\";\nimport { CameraKitSource, CameraKitSourceOptions, CameraKitSourceSubscriber } from \"./CameraKitSource\";\n\nconst getYUVImageData = async (canvas: HTMLCanvasElement, lensCore: LensCore): Promise<ImageData> => {\n const { width, height } = canvas;\n // A YUV buffer has lower-res UV channels, so the total number of bytes works out like so:\n const outputBuffer = new ArrayBuffer((width * height * 3) / 2);\n await lensCore.imageToYuvBuffer({ image: canvas, width, height, outputBuffer });\n const pixels = new Uint8ClampedArray(outputBuffer);\n return new ImageData(pixels, width, height);\n};\n\nconst getRGBImageData = (output: HTMLCanvasElement, imageReader2D: CanvasRenderingContext2D | null): ImageData => {\n if (imageReader2D === null) return new ImageData(0, 0);\n imageReader2D.drawImage(output, 0, 0);\n return imageReader2D.getImageData(0, 0, output.width, output.height);\n};\n\nconst getImageBitmap = async (imageData: ImageData, format: FrameFormat): Promise<ImageBitmap> => {\n switch (format) {\n case \"nv12\":\n case \"yuv\":\n if (!window.VideoFrame)\n return Promise.reject(\n new Error(`Cannot process frame. ImageData in ${format} is not supported by this browser.`)\n );\n const frame = new VideoFrame(imageData.data.buffer, {\n format: \"NV12\",\n codedWidth: imageData.width,\n codedHeight: imageData.height,\n timestamp: 0,\n });\n return createImageBitmap(frame);\n case \"rgb\":\n return createImageBitmap(imageData);\n }\n};\n\n/** @internal */\nexport type FrameFormat = \"rgb\" | \"yuv\" | \"nv12\";\n\n/** @internal */\nexport interface FrameInput {\n format?: FrameFormat;\n imageData: ImageData;\n timestampMillis: number;\n}\n\n/** @internal */\nexport interface FrameOutput {\n live: ImageData;\n capture: ImageData;\n}\n\n/** @internal */\nexport interface MediaSourceFunction {\n (render: (frame: FrameInput) => Promise<FrameOutput>): Promise<void>;\n}\n\n/**\n * Creates a {@link CameraKitSource} from a function which provides per-frame pixel data to CameraKit.\n *\n * @param sourceFunction This function will be called in a requestAnimationFrame loop. Each time it is called, it is\n * passed a `render` function. It may call `render` and CameraKit will process the pixel data passed to `render` and\n * return a Promise of the processed pixels (along with rendering them to the normal output canvases).\n * @param options\n * @param options.cameraType By default we set this to 'user', which is the camera type most Lenses expect.\n *\n * @internal\n */\nexport const createFunctionSource = (\n sourceFunction: MediaSourceFunction,\n options: Omit<CameraKitSourceOptions, \"fpsLimit\"> = {}\n): CameraKitSource => {\n let width = 0;\n let height = 0;\n let shouldProcessFrame = true;\n\n // We require an auxiliary canvas that we can use to read back pixel data (unless we're in YUV mode, in which case\n // we use LensCore to convert between formats and we don't need this canvas).\n const imageReaderCanvas = document.createElement(\"canvas\");\n const imageReader2D = imageReaderCanvas.getContext(\"2d\");\n\n const subscriber: CameraKitSourceSubscriber = {\n onAttach: (source, lensCore, reportError) => {\n const outputs = lensCore.getOutputCanvases();\n const output = {\n live: outputs[lensCore.CanvasType.Preview.value],\n capture: outputs[lensCore.CanvasType.Capture.value],\n };\n\n const processFrame = (source: CameraKitSource, lensCore: LensCore, reportError: (error: Error) => void) =>\n requestAnimationFrame(async () => {\n if (!shouldProcessFrame) return;\n try {\n await sourceFunction(({ format, imageData, timestampMillis }) => {\n // TODO: with processFrame promisified, we don't really need to create a wrapper promise\n const frameOutput = new Promise<FrameOutput>(async (resolve, reject) => {\n const inputFrame = await getImageBitmap(imageData, format ?? \"rgb\");\n if (inputFrame.width !== width || inputFrame.height !== height) {\n width = imageReaderCanvas.width = inputFrame.width;\n height = imageReaderCanvas.height = inputFrame.height;\n // We don't await this promise, because we want to continue to process frames and\n // let LensCore manage the concurrency between setting resolution and processing a\n // frame.\n source.setRenderSize(width, height);\n }\n lensCore\n .processFrame({ inputFrame, timestampMillis })\n .then(async () => {\n // Closing releases graphics resources associated with the frame, now that is\n // has been processed.\n inputFrame.close();\n\n switch (format ?? \"rgb\") {\n case \"nv12\":\n case \"yuv\":\n const [live, capture] = await Promise.all([\n getYUVImageData(output.live, lensCore),\n getYUVImageData(output.capture, lensCore),\n ]).catch((error) => {\n reject(error);\n return [undefined, undefined] as const;\n });\n // if either of these is undefined, we'll have already rejected\n // the promise, so we can return.\n if (!live || !capture) return;\n return resolve({ live, capture });\n case \"rgb\":\n return resolve({\n live: getRGBImageData(output.live, imageReader2D),\n capture: getRGBImageData(output.capture, imageReader2D),\n });\n }\n })\n .catch((error) => {\n inputFrame.close();\n reject(error);\n });\n });\n // Even if there's an error processing the frame, we do want to attempt to process the next\n // frame. We expect `sourceFunction` to handle a rejected `frameOutput` Promise.\n frameOutput.finally(() => processFrame(source, lensCore, reportError));\n return frameOutput;\n });\n } catch (error) {\n reportError(\n new Error(\n \"Failure to process frame, which was not handled by the provided \" +\n `MediaSourceFunction ${sourceFunction.name ?? \"anonymous\"}.`,\n { cause: error }\n )\n );\n }\n });\n processFrame(source, lensCore, reportError);\n },\n onDetach: () => {\n shouldProcessFrame = false;\n },\n };\n\n return new CameraKitSource({ useManualFrameProcessing: true }, subscriber, options);\n};\n"]}
@@ -63,9 +63,13 @@ export function createUserMediaSource(constraints = { video: true }, options = {
63
63
  * @category Rendering
64
64
  */
65
65
  export function createMediaStreamSource(stream, options = {}) {
66
- const optionsNotNull = Object.assign(Object.assign({}, defaultOptions), options);
67
- const { width, height } = stream.getVideoTracks().length > 0 ? stream.getVideoTracks()[0].getSettings() : { width: 0, height: 0 };
68
- const enableSourceAudio = stream.getAudioTracks().length > 0 && !optionsNotNull.disableSourceAudio;
66
+ var _a;
67
+ const { width, height, facingMode } = stream.getVideoTracks().length > 0
68
+ ? stream.getVideoTracks()[0].getSettings()
69
+ : { width: 0, height: 0, facingMode: undefined };
70
+ const detectedCameraType = facingMode === "user" || facingMode === "environment" ? facingMode : undefined;
71
+ const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaultOptions), options), { cameraType: (_a = options.cameraType) !== null && _a !== void 0 ? _a : detectedCameraType });
72
+ const enableSourceAudio = stream.getAudioTracks().length > 0 && !optionsWithDefaults.disableSourceAudio;
69
73
  const simulateStereoAudio = true;
70
74
  const sampleRate = 44100;
71
75
  let audioContext = undefined;
@@ -94,17 +98,14 @@ export function createMediaStreamSource(stream, options = {}) {
94
98
  onAttach: (source, lensCore, reportError) => __awaiter(this, void 0, void 0, function* () {
95
99
  if (width !== undefined && height !== undefined)
96
100
  yield source.setRenderSize(width, height);
97
- yield source.setTransform(optionsNotNull.transform);
101
+ yield source.setTransform(optionsWithDefaults.transform);
98
102
  if (enableSourceAudio) {
99
103
  // Audio paramters set has to be called before lens is applied
100
- lensCore.setAudioParameters({
104
+ yield lensCore.setAudioParameters({
101
105
  parameters: {
102
106
  numChannels: simulateStereoAudio ? 2 : 1,
103
107
  sampleRate,
104
108
  },
105
- onFailure: (error) => {
106
- reportError(error);
107
- },
108
109
  });
109
110
  try {
110
111
  // There is a possibility of the onAttach method being called twice in a row due to a bug.
@@ -146,12 +147,7 @@ export function createMediaStreamSource(stream, options = {}) {
146
147
  const rightSamples = e.data.buffer[0].length > 1 ? e.data.buffer[0][1] : leftSamples.slice();
147
148
  inputBuffers.push(rightSamples);
148
149
  }
149
- lensCore.processAudioSampleBuffer({
150
- input: inputBuffers,
151
- onFailure: (error) => {
152
- reportError(error);
153
- },
154
- });
150
+ lensCore.processAudioSampleBuffer({ input: inputBuffers }).catch(reportError);
155
151
  }
156
152
  };
157
153
  }
@@ -175,6 +171,6 @@ export function createMediaStreamSource(stream, options = {}) {
175
171
  audioContext = undefined;
176
172
  }
177
173
  }),
178
- }, options);
174
+ }, optionsWithDefaults);
179
175
  }
180
176
  //# sourceMappingURL=MediaStreamSource.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"MediaStreamSource.js","sourceRoot":"","sources":["../../src/media-sources/MediaStreamSource.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,eAAe,EAA0B,MAAM,mBAAmB,CAAC;AAE5E,MAAM,cAAc,GAA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,YAAY,GACd,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;oCAC5E,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;iCACnC;gCAED,QAAQ,CAAC,wBAAwB,CAAC;oCAC9B,KAAK,EAAE,YAAY;oCACnB,SAAS,EAAE,CAAC,KAAY,EAAE,EAAE;wCACxB,WAAW,CAAC,KAAK,CAAC,CAAC;oCACvB,CAAC;iCACJ,CAAC,CAAC;6BACN;wBACL,CAAC,CAAC;qBACL;gBACL,CAAC,CAAC;qBACD,KAAK,CAAC,CAAC,KAAY,EAAE,EAAE;oBACpB,WAAW,CAAC,KAAK,CAAC,CAAC;gBACvB,CAAC,CAAC,CAAC;aACV;QACL,CAAC,CAAA;QACD,QAAQ,EAAE,CAAO,WAAW,EAAE,EAAE;YAC5B,IAAI,OAAO,EAAE;gBACT,YAAY,CAAC,OAAO,CAAC,CAAC;gBACtB,OAAO,GAAG,SAAS,CAAC;aACvB;YACD,IAAI,WAAW,EAAE;gBACb,WAAW,CAAC,UAAU,EAAE,CAAC;gBACzB,WAAW,GAAG,SAAS,CAAC;aAC3B;YACD,IAAI,YAAY,EAAE;gBACd,MAAM,iBAAiB,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;gBACzD,YAAY,GAAG,SAAS,CAAC;aAC5B;QACL,CAAC,CAAA;KACJ,EACD,OAAO,CACV,CAAC;AACN,CAAC","sourcesContent":["import { ensureError } from \"../common/errorHelpers\";\nimport { Transform2D } from \"../transforms\";\nimport { CameraKitSource, CameraKitSourceOptions } from \"./CameraKitSource\";\n\nconst defaultOptions: MediaStreamSourceOptions = {\n transform: Transform2D.Identity,\n disableSourceAudio: false,\n};\n\nfunction closeWorklet(worklet: AudioWorkletNode | undefined) {\n if (!worklet) return;\n worklet.port.close();\n worklet.port.onmessage = null;\n worklet.disconnect();\n}\n\nasync function closeAudioContext(audioContext: AudioContext | undefined) {\n if (!audioContext || audioContext.state === \"closed\") return;\n return audioContext.close();\n}\n\n/** @category Rendering */\nexport interface MediaStreamSourceOptions {\n transform: Transform2D;\n disableSourceAudio: boolean; // defaults to false\n}\n\n/**\n * Create a {@link CameraKitSource} from a user's media device -- this calls\n * [MediaDevices.getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) to get a\n * MediaStream and then calls {@link createMediaStreamSource}.\n *\n * @param constraints Specify contraints used to get a MediaStream from a media device. By default we simply request\n * a video stream.\n * @param options\n * @param options.transform By default we horizontally mirror the video stream. The most common use-case is to obtain a\n * stream from a front-facing web cam, which requires mirroring to be viewed naturally.\n * @param options.cameraType By default we set this to 'front' to indicate a camera pointed at the user (e.g. a webcam).\n * @param options.fpsLimit By default we set no limit on FPS – if the source device has a known FPS setting this limit\n * may prevent CameraKit from using more compute resources than strictly necessary.\n * @returns A Promise, resolving to {@link CameraKitSource}\n *\n * @category Rendering\n *\n * @deprecated The helper will be removed in one of the future releases.\n * Consumer apps are responsible for acquiring a media stream,\n * which can then be supplied to {@link createMediaStreamSource}.\n */\nexport async function createUserMediaSource(\n constraints: MediaStreamConstraints = { video: true },\n options: CameraKitSourceOptions<MediaStreamSourceOptions> = {}\n): Promise<CameraKitSource> {\n const stream = await navigator.mediaDevices.getUserMedia(constraints);\n return createMediaStreamSource(stream, { transform: Transform2D.MirrorX, cameraType: \"front\", ...options });\n}\n\n/**\n * Create a {@link CameraKitSource} from any\n * [MediaStream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream).\n *\n * @param stream Any MediaStream, such as obtained via `canvas.captureStream()` or `mediaDevices.getUserMedia()`.\n * @param options\n * @param options.transform We apply no transformation by default.\n * @param options.disableSourceAudio By default we pass audio to lens. Settings this to true will disable sending audio\n * to the lens.\n * @param options.cameraType By default we set this to 'user', which is the camera type most Lenses expect.\n * @param options.fpsLimit By default we set no limit on FPS – if the MediaStream has a known FPS setting this limit\n * may prevent CameraKit from using more compute resources than strictly necessary.\n *\n * @category Rendering\n */\nexport function createMediaStreamSource(\n stream: MediaStream,\n options: CameraKitSourceOptions<MediaStreamSourceOptions> = {}\n): CameraKitSource {\n const optionsNotNull = {\n ...defaultOptions,\n ...options,\n };\n\n const { width, height } =\n stream.getVideoTracks().length > 0 ? stream.getVideoTracks()[0].getSettings() : { width: 0, height: 0 };\n const enableSourceAudio: boolean = stream.getAudioTracks().length > 0 && !optionsNotNull.disableSourceAudio;\n\n const simulateStereoAudio = true;\n const sampleRate: number = 44100;\n\n let audioContext: AudioContext | undefined = undefined;\n let audioSource: MediaStreamAudioSourceNode | undefined = undefined;\n let worklet: AudioWorkletNode | undefined = undefined;\n let microphoneRecorderUrl: string;\n\n if (enableSourceAudio) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_AudioWorklet\n const microphoneRecorderWorklet = `\n class MicrophoneWorkletProcessor extends AudioWorkletProcessor {\n process(inputs, outputs, parameters) {\n this.port.postMessage({\n eventType: 'data',\n buffer: inputs\n });\n return true;\n }\n }\n registerProcessor('microphone-worklet', MicrophoneWorkletProcessor);`;\n const microphoneRecorderBlob = new Blob([microphoneRecorderWorklet], {\n type: \"application/javascript\",\n });\n microphoneRecorderUrl = URL.createObjectURL(microphoneRecorderBlob);\n }\n\n return new CameraKitSource(\n { media: stream },\n {\n onAttach: async (source, lensCore, reportError) => {\n if (width !== undefined && height !== undefined) await source.setRenderSize(width, height);\n await source.setTransform(optionsNotNull.transform);\n\n if (enableSourceAudio) {\n // Audio paramters set has to be called before lens is applied\n lensCore.setAudioParameters({\n parameters: {\n numChannels: simulateStereoAudio ? 2 : 1,\n sampleRate,\n },\n onFailure: (error: Error) => {\n reportError(error);\n },\n });\n\n try {\n // There is a possibility of the onAttach method being called twice in a row due to a bug.\n // To ensure there are not leaks, it is better to close any existing connections.\n closeWorklet(worklet);\n audioSource?.disconnect();\n await closeAudioContext(audioContext);\n } catch (error) {\n // We still want to continue if anything above failed\n reportError(ensureError(error));\n }\n\n audioContext = new AudioContext();\n audioSource = audioContext.createMediaStreamSource(stream);\n const scopedAudioSource = audioSource;\n audioContext.audioWorklet\n .addModule(microphoneRecorderUrl)\n .then(() => {\n if (audioContext) {\n worklet = new AudioWorkletNode(audioContext, \"microphone-worklet\");\n scopedAudioSource.connect(worklet);\n worklet.connect(audioContext.destination);\n // NOTE: We subscribe to messages here, and they will continue to arrive\n // even after audioContext.close() is called. To disconnect the audio worklets\n // created here, we need to track two variables - worklet and audioSource.\n // By calling disconnect() on them, we can properly\n // disconnect the audio worklets.\n worklet.port.onmessage = (e) => {\n if (e.data.eventType === \"data\") {\n // developer.mozilla.org/en-US/docs/Web/API/AudioWorkletProcessor/process\n // inputs[n][m] is the list of samples in the n-th input at the m-th channel.\n const leftSamples = e.data.buffer[0][0] as Float32Array;\n\n // Firefox might have leftSamples undefined:\n // https://jira.sc-corp.net/browse/CAMKIT-5189\n if (!leftSamples) return;\n\n let inputBuffers = [leftSamples];\n if (simulateStereoAudio) {\n const rightSamples =\n e.data.buffer[0].length > 1 ? e.data.buffer[0][1] : leftSamples.slice();\n inputBuffers.push(rightSamples);\n }\n\n lensCore.processAudioSampleBuffer({\n input: inputBuffers,\n onFailure: (error: Error) => {\n reportError(error);\n },\n });\n }\n };\n }\n })\n .catch((error: Error) => {\n reportError(error);\n });\n }\n },\n onDetach: async (reportError) => {\n if (worklet) {\n closeWorklet(worklet);\n worklet = undefined;\n }\n if (audioSource) {\n audioSource.disconnect();\n audioSource = undefined;\n }\n if (audioContext) {\n await closeAudioContext(audioContext).catch(reportError);\n audioContext = undefined;\n }\n },\n },\n options\n );\n}\n"]}
1
+ {"version":3,"file":"MediaStreamSource.js","sourceRoot":"","sources":["../../src/media-sources/MediaStreamSource.ts"],"names":[],"mappings":";AAAA,OAAO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aAC5B;QACL,CAAC,CAAA;KACJ,EACD,mBAAmB,CACtB,CAAC;AACN,CAAC","sourcesContent":["import { ensureError } from \"../common/errorHelpers\";\nimport { Transform2D } from \"../transforms\";\nimport { CameraKitSource, CameraKitSourceOptions } from \"./CameraKitSource\";\n\nconst defaultOptions: MediaStreamSourceOptions = {\n transform: Transform2D.Identity,\n disableSourceAudio: false,\n};\n\nfunction closeWorklet(worklet: AudioWorkletNode | undefined) {\n if (!worklet) return;\n worklet.port.close();\n worklet.port.onmessage = null;\n worklet.disconnect();\n}\n\nasync function closeAudioContext(audioContext: AudioContext | undefined) {\n if (!audioContext || audioContext.state === \"closed\") return;\n return audioContext.close();\n}\n\n/** @category Rendering */\nexport interface MediaStreamSourceOptions {\n transform: Transform2D;\n disableSourceAudio: boolean; // defaults to false\n}\n\n/**\n * Create a {@link CameraKitSource} from a user's media device -- this calls\n * [MediaDevices.getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) to get a\n * MediaStream and then calls {@link createMediaStreamSource}.\n *\n * @param constraints Specify contraints used to get a MediaStream from a media device. By default we simply request\n * a video stream.\n * @param options\n * @param options.transform By default we horizontally mirror the video stream. The most common use-case is to obtain a\n * stream from a front-facing web cam, which requires mirroring to be viewed naturally.\n * @param options.cameraType By default we set this to 'front' to indicate a camera pointed at the user (e.g. a webcam).\n * @param options.fpsLimit By default we set no limit on FPS – if the source device has a known FPS setting this limit\n * may prevent CameraKit from using more compute resources than strictly necessary.\n * @returns A Promise, resolving to {@link CameraKitSource}\n *\n * @category Rendering\n *\n * @deprecated The helper will be removed in one of the future releases.\n * Consumer apps are responsible for acquiring a media stream,\n * which can then be supplied to {@link createMediaStreamSource}.\n */\nexport async function createUserMediaSource(\n constraints: MediaStreamConstraints = { video: true },\n options: CameraKitSourceOptions<MediaStreamSourceOptions> = {}\n): Promise<CameraKitSource> {\n const stream = await navigator.mediaDevices.getUserMedia(constraints);\n return createMediaStreamSource(stream, { transform: Transform2D.MirrorX, cameraType: \"front\", ...options });\n}\n\n/**\n * Create a {@link CameraKitSource} from any\n * [MediaStream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream).\n *\n * @param stream Any MediaStream, such as obtained via `canvas.captureStream()` or `mediaDevices.getUserMedia()`.\n * @param options\n * @param options.transform We apply no transformation by default.\n * @param options.disableSourceAudio By default we pass audio to lens. Settings this to true will disable sending audio\n * to the lens.\n * @param options.cameraType By default we set this to 'user', which is the camera type most Lenses expect.\n * @param options.fpsLimit By default we set no limit on FPS – if the MediaStream has a known FPS setting this limit\n * may prevent CameraKit from using more compute resources than strictly necessary.\n *\n * @category Rendering\n */\nexport function createMediaStreamSource(\n stream: MediaStream,\n options: CameraKitSourceOptions<MediaStreamSourceOptions> = {}\n): CameraKitSource {\n const { width, height, facingMode } =\n stream.getVideoTracks().length > 0\n ? stream.getVideoTracks()[0].getSettings()\n : { width: 0, height: 0, facingMode: undefined };\n\n const detectedCameraType = facingMode === \"user\" || facingMode === \"environment\" ? facingMode : undefined;\n\n const optionsWithDefaults = {\n ...defaultOptions,\n ...options,\n cameraType: options.cameraType ?? detectedCameraType,\n };\n\n const enableSourceAudio: boolean = stream.getAudioTracks().length > 0 && !optionsWithDefaults.disableSourceAudio;\n\n const simulateStereoAudio = true;\n const sampleRate: number = 44100;\n\n let audioContext: AudioContext | undefined = undefined;\n let audioSource: MediaStreamAudioSourceNode | undefined = undefined;\n let worklet: AudioWorkletNode | undefined = undefined;\n let microphoneRecorderUrl: string;\n\n if (enableSourceAudio) {\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_AudioWorklet\n const microphoneRecorderWorklet = `\n class MicrophoneWorkletProcessor extends AudioWorkletProcessor {\n process(inputs, outputs, parameters) {\n this.port.postMessage({\n eventType: 'data',\n buffer: inputs\n });\n return true;\n }\n }\n registerProcessor('microphone-worklet', MicrophoneWorkletProcessor);`;\n const microphoneRecorderBlob = new Blob([microphoneRecorderWorklet], {\n type: \"application/javascript\",\n });\n microphoneRecorderUrl = URL.createObjectURL(microphoneRecorderBlob);\n }\n\n return new CameraKitSource(\n { media: stream },\n {\n onAttach: async (source, lensCore, reportError) => {\n if (width !== undefined && height !== undefined) await source.setRenderSize(width, height);\n await source.setTransform(optionsWithDefaults.transform);\n\n if (enableSourceAudio) {\n // Audio paramters set has to be called before lens is applied\n await lensCore.setAudioParameters({\n parameters: {\n numChannels: simulateStereoAudio ? 2 : 1,\n sampleRate,\n },\n });\n\n try {\n // There is a possibility of the onAttach method being called twice in a row due to a bug.\n // To ensure there are not leaks, it is better to close any existing connections.\n closeWorklet(worklet);\n audioSource?.disconnect();\n await closeAudioContext(audioContext);\n } catch (error) {\n // We still want to continue if anything above failed\n reportError(ensureError(error));\n }\n\n audioContext = new AudioContext();\n audioSource = audioContext.createMediaStreamSource(stream);\n const scopedAudioSource = audioSource;\n audioContext.audioWorklet\n .addModule(microphoneRecorderUrl)\n .then(() => {\n if (audioContext) {\n worklet = new AudioWorkletNode(audioContext, \"microphone-worklet\");\n scopedAudioSource.connect(worklet);\n worklet.connect(audioContext.destination);\n // NOTE: We subscribe to messages here, and they will continue to arrive\n // even after audioContext.close() is called. To disconnect the audio worklets\n // created here, we need to track two variables - worklet and audioSource.\n // By calling disconnect() on them, we can properly\n // disconnect the audio worklets.\n worklet.port.onmessage = (e) => {\n if (e.data.eventType === \"data\") {\n // developer.mozilla.org/en-US/docs/Web/API/AudioWorkletProcessor/process\n // inputs[n][m] is the list of samples in the n-th input at the m-th channel.\n const leftSamples = e.data.buffer[0][0] as Float32Array;\n\n // Firefox might have leftSamples undefined:\n // https://jira.sc-corp.net/browse/CAMKIT-5189\n if (!leftSamples) return;\n\n let inputBuffers = [leftSamples];\n if (simulateStereoAudio) {\n const rightSamples =\n e.data.buffer[0].length > 1 ? e.data.buffer[0][1] : leftSamples.slice();\n inputBuffers.push(rightSamples);\n }\n\n lensCore.processAudioSampleBuffer({ input: inputBuffers }).catch(reportError);\n }\n };\n }\n })\n .catch((error: Error) => {\n reportError(error);\n });\n }\n },\n onDetach: async (reportError) => {\n if (worklet) {\n closeWorklet(worklet);\n worklet = undefined;\n }\n if (audioSource) {\n audioSource.disconnect();\n audioSource = undefined;\n }\n if (audioContext) {\n await closeAudioContext(audioContext).catch(reportError);\n audioContext = undefined;\n }\n },\n },\n optionsWithDefaults\n );\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { __awaiter } from "tslib";
2
2
  import { v4 } from "uuid";
3
- import { catchError, from, of, switchMap, take } from "rxjs";
4
- import { cameraKitUserAgent as userAgent } from "../common/cameraKitUserAgent";
3
+ import { catchError, combineLatestWith, from, fromEvent, map, merge, of, switchMap, take } from "rxjs";
5
4
  import { entries } from "../common/entries";
6
5
  import { Injectable } from "../dependency-injection/Injectable";
7
6
  import { createBatchingHandler } from "../handlers/batchingHandler";
@@ -15,6 +14,7 @@ import { remoteConfigurationFactory } from "../remote-configuration/remoteConfig
15
14
  import { IndexedDBPersistence } from "../persistence/IndexedDBPersistence";
16
15
  import { ExpiringPersistence } from "../persistence/ExpiringPersistence";
17
16
  import { convertDaysToSeconds } from "../common/time";
17
+ import { getPlatformInfo } from "../platform/platformInfo";
18
18
  import { metricsHandlerFactory } from "./metricsHandler";
19
19
  import { metricsEventTargetFactory } from "./metricsEventTarget";
20
20
  const logger = getLogger("BusinessEventsReporter");
@@ -59,7 +59,7 @@ const getOrGenerateVendorUuid = (persistence) => __awaiter(void 0, void 0, void
59
59
  throw new Error("Failed to generate vendor UUID");
60
60
  }
61
61
  });
62
- function listenAndReport(metricsEventTarget, metricsHandler, pageVisibility, eventHandlers, apiHostname, appVendorUuid) {
62
+ function listenAndReport(metricsEventTarget, metricsHandler, pageVisibility, eventHandlers, apiHostname, appVendorAndPartnerUuid) {
63
63
  const sessionId = v4();
64
64
  logger.log(`Session ID: ${sessionId}`);
65
65
  // Blizzard convention is to start the sequenceId at 1.
@@ -92,54 +92,75 @@ function listenAndReport(metricsEventTarget, metricsHandler, pageVisibility, eve
92
92
  maxBatchAge: BUSINESS_EVENT_BATCH_MAX_AGE_MS,
93
93
  pageVisibility,
94
94
  })).handler;
95
- const makeBlizzardEvent = (event) => {
95
+ const makeBlizzardEvent = (event, appVendorUuid, partnerUuid) => {
96
96
  var _a;
97
- const deviceConnectivity = (_a = connectivityTypeMapping[userAgent.connectionType]) !== null && _a !== void 0 ? _a : blizzard.CameraKitConnectivityType.CAMERA_KIT_CONNECTIVITY_TYPE_UNKNOWN;
97
+ const { sdkShortVersion, sdkLongVersion, lensCore, locale, origin, deviceModel, connectionType } = getPlatformInfo();
98
+ const deviceConnectivity = (_a = connectivityTypeMapping[connectionType]) !== null && _a !== void 0 ? _a : blizzard.CameraKitConnectivityType.CAMERA_KIT_CONNECTIVITY_TYPE_UNKNOWN;
98
99
  return Object.assign(Object.assign({}, event), { cameraKitEventBase: blizzard.CameraKitEventBase.fromPartial({
99
100
  kitEventBase: blizzard.KitEventBase.fromPartial({
100
- locale: userAgent.locale,
101
+ locale,
101
102
  kitVariant: blizzard.KitType.CAMERA_KIT_WEB,
102
- kitVariantVersion: userAgent.sdkShortVersion,
103
+ kitVariantVersion: sdkShortVersion,
103
104
  kitClientTimestampMillis: Date.now(),
104
105
  }),
105
106
  deviceCluster: 0,
106
- cameraKitVersion: userAgent.sdkLongVersion,
107
- lensCoreVersion: userAgent.lensCoreVersion,
108
- deviceModel: userAgent.deviceModel,
107
+ cameraKitVersion: sdkLongVersion,
108
+ lensCoreVersion: lensCore.version,
109
+ deviceModel,
109
110
  cameraKitVariant: blizzard.CameraKitVariant.CAMERA_KIT_VARIANT_PARTNER,
110
111
  cameraKitFlavor: blizzard.CameraKitFlavor.CAMERA_KIT_FLAVOR_DEBUG,
111
112
  // We overload appId, using the origin instead because it's nice and human-readable (our backed adds
112
113
  // the true appId as oauth_client_id before forwarding events to Blizzard).
113
- appId: userAgent.origin,
114
+ appId: origin,
114
115
  deviceConnectivity,
115
- sessionId: sessionId,
116
+ sessionId,
116
117
  appVendorUuid,
118
+ partnerUuid,
117
119
  }) });
118
120
  };
119
121
  const sendServerEvent = (eventName, eventData) => {
122
+ const { osName: osType, osVersion } = getPlatformInfo();
120
123
  return handler(blizzard.ServerEvent.fromPartial({
121
124
  eventName,
122
- osType: userAgent.osType,
123
- osVersion: userAgent.osVersion,
125
+ osType,
126
+ osVersion,
124
127
  maxSequenceIdOnInstance: 0,
125
128
  sequenceId: sequenceId++,
126
129
  eventData,
127
130
  }));
128
131
  };
129
- entries(eventHandlers).forEach(([eventType, createEventData]) => {
130
- metricsEventTarget.addEventListener(eventType, ({ detail }) => {
131
- // Safety: When iterating over object keys in a mapped type, we lose the association between the key type
132
- // and the value type at each iteration, the key type is a union of all possible keys and the value type
133
- // is a union of all possible values. When the value is a function with an argument, and that argument
134
- // depends on the key type (which is a union), the contravariance of the argument type means that the union
135
- // becomes an intersection. In our case here, this means the compiler expects each argument to contain all
136
- // properties from all event types. The cast is safe because the mapped `EventHandlers` type ensures that
137
- // `createEventData` takes an argument of the type corresponding its key's `eventType`'s event detail.
138
- const [eventName, eventData] = createEventData(makeBlizzardEvent(detail));
139
- sendServerEvent(eventName, eventData);
140
- });
132
+ // Add event listeners for each event type and turn those listeners into Observables
133
+ const metricsEvents = entries(eventHandlers).map(([eventType, createEventData]) => fromEvent(metricsEventTarget, eventType).pipe(map((event) => ({ event, createEventData }))));
134
+ // Subscribe to all the metrics events and combine them with the app/partner IDs obtained
135
+ // from remote configuration -- this means we'll queue up any metrics events that occur
136
+ // before remote config is downloaded, and send them once that config is available.
137
+ merge(...metricsEvents)
138
+ .pipe(combineLatestWith(appVendorAndPartnerUuid))
139
+ .subscribe(([{ event, createEventData }, { appVendorUuid, partnerUuid }]) => {
140
+ // Safety: When iterating over object keys in a mapped type, we lose the association between the key type
141
+ // and the value type – at each iteration, the key type is a union of all possible keys and the value type
142
+ // is a union of all possible values. When the value is a function with an argument, and that argument
143
+ // depends on the key type (which is a union), the contravariance of the argument type means that the union
144
+ // becomes an intersection. In our case here, this means the compiler expects each argument to contain all
145
+ // properties from all event types. The cast is safe because the mapped `EventHandlers` type ensures that
146
+ // `createEventData` takes an argument of the type corresponding its key's `eventType`'s event detail.
147
+ const [eventName, eventData] = createEventData(makeBlizzardEvent(event.detail, appVendorUuid, partnerUuid));
148
+ sendServerEvent(eventName, eventData);
141
149
  });
142
150
  }
151
+ function getAppVendorAndPartnerUuid(configuration, remoteConfiguration) {
152
+ const vendorAnalyticsPersistence = new ExpiringPersistence(() => vendorUuidExpiry, new IndexedDBPersistence({ databaseName: "SessionHistory" }));
153
+ return remoteConfiguration.getInitializationConfig().pipe(take(1), switchMap(({ appVendorUuidOptIn }) => {
154
+ const partnerUuid = configuration.analyticsId;
155
+ if (appVendorUuidOptIn) {
156
+ return from(getOrGenerateVendorUuid(vendorAnalyticsPersistence)).pipe(map((appVendorUuid) => ({ appVendorUuid, partnerUuid })));
157
+ }
158
+ return of({ appVendorUuid: undefined, partnerUuid });
159
+ }), catchError((error) => {
160
+ logger.warn(`Failed to retrieve or generate vendor UUID.`, error);
161
+ return of({ appVendorUuid: undefined, partnerUuid: configuration.analyticsId });
162
+ }));
163
+ }
143
164
  export const businessEventsReporterFactory = Injectable("businessEventsReporter", [
144
165
  metricsEventTargetFactory.token,
145
166
  metricsHandlerFactory.token,
@@ -147,87 +168,72 @@ export const businessEventsReporterFactory = Injectable("businessEventsReporter"
147
168
  configurationToken,
148
169
  remoteConfigurationFactory.token,
149
170
  ], (metricsEventTarget, metricsHandler, pageVisibility, configuration, remoteConfiguration) => {
150
- const vendorAnalyticsPersistence = new ExpiringPersistence(() => vendorUuidExpiry, new IndexedDBPersistence({ databaseName: "SessionHistory" }));
151
- remoteConfiguration
152
- .getInitializationConfig()
153
- .pipe(take(1), switchMap(({ appVendorUuidOptIn }) => {
154
- if (appVendorUuidOptIn) {
155
- return from(getOrGenerateVendorUuid(vendorAnalyticsPersistence));
156
- }
157
- return of(undefined);
158
- }), catchError((error) => {
159
- logger.warn(`Failed to retrieve or generate vendor UUID.`, error);
160
- return of(undefined);
161
- }))
162
- .subscribe({
163
- next: (appVendorUuid) => {
164
- /**
165
- * This defines a mapping from a business event's external name (the name we document in public
166
- * API docs), to its internal representation as a Blizzard ServerEvent.
167
- *
168
- * It is important that we do this, since the naming of these internal business events are
169
- * unintuitive and will not make sense to SDK users.
170
- *
171
- * To specify the internal event, we must give the ServerEvent's eventName, the specific property
172
- * name which contains the event data (this is a "oneof" property on ServerEvent), and use the
173
- * correct event type's `fromPartial` method (this is generated from the ServerEvent protobuf).
174
- *
175
- * These events are documented here:
176
- * https://docs.google.com/document/d/1-kSzFWCWw9Qo3D08FR1_cqeHTsUtk9p3p3uOptzWDTY/
177
- *
178
- * They are defined in code here:
179
- * https://github.sc-corp.net/Snapchat/snapchat/tree/master/blizzard/schema/blizzard-schema/
180
- * codeGen/src/main/java/com/snapchat/analytics/schema/events/cameraKit
181
- */
182
- listenAndReport(metricsEventTarget, metricsHandler, pageVisibility, {
183
- assetDownload: (event) => [
184
- "CAMERA_KIT_ASSET_DOWNLOAD",
185
- { cameraKitAssetDownload: blizzard.CameraKitAssetDownload.fromPartial(event) },
186
- ],
187
- assetValidationFailed: (event) => [
188
- "CAMERA_KIT_ASSET_VALIDATION_FAILED",
189
- {
190
- cameraKitAssetValidationFailed: blizzard.CameraKitAssetValidationFailed.fromPartial(event),
191
- },
192
- ],
193
- benchmarkComplete: (event) => [
194
- "CAMERA_KIT_WEB_BENCHMARK_COMPLETE",
195
- {
196
- cameraKitWebBenchmarkComplete: blizzard.CameraKitWebBenchmarkComplete.fromPartial(event),
197
- },
198
- ],
199
- exception: (event) => [
200
- "CAMERA_KIT_EXCEPTION",
201
- { cameraKitException: blizzard.CameraKitException.fromPartial(event) },
202
- ],
203
- legalPrompt: (event) => [
204
- "CAMERA_KIT_LEGAL_PROMPT",
205
- { cameraKitLegalPrompt: blizzard.CameraKitLegalPrompt.fromPartial(event) },
206
- ],
207
- lensDownload: (event) => [
208
- "CAMERA_KIT_LENS_DOWNLOAD",
209
- { cameraKitLensDownload: blizzard.CameraKitLensDownload.fromPartial(event) },
210
- ],
211
- lensView: (event) => [
212
- "CAMERA_KIT_WEB_LENS_SWIPE",
213
- { cameraKitWebLensSwipe: blizzard.CameraKitWebLensSwipe.fromPartial(event) },
214
- ],
215
- lensWait: (event) => [
216
- "CAMERA_KIT_LENS_SPIN",
217
- { cameraKitLensSpin: blizzard.CameraKitLensSpin.fromPartial(event) },
218
- ],
219
- lensContentValidationFailed: (event) => [
220
- "CAMERA_KIT_LENS_CONTENT_VALIDATION_FAILED",
221
- {
222
- cameraKitLensContentValidationFailed: blizzard.CameraKitLensContentValidationFailed.fromPartial(event),
223
- },
224
- ],
225
- session: (event) => [
226
- "CAMERA_KIT_SESSION",
227
- { cameraKitSession: blizzard.CameraKitSession.fromPartial(event) },
228
- ],
229
- }, configuration.apiHostname, appVendorUuid);
230
- },
231
- });
171
+ const appVendorAndPartnerUuid = getAppVendorAndPartnerUuid(configuration, remoteConfiguration);
172
+ /**
173
+ * This defines a mapping from a business event's external name (the name we document in public
174
+ * API docs), to its internal representation as a Blizzard ServerEvent.
175
+ *
176
+ * It is important that we do this, since the naming of these internal business events are
177
+ * unintuitive and will not make sense to SDK users.
178
+ *
179
+ * To specify the internal event, we must give the ServerEvent's eventName, the specific property
180
+ * name which contains the event data (this is a "oneof" property on ServerEvent), and use the
181
+ * correct event type's `fromPartial` method (this is generated from the ServerEvent protobuf).
182
+ *
183
+ * These events are documented here:
184
+ * https://docs.google.com/document/d/1-kSzFWCWw9Qo3D08FR1_cqeHTsUtk9p3p3uOptzWDTY/
185
+ *
186
+ * They are defined in code here:
187
+ * https://github.sc-corp.net/Snapchat/snapchat/tree/master/blizzard/schema/blizzard-schema/
188
+ * codeGen/src/main/java/com/snapchat/analytics/schema/events/cameraKit
189
+ */
190
+ listenAndReport(metricsEventTarget, metricsHandler, pageVisibility, {
191
+ assetDownload: (event) => [
192
+ "CAMERA_KIT_ASSET_DOWNLOAD",
193
+ { cameraKitAssetDownload: blizzard.CameraKitAssetDownload.fromPartial(event) },
194
+ ],
195
+ assetValidationFailed: (event) => [
196
+ "CAMERA_KIT_ASSET_VALIDATION_FAILED",
197
+ {
198
+ cameraKitAssetValidationFailed: blizzard.CameraKitAssetValidationFailed.fromPartial(event),
199
+ },
200
+ ],
201
+ benchmarkComplete: (event) => [
202
+ "CAMERA_KIT_WEB_BENCHMARK_COMPLETE",
203
+ {
204
+ cameraKitWebBenchmarkComplete: blizzard.CameraKitWebBenchmarkComplete.fromPartial(event),
205
+ },
206
+ ],
207
+ exception: (event) => [
208
+ "CAMERA_KIT_EXCEPTION",
209
+ { cameraKitException: blizzard.CameraKitException.fromPartial(event) },
210
+ ],
211
+ legalPrompt: (event) => [
212
+ "CAMERA_KIT_LEGAL_PROMPT",
213
+ { cameraKitLegalPrompt: blizzard.CameraKitLegalPrompt.fromPartial(event) },
214
+ ],
215
+ lensDownload: (event) => [
216
+ "CAMERA_KIT_LENS_DOWNLOAD",
217
+ { cameraKitLensDownload: blizzard.CameraKitLensDownload.fromPartial(event) },
218
+ ],
219
+ lensView: (event) => [
220
+ "CAMERA_KIT_WEB_LENS_SWIPE",
221
+ { cameraKitWebLensSwipe: blizzard.CameraKitWebLensSwipe.fromPartial(event) },
222
+ ],
223
+ lensWait: (event) => [
224
+ "CAMERA_KIT_LENS_SPIN",
225
+ { cameraKitLensSpin: blizzard.CameraKitLensSpin.fromPartial(event) },
226
+ ],
227
+ lensContentValidationFailed: (event) => [
228
+ "CAMERA_KIT_LENS_CONTENT_VALIDATION_FAILED",
229
+ {
230
+ cameraKitLensContentValidationFailed: blizzard.CameraKitLensContentValidationFailed.fromPartial(event),
231
+ },
232
+ ],
233
+ session: (event) => [
234
+ "CAMERA_KIT_SESSION",
235
+ { cameraKitSession: blizzard.CameraKitSession.fromPartial(event) },
236
+ ],
237
+ }, configuration.apiHostname, appVendorAndPartnerUuid);
232
238
  });
233
239
  //# sourceMappingURL=businessEventsReporter.js.map