@snap/camera-kit 0.13.2 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/docs/html/assets/search.js +1 -1
- package/docs/html/classes/CameraKit.html +4 -3
- package/docs/html/classes/CameraKitSession.html +4 -3
- package/docs/html/classes/CameraKitSource.html +4 -3
- package/docs/html/classes/LensPerformanceMeasurement.html +4 -3
- package/docs/html/classes/LensPerformanceMetrics.html +4 -3
- package/docs/html/classes/LensRepository.html +6 -5
- package/docs/html/classes/LensSources.html +4 -3
- package/docs/html/classes/Transform2D.html +4 -3
- package/docs/html/classes/TypedCustomEvent.html +4 -3
- package/docs/html/classes/TypedEventTarget.html +4 -3
- package/docs/html/functions/Injectable.html +4 -3
- package/docs/html/functions/bootstrapCameraKit.html +4 -3
- package/docs/html/functions/createExtension.html +4 -3
- package/docs/html/functions/createImageSource.html +4 -3
- package/docs/html/functions/createMediaStreamSource.html +4 -3
- package/docs/html/functions/createUserMediaSource.html +4 -3
- package/docs/html/functions/createVideoSource.html +4 -3
- package/docs/html/functions/estimateLensPerformance.html +4 -3
- package/docs/html/functions/getRequiredBootstrapURLs.html +4 -3
- package/docs/html/functions/lensSourcesFactory.html +4 -3
- package/docs/html/functions/remoteApiServicesFactory.html +4 -3
- package/docs/html/index.html +6 -5
- package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +16 -5
- package/docs/html/interfaces/CameraKitSourceSubscriber.html +5 -4
- package/docs/html/interfaces/ComputedFrameMetrics.html +4 -3
- package/docs/html/interfaces/CreateSessionOptions.html +4 -3
- package/docs/html/interfaces/EstimatedLensPerformance.html +4 -3
- package/docs/html/interfaces/Lens.html +13 -3
- package/docs/html/interfaces/LensSource.html +4 -3
- package/docs/html/interfaces/MediaStreamSourceOptions.html +4 -3
- package/docs/html/interfaces/Preview.html +4 -3
- package/docs/html/interfaces/RemoteApiRequest.html +4 -3
- package/docs/html/interfaces/RemoteApiResponse.html +4 -3
- package/docs/html/interfaces/RemoteApiService.html +4 -3
- package/docs/html/interfaces/Snapcode.html +4 -3
- package/docs/html/interfaces/UriCancelRequest.html +4 -3
- package/docs/html/interfaces/UriRequest.html +4 -3
- package/docs/html/interfaces/UriResponse.html +4 -3
- package/docs/html/interfaces/VideoSourceOptions.html +4 -3
- package/docs/html/modules.html +6 -4
- package/docs/html/types/AssetLoader.html +4 -3
- package/docs/html/types/AssetTiming.html +4 -3
- package/docs/html/types/BenchmarkError.html +4 -3
- package/docs/html/types/BootstrapError.html +4 -3
- package/docs/html/types/CacheKeyNotFoundError.html +4 -3
- package/docs/html/types/CameraKitDeviceInfo.html +4 -3
- package/docs/html/types/CameraKitDeviceOptions.html +4 -3
- package/docs/html/types/CameraKitSessionEventListener.html +4 -3
- package/docs/html/types/CameraKitSessionEvents.html +6 -5
- package/docs/html/types/CameraKitSourceError.html +4 -3
- package/docs/html/types/CameraKitSourceInfo.html +4 -3
- package/docs/html/types/CameraKitSourceOptions.html +4 -3
- package/docs/html/types/ConfigurationError.html +4 -3
- package/docs/html/types/Keyboard.html +4 -3
- package/docs/html/types/KeyboardEvents.html +4 -3
- package/docs/html/types/LegalError.html +4 -3
- package/docs/html/types/LensAbortError.html +119 -0
- package/docs/html/types/LensAssetError.html +4 -3
- package/docs/html/types/LensContentValidationError.html +4 -3
- package/docs/html/types/LensError.html +4 -3
- package/docs/html/types/LensExecutionError.html +4 -3
- package/docs/html/types/LensImagePickerError.html +4 -3
- package/docs/html/types/LensLaunchParams.html +4 -3
- package/docs/html/types/LensMetricsEvents.html +4 -3
- package/docs/html/types/LensPerformanceCluster.html +4 -3
- package/docs/html/types/LensView.html +4 -3
- package/docs/html/types/LensWait.html +4 -3
- package/docs/html/types/PersistentStoreError.html +4 -3
- package/docs/html/types/PlatformNotSupportedError.html +4 -3
- package/docs/html/types/PublicContainer.html +4 -3
- package/docs/html/types/RemoteApiRequestHandler.html +4 -3
- package/docs/html/types/RemoteApiServices.html +4 -3
- package/docs/html/types/RemoteApiStatus.html +4 -3
- package/docs/html/types/RenderTarget.html +4 -3
- package/docs/html/types/Uri.html +4 -3
- package/docs/html/types/WebGLError.html +4 -3
- package/docs/html/variables/extensionRequestContext.html +4 -3
- package/docs/md/README.md +1 -1
- package/docs/md/classes/CameraKit.md +1 -1
- package/docs/md/classes/CameraKitSession.md +1 -1
- package/docs/md/classes/CameraKitSource.md +1 -1
- package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
- package/docs/md/classes/LensPerformanceMetrics.md +1 -1
- package/docs/md/classes/LensRepository.md +3 -3
- package/docs/md/classes/LensSources.md +1 -1
- package/docs/md/classes/Transform2D.md +1 -1
- package/docs/md/classes/TypedCustomEvent.md +1 -1
- package/docs/md/classes/TypedEventTarget.md +1 -1
- package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +13 -2
- package/docs/md/interfaces/CameraKitSourceSubscriber.md +3 -3
- package/docs/md/interfaces/ComputedFrameMetrics.md +1 -1
- package/docs/md/interfaces/CreateSessionOptions.md +1 -1
- package/docs/md/interfaces/EstimatedLensPerformance.md +1 -1
- package/docs/md/interfaces/Lens.md +11 -1
- package/docs/md/interfaces/LensSource.md +1 -1
- package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
- package/docs/md/interfaces/Preview.md +1 -1
- package/docs/md/interfaces/RemoteApiRequest.md +1 -1
- package/docs/md/interfaces/RemoteApiResponse.md +1 -1
- package/docs/md/interfaces/RemoteApiService.md +1 -1
- package/docs/md/interfaces/Snapcode.md +1 -1
- package/docs/md/interfaces/UriCancelRequest.md +1 -1
- package/docs/md/interfaces/UriRequest.md +1 -1
- package/docs/md/interfaces/UriResponse.md +1 -1
- package/docs/md/interfaces/VideoSourceOptions.md +1 -1
- package/docs/md/modules.md +24 -4
- package/lib/CameraKit.d.ts +139 -7
- package/lib/CameraKit.js +19 -19
- package/lib/CameraKit.js.map +1 -1
- package/lib/__tests__/data.d.ts +9 -4
- package/lib/__tests__/data.js +19 -9
- package/lib/__tests__/data.js.map +1 -1
- package/lib/bootstrapCameraKit.js +2 -2
- package/lib/bootstrapCameraKit.js.map +1 -1
- package/lib/common/localization.js +7 -31
- package/lib/common/localization.js.map +1 -1
- package/lib/configuration.d.ts +7 -0
- package/lib/configuration.js +1 -0
- package/lib/configuration.js.map +1 -1
- package/lib/configurationOverrides.d.ts +2 -2
- package/lib/configurationOverrides.js +11 -6
- package/lib/configurationOverrides.js.map +1 -1
- package/lib/dependency-injection/RootServices.d.ts +2 -2
- package/lib/dependency-injection/RootServices.js.map +1 -1
- package/lib/environment.json +1 -1
- package/lib/extensions/extensionRequestContext.js +4 -4
- package/lib/extensions/extensionRequestContext.js.map +1 -1
- package/lib/extensions/uriHandlersRegister.d.ts +2 -2
- package/lib/extensions/uriHandlersRegister.js.map +1 -1
- package/lib/generated-proto/blizzard/cameraKitEvents.d.ts +272 -0
- package/lib/generated-proto/blizzard/cameraKitEvents.js +38 -24
- package/lib/generated-proto/blizzard/cameraKitEvents.js.map +1 -1
- package/lib/handlers/cameraKitServiceFetchHandlerFactory.js +2 -2
- package/lib/handlers/cameraKitServiceFetchHandlerFactory.js.map +1 -1
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/index.js.map +1 -1
- package/lib/lens/Lens.d.ts +9 -1
- package/lib/lens/Lens.js +2 -1
- package/lib/lens/Lens.js.map +1 -1
- package/lib/lens/LensPersistenceStore.d.ts +2 -2
- package/lib/lens/LensPersistenceStore.js.map +1 -1
- package/lib/lens/LensRepository.d.ts +2 -2
- package/lib/lens/LensRepository.js +5 -4
- package/lib/lens/LensRepository.js.map +1 -1
- package/lib/lens/assets/LensAssetRepository.d.ts +4 -4
- package/lib/lens/assets/LensAssetRepository.js +1 -3
- package/lib/lens/assets/LensAssetRepository.js.map +1 -1
- package/lib/lens/assets/LensAssetsProvider.d.ts +9 -3
- package/lib/lens/assets/LensAssetsProvider.js +12 -5
- package/lib/lens/assets/LensAssetsProvider.js.map +1 -1
- package/lib/lens-client-interface/imagePicker.d.ts +2 -2
- package/lib/lens-client-interface/imagePicker.js.map +1 -1
- package/lib/lens-client-interface/lensClientInterface.d.ts +2 -2
- package/lib/lens-client-interface/lensClientInterface.js.map +1 -1
- package/lib/lens-core-module/generated-types.d.ts +4 -2
- package/lib/lens-core-module/generated-types.js.map +1 -1
- package/lib/lens-core-module/index.d.ts +1 -0
- package/lib/lens-core-module/index.js +1 -0
- package/lib/lens-core-module/index.js.map +1 -1
- package/lib/lens-core-module/lensCore.d.ts +41 -0
- package/lib/lens-core-module/lensCore.js +54 -0
- package/lib/lens-core-module/lensCore.js.map +1 -0
- package/lib/lens-core-module/lensCoreError.d.ts +15 -0
- package/lib/lens-core-module/lensCoreError.js +43 -0
- package/lib/lens-core-module/lensCoreError.js.map +1 -0
- package/lib/lens-core-module/loader/lensCoreFactory.d.ts +1 -2
- package/lib/lens-core-module/loader/lensCoreFactory.js +24 -26
- package/lib/lens-core-module/loader/lensCoreFactory.js.map +1 -1
- package/lib/lensCoreWasmVersions.json +3 -3
- package/lib/logger/registerLogEntriesSubscriber.js +2 -2
- package/lib/logger/registerLogEntriesSubscriber.js.map +1 -1
- package/lib/media-sources/CameraKitSource.d.ts +3 -3
- package/lib/media-sources/CameraKitSource.js +22 -31
- package/lib/media-sources/CameraKitSource.js.map +1 -1
- package/lib/media-sources/FunctionSource.js +33 -36
- package/lib/media-sources/FunctionSource.js.map +1 -1
- package/lib/media-sources/MediaStreamSource.js +11 -15
- package/lib/media-sources/MediaStreamSource.js.map +1 -1
- package/lib/metrics/businessEventsReporter.js +114 -108
- package/lib/metrics/businessEventsReporter.js.map +1 -1
- package/lib/metrics/reporters/reportGlobalException.js +25 -7
- package/lib/metrics/reporters/reportGlobalException.js.map +1 -1
- package/lib/metrics/reporters/reportHttpMetrics.js +2 -2
- package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -1
- package/lib/metrics/reporters/reportLensView.js +5 -3
- package/lib/metrics/reporters/reportLensView.js.map +1 -1
- package/lib/metrics/reporters/reportLensWait.js +8 -2
- package/lib/metrics/reporters/reportLensWait.js.map +1 -1
- package/lib/metrics/reporters/reportPlatformCapabilities.d.ts +12 -0
- package/lib/metrics/reporters/reportPlatformCapabilities.js +18 -0
- package/lib/metrics/reporters/reportPlatformCapabilities.js.map +1 -0
- package/lib/metrics/reporters/reporters.d.ts +2 -1
- package/lib/metrics/reporters/reporters.js +3 -1
- package/lib/metrics/reporters/reporters.js.map +1 -1
- package/lib/namedErrors.d.ts +17 -0
- package/lib/namedErrors.js +2 -0
- package/lib/namedErrors.js.map +1 -1
- package/lib/platform/assertPlatformSupported.d.ts +4 -0
- package/lib/platform/assertPlatformSupported.js +15 -0
- package/lib/platform/assertPlatformSupported.js.map +1 -0
- package/lib/platform/cameraKitUserAgent.d.ts +2 -0
- package/lib/platform/cameraKitUserAgent.js +20 -0
- package/lib/platform/cameraKitUserAgent.js.map +1 -0
- package/lib/platform/platformCapabilities.d.ts +50 -0
- package/lib/platform/platformCapabilities.js +122 -0
- package/lib/platform/platformCapabilities.js.map +1 -0
- package/lib/{common/cameraKitUserAgent.d.ts → platform/platformInfo.d.ts} +13 -10
- package/lib/{common/cameraKitUserAgent.js → platform/platformInfo.js} +94 -100
- package/lib/platform/platformInfo.js.map +1 -0
- package/lib/remote-configuration/cofHandler.js +2 -2
- package/lib/remote-configuration/cofHandler.js.map +1 -1
- package/lib/remote-configuration/preloadConfiguration.d.ts +2 -2
- package/lib/remote-configuration/preloadConfiguration.js.map +1 -1
- package/lib/session/CameraKitSession.d.ts +3 -3
- package/lib/session/CameraKitSession.js +23 -30
- package/lib/session/CameraKitSession.js.map +1 -1
- package/lib/session/CameraKitSessionEvents.d.ts +7 -3
- package/lib/session/CameraKitSessionEvents.js +17 -0
- package/lib/session/CameraKitSessionEvents.js.map +1 -1
- package/lib/session/LensPerformanceMetrics.d.ts +2 -2
- package/lib/session/LensPerformanceMetrics.js +4 -3
- package/lib/session/LensPerformanceMetrics.js.map +1 -1
- package/lib/session/lensState.d.ts +2 -2
- package/lib/session/lensState.js +36 -37
- package/lib/session/lensState.js.map +1 -1
- package/package.json +2 -2
- package/lib/assertPlatformSupported.d.ts +0 -6
- package/lib/assertPlatformSupported.js +0 -21
- package/lib/assertPlatformSupported.js.map +0 -1
- package/lib/common/cameraKitUserAgent.js.map +0 -1
- package/lib/common/locale.d.ts +0 -2
- package/lib/common/locale.js +0 -11
- package/lib/common/locale.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platformInfo.js","sourceRoot":"","sources":["../../src/platform/platformInfo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,WAAW,MAAM,qBAAqB,CAAC;AAC9C,OAAO,YAAY,MAAM,8BAA8B,CAAC;AAuBxD;;;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;;;GAGG;AACH,SAAS,gBAAgB,CAAC,SAAiB;IACvC,uEAAuE;IACvE,MAAM,kBAAkB,GAAG,SAAS,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAElE,IAAI,kBAAkB,EAAE;QACpB,OAA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MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;QAC9C,OAAO,GAAG,IAAI,MAAM,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5C,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC;IAE9B,OAAO;QACH,eAAe;QACf,cAAc,EAAE,WAAW,CAAC,eAAe;QAC3C,QAAQ,EAAE,YAAY;QACtB,+GAA+G;QAC/G,8GAA8G;QAC9G,6FAA6F;QAC7F,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;QAChC,MAAM,EAAE,aAAa,CAAC,QAAQ;QAC9B,SAAS;QACT,WAAW;QACX,MAAM;QACN,UAAU;QACV,MAAM,EAAE,WAAW,EAAE;QACrB,cAAc,EAAE,MAAA,MAAA,SAAS,CAAC,UAAU,0CAAE,IAAI,mCAAI,SAAS;KAC1D,CAAC;AACN,CAAC,CAAC,CAAC","sourcesContent":["import { memoize } from \"../common/memoize\";\nimport { isRecord } from \"../common/typeguards\";\nimport environment from \"../environment.json\";\nimport lensCoreWasm from \"../lensCoreWasmVersions.json\";\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 * 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 * The origin may be useful to identify the running application (e.g. to attribute metrics).\n *\n * We need to handle cases in which we run inside a child browsing context (e.g. an iframe), which may not have a\n * hostname – in this case we'll check each ancestor context until we find a valid hostname.\n */\nfunction parseOrigin(): string {\n if (location.hostname !== \"\") return location.hostname;\n\n // Firefox does not implement ancestorOrigins, so we need a fallback.\n // Context here: https://github.com/whatwg/html/issues/1918\n const possibleOrigins =\n location.ancestorOrigins === undefined && typeof window !== \"undefined\"\n ? [window.parent.origin, window.top?.origin ?? \"\"]\n : location.ancestorOrigins ?? [];\n\n for (let origin of possibleOrigins) {\n try {\n origin = new URL(origin).hostname;\n if (origin) return origin;\n } catch (_) {}\n }\n\n return \"unknown\";\n}\n\n/* eslint-disable max-len */\n/**\n * The backend defines the allowed list of known OSes 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 parseOSName(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 * Parse the OS (a.k.a. platform) 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 parseOSVersion(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 * 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 = parseOSName(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 [\"Google Chrome\", \"Chrome\"],\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: parseOSName(userAgentData.platform),\n };\n}\n\n/** @internal */\nexport interface PlatformInfo {\n sdkShortVersion: string;\n sdkLongVersion: string;\n lensCore: {\n version: string;\n buildNumber: string;\n baseUrl: string;\n };\n browser: { brand: string; version: string };\n osName: string;\n osVersion: string;\n deviceModel: string;\n locale: string;\n fullLocale: string;\n origin: string;\n connectionType: ConnectionType;\n}\n\n/** @internal */\nexport const getPlatformInfo = memoize(function getPlatformIno(): PlatformInfo {\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 userAgent = navigator.userAgent;\n const userAgentData = isNavigatorUAData(navigator.userAgentData)\n ? normalizeUserAgentData(navigator.userAgentData)\n : parseUserAgentData(userAgent);\n\n const osVersion = parseOSVersion(userAgent);\n const deviceModel = parseDeviceModel(userAgent);\n\n // Remove any `-prerelease` or `+buildmetadata` portions from the semver string.\n const sdkShortVersion = environment.PACKAGE_VERSION.replace(/[-+]\\S+$/, \"\");\n\n const locale = navigator.language;\n // The full locale string includes all the languages with qvalues -- this is needed for some API calls.\n // More on qvalues: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values\n const fullLocale =\n (navigator.languages ?? [])\n .map((lang, index) => {\n const qvalue = Math.max(0, (10 - index) / 10);\n return `${lang};q=${qvalue.toFixed(1)}`;\n })\n .join(\", \") || locale;\n\n return {\n sdkShortVersion,\n sdkLongVersion: environment.PACKAGE_VERSION,\n lensCore: lensCoreWasm,\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 -- either way we're okay just picking the first one.\n browser: userAgentData.brands[0],\n osName: userAgentData.platform,\n osVersion,\n deviceModel,\n locale,\n fullLocale,\n origin: parseOrigin(),\n connectionType: navigator.connection?.type ?? \"unknown\",\n };\n});\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __awaiter, __rest } from "tslib";
|
|
2
2
|
import { BrowserHeaders } from "browser-headers";
|
|
3
|
-
import {
|
|
3
|
+
import { getCameraKitUserAgent } from "../platform/cameraKitUserAgent";
|
|
4
4
|
import { ensureError } from "../common/errorHelpers";
|
|
5
5
|
import { CircumstancesServiceClientImpl, GrpcWebImpl } from "../generated-proto/pb_schema/cdp/cof/circumstance_service";
|
|
6
6
|
import { HandlerChainBuilder } from "../handlers/HandlerChainBuilder";
|
|
@@ -36,7 +36,7 @@ export const cofHandlerFactory = Injectable("cofHandler", [configurationToken, r
|
|
|
36
36
|
signal.addEventListener("abort", () => reject(new Error("COF request aborted by handler chain.")));
|
|
37
37
|
}
|
|
38
38
|
client
|
|
39
|
-
.targetingQuery(request, new BrowserHeaders(Object.assign({ authorization: `Bearer ${config.apiToken}`, "x-snap-client-user-agent":
|
|
39
|
+
.targetingQuery(request, new BrowserHeaders(Object.assign({ authorization: `Bearer ${config.apiToken}`, "x-snap-client-user-agent": getCameraKitUserAgent() }, metadata)))
|
|
40
40
|
.then((response) => {
|
|
41
41
|
// NOTE: in order for cache persistance to work, we need to make the object cloneable,
|
|
42
42
|
// i.e. with no methods (it appears targetingQuery() attaches toObject() to response
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cofHandler.js","sourceRoot":"","sources":["../../src/remote-configuration/cofHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,8BAA8B,EAAE,WAAW,EAAE,MAAM,2DAA2D,CAAC;AAGxH,OAAO,EAAoB,mBAAmB,EAAmB,MAAM,iCAAiC,CAAC;AACzG,OAAO,EAEH,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,EACtB,8BAA8B,GACjC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,oCAAoC,CAAC;AAChH,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAEH,gCAAgC,GACnC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAA0B,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAMhE,MAAM,EAAE,GAAG,CAAyC,CAA6C,EAAE,EAAE,CAAC,CAAC,CAAC;AAExG,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAItC;;;;;;;GAOG;AACH,M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,EAAE,CAAC,CAAC;SACjD,GAAG,CACA,4BAA4B;IACxB,+EAA+E;IAC/E,iFAAiF;IACjF,+EAA+E;IAC/E,wBAAwB;IACxB,IAAI,mBAAmB,CACnB,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EACtB,IAAI,oBAAoB,CAAC,EAAE,YAAY,EAAE,UAAU,EAAE,CAAC,CACzD,EACD,CAAC,CAAkC,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAEzD,mDAAmD;IACnD,2EAA2E;IAC3E,4BAA4B,CAAC,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CACjE,CACJ,CAAC,OAAO,CAChB,CAAC;AACN,CAAC,CACJ,CAAC","sourcesContent":["import { BrowserHeaders } from \"browser-headers\";\nimport { cameraKitUserAgent } from \"../common/cameraKitUserAgent\";\nimport { ensureError } from \"../common/errorHelpers\";\nimport { CircumstancesServiceClientImpl, GrpcWebImpl } from \"../generated-proto/pb_schema/cdp/cof/circumstance_service\";\nimport { ConfigTargetingRequest } from \"../generated-proto/pb_schema/cdp/cof/config_request\";\nimport { ConfigTargetingResponse } from \"../generated-proto/pb_schema/cdp/cof/config_response\";\nimport { ChainableHandler, HandlerChainBuilder, RequestMetadata } from \"../handlers/HandlerChainBuilder\";\nimport {\n RequestStateEventTarget,\n dispatchRequestCompleted,\n dispatchRequestErrored,\n dispatchRequestStarted,\n requestStateEventTargetFactory,\n} from \"../handlers/requestStateEmittingHandler\";\nimport { createResponseCachingHandler, staleWhileRevalidateStrategy } from \"../handlers/responseCachingHandler\";\nimport { createRetryingHandler } from \"../handlers/retryingHandler\";\nimport { createTimeoutHandler } from \"../handlers/timeoutHandler\";\nimport { ExpiringPersistence } from \"../persistence/ExpiringPersistence\";\nimport { IndexedDBPersistence } from \"../persistence/IndexedDBPersistence\";\nimport {\n OperationalMetricsReporter,\n operationalMetricReporterFactory,\n} from \"../metrics/operational/operationalMetricsReporter\";\nimport { CameraKitConfiguration, configurationToken } from \"../configuration\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\n\nexport interface Metadata {\n [key: string]: string;\n}\n\nconst id = <Req, Res, Meta extends RequestMetadata>(h: ChainableHandler<Req, Res, Req, Res, Meta>) => h;\n\nexport const COF_REQUEST_TYPE = \"cof\";\n\nexport type CofDimensions = { requestType: typeof COF_REQUEST_TYPE };\n\n/**\n * Handler chain used to make COF requests. Uses the COF client to perform the\n * requests, with retries, timeout, and caching.\n *\n * The handler will first attempt to retrieve the COF response from cache. If it is found, the result is returned\n * immediately and the cache is updated in the background. If no response is found, a COF request is made. This request\n * will retry (with exponential backoff + jitter) for 5 seconds before returning an error to the caller.\n */\nexport const cofHandlerFactory = Injectable(\n \"cofHandler\",\n [configurationToken, requestStateEventTargetFactory.token, operationalMetricReporterFactory.token] as const,\n (\n config: CameraKitConfiguration,\n requestStateEventTarget: RequestStateEventTarget,\n reporter: OperationalMetricsReporter\n ) => {\n // We need to wrap `targetingQuery` to create a usable Handler – the main issue is that HandlerChainBuilder\n // always adds a `signal` property to the metadata argument (second argument of the Handler), but\n // `targetingQuery` expects the second argument to only contain headers.\n return (\n new HandlerChainBuilder(\n async (\n request: Partial<ConfigTargetingRequest>,\n { signal, isSideEffect: _, ...metadata }: Metadata & RequestMetadata\n ) => {\n const rpc = new GrpcWebImpl(`https://${config.apiHostname}`, {});\n const client = new CircumstancesServiceClientImpl(rpc);\n return new Promise<ConfigTargetingResponse>((resolve, reject) => {\n if (signal) {\n signal.addEventListener(\"abort\", () =>\n reject(new Error(\"COF request aborted by handler chain.\"))\n );\n }\n client\n .targetingQuery(\n request,\n new BrowserHeaders({\n authorization: `Bearer ${config.apiToken}`,\n \"x-snap-client-user-agent\": cameraKitUserAgent.userAgent,\n ...metadata,\n })\n )\n .then((response) => {\n // NOTE: in order for cache persistance to work, we need to make the object cloneable,\n // i.e. with no methods (it appears targetingQuery() attaches toObject() to response\n // object). Safety: We have to cast response object to a type that has toObject\n // defined, because that is indeed what generated code has:\n // eslint-disable-next-line max-len\n // https://github.sc-corp.net/Snapchat/camera-kit-web-sdk/blob/8d6b4e8bfa3717b376ab197a49972a1e410851f7/packages/web-sdk/src/generated-proto/pb_schema/cdp/cof/circumstance_service.ts#L1459\n delete (response as any).toObject;\n resolve(response);\n })\n .catch(reject);\n });\n }\n )\n .map(\n id((next) => async (request, metadata) => {\n const dimensions: CofDimensions = { requestType: COF_REQUEST_TYPE };\n const { requestId } = dispatchRequestStarted(requestStateEventTarget, { dimensions });\n try {\n const response = await next(request, metadata);\n // TODO: We hardcode status code and sizeByte values because we do not have access to\n // underlying transport of configs-web.\n // When this ticket is done https://jira.sc-corp.net/browse/CAMKIT-2840,\n // we will remove this handler and benefit from existing ones.\n const status = 200;\n let sizeByte = 0;\n try {\n sizeByte = new TextEncoder().encode(JSON.stringify(response)).byteLength;\n } finally {\n dispatchRequestCompleted(requestStateEventTarget, {\n requestId,\n dimensions,\n status,\n sizeByte,\n });\n return response;\n }\n } catch (error) {\n dispatchRequestErrored(requestStateEventTarget, {\n requestId,\n dimensions,\n error: ensureError(error),\n });\n throw error;\n }\n })\n )\n // targetingQuery() always converts failed responses into errors (unlike fetch()), so we need a custom\n // retryPredicate that retries all errors. We'll keep retrying (with backoff) for 20 seconds total\n // elapsed time before we return an error back up the chain.\n .map(createRetryingHandler({ retryPredicate: (r) => r instanceof Error }))\n // API gateway has 15 seconds timeout, so we rely on that first\n .map(createTimeoutHandler({ timeout: 20 * 1000 }))\n .map(\n createResponseCachingHandler(\n // COF responses will be removed from cache after 1 week. Keep in mind that the\n // staleWhileRevalidate strategy will update the cache each time COF is requested\n // – this expiration comes into play only if e.g. a user doesn't load the page\n // for more than a week.\n new ExpiringPersistence<ConfigTargetingResponse>(\n () => 7 * 24 * 60 * 60,\n new IndexedDBPersistence({ databaseName: \"COFCache\" })\n ),\n (r: Partial<ConfigTargetingRequest>) => JSON.stringify(r),\n\n // If we have a matching response already in cache,\n // we'll return it immediately and then update the cache in the background.\n staleWhileRevalidateStrategy({ requestType: \"cof\", reporter })\n )\n ).handler\n );\n }\n);\n"]}
|
|
1
|
+
{"version":3,"file":"cofHandler.js","sourceRoot":"","sources":["../../src/remote-configuration/cofHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,8BAA8B,EAAE,WAAW,EAAE,MAAM,2DAA2D,CAAC;AAGxH,OAAO,EAAoB,mBAAmB,EAAmB,MAAM,iCAAiC,CAAC;AACzG,OAAO,EAEH,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,EACtB,8BAA8B,GACjC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,oCAAoC,CAAC;AAChH,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAEH,gCAAgC,GACnC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAA0B,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAMhE,MAAM,EAAE,GAAG,CAAyC,CAA6C,EAAE,EAAE,CAAC,CAAC,CAAC;AAExG,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAItC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,UAAU,CACvC,YAAY,EACZ,CAAC,kBAAkB,EAAE,8BAA8B,CAAC,KAAK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wB;IACxB,IAAI,mBAAmB,CACnB,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EACtB,IAAI,oBAAoB,CAAC,EAAE,YAAY,EAAE,UAAU,EAAE,CAAC,CACzD,EACD,CAAC,CAAkC,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAEzD,mDAAmD;IACnD,2EAA2E;IAC3E,4BAA4B,CAAC,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CACjE,CACJ,CAAC,OAAO,CAChB,CAAC;AACN,CAAC,CACJ,CAAC","sourcesContent":["import { BrowserHeaders } from \"browser-headers\";\nimport { getCameraKitUserAgent } from \"../platform/cameraKitUserAgent\";\nimport { ensureError } from \"../common/errorHelpers\";\nimport { CircumstancesServiceClientImpl, GrpcWebImpl } from \"../generated-proto/pb_schema/cdp/cof/circumstance_service\";\nimport { ConfigTargetingRequest } from \"../generated-proto/pb_schema/cdp/cof/config_request\";\nimport { ConfigTargetingResponse } from \"../generated-proto/pb_schema/cdp/cof/config_response\";\nimport { ChainableHandler, HandlerChainBuilder, RequestMetadata } from \"../handlers/HandlerChainBuilder\";\nimport {\n RequestStateEventTarget,\n dispatchRequestCompleted,\n dispatchRequestErrored,\n dispatchRequestStarted,\n requestStateEventTargetFactory,\n} from \"../handlers/requestStateEmittingHandler\";\nimport { createResponseCachingHandler, staleWhileRevalidateStrategy } from \"../handlers/responseCachingHandler\";\nimport { createRetryingHandler } from \"../handlers/retryingHandler\";\nimport { createTimeoutHandler } from \"../handlers/timeoutHandler\";\nimport { ExpiringPersistence } from \"../persistence/ExpiringPersistence\";\nimport { IndexedDBPersistence } from \"../persistence/IndexedDBPersistence\";\nimport {\n OperationalMetricsReporter,\n operationalMetricReporterFactory,\n} from \"../metrics/operational/operationalMetricsReporter\";\nimport { CameraKitConfiguration, configurationToken } from \"../configuration\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\n\nexport interface Metadata {\n [key: string]: string;\n}\n\nconst id = <Req, Res, Meta extends RequestMetadata>(h: ChainableHandler<Req, Res, Req, Res, Meta>) => h;\n\nexport const COF_REQUEST_TYPE = \"cof\";\n\nexport type CofDimensions = { requestType: typeof COF_REQUEST_TYPE };\n\n/**\n * Handler chain used to make COF requests. Uses the COF client to perform the\n * requests, with retries, timeout, and caching.\n *\n * The handler will first attempt to retrieve the COF response from cache. If it is found, the result is returned\n * immediately and the cache is updated in the background. If no response is found, a COF request is made. This request\n * will retry (with exponential backoff + jitter) for 5 seconds before returning an error to the caller.\n */\nexport const cofHandlerFactory = Injectable(\n \"cofHandler\",\n [configurationToken, requestStateEventTargetFactory.token, operationalMetricReporterFactory.token] as const,\n (\n config: CameraKitConfiguration,\n requestStateEventTarget: RequestStateEventTarget,\n reporter: OperationalMetricsReporter\n ) => {\n // We need to wrap `targetingQuery` to create a usable Handler – the main issue is that HandlerChainBuilder\n // always adds a `signal` property to the metadata argument (second argument of the Handler), but\n // `targetingQuery` expects the second argument to only contain headers.\n return (\n new HandlerChainBuilder(\n async (\n request: Partial<ConfigTargetingRequest>,\n { signal, isSideEffect: _, ...metadata }: Metadata & RequestMetadata\n ) => {\n const rpc = new GrpcWebImpl(`https://${config.apiHostname}`, {});\n const client = new CircumstancesServiceClientImpl(rpc);\n return new Promise<ConfigTargetingResponse>((resolve, reject) => {\n if (signal) {\n signal.addEventListener(\"abort\", () =>\n reject(new Error(\"COF request aborted by handler chain.\"))\n );\n }\n client\n .targetingQuery(\n request,\n new BrowserHeaders({\n authorization: `Bearer ${config.apiToken}`,\n \"x-snap-client-user-agent\": getCameraKitUserAgent(),\n ...metadata,\n })\n )\n .then((response) => {\n // NOTE: in order for cache persistance to work, we need to make the object cloneable,\n // i.e. with no methods (it appears targetingQuery() attaches toObject() to response\n // object). Safety: We have to cast response object to a type that has toObject\n // defined, because that is indeed what generated code has:\n // eslint-disable-next-line max-len\n // https://github.sc-corp.net/Snapchat/camera-kit-web-sdk/blob/8d6b4e8bfa3717b376ab197a49972a1e410851f7/packages/web-sdk/src/generated-proto/pb_schema/cdp/cof/circumstance_service.ts#L1459\n delete (response as any).toObject;\n resolve(response);\n })\n .catch(reject);\n });\n }\n )\n .map(\n id((next) => async (request, metadata) => {\n const dimensions: CofDimensions = { requestType: COF_REQUEST_TYPE };\n const { requestId } = dispatchRequestStarted(requestStateEventTarget, { dimensions });\n try {\n const response = await next(request, metadata);\n // TODO: We hardcode status code and sizeByte values because we do not have access to\n // underlying transport of configs-web.\n // When this ticket is done https://jira.sc-corp.net/browse/CAMKIT-2840,\n // we will remove this handler and benefit from existing ones.\n const status = 200;\n let sizeByte = 0;\n try {\n sizeByte = new TextEncoder().encode(JSON.stringify(response)).byteLength;\n } finally {\n dispatchRequestCompleted(requestStateEventTarget, {\n requestId,\n dimensions,\n status,\n sizeByte,\n });\n return response;\n }\n } catch (error) {\n dispatchRequestErrored(requestStateEventTarget, {\n requestId,\n dimensions,\n error: ensureError(error),\n });\n throw error;\n }\n })\n )\n // targetingQuery() always converts failed responses into errors (unlike fetch()), so we need a custom\n // retryPredicate that retries all errors. We'll keep retrying (with backoff) for 20 seconds total\n // elapsed time before we return an error back up the chain.\n .map(createRetryingHandler({ retryPredicate: (r) => r instanceof Error }))\n // API gateway has 15 seconds timeout, so we rely on that first\n .map(createTimeoutHandler({ timeout: 20 * 1000 }))\n .map(\n createResponseCachingHandler(\n // COF responses will be removed from cache after 1 week. Keep in mind that the\n // staleWhileRevalidate strategy will update the cache each time COF is requested\n // – this expiration comes into play only if e.g. a user doesn't load the page\n // for more than a week.\n new ExpiringPersistence<ConfigTargetingResponse>(\n () => 7 * 24 * 60 * 60,\n new IndexedDBPersistence({ databaseName: \"COFCache\" })\n ),\n (r: Partial<ConfigTargetingRequest>) => JSON.stringify(r),\n\n // If we have a matching response already in cache,\n // we'll return it immediately and then update the cache in the background.\n staleWhileRevalidateStrategy({ requestType: \"cof\", reporter })\n )\n ).handler\n );\n }\n);\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { LensCore } from "../lens-core-module";
|
|
2
2
|
import { RemoteConfiguration } from "./remoteConfiguration";
|
|
3
3
|
export declare const setPreloadedConfiguration: {
|
|
4
|
-
(args_0:
|
|
4
|
+
(args_0: LensCore, args_1: RemoteConfiguration): void;
|
|
5
5
|
token: "setPreloadedConfiguration";
|
|
6
6
|
dependencies: readonly ["lensCore", "remoteConfiguration"];
|
|
7
7
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preloadConfiguration.js","sourceRoot":"","sources":["../../src/remote-configuration/preloadConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,gDAAgD,CAAC;AAC3E,OAAO,
|
|
1
|
+
{"version":3,"file":"preloadConfiguration.js","sourceRoot":"","sources":["../../src/remote-configuration/preloadConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,gDAAgD,CAAC;AAC3E,OAAO,EAA4D,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAChH,OAAO,EAAuB,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAExF,MAAM,CAAC,MAAM,yBAAyB,GAAG,UAAU,CAC/C,2BAA2B,EAC3B,CAAC,eAAe,CAAC,KAAK,EAAE,0BAA0B,CAAC,KAAK,CAAU,EAClE,CAAC,QAAkB,EAAE,mBAAwC,EAAE,EAAE;IAC7D,mBAAmB;SACd,YAAY,CAAC,SAAS,CAAC,gBAAgB,CAAC;SACxC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;SACb,SAAS,CAAC,CAAC,OAAO,EAAE,EAAE;QACnB,MAAM,MAAM,GAAmC,OAAO,CAAC,GAAG,CACtD,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAqB,CAAA,CACnE,CAAC;QAEF,QAAQ,CAAC,yBAAyB,CAAC,MAAM,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;AACX,CAAC,CACJ,CAAC","sourcesContent":["import { take } from \"rxjs\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { Namespace } from \"../generated-proto/pb_schema/cdp/cof/namespace\";\nimport { LensCore, LensCoreConfig, SetPreloadedConfigurationInput, lensCoreFactory } from \"../lens-core-module\";\nimport { RemoteConfiguration, remoteConfigurationFactory } from \"./remoteConfiguration\";\n\nexport const setPreloadedConfiguration = Injectable(\n \"setPreloadedConfiguration\",\n [lensCoreFactory.token, remoteConfigurationFactory.token] as const,\n (lensCore: LensCore, remoteConfiguration: RemoteConfiguration) => {\n remoteConfiguration\n .getNamespace(Namespace.LENS_CORE_CONFIG)\n .pipe(take(1))\n .subscribe((configs) => {\n const inputs: SetPreloadedConfigurationInput = configs.map(\n ({ configId, value }) => ({ configId, value } as LensCoreConfig)\n );\n\n lensCore.setPreloadedConfiguration(inputs);\n });\n }\n);\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Observable } from "rxjs";
|
|
2
2
|
import { Lens } from "../lens";
|
|
3
|
-
import {
|
|
3
|
+
import { LensCore } from "../lens-core-module";
|
|
4
4
|
import { LensLaunchParams } from "../lens/LensLaunchParams";
|
|
5
5
|
import { TypedEventTarget } from "../events/TypedEventTarget";
|
|
6
6
|
import { CameraKitDeviceInfo, CameraKitDeviceOptions, CameraKitSource } from "../media-sources/CameraKitSource";
|
|
@@ -98,7 +98,7 @@ export declare class CameraKitSession {
|
|
|
98
98
|
/**
|
|
99
99
|
* Use this to interact with lenses which require text input.
|
|
100
100
|
*/
|
|
101
|
-
keyboard: Keyboard, lensCore:
|
|
101
|
+
keyboard: Keyboard, lensCore: LensCore, sessionState: SessionState, lensState: LensState, logEntries: Observable<LogEntry>, pageVisibility: PageVisibility);
|
|
102
102
|
/**
|
|
103
103
|
* Apply a Lens to this session.
|
|
104
104
|
*
|
|
@@ -245,7 +245,7 @@ export declare class CameraKitSession {
|
|
|
245
245
|
* @internal
|
|
246
246
|
*/
|
|
247
247
|
export declare const cameraKitSessionFactory: {
|
|
248
|
-
(args_0:
|
|
248
|
+
(args_0: LensCore, args_1: Observable<LogEntry>, args_2: LensKeyboard, args_3: import("@snap/state-management").StateMachine<import("@snap/state-management").Action<"suspend", CameraKitSession> | import("@snap/state-management").Action<"resume", CameraKitSession> | import("@snap/state-management").Action<"destroy", undefined>, import("@snap/state-management").State<"inactive", undefined> | import("@snap/state-management").State<"active", CameraKitSession> | import("@snap/state-management").State<"destroyed", undefined>>, args_4: import("@snap/state-management").StateMachine<import("@snap/state-management").Action<"applyLens", {
|
|
249
249
|
lens: Lens;
|
|
250
250
|
launchParams?: LensLaunchParams | undefined;
|
|
251
251
|
}> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
|
|
@@ -19,7 +19,7 @@ import { LensPerformanceMetrics } from "./LensPerformanceMetrics";
|
|
|
19
19
|
import { lensStateFactory } from "./lensState";
|
|
20
20
|
import { sessionStateFactory } from "./sessionState";
|
|
21
21
|
import { lensKeyboardFactory } from "./LensKeyboard";
|
|
22
|
-
import { isSessionError } from "./CameraKitSessionEvents";
|
|
22
|
+
import { isPublicLensError, isSessionError } from "./CameraKitSessionEvents";
|
|
23
23
|
const logger = getLogger("CameraKitSession");
|
|
24
24
|
const log = errorLoggingDecorator(logger);
|
|
25
25
|
function isOptionalRenderTarget(value) {
|
|
@@ -88,16 +88,17 @@ export class CameraKitSession {
|
|
|
88
88
|
};
|
|
89
89
|
const sessionErrors = logEntries.pipe(filter((entry) => entry.level === "error"), map((entry) => entry.messages.find((e) => e instanceof Error)), filter(isSessionError));
|
|
90
90
|
this.subscriptions = [
|
|
91
|
+
// In case of an abort error, the only option is to destroy the current session,
|
|
92
|
+
// as it becomes inoperable.
|
|
93
|
+
sessionErrors.pipe(filter((error) => error.name === "LensAbortError")).subscribe(() => this.destroy()),
|
|
91
94
|
// In case of LensCore lens execution error, we must remove the lens from rendering
|
|
92
95
|
// NOTE: LensCore doesn't differentiate recoverable vs non-recoverable errors and
|
|
93
96
|
// it is recommened to always remove the lens.
|
|
94
97
|
sessionErrors
|
|
95
98
|
.pipe(filter((error) => error.name === "LensExecutionError"))
|
|
96
99
|
.subscribe(() => this.removeLens()),
|
|
97
|
-
// Report
|
|
98
|
-
sessionErrors.subscribe((error) => {
|
|
99
|
-
if (error.name !== "LensExecutionError" && error.name !== "LensImagePickerError")
|
|
100
|
-
return;
|
|
100
|
+
// Report public session errors to apps
|
|
101
|
+
sessionErrors.pipe(filter(isPublicLensError)).subscribe((error) => {
|
|
101
102
|
const state = lensState.getState();
|
|
102
103
|
if (!isState(state, "noLensApplied")) {
|
|
103
104
|
this.events.dispatchEvent(new TypedCustomEvent("error", { error, lens: state.data }));
|
|
@@ -221,15 +222,9 @@ export class CameraKitSession {
|
|
|
221
222
|
return;
|
|
222
223
|
this.playing = target;
|
|
223
224
|
const type = this.renderTargetToCanvasType(target);
|
|
224
|
-
return
|
|
225
|
-
this.
|
|
226
|
-
|
|
227
|
-
onSuccess: resolve,
|
|
228
|
-
onFailure: (error) => {
|
|
229
|
-
this.playing = false;
|
|
230
|
-
reject(error);
|
|
231
|
-
},
|
|
232
|
-
});
|
|
225
|
+
return this.lensCore.playCanvas({ type }).catch((error) => {
|
|
226
|
+
this.playing = false;
|
|
227
|
+
throw error;
|
|
233
228
|
});
|
|
234
229
|
});
|
|
235
230
|
}
|
|
@@ -247,15 +242,9 @@ export class CameraKitSession {
|
|
|
247
242
|
const priorPlayingState = this.playing;
|
|
248
243
|
this.playing = false;
|
|
249
244
|
const type = this.renderTargetToCanvasType(target);
|
|
250
|
-
return
|
|
251
|
-
this.
|
|
252
|
-
|
|
253
|
-
onSuccess: resolve,
|
|
254
|
-
onFailure: (error) => {
|
|
255
|
-
this.playing = priorPlayingState;
|
|
256
|
-
reject(error);
|
|
257
|
-
},
|
|
258
|
-
});
|
|
245
|
+
return this.lensCore.pauseCanvas({ type }).catch((error) => {
|
|
246
|
+
this.playing = priorPlayingState;
|
|
247
|
+
throw error;
|
|
259
248
|
});
|
|
260
249
|
});
|
|
261
250
|
}
|
|
@@ -324,9 +313,7 @@ export class CameraKitSession {
|
|
|
324
313
|
return __awaiter(this, void 0, void 0, function* () {
|
|
325
314
|
// LensCore uses 0 to remove the limit.
|
|
326
315
|
const fps = fpsLimit < Number.POSITIVE_INFINITY ? fpsLimit : 0;
|
|
327
|
-
return
|
|
328
|
-
this.lensCore.setFPSLimit({ fps, onSuccess, onFailure });
|
|
329
|
-
});
|
|
316
|
+
return this.lensCore.setFPSLimit({ fps });
|
|
330
317
|
});
|
|
331
318
|
}
|
|
332
319
|
/**
|
|
@@ -336,12 +323,18 @@ export class CameraKitSession {
|
|
|
336
323
|
*/
|
|
337
324
|
destroy() {
|
|
338
325
|
return __awaiter(this, void 0, void 0, function* () {
|
|
326
|
+
try {
|
|
327
|
+
yield this.lensCore.clearAllLenses();
|
|
328
|
+
yield this.lensCore.teardown();
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
// If a LensCore is in an aborted state, the above lines may throw an error.
|
|
332
|
+
// In such cases, we should continue with the cleanup process.
|
|
333
|
+
// We are also not interested in reporting these errors to our backend.
|
|
334
|
+
logger.warn("An error occurred in LensCore during the session termination process.", error);
|
|
335
|
+
}
|
|
339
336
|
this.subscriptions.forEach((sub) => sub.unsubscribe());
|
|
340
|
-
yield this.removeLens();
|
|
341
337
|
yield this.safelyDetachSource();
|
|
342
|
-
yield new Promise((resolve, reject) => {
|
|
343
|
-
this.lensCore.teardown({ onSuccess: resolve, onFailure: reject });
|
|
344
|
-
});
|
|
345
338
|
this.removePageVisibilityHandlers();
|
|
346
339
|
this.sessionState.dispatch("destroy", undefined);
|
|
347
340
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CameraKitSession.js","sourceRoot":"","sources":["../../src/session/CameraKitSession.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,EAAc,EAAE,EAAgB,SAAS,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACjG,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAQ,MAAM,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AAE7E,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,SAAS,EAAY,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAkB,qB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L,CAAC;KAAA;CACJ;AA9RS;IAFL,QAAQ;IACR,GAAG;IACa,WAAA,KAAK,CAAC,MAAM,CAAC,CAAA;;;;iDA4B7B;AAgBK;IADL,GAAG;;;;kDAqBH;AAwBK;IAFL,QAAQ;IACR,GAAG;IACQ,WAAA,KAAK,CAAC,sBAAsB,CAAC,CAAA;;;;4CAexC;AAWK;IAFL,QAAQ;IACR,GAAG;IACS,WAAA,KAAK,CAAC,sBAAsB,CAAC,CAAA;;;;6CAgBzC;AAQD;IADC,GAAG;;;;4CAMH;AAQD;IADC,GAAG;;;;8CAMH;AAqCK;IAFL,QAAQ;IACR,GAAG;;;;iDAkCH;AAgBK;IADL,GAAG;;;;mDAOH;AAQK;IADL,GAAG;;;;+CAUH;AAuBL;;GAEG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,UAAU,CAC7C,kBAAkB,EAClB;IACI,eAAe,CAAC,KAAK;IACrB,iBAAiB,CAAC,KAAK;IACvB,mBAAmB,CAAC,KAAK;IACzB,mBAAmB,CAAC,KAAK;IACzB,gBAAgB,CAAC,KAAK;IACtB,qBAAqB,CAAC,KAAK;CACrB,EACV,CACI,QAAwB,EACxB,UAAgC,EAChC,QAAsB,EACtB,YAA0B,EAC1B,SAAoB,EACpB,cAA8B,EAChC,EAAE,CAAC,IAAI,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,CAAC,CACrG,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/member-ordering */\nimport { filter, firstValueFrom, map, Observable, of, Subscription, takeUntil, tap } from \"rxjs\";\nimport { dispatch, forActions, inStates, isAction, isState } from \"@snap/state-management\";\nimport { Lens, isLens } from \"../lens\";\nimport { CanvasType, LensCoreModule } from \"../lens-core-module\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { LensLaunchParams } from \"../lens/LensLaunchParams\";\nimport { getTypeName, guard, validate } from \"../common/validate\";\nimport { TypedEventTarget } from \"../events/TypedEventTarget\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { CameraKitDeviceInfo, CameraKitDeviceOptions, CameraKitSource } from \"../media-sources/CameraKitSource\";\nimport { cameraKitSourceError } from \"../namedErrors\";\nimport { createMediaStreamSource } from \"../media-sources/MediaStreamSource\";\nimport { createVideoSource } from \"../media-sources/VideoSource\";\nimport { getLogger, LogEntry } from \"../logger/logger\";\nimport { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { PageVisibility, pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { LensPerformanceMetrics } from \"./LensPerformanceMetrics\";\nimport { lensStateFactory, LensState } from \"./lensState\";\nimport { SessionState, sessionStateFactory } from \"./sessionState\";\nimport { Keyboard, lensKeyboardFactory, LensKeyboard } from \"./LensKeyboard\";\nimport { CameraKitSessionEvents, isSessionError } from \"./CameraKitSessionEvents\";\n\nconst logger = getLogger(\"CameraKitSession\");\nconst log = errorLoggingDecorator(logger);\n\nfunction isOptionalRenderTarget(value: unknown): value is RenderTarget | undefined {\n return value === \"live\" || value === \"capture\" || value === undefined;\n}\n\n/**\n * Enumerates the supported render targets.\n *\n * Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose\n * which render target to render, and the result for each target is available as a separate `<canvas>` element.\n *\n * @category Rendering\n * @category Lenses\n */\nexport type RenderTarget = \"live\" | \"capture\";\n\n/**\n * A CameraKitSession represents a single rendering pipeline connecting an input media source to output `<canvas>`\n * elements. When a Lens is applied to the session, CameraKit uses the Lens to transform the input media into rendered\n * output.\n *\n * CameraKitSession is the primary object that applications interact with when integrating the CameraKit SDK.\n *\n * A CameraKitSession instance is obtained by calling {@link CameraKit.createSession}.\n *\n * @example\n * ```ts\n * const cameraKit = await bootstrapCameraKit(config)\n * const session = await cameraKit.createSession()\n * ```\n *\n * @category Rendering\n * @category Lenses\n */\nexport class CameraKitSession {\n /**\n * CameraKitSession renders video output to a `<canvas>` element. In fact, each session contains two canvas outputs\n * corresponding to the RenderTargets used by Lens creators, when using LensStudio to create a Lens.\n *\n * The `live` output renders content suitable for the Lens user (e.g. it may contain additional UI elements\n * applicable only to the person applying the lens). The `capture` output renders content suitable for sharing with\n * other users (e.g. sent to the other members of a video call, or saved to disk for sharing later).\n *\n * For many lenses, these outputs are identical – but each lens is free to render differently, based on its own\n * use-case.\n */\n readonly output: {\n live: HTMLCanvasElement;\n capture: HTMLCanvasElement;\n };\n\n /**\n * Indicates whether or not the session is currently rendering. If `false`, rendering is stopped. Otherwise the\n * value indicates which output is being rendered.\n */\n playing: false | RenderTarget;\n\n /**\n * Add event listeners here to handle events which occur during the CameraKitSession.\n *\n * **Note:** Applications may want to handle the `error` event, and check the contained error type -- if the type\n * is {@link LensExecutionError}, this means the current lens was unable to render and CameraKit will automatically\n * remove the lens.\n *\n * @example\n * ```ts\n * cameraKitSession.events.addEventListener('error', ({ detail }) => {\n * if (detail.error.name === 'LensExecutionError') {\n * console.log(`Lens ${detail.lens.name} encountered an error and was removed. Please pick a different lens.`)\n * }\n * })\n * ```\n */\n readonly events = new TypedEventTarget<CameraKitSessionEvents>();\n\n /**\n * Use this to measure current lens performance.\n */\n readonly metrics: LensPerformanceMetrics;\n\n private readonly removePageVisibilityHandlers: () => void;\n private source?: CameraKitSource;\n private subscriptions: Subscription[];\n\n /**\n * @internal\n */\n constructor(\n /**\n * Use this to interact with lenses which require text input.\n */\n public readonly keyboard: Keyboard,\n\n private readonly lensCore: LensCoreModule,\n private readonly sessionState: SessionState,\n private readonly lensState: LensState,\n logEntries: Observable<LogEntry>,\n pageVisibility: PageVisibility\n ) {\n const outputs = this.lensCore.getOutputCanvases();\n this.output = {\n live: outputs[this.lensCore.CanvasType.Preview.value],\n capture: outputs[this.lensCore.CanvasType.Capture.value],\n };\n this.playing = false;\n\n this.metrics = new LensPerformanceMetrics(this.lensCore);\n\n const removeOnHidden = pageVisibility.onPageHidden(() => this.sessionState.dispatch(\"suspend\", this));\n const removeOnVisible = pageVisibility.onPageVisible(() => this.sessionState.dispatch(\"resume\", this));\n this.removePageVisibilityHandlers = () => {\n removeOnHidden();\n removeOnVisible();\n };\n\n const sessionErrors = logEntries.pipe(\n filter((entry) => entry.level === \"error\"),\n map((entry) => entry.messages.find((e) => e instanceof Error)),\n filter(isSessionError)\n );\n\n this.subscriptions = [\n // In case of LensCore lens execution error, we must remove the lens from rendering\n // NOTE: LensCore doesn't differentiate recoverable vs non-recoverable errors and\n // it is recommened to always remove the lens.\n sessionErrors\n .pipe(filter((error) => error.name === \"LensExecutionError\"))\n .subscribe(() => this.removeLens()),\n\n // Report LensExecutionError and LensImagePickerError errors to apps\n sessionErrors.subscribe((error) => {\n if (error.name !== \"LensExecutionError\" && error.name !== \"LensImagePickerError\") return;\n\n const state = lensState.getState();\n if (!isState(state, \"noLensApplied\")) {\n this.events.dispatchEvent(new TypedCustomEvent(\"error\", { error, lens: state.data }));\n } else {\n // NOTE: at this point the error is already reported, so we can just log a warning\n logger.warn(\n new Error(\"Lens error occurred even though there is no active lens.\", {\n cause: error,\n })\n );\n }\n }),\n ];\n }\n\n /**\n * Apply a Lens to this session.\n *\n * This method will download (and cache) the Lens executable, and then use that Lens for rendering. If the session\n * is currently playing, this will immediately update the rendered output. Otherwise, the new Lens will be used\n * when session playback in resumed.\n *\n * Calling `applyLens` replaces any prior Lens – only one Lens is allowed at a time (per session).\n *\n * **NOTE**: Errors may occur after the Lens is applied. If the Lens encounters errors while rendering,\n * Camera Kit will automatically remove the Lens from the session and emit a {@link LensExecutionError} event.\n * Applications may want to listen for this error and, for example,\n * prevent the Lens from being selected again by the user.\n *\n * ```ts\n * session.events.addEventListener(\"error\", ({ detail }) => {\n * if (detail.error.name === \"LensExecutionError\") {\n * preventFutureLensSelection(detail.lens);\n * showMessage(\"We're sorry, but the Lens you selected encountered an error. Please choose a different Lens.\");\n * }\n * });\n * ```\n *\n * @param lens The Lens to apply to this session.\n * @param launchParams: This can optionally be provided to pass some initial data to the lens – only certain lenses\n * expect launch data.\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the lens has been applied.\n * 2. Resolved with `false`: the lens has not been applied, but no error occurred – this can happen if a\n * subsequent call to `applyLens` interrupted the lens application.\n * 3. Rejected: the lens has not been applied because an error occurred. This can happen if:\n * - The lens ID cannot be found in the LensRepository (use LensRepository to load the lens before calling this\n * method)\n * - Lens content download fails, or the download of any required lens assets fails.\n * - An internal failure occurs in the Lens rendering engine when attempting to apply the lens.\n */\n @validate\n @log\n async applyLens(@guard(isLens) lens: Lens, launchParams?: LensLaunchParams): Promise<boolean> {\n const action = this.lensState.actions.applyLens({ lens, launchParams });\n return firstValueFrom(\n of(action).pipe(\n dispatch(this.lensState),\n\n // If another applyLens occurs while we're waiting, resolve this applyLens promise early – we're no\n // longer waiting for the requested lens to be applied.\n takeUntil(\n this.lensState.events.pipe(\n forActions(\"applyLens\"),\n filter(([a]) => a !== action)\n )\n ),\n\n // If lens application failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"applyLensFailed\") && a.data.lens.id === lens.id) throw a.data.error;\n }),\n\n inStates(\"lensApplied\"),\n\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early – i.e. the lens was not\n // applied (application was interrupted by a new call to `applyLens`), so we'll resolve with `false`.\n { defaultValue: false }\n );\n }\n\n /**\n * Remove a Lens from this session.\n *\n * When a Lens is removed, rendering continues if the session is playing. It will just render the session input\n * directly to the outputs without any image processing.\n *\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the session's rendered output has no lens applied.\n * 2. Resolved with `false`: the current lens has been removed, but a subsequent call to `applyLens` means that the\n * session's rendered output will still have a (new) lens applied.\n * 3. Rejected: the lens has failed to be removed. This can happen if an internal failure occurs in the Lens\n * rendering engine when attempting to remove the lens.\n */\n @log\n async removeLens(): Promise<boolean> {\n if (isState(this.lensState.getState(), \"noLensApplied\")) return true;\n return firstValueFrom(\n of(this.lensState.actions.removeLens()).pipe(\n dispatch(this.lensState),\n // If lens removal failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"removeLensFailed\")) throw a.data;\n }),\n inStates(\"noLensApplied\"),\n\n // If applyLens is called while we're waiting for removal, complete immediately – applying the next lens\n // will replace the current one.\n takeUntil(this.lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early (otherwise firstValueFrom will\n // return a rejected Promise).\n { defaultValue: false }\n );\n }\n\n /**\n * Start/resume session playback – LensCore will begin rendering frames to the output.\n *\n * If no source has been set for the session, calling `play()` will update the playing state, but no actual image\n * processing will occur until `setSource()` is called.\n *\n * @example\n * ```ts\n * const cameraKitSession = await cameraKit.createSession()\n * await cameraKitSession.setSource(mySource)\n * await cameraKitSession.play()\n *\n * // If you call `play` before `setSource`, the call to `play` will resolve but playback will only begin once a\n * // media source has been set.\n * ```\n *\n * @param target Specify the {@link RenderTarget} to render. Defaults to the `live` RenderTarget.\n * @returns Promise resolves when playback state has been updated. If no source has been set, this means `play` will\n * resolve before any frames are processed -- but once a source is set, frames will immediately begin processing.\n */\n @validate\n @log\n async play(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (this.playing) return;\n this.playing = target;\n\n const type = this.renderTargetToCanvasType(target);\n return new Promise((resolve, reject) => {\n this.lensCore.playCanvas({\n type,\n onSuccess: resolve,\n onFailure: (error: Error) => {\n this.playing = false;\n reject(error);\n },\n });\n });\n }\n\n /**\n * Pause session playback – LensCore will stop rendering frames to the output.\n *\n * @param target Specify the RenderTarget to pause playback. May be either `'live'` or `'capture'`.\n * Default is `'live'`.\n * @returns Promise resolves when playback has stopped.\n */\n @validate\n @log\n async pause(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (!this.playing) return;\n const priorPlayingState = this.playing;\n this.playing = false;\n\n const type = this.renderTargetToCanvasType(target);\n return new Promise((resolve, reject) => {\n this.lensCore.pauseCanvas({\n type,\n onSuccess: resolve,\n onFailure: (error: Error) => {\n this.playing = priorPlayingState;\n reject(error);\n },\n });\n });\n }\n\n /**\n * Mute all sounds (default SDK state is unmuted).\n *\n * @param fade Do we want audio to fade out?\n */\n @log\n mute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: true,\n fade,\n });\n }\n\n /**\n * Unmute all sounds.\n *\n * @param fade Do we want audio to fade in?\n */\n @log\n unmute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: false,\n fade,\n });\n }\n\n /**\n * Set the media source for this session.\n *\n * Sessions may only have one source at a time - if `setSource` is called multiple times, subsequent calls replace\n * the prior source. Setting the source does not trigger rendering (that’s done by `session.play()`). If the session\n * is already playing, setting the source will immediately begin rendering the new source.\n *\n * The CameraKit SDK provides implementations for various common sources, which applications can create using the\n * following functions:\n * - {@link createMediaStreamSource}\n * - {@link createVideoSource}\n * - {@link createImageSource}\n *\n * @param source A CameraKitSource object representing input media (e.g. a webcam stream, video, or some other\n * source of image data), which CameraKit will supply to Lenses in order for them to render effects on top of that\n * source.\n * @returns Promise is resolved when the source has successfully be set. If the session was already in the playing\n * state, the Promise resolves when the first frame from the new source has been rendered. The resolved value is\n * the {@link CameraKitSource} object attached to the session.\n */\n async setSource(source: CameraKitSource): Promise<CameraKitSource>;\n /** Deprecated: Support for CameraKitDeviceInfo will be removed in future releases.\n * Please use CameraKitDeviceOptions instead which accepts the \"environment\" and \"user\" cameraType\n * @deprecated\n */\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceInfo>\n ): Promise<CameraKitSource>;\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceOptions>\n ): Promise<CameraKitSource>;\n @validate\n @log\n async setSource(\n source: CameraKitSource | MediaStream | HTMLVideoElement,\n options: Partial<CameraKitDeviceInfo | CameraKitDeviceOptions> = {}\n ): Promise<CameraKitSource> {\n await this.safelyDetachSource();\n\n // For convenience, we allow callers to pass in native objects (e.g. MediaStream) as well as CameraKitSource.\n // Native objects are wrapped in corresponding CameraKitSource classes with default options.\n const cameraKitSource =\n source instanceof MediaStream\n ? createMediaStreamSource(source, options)\n : source instanceof HTMLVideoElement\n ? createVideoSource(source, options)\n : source;\n\n const priorPlayingState = this.playing;\n this.playing = false;\n\n // The source will provide its data to LensCore, and use other LensCore APIs (e.g. setRenderSize,\n // setInputTransform) to render the source correctly.\n await cameraKitSource.attach(this.lensCore, (error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source attachment.\", error));\n });\n\n // If attachment is successful, we'll update our source so that we can detach it later.\n this.source = cameraKitSource;\n\n // Finally we'll resume playback, if appropriate.\n if (priorPlayingState) {\n await this.play(priorPlayingState);\n }\n\n return cameraKitSource;\n }\n\n /**\n * Set an FPS limit.\n *\n * This may be useful to reduce CPU/GPU resource usage by CameraKit if, for example, the input\n * media source has a low FPS – CameraKit would then not try to render more frequently than the source produces\n * new frames.\n *\n * This may also be useful to gracefully degrade performance in situations where lowering FPS is preferable over\n * alternatives.\n *\n * @param fpsLimit A maximum FPS, rendering will not exceed this limit\n * @returns Promise is resolved when the limit is successfully set.\n */\n @log\n async setFPSLimit(fpsLimit: number): Promise<void> {\n // LensCore uses 0 to remove the limit.\n const fps = fpsLimit < Number.POSITIVE_INFINITY ? fpsLimit : 0;\n return new Promise((onSuccess, onFailure) => {\n this.lensCore.setFPSLimit({ fps, onSuccess, onFailure });\n });\n }\n\n /**\n * Destroy the session.\n *\n * The session will become inoperable. Frame processing stops, and any session-scoped graphical resources are freed.\n */\n @log\n async destroy(): Promise<void> {\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n await this.removeLens();\n await this.safelyDetachSource();\n await new Promise<void>((resolve, reject) => {\n this.lensCore.teardown({ onSuccess: resolve, onFailure: reject });\n });\n this.removePageVisibilityHandlers();\n this.sessionState.dispatch(\"destroy\", undefined);\n }\n\n private renderTargetToCanvasType(target: RenderTarget): CanvasType {\n return target === \"capture\" ? this.lensCore.CanvasType.Capture : this.lensCore.CanvasType.Preview;\n }\n\n private async safelyDetachSource(): Promise<void> {\n if (this.source) {\n try {\n await this.source.detach((error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source detachment.\", error));\n });\n // If there's a failure to detach, we will report the error and proceed. Failure to detach may lead to a\n // memory leak, but it shouldn't prevent us from switching to the new source.\n } catch (error) {\n logger.error(\n cameraKitSourceError(`Detaching prior source of type ${getTypeName(this.source)} failed.`, error)\n );\n }\n }\n }\n}\n\n/**\n * @internal\n */\nexport const cameraKitSessionFactory = Injectable(\n \"CameraKitSession\",\n [\n lensCoreFactory.token,\n logEntriesFactory.token,\n lensKeyboardFactory.token,\n sessionStateFactory.token,\n lensStateFactory.token,\n pageVisibilityFactory.token,\n ] as const,\n (\n lensCore: LensCoreModule,\n logEntries: Observable<LogEntry>,\n keyboard: LensKeyboard,\n sessionState: SessionState,\n lensState: LensState,\n pageVisibility: PageVisibility\n ) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries, pageVisibility)\n);\n"]}
|
|
1
|
+
{"version":3,"file":"CameraKitSession.js","sourceRoot":"","sources":["../../src/session/CameraKitSession.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,EAAc,EAAE,EAAgB,SAAS,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACjG,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAQ,MAAM,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AAE7E,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC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["/* eslint-disable @typescript-eslint/member-ordering */\nimport { filter, firstValueFrom, map, Observable, of, Subscription, takeUntil, tap } from \"rxjs\";\nimport { dispatch, forActions, inStates, isAction, isState } from \"@snap/state-management\";\nimport { Lens, isLens } from \"../lens\";\nimport { CanvasType, LensCore } from \"../lens-core-module\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { LensLaunchParams } from \"../lens/LensLaunchParams\";\nimport { getTypeName, guard, validate } from \"../common/validate\";\nimport { TypedEventTarget } from \"../events/TypedEventTarget\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { CameraKitDeviceInfo, CameraKitDeviceOptions, CameraKitSource } from \"../media-sources/CameraKitSource\";\nimport { cameraKitSourceError, LensExecutionError } from \"../namedErrors\";\nimport { createMediaStreamSource } from \"../media-sources/MediaStreamSource\";\nimport { createVideoSource } from \"../media-sources/VideoSource\";\nimport { getLogger, LogEntry } from \"../logger/logger\";\nimport { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { PageVisibility, pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { LensPerformanceMetrics } from \"./LensPerformanceMetrics\";\nimport { lensStateFactory, LensState } from \"./lensState\";\nimport { SessionState, sessionStateFactory } from \"./sessionState\";\nimport { Keyboard, lensKeyboardFactory, LensKeyboard } from \"./LensKeyboard\";\nimport { CameraKitSessionEvents, isPublicLensError, isSessionError } from \"./CameraKitSessionEvents\";\n\nconst logger = getLogger(\"CameraKitSession\");\nconst log = errorLoggingDecorator(logger);\n\nfunction isOptionalRenderTarget(value: unknown): value is RenderTarget | undefined {\n return value === \"live\" || value === \"capture\" || value === undefined;\n}\n\n/**\n * Enumerates the supported render targets.\n *\n * Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose\n * which render target to render, and the result for each target is available as a separate `<canvas>` element.\n *\n * @category Rendering\n * @category Lenses\n */\nexport type RenderTarget = \"live\" | \"capture\";\n\n/**\n * A CameraKitSession represents a single rendering pipeline connecting an input media source to output `<canvas>`\n * elements. When a Lens is applied to the session, CameraKit uses the Lens to transform the input media into rendered\n * output.\n *\n * CameraKitSession is the primary object that applications interact with when integrating the CameraKit SDK.\n *\n * A CameraKitSession instance is obtained by calling {@link CameraKit.createSession}.\n *\n * @example\n * ```ts\n * const cameraKit = await bootstrapCameraKit(config)\n * const session = await cameraKit.createSession()\n * ```\n *\n * @category Rendering\n * @category Lenses\n */\nexport class CameraKitSession {\n /**\n * CameraKitSession renders video output to a `<canvas>` element. In fact, each session contains two canvas outputs\n * corresponding to the RenderTargets used by Lens creators, when using LensStudio to create a Lens.\n *\n * The `live` output renders content suitable for the Lens user (e.g. it may contain additional UI elements\n * applicable only to the person applying the lens). The `capture` output renders content suitable for sharing with\n * other users (e.g. sent to the other members of a video call, or saved to disk for sharing later).\n *\n * For many lenses, these outputs are identical – but each lens is free to render differently, based on its own\n * use-case.\n */\n readonly output: {\n live: HTMLCanvasElement;\n capture: HTMLCanvasElement;\n };\n\n /**\n * Indicates whether or not the session is currently rendering. If `false`, rendering is stopped. Otherwise the\n * value indicates which output is being rendered.\n */\n playing: false | RenderTarget;\n\n /**\n * Add event listeners here to handle events which occur during the CameraKitSession.\n *\n * **Note:** Applications may want to handle the `error` event, and check the contained error type -- if the type\n * is {@link LensExecutionError}, this means the current lens was unable to render and CameraKit will automatically\n * remove the lens.\n *\n * @example\n * ```ts\n * cameraKitSession.events.addEventListener('error', ({ detail }) => {\n * if (detail.error.name === 'LensExecutionError') {\n * console.log(`Lens ${detail.lens.name} encountered an error and was removed. Please pick a different lens.`)\n * }\n * })\n * ```\n */\n readonly events = new TypedEventTarget<CameraKitSessionEvents>();\n\n /**\n * Use this to measure current lens performance.\n */\n readonly metrics: LensPerformanceMetrics;\n\n private readonly removePageVisibilityHandlers: () => void;\n private source?: CameraKitSource;\n private subscriptions: Subscription[];\n\n /**\n * @internal\n */\n constructor(\n /**\n * Use this to interact with lenses which require text input.\n */\n public readonly keyboard: Keyboard,\n\n private readonly lensCore: LensCore,\n private readonly sessionState: SessionState,\n private readonly lensState: LensState,\n logEntries: Observable<LogEntry>,\n pageVisibility: PageVisibility\n ) {\n const outputs = this.lensCore.getOutputCanvases();\n this.output = {\n live: outputs[this.lensCore.CanvasType.Preview.value],\n capture: outputs[this.lensCore.CanvasType.Capture.value],\n };\n this.playing = false;\n\n this.metrics = new LensPerformanceMetrics(this.lensCore);\n\n const removeOnHidden = pageVisibility.onPageHidden(() => this.sessionState.dispatch(\"suspend\", this));\n const removeOnVisible = pageVisibility.onPageVisible(() => this.sessionState.dispatch(\"resume\", this));\n this.removePageVisibilityHandlers = () => {\n removeOnHidden();\n removeOnVisible();\n };\n\n const sessionErrors = logEntries.pipe(\n filter((entry) => entry.level === \"error\"),\n map((entry) => entry.messages.find((e) => e instanceof Error)),\n filter(isSessionError)\n );\n\n this.subscriptions = [\n // In case of an abort error, the only option is to destroy the current session,\n // as it becomes inoperable.\n sessionErrors.pipe(filter((error) => error.name === \"LensAbortError\")).subscribe(() => this.destroy()),\n\n // In case of LensCore lens execution error, we must remove the lens from rendering\n // NOTE: LensCore doesn't differentiate recoverable vs non-recoverable errors and\n // it is recommened to always remove the lens.\n sessionErrors\n .pipe(filter((error) => error.name === \"LensExecutionError\"))\n .subscribe(() => this.removeLens()),\n\n // Report public session errors to apps\n sessionErrors.pipe(filter(isPublicLensError)).subscribe((error) => {\n const state = lensState.getState();\n if (!isState(state, \"noLensApplied\")) {\n this.events.dispatchEvent(new TypedCustomEvent(\"error\", { error, lens: state.data }));\n } else {\n // NOTE: at this point the error is already reported, so we can just log a warning\n logger.warn(\n new Error(\"Lens error occurred even though there is no active lens.\", {\n cause: error,\n })\n );\n }\n }),\n ];\n }\n\n /**\n * Apply a Lens to this session.\n *\n * This method will download (and cache) the Lens executable, and then use that Lens for rendering. If the session\n * is currently playing, this will immediately update the rendered output. Otherwise, the new Lens will be used\n * when session playback in resumed.\n *\n * Calling `applyLens` replaces any prior Lens – only one Lens is allowed at a time (per session).\n *\n * **NOTE**: Errors may occur after the Lens is applied. If the Lens encounters errors while rendering,\n * Camera Kit will automatically remove the Lens from the session and emit a {@link LensExecutionError} event.\n * Applications may want to listen for this error and, for example,\n * prevent the Lens from being selected again by the user.\n *\n * ```ts\n * session.events.addEventListener(\"error\", ({ detail }) => {\n * if (detail.error.name === \"LensExecutionError\") {\n * preventFutureLensSelection(detail.lens);\n * showMessage(\"We're sorry, but the Lens you selected encountered an error. Please choose a different Lens.\");\n * }\n * });\n * ```\n *\n * @param lens The Lens to apply to this session.\n * @param launchParams: This can optionally be provided to pass some initial data to the lens – only certain lenses\n * expect launch data.\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the lens has been applied.\n * 2. Resolved with `false`: the lens has not been applied, but no error occurred – this can happen if a\n * subsequent call to `applyLens` interrupted the lens application.\n * 3. Rejected: the lens has not been applied because an error occurred. This can happen if:\n * - The lens ID cannot be found in the LensRepository (use LensRepository to load the lens before calling this\n * method)\n * - Lens content download fails, or the download of any required lens assets fails.\n * - An internal failure occurs in the Lens rendering engine when attempting to apply the lens.\n */\n @validate\n @log\n async applyLens(@guard(isLens) lens: Lens, launchParams?: LensLaunchParams): Promise<boolean> {\n const action = this.lensState.actions.applyLens({ lens, launchParams });\n return firstValueFrom(\n of(action).pipe(\n dispatch(this.lensState),\n\n // If another applyLens occurs while we're waiting, resolve this applyLens promise early – we're no\n // longer waiting for the requested lens to be applied.\n takeUntil(\n this.lensState.events.pipe(\n forActions(\"applyLens\"),\n filter(([a]) => a !== action)\n )\n ),\n\n // If lens application failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"applyLensFailed\") && a.data.lens.id === lens.id) throw a.data.error;\n }),\n\n inStates(\"lensApplied\"),\n\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early – i.e. the lens was not\n // applied (application was interrupted by a new call to `applyLens`), so we'll resolve with `false`.\n { defaultValue: false }\n );\n }\n\n /**\n * Remove a Lens from this session.\n *\n * When a Lens is removed, rendering continues if the session is playing. It will just render the session input\n * directly to the outputs without any image processing.\n *\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the session's rendered output has no lens applied.\n * 2. Resolved with `false`: the current lens has been removed, but a subsequent call to `applyLens` means that the\n * session's rendered output will still have a (new) lens applied.\n * 3. Rejected: the lens has failed to be removed. This can happen if an internal failure occurs in the Lens\n * rendering engine when attempting to remove the lens.\n */\n @log\n async removeLens(): Promise<boolean> {\n if (isState(this.lensState.getState(), \"noLensApplied\")) return true;\n return firstValueFrom(\n of(this.lensState.actions.removeLens()).pipe(\n dispatch(this.lensState),\n // If lens removal failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"removeLensFailed\")) throw a.data;\n }),\n inStates(\"noLensApplied\"),\n\n // If applyLens is called while we're waiting for removal, complete immediately – applying the next lens\n // will replace the current one.\n takeUntil(this.lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early (otherwise firstValueFrom will\n // return a rejected Promise).\n { defaultValue: false }\n );\n }\n\n /**\n * Start/resume session playback – LensCore will begin rendering frames to the output.\n *\n * If no source has been set for the session, calling `play()` will update the playing state, but no actual image\n * processing will occur until `setSource()` is called.\n *\n * @example\n * ```ts\n * const cameraKitSession = await cameraKit.createSession()\n * await cameraKitSession.setSource(mySource)\n * await cameraKitSession.play()\n *\n * // If you call `play` before `setSource`, the call to `play` will resolve but playback will only begin once a\n * // media source has been set.\n * ```\n *\n * @param target Specify the {@link RenderTarget} to render. Defaults to the `live` RenderTarget.\n * @returns Promise resolves when playback state has been updated. If no source has been set, this means `play` will\n * resolve before any frames are processed -- but once a source is set, frames will immediately begin processing.\n */\n @validate\n @log\n async play(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (this.playing) return;\n this.playing = target;\n\n const type = this.renderTargetToCanvasType(target);\n return this.lensCore.playCanvas({ type }).catch((error) => {\n this.playing = false;\n throw error;\n });\n }\n\n /**\n * Pause session playback – LensCore will stop rendering frames to the output.\n *\n * @param target Specify the RenderTarget to pause playback. May be either `'live'` or `'capture'`.\n * Default is `'live'`.\n * @returns Promise resolves when playback has stopped.\n */\n @validate\n @log\n async pause(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (!this.playing) return;\n const priorPlayingState = this.playing;\n this.playing = false;\n\n const type = this.renderTargetToCanvasType(target);\n return this.lensCore.pauseCanvas({ type }).catch((error) => {\n this.playing = priorPlayingState;\n throw error;\n });\n }\n\n /**\n * Mute all sounds (default SDK state is unmuted).\n *\n * @param fade Do we want audio to fade out?\n */\n @log\n mute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: true,\n fade,\n });\n }\n\n /**\n * Unmute all sounds.\n *\n * @param fade Do we want audio to fade in?\n */\n @log\n unmute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: false,\n fade,\n });\n }\n\n /**\n * Set the media source for this session.\n *\n * Sessions may only have one source at a time - if `setSource` is called multiple times, subsequent calls replace\n * the prior source. Setting the source does not trigger rendering (that’s done by `session.play()`). If the session\n * is already playing, setting the source will immediately begin rendering the new source.\n *\n * The CameraKit SDK provides implementations for various common sources, which applications can create using the\n * following functions:\n * - {@link createMediaStreamSource}\n * - {@link createVideoSource}\n * - {@link createImageSource}\n *\n * @param source A CameraKitSource object representing input media (e.g. a webcam stream, video, or some other\n * source of image data), which CameraKit will supply to Lenses in order for them to render effects on top of that\n * source.\n * @returns Promise is resolved when the source has successfully be set. If the session was already in the playing\n * state, the Promise resolves when the first frame from the new source has been rendered. The resolved value is\n * the {@link CameraKitSource} object attached to the session.\n */\n async setSource(source: CameraKitSource): Promise<CameraKitSource>;\n /** Deprecated: Support for CameraKitDeviceInfo will be removed in future releases.\n * Please use CameraKitDeviceOptions instead which accepts the \"environment\" and \"user\" cameraType\n * @deprecated\n */\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceInfo>\n ): Promise<CameraKitSource>;\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceOptions>\n ): Promise<CameraKitSource>;\n @validate\n @log\n async setSource(\n source: CameraKitSource | MediaStream | HTMLVideoElement,\n options: Partial<CameraKitDeviceInfo | CameraKitDeviceOptions> = {}\n ): Promise<CameraKitSource> {\n await this.safelyDetachSource();\n\n // For convenience, we allow callers to pass in native objects (e.g. MediaStream) as well as CameraKitSource.\n // Native objects are wrapped in corresponding CameraKitSource classes with default options.\n const cameraKitSource =\n source instanceof MediaStream\n ? createMediaStreamSource(source, options)\n : source instanceof HTMLVideoElement\n ? createVideoSource(source, options)\n : source;\n\n const priorPlayingState = this.playing;\n this.playing = false;\n\n // The source will provide its data to LensCore, and use other LensCore APIs (e.g. setRenderSize,\n // setInputTransform) to render the source correctly.\n await cameraKitSource.attach(this.lensCore, (error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source attachment.\", error));\n });\n\n // If attachment is successful, we'll update our source so that we can detach it later.\n this.source = cameraKitSource;\n\n // Finally we'll resume playback, if appropriate.\n if (priorPlayingState) {\n await this.play(priorPlayingState);\n }\n\n return cameraKitSource;\n }\n\n /**\n * Set an FPS limit.\n *\n * This may be useful to reduce CPU/GPU resource usage by CameraKit if, for example, the input\n * media source has a low FPS – CameraKit would then not try to render more frequently than the source produces\n * new frames.\n *\n * This may also be useful to gracefully degrade performance in situations where lowering FPS is preferable over\n * alternatives.\n *\n * @param fpsLimit A maximum FPS, rendering will not exceed this limit\n * @returns Promise is resolved when the limit is successfully set.\n */\n @log\n async setFPSLimit(fpsLimit: number): Promise<void> {\n // LensCore uses 0 to remove the limit.\n const fps = fpsLimit < Number.POSITIVE_INFINITY ? fpsLimit : 0;\n return this.lensCore.setFPSLimit({ fps });\n }\n\n /**\n * Destroy the session.\n *\n * The session will become inoperable. Frame processing stops, and any session-scoped graphical resources are freed.\n */\n @log\n async destroy(): Promise<void> {\n try {\n await this.lensCore.clearAllLenses();\n await this.lensCore.teardown();\n } catch (error) {\n // If a LensCore is in an aborted state, the above lines may throw an error.\n // In such cases, we should continue with the cleanup process.\n // We are also not interested in reporting these errors to our backend.\n logger.warn(\"An error occurred in LensCore during the session termination process.\", error);\n }\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n await this.safelyDetachSource();\n this.removePageVisibilityHandlers();\n this.sessionState.dispatch(\"destroy\", undefined);\n }\n\n private renderTargetToCanvasType(target: RenderTarget): CanvasType {\n return target === \"capture\" ? this.lensCore.CanvasType.Capture : this.lensCore.CanvasType.Preview;\n }\n\n private async safelyDetachSource(): Promise<void> {\n if (this.source) {\n try {\n await this.source.detach((error) => {\n logger.error(cameraKitSourceError(\"Error occurred during source detachment.\", error));\n });\n // If there's a failure to detach, we will report the error and proceed. Failure to detach may lead to a\n // memory leak, but it shouldn't prevent us from switching to the new source.\n } catch (error) {\n logger.error(\n cameraKitSourceError(`Detaching prior source of type ${getTypeName(this.source)} failed.`, error)\n );\n }\n }\n }\n}\n\n/**\n * @internal\n */\nexport const cameraKitSessionFactory = Injectable(\n \"CameraKitSession\",\n [\n lensCoreFactory.token,\n logEntriesFactory.token,\n lensKeyboardFactory.token,\n sessionStateFactory.token,\n lensStateFactory.token,\n pageVisibilityFactory.token,\n ] as const,\n (\n lensCore: LensCore,\n logEntries: Observable<LogEntry>,\n keyboard: LensKeyboard,\n sessionState: SessionState,\n lensState: LensState,\n pageVisibility: PageVisibility\n ) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries, pageVisibility)\n);\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CameraKitSourceError, LensExecutionError, LensImagePickerError } from "../namedErrors";
|
|
1
|
+
import { CameraKitSourceError, LensExecutionError, LensImagePickerError, LensAbortError } from "../namedErrors";
|
|
2
2
|
import { TypedCustomEvent } from "../events/TypedCustomEvent";
|
|
3
3
|
import { TypedEventListener } from "../events/TypedEventTarget";
|
|
4
4
|
import { Lens } from "../lens";
|
|
@@ -10,7 +10,7 @@ export declare function isSessionError(value: unknown): value is SessionErrors;
|
|
|
10
10
|
* Misc errors that occur during CameraKit session.
|
|
11
11
|
* @internal
|
|
12
12
|
*/
|
|
13
|
-
export type SessionErrors = LensExecutionError | LensImagePickerError | CameraKitSourceError;
|
|
13
|
+
export type SessionErrors = LensExecutionError | LensAbortError | LensImagePickerError | CameraKitSourceError;
|
|
14
14
|
/**
|
|
15
15
|
* Events emitted by {@link CameraKitSession.events | CameraKitSession.events}.
|
|
16
16
|
*
|
|
@@ -24,10 +24,14 @@ export type SessionErrors = LensExecutionError | LensImagePickerError | CameraKi
|
|
|
24
24
|
* @category Lenses
|
|
25
25
|
*/
|
|
26
26
|
export type CameraKitSessionEvents = TypedCustomEvent<"error", {
|
|
27
|
-
error: LensExecutionError | LensImagePickerError;
|
|
27
|
+
error: LensExecutionError | LensAbortError | LensImagePickerError;
|
|
28
28
|
lens: Lens;
|
|
29
29
|
}>;
|
|
30
30
|
/**
|
|
31
31
|
* Listener of {@link CameraKitSessionEvents} events.
|
|
32
32
|
*/
|
|
33
33
|
export type CameraKitSessionEventListener = TypedEventListener<CameraKitSessionEvents>;
|
|
34
|
+
/**
|
|
35
|
+
* Returns true if given value is of {@link SessionErrors} type, which is notified to client.
|
|
36
|
+
*/
|
|
37
|
+
export declare function isPublicLensError(value: unknown): value is CameraKitSessionEvents["detail"]["error"];
|
|
@@ -10,6 +10,7 @@ export function isSessionError(value) {
|
|
|
10
10
|
return false;
|
|
11
11
|
const maybeSessionErrorName = value.name;
|
|
12
12
|
switch (maybeSessionErrorName) {
|
|
13
|
+
case "LensAbortError":
|
|
13
14
|
case "CameraKitSourceError":
|
|
14
15
|
case "LensExecutionError":
|
|
15
16
|
case "LensImagePickerError":
|
|
@@ -18,4 +19,20 @@ export function isSessionError(value) {
|
|
|
18
19
|
return isReachable(maybeSessionErrorName);
|
|
19
20
|
}
|
|
20
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Returns true if given value is of {@link SessionErrors} type, which is notified to client.
|
|
24
|
+
*/
|
|
25
|
+
export function isPublicLensError(value) {
|
|
26
|
+
if (!(value instanceof Error))
|
|
27
|
+
return false;
|
|
28
|
+
const maybeSessionErrorName = value.name;
|
|
29
|
+
switch (maybeSessionErrorName) {
|
|
30
|
+
case "LensAbortError":
|
|
31
|
+
case "LensExecutionError":
|
|
32
|
+
case "LensImagePickerError":
|
|
33
|
+
return true;
|
|
34
|
+
default:
|
|
35
|
+
return isReachable(maybeSessionErrorName);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
21
38
|
//# sourceMappingURL=CameraKitSessionEvents.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CameraKitSessionEvents.js","sourceRoot":"","sources":["../../src/session/CameraKitSessionEvents.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,MAAM,WAAW,GAAG,CAAC,CAAQ,EAAE,EAAE,CAAC,KAAK,CAAC;AAExC;;GAEG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IACzC,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,qBAAqB,GAAI,KAAuB,CAAC,IAAI,CAAC;IAC5D,QAAQ,qBAAqB,EAAE;QAC3B,KAAK,sBAAsB,CAAC;QAC5B,KAAK,oBAAoB,CAAC;QAC1B,KAAK,sBAAsB;YACvB,OAAO,IAAI,CAAC;QAChB;YACI,OAAO,WAAW,CAAC,qBAAqB,CAAC,CAAC;KACjD;AACL,CAAC","sourcesContent":["import { CameraKitSourceError, LensExecutionError, LensImagePickerError } from \"../namedErrors\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { TypedEventListener } from \"../events/TypedEventTarget\";\nimport { Lens } from \"../lens\";\n\n/**\n * A type guard helper to detect unreachable code.\n */\nconst isReachable = (_: never) => false;\n\n/**\n * Returns true if given value is of {@link SessionErrors} type and false otherwise.\n */\nexport function isSessionError(value: unknown): value is SessionErrors {\n if (!(value instanceof Error)) return false;\n\n const maybeSessionErrorName = (value as SessionErrors).name;\n switch (maybeSessionErrorName) {\n case \"CameraKitSourceError\":\n case \"LensExecutionError\":\n case \"LensImagePickerError\":\n return true;\n default:\n return isReachable(maybeSessionErrorName);\n }\n}\n\n/**\n * Misc errors that occur during CameraKit session.\n * @internal\n */\nexport type SessionErrors = LensExecutionError | LensImagePickerError | CameraKitSourceError;\n\n/**\n * Events emitted by {@link CameraKitSession.events | CameraKitSession.events}.\n *\n * The following events are emitted:\n * - `error`: An error has been encountered during lens rendering. May contain an error of type:\n * - {@link LensExecutionError} If an error of this type occurs, the rendering lens will be automatically removed\n * from the associated CameraKitSession.\n * - {@link LensImagePickerError}\n *\n * @category Rendering\n * @category Lenses\n */\nexport type CameraKitSessionEvents = TypedCustomEvent<\n \"error\",\n { error: LensExecutionError | LensImagePickerError; lens: Lens }\n>;\n\n/**\n * Listener of {@link CameraKitSessionEvents} events.\n */\nexport type CameraKitSessionEventListener = TypedEventListener<CameraKitSessionEvents>;\n"]}
|
|
1
|
+
{"version":3,"file":"CameraKitSessionEvents.js","sourceRoot":"","sources":["../../src/session/CameraKitSessionEvents.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,MAAM,WAAW,GAAG,CAAC,CAAQ,EAAE,EAAE,CAAC,KAAK,CAAC;AAExC;;GAEG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IACzC,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,qBAAqB,GAAI,KAAuB,CAAC,IAAI,CAAC;IAC5D,QAAQ,qBAAqB,EAAE;QAC3B,KAAK,gBAAgB,CAAC;QACtB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,oBAAoB,CAAC;QAC1B,KAAK,sBAAsB;YACvB,OAAO,IAAI,CAAC;QAChB;YACI,OAAO,WAAW,CAAC,qBAAqB,CAAC,CAAC;KACjD;AACL,CAAC;AA8BD;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC5C,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,qBAAqB,GAAI,KAAmD,CAAC,IAAI,CAAC;IACxF,QAAQ,qBAAqB,EAAE;QAC3B,KAAK,gBAAgB,CAAC;QACtB,KAAK,oBAAoB,CAAC;QAC1B,KAAK,sBAAsB;YACvB,OAAO,IAAI,CAAC;QAChB;YACI,OAAO,WAAW,CAAC,qBAAqB,CAAC,CAAC;KACjD;AACL,CAAC","sourcesContent":["import { CameraKitSourceError, LensExecutionError, LensImagePickerError, LensAbortError } from \"../namedErrors\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { TypedEventListener } from \"../events/TypedEventTarget\";\nimport { Lens } from \"../lens\";\n\n/**\n * A type guard helper to detect unreachable code.\n */\nconst isReachable = (_: never) => false;\n\n/**\n * Returns true if given value is of {@link SessionErrors} type and false otherwise.\n */\nexport function isSessionError(value: unknown): value is SessionErrors {\n if (!(value instanceof Error)) return false;\n\n const maybeSessionErrorName = (value as SessionErrors).name;\n switch (maybeSessionErrorName) {\n case \"LensAbortError\":\n case \"CameraKitSourceError\":\n case \"LensExecutionError\":\n case \"LensImagePickerError\":\n return true;\n default:\n return isReachable(maybeSessionErrorName);\n }\n}\n\n/**\n * Misc errors that occur during CameraKit session.\n * @internal\n */\nexport type SessionErrors = LensExecutionError | LensAbortError | LensImagePickerError | CameraKitSourceError;\n\n/**\n * Events emitted by {@link CameraKitSession.events | CameraKitSession.events}.\n *\n * The following events are emitted:\n * - `error`: An error has been encountered during lens rendering. May contain an error of type:\n * - {@link LensExecutionError} If an error of this type occurs, the rendering lens will be automatically removed\n * from the associated CameraKitSession.\n * - {@link LensImagePickerError}\n *\n * @category Rendering\n * @category Lenses\n */\nexport type CameraKitSessionEvents = TypedCustomEvent<\n \"error\",\n { error: LensExecutionError | LensAbortError | LensImagePickerError; lens: Lens }\n>;\n\n/**\n * Listener of {@link CameraKitSessionEvents} events.\n */\nexport type CameraKitSessionEventListener = TypedEventListener<CameraKitSessionEvents>;\n\n/**\n * Returns true if given value is of {@link SessionErrors} type, which is notified to client.\n */\nexport function isPublicLensError(value: unknown): value is CameraKitSessionEvents[\"detail\"][\"error\"] {\n if (!(value instanceof Error)) return false;\n\n const maybeSessionErrorName = (value as CameraKitSessionEvents[\"detail\"][\"error\"]).name;\n switch (maybeSessionErrorName) {\n case \"LensAbortError\":\n case \"LensExecutionError\":\n case \"LensImagePickerError\":\n return true;\n default:\n return isReachable(maybeSessionErrorName);\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { LensCore } from "../lens-core-module";
|
|
2
2
|
import { LensPerformanceMeasurement } from "./LensPerformanceMeasurement";
|
|
3
3
|
/**
|
|
4
4
|
* Use to measure lens rendering performance.
|
|
@@ -20,7 +20,7 @@ export declare class LensPerformanceMetrics {
|
|
|
20
20
|
private lensCore;
|
|
21
21
|
private readonly measurementInstances;
|
|
22
22
|
/** @internal */
|
|
23
|
-
constructor(lensCore:
|
|
23
|
+
constructor(lensCore: LensCore);
|
|
24
24
|
/**
|
|
25
25
|
* Begin a measurement window, during which time rendering metrics will be gathered.
|
|
26
26
|
*
|
|
@@ -25,7 +25,8 @@ export class LensPerformanceMetrics {
|
|
|
25
25
|
constructor(lensCore) {
|
|
26
26
|
this.lensCore = lensCore;
|
|
27
27
|
this.measurementInstances = new Set();
|
|
28
|
-
this.lensCore
|
|
28
|
+
this.lensCore
|
|
29
|
+
.setOnFrameProcessedCallback({
|
|
29
30
|
onFrameProcessed: ({ processingTimeMs }) => {
|
|
30
31
|
try {
|
|
31
32
|
for (const measurement of this.measurementInstances.values()) {
|
|
@@ -36,8 +37,8 @@ export class LensPerformanceMetrics {
|
|
|
36
37
|
logger.error(error);
|
|
37
38
|
}
|
|
38
39
|
},
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
})
|
|
41
|
+
.catch((error) => logger.error(`Failed registering setOnFrameProcessedCallback with error: ${error.message}`));
|
|
41
42
|
}
|
|
42
43
|
/**
|
|
43
44
|
* Begin a measurement window, during which time rendering metrics will be gathered.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LensPerformanceMetrics.js","sourceRoot":"","sources":["../../src/session/LensPerformanceMetrics.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E,MAAM,MAAM,GAAG,SAAS,CAAC,kBAAkB,CAAC,CAAC;AAC7C,MAAM,GAAG,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;AAE1C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,sBAAsB;IAG/B,gBAAgB;IAChB,YAAoB,
|
|
1
|
+
{"version":3,"file":"LensPerformanceMetrics.js","sourceRoot":"","sources":["../../src/session/LensPerformanceMetrics.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E,MAAM,MAAM,GAAG,SAAS,CAAC,kBAAkB,CAAC,CAAC;AAC7C,MAAM,GAAG,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;AAE1C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,sBAAsB;IAG/B,gBAAgB;IAChB,YAAoB,QAAkB;QAAlB,aAAQ,GAAR,QAAQ,CAAU;QAClC,IAAI,CAAC,oBAAoB,GAAG,IAAI,GAAG,EAAE,CAAC;QACtC,IAAI,CAAC,QAAQ;aACR,2BAA2B,CAAC;YACzB,gBAAgB,EAAE,CAAC,EAAE,gBAAgB,EAAE,EAAE,EAAE;gBACvC,IAAI;oBACA,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,EAAE,EAAE;wBAC1D,WAAW,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;qBACxC;iBACJ;gBAAC,OAAO,KAAK,EAAE;oBACZ,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;iBACvB;YACL,CAAC;SACJ,CAAC;aACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CACb,MAAM,CAAC,KAAK,CAAC,8DAA8D,KAAK,CAAC,OAAO,EAAE,CAAC,CAC9F,CAAC;IACV,CAAC;IAED;;;;;OAKG;IAEH,gBAAgB;QACZ,OAAO,IAAI,0BAA0B,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACrE,CAAC;CACJ;AAHG;IADC,GAAG;;;oCACgB,0BAA0B;8DAE7C","sourcesContent":["import { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { LensCore } from \"../lens-core-module\";\nimport { getLogger } from \"../logger/logger\";\nimport { LensPerformanceMeasurement } from \"./LensPerformanceMeasurement\";\n\nconst logger = getLogger(\"RenderingMetrics\");\nconst log = errorLoggingDecorator(logger);\n\n/**\n * Use to measure lens rendering performance.\n *\n * The {@link LensPerformanceMetrics.beginMeasurement} method is used to start measuring rendering performance. After\n * a measurement has begun, performance metrics can be read using {@link LensPerformanceMeasurement}.\n *\n * @example\n * ```ts\n * const measurement = cameraKitSession.metrics.beginMeasurement()\n * // some time later\n * console.log(measurement.measure())\n * ```\n *\n * @category Rendering\n * @category Metrics\n */\nexport class LensPerformanceMetrics {\n private readonly measurementInstances: Set<LensPerformanceMeasurement>;\n\n /** @internal */\n constructor(private lensCore: LensCore) {\n this.measurementInstances = new Set();\n this.lensCore\n .setOnFrameProcessedCallback({\n onFrameProcessed: ({ processingTimeMs }) => {\n try {\n for (const measurement of this.measurementInstances.values()) {\n measurement.update(processingTimeMs);\n }\n } catch (error) {\n logger.error(error);\n }\n },\n })\n .catch((error) =>\n logger.error(`Failed registering setOnFrameProcessedCallback with error: ${error.message}`)\n );\n }\n\n /**\n * Begin a measurement window, during which time rendering metrics will be gathered.\n *\n * @returns A {@link LensPerformanceMeasurement} representing an ongoing measurement of aggregated rendering\n * metrics, from which specific metrics can be obtained.\n */\n @log\n beginMeasurement(): LensPerformanceMeasurement {\n return new LensPerformanceMeasurement(this.measurementInstances);\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { StateMachine } from "@snap/state-management";
|
|
2
2
|
import { Lens } from "../lens/Lens";
|
|
3
3
|
import { LensRepository } from "../lens/LensRepository";
|
|
4
|
-
import {
|
|
4
|
+
import { LensCore } from "../lens-core-module";
|
|
5
5
|
import { IndexedDBPersistence } from "../persistence/IndexedDBPersistence";
|
|
6
6
|
import { LensLaunchParams } from "../lens/LensLaunchParams";
|
|
7
7
|
import { LensAssetRepository } from "../lens/assets/LensAssetRepository";
|
|
@@ -17,7 +17,7 @@ declare const createLensState: () => StateMachine<import("@snap/state-management
|
|
|
17
17
|
export type LensErrors = LegalError | LensContentValidationError | LensError;
|
|
18
18
|
export type LensState = ReturnType<typeof createLensState>;
|
|
19
19
|
export declare const lensStateFactory: {
|
|
20
|
-
(args_0:
|
|
20
|
+
(args_0: LensCore, args_1: LensRepository, args_2: LensAssetRepository, args_3: IndexedDBPersistence<ArrayBuffer>, args_4: StateMachine<import("@snap/state-management").Action<"requestLegalPrompt", undefined> | import("@snap/state-management").Action<"accept", string> | import("@snap/state-management").Action<"reject", string>, import("@snap/state-management").State<"unknown", undefined> | import("@snap/state-management").State<"accepted", undefined> | import("@snap/state-management").State<"rejected", undefined>>, args_5: OperationalMetricsReporter): StateMachine<import("@snap/state-management").Action<"applyLens", {
|
|
21
21
|
lens: Lens;
|
|
22
22
|
launchParams?: LensLaunchParams | undefined;
|
|
23
23
|
}> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
|