@snap/camera-kit
Version:
Camera Kit Web
282 lines • 11.3 kB
TypeScript
import type { EstimatedLensPerformance } from "./benchmark/estimateLensPerformanceCluster";
import type { Lens } from "./lens/Lens";
import { type Logger, type LogLevel } from "./logger/logger";
interface CameraKitRuntimeConfiguration {
lensPerformance: EstimatedLensPerformance | Promise<EstimatedLensPerformance>;
logger: Logger;
logLevel: LogLevel;
shouldUseWorker: boolean;
apiHostname: CameraKitApiHostname;
userAgentFlavor: "release" | "debug";
fonts: FontConfig[];
lensHttpHandler?: LensHttpHandler;
lensHttpValidationStrategy: ValidationStrategy;
trustedTypesPolicyName: string;
}
export type CameraKitApiHostname = "camera-kit-api.snapar.com" | "api-kit.snapchat.com";
/**
* Defines how Camera Kit handles lens HTTP requests against Remote API specs in the My Lenses portal.
*
* - `"deny"`: Rejects all lens HTTP requests.
* - `"strict"`: Full validation: host + path + method + path parameters + query parameters + headers. Default.
* - `"route"`: Validates host + path + method + path parameters (skips query parameters and headers).
* - `"host"`: Validates host only.
* - `"unrestricted"`: No validation.
*
* @remarks
* Use `"unrestricted"` only if you fully trust your lens developers. Lenses will be able to make
* HTTP requests to any endpoint without validation against the allowlist.
*/
export type ValidationStrategy = "deny" | "strict" | "route" | "host" | "unrestricted";
/**
* Represents a font to be used by Camera Kit for text rendering.
*/
export interface Font {
/**
* A unique name for the font.
*/
name: string;
/**
* A buffer containing the font data (e.g., the contents of a `.ttf` file).
*/
data: ArrayBuffer;
}
/**
* A font configuration entry: either a {@link Font} with custom font data, or `"default"` to reference the
* built-in font bundled with Camera Kit.
*/
export type FontConfig = Font | "default";
/**
* Represents context for an HTTP request made by a Lens.
*
* This interface provides detailed information about the request, such as its identifier,
* method, data payload, headers, and associated Lens object.
*/
export interface LensHttpRequest {
/**
* The URL of the HTTP request.
*/
url: string;
/**
* A unique identifier for the HTTP request.
*/
identifier: string;
/**
* The HTTP method of the request (e.g., GET, POST, PUT, DELETE).
*/
method: string;
/**
* The raw data payload for the HTTP request, represented as an `ArrayBuffer`.
*/
data: ArrayBuffer;
/**
* The headers included in the HTTP request.
*/
headers: Record<string, string>;
/**
* The {@link Lens} that initiated this request.
*/
lens: Lens;
}
/**
* A handler function for customizing HTTP requests made by a Lens.
*
* This function is called whenever a Lens makes an HTTP request.
* It allows you to modify the request or response, integrate custom HTTP libraries,
* add authentication, or log request details.
*
* @param url - The URL for the HTTP request.
* @param init - The initial configuration for the HTTP request, following the Fetch API's `RequestInit`.
* @param lensRequest - Additional context about the Lens-specific request.
* @returns A Promise resolving to the HTTP response (`Response`).
*/
export type LensHttpHandler = (url: string, init: RequestInit, lensRequest: LensHttpRequest) => Promise<Response>;
/**
* Configuration which must be provided when calling {@link bootstrapCameraKit}. These values are used to create various
* CameraKit components.
*
* @category Bootstrapping and Configuration
*/
export interface CameraKitBootstrapConfiguration {
/**
* Long-lived token granting your application access to CameraKit APIs. This is found in the SnapKit Dev Portal,
* where it's called the API Token.
*/
apiToken: string;
/**
* Determine where to print CameraKit log messages. By default no logs will be printed.
*
* CameraKit emits log messages to help diagnose and root cause issues that may occur during the development of a
* host application. The printing of these can be controlled via the following options:
* - `"noop"`: log messages are ignored.
* - `"console"`: log messages are printed to console.
* - A custom {@link Logger} instance can be provided to integrate with an existing logging system.
*/
logger?: "noop" | "console" | Logger;
/**
* Log only if a logged entry level is greater than or equal to this level. Here is the order of levels:
* error > warn > log = info > debug. Default value is "info".
*/
logLevel?: LogLevel;
/**
* Some lenses may decide to modify their behavior based on the performance of the current environment. If you are
* using such lenses, providing an estimation of lens performance may lead to better user experience (especially on
* low-performance devices).
*
* Running the {@link estimateLensPerformance} function will run benchmarks and estimate an appropriate lens
* performance cluster (i.e. a performance rating) based on the current environment.
*
* Lower cluster = worse expected performance capability.
*
* @example
* ```ts
* import { bootstrapCameraKit, estimateLensPerformance } from '@snap/camera-kit`
*
* const cameraKit = await bootstrapCameraKit({
* apiToken: '...',
* lensPerformance: estimateLensPerformance(),
* })
* ```
*/
lensPerformance?: EstimatedLensPerformance | Promise<EstimatedLensPerformance>;
/**
* In recommended production deployments, the WebAssembly assets required by CameraKit will be downloaded from an
* optimized CDN. But sometimes (e.g. during development or within a CI pipeline), it may be necessary to download
* these assets from somewhere else.
*
* This configuration option allows the application to specify URLs to be used for both the WebAssembly and JS glue
* file that are used to run and interact with CameraKit's rendering engine.
*/
lensCoreOverrideUrls?: {
wasm: string;
js: string;
};
/**
* In recommended production deployments, the WebAssembly assets required by CameraKit will be downloaded from an
* optimized CDN. But sometimes during development or within a CI pipeline, it may be necessary to download these
* assets from somewhere else. With a provided `wasmEndpointOverride`, asset URLs will be automatically generated
* based on this root endpoint.
*/
wasmEndpointOverride?: string;
/**
* Applications may optionally provide a unique identifier called analyticsId. This ID would enable Camera Kit to
* improve data reporting and accuracy and to better support potential needs related to an application's lens and
* user analytics.
*/
analyticsId?: string;
/**
* An array of fonts to be used by Camera Kit for text rendering.
*
* Lenses usually have their own font assets, but emojis are often not embedded.
* As a result, you may need to provide additional fonts (e.g., an emoji font) to ensure all glyphs render
* correctly.
*
* When rendering text, Camera Kit tries each font in array order until it finds the needed glyph.
* The built-in font is always available — even with an empty array or no `"default"` entry, it is
* checked after all provided fonts. Use `"default"` to control its position in the lookup order.
*
* @example
* // The built-in font will be checked before `fallbackFont`, but after `emojiFont`.
* fonts: [
* { name: 'EmojiFont', data: emojiFontArrayBuffer },
* "default",
* { name: 'FallbackFont', data: fallbackFontArrayBuffer },
* ]
*/
fonts?: FontConfig[];
/**
* An optional custom HTTP handler for requests made by a Lens.
*
* This handler allows you to intercept and customize the behavior of HTTP requests,
* such as adding authentication headers, logging request details, or replacing the default
* HTTP library used by the Lens system.
*
* If not specified, the Lens system will use a default HTTP implementation.
*
* @example
* ```typescript
* const customLensHttpHandler: LensHttpHandler = async (url, init, lensRequest) => {
* // Add an authentication token to the headers
* const sessionToken = await getAuthToken();
* const updatedInit = {
* ...init,
* headers: {
* ...init.headers,
* 'Authorization': `Bearer ${sessionToken}`,
* },
* };
*
* // Log the request details for debugging
* console.log(`Requesting ${lensRequest.url} from lens: ${lensRequest.lens.name}`);
*
* // Use fetch to perform the HTTP request
* return fetch(url, updatedInit);
* };
*
* const cameraKit = bootstrapCameraKit({
* apiToken,
* lensHttpHandler: customLensHttpHandler,
* });
* ```
*/
lensHttpHandler?: LensHttpHandler;
/**
* Configures how Camera Kit validates lens HTTP requests against Remote API specs.
*
* Available strategies:
* - `"deny"`: Rejects all lens HTTP requests.
* - `"strict"` (default): Full validation of host, path, method, and parameters.
* - `"route"`: Validates host, path (including path parameters), and method.
* Skips validation of query parameters and headers.
* - `"host"`: Only validates the host.
* - `"unrestricted"`: No validation.
*
* @remarks
* Use `"unrestricted"` only if you fully trust your lens developers, as lenses will be able to make
* HTTP requests to any endpoint without validation.
*
* @example
* ```typescript
* const cameraKit = bootstrapCameraKit({
* apiToken,
* lensHttpValidationStrategy: "host",
* });
* ```
*
* @example
* Combine with custom handler:
* ```typescript
* const cameraKit = bootstrapCameraKit({
* apiToken,
* lensHttpValidationStrategy: "unrestricted",
* lensHttpHandler: async (url, init, lensRequest) => {
* // Custom logic here
* return fetch(url, init);
* },
* });
* ```
*/
lensHttpValidationStrategy?: ValidationStrategy;
/**
* The name of the Trusted Types policy to use when loading scripts.
* Defaults to "snap-camera-kit".
*/
trustedTypesPolicyName?: string;
}
/**
* This type represents the result of merging user-supplied config with default config -- as such, it has no nullable
* fields, making it a more convenient type for other components to use.
*
* @internal
*/
export type CameraKitConfiguration = CameraKitRuntimeConfiguration & CameraKitBootstrapConfiguration;
/** @internal */
export declare const configurationToken = "configuration";
/** @internal */
export declare const createCameraKitConfigurationFactory: (configuration: CameraKitBootstrapConfiguration) => {
(): CameraKitConfiguration;
token: "configuration";
dependencies: [];
};
export {};
//# sourceMappingURL=configuration.d.ts.map