@snap/camera-kit 0.12.0 → 0.13.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 (219) hide show
  1. package/README.md +25 -3
  2. package/docs/html/assets/search.js +1 -1
  3. package/docs/html/classes/CameraKit.html +12 -7
  4. package/docs/html/classes/CameraKitSession.html +27 -7
  5. package/docs/html/classes/CameraKitSource.html +26 -17
  6. package/docs/html/classes/LensPerformanceMeasurement.html +12 -7
  7. package/docs/html/classes/LensPerformanceMetrics.html +12 -7
  8. package/docs/html/classes/LensRepository.html +12 -7
  9. package/docs/html/classes/LensSources.html +12 -7
  10. package/docs/html/classes/Transform2D.html +12 -7
  11. package/docs/html/classes/TypedCustomEvent.html +12 -7
  12. package/docs/html/classes/TypedEventTarget.html +12 -7
  13. package/docs/html/functions/Injectable.html +12 -7
  14. package/docs/html/functions/bootstrapCameraKit.html +12 -7
  15. package/docs/html/functions/createExtension.html +12 -7
  16. package/docs/html/functions/createImageSource.html +12 -7
  17. package/docs/html/functions/createMediaStreamSource.html +12 -7
  18. package/docs/html/functions/createUserMediaSource.html +12 -7
  19. package/docs/html/functions/createVideoSource.html +12 -7
  20. package/docs/html/functions/estimateLensPerformance.html +12 -7
  21. package/docs/html/functions/getRequiredBootstrapURLs.html +12 -7
  22. package/docs/html/functions/lensSourcesFactory.html +12 -7
  23. package/docs/html/functions/{uriHandlersFactory.html → remoteApiServicesFactory.html} +16 -14
  24. package/docs/html/index.html +40 -12
  25. package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +12 -7
  26. package/docs/html/interfaces/CameraKitSourceSubscriber.html +12 -7
  27. package/docs/html/interfaces/ComputedFrameMetrics.html +12 -7
  28. package/docs/html/interfaces/CreateSessionOptions.html +12 -7
  29. package/docs/html/interfaces/EstimatedLensPerformance.html +12 -7
  30. package/docs/html/interfaces/Lens.html +12 -7
  31. package/docs/html/interfaces/LensSource.html +16 -11
  32. package/docs/html/interfaces/MediaStreamSourceOptions.html +12 -7
  33. package/docs/html/interfaces/Preview.html +12 -7
  34. package/docs/html/interfaces/RemoteApiRequest.html +164 -0
  35. package/docs/html/interfaces/RemoteApiResponse.html +156 -0
  36. package/docs/html/interfaces/{UriHandler.html → RemoteApiService.html} +34 -68
  37. package/docs/html/interfaces/Snapcode.html +12 -7
  38. package/docs/html/interfaces/UriCancelRequest.html +12 -7
  39. package/docs/html/interfaces/UriRequest.html +13 -8
  40. package/docs/html/interfaces/UriResponse.html +12 -7
  41. package/docs/html/interfaces/VideoSourceOptions.html +12 -7
  42. package/docs/html/modules.html +22 -12
  43. package/docs/html/types/AssetLoader.html +12 -7
  44. package/docs/html/types/AssetTiming.html +12 -7
  45. package/docs/html/types/BenchmarkError.html +12 -7
  46. package/docs/html/types/BootstrapError.html +12 -7
  47. package/docs/html/types/CacheKeyNotFoundError.html +12 -7
  48. package/docs/html/types/CameraKitDeviceInfo.html +19 -9
  49. package/docs/html/types/CameraKitDeviceOptions.html +119 -0
  50. package/docs/html/types/CameraKitSessionEventListener.html +12 -7
  51. package/docs/html/types/CameraKitSessionEvents.html +12 -7
  52. package/docs/html/types/CameraKitSourceError.html +12 -7
  53. package/docs/html/types/CameraKitSourceInfo.html +12 -7
  54. package/docs/html/types/CameraKitSourceOptions.html +13 -8
  55. package/docs/html/types/ConfigurationError.html +12 -7
  56. package/docs/html/types/Keyboard.html +12 -7
  57. package/docs/html/types/KeyboardEvents.html +12 -7
  58. package/docs/html/types/LegalError.html +12 -7
  59. package/docs/html/types/LensAssetError.html +12 -7
  60. package/docs/html/types/LensContentValidationError.html +12 -7
  61. package/docs/html/types/LensError.html +12 -7
  62. package/docs/html/types/LensExecutionError.html +12 -7
  63. package/docs/html/types/LensImagePickerError.html +12 -7
  64. package/docs/html/types/LensLaunchParams.html +12 -7
  65. package/docs/html/types/LensMetricsEvents.html +12 -7
  66. package/docs/html/types/LensPerformanceCluster.html +12 -7
  67. package/docs/html/types/LensView.html +12 -7
  68. package/docs/html/types/LensWait.html +12 -7
  69. package/docs/html/types/PersistentStoreError.html +12 -7
  70. package/docs/html/types/PlatformNotSupportedError.html +12 -7
  71. package/docs/html/types/PublicContainer.html +12 -7
  72. package/docs/html/types/RemoteApiRequestHandler.html +141 -0
  73. package/docs/html/types/{UriHandlers.html → RemoteApiServices.html} +15 -13
  74. package/docs/html/types/RemoteApiStatus.html +114 -0
  75. package/docs/html/types/RenderTarget.html +12 -7
  76. package/docs/html/types/Uri.html +12 -7
  77. package/docs/html/types/WebGLError.html +12 -7
  78. package/docs/html/variables/extensionRequestContext.html +12 -7
  79. package/docs/md/README.md +25 -3
  80. package/docs/md/classes/CameraKit.md +1 -1
  81. package/docs/md/classes/CameraKitSession.md +19 -1
  82. package/docs/md/classes/CameraKitSource.md +19 -7
  83. package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
  84. package/docs/md/classes/LensPerformanceMetrics.md +1 -1
  85. package/docs/md/classes/LensRepository.md +1 -1
  86. package/docs/md/classes/LensSources.md +1 -1
  87. package/docs/md/classes/Transform2D.md +1 -1
  88. package/docs/md/classes/TypedCustomEvent.md +1 -1
  89. package/docs/md/classes/TypedEventTarget.md +1 -1
  90. package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +1 -1
  91. package/docs/md/interfaces/CameraKitSourceSubscriber.md +1 -1
  92. package/docs/md/interfaces/ComputedFrameMetrics.md +1 -1
  93. package/docs/md/interfaces/CreateSessionOptions.md +1 -1
  94. package/docs/md/interfaces/EstimatedLensPerformance.md +1 -1
  95. package/docs/md/interfaces/Lens.md +1 -1
  96. package/docs/md/interfaces/LensSource.md +3 -3
  97. package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
  98. package/docs/md/interfaces/Preview.md +1 -1
  99. package/docs/md/interfaces/RemoteApiRequest.md +46 -0
  100. package/docs/md/interfaces/RemoteApiResponse.md +37 -0
  101. package/docs/md/interfaces/RemoteApiService.md +45 -0
  102. package/docs/md/interfaces/Snapcode.md +1 -1
  103. package/docs/md/interfaces/UriCancelRequest.md +1 -1
  104. package/docs/md/interfaces/UriRequest.md +2 -2
  105. package/docs/md/interfaces/UriResponse.md +1 -1
  106. package/docs/md/interfaces/VideoSourceOptions.md +1 -1
  107. package/docs/md/modules.md +66 -15
  108. package/lib/CameraKit.js +3 -1
  109. package/lib/CameraKit.js.map +1 -1
  110. package/lib/__tests__/data.d.ts +1 -1
  111. package/lib/__tests__/data.js +1 -0
  112. package/lib/__tests__/data.js.map +1 -1
  113. package/lib/bootstrapCameraKit.js +12 -10
  114. package/lib/bootstrapCameraKit.js.map +1 -1
  115. package/lib/common/any.d.ts +17 -0
  116. package/lib/common/any.js +36 -0
  117. package/lib/common/any.js.map +1 -0
  118. package/lib/common/cameraKitUserAgent.d.ts +5 -0
  119. package/lib/common/cameraKitUserAgent.js +2 -1
  120. package/lib/common/cameraKitUserAgent.js.map +1 -1
  121. package/lib/common/date.d.ts +3 -0
  122. package/lib/common/date.js +13 -0
  123. package/lib/common/date.js.map +1 -0
  124. package/lib/common/errorHelpers.js +1 -1
  125. package/lib/common/errorHelpers.js.map +1 -1
  126. package/lib/common/time.d.ts +1 -0
  127. package/lib/common/time.js +1 -0
  128. package/lib/common/time.js.map +1 -1
  129. package/lib/common/types.d.ts +8 -0
  130. package/lib/common/types.js.map +1 -1
  131. package/lib/dependency-injection/RootServices.d.ts +2 -0
  132. package/lib/dependency-injection/RootServices.js.map +1 -1
  133. package/lib/environment.json +1 -1
  134. package/lib/extensions/LensSources.d.ts +2 -2
  135. package/lib/extensions/LensSources.js +7 -3
  136. package/lib/extensions/LensSources.js.map +1 -1
  137. package/lib/extensions/RemoteApiServices.d.ts +101 -0
  138. package/lib/extensions/RemoteApiServices.js +198 -0
  139. package/lib/extensions/RemoteApiServices.js.map +1 -0
  140. package/lib/extensions/UriHandlers.d.ts +10 -17
  141. package/lib/extensions/UriHandlers.js +5 -60
  142. package/lib/extensions/UriHandlers.js.map +1 -1
  143. package/lib/extensions/uriHandlersRegister.d.ts +21 -0
  144. package/lib/extensions/uriHandlersRegister.js +72 -0
  145. package/lib/extensions/uriHandlersRegister.js.map +1 -0
  146. package/lib/generated-proto/pb_schema/camera_kit/v3/features/remote_api_info.d.ts +31 -0
  147. package/lib/generated-proto/pb_schema/camera_kit/v3/features/remote_api_info.js +43 -0
  148. package/lib/generated-proto/pb_schema/camera_kit/v3/features/remote_api_info.js.map +1 -0
  149. package/lib/generated-proto/pb_schema/cdp/cof/namespace.d.ts +1 -0
  150. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js +1 -0
  151. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js.map +1 -1
  152. package/lib/generated-proto/pb_schema/lenses/remote_api/remote_api_service.d.ts +569 -0
  153. package/lib/generated-proto/pb_schema/lenses/remote_api/remote_api_service.js +1175 -0
  154. package/lib/generated-proto/pb_schema/lenses/remote_api/remote_api_service.js.map +1 -0
  155. package/lib/handlers/defaultFetchHandler.js +17 -4
  156. package/lib/handlers/defaultFetchHandler.js.map +1 -1
  157. package/lib/index.d.ts +1 -0
  158. package/lib/index.js +1 -0
  159. package/lib/index.js.map +1 -1
  160. package/lib/legal/legalState.js +1 -1
  161. package/lib/legal/legalState.js.map +1 -1
  162. package/lib/lens/lensHttpUtil.js +26 -4
  163. package/lib/lens/lensHttpUtil.js.map +1 -1
  164. package/lib/lens-core-module/generated-types.d.ts +24 -4
  165. package/lib/lens-core-module/generated-types.js.map +1 -1
  166. package/lib/lensCoreWasmVersions.json +3 -3
  167. package/lib/logger/registerLogEntriesSubscriber.js +13 -1
  168. package/lib/logger/registerLogEntriesSubscriber.js.map +1 -1
  169. package/lib/media-sources/CameraKitSource.d.ts +13 -3
  170. package/lib/media-sources/CameraKitSource.js +2 -8
  171. package/lib/media-sources/CameraKitSource.js.map +1 -1
  172. package/lib/media-sources/FunctionSource.d.ts +1 -1
  173. package/lib/media-sources/FunctionSource.js +1 -1
  174. package/lib/media-sources/FunctionSource.js.map +1 -1
  175. package/lib/media-sources/ImageSource.d.ts +1 -1
  176. package/lib/media-sources/ImageSource.js +1 -1
  177. package/lib/media-sources/ImageSource.js.map +1 -1
  178. package/lib/media-sources/MediaStreamSource.d.ts +1 -1
  179. package/lib/media-sources/MediaStreamSource.js +2 -1
  180. package/lib/media-sources/MediaStreamSource.js.map +1 -1
  181. package/lib/media-sources/VideoSource.d.ts +1 -1
  182. package/lib/media-sources/VideoSource.js +1 -1
  183. package/lib/media-sources/VideoSource.js.map +1 -1
  184. package/lib/metrics/businessEventsReporter.d.ts +3 -2
  185. package/lib/metrics/businessEventsReporter.js +125 -65
  186. package/lib/metrics/businessEventsReporter.js.map +1 -1
  187. package/lib/metrics/operational/operationalMetricsReporter.js +23 -5
  188. package/lib/metrics/operational/operationalMetricsReporter.js.map +1 -1
  189. package/lib/metrics/reporters/reportHttpMetrics.d.ts +0 -7
  190. package/lib/metrics/reporters/reportHttpMetrics.js +3 -2
  191. package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -1
  192. package/lib/metrics/reporters/reportLensView.d.ts +1 -1
  193. package/lib/metrics/reporters/reportLensView.js +41 -13
  194. package/lib/metrics/reporters/reportLensView.js.map +1 -1
  195. package/lib/metrics/reporters/reportUserSession.js +15 -16
  196. package/lib/metrics/reporters/reportUserSession.js.map +1 -1
  197. package/lib/metrics/reporters/reporters.d.ts +1 -1
  198. package/lib/persistence/ExpiringPersistence.d.ts +2 -1
  199. package/lib/persistence/ExpiringPersistence.js +15 -1
  200. package/lib/persistence/ExpiringPersistence.js.map +1 -1
  201. package/lib/persistence/IndexedDBPersistence.d.ts +1 -1
  202. package/lib/persistence/IndexedDBPersistence.js +11 -1
  203. package/lib/persistence/IndexedDBPersistence.js.map +1 -1
  204. package/lib/persistence/Persistence.d.ts +1 -1
  205. package/lib/persistence/Persistence.js.map +1 -1
  206. package/lib/remote-configuration/preloadConfiguration.d.ts +7 -0
  207. package/lib/remote-configuration/preloadConfiguration.js +15 -0
  208. package/lib/remote-configuration/preloadConfiguration.js.map +1 -0
  209. package/lib/remote-configuration/remoteConfiguration.d.ts +5 -1
  210. package/lib/remote-configuration/remoteConfiguration.js +10 -2
  211. package/lib/remote-configuration/remoteConfiguration.js.map +1 -1
  212. package/lib/session/CameraKitSession.d.ts +7 -2
  213. package/lib/session/CameraKitSession.js +1 -0
  214. package/lib/session/CameraKitSession.js.map +1 -1
  215. package/lib/session/sessionState.d.ts +2 -2
  216. package/lib/session/sessionState.js +3 -3
  217. package/lib/session/sessionState.js.map +1 -1
  218. package/package.json +2 -1
  219. package/docs/md/interfaces/UriHandler.md +0 -63
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrapCameraKit.js","sourceRoot":"","sources":["../src/bootstrapCameraKit.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAC7D,OAAO,EAAa,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,2CAA2C,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,EAAE,6BAA6B,EAAE,MAAM,6CAA6C,CAAC;AAC5F,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,mCAAmC,EAAE,MAAM,gDAAgD,CAAC;AACrG,OAAO,EAAmC,mCAAmC,EAAE,MAAM,iBAAiB,CAAC;AAEvG,OAAO,EAAE,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,gCAAgC,EAAE,MAAM,kDAAkD,CAAC;AACpG,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;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,EAAE,GAAG,WAAW,CAAC;YACxD,MAAM,QAAQ,GAAG,SAAS,CAAC,GAAG,CAAC,gCAAgC,CAAC,KAAK,CAAC,CAAC;YACvE,QAAQ,CAAC,KAAK,CAAC,gBAAgB,EAAE,eAAe,CAAC,CAAC;YAElD,OAAO,SAAS,CAAC;SACpB;QAAC,OAAO,KAAK,EAAE;YACZ,IAAI,eAAe,CAAC,KAAK,CAAC,EAAE;gBACxB,KAAK,GAAG,cAAc,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;aACpF;YACD,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,KAAK,CAAC;SACf;IACL,CAAC;CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAM,UAAU,eAAe;IAC3B,OAAO,IAAI,gBAAgB,CAAC,EAAE,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { lensRepositoryFactory } from \"./lens/LensRepository\";\nimport { Container } from \"./dependency-injection/Container\";\nimport { CameraKit, cameraKitFactory } from \"./CameraKit\";\nimport { lensCoreFactory } from \"./lens-core-module/loader/lensCoreFactory\";\nimport { Injectable } from \"./dependency-injection/Injectable\";\nimport { remoteMediaAssetLoaderFactory } from \"./lens/assets/remoteMediaAssetLoaderFactory\";\nimport { deviceDependentAssetLoaderFactory } from \"./lens/assets/deviceDependentAssetLoader\";\nimport { staticAssetLoaderFactory } from \"./lens/assets/staticAssetLoader\";\nimport { defaultFetchHandlerFactory } from \"./handlers/defaultFetchHandler\";\nimport { cameraKitServiceFetchHandlerFactory } from \"./handlers/cameraKitServiceFetchHandlerFactory\";\nimport { CameraKitBootstrapConfiguration, createCameraKitConfigurationFactory } from \"./configuration\";\nimport { PublicServices } from \"./dependency-injection/RootServices\";\nimport { PartialContainer } from \"./dependency-injection/PartialContainer\";\nimport { metricsHandlerFactory } from \"./metrics/metricsHandler\";\nimport { operationalMetricReporterFactory } from \"./metrics/operational/operationalMetricsReporter\";\nimport { lensSourcesFactory } from \"./extensions/LensSources\";\nimport { uriHandlersFactory } from \"./extensions/UriHandlers\";\nimport { assert } from \"./common/assertions\";\nimport { isSafeString } from \"./common/typeguards\";\nimport { metricsEventTargetFactory } from \"./metrics/metricsEventTarget\";\nimport { reportGloballyScopedMetrics } from \"./metrics/reporters/reporters\";\nimport { getLogger } from \"./logger/logger\";\nimport { logEntriesFactory } from \"./logger/logEntries\";\nimport { assertPlatformSupported } from \"./assertPlatformSupported\";\nimport { lensPersistenceStoreFactory } from \"./lens/LensPersistenceStore\";\nimport { remoteConfigurationFactory } from \"./remote-configuration/remoteConfiguration\";\nimport { lensAssetRepositoryFactory } from \"./lens/assets/LensAssetRepository\";\nimport { legalStateFactory } from \"./legal/legalState\";\nimport { legalPromptFactory } from \"./legal/legalPrompt\";\nimport { bootstrapError, ConfigurationError, configurationError, PlatformNotSupportedError } from \"./namedErrors\";\nimport { businessEventsReporterFactory } from \"./metrics/businessEventsReporter\";\nimport { reportGlobalException } from \"./metrics/reporters/reportGlobalException\";\nimport { registerLogEntriesSubscriber } from \"./logger/registerLogEntriesSubscriber\";\nimport { requestStateEventTargetFactory } from \"./handlers/requestStateEmittingHandler\";\nimport { pageVisibilityFactory } from \"./common/pageVisibility\";\nimport { cofHandlerFactory } from \"./remote-configuration/cofHandler\";\n\nconst logger = getLogger(\"bootstrapCameraKit\");\n\n// The following errors are not wrapped with BootstrapError and bubble up as is.\nconst nonWrappableErrors: [ConfigurationError[\"name\"], PlatformNotSupportedError[\"name\"]] = [\n \"ConfigurationError\",\n \"PlatformNotSupportedError\",\n];\n\n/**\n * Returns true if given error has to be wrapped with BoostrapError.\n */\nfunction shouldWrapError(error: unknown): boolean {\n if (error instanceof Error) {\n return !nonWrappableErrors.some((name) => error.name === name);\n }\n return true;\n}\n\n/**\n * For more advanced use-cases, this DI Container holds services for which a custom implementation may be provided by\n * the application.\n *\n * @category Bootstrapping and Configuration\n */\nexport type PublicContainer = Container<PublicServices>;\n\n/**\n * Bootstrap CameraKit. This will download the WebAssembly code which powers CameraKit's rendering engine, and return\n * an instance of {@link CameraKit}.\n *\n * CameraKit must be provided with some configuration (the application's API token), and there are some additional\n * configurations which are optional.\n *\n * Descriptions of the available configurations can be found in the documentation for\n * {@link CameraKitBootstrapConfiguration}\n *\n * ---\n *\n * There is also a second, more advanced way to modify CameraKit to provide greater flexibility to support less common\n * use cases.\n *\n * This requires some knowledge of CameraKit's dependency injection system, and allows applications to provide their\n * own custom implementations of certain CameraKit components. This functionality will only be needed by applications\n * with very specific, more advanced requirements.\n *\n * @example\n * ```ts\n * // The most common way to bootstrap:\n * const cameraKit = await bootstrapCameraKit({ apiToken: myApiToken })\n *\n * // For special advanced use-cases, it is possible to provide custom implementations for certain CameraKit components.\n * const cameraKit = await bootstrapCameraKit(config, (container) => {\n * return container.provides(myCustomRemoteMediaAssetLoaderFactory)\n * })\n * ```\n *\n * @param configuration Configure CameraKit with e.g. credentials, global resource endpoints, etc.\n * @param provide Optional function that can make modifications to CameraKit's root DI container.\n * @returns A {@link CameraKit} instance, which is the entry point to CameraKit's API.\n *\n * @throws\n * - {@link ConfigurationError} when provided configuration object is invalid\n * - {@link PlatformNotSupportedError} when current platform is not supported by CameraKit\n * - {@link BootstrapError} when a failure occurs while initializing CameraKit and downloading the render engine\n * WebAssembly binary.\n *\n * @category Bootstrapping and Configuration\n */\nexport async function bootstrapCameraKit(\n configuration: CameraKitBootstrapConfiguration,\n provide?: (c: PublicContainer) => PublicContainer\n): Promise<CameraKit> {\n try {\n const startTimeMs = performance.now();\n\n assert(isSafeString(configuration.apiToken), configurationError(\"Invalid or unsafe apiToken provided.\"));\n\n const configurationFactory = createCameraKitConfigurationFactory(configuration);\n\n // Public container holds services which applications can overwrite with their own implementations.\n const defaultPublicContainer = Container.provides(configurationFactory)\n .provides(pageVisibilityFactory)\n .provides(defaultFetchHandlerFactory)\n .provides(remoteMediaAssetLoaderFactory)\n .provides(lensSourcesFactory)\n .provides(uriHandlersFactory);\n\n const publicContainer = provide ? provide(defaultPublicContainer) : defaultPublicContainer;\n\n // Now that the client's provide() function has completed and the configuration override is ready,\n // we create another container to initialize the logger. This ensures that logging is available\n // as we continue bootstrapping. We don't initialize the logger as part of the defaultPublicContainer\n // because we don't want applications to provide their own logger implementations,\n // and we're not interested in errors thrown by their provide() function.\n // Below is the minimum required container to report errors to Blizzard.\n const telemetryContainer = Container.provides(publicContainer)\n .provides(logEntriesFactory)\n .run(registerLogEntriesSubscriber)\n .provides(cameraKitServiceFetchHandlerFactory)\n .provides(requestStateEventTargetFactory)\n .provides(metricsEventTargetFactory)\n .provides(metricsHandlerFactory)\n .provides(operationalMetricReporterFactory)\n .provides(reportGlobalException)\n .run(businessEventsReporterFactory);\n\n // Run the exception logger so that it can subscribe to log events -- we can't use `Container.run()` because\n // reportGlobalException is also used as a dependency by other Services (and run does not provide Services,\n // it just runs them once).\n telemetryContainer.get(reportGlobalException.token);\n\n // At this point, logger is configured to report to console and Blizzard.\n\n assertPlatformSupported();\n\n // LensCore is a foundational component which must be created asynchronously.\n // But it's annoying for every consumer of LensCore to have to wait on Promise<LensCore>\n // (which means they become async themselves). So we'll create a DI container which provides Promise<LensCore>,\n // wait for that promise once here, then create a new DI container that just contains LensCore.\n const lensCore = await telemetryContainer.provides(lensCoreFactory).get(lensCoreFactory.token);\n\n const container = telemetryContainer\n .provides(Injectable(lensCoreFactory.token, () => lensCore))\n .provides(cofHandlerFactory)\n .provides(remoteConfigurationFactory)\n .provides(lensPersistenceStoreFactory)\n .provides(deviceDependentAssetLoaderFactory)\n .provides(staticAssetLoaderFactory)\n .provides(lensAssetRepositoryFactory)\n .provides(lensRepositoryFactory)\n .provides(legalPromptFactory)\n .provides(legalStateFactory)\n .provides(cameraKitFactory)\n // We'll run a PartialContainer containing reporters for globally-scoped metrics. Running this container\n // allows each metric reporter to initialize itself (e.g. by adding event listeners to detect when certain\n // actions occur). This PartialContainer also includes the service which listens to locally-reported metrics\n // and sends them to our backend.\n .run(reportGloballyScopedMetrics);\n\n const cameraKit = container.get(cameraKitFactory.token);\n\n const bootstrapTimeMs = performance.now() - startTimeMs;\n const reporter = container.get(operationalMetricReporterFactory.token);\n reporter.timer(\"bootstrap_time\", bootstrapTimeMs);\n\n return cameraKit;\n } catch (error) {\n if (shouldWrapError(error)) {\n error = bootstrapError(\"Error occurred during Camera Kit bootstrapping.\", error);\n }\n logger.error(error);\n throw error;\n }\n}\n\n/**\n * Extensions offer a way to provide custom implementations of certain parts of the CameraKit SDK.\n *\n * This enables more advanced use-cases, in which the default behavior of the SDK is substantially altered. For example,\n * replacing the default implementation that loads remote lens assets with a custom implementation that returns\n * different assets based on some business logic within the application.\n *\n * An extension is implemented as a [PartialContainer] – a collection of factory functions, each with its own\n * dependencies, which each provide some \"Service.\" A Service can be of any type, and the CameraKit SDK defines its\n * own Services, some of which can be overridden by providing a custom implementation of the type via an extension.\n *\n * Here's an example of how extensions might be used:\n * ```ts\n * import { bootstrapCameraKit, createExtension, remoteMediaAssetLoaderFactory } from '@snap/camera-kit'\n *\n * const myCustomRemoteAssetLoader = Injectable(\n * remoteMediaAssetLoaderFactory.token,\n * [remoteMediaAssetLoaderFactory.token] as const,\n * (defaultLoader: AssetLoader): AssetLoader => {\n * return async (asset, lens) => {\n * if (lens?.id === MY_SPECIAL_LENS) {\n * return (await fetch('my/asset.glb')).arrayBuffer()\n * }\n * return defaultLoader(asset, lens)\n * }\n * },\n * )\n *\n * const myExtension = createExtension().provides(myCustomeRemoteAssetLoader)\n * const cameraKit = bootstrapCameraKit(config, container => container.provides(myExtension))\n * ```\n *\n * This also enables greater modularity – the person/team creating the extension can do so in their own package, which\n * could be shared by many applications that all require the same functionality.\n *\n * @returns A {@link PartialContainer} which can be used to create a collection of Services, and can later be provided\n * to CameraKit's DI container during {@link bootstrapCameraKit}.\n *\n * @category Bootstrapping and Configuration\n */\nexport function createExtension(): PartialContainer {\n return new PartialContainer({});\n}\n"]}
1
+ {"version":3,"file":"bootstrapCameraKit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CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;aACpF;YACD,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,KAAK,CAAC;SACf;IACL,CAAC;CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAM,UAAU,eAAe;IAC3B,OAAO,IAAI,gBAAgB,CAAC,EAAE,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { lensRepositoryFactory } from \"./lens/LensRepository\";\nimport { Container } from \"./dependency-injection/Container\";\nimport { CameraKit, cameraKitFactory } from \"./CameraKit\";\nimport { lensCoreFactory } from \"./lens-core-module/loader/lensCoreFactory\";\nimport { Injectable } from \"./dependency-injection/Injectable\";\nimport { remoteMediaAssetLoaderFactory } from \"./lens/assets/remoteMediaAssetLoaderFactory\";\nimport { deviceDependentAssetLoaderFactory } from \"./lens/assets/deviceDependentAssetLoader\";\nimport { staticAssetLoaderFactory } from \"./lens/assets/staticAssetLoader\";\nimport { defaultFetchHandlerFactory } from \"./handlers/defaultFetchHandler\";\nimport { cameraKitServiceFetchHandlerFactory } from \"./handlers/cameraKitServiceFetchHandlerFactory\";\nimport { CameraKitBootstrapConfiguration, createCameraKitConfigurationFactory } from \"./configuration\";\nimport { PublicServices } from \"./dependency-injection/RootServices\";\nimport { PartialContainer } from \"./dependency-injection/PartialContainer\";\nimport { metricsHandlerFactory } from \"./metrics/metricsHandler\";\nimport { operationalMetricReporterFactory } from \"./metrics/operational/operationalMetricsReporter\";\nimport { lensSourcesFactory } from \"./extensions/LensSources\";\nimport { uriHandlersFactory } from \"./extensions/UriHandlers\";\nimport { assert } from \"./common/assertions\";\nimport { isSafeString } from \"./common/typeguards\";\nimport { metricsEventTargetFactory } from \"./metrics/metricsEventTarget\";\nimport { reportGloballyScopedMetrics } from \"./metrics/reporters/reporters\";\nimport { getLogger } from \"./logger/logger\";\nimport { logEntriesFactory } from \"./logger/logEntries\";\nimport { assertPlatformSupported } from \"./assertPlatformSupported\";\nimport { lensPersistenceStoreFactory } from \"./lens/LensPersistenceStore\";\nimport { remoteConfigurationFactory } from \"./remote-configuration/remoteConfiguration\";\nimport { lensAssetRepositoryFactory } from \"./lens/assets/LensAssetRepository\";\nimport { legalStateFactory } from \"./legal/legalState\";\nimport { legalPromptFactory } from \"./legal/legalPrompt\";\nimport { bootstrapError, ConfigurationError, configurationError, PlatformNotSupportedError } from \"./namedErrors\";\nimport { businessEventsReporterFactory } from \"./metrics/businessEventsReporter\";\nimport { reportGlobalException } from \"./metrics/reporters/reportGlobalException\";\nimport { registerLogEntriesSubscriber } from \"./logger/registerLogEntriesSubscriber\";\nimport { requestStateEventTargetFactory } from \"./handlers/requestStateEmittingHandler\";\nimport { pageVisibilityFactory } from \"./common/pageVisibility\";\nimport { cofHandlerFactory } from \"./remote-configuration/cofHandler\";\nimport { remoteApiServicesFactory } from \"./extensions/RemoteApiServices\";\n\nconst logger = getLogger(\"bootstrapCameraKit\");\n\n// The following errors are not wrapped with BootstrapError and bubble up as is.\nconst nonWrappableErrors: [ConfigurationError[\"name\"], PlatformNotSupportedError[\"name\"]] = [\n \"ConfigurationError\",\n \"PlatformNotSupportedError\",\n];\n\n/**\n * Returns true if given error has to be wrapped with BoostrapError.\n */\nfunction shouldWrapError(error: unknown): boolean {\n if (error instanceof Error) {\n return !nonWrappableErrors.some((name) => error.name === name);\n }\n return true;\n}\n\n/**\n * For more advanced use-cases, this DI Container holds services for which a custom implementation may be provided by\n * the application.\n *\n * @category Bootstrapping and Configuration\n */\nexport type PublicContainer = Container<PublicServices>;\n\n/**\n * Bootstrap CameraKit. This will download the WebAssembly code which powers CameraKit's rendering engine, and return\n * an instance of {@link CameraKit}.\n *\n * CameraKit must be provided with some configuration (the application's API token), and there are some additional\n * configurations which are optional.\n *\n * Descriptions of the available configurations can be found in the documentation for\n * {@link CameraKitBootstrapConfiguration}\n *\n * ---\n *\n * There is also a second, more advanced way to modify CameraKit to provide greater flexibility to support less common\n * use cases.\n *\n * This requires some knowledge of CameraKit's dependency injection system, and allows applications to provide their\n * own custom implementations of certain CameraKit components. This functionality will only be needed by applications\n * with very specific, more advanced requirements.\n *\n * @example\n * ```ts\n * // The most common way to bootstrap:\n * const cameraKit = await bootstrapCameraKit({ apiToken: myApiToken })\n *\n * // For special advanced use-cases, it is possible to provide custom implementations for certain CameraKit components.\n * const cameraKit = await bootstrapCameraKit(config, (container) => {\n * return container.provides(myCustomRemoteMediaAssetLoaderFactory)\n * })\n * ```\n *\n * @param configuration Configure CameraKit with e.g. credentials, global resource endpoints, etc.\n * @param provide Optional function that can make modifications to CameraKit's root DI container.\n * @returns A {@link CameraKit} instance, which is the entry point to CameraKit's API.\n *\n * @throws\n * - {@link ConfigurationError} when provided configuration object is invalid\n * - {@link PlatformNotSupportedError} when current platform is not supported by CameraKit\n * - {@link BootstrapError} when a failure occurs while initializing CameraKit and downloading the render engine\n * WebAssembly binary.\n *\n * @category Bootstrapping and Configuration\n */\nexport async function bootstrapCameraKit(\n configuration: CameraKitBootstrapConfiguration,\n provide?: (c: PublicContainer) => PublicContainer\n): Promise<CameraKit> {\n try {\n const startTimeMs = performance.now();\n\n assert(isSafeString(configuration.apiToken), configurationError(\"Invalid or unsafe apiToken provided.\"));\n\n const configurationFactory = createCameraKitConfigurationFactory(configuration);\n\n // Public container holds services which applications can overwrite with their own implementations.\n const defaultPublicContainer = Container.provides(configurationFactory)\n .provides(pageVisibilityFactory)\n .provides(defaultFetchHandlerFactory)\n .provides(remoteMediaAssetLoaderFactory)\n .provides(lensSourcesFactory)\n .provides(remoteApiServicesFactory)\n .provides(uriHandlersFactory);\n\n const publicContainer = provide ? provide(defaultPublicContainer) : defaultPublicContainer;\n\n // Now that the client's provide() function has completed and the configuration override is ready,\n // we create another container to initialize the logger. This ensures that logging is available\n // as we continue bootstrapping. We don't initialize the logger as part of the defaultPublicContainer\n // because we don't want applications to provide their own logger implementations,\n // and we're not interested in errors thrown by their provide() function.\n // Below is the minimum required container to report errors to Blizzard.\n const telemetryContainer = Container.provides(publicContainer)\n .provides(logEntriesFactory)\n .run(registerLogEntriesSubscriber)\n .provides(cameraKitServiceFetchHandlerFactory)\n .provides(requestStateEventTargetFactory)\n .provides(metricsEventTargetFactory)\n .provides(metricsHandlerFactory)\n .provides(operationalMetricReporterFactory)\n .provides(reportGlobalException)\n .provides(cofHandlerFactory)\n .provides(remoteConfigurationFactory)\n .provides(legalPromptFactory)\n .provides(legalStateFactory)\n // We'll run a PartialContainer containing reporters for globally-scoped metrics. Running this container\n // allows each metric reporter to initialize itself (e.g. by adding event listeners to detect when certain\n // actions occur). This PartialContainer also includes the service which listens to locally-reported metrics\n // and sends them to our backend.\n .run(reportGloballyScopedMetrics)\n .run(businessEventsReporterFactory);\n\n // Run the exception logger so that it can subscribe to log events -- we can't use `Container.run()` because\n // reportGlobalException is also used as a dependency by other Services (and run does not provide Services,\n // it just runs them once).\n telemetryContainer.get(reportGlobalException.token);\n\n // At this point, logger is configured to report to console and Blizzard.\n\n assertPlatformSupported();\n\n // LensCore is a foundational component which must be created asynchronously.\n // But it's annoying for every consumer of LensCore to have to wait on Promise<LensCore>\n // (which means they become async themselves). So we'll create a DI container which provides Promise<LensCore>,\n // wait for that promise once here, then create a new DI container that just contains LensCore.\n const lensCore = await telemetryContainer.provides(lensCoreFactory).get(lensCoreFactory.token);\n\n const container = telemetryContainer\n .provides(Injectable(lensCoreFactory.token, () => lensCore))\n .provides(lensPersistenceStoreFactory)\n .provides(deviceDependentAssetLoaderFactory)\n .provides(staticAssetLoaderFactory)\n .provides(lensAssetRepositoryFactory)\n .provides(lensRepositoryFactory)\n\n .provides(cameraKitFactory);\n\n const cameraKit = container.get(cameraKitFactory.token);\n\n const bootstrapTimeMs = performance.now() - startTimeMs;\n const reporter = container.get(operationalMetricReporterFactory.token);\n reporter.timer(\"bootstrap_time\", bootstrapTimeMs);\n\n return cameraKit;\n } catch (error) {\n if (shouldWrapError(error)) {\n error = bootstrapError(\"Error occurred during Camera Kit bootstrapping.\", error);\n }\n logger.error(error);\n throw error;\n }\n}\n\n/**\n * Extensions offer a way to provide custom implementations of certain parts of the CameraKit SDK.\n *\n * This enables more advanced use-cases, in which the default behavior of the SDK is substantially altered. For example,\n * replacing the default implementation that loads remote lens assets with a custom implementation that returns\n * different assets based on some business logic within the application.\n *\n * An extension is implemented as a [PartialContainer] – a collection of factory functions, each with its own\n * dependencies, which each provide some \"Service.\" A Service can be of any type, and the CameraKit SDK defines its\n * own Services, some of which can be overridden by providing a custom implementation of the type via an extension.\n *\n * Here's an example of how extensions might be used:\n * ```ts\n * import { bootstrapCameraKit, createExtension, remoteMediaAssetLoaderFactory } from '@snap/camera-kit'\n *\n * const myCustomRemoteAssetLoader = Injectable(\n * remoteMediaAssetLoaderFactory.token,\n * [remoteMediaAssetLoaderFactory.token] as const,\n * (defaultLoader: AssetLoader): AssetLoader => {\n * return async (asset, lens) => {\n * if (lens?.id === MY_SPECIAL_LENS) {\n * return (await fetch('my/asset.glb')).arrayBuffer()\n * }\n * return defaultLoader(asset, lens)\n * }\n * },\n * )\n *\n * const myExtension = createExtension().provides(myCustomeRemoteAssetLoader)\n * const cameraKit = bootstrapCameraKit(config, container => container.provides(myExtension))\n * ```\n *\n * This also enables greater modularity – the person/team creating the extension can do so in their own package, which\n * could be shared by many applications that all require the same functionality.\n *\n * @returns A {@link PartialContainer} which can be used to create a collection of Services, and can later be provided\n * to CameraKit's DI container during {@link bootstrapCameraKit}.\n *\n * @category Bootstrapping and Configuration\n */\nexport function createExtension(): PartialContainer {\n return new PartialContainer({});\n}\n"]}
@@ -0,0 +1,17 @@
1
+ import { Any } from "../generated-proto/pb_schema/google/protobuf/any";
2
+ export declare const knownAnyTypes: {
3
+ remoteApiInfo: string;
4
+ };
5
+ /**
6
+ * JSON-serialized any message according to spec: https://protobuf.dev/reference/protobuf/google.protobuf/#json
7
+ */
8
+ export interface AnyJson extends Record<string, unknown> {
9
+ "@type": string;
10
+ }
11
+ /**
12
+ * Gets JSON-serialized any message and maps it to JS representation of Any type.
13
+ * @param jsonAny JSON-serialized any message according to spec:
14
+ * https://protobuf.dev/reference/protobuf/google.protobuf/#json
15
+ * @returns JS representation of Any proto message.
16
+ */
17
+ export declare function encodeKnownAnyJson(jsonAny: AnyJson): Any | void;
@@ -0,0 +1,36 @@
1
+ import { RemoteApiInfo } from "../generated-proto/pb_schema/camera_kit/v3/features/remote_api_info";
2
+ // There is a discrepancy in how the CameraKit backend and ts-proto serialize a protobuf message into JSON.
3
+ // The backend serialization follows the spec outlined here:
4
+ // https://protobuf.dev/reference/protobuf/google.protobuf/#json
5
+ // According to this specification, the actual message is represented as JSON
6
+ // with an additional @type discriminator field.
7
+ // However, this approach is not consistent with what the client-side expects for Any.
8
+ // It requires it to be in the format { typeUrl: string, value: UInt8Array }.
9
+ // Therefore, we need to map the JSON representation of Any to the actual Any message.
10
+ // This issue only applies to JSON-serialized protos returned by our backend.
11
+ // The JSON serialization of the ts-proto package that we use
12
+ // does not appear to be following the spec regarding Any.
13
+ // Even if it does, the deserialization part has to be handled manually.
14
+ // This issue does not apply to cases where the Lens object is deserialized from a binary proto message.
15
+ // Ideally, to fix this issue, we want to switch to gRPC web for our backend communication,
16
+ // similar to how we do it for COF. Ticket: https://jira.sc-corp.net/browse/CAMKIT-4668
17
+ export const knownAnyTypes = {
18
+ remoteApiInfo: "type.googleapis.com/com.snap.camerakit.v3.features.RemoteApiInfo",
19
+ };
20
+ /**
21
+ * Gets JSON-serialized any message and maps it to JS representation of Any type.
22
+ * @param jsonAny JSON-serialized any message according to spec:
23
+ * https://protobuf.dev/reference/protobuf/google.protobuf/#json
24
+ * @returns JS representation of Any proto message.
25
+ */
26
+ export function encodeKnownAnyJson(jsonAny) {
27
+ const typeUrl = jsonAny["@type"];
28
+ if (typeUrl === knownAnyTypes.remoteApiInfo) {
29
+ return {
30
+ typeUrl,
31
+ // Safety: we know that spec ensures all message fields to exists
32
+ value: RemoteApiInfo.encode(jsonAny).finish(),
33
+ };
34
+ }
35
+ }
36
+ //# sourceMappingURL=any.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"any.js","sourceRoot":"","sources":["../../src/common/any.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qEAAqE,CAAC;AAGpG,2GAA2G;AAC3G,4DAA4D;AAC5D,gEAAgE;AAChE,6EAA6E;AAC7E,gDAAgD;AAChD,sFAAsF;AACtF,6EAA6E;AAC7E,sFAAsF;AACtF,6EAA6E;AAC7E,6DAA6D;AAC7D,0DAA0D;AAC1D,wEAAwE;AACxE,wGAAwG;AACxG,2FAA2F;AAC3F,uFAAuF;AAEvF,MAAM,CAAC,MAAM,aAAa,GAAG;IACzB,aAAa,EAAE,kEAAkE;CACpF,CAAC;AASF;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAgB;IAC/C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACjC,IAAI,OAAO,KAAK,aAAa,CAAC,aAAa,EAAE;QACzC,OAAO;YACH,OAAO;YACP,iEAAiE;YACjE,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,OAAmC,CAAC,CAAC,MAAM,EAAE;SAC5E,CAAC;KACL;AACL,CAAC","sourcesContent":["import { RemoteApiInfo } from \"../generated-proto/pb_schema/camera_kit/v3/features/remote_api_info\";\nimport { Any } from \"../generated-proto/pb_schema/google/protobuf/any\";\n\n// There is a discrepancy in how the CameraKit backend and ts-proto serialize a protobuf message into JSON.\n// The backend serialization follows the spec outlined here:\n// https://protobuf.dev/reference/protobuf/google.protobuf/#json\n// According to this specification, the actual message is represented as JSON\n// with an additional @type discriminator field.\n// However, this approach is not consistent with what the client-side expects for Any.\n// It requires it to be in the format { typeUrl: string, value: UInt8Array }.\n// Therefore, we need to map the JSON representation of Any to the actual Any message.\n// This issue only applies to JSON-serialized protos returned by our backend.\n// The JSON serialization of the ts-proto package that we use\n// does not appear to be following the spec regarding Any.\n// Even if it does, the deserialization part has to be handled manually.\n// This issue does not apply to cases where the Lens object is deserialized from a binary proto message.\n// Ideally, to fix this issue, we want to switch to gRPC web for our backend communication,\n// similar to how we do it for COF. Ticket: https://jira.sc-corp.net/browse/CAMKIT-4668\n\nexport const knownAnyTypes = {\n remoteApiInfo: \"type.googleapis.com/com.snap.camerakit.v3.features.RemoteApiInfo\",\n};\n\n/**\n * JSON-serialized any message according to spec: https://protobuf.dev/reference/protobuf/google.protobuf/#json\n */\nexport interface AnyJson extends Record<string, unknown> {\n \"@type\": string;\n}\n\n/**\n * Gets JSON-serialized any message and maps it to JS representation of Any type.\n * @param jsonAny JSON-serialized any message according to spec:\n * https://protobuf.dev/reference/protobuf/google.protobuf/#json\n * @returns JS representation of Any proto message.\n */\nexport function encodeKnownAnyJson(jsonAny: AnyJson): Any | void {\n const typeUrl = jsonAny[\"@type\"];\n if (typeUrl === knownAnyTypes.remoteApiInfo) {\n return {\n typeUrl,\n // Safety: we know that spec ensures all message fields to exists\n value: RemoteApiInfo.encode(jsonAny as unknown as RemoteApiInfo).finish(),\n };\n }\n}\n"]}
@@ -7,9 +7,13 @@ interface NavigatorUAData {
7
7
  mobile: boolean;
8
8
  platform: string;
9
9
  }
10
+ export type ConnectionType = "bluetooth" | "cellular" | "ethernet" | "none" | "wifi" | "wimax" | "other" | "unknown";
10
11
  declare global {
11
12
  interface Navigator {
12
13
  userAgentData?: NavigatorUAData;
14
+ connection?: {
15
+ type?: ConnectionType;
16
+ };
13
17
  }
14
18
  }
15
19
  /** @internal */
@@ -28,6 +32,7 @@ export interface CameraKitUserAgent {
28
32
  };
29
33
  origin: string;
30
34
  userAgent: string;
35
+ connectionType: ConnectionType | undefined;
31
36
  }
32
37
  /** @internal */
33
38
  export declare const cameraKitUserAgent: CameraKitUserAgent;
@@ -183,7 +183,7 @@ function parseApplicationOrigin() {
183
183
  return origin;
184
184
  }
185
185
  function getCameraKitUserAgent() {
186
- var _a;
186
+ var _a, _b;
187
187
  const userAgent = (_a = navigator.userAgent) !== null && _a !== void 0 ? _a : "";
188
188
  // [NavigatorUAData](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData) is currently only
189
189
  // available on Chromium-based browsers – it's nice because it gives us clear, well-documented information. But
@@ -226,6 +226,7 @@ function getCameraKitUserAgent() {
226
226
  browser,
227
227
  origin,
228
228
  userAgent: cameraKitUserAgent,
229
+ connectionType: (_b = navigator.connection) === null || _b === void 0 ? void 0 : _b.type,
229
230
  };
230
231
  }
231
232
  /** @internal */
@@ -1 +1 @@
1
- {"version":3,"file":"cameraKitUserAgent.js","sourceRoot":"","sources":["../../src/common/cameraKitUserAgent.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,MAAM,qBAAqB,CAAC;AAC9C,OAAO,YAAY,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAgBxC;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAc;IACrC,OAAO,CACH,QAAQ,CAAC,KAAK,CAAC;QACf,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC9B,KAAK,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YAC5B,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,SAAS,CAAC,KAAK,QAAQ,CAAC;QACzG,CAAC,CAAC;QACF,OAAO,KAAK,CAAC,QAAQ,CAAC,KAAK,SAAS;QACpC,OAAO,KAAK,CAAC,UAAU,CAAC,KAAK,QAAQ,CACxC,CAAC;AACN,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAS,oBAAoB,CAAC,SAAiB;IAC3C,+DAA+D;IAC/D,SAAS;IACT,cAAc;IACd,aAAa;IACb,WAAW;IACX,WAAW;IACX,MAAM,YAAY,GAAG,S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AoC;IACpC,mCAAmC;IACnC,+JAA+J;IAC/J,MAAM,kBAAkB,GACpB,gBAAgB,eAAe,GAAG;QAClC,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE;QACxC,IAAI,WAAW,KAAK,aAAa,CAAC,QAAQ,IAAI,eAAe,IAAI;QACjE,GAAG,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,OAAO,GAAG;QACtC,QAAQ,YAAY,CAAC,OAAO,GAAG;QAC/B,+GAA+G;QAC/G,qGAAqG;QACrG,SAAS,MAAM,EAAE,CAAC;IAEtB,OAAO;QACH,MAAM,EAAE,aAAa,CAAC,QAAQ;QAC9B,SAAS,EAAE,eAAe;QAC1B,MAAM;QACN,eAAe;QACf,cAAc;QACd,MAAM;QACN,eAAe,EAAE,GAAG,YAAY,CAAC,OAAO,EAAE;QAC1C,WAAW;QACX,OAAO;QACP,MAAM;QACN,SAAS,EAAE,kBAAkB;KAChC,CAAC;AACN,CAAC;AAiBD,gBAAgB;AAChB,MAAM,CAAC,MAAM,kBAAkB,GAAG,qBAAqB,EAAE,CAAC","sourcesContent":["import environment from \"../environment.json\";\nimport lensCoreWasm from \"../lensCoreWasmVersions.json\";\nimport { locale } from \"./locale\";\nimport { isRecord } from \"./typeguards\";\n\ntype BrandArray = Array<{ brand: string; version: string }>;\n\ninterface NavigatorUAData {\n brands: BrandArray;\n mobile: boolean;\n platform: string;\n}\n\ndeclare global {\n interface Navigator {\n userAgentData?: NavigatorUAData;\n }\n}\n\n/**\n * Some user agents may not properly implement the NavigatorUAData interface, so we have to do our own validation here\n * to make sure we're dealing with a well-formed value.\n */\nfunction isNavigatorUAData(value: unknown): value is NavigatorUAData {\n return (\n isRecord(value) &&\n Array.isArray(value[\"brands\"]) &&\n value[\"brands\"].every((brand) => {\n return isRecord(brand) && typeof brand[\"brand\"] === \"string\" && typeof brand[\"version\"] === \"string\";\n }) &&\n typeof value[\"mobile\"] === \"boolean\" &&\n typeof value[\"platform\"] === \"string\"\n );\n}\n\n/**\n * Parse the platform (i.e. OS) version.\n *\n * From limited testing, this seems to often produce incorrect results – the userAgent string does not typically include\n * the actual OS version.\n *\n * Better results could be obtained from [NavigatorUAData.getHighEntropyValues]\n * (https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/getHighEntropyValues), but this presents two\n * problems: 1) it's currently only supported on Chrome and 2) browsers may prompt the user for permission to share\n * this information.\n *\n * So, at least for now, we'll be satisfied with the incorrect version number.\n */\nfunction parsePlatformVersion(userAgent: string) {\n // possible platform version values inside of user agent string\n // \" 11;\"\n // \" 10_15_7)\"\n // \" 13_5_1 \"\n // \" 10.0;\"\n // \" 15_1 \"\n const versionMatch = userAgent.match(/\\s([\\d][\\d_.]*[\\d])(;|\\)|\\s)/);\n\n if (versionMatch != null) {\n return versionMatch[1].replace(/_/g, \".\");\n }\n\n return \"\";\n}\n\n/**\n * In the future, we may invest in more robust device-detection (e.g. a UA string database), but for now this will give\n * us some sense of device usage.\n */\nfunction parseDeviceModel(userAgent: string) {\n // from user agent like \"(Linux; Android 11; Pixel 2)\" extact \"Pixel 2\"\n const userAgentWithModel = userAgent.match(/;[^;]+?;([^\\)]+?)\\)/);\n\n if (userAgentWithModel) {\n return userAgentWithModel[1].trim();\n }\n\n // from user agent like \"... (iPad; CPU OS 15_1 like Mac OS X) ...\" extract \"IPad\"\n const userAgentWithModel2 = userAgent.match(/\\(([^;]+);/);\n\n if (userAgentWithModel2) {\n return userAgentWithModel2[1].trim();\n }\n\n return \"unknown\";\n}\n\n/**\n * Some browsers (e.g. Safari) do not support the `Navigator.userAgentData` API. We'll attempt a sort of polyfill by\n * parsing the data found in [NavigatorUAData](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData) from\n * the raw user agent string.\n */\nfunction parseUserAgentData(userAgent: string): NavigatorUAData {\n let brand: BrandArray[number];\n\n // Parse UA string for Chromium-based browsers (e.g. Chrome, Edge)\n if (/Chrome/.test(userAgent)) {\n const versionMatch = userAgent.match(/Chrome\\/([\\d.]+)/);\n brand = {\n brand: \"Chrome\",\n version: versionMatch !== null ? versionMatch[1] : \"unknown\",\n };\n }\n\n // Parse UA string for Safari (very important for this to only be done if Chrome is not found – Chrome userAgent\n // strings will contain \"Safari\")\n else if (/Safari/.test(userAgent)) {\n let versionMatch = userAgent.match(/Version\\/([\\d.]+)/);\n if (versionMatch === null) versionMatch = userAgent.match(/Safari\\/([\\d.]+)/);\n brand = {\n brand: \"Safari\",\n version: versionMatch !== null ? versionMatch[1] : \"unknown\",\n };\n }\n\n // Parse UA for unknown browser.\n // TODO: will be changed, default value support should be added on a COF server side.\n else {\n brand = {\n brand: \"Firefox\",\n version: \"0\",\n };\n }\n\n // We're not using `mobile` for anything, and we have no consistent way to determine this from the UA string.\n // We'll set it to false, but this should not be used – instead, we'll need to rely on more sophisticated methods\n // (e.g. a userAgent database) to determine actual device.\n const mobile = false;\n const platform = parsePlaftformName(userAgent);\n\n return {\n brands: [brand],\n mobile,\n platform,\n };\n}\n\n/* eslint-disable max-len */\n/**\n * The `brands` array found in [NavigatorUAData](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData) is\n * intentionally designed to discourage standardized processing. This method of extracting brand information will be\n * inherently brittle, and it relies on us matching some well-known brands.\n *\n * For more detail from the spec:\n * See https://wicg.github.io/ua-client-hints/#monkeypatch-html-windoworworkerglobalscope\n * And https://wicg.github.io/ua-client-hints/#grease\n *\n * We also must match the list of known brands allowed by the backend, defined here:\n * https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n */\n/* eslint-enable */\ntype KnownBrand = \"Chrome\" | \"Safari\" | \"Firefox\";\nfunction normalizeBrands(brands: BrandArray): BrandArray {\n const knownBrands = new Map<string, KnownBrand>([\n [\"Chrome\", \"Chrome\"],\n [\"Chromium\", \"Chrome\"],\n [\"Firefox\", \"Firefox\"],\n [\"Microsoft Edge\", \"Chrome\"],\n [\"Safari\", \"Safari\"],\n ]);\n\n const normalizedBrands = brands\n .filter(({ brand }) => knownBrands.has(brand))\n .map((brand) => {\n return {\n // Safety: we've filtered out brands which do not appear as keys in `knownBrands`, so this cannot return\n // undefined.\n brand: knownBrands.get(brand.brand)!,\n version: brand.version,\n };\n });\n\n // TODO: default \"unknown\" value should be added on COF server side. For now we'll use Firefox.\n if (normalizedBrands.length === 0) return [{ brand: \"Firefox\", version: \"0\" }];\n return normalizedBrands;\n}\n\n/* eslint-disable max-len */\n/**\n * We must ensure the data we get from `navigator.userAgentData` is normalized to match what our backend expects to\n * see in our custom CameraKitWeb userAgent string.\n *\n * This string is defined here:\n * https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n */\n/* eslint-enable */\nfunction normalizeUserAgentData(userAgentData: NavigatorUAData): NavigatorUAData {\n return {\n brands: normalizeBrands(userAgentData.brands),\n mobile: userAgentData.mobile,\n platform: parsePlaftformName(userAgentData.platform),\n };\n}\n\n/* eslint-disable max-len */\n/**\n * The backend defines the allowed list of known platforms which will pass their RegEx test when found in our custom\n * CameraKitWeb userAgent string.\n *\n * See https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n */\n/* eslint-enable */\ntype KnownPlatform = \"macos\" | \"windows\" | \"linux\" | \"android\" | \"ios\" | \"ipados\" | \"unknown\";\nfunction parsePlaftformName(userAgent: string): KnownPlatform {\n const knownPlatforms = new Map<string, KnownPlatform>([\n [\"android\", \"android\"],\n [\"linux\", \"linux\"],\n [\"iphone os\", \"ios\"],\n [\"ipad\", \"ipados\"],\n [\"mac os\", \"macos\"],\n [\"macos\", \"macos\"],\n [\"windows\", \"windows\"],\n ]);\n\n const normalizedUserAgent = userAgent.toLowerCase();\n for (const [match, platform] of knownPlatforms.entries()) {\n if (normalizedUserAgent.includes(match)) return platform;\n }\n return \"unknown\";\n}\n\n/**\n * We'll use the application's origin as an identifier – this isn't used for any kind of authentication, but it may be\n * useful metadata to have in the future.\n *\n * We also need to handle cases in which the SDK is used in a child browsing context (e.g. an iframe), which may not\n * have a hostname – in this case we'll check each ancestor context until we find a valid hostname.\n */\nfunction parseApplicationOrigin(): string {\n let origin = location.hostname;\n // Firefox does not implement ancestorOrigins, so we need a fallback.\n // Context here: https://github.com/whatwg/html/issues/1918\n const ancestorOrigins =\n location.ancestorOrigins === undefined\n ? typeof window !== \"undefined\"\n ? [window.parent.origin, window.top?.origin ?? \"\"]\n : []\n : Array.from(location.ancestorOrigins ?? []);\n\n while (origin === \"\" && ancestorOrigins.length > 0) {\n // Safety: ancestorOrigins must contain at least one element, so shift() will always be defined.\n origin = new URL(ancestorOrigins.shift()!).hostname;\n }\n return origin;\n}\n\nfunction getCameraKitUserAgent(): CameraKitUserAgent {\n const userAgent = navigator.userAgent ?? \"\";\n // [NavigatorUAData](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData) is currently only\n // available on Chromium-based browsers – it's nice because it gives us clear, well-documented information. But\n // we'll have to fallback to parsing the userAgent string when it's not available.\n const userAgentData = isNavigatorUAData(navigator.userAgentData)\n ? normalizeUserAgentData(navigator.userAgentData)\n : parseUserAgentData(userAgent);\n\n const platformVersion = parsePlatformVersion(userAgent);\n const deviceModel = parseDeviceModel(userAgent);\n\n // In cases where we've parsed the userAgent string to find the brand, there will only ever be a single brand –\n // in browsers which support NavigatorUAData there could be more than one (e.g. Chrome and Chromium), but they\n // should be equivalent for our purposes.\n const browser = userAgentData.brands[0];\n const origin = parseApplicationOrigin();\n\n const sdkLongVersion = environment.PACKAGE_VERSION;\n // Remove any `-prerelease` or `+buildmetadata` portions from the semver string.\n const sdkShortVersion = sdkLongVersion.replace(/[-+]\\S+$/, \"\");\n\n // Set this to `debug` manually while testing / root-causing.\n const flavor: \"release\" | \"debug\" = \"release\";\n\n // This full string is defined here:\n // eslint-disable-next-line max-len\n // https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n const cameraKitUserAgent =\n `CameraKitWeb/${sdkShortVersion} ` +\n `${flavor === \"release\" ? \"\" : \"DEBUG\"}` +\n `(${deviceModel}; ${userAgentData.platform} ${platformVersion}) ` +\n `${browser.brand}/${browser.version} ` +\n `Core/${lensCoreWasm.version} ` +\n // We overload appId, using the origin instead of the true appId parsed from the apiToken -- we do this because\n // origin is human-readable, and this is used to populate the appId dimension in operational metrics.\n `AppId/${origin}`;\n\n return {\n osType: userAgentData.platform,\n osVersion: platformVersion,\n locale,\n sdkShortVersion,\n sdkLongVersion,\n flavor,\n lensCoreVersion: `${lensCoreWasm.version}`,\n deviceModel,\n browser,\n origin,\n userAgent: cameraKitUserAgent,\n };\n}\n\n/** @internal */\nexport interface CameraKitUserAgent {\n osType: string;\n osVersion: string;\n locale: string;\n sdkShortVersion: string;\n sdkLongVersion: string;\n flavor: \"release\" | \"debug\";\n lensCoreVersion: string;\n deviceModel: string;\n browser: { brand: string; version: string };\n origin: string;\n userAgent: string;\n}\n\n/** @internal */\nexport const cameraKitUserAgent = getCameraKitUserAgent();\n"]}
1
+ {"version":3,"file":"cameraKitUserAgent.js","sourceRoot":"","sources":["../../src/common/cameraKitUserAgent.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,MAAM,qBAAqB,CAAC;AAC9C,OAAO,YAAY,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAuBxC;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAc;IACrC,OAAO,CACH,QAAQ,CAAC,KAAK,CAAC;QACf,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC9B,KAAK,C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AkB,GAAG,qBAAqB,EAAE,CAAC","sourcesContent":["import environment from \"../environment.json\";\nimport lensCoreWasm from \"../lensCoreWasmVersions.json\";\nimport { locale } from \"./locale\";\nimport { isRecord } from \"./typeguards\";\n\ntype BrandArray = Array<{ brand: string; version: string }>;\n\ninterface NavigatorUAData {\n brands: BrandArray;\n mobile: boolean;\n platform: string;\n}\n\nexport type ConnectionType = \"bluetooth\" | \"cellular\" | \"ethernet\" | \"none\" | \"wifi\" | \"wimax\" | \"other\" | \"unknown\";\n\ndeclare global {\n interface Navigator {\n userAgentData?: NavigatorUAData;\n connection?: {\n // This currently has extremely limited support in browsers.\n // https://wicg.github.io/netinfo/#dom-networkinformation-type\n type?: ConnectionType;\n };\n }\n}\n\n/**\n * Some user agents may not properly implement the NavigatorUAData interface, so we have to do our own validation here\n * to make sure we're dealing with a well-formed value.\n */\nfunction isNavigatorUAData(value: unknown): value is NavigatorUAData {\n return (\n isRecord(value) &&\n Array.isArray(value[\"brands\"]) &&\n value[\"brands\"].every((brand) => {\n return isRecord(brand) && typeof brand[\"brand\"] === \"string\" && typeof brand[\"version\"] === \"string\";\n }) &&\n typeof value[\"mobile\"] === \"boolean\" &&\n typeof value[\"platform\"] === \"string\"\n );\n}\n\n/**\n * Parse the platform (i.e. OS) version.\n *\n * From limited testing, this seems to often produce incorrect results – the userAgent string does not typically include\n * the actual OS version.\n *\n * Better results could be obtained from [NavigatorUAData.getHighEntropyValues]\n * (https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/getHighEntropyValues), but this presents two\n * problems: 1) it's currently only supported on Chrome and 2) browsers may prompt the user for permission to share\n * this information.\n *\n * So, at least for now, we'll be satisfied with the incorrect version number.\n */\nfunction parsePlatformVersion(userAgent: string) {\n // possible platform version values inside of user agent string\n // \" 11;\"\n // \" 10_15_7)\"\n // \" 13_5_1 \"\n // \" 10.0;\"\n // \" 15_1 \"\n const versionMatch = userAgent.match(/\\s([\\d][\\d_.]*[\\d])(;|\\)|\\s)/);\n\n if (versionMatch != null) {\n return versionMatch[1].replace(/_/g, \".\");\n }\n\n return \"\";\n}\n\n/**\n * In the future, we may invest in more robust device-detection (e.g. a UA string database), but for now this will give\n * us some sense of device usage.\n */\nfunction parseDeviceModel(userAgent: string) {\n // from user agent like \"(Linux; Android 11; Pixel 2)\" extact \"Pixel 2\"\n const userAgentWithModel = userAgent.match(/;[^;]+?;([^\\)]+?)\\)/);\n\n if (userAgentWithModel) {\n return userAgentWithModel[1].trim();\n }\n\n // from user agent like \"... (iPad; CPU OS 15_1 like Mac OS X) ...\" extract \"IPad\"\n const userAgentWithModel2 = userAgent.match(/\\(([^;]+);/);\n\n if (userAgentWithModel2) {\n return userAgentWithModel2[1].trim();\n }\n\n return \"unknown\";\n}\n\n/**\n * Some browsers (e.g. Safari) do not support the `Navigator.userAgentData` API. We'll attempt a sort of polyfill by\n * parsing the data found in [NavigatorUAData](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData) from\n * the raw user agent string.\n */\nfunction parseUserAgentData(userAgent: string): NavigatorUAData {\n let brand: BrandArray[number];\n\n // Parse UA string for Chromium-based browsers (e.g. Chrome, Edge)\n if (/Chrome/.test(userAgent)) {\n const versionMatch = userAgent.match(/Chrome\\/([\\d.]+)/);\n brand = {\n brand: \"Chrome\",\n version: versionMatch !== null ? versionMatch[1] : \"unknown\",\n };\n }\n\n // Parse UA string for Safari (very important for this to only be done if Chrome is not found – Chrome userAgent\n // strings will contain \"Safari\")\n else if (/Safari/.test(userAgent)) {\n let versionMatch = userAgent.match(/Version\\/([\\d.]+)/);\n if (versionMatch === null) versionMatch = userAgent.match(/Safari\\/([\\d.]+)/);\n brand = {\n brand: \"Safari\",\n version: versionMatch !== null ? versionMatch[1] : \"unknown\",\n };\n }\n\n // Parse UA for unknown browser.\n // TODO: will be changed, default value support should be added on a COF server side.\n else {\n brand = {\n brand: \"Firefox\",\n version: \"0\",\n };\n }\n\n // We're not using `mobile` for anything, and we have no consistent way to determine this from the UA string.\n // We'll set it to false, but this should not be used – instead, we'll need to rely on more sophisticated methods\n // (e.g. a userAgent database) to determine actual device.\n const mobile = false;\n const platform = parsePlaftformName(userAgent);\n\n return {\n brands: [brand],\n mobile,\n platform,\n };\n}\n\n/* eslint-disable max-len */\n/**\n * The `brands` array found in [NavigatorUAData](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData) is\n * intentionally designed to discourage standardized processing. This method of extracting brand information will be\n * inherently brittle, and it relies on us matching some well-known brands.\n *\n * For more detail from the spec:\n * See https://wicg.github.io/ua-client-hints/#monkeypatch-html-windoworworkerglobalscope\n * And https://wicg.github.io/ua-client-hints/#grease\n *\n * We also must match the list of known brands allowed by the backend, defined here:\n * https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n */\n/* eslint-enable */\ntype KnownBrand = \"Chrome\" | \"Safari\" | \"Firefox\";\nfunction normalizeBrands(brands: BrandArray): BrandArray {\n const knownBrands = new Map<string, KnownBrand>([\n [\"Chrome\", \"Chrome\"],\n [\"Chromium\", \"Chrome\"],\n [\"Firefox\", \"Firefox\"],\n [\"Microsoft Edge\", \"Chrome\"],\n [\"Safari\", \"Safari\"],\n ]);\n\n const normalizedBrands = brands\n .filter(({ brand }) => knownBrands.has(brand))\n .map((brand) => {\n return {\n // Safety: we've filtered out brands which do not appear as keys in `knownBrands`, so this cannot return\n // undefined.\n brand: knownBrands.get(brand.brand)!,\n version: brand.version,\n };\n });\n\n // TODO: default \"unknown\" value should be added on COF server side. For now we'll use Firefox.\n if (normalizedBrands.length === 0) return [{ brand: \"Firefox\", version: \"0\" }];\n return normalizedBrands;\n}\n\n/* eslint-disable max-len */\n/**\n * We must ensure the data we get from `navigator.userAgentData` is normalized to match what our backend expects to\n * see in our custom CameraKitWeb userAgent string.\n *\n * This string is defined here:\n * https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n */\n/* eslint-enable */\nfunction normalizeUserAgentData(userAgentData: NavigatorUAData): NavigatorUAData {\n return {\n brands: normalizeBrands(userAgentData.brands),\n mobile: userAgentData.mobile,\n platform: parsePlaftformName(userAgentData.platform),\n };\n}\n\n/* eslint-disable max-len */\n/**\n * The backend defines the allowed list of known platforms which will pass their RegEx test when found in our custom\n * CameraKitWeb userAgent string.\n *\n * See https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n */\n/* eslint-enable */\ntype KnownPlatform = \"macos\" | \"windows\" | \"linux\" | \"android\" | \"ios\" | \"ipados\" | \"unknown\";\nfunction parsePlaftformName(userAgent: string): KnownPlatform {\n const knownPlatforms = new Map<string, KnownPlatform>([\n [\"android\", \"android\"],\n [\"linux\", \"linux\"],\n [\"iphone os\", \"ios\"],\n [\"ipad\", \"ipados\"],\n [\"mac os\", \"macos\"],\n [\"macos\", \"macos\"],\n [\"windows\", \"windows\"],\n ]);\n\n const normalizedUserAgent = userAgent.toLowerCase();\n for (const [match, platform] of knownPlatforms.entries()) {\n if (normalizedUserAgent.includes(match)) return platform;\n }\n return \"unknown\";\n}\n\n/**\n * We'll use the application's origin as an identifier – this isn't used for any kind of authentication, but it may be\n * useful metadata to have in the future.\n *\n * We also need to handle cases in which the SDK is used in a child browsing context (e.g. an iframe), which may not\n * have a hostname – in this case we'll check each ancestor context until we find a valid hostname.\n */\nfunction parseApplicationOrigin(): string {\n let origin = location.hostname;\n // Firefox does not implement ancestorOrigins, so we need a fallback.\n // Context here: https://github.com/whatwg/html/issues/1918\n const ancestorOrigins =\n location.ancestorOrigins === undefined\n ? typeof window !== \"undefined\"\n ? [window.parent.origin, window.top?.origin ?? \"\"]\n : []\n : Array.from(location.ancestorOrigins ?? []);\n\n while (origin === \"\" && ancestorOrigins.length > 0) {\n // Safety: ancestorOrigins must contain at least one element, so shift() will always be defined.\n origin = new URL(ancestorOrigins.shift()!).hostname;\n }\n return origin;\n}\n\nfunction getCameraKitUserAgent(): CameraKitUserAgent {\n const userAgent = navigator.userAgent ?? \"\";\n // [NavigatorUAData](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData) is currently only\n // available on Chromium-based browsers – it's nice because it gives us clear, well-documented information. But\n // we'll have to fallback to parsing the userAgent string when it's not available.\n const userAgentData = isNavigatorUAData(navigator.userAgentData)\n ? normalizeUserAgentData(navigator.userAgentData)\n : parseUserAgentData(userAgent);\n\n const platformVersion = parsePlatformVersion(userAgent);\n const deviceModel = parseDeviceModel(userAgent);\n\n // In cases where we've parsed the userAgent string to find the brand, there will only ever be a single brand –\n // in browsers which support NavigatorUAData there could be more than one (e.g. Chrome and Chromium), but they\n // should be equivalent for our purposes.\n const browser = userAgentData.brands[0];\n const origin = parseApplicationOrigin();\n\n const sdkLongVersion = environment.PACKAGE_VERSION;\n // Remove any `-prerelease` or `+buildmetadata` portions from the semver string.\n const sdkShortVersion = sdkLongVersion.replace(/[-+]\\S+$/, \"\");\n\n // Set this to `debug` manually while testing / root-causing.\n const flavor: \"release\" | \"debug\" = \"release\";\n\n // This full string is defined here:\n // eslint-disable-next-line max-len\n // https://github.sc-corp.net/Snapchat/useragent/blob/9333afe7cc6ac00503ad46cb234bcf94006dff98/java/useragent/src/main/java/snapchat/client/UserAgent.java#L124\n const cameraKitUserAgent =\n `CameraKitWeb/${sdkShortVersion} ` +\n `${flavor === \"release\" ? \"\" : \"DEBUG\"}` +\n `(${deviceModel}; ${userAgentData.platform} ${platformVersion}) ` +\n `${browser.brand}/${browser.version} ` +\n `Core/${lensCoreWasm.version} ` +\n // We overload appId, using the origin instead of the true appId parsed from the apiToken -- we do this because\n // origin is human-readable, and this is used to populate the appId dimension in operational metrics.\n `AppId/${origin}`;\n\n return {\n osType: userAgentData.platform,\n osVersion: platformVersion,\n locale,\n sdkShortVersion,\n sdkLongVersion,\n flavor,\n lensCoreVersion: `${lensCoreWasm.version}`,\n deviceModel,\n browser,\n origin,\n userAgent: cameraKitUserAgent,\n connectionType: navigator.connection?.type,\n };\n}\n\n/** @internal */\nexport interface CameraKitUserAgent {\n osType: string;\n osVersion: string;\n locale: string;\n sdkShortVersion: string;\n sdkLongVersion: string;\n flavor: \"release\" | \"debug\";\n lensCoreVersion: string;\n deviceModel: string;\n browser: { brand: string; version: string };\n origin: string;\n userAgent: string;\n connectionType: ConnectionType | undefined;\n}\n\n/** @internal */\nexport const cameraKitUserAgent = getCameraKitUserAgent();\n"]}
@@ -0,0 +1,3 @@
1
+ export declare const DEFAULT_TIMEZONE = "America/Los_Angeles";
2
+ export declare const dayFormatter: Intl.DateTimeFormat;
3
+ export declare const monthFormatter: Intl.DateTimeFormat;
@@ -0,0 +1,13 @@
1
+ export const DEFAULT_TIMEZONE = "America/Los_Angeles";
2
+ export const dayFormatter = new Intl.DateTimeFormat("en-US", {
3
+ timeZone: DEFAULT_TIMEZONE,
4
+ year: "numeric",
5
+ month: "numeric",
6
+ day: "numeric",
7
+ });
8
+ export const monthFormatter = new Intl.DateTimeFormat("en-US", {
9
+ timeZone: DEFAULT_TIMEZONE,
10
+ year: "numeric",
11
+ month: "numeric",
12
+ });
13
+ //# sourceMappingURL=date.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date.js","sourceRoot":"","sources":["../../src/common/date.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,gBAAgB,GAAG,qBAAqB,CAAC;AAEtD,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;IACzD,QAAQ,EAAE,gBAAgB;IAC1B,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,SAAS;IAChB,GAAG,EAAE,SAAS;CACjB,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;IAC3D,QAAQ,EAAE,gBAAgB;IAC1B,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,SAAS;CACnB,CAAC,CAAC","sourcesContent":["export const DEFAULT_TIMEZONE = \"America/Los_Angeles\";\n\nexport const dayFormatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: DEFAULT_TIMEZONE,\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n});\n\nexport const monthFormatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: DEFAULT_TIMEZONE,\n year: \"numeric\",\n month: \"numeric\",\n});\n"]}
@@ -6,7 +6,7 @@
6
6
  export function stringifyError(error) {
7
7
  var _a;
8
8
  const outer = (_a = error.stack) !== null && _a !== void 0 ? _a : "";
9
- return error.cause ? `${outer}\nCaused By: ${stringifyError(ensureError(error.cause))}` : outer;
9
+ return error.cause ? `${outer}\nCaused by:\n\t${stringifyError(ensureError(error.cause))}` : outer;
10
10
  }
11
11
  /**
12
12
  * If given a value of type Error, return it – otherwise wrap the value in an Error.
@@ -1 +1 @@
1
- {"version":3,"file":"errorHelpers.js","sourceRoot":"","sources":["../../src/common/errorHelpers.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,KAAY;;IACvC,MAAM,KAAK,GAAG,MAAA,KAAK,CAAC,KAAK,mCAAI,EAAE,CAAC;IAChC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,gBAAgB,cAAc,CAAC,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;AACpG,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,KAAc;IACtC,IAAI,KAAK,YAAY,KAAK;QAAE,OAAO,KAAK,CAAC;IAEzC,IAAI;QACA,OAAO,IAAI,KAAK,CAAC,4DAA4D,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;KACzG;IAAC,OAAO,CAAC,EAAE;QACR,OAAO,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;KACtG;AACL,CAAC","sourcesContent":["/**\n * Returns a stack trace for a given error, and also appends the stack trace of any nested error, if one exists.\n * @param error Error to stringify.\n * @returns Error stack trace.\n */\nexport function stringifyError(error: Error): string {\n const outer = error.stack ?? \"\";\n return error.cause ? `${outer}\\nCaused By: ${stringifyError(ensureError(error.cause))}` : outer;\n}\n\n/**\n * If given a value of type Error, return it – otherwise wrap the value in an Error.\n */\nexport function ensureError(error: unknown): Error {\n if (error instanceof Error) return error;\n\n try {\n return new Error(`Non-Error type exception thrown. Serialized error value: ${JSON.stringify(error)}`);\n } catch (_) {\n return new Error(\"Non-Error type exception thrown. Original error value could not be serialized.\");\n }\n}\n"]}
1
+ {"version":3,"file":"errorHelpers.js","sourceRoot":"","sources":["../../src/common/errorHelpers.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,KAAY;;IACvC,MAAM,KAAK,GAAG,MAAA,KAAK,CAAC,KAAK,mCAAI,EAAE,CAAC;IAChC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,mBAAmB,cAAc,CAAC,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;AACvG,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,KAAc;IACtC,IAAI,KAAK,YAAY,KAAK;QAAE,OAAO,KAAK,CAAC;IAEzC,IAAI;QACA,OAAO,IAAI,KAAK,CAAC,4DAA4D,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;KACzG;IAAC,OAAO,CAAC,EAAE;QACR,OAAO,IAAI,KAAK,CAAC,gFAAgF,CAAC,CAAC;KACtG;AACL,CAAC","sourcesContent":["/**\n * Returns a stack trace for a given error, and also appends the stack trace of any nested error, if one exists.\n * @param error Error to stringify.\n * @returns Error stack trace.\n */\nexport function stringifyError(error: Error): string {\n const outer = error.stack ?? \"\";\n return error.cause ? `${outer}\\nCaused by:\\n\\t${stringifyError(ensureError(error.cause))}` : outer;\n}\n\n/**\n * If given a value of type Error, return it – otherwise wrap the value in an Error.\n */\nexport function ensureError(error: unknown): Error {\n if (error instanceof Error) return error;\n\n try {\n return new Error(`Non-Error type exception thrown. Serialized error value: ${JSON.stringify(error)}`);\n } catch (_) {\n return new Error(\"Non-Error type exception thrown. Original error value could not be serialized.\");\n }\n}\n"]}
@@ -1 +1,2 @@
1
1
  export declare const getTimeMs: () => number;
2
+ export declare const convertDaysToSeconds: (days: number) => number;
@@ -1,2 +1,3 @@
1
1
  export const getTimeMs = () => performance.now();
2
+ export const convertDaysToSeconds = (days) => days * 24 * 60 * 60;
2
3
  //# sourceMappingURL=time.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"time.js","sourceRoot":"","sources":["../../src/common/time.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC","sourcesContent":["export const getTimeMs = () => performance.now();\n"]}
1
+ {"version":3,"file":"time.js","sourceRoot":"","sources":["../../src/common/time.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;AAEjD,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC","sourcesContent":["export const getTimeMs = () => performance.now();\n\nexport const convertDaysToSeconds = (days: number) => days * 24 * 60 * 60;\n"]}
@@ -7,4 +7,12 @@
7
7
  */
8
8
  type _TupleOf<T, N extends number, R extends unknown[]> = R["length"] extends N ? R : _TupleOf<T, N, [T, ...R]>;
9
9
  export type TupleOf<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never;
10
+ /**
11
+ * Converts snake_case string literal types to camelCase.
12
+ */
13
+ export type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}` ? `${T}${Capitalize<SnakeToCamelCase<U>>}` : S;
14
+ /**
15
+ * Converts camelCase string literal types to snake_case.
16
+ */
17
+ export type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelToSnakeCase<U>}` : S;
10
18
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * For instances where we'd like to define a Tuple to be of certain type and length.\n * Example: TupleOf<number, 3> // [number, number, number]\n *\n * For more example and use cases regarding Recursive conditional types\n * see: https://github.com/microsoft/TypeScript/pull/40002\n */\ntype _TupleOf<T, N extends number, R extends unknown[]> = R[\"length\"] extends N ? R : _TupleOf<T, N, [T, ...R]>;\nexport type TupleOf<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * For instances where we'd like to define a Tuple to be of certain type and length.\n * Example: TupleOf<number, 3> // [number, number, number]\n *\n * For more example and use cases regarding Recursive conditional types\n * see: https://github.com/microsoft/TypeScript/pull/40002\n */\ntype _TupleOf<T, N extends number, R extends unknown[]> = R[\"length\"] extends N ? R : _TupleOf<T, N, [T, ...R]>;\nexport type TupleOf<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never;\n\n/**\n * Converts snake_case string literal types to camelCase.\n */\nexport type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`\n ? `${T}${Capitalize<SnakeToCamelCase<U>>}`\n : S;\n\n/**\n * Converts camelCase string literal types to snake_case.\n */\nexport type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}`\n ? `${T extends Capitalize<T> ? \"_\" : \"\"}${Lowercase<T>}${CamelToSnakeCase<U>}`\n : S;\n"]}
@@ -22,6 +22,7 @@ import { logEntriesFactory } from "../logger/logEntries";
22
22
  import { reportGlobalException } from "../metrics/reporters/reportGlobalException";
23
23
  import { requestStateEventTargetFactory } from "../handlers/requestStateEmittingHandler";
24
24
  import { pageVisibilityFactory } from "../common/pageVisibility";
25
+ import { remoteApiServicesFactory } from "../extensions/RemoteApiServices";
25
26
  import { ServicesFromInjectables } from "./types";
26
27
  /**
27
28
  * All services available to be customized by client app.
@@ -32,6 +33,7 @@ export type PublicServices = ServicesFromInjectables<[
32
33
  typeof defaultFetchHandlerFactory,
33
34
  typeof remoteMediaAssetLoaderFactory,
34
35
  typeof lensSourcesFactory,
36
+ typeof remoteApiServicesFactory,
35
37
  typeof uriHandlersFactory
36
38
  ]>;
37
39
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"RootServices.js","sourceRoot":"","sources":["../../src/dependency-injection/RootServices.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC","sourcesContent":["import { lensRepositoryFactory } from \"../lens/LensRepository\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { remoteMediaAssetLoaderFactory } from \"../lens/assets/remoteMediaAssetLoaderFactory\";\nimport { deviceDependentAssetLoaderFactory } from \"../lens/assets/deviceDependentAssetLoader\";\nimport { staticAssetLoaderFactory } from \"../lens/assets/staticAssetLoader\";\nimport { defaultFetchHandlerFactory } from \"../handlers/defaultFetchHandler\";\nimport { cameraKitServiceFetchHandlerFactory } from \"../handlers/cameraKitServiceFetchHandlerFactory\";\nimport { createCameraKitConfigurationFactory } from \"../configuration\";\nimport { LensCoreModule } from \"../lens-core-module/generated-types\";\nimport { metricsEventTargetFactory } from \"../metrics/metricsEventTarget\";\nimport { metricsHandlerFactory } from \"../metrics/metricsHandler\";\nimport { operationalMetricReporterFactory } from \"../metrics/operational/operationalMetricsReporter\";\nimport { lensSourcesFactory } from \"../extensions/LensSources\";\nimport { uriHandlersFactory } from \"../extensions/UriHandlers\";\nimport { lensPersistenceStoreFactory } from \"../lens/LensPersistenceStore\";\nimport { cofHandlerFactory } from \"../remote-configuration/cofHandler\";\nimport { remoteConfigurationFactory } from \"../remote-configuration/remoteConfiguration\";\nimport { lensAssetRepositoryFactory } from \"../lens/assets/LensAssetRepository\";\nimport { legalStateFactory } from \"../legal/legalState\";\nimport { legalPromptFactory } from \"../legal/legalPrompt\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { reportGlobalException } from \"../metrics/reporters/reportGlobalException\";\nimport { requestStateEventTargetFactory } from \"../handlers/requestStateEmittingHandler\";\nimport { pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { ServicesFromInjectables } from \"./types\";\n\n/**\n * All services available to be customized by client app.\n */\nexport type PublicServices = ServicesFromInjectables<\n [\n ReturnType<typeof createCameraKitConfigurationFactory>,\n typeof pageVisibilityFactory,\n typeof defaultFetchHandlerFactory,\n typeof remoteMediaAssetLoaderFactory,\n typeof lensSourcesFactory,\n typeof uriHandlersFactory\n ]\n>;\n\n/**\n * Define all the Services contained in CameraKit's root dependency injection container.\n *\n * Note: we do end up defining this list of Services twice (once here to create the type, once when we actually\n * create the Container inside the `bootstrapCameraKit` function). We could avoid doing this and just infer the\n * RootContainer type from the constructed container – but since we can only do that *inside* `bootstrapCameraKit`, it\n * makes it more awkward to provide a type for the `provide` user-supplied function (or use the type elsewhere, like in\n * CameraKitSession).\n *\n * There may be a way to eliminate this extra boilerplate, but for now it's required in order to present a cleaner\n * `bootstrapCameraKit` API to applications.\n */\nexport type RootServices = {\n // bootstrapCameraKit replaces the lensCoreFactory token's value with the resolved LensCoreModule (rather than the\n // Promise of the LensCoreModule), so we need to do the same re-mapping here.\n [lensCoreFactory.token]: LensCoreModule;\n} & PublicServices &\n ServicesFromInjectables<\n [\n typeof metricsEventTargetFactory,\n typeof requestStateEventTargetFactory,\n typeof cameraKitServiceFetchHandlerFactory,\n typeof cofHandlerFactory,\n typeof remoteConfigurationFactory,\n typeof lensRepositoryFactory,\n typeof lensPersistenceStoreFactory,\n typeof metricsHandlerFactory,\n typeof operationalMetricReporterFactory,\n typeof lensAssetRepositoryFactory,\n typeof deviceDependentAssetLoaderFactory,\n typeof staticAssetLoaderFactory,\n typeof legalStateFactory,\n typeof legalPromptFactory,\n typeof logEntriesFactory,\n typeof reportGlobalException\n ]\n >;\n"]}
1
+ {"version":3,"file":"RootServices.js","sourceRoot":"","sources":["../../src/dependency-injection/RootServices.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC","sourcesContent":["import { lensRepositoryFactory } from \"../lens/LensRepository\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { remoteMediaAssetLoaderFactory } from \"../lens/assets/remoteMediaAssetLoaderFactory\";\nimport { deviceDependentAssetLoaderFactory } from \"../lens/assets/deviceDependentAssetLoader\";\nimport { staticAssetLoaderFactory } from \"../lens/assets/staticAssetLoader\";\nimport { defaultFetchHandlerFactory } from \"../handlers/defaultFetchHandler\";\nimport { cameraKitServiceFetchHandlerFactory } from \"../handlers/cameraKitServiceFetchHandlerFactory\";\nimport { createCameraKitConfigurationFactory } from \"../configuration\";\nimport { LensCoreModule } from \"../lens-core-module/generated-types\";\nimport { metricsEventTargetFactory } from \"../metrics/metricsEventTarget\";\nimport { metricsHandlerFactory } from \"../metrics/metricsHandler\";\nimport { operationalMetricReporterFactory } from \"../metrics/operational/operationalMetricsReporter\";\nimport { lensSourcesFactory } from \"../extensions/LensSources\";\nimport { uriHandlersFactory } from \"../extensions/UriHandlers\";\nimport { lensPersistenceStoreFactory } from \"../lens/LensPersistenceStore\";\nimport { cofHandlerFactory } from \"../remote-configuration/cofHandler\";\nimport { remoteConfigurationFactory } from \"../remote-configuration/remoteConfiguration\";\nimport { lensAssetRepositoryFactory } from \"../lens/assets/LensAssetRepository\";\nimport { legalStateFactory } from \"../legal/legalState\";\nimport { legalPromptFactory } from \"../legal/legalPrompt\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { reportGlobalException } from \"../metrics/reporters/reportGlobalException\";\nimport { requestStateEventTargetFactory } from \"../handlers/requestStateEmittingHandler\";\nimport { pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { remoteApiServicesFactory } from \"../extensions/RemoteApiServices\";\nimport { ServicesFromInjectables } from \"./types\";\n\n/**\n * All services available to be customized by client app.\n */\nexport type PublicServices = ServicesFromInjectables<\n [\n ReturnType<typeof createCameraKitConfigurationFactory>,\n typeof pageVisibilityFactory,\n typeof defaultFetchHandlerFactory,\n typeof remoteMediaAssetLoaderFactory,\n typeof lensSourcesFactory,\n typeof remoteApiServicesFactory,\n typeof uriHandlersFactory\n ]\n>;\n\n/**\n * Define all the Services contained in CameraKit's root dependency injection container.\n *\n * Note: we do end up defining this list of Services twice (once here to create the type, once when we actually\n * create the Container inside the `bootstrapCameraKit` function). We could avoid doing this and just infer the\n * RootContainer type from the constructed container – but since we can only do that *inside* `bootstrapCameraKit`, it\n * makes it more awkward to provide a type for the `provide` user-supplied function (or use the type elsewhere, like in\n * CameraKitSession).\n *\n * There may be a way to eliminate this extra boilerplate, but for now it's required in order to present a cleaner\n * `bootstrapCameraKit` API to applications.\n */\nexport type RootServices = {\n // bootstrapCameraKit replaces the lensCoreFactory token's value with the resolved LensCoreModule (rather than the\n // Promise of the LensCoreModule), so we need to do the same re-mapping here.\n [lensCoreFactory.token]: LensCoreModule;\n} & PublicServices &\n ServicesFromInjectables<\n [\n typeof metricsEventTargetFactory,\n typeof requestStateEventTargetFactory,\n typeof cameraKitServiceFetchHandlerFactory,\n typeof cofHandlerFactory,\n typeof remoteConfigurationFactory,\n typeof lensRepositoryFactory,\n typeof lensPersistenceStoreFactory,\n typeof metricsHandlerFactory,\n typeof operationalMetricReporterFactory,\n typeof lensAssetRepositoryFactory,\n typeof deviceDependentAssetLoaderFactory,\n typeof staticAssetLoaderFactory,\n typeof legalStateFactory,\n typeof legalPromptFactory,\n typeof logEntriesFactory,\n typeof reportGlobalException\n ]\n >;\n"]}
@@ -1 +1 @@
1
- { "PACKAGE_VERSION": "0.12.0-alpha.1" }
1
+ { "PACKAGE_VERSION": "0.13.0-alpha.1" }
@@ -12,12 +12,12 @@ export interface LensSource {
12
12
  * @param lensId Lens ID to get.
13
13
  * @param groupId Group ID the lens belongs to.
14
14
  */
15
- getLens(lensId: string, groupId: string): Promise<ArrayBuffer>;
15
+ getLens?(lensId: string, groupId: string): Promise<ArrayBuffer>;
16
16
  /**
17
17
  * Returns encoded lens objects.
18
18
  * @param groupId Group ID to get lenses of.
19
19
  */
20
- getLensGroup(groupId: string): Promise<ArrayBuffer[]>;
20
+ getLensGroup?(groupId: string): Promise<ArrayBuffer[]>;
21
21
  }
22
22
  /**
23
23
  * A chain of {@link LensSource} objects to be registered in Camera Kit on bootstrap. Camera Kit evaluates all
@@ -38,9 +38,13 @@ export class LensSources {
38
38
  var _a, _b;
39
39
  return __awaiter(this, void 0, void 0, function* () {
40
40
  if ((_a = this.source) === null || _a === void 0 ? void 0 : _a.isGroupOwner(groupId)) {
41
- return isUndefined(lensId)
42
- ? this.source.getLensGroup(groupId)
43
- : this.source.getLens(lensId, groupId).then((envelope) => [envelope]);
41
+ if (isUndefined(lensId)) {
42
+ if (this.source.getLensGroup)
43
+ return this.source.getLensGroup(groupId);
44
+ }
45
+ else if (this.source.getLens) {
46
+ return this.source.getLens(lensId, groupId).then((envelope) => [envelope]);
47
+ }
44
48
  }
45
49
  return (_b = this.fallbackSources) === null || _b === void 0 ? void 0 : _b.retrieveLenses({ groupId, lensId });
46
50
  });
@@ -1 +1 @@
1
- {"version":3,"file":"LensSources.js","sourceRoot":"","sources":["../../src/extensions/LensSources.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AA0BhE;;;;;GAKG;AACH,MAAM,OAAO,WAAW;IACpB;;;OAGG;IACH,MAAM,CAAC,KAAK;QACR,qEAAqE;QACrE,sDAAsD;QACtD,mBAAmB;QACnB,OAAO,IAAI,WAAW,EAAE,CAAC;IAC7B,CAAC;IAKD;;;;OAIG;IACH,YAAY,eAA4B,EAAE,MAAkB;QACxD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED;;;;;;OAMG;IACG,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAwC;;;YAC1E,IAAI,MAAA,IAAI,CAAC,MAAM,0CAAE,YAAY,CAAC,OAAO,CAAC,EAAE;gBACpC,OAAO,WAAW,CAAC,MAAM,CAAC;oBACtB,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC;oBACnC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;aAC7E;YACD,OAAO,MAAA,IAAI,CAAC,eAAe,0CAAE,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;;KACpE;CACJ;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC,aAAa,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC","sourcesContent":["import { isUndefined } from \"../common/typeguards\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\n\n/**\n * A source of a lens group.\n */\nexport interface LensSource {\n /**\n * Whether the given source is able to load lenses of the supplied group.\n * @param groupId Group ID to check.\n */\n isGroupOwner(groupId: string): boolean;\n\n /**\n * Returns an encoded lens object.\n * @param lensId Lens ID to get.\n * @param groupId Group ID the lens belongs to.\n */\n getLens(lensId: string, groupId: string): Promise<ArrayBuffer>;\n\n /**\n * Returns encoded lens objects.\n * @param groupId Group ID to get lenses of.\n */\n getLensGroup(groupId: string): Promise<ArrayBuffer[]>;\n}\n\n/**\n * A chain of {@link LensSource} objects to be registered in Camera Kit on bootstrap. Camera Kit evaluates all\n * registered {@link LensSource} objects for a group ownership during Lens retrieval ({@link CameraKit.lenses}).\n * And if a source claims the ownership, its {@link LensSource.getLens} or {@link LensSource.getLensGroup}\n * methods are called.\n */\nexport class LensSources {\n /**\n * Returns empty LensSources instance.\n * @internal\n */\n static empty() {\n // NOTE: we want to keep LensSources constructor to require arguments\n // but internally we don't need them for the base case\n // @ts-expect-error\n return new LensSources();\n }\n\n private readonly fallbackSources: LensSources | undefined;\n private readonly source: LensSource | undefined;\n\n /**\n * Creates an instance of Lens sources.\n * @param fallbackSources A fallback sources if given {@link LensSource} doesn't claim a group ownership.\n * @param source Lens source.\n */\n constructor(fallbackSources: LensSources, source: LensSource) {\n this.fallbackSources = fallbackSources;\n this.source = source;\n }\n\n /**\n * Returns envelopes of lens/groups taking into account group ownership.\n * @internal\n * @param groupId A group to test ownership and get lens envelopes of.\n * @param lensId An optional lens ID to narrow envelopes down to a single lens.\n * @returns Envelopes or undefined if not applicable.\n */\n async retrieveLenses({ groupId, lensId }: { groupId: string; lensId?: string }): Promise<ArrayBuffer[] | void> {\n if (this.source?.isGroupOwner(groupId)) {\n return isUndefined(lensId)\n ? this.source.getLensGroup(groupId)\n : this.source.getLens(lensId, groupId).then((envelope) => [envelope]);\n }\n return this.fallbackSources?.retrieveLenses({ groupId, lensId });\n }\n}\n\nexport const lensSourcesFactory = Injectable(\"lensSources\", () => LensSources.empty());\n"]}
1
+ {"version":3,"file":"LensSources.js","sourceRoot":"","sources":["../../src/extensions/LensSources.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AA0BhE;;;;;GAKG;AACH,MAAM,OAAO,WAAW;IACpB;;;OAGG;IACH,MAAM,CAAC,KAAK;QACR,qEAAqE;QACrE,sDAAsD;QACtD,mBAAmB;QACnB,OAAO,IAAI,WAAW,EAAE,CAAC;IAC7B,CAAC;IAKD;;;;OAIG;IACH,YAAY,eAA4B,EAAE,MAAkB;QACxD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED;;;;;;OAMG;IACG,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAwC;;;YAC1E,IAAI,MAAA,IAAI,CAAC,MAAM,0CAAE,YAAY,CAAC,OAAO,CAAC,EAAE;gBACpC,IAAI,WAAW,CAAC,MAAM,CAAC,EAAE;oBACrB,IAAI,IAAI,CAAC,MAAM,CAAC,YAAY;wBAAE,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;iBAC1E;qBAAM,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;oBAC5B,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;iBAC9E;aACJ;YACD,OAAO,MAAA,IAAI,CAAC,eAAe,0CAAE,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;;KACpE;CACJ;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC,aAAa,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC","sourcesContent":["import { isUndefined } from \"../common/typeguards\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\n\n/**\n * A source of a lens group.\n */\nexport interface LensSource {\n /**\n * Whether the given source is able to load lenses of the supplied group.\n * @param groupId Group ID to check.\n */\n isGroupOwner(groupId: string): boolean;\n\n /**\n * Returns an encoded lens object.\n * @param lensId Lens ID to get.\n * @param groupId Group ID the lens belongs to.\n */\n getLens?(lensId: string, groupId: string): Promise<ArrayBuffer>;\n\n /**\n * Returns encoded lens objects.\n * @param groupId Group ID to get lenses of.\n */\n getLensGroup?(groupId: string): Promise<ArrayBuffer[]>;\n}\n\n/**\n * A chain of {@link LensSource} objects to be registered in Camera Kit on bootstrap. Camera Kit evaluates all\n * registered {@link LensSource} objects for a group ownership during Lens retrieval ({@link CameraKit.lenses}).\n * And if a source claims the ownership, its {@link LensSource.getLens} or {@link LensSource.getLensGroup}\n * methods are called.\n */\nexport class LensSources {\n /**\n * Returns empty LensSources instance.\n * @internal\n */\n static empty() {\n // NOTE: we want to keep LensSources constructor to require arguments\n // but internally we don't need them for the base case\n // @ts-expect-error\n return new LensSources();\n }\n\n private readonly fallbackSources: LensSources | undefined;\n private readonly source: LensSource | undefined;\n\n /**\n * Creates an instance of Lens sources.\n * @param fallbackSources A fallback sources if given {@link LensSource} doesn't claim a group ownership.\n * @param source Lens source.\n */\n constructor(fallbackSources: LensSources, source: LensSource) {\n this.fallbackSources = fallbackSources;\n this.source = source;\n }\n\n /**\n * Returns envelopes of lens/groups taking into account group ownership.\n * @internal\n * @param groupId A group to test ownership and get lens envelopes of.\n * @param lensId An optional lens ID to narrow envelopes down to a single lens.\n * @returns Envelopes or undefined if not applicable.\n */\n async retrieveLenses({ groupId, lensId }: { groupId: string; lensId?: string }): Promise<ArrayBuffer[] | void> {\n if (this.source?.isGroupOwner(groupId)) {\n if (isUndefined(lensId)) {\n if (this.source.getLensGroup) return this.source.getLensGroup(groupId);\n } else if (this.source.getLens) {\n return this.source.getLens(lensId, groupId).then((envelope) => [envelope]);\n }\n }\n return this.fallbackSources?.retrieveLenses({ groupId, lensId });\n }\n}\n\nexport const lensSourcesFactory = Injectable(\"lensSources\", () => LensSources.empty());\n"]}
@@ -0,0 +1,101 @@
1
+ import { ResponseCode } from "../generated-proto/pb_schema/lenses/remote_api/remote_api_service";
2
+ import { LensRepository } from "../lens";
3
+ import { Lens } from "../lens/Lens";
4
+ import { LensState } from "../session/lensState";
5
+ import { SessionState } from "../session/sessionState";
6
+ import { OperationalMetricsReporter } from "../metrics/operational/operationalMetricsReporter";
7
+ import { UriHandler } from "./UriHandlers";
8
+ declare const statusToResponseCodeMap: {
9
+ success: ResponseCode.SUCCESS;
10
+ redirected: ResponseCode.REDIRECTED;
11
+ badRequest: ResponseCode.BAD_REQUEST;
12
+ accessDenied: ResponseCode.ACCESS_DENIED;
13
+ notFound: ResponseCode.NOT_FOUND;
14
+ timeout: ResponseCode.TIMEOUT;
15
+ requestTooLarge: ResponseCode.REQUEST_TOO_LARGE;
16
+ serverError: ResponseCode.SERVER_ERROR;
17
+ cancelled: ResponseCode.CANCELLED;
18
+ proxyError: ResponseCode.PROXY_ERROR;
19
+ };
20
+ /**
21
+ * Status of a Remote API response.
22
+ */
23
+ export type RemoteApiStatus = keyof typeof statusToResponseCodeMap;
24
+ /**
25
+ * Remote API request sent by a lens.
26
+ */
27
+ export interface RemoteApiRequest {
28
+ /**
29
+ * Unique id of the remote API service specification.
30
+ */
31
+ apiSpecId: string;
32
+ /**
33
+ * Unique id of the remote API service endpoint requested by this request.
34
+ */
35
+ endpointId: string;
36
+ /**
37
+ * A map of named parameters associated with the request.
38
+ */
39
+ parameters: Record<string, string>;
40
+ /**
41
+ * Additional binary request payload.
42
+ */
43
+ body: ArrayBuffer;
44
+ }
45
+ /**
46
+ * Remote API response to a request sent by a lens.
47
+ */
48
+ export interface RemoteApiResponse {
49
+ /**
50
+ * Status of the response
51
+ */
52
+ status: RemoteApiStatus;
53
+ /**
54
+ * A map of named metadata associated with the response.
55
+ */
56
+ metadata: Record<string, string>;
57
+ /**
58
+ * Additional binary request payload.
59
+ */
60
+ body: ArrayBuffer;
61
+ }
62
+ /**
63
+ * Represents a Remote API request cancellation handler function.
64
+ */
65
+ export type RemoteApiCancelRequestHandler = () => void;
66
+ /**
67
+ * Represents a Remote API request handler function.
68
+ * It is provided with a reply callback that must be invoked to send a response back to the lens.
69
+ * The reply callback can be invoked multiple times if needed.
70
+ * Additionally, the handler can return a cancellation callback, which is triggered when the lens cancels the request.
71
+ */
72
+ export type RemoteApiRequestHandler = (reply: (response: RemoteApiResponse) => void) => RemoteApiCancelRequestHandler | void;
73
+ /**
74
+ * Service to handle a lens Remote API request.
75
+ */
76
+ export interface RemoteApiService {
77
+ /**
78
+ * Remote API spec ID(s).
79
+ */
80
+ apiSpecId: string;
81
+ /**
82
+ * This method is called by Camera Kit when a lens triggers a Remote API request with a corresponding spec ID.
83
+ * If the service can handle the request, the method returns a request handler; otherwise, it returns nothing.
84
+ * @param request Remote API request object.
85
+ * @param lens Lens that trigges the request.
86
+ * @returns A request handler if applicable.
87
+ */
88
+ getRequestHandler(request: RemoteApiRequest, lens: Lens): RemoteApiRequestHandler | undefined;
89
+ }
90
+ export type RemoteApiServices = RemoteApiService[];
91
+ export declare const remoteApiServicesFactory: {
92
+ (): RemoteApiServices;
93
+ token: "remoteApiServices";
94
+ dependencies: [];
95
+ };
96
+ /**
97
+ * Provides a URI handler that searches for a match within the provided services to handle Remote API requests,
98
+ * i.e., those whose URI starts with 'app://remote-api/performApiRequest'.
99
+ */
100
+ export declare function getRemoteApiUriHandler(registeredServices: RemoteApiService[], sessionState: SessionState, lensState: LensState, lensRepository: LensRepository, reporter: OperationalMetricsReporter): UriHandler;
101
+ export {};