@snap/camera-kit 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/LICENSE.md +5921 -1485
  2. package/README.md +1 -1
  3. package/docs/html/assets/search.js +1 -1
  4. package/docs/html/classes/CameraKit.html +7 -7
  5. package/docs/html/classes/CameraKitSession.html +17 -25
  6. package/docs/html/classes/CameraKitSource.html +15 -10
  7. package/docs/html/classes/LensPerformanceMeasurement.html +7 -7
  8. package/docs/html/classes/LensPerformanceMetrics.html +7 -7
  9. package/docs/html/classes/LensRepository.html +7 -7
  10. package/docs/html/classes/Transform2D.html +7 -7
  11. package/docs/html/classes/TypedCustomEvent.html +7 -7
  12. package/docs/html/classes/TypedEventTarget.html +7 -7
  13. package/docs/html/functions/ConcatInjectable.html +202 -0
  14. package/docs/html/functions/Injectable.html +15 -16
  15. package/docs/html/functions/bootstrapCameraKit.html +7 -7
  16. package/docs/html/functions/createExtension.html +7 -7
  17. package/docs/html/functions/createImageSource.html +7 -7
  18. package/docs/html/functions/createMediaStreamSource.html +7 -7
  19. package/docs/html/functions/createUserMediaSource.html +7 -7
  20. package/docs/html/functions/createVideoSource.html +7 -7
  21. package/docs/html/functions/estimateLensPerformance.html +7 -7
  22. package/docs/html/functions/getRequiredBootstrapURLs.html +7 -7
  23. package/docs/html/functions/lensSourcesFactory.html +17 -9
  24. package/docs/html/functions/remoteApiServicesFactory.html +7 -7
  25. package/docs/html/index.html +9 -9
  26. package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +7 -7
  27. package/docs/html/interfaces/CameraKitSourceSubscriber.html +7 -7
  28. package/docs/html/interfaces/ComputedFrameMetrics.html +7 -7
  29. package/docs/html/interfaces/CreateSessionOptions.html +7 -7
  30. package/docs/html/interfaces/EstimatedLensPerformance.html +7 -7
  31. package/docs/html/interfaces/Lens.html +7 -7
  32. package/docs/html/interfaces/LensLaunchData.html +183 -0
  33. package/docs/html/interfaces/LensSource.html +28 -46
  34. package/docs/html/interfaces/MediaStreamSourceOptions.html +7 -7
  35. package/docs/html/interfaces/Preview.html +7 -7
  36. package/docs/html/interfaces/RemoteApiRequest.html +7 -7
  37. package/docs/html/interfaces/RemoteApiResponse.html +7 -7
  38. package/docs/html/interfaces/RemoteApiService.html +7 -7
  39. package/docs/html/interfaces/Snapcode.html +7 -7
  40. package/docs/html/interfaces/UriCancelRequest.html +7 -7
  41. package/docs/html/interfaces/UriRequest.html +7 -7
  42. package/docs/html/interfaces/UriResponse.html +7 -7
  43. package/docs/html/interfaces/VideoSourceOptions.html +7 -7
  44. package/docs/html/modules.html +12 -12
  45. package/docs/html/types/AssetLoader.html +7 -7
  46. package/docs/html/types/AssetTiming.html +7 -7
  47. package/docs/html/types/BenchmarkError.html +7 -7
  48. package/docs/html/types/BootstrapError.html +7 -7
  49. package/docs/html/types/CacheKeyNotFoundError.html +7 -7
  50. package/docs/html/types/CameraKitDeviceInfo.html +7 -7
  51. package/docs/html/types/CameraKitDeviceOptions.html +7 -7
  52. package/docs/html/types/CameraKitSessionEventListener.html +7 -7
  53. package/docs/html/types/CameraKitSessionEvents.html +7 -7
  54. package/docs/html/types/CameraKitSourceError.html +7 -7
  55. package/docs/html/types/CameraKitSourceInfo.html +7 -7
  56. package/docs/html/types/CameraKitSourceOptions.html +7 -7
  57. package/docs/html/types/ConfigurationError.html +7 -7
  58. package/docs/html/types/Keyboard.html +7 -7
  59. package/docs/html/types/KeyboardEvents.html +7 -7
  60. package/docs/html/types/LegalError.html +7 -7
  61. package/docs/html/types/LensAbortError.html +7 -7
  62. package/docs/html/types/LensAssetError.html +7 -7
  63. package/docs/html/types/LensContentValidationError.html +7 -7
  64. package/docs/html/types/LensError.html +7 -7
  65. package/docs/html/types/LensExecutionError.html +7 -7
  66. package/docs/html/types/LensImagePickerError.html +7 -7
  67. package/docs/html/types/LensMetricsEvents.html +7 -7
  68. package/docs/html/types/LensPerformanceCluster.html +7 -7
  69. package/docs/html/types/LensView.html +7 -7
  70. package/docs/html/types/LensWait.html +7 -7
  71. package/docs/html/types/PersistentStoreError.html +7 -7
  72. package/docs/html/types/PlatformNotSupportedError.html +7 -7
  73. package/docs/html/types/PublicContainer.html +7 -7
  74. package/docs/html/types/RemoteApiRequestHandler.html +7 -7
  75. package/docs/html/types/RemoteApiServices.html +7 -7
  76. package/docs/html/types/RemoteApiStatus.html +7 -7
  77. package/docs/html/types/RenderTarget.html +7 -7
  78. package/docs/html/types/Uri.html +7 -7
  79. package/docs/html/types/WebGLError.html +7 -7
  80. package/docs/html/variables/extensionRequestContext.html +7 -7
  81. package/docs/md/README.md +1 -1
  82. package/docs/md/classes/CameraKit.md +1 -1
  83. package/docs/md/classes/CameraKitSession.md +11 -22
  84. package/docs/md/classes/CameraKitSource.md +11 -5
  85. package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
  86. package/docs/md/classes/LensPerformanceMetrics.md +1 -1
  87. package/docs/md/classes/LensRepository.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 +1 -1
  92. package/docs/md/interfaces/CameraKitSourceSubscriber.md +1 -1
  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 +1 -1
  97. package/docs/md/interfaces/LensLaunchData.md +53 -0
  98. package/docs/md/interfaces/LensSource.md +23 -25
  99. package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
  100. package/docs/md/interfaces/Preview.md +1 -1
  101. package/docs/md/interfaces/RemoteApiRequest.md +1 -1
  102. package/docs/md/interfaces/RemoteApiResponse.md +1 -1
  103. package/docs/md/interfaces/RemoteApiService.md +1 -1
  104. package/docs/md/interfaces/Snapcode.md +1 -1
  105. package/docs/md/interfaces/UriCancelRequest.md +1 -1
  106. package/docs/md/interfaces/UriRequest.md +1 -1
  107. package/docs/md/interfaces/UriResponse.md +1 -1
  108. package/docs/md/interfaces/VideoSourceOptions.md +1 -1
  109. package/docs/md/modules.md +125 -28
  110. package/lib/CameraKit.d.ts +14 -6
  111. package/lib/__tests__/data.d.ts +2 -2
  112. package/lib/__tests__/data.js +2 -2
  113. package/lib/__tests__/data.js.map +1 -1
  114. package/lib/bootstrapCameraKit.js +12 -3
  115. package/lib/bootstrapCameraKit.js.map +1 -1
  116. package/lib/clients/createTsProtoClient.d.ts +47 -0
  117. package/lib/clients/createTsProtoClient.js +53 -0
  118. package/lib/clients/createTsProtoClient.js.map +1 -0
  119. package/lib/clients/grpcHandler.d.ts +23 -0
  120. package/lib/clients/grpcHandler.js +87 -0
  121. package/lib/clients/grpcHandler.js.map +1 -0
  122. package/lib/clients/lensesClient.d.ts +9 -0
  123. package/lib/clients/lensesClient.js +6 -0
  124. package/lib/clients/lensesClient.js.map +1 -0
  125. package/lib/common/entries.d.ts +1 -0
  126. package/lib/common/entries.js +2 -0
  127. package/lib/common/entries.js.map +1 -1
  128. package/lib/common/result.d.ts +36 -0
  129. package/lib/common/result.js +40 -0
  130. package/lib/common/result.js.map +1 -0
  131. package/lib/common/unionBy.d.ts +28 -0
  132. package/lib/common/unionBy.js +46 -0
  133. package/lib/common/unionBy.js.map +1 -0
  134. package/lib/configuration.js +14 -1
  135. package/lib/configuration.js.map +1 -1
  136. package/lib/dependency-injection/Injectable.d.ts +67 -11
  137. package/lib/dependency-injection/Injectable.js +21 -2
  138. package/lib/dependency-injection/Injectable.js.map +1 -1
  139. package/lib/dependency-injection/RootServices.d.ts +5 -1
  140. package/lib/dependency-injection/RootServices.js.map +1 -1
  141. package/lib/environment.json +1 -1
  142. package/lib/extensions/RemoteApiServices.d.ts +1 -1
  143. package/lib/extensions/RemoteApiServices.js +7 -7
  144. package/lib/extensions/RemoteApiServices.js.map +1 -1
  145. package/lib/extensions/uriHandlersRegister.d.ts +6 -6
  146. package/lib/extensions/uriHandlersRegister.js +1 -1
  147. package/lib/extensions/uriHandlersRegister.js.map +1 -1
  148. package/lib/generated-proto/blizzard/cameraKitEvents.js.map +1 -1
  149. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.d.ts +15 -17
  150. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js +62 -69
  151. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js.map +1 -1
  152. package/lib/generated-proto/pb_schema/camera_kit/v3/export.d.ts +6 -0
  153. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js +68 -0
  154. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js.map +1 -1
  155. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.d.ts +5 -6
  156. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js +11 -25
  157. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js.map +1 -1
  158. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.d.ts +19 -14
  159. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js +145 -64
  160. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js.map +1 -1
  161. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.d.ts +2 -0
  162. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js +30 -0
  163. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js.map +1 -1
  164. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.d.ts +15 -16
  165. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js +36 -62
  166. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js.map +1 -1
  167. package/lib/generated-proto/pb_schema/camera_kit/v3/service.d.ts +1294 -12
  168. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js +200 -0
  169. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js.map +1 -1
  170. package/lib/generated-proto/pb_schema/cdp/cof/config_result.d.ts +4 -0
  171. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js +4 -0
  172. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js.map +1 -1
  173. package/lib/generated-proto/pb_schema/google/protobuf/descriptor.d.ts +39 -45
  174. package/lib/generated-proto/pb_schema/google/protobuf/descriptor.js +74 -192
  175. package/lib/generated-proto/pb_schema/google/protobuf/descriptor.js.map +1 -1
  176. package/lib/handlers/defaultFetchHandler.js +1 -5
  177. package/lib/handlers/defaultFetchHandler.js.map +1 -1
  178. package/lib/index.d.ts +3 -3
  179. package/lib/index.js +2 -6
  180. package/lib/index.js.map +1 -1
  181. package/lib/lens/Lens.d.ts +2 -12
  182. package/lib/lens/Lens.js +2 -2
  183. package/lib/lens/Lens.js.map +1 -1
  184. package/lib/lens/LensLaunchData.d.ts +37 -0
  185. package/lib/lens/LensLaunchData.js +35 -0
  186. package/lib/lens/LensLaunchData.js.map +1 -0
  187. package/lib/lens/LensRepository.d.ts +4 -7
  188. package/lib/lens/LensRepository.js +24 -35
  189. package/lib/lens/LensRepository.js.map +1 -1
  190. package/lib/lens/LensSource.d.ts +43 -0
  191. package/lib/lens/LensSource.js +42 -0
  192. package/lib/lens/LensSource.js.map +1 -0
  193. package/lib/lens/assets/LensAssetRepository.js +2 -4
  194. package/lib/lens/assets/LensAssetRepository.js.map +1 -1
  195. package/lib/lens/assets/LensAssetsProvider.d.ts +1 -1
  196. package/lib/lens/cameraKitLensSource.d.ts +16 -0
  197. package/lib/lens/cameraKitLensSource.js +59 -0
  198. package/lib/lens/cameraKitLensSource.js.map +1 -0
  199. package/lib/lens-core-module/lensCore.d.ts +2 -1
  200. package/lib/lens-core-module/lensCore.js +6 -1
  201. package/lib/lens-core-module/lensCore.js.map +1 -1
  202. package/lib/lens-core-module/lensCoreError.js +1 -1
  203. package/lib/lens-core-module/lensCoreError.js.map +1 -1
  204. package/lib/lensCoreWasmVersions.json +3 -3
  205. package/lib/media-sources/CameraKitSource.d.ts +10 -4
  206. package/lib/media-sources/CameraKitSource.js +11 -4
  207. package/lib/media-sources/CameraKitSource.js.map +1 -1
  208. package/lib/media-sources/ImageSource.js +1 -11
  209. package/lib/media-sources/ImageSource.js.map +1 -1
  210. package/lib/media-sources/MediaStreamSource.js +1 -5
  211. package/lib/media-sources/MediaStreamSource.js.map +1 -1
  212. package/lib/media-sources/VideoSource.js +1 -11
  213. package/lib/media-sources/VideoSource.js.map +1 -1
  214. package/lib/metrics/businessEventsReporter.js +1 -1
  215. package/lib/metrics/businessEventsReporter.js.map +1 -1
  216. package/lib/metrics/reporters/reportGlobalException.d.ts +7 -0
  217. package/lib/metrics/reporters/reportGlobalException.js +22 -4
  218. package/lib/metrics/reporters/reportGlobalException.js.map +1 -1
  219. package/lib/metrics/reporters/reportHttpMetrics.js +14 -0
  220. package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -1
  221. package/lib/metrics/reporters/reportLensValidationFailed.d.ts +1 -1
  222. package/lib/metrics/reporters/reportLensView.d.ts +1 -1
  223. package/lib/metrics/reporters/reportLensWait.d.ts +1 -1
  224. package/lib/metrics/reporters/reportSessionException.d.ts +1 -1
  225. package/lib/metrics/reporters/reporters.d.ts +1 -1
  226. package/lib/persistence/ExpiringPersistence.js +3 -4
  227. package/lib/persistence/ExpiringPersistence.js.map +1 -1
  228. package/lib/platform/platformInfo.js +1 -1
  229. package/lib/platform/platformInfo.js.map +1 -1
  230. package/lib/remote-configuration/cofHandler.d.ts +1 -0
  231. package/lib/remote-configuration/cofHandler.js +61 -50
  232. package/lib/remote-configuration/cofHandler.js.map +1 -1
  233. package/lib/session/CameraKitSession.d.ts +9 -11
  234. package/lib/session/CameraKitSession.js +22 -18
  235. package/lib/session/CameraKitSession.js.map +1 -1
  236. package/lib/session/CameraKitSessionEvents.d.ts +1 -1
  237. package/lib/session/CameraKitSessionEvents.js.map +1 -1
  238. package/lib/session/LensKeyboard.d.ts +7 -1
  239. package/lib/session/lensState.d.ts +3 -3
  240. package/lib/session/lensState.js +40 -15
  241. package/lib/session/lensState.js.map +1 -1
  242. package/package.json +2 -2
  243. package/docs/html/classes/LensSources.html +0 -160
  244. package/docs/html/types/LensLaunchParams.html +0 -115
  245. package/docs/md/classes/LensSources.md +0 -29
  246. package/lib/common/any.d.ts +0 -19
  247. package/lib/common/any.js +0 -53
  248. package/lib/common/any.js.map +0 -1
  249. package/lib/extensions/LensSources.d.ts +0 -58
  250. package/lib/extensions/LensSources.js +0 -54
  251. package/lib/extensions/LensSources.js.map +0 -1
  252. package/lib/lens/LensLaunchParams.d.ts +0 -19
  253. package/lib/lens/LensLaunchParams.js +0 -40
  254. package/lib/lens/LensLaunchParams.js.map +0 -1
  255. package/lib/lens/index.d.ts +0 -7
  256. package/lib/lens/index.js +0 -7
  257. package/lib/lens/index.js.map +0 -1
  258. package/lib/lens/lensEnvelopeUtil.d.ts +0 -5
  259. package/lib/lens/lensEnvelopeUtil.js +0 -19
  260. package/lib/lens/lensEnvelopeUtil.js.map +0 -1
  261. package/lib/lens/lensHttpUtil.d.ts +0 -5
  262. package/lib/lens/lensHttpUtil.js +0 -52
  263. package/lib/lens/lensHttpUtil.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"CameraKitSession.js","sourceRoot":"","sources":["../../src/session/CameraKitSession.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,EAAc,EAAE,EAAgB,SAAS,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACjG,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAQ,MAAM,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AAE7E,OAAO,EAAE,WAAW,EA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AE,UAAU,EAAE,cAAc,CAAC,CACrG,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/member-ordering */\nimport { filter, firstValueFrom, map, Observable, of, Subscription, takeUntil, tap } from \"rxjs\";\nimport { dispatch, forActions, inStates, isAction, isState } from \"@snap/state-management\";\nimport { Lens, isLens } from \"../lens\";\nimport { CanvasType, LensCore } from \"../lens-core-module\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { LensLaunchParams } from \"../lens/LensLaunchParams\";\nimport { getTypeName, guard, validate } from \"../common/validate\";\nimport { TypedEventTarget } from \"../events/TypedEventTarget\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { CameraKitDeviceInfo, CameraKitDeviceOptions, CameraKitSource } from \"../media-sources/CameraKitSource\";\nimport { cameraKitSourceError, LensExecutionError } from \"../namedErrors\";\nimport { createMediaStreamSource } from \"../media-sources/MediaStreamSource\";\nimport { createVideoSource } from \"../media-sources/VideoSource\";\nimport { getLogger, LogEntry } from \"../logger/logger\";\nimport { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { PageVisibility, pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { LensPerformanceMetrics } from \"./LensPerformanceMetrics\";\nimport { lensStateFactory, LensState } from \"./lensState\";\nimport { SessionState, sessionStateFactory } from \"./sessionState\";\nimport { Keyboard, lensKeyboardFactory, LensKeyboard } from \"./LensKeyboard\";\nimport { CameraKitSessionEvents, isPublicLensError, isSessionError } from \"./CameraKitSessionEvents\";\n\nconst logger = getLogger(\"CameraKitSession\");\nconst log = errorLoggingDecorator(logger);\n\nfunction isOptionalRenderTarget(value: unknown): value is RenderTarget | undefined {\n return value === \"live\" || value === \"capture\" || value === undefined;\n}\n\n/**\n * Enumerates the supported render targets.\n *\n * Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose\n * which render target to render, and the result for each target is available as a separate `<canvas>` element.\n *\n * @category Rendering\n * @category Lenses\n */\nexport type RenderTarget = \"live\" | \"capture\";\n\n/**\n * A CameraKitSession represents a single rendering pipeline connecting an input media source to output `<canvas>`\n * elements. When a Lens is applied to the session, CameraKit uses the Lens to transform the input media into rendered\n * output.\n *\n * CameraKitSession is the primary object that applications interact with when integrating the CameraKit SDK.\n *\n * A CameraKitSession instance is obtained by calling {@link CameraKit.createSession}.\n *\n * @example\n * ```ts\n * const cameraKit = await bootstrapCameraKit(config)\n * const session = await cameraKit.createSession()\n * ```\n *\n * @category Rendering\n * @category Lenses\n */\nexport class CameraKitSession {\n /**\n * CameraKitSession renders video output to a `<canvas>` element. In fact, each session contains two canvas outputs\n * corresponding to the RenderTargets used by Lens creators, when using LensStudio to create a Lens.\n *\n * The `live` output renders content suitable for the Lens user (e.g. it may contain additional UI elements\n * applicable only to the person applying the lens). The `capture` output renders content suitable for sharing with\n * other users (e.g. sent to the other members of a video call, or saved to disk for sharing later).\n *\n * For many lenses, these outputs are identical – but each lens is free to render differently, based on its own\n * use-case.\n */\n readonly output: {\n live: HTMLCanvasElement;\n capture: HTMLCanvasElement;\n };\n\n /**\n * Indicates whether or not the session is currently rendering. If `false`, rendering is stopped. Otherwise the\n * value indicates which output is being rendered.\n */\n playing: false | RenderTarget;\n\n /**\n * Add event listeners here to handle events which occur during the CameraKitSession.\n *\n * **Note:** Applications may want to handle the `error` event, and check the contained error type -- if the type\n * is {@link LensExecutionError}, this means the current lens was unable to render and CameraKit will automatically\n * remove the lens.\n *\n * @example\n * ```ts\n * cameraKitSession.events.addEventListener('error', ({ detail }) => {\n * if (detail.error.name === 'LensExecutionError') {\n * console.log(`Lens ${detail.lens.name} encountered an error and was removed. Please pick a different lens.`)\n * }\n * })\n * ```\n */\n readonly events = new TypedEventTarget<CameraKitSessionEvents>();\n\n /**\n * Use this to measure current lens performance.\n */\n readonly metrics: LensPerformanceMetrics;\n\n private readonly removePageVisibilityHandlers: () => void;\n private source?: CameraKitSource;\n private subscriptions: Subscription[];\n\n /**\n * @internal\n */\n constructor(\n /**\n * Use this to interact with lenses which require text input.\n */\n public readonly keyboard: Keyboard,\n\n private readonly lensCore: LensCore,\n private readonly sessionState: SessionState,\n private readonly lensState: LensState,\n logEntries: Observable<LogEntry>,\n pageVisibility: PageVisibility\n ) {\n const outputs = this.lensCore.getOutputCanvases();\n this.output = {\n live: outputs[this.lensCore.CanvasType.Preview.value],\n capture: outputs[this.lensCore.CanvasType.Capture.value],\n };\n this.playing = false;\n\n this.metrics = new LensPerformanceMetrics(this.lensCore);\n\n const removeOnHidden = pageVisibility.onPageHidden(() => this.sessionState.dispatch(\"suspend\", this));\n const removeOnVisible = pageVisibility.onPageVisible(() => this.sessionState.dispatch(\"resume\", this));\n this.removePageVisibilityHandlers = () => {\n removeOnHidden();\n removeOnVisible();\n };\n\n const sessionErrors = logEntries.pipe(\n filter((entry) => entry.level === \"error\"),\n map((entry) => entry.messages.find((e) => e instanceof Error)),\n filter(isSessionError)\n );\n\n this.subscriptions = [\n // In case of an abort error, the only option is to destroy the current session,\n // as it becomes inoperable.\n sessionErrors.pipe(filter((error) => error.name === \"LensAbortError\")).subscribe(() => this.destroy()),\n\n // In case of LensCore lens execution error, we must remove the lens from rendering\n // NOTE: LensCore doesn't differentiate recoverable vs non-recoverable errors and\n // it is recommened to always remove the lens.\n sessionErrors\n .pipe(filter((error) => error.name === \"LensExecutionError\"))\n .subscribe(() => this.removeLens()),\n\n // Report public session errors to apps\n sessionErrors.pipe(filter(isPublicLensError)).subscribe((error) => {\n const state = lensState.getState();\n if (!isState(state, \"noLensApplied\")) {\n this.events.dispatchEvent(new TypedCustomEvent(\"error\", { error, lens: state.data }));\n } else {\n // NOTE: at this point the error is already reported, so we can just log a warning\n logger.warn(\n new Error(\"Lens error occurred even though there is no active lens.\", {\n cause: error,\n })\n );\n }\n }),\n ];\n }\n\n /**\n * Apply a Lens to this session.\n *\n * This method will download (and cache) the Lens executable, and then use that Lens for rendering. If the session\n * is currently playing, this will immediately update the rendered output. Otherwise, the new Lens will be used\n * when session playback in resumed.\n *\n * Calling `applyLens` replaces any prior Lens – only one Lens is allowed at a time (per session).\n *\n * **NOTE**: Errors may occur after the Lens is applied. If the Lens encounters errors while rendering,\n * Camera Kit will automatically remove the Lens from the session and emit a {@link LensExecutionError} event.\n * Applications may want to listen for this error and, for example,\n * prevent the Lens from being selected again by the user.\n *\n * ```ts\n * session.events.addEventListener(\"error\", ({ detail }) => {\n * if (detail.error.name === \"LensExecutionError\") {\n * preventFutureLensSelection(detail.lens);\n * showMessage(\"We're sorry, but the Lens you selected encountered an error. Please choose a different Lens.\");\n * }\n * });\n * ```\n *\n * @param lens The Lens to apply to this session.\n * @param launchParams: This can optionally be provided to pass some initial data to the lens – only certain lenses\n * expect launch data.\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the lens has been applied.\n * 2. Resolved with `false`: the lens has not been applied, but no error occurred – this can happen if a\n * subsequent call to `applyLens` interrupted the lens application.\n * 3. Rejected: the lens has not been applied because an error occurred. This can happen if:\n * - The lens ID cannot be found in the LensRepository (use LensRepository to load the lens before calling this\n * method)\n * - Lens content download fails, or the download of any required lens assets fails.\n * - An internal failure occurs in the Lens rendering engine when attempting to apply the lens.\n */\n @validate\n @log\n async applyLens(@guard(isLens) lens: Lens, launchParams?: LensLaunchParams): Promise<boolean> {\n const action = this.lensState.actions.applyLens({ lens, launchParams });\n return firstValueFrom(\n of(action).pipe(\n dispatch(this.lensState),\n\n // If another applyLens occurs while we're waiting, resolve this applyLens promise early – we're no\n // longer waiting for the requested lens to be applied.\n takeUntil(\n this.lensState.events.pipe(\n forActions(\"applyLens\"),\n filter(([a]) => a !== action)\n )\n ),\n\n // If lens application failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"applyLensFailed\") && a.data.lens.id === lens.id) throw a.data.error;\n }),\n\n inStates(\"lensApplied\"),\n\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early – i.e. the lens was not\n // applied (application was interrupted by a new call to `applyLens`), so we'll resolve with `false`.\n { defaultValue: false }\n );\n }\n\n /**\n * Remove a Lens from this session.\n *\n * When a Lens is removed, rendering continues if the session is playing. It will just render the session input\n * directly to the outputs without any image processing.\n *\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the session's rendered output has no lens applied.\n * 2. Resolved with `false`: the current lens has been removed, but a subsequent call to `applyLens` means that the\n * session's rendered output will still have a (new) lens applied.\n * 3. Rejected: the lens has failed to be removed. This can happen if an internal failure occurs in the Lens\n * rendering engine when attempting to remove the lens.\n */\n @log\n async removeLens(): Promise<boolean> {\n if (isState(this.lensState.getState(), \"noLensApplied\")) return true;\n return firstValueFrom(\n of(this.lensState.actions.removeLens()).pipe(\n dispatch(this.lensState),\n // If lens removal failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"removeLensFailed\")) throw a.data;\n }),\n inStates(\"noLensApplied\"),\n\n // If applyLens is called while we're waiting for removal, complete immediately – applying the next lens\n // will replace the current one.\n takeUntil(this.lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early (otherwise firstValueFrom will\n // return a rejected Promise).\n { defaultValue: false }\n );\n }\n\n /**\n * Start/resume session playback – LensCore will begin rendering frames to the output.\n *\n * If no source has been set for the session, calling `play()` will update the playing state, but no actual image\n * processing will occur until `setSource()` is called.\n *\n * @example\n * ```ts\n * const cameraKitSession = await cameraKit.createSession()\n * await cameraKitSession.setSource(mySource)\n * await cameraKitSession.play()\n *\n * // If you call `play` before `setSource`, the call to `play` will resolve but playback will only begin once a\n * // media source has been set.\n * ```\n *\n * @param target Specify the {@link RenderTarget} to render. Defaults to the `live` RenderTarget.\n * @returns Promise resolves when playback state has been updated. If no source has been set, this means `play` will\n * resolve before any frames are processed -- but once a source is set, frames will immediately begin processing.\n */\n @validate\n @log\n async play(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (this.playing) return;\n this.playing = target;\n\n const type = this.renderTargetToCanvasType(target);\n return this.lensCore.playCanvas({ type }).catch((error) => {\n this.playing = false;\n throw error;\n });\n }\n\n /**\n * Pause session playback – LensCore will stop rendering frames to the output.\n *\n * @param target Specify the RenderTarget to pause playback. May be either `'live'` or `'capture'`.\n * Default is `'live'`.\n * @returns Promise resolves when playback has stopped.\n */\n @validate\n @log\n async pause(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (!this.playing) return;\n const priorPlayingState = this.playing;\n this.playing = false;\n\n const type = this.renderTargetToCanvasType(target);\n return this.lensCore.pauseCanvas({ type }).catch((error) => {\n this.playing = priorPlayingState;\n throw error;\n });\n }\n\n /**\n * Mute all sounds (default SDK state is unmuted).\n *\n * @param fade Do we want audio to fade out?\n */\n @log\n mute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: true,\n fade,\n });\n }\n\n /**\n * Unmute all sounds.\n *\n * @param fade Do we want audio to fade in?\n */\n @log\n unmute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: false,\n fade,\n });\n }\n\n /**\n * Set the media source for this session.\n *\n * Sessions may only have one source at a time - if `setSource` is called multiple times, subsequent calls replace\n * the prior source. Setting the source does not trigger rendering (that’s done by `session.play()`). If the session\n * is already playing, setting the source will immediately begin rendering the new source.\n *\n * The CameraKit SDK provides implementations for various common sources, which applications can create using the\n * following functions:\n * - {@link createMediaStreamSource}\n * - {@link createVideoSource}\n * - {@link createImageSource}\n *\n * @param source A CameraKitSource object representing input media (e.g. a webcam stream, video, or some other\n * source of image data), which CameraKit will supply to Lenses in order for them to render effects on top of that\n * source.\n * @returns Promise is resolved when the source has successfully be set. If the session was already in the playing\n * state, the Promise resolves when the first frame from the new source has been rendered. The resolved value is\n * the {@link CameraKitSource} object attached to the session.\n */\n async setSource(source: CameraKitSource): Promise<CameraKitSource>;\n /** Deprecated: Support for CameraKitDeviceInfo will be removed in future releases.\n * Please use CameraKitDeviceOptions instead which accepts the \"environment\" and \"user\" cameraType\n * @deprecated\n */\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceInfo>\n ): Promise<CameraKitSource>;\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceOptions>\n ): Promise<CameraKitSource>;\n @validate\n @log\n async setSource(\n source: CameraKitSource | MediaStream | HTMLVideoElement,\n options: Partial<CameraKitDeviceInfo | CameraKitDeviceOptions> = {}\n ): Promise<CameraKitSource> {\n await this.safelyDetachSource();\n\n // For convenience, we allow callers to pass in native objects (e.g. MediaStream) as well as CameraKitSource.\n // Native objects are wrapped in corresponding CameraKitSource classes with default options.\n const cameraKitSource =\n source instanceof MediaStream\n ? createMediaStreamSource(source, options)\n : source instanceof HTMLVideoElement\n ? createVideoSource(source, options)\n : source;\n\n const priorPlayingState = this.playing;\n this.playing = false;\n\n // The source will provide its data to LensCore, and use other LensCore APIs (e.g. setRenderSize,\n // setInputTransform) to render the source correctly.\n await cameraKitSource.attach(this.lensCore, (error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source attachment.\", error));\n });\n\n // If attachment is successful, we'll update our source so that we can detach it later.\n this.source = cameraKitSource;\n\n // Finally we'll resume playback, if appropriate.\n if (priorPlayingState) {\n await this.play(priorPlayingState);\n }\n\n return cameraKitSource;\n }\n\n /**\n * Set an FPS limit.\n *\n * This may be useful to reduce CPU/GPU resource usage by CameraKit if, for example, the input\n * media source has a low FPS – CameraKit would then not try to render more frequently than the source produces\n * new frames.\n *\n * This may also be useful to gracefully degrade performance in situations where lowering FPS is preferable over\n * alternatives.\n *\n * @param fpsLimit A maximum FPS, rendering will not exceed this limit\n * @returns Promise is resolved when the limit is successfully set.\n */\n @log\n async setFPSLimit(fpsLimit: number): Promise<void> {\n // LensCore uses 0 to remove the limit.\n const fps = fpsLimit < Number.POSITIVE_INFINITY ? fpsLimit : 0;\n return this.lensCore.setFPSLimit({ fps });\n }\n\n /**\n * Destroy the session.\n *\n * The session will become inoperable. Frame processing stops, and any session-scoped graphical resources are freed.\n */\n @log\n async destroy(): Promise<void> {\n try {\n await this.lensCore.clearAllLenses();\n await this.lensCore.teardown();\n } catch (error) {\n // If a LensCore is in an aborted state, the above lines may throw an error.\n // In such cases, we should continue with the cleanup process.\n // We are also not interested in reporting these errors to our backend.\n logger.warn(\"An error occurred in LensCore during the session termination process.\", error);\n }\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n await this.safelyDetachSource();\n this.removePageVisibilityHandlers();\n this.sessionState.dispatch(\"destroy\", undefined);\n }\n\n private renderTargetToCanvasType(target: RenderTarget): CanvasType {\n return target === \"capture\" ? this.lensCore.CanvasType.Capture : this.lensCore.CanvasType.Preview;\n }\n\n private async safelyDetachSource(): Promise<void> {\n if (this.source) {\n try {\n await this.source.detach((error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source detachment.\", error));\n });\n // If there's a failure to detach, we will report the error and proceed. Failure to detach may lead to a\n // memory leak, but it shouldn't prevent us from switching to the new source.\n } catch (error) {\n logger.error(\n cameraKitSourceError(`Detaching prior source of type ${getTypeName(this.source)} failed.`, error)\n );\n }\n }\n }\n}\n\n/**\n * @internal\n */\nexport const cameraKitSessionFactory = Injectable(\n \"CameraKitSession\",\n [\n lensCoreFactory.token,\n logEntriesFactory.token,\n lensKeyboardFactory.token,\n sessionStateFactory.token,\n lensStateFactory.token,\n pageVisibilityFactory.token,\n ] as const,\n (\n lensCore: LensCore,\n logEntries: Observable<LogEntry>,\n keyboard: LensKeyboard,\n sessionState: SessionState,\n lensState: LensState,\n pageVisibility: PageVisibility\n ) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries, pageVisibility)\n);\n"]}
1
+ {"version":3,"file":"CameraKitSession.js","sourceRoot":"","sources":["../../src/session/CameraKitSession.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,EAAc,EAAE,EAAgB,SAAS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G;;;;8CAMH;AA6BK;IAFL,QAAQ;IACR,GAAG;;;;iDAoCH;AAgBK;IADL,GAAG;;;;mDAKH;AAQK;IADL,GAAG;;;;+CAeH;AAuBL;;GAEG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,UAAU,CAC7C,kBAAkB,EAClB;IACI,eAAe,CAAC,KAAK;IACrB,iBAAiB,CAAC,KAAK;IACvB,mBAAmB,CAAC,KAAK;IACzB,mBAAmB,CAAC,KAAK;IACzB,gBAAgB,CAAC,KAAK;IACtB,qBAAqB,CAAC,KAAK;CACrB,EACV,CACI,QAAkB,EAClB,UAAgC,EAChC,QAAsB,EACtB,YAA0B,EAC1B,SAAoB,EACpB,cAA8B,EAChC,EAAE,CAAC,IAAI,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,CAAC,CACrG,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/member-ordering */\nimport { filter, firstValueFrom, map, Observable, of, Subscription, takeUntil, tap } from \"rxjs\";\nimport { dispatch, forActions, inStates, isAction, isState } from \"@snap/state-management\";\nimport { Lens, isLens } from \"../lens/Lens\";\nimport { CanvasType, LensCore } from \"../lens-core-module\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { LensLaunchData } from \"../lens/LensLaunchData\";\nimport { getTypeName, guard, validate } from \"../common/validate\";\nimport { TypedEventTarget } from \"../events/TypedEventTarget\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { CameraKitDeviceOptions, CameraKitSource } from \"../media-sources/CameraKitSource\";\nimport { cameraKitSourceError, LensExecutionError } from \"../namedErrors\";\nimport { createMediaStreamSource } from \"../media-sources/MediaStreamSource\";\nimport { createVideoSource } from \"../media-sources/VideoSource\";\nimport { getLogger, LogEntry } from \"../logger/logger\";\nimport { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { PageVisibility, pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { LensPerformanceMetrics } from \"./LensPerformanceMetrics\";\nimport { lensStateFactory, LensState } from \"./lensState\";\nimport { SessionState, sessionStateFactory } from \"./sessionState\";\nimport { Keyboard, lensKeyboardFactory, LensKeyboard } from \"./LensKeyboard\";\nimport { CameraKitSessionEvents, isPublicLensError, isSessionError } from \"./CameraKitSessionEvents\";\n\nconst logger = getLogger(\"CameraKitSession\");\nconst log = errorLoggingDecorator(logger);\n\nfunction isOptionalRenderTarget(value: unknown): value is RenderTarget | undefined {\n return value === \"live\" || value === \"capture\" || value === undefined;\n}\n\n/**\n * Enumerates the supported render targets.\n *\n * Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose\n * which render target to render, and the result for each target is available as a separate `<canvas>` element.\n *\n * @category Rendering\n * @category Lenses\n */\nexport type RenderTarget = \"live\" | \"capture\";\n\n/**\n * A CameraKitSession represents a single rendering pipeline connecting an input media source to output `<canvas>`\n * elements. When a Lens is applied to the session, CameraKit uses the Lens to transform the input media into rendered\n * output.\n *\n * CameraKitSession is the primary object that applications interact with when integrating the CameraKit SDK.\n *\n * A CameraKitSession instance is obtained by calling {@link CameraKit.createSession}.\n *\n * @example\n * ```ts\n * const cameraKit = await bootstrapCameraKit(config)\n * const session = await cameraKit.createSession()\n * ```\n *\n * @category Rendering\n * @category Lenses\n */\nexport class CameraKitSession {\n /**\n * CameraKitSession renders video output to a `<canvas>` element. In fact, each session contains two canvas outputs\n * corresponding to the RenderTargets used by Lens creators, when using LensStudio to create a Lens.\n *\n * The `live` output renders content suitable for the Lens user (e.g. it may contain additional UI elements\n * applicable only to the person applying the lens). The `capture` output renders content suitable for sharing with\n * other users (e.g. sent to the other members of a video call, or saved to disk for sharing later).\n *\n * For many lenses, these outputs are identical – but each lens is free to render differently, based on its own\n * use-case.\n */\n readonly output: {\n live: HTMLCanvasElement;\n capture: HTMLCanvasElement;\n };\n\n /**\n * Indicates whether or not the session is currently rendering. If `false`, rendering is stopped. Otherwise the\n * value indicates which output is being rendered.\n */\n playing: {\n live: boolean;\n capture: boolean;\n };\n\n /**\n * Add event listeners here to handle events which occur during the CameraKitSession.\n *\n * **Note:** Applications may want to handle the `error` event, and check the contained error type -- if the type\n * is {@link LensExecutionError}, this means the current lens was unable to render and CameraKit will automatically\n * remove the lens.\n *\n * @example\n * ```ts\n * cameraKitSession.events.addEventListener('error', ({ detail }) => {\n * if (detail.error.name === 'LensExecutionError') {\n * console.log(`Lens ${detail.lens.name} encountered an error and was removed. Please pick a different lens.`)\n * }\n * })\n * ```\n */\n readonly events = new TypedEventTarget<CameraKitSessionEvents>();\n\n /**\n * Use this to measure current lens performance.\n */\n readonly metrics: LensPerformanceMetrics;\n\n private readonly removePageVisibilityHandlers: () => void;\n private source?: CameraKitSource;\n private subscriptions: Subscription[];\n\n /**\n * @internal\n */\n constructor(\n /**\n * Use this to interact with lenses which require text input.\n */\n public readonly keyboard: Keyboard,\n\n private readonly lensCore: LensCore,\n private readonly sessionState: SessionState,\n private readonly lensState: LensState,\n logEntries: Observable<LogEntry>,\n pageVisibility: PageVisibility\n ) {\n const outputs = this.lensCore.getOutputCanvases();\n this.output = {\n live: outputs[this.lensCore.CanvasType.Preview.value],\n capture: outputs[this.lensCore.CanvasType.Capture.value],\n };\n this.playing = {\n live: false,\n capture: false,\n };\n\n this.metrics = new LensPerformanceMetrics(this.lensCore);\n\n const removeOnHidden = pageVisibility.onPageHidden(() => this.sessionState.dispatch(\"suspend\", this));\n const removeOnVisible = pageVisibility.onPageVisible(() => this.sessionState.dispatch(\"resume\", this));\n this.removePageVisibilityHandlers = () => {\n removeOnHidden();\n removeOnVisible();\n };\n\n const sessionErrors = logEntries.pipe(\n filter((entry) => entry.level === \"error\"),\n map((entry) => entry.messages.find((e) => e instanceof Error)),\n filter(isSessionError)\n );\n\n this.subscriptions = [\n // In case of an abort error, the only option is to destroy the current session,\n // as it becomes inoperable.\n sessionErrors.pipe(filter((error) => error.name === \"LensAbortError\")).subscribe(() => this.destroy()),\n\n // In case of LensCore lens execution error, we must remove the lens from rendering\n // NOTE: LensCore doesn't differentiate recoverable vs non-recoverable errors and\n // it is recommened to always remove the lens.\n sessionErrors\n .pipe(filter((error) => error.name === \"LensExecutionError\"))\n .subscribe(() => this.removeLens()),\n\n // Report public session errors to apps\n sessionErrors.pipe(filter(isPublicLensError)).subscribe((error) => {\n const state = lensState.getState();\n if (!isState(state, \"noLensApplied\")) {\n this.events.dispatchEvent(new TypedCustomEvent(\"error\", { error, lens: state.data }));\n } else {\n // NOTE: at this point the error is already reported, so we can just log a warning\n logger.warn(\"Lens error occurred even though there is no active lens.\", error);\n }\n }),\n ];\n }\n\n /**\n * Apply a Lens to this session.\n *\n * This method will download (and cache) the Lens executable, and then use that Lens for rendering. If the session\n * is currently playing, this will immediately update the rendered output. Otherwise, the new Lens will be used\n * when session playback in resumed.\n *\n * Calling `applyLens` replaces any prior Lens – only one Lens is allowed at a time (per session).\n *\n * **NOTE**: Errors may occur after the Lens is applied. If the Lens encounters errors while rendering,\n * Camera Kit will automatically remove the Lens from the session and emit a {@link LensExecutionError} event.\n * Applications may want to listen for this error and, for example,\n * prevent the Lens from being selected again by the user.\n *\n * ```ts\n * session.events.addEventListener(\"error\", ({ detail }) => {\n * if (detail.error.name === \"LensExecutionError\") {\n * preventFutureLensSelection(detail.lens);\n * showMessage(\"We're sorry, but the Lens you selected encountered an error. Please choose a different Lens.\");\n * }\n * });\n * ```\n *\n * @param lens The Lens to apply to this session.\n * @param launchParams: This can optionally be provided to pass some initial data to the lens – only certain lenses\n * expect launch data.\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the lens has been applied.\n * 2. Resolved with `false`: the lens has not been applied, but no error occurred – this can happen if a\n * subsequent call to `applyLens` interrupted the lens application.\n * 3. Rejected: the lens has not been applied because an error occurred. This can happen if:\n * - The lens ID cannot be found in the LensRepository (use LensRepository to load the lens before calling this\n * method)\n * - Lens content download fails, or the download of any required lens assets fails.\n * - An internal failure occurs in the Lens rendering engine when attempting to apply the lens.\n */\n @validate\n @log\n async applyLens(@guard(isLens) lens: Lens, launchData?: LensLaunchData): Promise<boolean> {\n const action = this.lensState.actions.applyLens({ lens, launchData });\n return firstValueFrom(\n of(action).pipe(\n dispatch(this.lensState),\n\n // If another applyLens occurs while we're waiting, resolve this applyLens promise early – we're no\n // longer waiting for the requested lens to be applied.\n takeUntil(\n this.lensState.events.pipe(\n forActions(\"applyLens\"),\n filter(([a]) => a !== action)\n )\n ),\n\n // If lens application failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"applyLensFailed\") && a.data.lens.id === lens.id) throw a.data.error;\n }),\n\n inStates(\"lensApplied\"),\n\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early – i.e. the lens was not\n // applied (application was interrupted by a new call to `applyLens`), so we'll resolve with `false`.\n { defaultValue: false }\n );\n }\n\n /**\n * Remove a Lens from this session.\n *\n * When a Lens is removed, rendering continues if the session is playing. It will just render the session input\n * directly to the outputs without any image processing.\n *\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the session's rendered output has no lens applied.\n * 2. Resolved with `false`: the current lens has been removed, but a subsequent call to `applyLens` means that the\n * session's rendered output will still have a (new) lens applied.\n * 3. Rejected: the lens has failed to be removed. This can happen if an internal failure occurs in the Lens\n * rendering engine when attempting to remove the lens.\n */\n @log\n async removeLens(): Promise<boolean> {\n if (isState(this.lensState.getState(), \"noLensApplied\")) return true;\n return firstValueFrom(\n of(this.lensState.actions.removeLens()).pipe(\n dispatch(this.lensState),\n // If lens removal failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"removeLensFailed\")) throw a.data;\n }),\n inStates(\"noLensApplied\"),\n\n // If applyLens is called while we're waiting for removal, complete immediately – applying the next lens\n // will replace the current one.\n takeUntil(this.lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early (otherwise firstValueFrom will\n // return a rejected Promise).\n { defaultValue: false }\n );\n }\n\n /**\n * Start/resume session playback – LensCore will begin rendering frames to the output.\n *\n * If no source has been set for the session, calling `play()` will update the playing state, but no actual image\n * processing will occur until `setSource()` is called.\n *\n * @example\n * ```ts\n * const cameraKitSession = await cameraKit.createSession()\n * await cameraKitSession.setSource(mySource)\n * await cameraKitSession.play()\n *\n * // If you call `play` before `setSource`, the call to `play` will resolve but playback will only begin once a\n * // media source has been set.\n * ```\n *\n * @param target Specify the {@link RenderTarget} to render. Defaults to the `live` RenderTarget.\n * @returns Promise resolves when playback state has been updated. If no source has been set, this means `play` will\n * resolve before any frames are processed -- but once a source is set, frames will immediately begin processing.\n */\n @validate\n @log\n async play(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (this.playing[target]) return;\n\n this.playing[target] = true;\n const type = this.renderTargetToCanvasType(target);\n return this.lensCore.playCanvas({ type }).catch((error) => {\n this.playing[target] = false;\n throw error;\n });\n }\n\n /**\n * Pause session playback – LensCore will stop rendering frames to the output.\n *\n * @param target Specify the RenderTarget to pause playback. May be either `'live'` or `'capture'`.\n * Default is `'live'`.\n * @returns Promise resolves when playback has stopped.\n */\n @validate\n @log\n async pause(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (this.playing[target] === false) return;\n this.playing[target] = false;\n const type = this.renderTargetToCanvasType(target);\n return this.lensCore.pauseCanvas({ type }).catch((error) => {\n this.playing[target] = true;\n throw error;\n });\n }\n\n /**\n * Mute all sounds (default SDK state is unmuted).\n *\n * @param fade Do we want audio to fade out?\n */\n @log\n mute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: true,\n fade,\n });\n }\n\n /**\n * Unmute all sounds.\n *\n * @param fade Do we want audio to fade in?\n */\n @log\n unmute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: false,\n fade,\n });\n }\n\n /**\n * Set the media source for this session.\n *\n * Sessions may only have one source at a time - if `setSource` is called multiple times, subsequent calls replace\n * the prior source. Setting the source does not trigger rendering (that’s done by `session.play()`). If the session\n * is already playing, setting the source will immediately begin rendering the new source.\n *\n * The CameraKit SDK provides implementations for various common sources, which applications can create using the\n * following functions:\n * - {@link createMediaStreamSource}\n * - {@link createVideoSource}\n * - {@link createImageSource}\n *\n * @param source A CameraKitSource object representing input media (e.g. a webcam stream, video, or some other\n * source of image data), which CameraKit will supply to Lenses in order for them to render effects on top of that\n * source.\n * @returns Promise is resolved when the source has successfully be set. If the session was already in the playing\n * state, the Promise resolves when the first frame from the new source has been rendered. The resolved value is\n * the {@link CameraKitSource} object attached to the session.\n */\n async setSource(source: CameraKitSource): Promise<CameraKitSource>;\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceOptions>\n ): Promise<CameraKitSource>;\n @validate\n @log\n async setSource(\n source: CameraKitSource | MediaStream | HTMLVideoElement,\n options: Partial<CameraKitDeviceOptions> = {}\n ): Promise<CameraKitSource> {\n await this.safelyDetachSource();\n\n // For convenience, we allow callers to pass in native objects (e.g. MediaStream) as well as CameraKitSource.\n // Native objects are wrapped in corresponding CameraKitSource classes with default options.\n const cameraKitSource =\n source instanceof MediaStream\n ? createMediaStreamSource(source, options)\n : source instanceof HTMLVideoElement\n ? createVideoSource(source, options)\n : source;\n\n const priorPlayingState = this.playing;\n this.playing = {\n live: false,\n capture: false,\n };\n\n // The source will provide its data to LensCore, and use other LensCore APIs (e.g. setRenderSize,\n // setInputTransform) to render the source correctly.\n await cameraKitSource.attach(this.lensCore, (error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source attachment.\", error));\n });\n\n // If attachment is successful, we'll update our source so that we can detach it later.\n this.source = cameraKitSource;\n\n // Finally we'll resume playback, if appropriate.\n if (priorPlayingState.live) await this.play(\"live\");\n if (priorPlayingState.capture) await this.play(\"capture\");\n\n return cameraKitSource;\n }\n\n /**\n * Set an FPS limit.\n *\n * This may be useful to reduce CPU/GPU resource usage by CameraKit if, for example, the input\n * media source has a low FPS – CameraKit would then not try to render more frequently than the source produces\n * new frames.\n *\n * This may also be useful to gracefully degrade performance in situations where lowering FPS is preferable over\n * alternatives.\n *\n * @param fpsLimit A maximum FPS, rendering will not exceed this limit\n * @returns Promise is resolved when the limit is successfully set.\n */\n @log\n async setFPSLimit(fpsLimit: number): Promise<void> {\n // LensCore uses 0 to remove the limit.\n const fps = fpsLimit < Number.POSITIVE_INFINITY ? fpsLimit : 0;\n return this.lensCore.setFPSLimit({ fps });\n }\n\n /**\n * Destroy the session.\n *\n * The session will become inoperable. Frame processing stops, and any session-scoped graphical resources are freed.\n */\n @log\n async destroy(): Promise<void> {\n try {\n await this.lensCore.clearAllLenses();\n await this.lensCore.teardown();\n } catch (error) {\n // If a LensCore is in an aborted state, the above lines may throw an error.\n // In such cases, we should continue with the cleanup process.\n // We are also not interested in reporting these errors to our backend.\n logger.warn(\"An error occurred in LensCore during the session termination process.\", error);\n }\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n await this.safelyDetachSource();\n this.removePageVisibilityHandlers();\n this.sessionState.dispatch(\"destroy\", undefined);\n }\n\n private renderTargetToCanvasType(target: RenderTarget): CanvasType {\n return target === \"capture\" ? this.lensCore.CanvasType.Capture : this.lensCore.CanvasType.Preview;\n }\n\n private async safelyDetachSource(): Promise<void> {\n if (this.source) {\n try {\n await this.source.detach((error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source detachment.\", error));\n });\n // If there's a failure to detach, we will report the error and proceed. Failure to detach may lead to a\n // memory leak, but it shouldn't prevent us from switching to the new source.\n } catch (error) {\n logger.error(\n cameraKitSourceError(`Detaching prior source of type ${getTypeName(this.source)} failed.`, error)\n );\n }\n }\n }\n}\n\n/**\n * @internal\n */\nexport const cameraKitSessionFactory = Injectable(\n \"CameraKitSession\",\n [\n lensCoreFactory.token,\n logEntriesFactory.token,\n lensKeyboardFactory.token,\n sessionStateFactory.token,\n lensStateFactory.token,\n pageVisibilityFactory.token,\n ] as const,\n (\n lensCore: LensCore,\n logEntries: Observable<LogEntry>,\n keyboard: LensKeyboard,\n sessionState: SessionState,\n lensState: LensState,\n pageVisibility: PageVisibility\n ) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries, pageVisibility)\n);\n"]}
@@ -1,7 +1,7 @@
1
1
  import { CameraKitSourceError, LensExecutionError, LensImagePickerError, LensAbortError } from "../namedErrors";
2
2
  import { TypedCustomEvent } from "../events/TypedCustomEvent";
3
3
  import { TypedEventListener } from "../events/TypedEventTarget";
4
- import { Lens } from "../lens";
4
+ import { Lens } from "../lens/Lens";
5
5
  /**
6
6
  * Returns true if given value is of {@link SessionErrors} type and false otherwise.
7
7
  */
@@ -1 +1 @@
1
- {"version":3,"file":"CameraKitSessionEvents.js","sourceRoot":"","sources":["../../src/session/CameraKitSessionEvents.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,MAAM,WAAW,GAAG,CAAC,CAAQ,EAAE,EAAE,CAAC,KAAK,CAAC;AAExC;;GAEG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IACzC,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,qBAAqB,GAAI,KAAuB,CAAC,IAAI,CAAC;IAC5D,QAAQ,qBAAqB,EAAE;QAC3B,KAAK,gBAAgB,CAAC;QACtB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,oBAAoB,CAAC;QAC1B,KAAK,sBAAsB;YACvB,OAAO,IAAI,CAAC;QAChB;YACI,OAAO,WAAW,CAAC,qBAAqB,CAAC,CAAC;KACjD;AACL,CAAC;AA8BD;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC5C,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,qBAAqB,GAAI,KAAmD,CAAC,IAAI,CAAC;IACxF,QAAQ,qBAAqB,EAAE;QAC3B,KAAK,gBAAgB,CAAC;QACtB,KAAK,oBAAoB,CAAC;QAC1B,KAAK,sBAAsB;YACvB,OAAO,IAAI,CAAC;QAChB;YACI,OAAO,WAAW,CAAC,qBAAqB,CAAC,CAAC;KACjD;AACL,CAAC","sourcesContent":["import { CameraKitSourceError, LensExecutionError, LensImagePickerError, LensAbortError } from \"../namedErrors\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { TypedEventListener } from \"../events/TypedEventTarget\";\nimport { Lens } from \"../lens\";\n\n/**\n * A type guard helper to detect unreachable code.\n */\nconst isReachable = (_: never) => false;\n\n/**\n * Returns true if given value is of {@link SessionErrors} type and false otherwise.\n */\nexport function isSessionError(value: unknown): value is SessionErrors {\n if (!(value instanceof Error)) return false;\n\n const maybeSessionErrorName = (value as SessionErrors).name;\n switch (maybeSessionErrorName) {\n case \"LensAbortError\":\n case \"CameraKitSourceError\":\n case \"LensExecutionError\":\n case \"LensImagePickerError\":\n return true;\n default:\n return isReachable(maybeSessionErrorName);\n }\n}\n\n/**\n * Misc errors that occur during CameraKit session.\n * @internal\n */\nexport type SessionErrors = LensExecutionError | LensAbortError | LensImagePickerError | CameraKitSourceError;\n\n/**\n * Events emitted by {@link CameraKitSession.events | CameraKitSession.events}.\n *\n * The following events are emitted:\n * - `error`: An error has been encountered during lens rendering. May contain an error of type:\n * - {@link LensExecutionError} If an error of this type occurs, the rendering lens will be automatically removed\n * from the associated CameraKitSession.\n * - {@link LensImagePickerError}\n *\n * @category Rendering\n * @category Lenses\n */\nexport type CameraKitSessionEvents = TypedCustomEvent<\n \"error\",\n { error: LensExecutionError | LensAbortError | LensImagePickerError; lens: Lens }\n>;\n\n/**\n * Listener of {@link CameraKitSessionEvents} events.\n */\nexport type CameraKitSessionEventListener = TypedEventListener<CameraKitSessionEvents>;\n\n/**\n * Returns true if given value is of {@link SessionErrors} type, which is notified to client.\n */\nexport function isPublicLensError(value: unknown): value is CameraKitSessionEvents[\"detail\"][\"error\"] {\n if (!(value instanceof Error)) return false;\n\n const maybeSessionErrorName = (value as CameraKitSessionEvents[\"detail\"][\"error\"]).name;\n switch (maybeSessionErrorName) {\n case \"LensAbortError\":\n case \"LensExecutionError\":\n case \"LensImagePickerError\":\n return true;\n default:\n return isReachable(maybeSessionErrorName);\n }\n}\n"]}
1
+ {"version":3,"file":"CameraKitSessionEvents.js","sourceRoot":"","sources":["../../src/session/CameraKitSessionEvents.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,MAAM,WAAW,GAAG,CAAC,CAAQ,EAAE,EAAE,CAAC,KAAK,CAAC;AAExC;;GAEG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IACzC,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,qBAAqB,GAAI,KAAuB,CAAC,IAAI,CAAC;IAC5D,QAAQ,qBAAqB,EAAE;QAC3B,KAAK,gBAAgB,CAAC;QACtB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,oBAAoB,CAAC;QAC1B,KAAK,sBAAsB;YACvB,OAAO,IAAI,CAAC;QAChB;YACI,OAAO,WAAW,CAAC,qBAAqB,CAAC,CAAC;KACjD;AACL,CAAC;AA8BD;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC5C,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,qBAAqB,GAAI,KAAmD,CAAC,IAAI,CAAC;IACxF,QAAQ,qBAAqB,EAAE;QAC3B,KAAK,gBAAgB,CAAC;QACtB,KAAK,oBAAoB,CAAC;QAC1B,KAAK,sBAAsB;YACvB,OAAO,IAAI,CAAC;QAChB;YACI,OAAO,WAAW,CAAC,qBAAqB,CAAC,CAAC;KACjD;AACL,CAAC","sourcesContent":["import { CameraKitSourceError, LensExecutionError, LensImagePickerError, LensAbortError } from \"../namedErrors\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { TypedEventListener } from \"../events/TypedEventTarget\";\nimport { Lens } from \"../lens/Lens\";\n\n/**\n * A type guard helper to detect unreachable code.\n */\nconst isReachable = (_: never) => false;\n\n/**\n * Returns true if given value is of {@link SessionErrors} type and false otherwise.\n */\nexport function isSessionError(value: unknown): value is SessionErrors {\n if (!(value instanceof Error)) return false;\n\n const maybeSessionErrorName = (value as SessionErrors).name;\n switch (maybeSessionErrorName) {\n case \"LensAbortError\":\n case \"CameraKitSourceError\":\n case \"LensExecutionError\":\n case \"LensImagePickerError\":\n return true;\n default:\n return isReachable(maybeSessionErrorName);\n }\n}\n\n/**\n * Misc errors that occur during CameraKit session.\n * @internal\n */\nexport type SessionErrors = LensExecutionError | LensAbortError | LensImagePickerError | CameraKitSourceError;\n\n/**\n * Events emitted by {@link CameraKitSession.events | CameraKitSession.events}.\n *\n * The following events are emitted:\n * - `error`: An error has been encountered during lens rendering. May contain an error of type:\n * - {@link LensExecutionError} If an error of this type occurs, the rendering lens will be automatically removed\n * from the associated CameraKitSession.\n * - {@link LensImagePickerError}\n *\n * @category Rendering\n * @category Lenses\n */\nexport type CameraKitSessionEvents = TypedCustomEvent<\n \"error\",\n { error: LensExecutionError | LensAbortError | LensImagePickerError; lens: Lens }\n>;\n\n/**\n * Listener of {@link CameraKitSessionEvents} events.\n */\nexport type CameraKitSessionEventListener = TypedEventListener<CameraKitSessionEvents>;\n\n/**\n * Returns true if given value is of {@link SessionErrors} type, which is notified to client.\n */\nexport function isPublicLensError(value: unknown): value is CameraKitSessionEvents[\"detail\"][\"error\"] {\n if (!(value instanceof Error)) return false;\n\n const maybeSessionErrorName = (value as CameraKitSessionEvents[\"detail\"][\"error\"]).name;\n switch (maybeSessionErrorName) {\n case \"LensAbortError\":\n case \"LensExecutionError\":\n case \"LensImagePickerError\":\n return true;\n default:\n return isReachable(maybeSessionErrorName);\n }\n}\n"]}
@@ -79,9 +79,15 @@ export declare class LensKeyboard {
79
79
  export declare const lensKeyboardFactory: {
80
80
  (args_0: import("@snap/state-management").StateMachine<import("@snap/state-management").Action<"applyLens", {
81
81
  lens: Lens;
82
- launchParams?: import("..").LensLaunchParams | undefined;
82
+ launchData?: import("..").LensLaunchData | undefined;
83
83
  }> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
84
84
  error: import("./lensState").LensErrors;
85
+ /**
86
+ * Send text to the active Lens. Also updates the provided HTMLTextAreaElement.
87
+ *
88
+ * @param text String to render. This can include escape sequences, such as the newline character ( \n ) for
89
+ * multi-line input.
90
+ */
85
91
  lens: Lens;
86
92
  }> | import("@snap/state-management").Action<"applyLensAborted", Lens> | import("@snap/state-management").Action<"removeLens", undefined> | import("@snap/state-management").Action<"turnedOff", Lens> | import("@snap/state-management").Action<"removeLensComplete", undefined> | import("@snap/state-management").Action<"removeLensFailed", Error>, import("@snap/state-management").State<"noLensApplied", undefined> | import("@snap/state-management").State<"applyingLens", Lens> | import("@snap/state-management").State<"lensApplied", Lens>>): LensKeyboard;
87
93
  token: "lensKeyboard";
@@ -3,13 +3,13 @@ import { Lens } from "../lens/Lens";
3
3
  import { LensRepository } from "../lens/LensRepository";
4
4
  import { LensCore } from "../lens-core-module";
5
5
  import { IndexedDBPersistence } from "../persistence/IndexedDBPersistence";
6
- import { LensLaunchParams } from "../lens/LensLaunchParams";
6
+ import { LensLaunchData } from "../lens/LensLaunchData";
7
7
  import { LensAssetRepository } from "../lens/assets/LensAssetRepository";
8
8
  import { LegalError, LensContentValidationError, LensError } from "../namedErrors";
9
9
  import { OperationalMetricsReporter } from "../metrics/operational/operationalMetricsReporter";
10
10
  declare const createLensState: () => StateMachine<import("@snap/state-management").Action<"applyLens", {
11
11
  lens: Lens;
12
- launchParams?: LensLaunchParams | undefined;
12
+ launchData?: LensLaunchData | undefined;
13
13
  }> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
14
14
  error: LensErrors;
15
15
  lens: Lens;
@@ -19,7 +19,7 @@ export type LensState = ReturnType<typeof createLensState>;
19
19
  export declare const lensStateFactory: {
20
20
  (args_0: LensCore, args_1: LensRepository, args_2: LensAssetRepository, args_3: IndexedDBPersistence<ArrayBuffer>, args_4: StateMachine<import("@snap/state-management").Action<"requestLegalPrompt", undefined> | import("@snap/state-management").Action<"accept", string> | import("@snap/state-management").Action<"reject", string>, import("@snap/state-management").State<"unknown", undefined> | import("@snap/state-management").State<"accepted", undefined> | import("@snap/state-management").State<"rejected", undefined>>, args_5: OperationalMetricsReporter): StateMachine<import("@snap/state-management").Action<"applyLens", {
21
21
  lens: Lens;
22
- launchParams?: LensLaunchParams | undefined;
22
+ launchData?: LensLaunchData | undefined;
23
23
  }> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
24
24
  error: LensErrors;
25
25
  lens: Lens;
@@ -4,7 +4,7 @@ import { Injectable } from "../dependency-injection/Injectable";
4
4
  import { lensRepositoryFactory } from "../lens/LensRepository";
5
5
  import { lensCoreFactory } from "../lens-core-module";
6
6
  import { lensPersistenceStoreFactory } from "../lens/LensPersistenceStore";
7
- import { createLaunchData } from "../lens/LensLaunchParams";
7
+ import { encodeLensLaunchData } from "../lens/LensLaunchData";
8
8
  import { legalStateFactory } from "../legal/legalState";
9
9
  import { lensAssetRepositoryFactory } from "../lens/assets/LensAssetRepository";
10
10
  import { legalError, lensContentValidationError, lensError, } from "../namedErrors";
@@ -12,6 +12,7 @@ import { getLogger } from "../logger/logger";
12
12
  import { Timer } from "../metrics/operational/Timer";
13
13
  import { operationalMetricReporterFactory, } from "../metrics/operational/operationalMetricsReporter";
14
14
  import { unsubscribed } from "../observable-operators/unsubscribed";
15
+ import { assertUnreachable } from "../common/assertions";
15
16
  const logger = getLogger("LensState");
16
17
  const createLensState = () => {
17
18
  const actions = defineActions(defineAction("applyLens")(), defineAction("downloadComplete")(), defineAction("turnedOn")(), defineAction("resourcesLoaded")(), defineAction("firstFrameProcessed")(), defineAction("applyLensComplete")(), defineAction("applyLensFailed")(), defineAction("applyLensAborted")(), defineAction("removeLens")(), defineAction("turnedOff")(), defineAction("removeLensComplete")(), defineAction("removeLensFailed")());
@@ -62,14 +63,11 @@ export const lensStateFactory = Injectable("lensState", [
62
63
  // are not present for subsequent applies.
63
64
  const applyTimer = new Timer("lens").mark("apply", { first: `${firstLensApply}` });
64
65
  firstLensApply = false;
65
- return of(a.data).pipe(mergeMap(({ lens, launchParams }) =>
66
- // If retrieval throws an error, we still want to proceed with the lens
67
- // because persisted data is not a necessity.
68
- from(lensPersistence.retrieve(lens.id).catch(() => undefined)).pipe(map((persistentStore) => ({ lens, launchParams, persistentStore })))), map(({ lens, launchParams, persistentStore }) => {
69
- const launchData = createLaunchData({
70
- launchParams,
71
- persistentStore,
72
- });
66
+ return of(a.data).pipe(mergeMap(({ lens, launchData }) => {
67
+ // If retrieval throws an error, we still want to proceed with the lens
68
+ // because persisted data is not a necessity.
69
+ return from(lensPersistence.retrieve(lens.id).catch(() => undefined)).pipe(map((persistentStore) => ({ lens, launchData, persistentStore })));
70
+ }), map(({ lens, launchData, persistentStore }) => {
73
71
  const lensDetails = lensRepository.getLensMetadata(lens.id);
74
72
  if (!lensDetails) {
75
73
  throw new Error(`Cannot apply lens ${lens.id}. It has not been loaded by the Lens ` +
@@ -81,7 +79,11 @@ export const lensStateFactory = Injectable("lensState", [
81
79
  throw new Error(`Cannot apply lens ${lens.id}. Metadata retrieved for this lens does not ` +
82
80
  `include the lens content URL.`);
83
81
  }
84
- return { lens, launchData, content };
82
+ return {
83
+ lens,
84
+ launchData: encodeLensLaunchData(launchData !== null && launchData !== void 0 ? launchData : {}, persistentStore !== null && persistentStore !== void 0 ? persistentStore : new ArrayBuffer(0)),
85
+ content,
86
+ };
85
87
  }),
86
88
  // Load lens assets and the lens itself in parallel. Both count toward lens download time.
87
89
  // TODO: use RxJS fetch utilities so that these requests can be cancelled on unsubscribe.
@@ -103,10 +105,7 @@ export const lensStateFactory = Injectable("lensState", [
103
105
  // One optimization can be done here: do not copy the array if getLensContent()
104
106
  // returned uncached buffer
105
107
  const lensDataBuffer = lensBuffer.slice(0);
106
- // LensCore chokes trying if launchData is set to undefined; we must omit it.
107
- return launchData === undefined
108
- ? { lensId: lens.id, lensDataBuffer, lensChecksum }
109
- : { lensId: lens.id, lensDataBuffer, lensChecksum, launchData };
108
+ return { lensId: lens.id, lensDataBuffer, lensChecksum, launchData };
110
109
  }));
111
110
  }),
112
111
  // If removeLens is dispatched while downloading, cancel download, don't apply the lens.
@@ -207,7 +206,33 @@ export const lensStateFactory = Injectable("lensState", [
207
206
  error: logger.error,
208
207
  });
209
208
  // Log transitions
210
- lensState.events.subscribe(([a, s]) => logger.debug(`Action: "${a.name}", state: "${s.name}"`));
209
+ lensState.events.subscribe(([a, s]) => {
210
+ const data = extractLoggableData(a);
211
+ logger.debug(`Action: "${a.name}", state: "${s.name}"${data ? ", data: " + JSON.stringify(data) : ""}`);
212
+ });
211
213
  return lensState;
212
214
  });
215
+ function extractLoggableData(action) {
216
+ switch (action.name) {
217
+ case "applyLens":
218
+ return { lensId: action.data.lens.id };
219
+ case "applyLensFailed":
220
+ return { lensId: action.data.lens.id, error: action.data.error.message };
221
+ case "downloadComplete":
222
+ case "turnedOn":
223
+ case "resourcesLoaded":
224
+ case "firstFrameProcessed":
225
+ case "applyLensComplete":
226
+ case "applyLensAborted":
227
+ case "turnedOff":
228
+ return { lensId: action.data.id };
229
+ case "removeLens":
230
+ case "removeLensComplete":
231
+ return undefined;
232
+ case "removeLensFailed":
233
+ return { error: action.data.message };
234
+ default:
235
+ assertUnreachable(action);
236
+ }
237
+ }
213
238
  //# sourceMappingURL=lensState.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"lensState.js","sourceRoot":"","sources":["../../src/session/lensState.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,YAAY,EACZ,aAAa,EACb,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,YAAY,GACf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACH,UAAU,EACV,UAAU,EACV,IAAI,EACJ,GAAG,EACH,KAAK,EACL,QAAQ,EACR,UAAU,EACV,EAAE,EACF,SAAS,EACT,IAAI,EACJ,SAAS,EACT,GAAG,GACN,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAEhE,OAAO,EAAkB,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAY,MAAM,qBAAqB,CAAC;AAGhE,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAoB,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAc,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAuB,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AACrG,OAAO,EACH,UAAU,EAEV,0BAA0B,EAE1B,SAAS,GAEZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AACrD,OAAO,EACH,gCAAgC,GAEnC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,sCAA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AAC;AACrB,CAAC,CACJ,CAAC","sourcesContent":["import {\n Actions,\n defineAction,\n defineActions,\n defineState,\n defineStates,\n dispatch,\n forActions,\n inStates,\n StateMachine,\n} from \"@snap/state-management\";\nimport {\n catchError,\n exhaustMap,\n from,\n map,\n merge,\n mergeMap,\n Observable,\n of,\n switchMap,\n take,\n takeUntil,\n tap,\n} from \"rxjs\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { Lens } from \"../lens/Lens\";\nimport { LensRepository, lensRepositoryFactory } from \"../lens/LensRepository\";\nimport { lensCoreFactory, LensCore } from \"../lens-core-module\";\nimport { AddLensInput } from \"../lens-core-module/generated-types\";\nimport { IndexedDBPersistence } from \"../persistence/IndexedDBPersistence\";\nimport { lensPersistenceStoreFactory } from \"../lens/LensPersistenceStore\";\nimport { createLaunchData, LensLaunchParams } from \"../lens/LensLaunchParams\";\nimport { LegalState, legalStateFactory } from \"../legal/legalState\";\nimport { LensAssetRepository, lensAssetRepositoryFactory } from \"../lens/assets/LensAssetRepository\";\nimport {\n legalError,\n LegalError,\n lensContentValidationError,\n LensContentValidationError,\n lensError,\n LensError,\n} from \"../namedErrors\";\nimport { getLogger } from \"../logger/logger\";\nimport { Timer } from \"../metrics/operational/Timer\";\nimport {\n operationalMetricReporterFactory,\n OperationalMetricsReporter,\n} from \"../metrics/operational/operationalMetricsReporter\";\nimport { unsubscribed } from \"../observable-operators/unsubscribed\";\n\nconst logger = getLogger(\"LensState\");\n\nconst createLensState = () => {\n const actions = defineActions(\n defineAction(\"applyLens\")<{ lens: Lens; launchParams?: LensLaunchParams }>(),\n defineAction(\"downloadComplete\")<Lens>(),\n defineAction(\"turnedOn\")<Lens>(),\n defineAction(\"resourcesLoaded\")<Lens>(),\n defineAction(\"firstFrameProcessed\")<Lens>(),\n defineAction(\"applyLensComplete\")<Lens>(),\n defineAction(\"applyLensFailed\")<{ error: LensErrors; lens: Lens }>(),\n defineAction(\"applyLensAborted\")<Lens>(),\n\n defineAction(\"removeLens\")(),\n defineAction(\"turnedOff\")<Lens>(),\n defineAction(\"removeLensComplete\")(),\n defineAction(\"removeLensFailed\")<Error>()\n );\n\n const states = defineStates(\n defineState(\"noLensApplied\")(),\n defineState(\"applyingLens\")<Lens>(),\n defineState(\"lensApplied\")<Lens>()\n );\n\n return new StateMachine(actions, states, states.noLensApplied(), (events) =>\n merge(\n events.pipe(\n // We allow a new lens to be applied at any time, no matter the state.\n inStates(\"noLensApplied\", \"applyingLens\", \"lensApplied\"),\n forActions(\"applyLens\"),\n map(([a]) => states.applyingLens(a.data.lens))\n ),\n events.pipe(\n inStates(\"applyingLens\"),\n forActions(\"applyLensComplete\"),\n map(([a]) => states.lensApplied(a.data))\n ),\n events.pipe(\n inStates(\"applyingLens\"),\n forActions(\"applyLensFailed\"),\n map(() => states.noLensApplied())\n ),\n events.pipe(\n inStates(\"lensApplied\"),\n forActions(\"removeLensComplete\"),\n map(() => states.noLensApplied())\n )\n )\n );\n};\n\nexport type LensErrors = LegalError | LensContentValidationError | LensError;\n\nexport type LensState = ReturnType<typeof createLensState>;\n\nexport const lensStateFactory = Injectable(\n \"lensState\",\n [\n lensCoreFactory.token,\n lensRepositoryFactory.token,\n lensAssetRepositoryFactory.token,\n lensPersistenceStoreFactory.token,\n legalStateFactory.token,\n operationalMetricReporterFactory.token,\n ] as const,\n (\n lensCore: LensCore,\n lensRepository: LensRepository,\n lensAssetRepository: LensAssetRepository,\n lensPersistence: IndexedDBPersistence<ArrayBuffer>,\n legalState: LegalState,\n operationalMetricsReporter: OperationalMetricsReporter\n ): LensState => {\n const lensState = createLensState();\n let firstLensApply = true;\n\n /**\n * Apply lens\n */\n lensState.events\n .pipe(\n forActions(\"applyLens\"),\n\n // Determine the legal state (e.g. terms have been accepted). Using exhaustMap means while we are\n // ascertaining legal status (which may include prompting the end user to accept terms), we will ignore\n // any new applyLens actions.\n exhaustMap(([a]) =>\n of(legalState.actions.requestLegalPrompt()).pipe(\n dispatch(legalState),\n inStates(\"accepted\", \"rejected\"),\n take(1),\n map(([, { name }]) => {\n if (name === \"accepted\") return a;\n return lensState.actions.applyLensFailed({\n error: legalError(\n `Failed to apply lens ${a.data.lens.id}. Required legal terms were not accepted.`\n ),\n lens: a.data.lens,\n });\n })\n )\n ),\n\n // The use of switchMap is important so that if we get a new applyLens action while we're still\n // downloading lens content for a previously-requested lens, we can cancel those requests and ensure\n // that lenses are applied in the order they're requested.\n switchMap((a) => {\n if (a.name === \"applyLensFailed\") return of(a);\n\n const { lens } = a.data;\n // Convenience method making dispatching an action with Lens data less verbose.\n const dispatch = (action: Extract<Actions<LensState>, { data: Lens }>[\"name\"]) => {\n lensState.dispatch(action, lens);\n };\n\n // We record if this was the first lens apply for this page load, since there may be additional\n // sources of latency (e.g. remote configuration that needs to be loaded) on the first apply that\n // are not present for subsequent applies.\n const applyTimer = new Timer(\"lens\").mark(\"apply\", { first: `${firstLensApply}` });\n firstLensApply = false;\n\n return of(a.data).pipe(\n mergeMap(({ lens, launchParams }) =>\n // If retrieval throws an error, we still want to proceed with the lens\n // because persisted data is not a necessity.\n from(lensPersistence.retrieve(lens.id).catch(() => undefined)).pipe(\n map((persistentStore) => ({ lens, launchParams, persistentStore }))\n )\n ),\n\n map(({ lens, launchParams, persistentStore }) => {\n const launchData = createLaunchData({\n launchParams,\n persistentStore,\n });\n\n const lensDetails = lensRepository.getLensMetadata(lens.id);\n if (!lensDetails) {\n throw new Error(\n `Cannot apply lens ${lens.id}. It has not been loaded by the Lens ` +\n `repository. Use CameraKit.lensRepository.loadLens (or loadLensGroups) ` +\n `to load lens metadata before calling CameraKitSession.applyLens.`\n );\n }\n\n const { content } = lensDetails;\n if (!content) {\n throw new Error(\n `Cannot apply lens ${lens.id}. Metadata retrieved for this lens does not ` +\n `include the lens content URL.`\n );\n }\n\n return { lens, launchData, content };\n }),\n\n // Load lens assets and the lens itself in parallel. Both count toward lens download time.\n // TODO: use RxJS fetch utilities so that these requests can be cancelled on unsubscribe.\n mergeMap(({ lens, launchData, content }) => {\n const networkTimer = applyTimer.mark(\"network\");\n\n return from(\n Promise.all([\n lensRepository.getLensContent(lens).finally(() => networkTimer.measure(\"lens\")),\n content.assetManifest.length > 0\n ? lensAssetRepository\n .cacheAssets(content.assetManifest, lens)\n .finally(() => networkTimer.measure(\"assets\"))\n : Promise.resolve(),\n ])\n ).pipe(\n tap(() => {\n networkTimer.measure();\n lensState.dispatch(\"downloadComplete\", lens);\n }),\n map(([{ lensBuffer, lensChecksum }]): AddLensInput => {\n // NOTE: cached array buffer has to be copied each time in order to be reused,\n // otherwise the original cached copy would be detached by LensCore\n // One optimization can be done here: do not copy the array if getLensContent()\n // returned uncached buffer\n const lensDataBuffer = lensBuffer.slice(0);\n // LensCore chokes trying if launchData is set to undefined; we must omit it.\n return launchData === undefined\n ? { lensId: lens.id, lensDataBuffer, lensChecksum }\n : { lensId: lens.id, lensDataBuffer, lensChecksum, launchData };\n })\n );\n }),\n\n // If removeLens is dispatched while downloading, cancel download, don't apply the lens.\n takeUntil(lensState.events.pipe(forActions(\"removeLens\"))),\n\n // Once the lens has downloaded, we can call replaceLenses. We're not concerned about\n // waiting for prior in-progress calls to replaceLenses to complete, because LensCore\n // guarantees that calls to replaceLenses will always be processed sequentially in the order\n // they are received.\n mergeMap(\n (lensInput) =>\n new Observable<Actions<LensState>>((subscriber) => {\n const coreTimer = applyTimer.mark(\"core\");\n\n // replaceLenses has the property that if it fails, LensCore guarantees that no\n // lenses are active – so we can safely dispatch applyLensFailed and transition\n // to noLensApplied state.\n lensCore\n .replaceLenses({\n lenses: [\n {\n ...lensInput,\n onTurnOn: () => dispatch(\"turnedOn\"),\n onResourcesLoaded: () => dispatch(\"resourcesLoaded\"),\n\n // onFirstFrameProcessed marks the end of the lens application for\n // the end-user -- this is when they see the newly applied lens\n // begin to render. As such, this is where we stop our overall\n // latency measurement and report latency metrics.\n onFirstFrameProcessed: () => {\n coreTimer.measure(\"first-frame\");\n applyTimer.measure(\"success\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n dispatch(\"firstFrameProcessed\");\n },\n onTurnOff: () => dispatch(\"turnedOff\"),\n },\n ],\n })\n .then(() => {\n coreTimer.measure(\"success\");\n\n // We emit applyLensComplete (and applyLensFailed, below) on an\n // Observable, which is piped to `dispatch` – this allows `switchMap` to\n // properly cancel the dispatch of these actions if a new applyLens\n // arrives while we're waiting for onSuccess/onFailure.\n //\n // That's desirable behavior, because we don't want the applyingLens\n // state due to a *subsequent applyLens action* to be transitioned to\n // lensApplied by this action.\n subscriber.next(lensState.actions.applyLensComplete(lens));\n subscriber.complete();\n })\n .catch((lensCoreError) => {\n coreTimer.measure(\"failure\");\n applyTimer.measure(\"failure\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n\n const message = `Failed to apply lens ${lensInput.lensId}.`;\n const error = /validation failed/.test(lensCoreError.message)\n ? lensContentValidationError(message, lensCoreError)\n : lensError(message, lensCoreError);\n\n subscriber.next(lensState.actions.applyLensFailed({ error, lens }));\n subscriber.complete();\n });\n })\n ),\n catchError((error: LensErrors) => {\n applyTimer.measure(\"failure\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n return of(lensState.actions.applyLensFailed({ error, lens }));\n }),\n\n // If a new applyLens is received, `switchMap` will unsubscribe from this inner observable,\n // which stops the current lens application. When this happens we can record a separate metric\n // to measure aborted lens applications.\n unsubscribed(() => {\n applyTimer.measure(\"abort\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n })\n );\n }),\n dispatch(lensState)\n )\n .subscribe({\n error: logger.error,\n });\n\n /**\n * Remove lens\n */\n lensState.events\n .pipe(\n inStates(\"lensApplied\", \"noLensApplied\"),\n forActions(\"removeLens\"),\n mergeMap(\n () =>\n new Observable<Actions<LensState>>((subscriber) => {\n lensCore\n .clearAllLenses()\n .then(() => {\n subscriber.next(lensState.actions.removeLensComplete());\n subscriber.complete();\n })\n .catch((lensCoreError) => {\n const error = new Error(\"Failed to remove lenses.\", { cause: lensCoreError });\n subscriber.next(lensState.actions.removeLensFailed(error));\n subscriber.complete();\n });\n })\n ),\n dispatch(lensState)\n )\n .subscribe({\n error: logger.error,\n });\n\n lensState.events\n .pipe(\n inStates(\"applyingLens\"),\n forActions(\"removeLens\"),\n switchMap(([a]) =>\n lensState.events.pipe(\n // Wait to remove the lens until it has been applied.\n inStates(\"lensApplied\"),\n // But cancel the removal if a new applyLens supercedes the current lens. The goal here is to\n // make sure the latest apply/remove pre-empts any previous request to apply/remove.\n takeUntil(lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => a)\n )\n ),\n dispatch(lensState)\n )\n .subscribe({\n error: logger.error,\n });\n\n // Log transitions\n lensState.events.subscribe(([a, s]) => logger.debug(`Action: \"${a.name}\", state: \"${s.name}\"`));\n\n return lensState;\n }\n);\n"]}
1
+ {"version":3,"file":"lensState.js","sourceRoot":"","sources":["../../src/session/lensState.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,YAAY,EACZ,aAAa,EACb,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,YAAY,GACf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACH,UAAU,EACV,UAAU,EACV,IAAI,EACJ,GAAG,EACH,KAAK,EACL,QAAQ,EACR,UAAU,EACV,EAAE,EACF,SAAS,EACT,IAAI,EACJ,SAAS,EACT,GAAG,GACN,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAEhE,OAAO,EAAkB,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAY,MAAM,qBAAqB,CAAC;AAGhE,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,oBAAoB,EAAkB,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAc,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAuB,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AACrG,OAAO,EACH,UAAU,EAEV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C,CAAC;KACjC;AACL,CAAC","sourcesContent":["import {\n Actions,\n defineAction,\n defineActions,\n defineState,\n defineStates,\n dispatch,\n forActions,\n inStates,\n StateMachine,\n} from \"@snap/state-management\";\nimport {\n catchError,\n exhaustMap,\n from,\n map,\n merge,\n mergeMap,\n Observable,\n of,\n switchMap,\n take,\n takeUntil,\n tap,\n} from \"rxjs\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { Lens } from \"../lens/Lens\";\nimport { LensRepository, lensRepositoryFactory } from \"../lens/LensRepository\";\nimport { lensCoreFactory, LensCore } from \"../lens-core-module\";\nimport { AddLensInput } from \"../lens-core-module/generated-types\";\nimport { IndexedDBPersistence } from \"../persistence/IndexedDBPersistence\";\nimport { lensPersistenceStoreFactory } from \"../lens/LensPersistenceStore\";\nimport { encodeLensLaunchData, LensLaunchData } from \"../lens/LensLaunchData\";\nimport { LegalState, legalStateFactory } from \"../legal/legalState\";\nimport { LensAssetRepository, lensAssetRepositoryFactory } from \"../lens/assets/LensAssetRepository\";\nimport {\n legalError,\n LegalError,\n lensContentValidationError,\n LensContentValidationError,\n lensError,\n LensError,\n} from \"../namedErrors\";\nimport { getLogger } from \"../logger/logger\";\nimport { Timer } from \"../metrics/operational/Timer\";\nimport {\n operationalMetricReporterFactory,\n OperationalMetricsReporter,\n} from \"../metrics/operational/operationalMetricsReporter\";\nimport { unsubscribed } from \"../observable-operators/unsubscribed\";\nimport { assertUnreachable } from \"../common/assertions\";\n\nconst logger = getLogger(\"LensState\");\n\nconst createLensState = () => {\n const actions = defineActions(\n defineAction(\"applyLens\")<{ lens: Lens; launchData?: LensLaunchData }>(),\n defineAction(\"downloadComplete\")<Lens>(),\n defineAction(\"turnedOn\")<Lens>(),\n defineAction(\"resourcesLoaded\")<Lens>(),\n defineAction(\"firstFrameProcessed\")<Lens>(),\n defineAction(\"applyLensComplete\")<Lens>(),\n defineAction(\"applyLensFailed\")<{ error: LensErrors; lens: Lens }>(),\n defineAction(\"applyLensAborted\")<Lens>(),\n\n defineAction(\"removeLens\")(),\n defineAction(\"turnedOff\")<Lens>(),\n defineAction(\"removeLensComplete\")(),\n defineAction(\"removeLensFailed\")<Error>()\n );\n\n const states = defineStates(\n defineState(\"noLensApplied\")(),\n defineState(\"applyingLens\")<Lens>(),\n defineState(\"lensApplied\")<Lens>()\n );\n\n return new StateMachine(actions, states, states.noLensApplied(), (events) =>\n merge(\n events.pipe(\n // We allow a new lens to be applied at any time, no matter the state.\n inStates(\"noLensApplied\", \"applyingLens\", \"lensApplied\"),\n forActions(\"applyLens\"),\n map(([a]) => states.applyingLens(a.data.lens))\n ),\n events.pipe(\n inStates(\"applyingLens\"),\n forActions(\"applyLensComplete\"),\n map(([a]) => states.lensApplied(a.data))\n ),\n events.pipe(\n inStates(\"applyingLens\"),\n forActions(\"applyLensFailed\"),\n map(() => states.noLensApplied())\n ),\n events.pipe(\n inStates(\"lensApplied\"),\n forActions(\"removeLensComplete\"),\n map(() => states.noLensApplied())\n )\n )\n );\n};\n\nexport type LensErrors = LegalError | LensContentValidationError | LensError;\n\nexport type LensState = ReturnType<typeof createLensState>;\n\nexport const lensStateFactory = Injectable(\n \"lensState\",\n [\n lensCoreFactory.token,\n lensRepositoryFactory.token,\n lensAssetRepositoryFactory.token,\n lensPersistenceStoreFactory.token,\n legalStateFactory.token,\n operationalMetricReporterFactory.token,\n ] as const,\n (\n lensCore: LensCore,\n lensRepository: LensRepository,\n lensAssetRepository: LensAssetRepository,\n lensPersistence: IndexedDBPersistence<ArrayBuffer>,\n legalState: LegalState,\n operationalMetricsReporter: OperationalMetricsReporter\n ): LensState => {\n const lensState = createLensState();\n let firstLensApply = true;\n\n /**\n * Apply lens\n */\n lensState.events\n .pipe(\n forActions(\"applyLens\"),\n\n // Determine the legal state (e.g. terms have been accepted). Using exhaustMap means while we are\n // ascertaining legal status (which may include prompting the end user to accept terms), we will ignore\n // any new applyLens actions.\n exhaustMap(([a]) =>\n of(legalState.actions.requestLegalPrompt()).pipe(\n dispatch(legalState),\n inStates(\"accepted\", \"rejected\"),\n take(1),\n map(([, { name }]) => {\n if (name === \"accepted\") return a;\n return lensState.actions.applyLensFailed({\n error: legalError(\n `Failed to apply lens ${a.data.lens.id}. Required legal terms were not accepted.`\n ),\n lens: a.data.lens,\n });\n })\n )\n ),\n\n // The use of switchMap is important so that if we get a new applyLens action while we're still\n // downloading lens content for a previously-requested lens, we can cancel those requests and ensure\n // that lenses are applied in the order they're requested.\n switchMap((a) => {\n if (a.name === \"applyLensFailed\") return of(a);\n\n const { lens } = a.data;\n // Convenience method making dispatching an action with Lens data less verbose.\n const dispatch = (action: Extract<Actions<LensState>, { data: Lens }>[\"name\"]) => {\n lensState.dispatch(action, lens);\n };\n\n // We record if this was the first lens apply for this page load, since there may be additional\n // sources of latency (e.g. remote configuration that needs to be loaded) on the first apply that\n // are not present for subsequent applies.\n const applyTimer = new Timer(\"lens\").mark(\"apply\", { first: `${firstLensApply}` });\n firstLensApply = false;\n\n return of(a.data).pipe(\n mergeMap(({ lens, launchData }) => {\n // If retrieval throws an error, we still want to proceed with the lens\n // because persisted data is not a necessity.\n return from(lensPersistence.retrieve(lens.id).catch(() => undefined)).pipe(\n map((persistentStore) => ({ lens, launchData, persistentStore }))\n );\n }),\n\n map(({ lens, launchData, persistentStore }) => {\n const lensDetails = lensRepository.getLensMetadata(lens.id);\n if (!lensDetails) {\n throw new Error(\n `Cannot apply lens ${lens.id}. It has not been loaded by the Lens ` +\n `repository. Use CameraKit.lensRepository.loadLens (or loadLensGroups) ` +\n `to load lens metadata before calling CameraKitSession.applyLens.`\n );\n }\n\n const { content } = lensDetails;\n if (!content) {\n throw new Error(\n `Cannot apply lens ${lens.id}. Metadata retrieved for this lens does not ` +\n `include the lens content URL.`\n );\n }\n\n return {\n lens,\n launchData: encodeLensLaunchData(\n launchData ?? {},\n persistentStore ?? new ArrayBuffer(0)\n ),\n content,\n };\n }),\n\n // Load lens assets and the lens itself in parallel. Both count toward lens download time.\n // TODO: use RxJS fetch utilities so that these requests can be cancelled on unsubscribe.\n mergeMap(({ lens, launchData, content }) => {\n const networkTimer = applyTimer.mark(\"network\");\n\n return from(\n Promise.all([\n lensRepository.getLensContent(lens).finally(() => networkTimer.measure(\"lens\")),\n content.assetManifest.length > 0\n ? lensAssetRepository\n .cacheAssets(content.assetManifest, lens)\n .finally(() => networkTimer.measure(\"assets\"))\n : Promise.resolve(),\n ])\n ).pipe(\n tap(() => {\n networkTimer.measure();\n lensState.dispatch(\"downloadComplete\", lens);\n }),\n map(([{ lensBuffer, lensChecksum }]): AddLensInput => {\n // NOTE: cached array buffer has to be copied each time in order to be reused,\n // otherwise the original cached copy would be detached by LensCore\n // One optimization can be done here: do not copy the array if getLensContent()\n // returned uncached buffer\n const lensDataBuffer = lensBuffer.slice(0);\n return { lensId: lens.id, lensDataBuffer, lensChecksum, launchData };\n })\n );\n }),\n\n // If removeLens is dispatched while downloading, cancel download, don't apply the lens.\n takeUntil(lensState.events.pipe(forActions(\"removeLens\"))),\n\n // Once the lens has downloaded, we can call replaceLenses. We're not concerned about\n // waiting for prior in-progress calls to replaceLenses to complete, because LensCore\n // guarantees that calls to replaceLenses will always be processed sequentially in the order\n // they are received.\n mergeMap(\n (lensInput) =>\n new Observable<Actions<LensState>>((subscriber) => {\n const coreTimer = applyTimer.mark(\"core\");\n\n // replaceLenses has the property that if it fails, LensCore guarantees that no\n // lenses are active – so we can safely dispatch applyLensFailed and transition\n // to noLensApplied state.\n lensCore\n .replaceLenses({\n lenses: [\n {\n ...lensInput,\n onTurnOn: () => dispatch(\"turnedOn\"),\n onResourcesLoaded: () => dispatch(\"resourcesLoaded\"),\n\n // onFirstFrameProcessed marks the end of the lens application for\n // the end-user -- this is when they see the newly applied lens\n // begin to render. As such, this is where we stop our overall\n // latency measurement and report latency metrics.\n onFirstFrameProcessed: () => {\n coreTimer.measure(\"first-frame\");\n applyTimer.measure(\"success\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n dispatch(\"firstFrameProcessed\");\n },\n onTurnOff: () => dispatch(\"turnedOff\"),\n },\n ],\n })\n .then(() => {\n coreTimer.measure(\"success\");\n\n // We emit applyLensComplete (and applyLensFailed, below) on an\n // Observable, which is piped to `dispatch` – this allows `switchMap` to\n // properly cancel the dispatch of these actions if a new applyLens\n // arrives while we're waiting for onSuccess/onFailure.\n //\n // That's desirable behavior, because we don't want the applyingLens\n // state due to a *subsequent applyLens action* to be transitioned to\n // lensApplied by this action.\n subscriber.next(lensState.actions.applyLensComplete(lens));\n subscriber.complete();\n })\n .catch((lensCoreError) => {\n coreTimer.measure(\"failure\");\n applyTimer.measure(\"failure\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n\n const message = `Failed to apply lens ${lensInput.lensId}.`;\n const error = /validation failed/.test(lensCoreError.message)\n ? lensContentValidationError(message, lensCoreError)\n : lensError(message, lensCoreError);\n\n subscriber.next(lensState.actions.applyLensFailed({ error, lens }));\n subscriber.complete();\n });\n })\n ),\n catchError((error: LensErrors) => {\n applyTimer.measure(\"failure\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n return of(lensState.actions.applyLensFailed({ error, lens }));\n }),\n\n // If a new applyLens is received, `switchMap` will unsubscribe from this inner observable,\n // which stops the current lens application. When this happens we can record a separate metric\n // to measure aborted lens applications.\n unsubscribed(() => {\n applyTimer.measure(\"abort\");\n applyTimer.stopAndReport(operationalMetricsReporter);\n })\n );\n }),\n dispatch(lensState)\n )\n .subscribe({\n error: logger.error,\n });\n\n /**\n * Remove lens\n */\n lensState.events\n .pipe(\n inStates(\"lensApplied\", \"noLensApplied\"),\n forActions(\"removeLens\"),\n mergeMap(\n () =>\n new Observable<Actions<LensState>>((subscriber) => {\n lensCore\n .clearAllLenses()\n .then(() => {\n subscriber.next(lensState.actions.removeLensComplete());\n subscriber.complete();\n })\n .catch((lensCoreError) => {\n const error = new Error(\"Failed to remove lenses.\", { cause: lensCoreError });\n subscriber.next(lensState.actions.removeLensFailed(error));\n subscriber.complete();\n });\n })\n ),\n dispatch(lensState)\n )\n .subscribe({\n error: logger.error,\n });\n\n lensState.events\n .pipe(\n inStates(\"applyingLens\"),\n forActions(\"removeLens\"),\n switchMap(([a]) =>\n lensState.events.pipe(\n // Wait to remove the lens until it has been applied.\n inStates(\"lensApplied\"),\n // But cancel the removal if a new applyLens supercedes the current lens. The goal here is to\n // make sure the latest apply/remove pre-empts any previous request to apply/remove.\n takeUntil(lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => a)\n )\n ),\n dispatch(lensState)\n )\n .subscribe({\n error: logger.error,\n });\n\n // Log transitions\n lensState.events.subscribe(([a, s]) => {\n const data = extractLoggableData(a);\n logger.debug(`Action: \"${a.name}\", state: \"${s.name}\"${data ? \", data: \" + JSON.stringify(data) : \"\"}`);\n });\n\n return lensState;\n }\n);\n\nfunction extractLoggableData(action: Actions<LensState>): Record<string, string> | undefined {\n switch (action.name) {\n case \"applyLens\":\n return { lensId: action.data.lens.id };\n case \"applyLensFailed\":\n return { lensId: action.data.lens.id, error: action.data.error.message };\n case \"downloadComplete\":\n case \"turnedOn\":\n case \"resourcesLoaded\":\n case \"firstFrameProcessed\":\n case \"applyLensComplete\":\n case \"applyLensAborted\":\n case \"turnedOff\":\n return { lensId: action.data.id };\n case \"removeLens\":\n case \"removeLensComplete\":\n return undefined;\n case \"removeLensFailed\":\n return { error: action.data.message };\n default:\n assertUnreachable(action);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snap/camera-kit",
3
- "version": "0.14.1",
3
+ "version": "0.15.0",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "description": "Camera Kit Web",
6
6
  "homepage": "https://ar.snap.com/camera-kit",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@improbable-eng/grpc-web": "^0.15.0",
52
- "@snap/state-management": "0.14.1",
52
+ "@snap/state-management": "^0.14.0",
53
53
  "browser-fs-access": "^0.31.1",
54
54
  "browser-headers": "^0.4.1",
55
55
  "long": "^4.0.0",