type Primitive = number | string | boolean | bigint | symbol | null | undefined; type Tags = Record; type Context = Record; type Contexts = Record; interface SpanContextData { traceId: string; spanId: string; } interface Span { spanContext(): SpanContextData; end(): void; } interface SpanOptions { name: string; tags?: Tags; } interface Breadcrumb { type?: string; category?: string; message: string; level?: 'info' | 'warning' | 'error'; data?: Record; } interface CaptureContext { level?: 'info' | 'warning' | 'error'; tags?: Tags; contexts?: Contexts; } interface MonitoringClient { /** * Captures an exception event and sends it to Sentry. * @param error The error to capture * @param captureContext Optional additional data to attach to the Sentry e vent. * @returns the id of the captured Sentry event. */ captureException(error: unknown, captureContext?: CaptureContext): string; /** * Captures a message event and sends it to Sentry. * @param message The message to capture * @param captureContext Define the level of the message or pass in additional data to attach to the message. * @returns the id of the captured message. */ captureMessage(message: string, captureContext?: CaptureContext): string; /** * Wraps a function with a span and finishes the span after the function is done. The created span is the active span and will be used as parent by other spans created inside the function, as long as the function is executed while the scope is active. * @param spanOptions The options for the span * @param callback The function to wrap with a span * @returns The return value of the callback */ startSpan(spanOptions: SpanOptions, callback: (span: Span | undefined) => T): T; /** * Records a new breadcrumb which will be attached to future events. * Breadcrumbs will be added to subsequent events to provide more context on user's actions prior to an error or crash. * @param breadcrumb The breadcrumb to record. */ addBreadcrumb(breadcrumb: Breadcrumb): void; } type HostModule = { __type: 'host'; create(host: H): T; }; type HostModuleAPI> = T extends HostModule ? U : never; type Host$1 = { channel?: { observeState(callback: (props: unknown, environment: Environment) => unknown): { disconnect: () => void; } | Promise<{ disconnect: () => void; }>; }; environment?: Environment; /** * Optional name of the environment, use for logging */ name?: string; /** * Optional bast url to use for API requests, for example `www.wixapis.com` */ apiBaseUrl?: string; /** * Optional function to get a monitoring client */ getMonitoringClient?: () => MonitoringClient; /** * Possible data to be provided by every host, for cross cutting concerns * like internationalization, billing, etc. */ essentials?: { /** * The language of the currently viewed session */ language?: string; /** * The locale of the currently viewed session */ locale?: string; /** * Any headers that should be passed through to the API requests */ passThroughHeaders?: Record; }; }; type HTTPMethod = 'POST' | 'GET' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'; type RESTFunctionDescriptor any = (...args: any[]) => any> = (httpClient: HttpClient) => T; interface HttpClient { request(req: RequestOptionsFactory): Promise>; fetchWithAuth: typeof fetch; wixAPIFetch: (relativeUrl: string, options: RequestInit) => Promise; getActiveToken?: () => string | undefined; } type RequestOptionsFactory = (context: any) => RequestOptions; type HttpResponse = { data: T; status: number; statusText: string; headers: any; request?: any; }; type RequestOptions<_TResponse = any, Data = any> = { method: HTTPMethod; url: string; data?: Data; params?: URLSearchParams; } & APIMetadata; type APIMetadata = { methodFqn?: string; entityFqdn?: string; packageName?: string; }; type BuildRESTFunction = T extends RESTFunctionDescriptor ? U : never; type EventDefinition = { __type: 'event-definition'; type: Type; isDomainEvent?: boolean; transformations?: (envelope: unknown) => Payload; __payload: Payload; }; declare function EventDefinition(type: Type, isDomainEvent?: boolean, transformations?: (envelope: any) => unknown): () => EventDefinition; type EventHandler = (payload: T['__payload']) => void | Promise; type BuildEventDefinition> = (handler: EventHandler) => void; type ServicePluginMethodInput = { request: any; metadata: any; }; type ServicePluginContract = Record unknown | Promise>; type ServicePluginMethodMetadata = { name: string; primaryHttpMappingPath: string; transformations: { fromREST: (...args: unknown[]) => ServicePluginMethodInput; toREST: (...args: unknown[]) => unknown; }; }; type ServicePluginDefinition = { __type: 'service-plugin-definition'; componentType: string; methods: ServicePluginMethodMetadata[]; __contract: Contract; }; declare function ServicePluginDefinition(componentType: string, methods: ServicePluginMethodMetadata[]): ServicePluginDefinition; type BuildServicePluginDefinition> = (implementation: T['__contract']) => void; declare const SERVICE_PLUGIN_ERROR_TYPE = "wix_spi_error"; type RequestContext = { isSSR: boolean; host: string; protocol?: string; }; type ResponseTransformer = (data: any, headers?: any) => any; /** * Ambassador request options types are copied mostly from AxiosRequestConfig. * They are copied and not imported to reduce the amount of dependencies (to reduce install time). * https://github.com/axios/axios/blob/3f53eb6960f05a1f88409c4b731a40de595cb825/index.d.ts#L307-L315 */ type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK'; type AmbassadorRequestOptions = { _?: T; url?: string; method?: Method; params?: any; data?: any; transformResponse?: ResponseTransformer | ResponseTransformer[]; }; type AmbassadorFactory = (payload: Request) => ((context: RequestContext) => AmbassadorRequestOptions) & { __isAmbassador: boolean; }; type AmbassadorFunctionDescriptor = AmbassadorFactory; type BuildAmbassadorFunction = T extends AmbassadorFunctionDescriptor ? (req: Request) => Promise : never; declare global { // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged. interface SymbolConstructor { readonly observable: symbol; } } declare const emptyObjectSymbol: unique symbol; /** Represents a strictly empty plain object, the `{}` value. When you annotate something as the type `{}`, it can be anything except `null` and `undefined`. This means that you cannot use `{}` to represent an empty plain object ([read more](https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference/52193484#52193484)). @example ``` import type {EmptyObject} from 'type-fest'; // The following illustrates the problem with `{}`. const foo1: {} = {}; // Pass const foo2: {} = []; // Pass const foo3: {} = 42; // Pass const foo4: {} = {a: 1}; // Pass // With `EmptyObject` only the first case is valid. const bar1: EmptyObject = {}; // Pass const bar2: EmptyObject = 42; // Fail const bar3: EmptyObject = []; // Fail const bar4: EmptyObject = {a: 1}; // Fail ``` Unfortunately, `Record`, `Record` and `Record` do not work. See {@link https://github.com/sindresorhus/type-fest/issues/395 #395}. @category Object */ type EmptyObject = {[emptyObjectSymbol]?: never}; /** Returns a boolean for whether the two given types are equal. @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650 @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796 Use-cases: - If you want to make a conditional branch based on the result of a comparison of two types. @example ``` import type {IsEqual} from 'type-fest'; // This type returns a boolean for whether the given array includes the given item. // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal. type Includes = Value extends readonly [Value[0], ...infer rest] ? IsEqual extends true ? true : Includes : false; ``` @category Type Guard @category Utilities */ type IsEqual = (() => G extends A & G | G ? 1 : 2) extends (() => G extends B & G | G ? 1 : 2) ? true : false; /** Filter out keys from an object. Returns `never` if `Exclude` is strictly equal to `Key`. Returns `never` if `Key` extends `Exclude`. Returns `Key` otherwise. @example ``` type Filtered = Filter<'foo', 'foo'>; //=> never ``` @example ``` type Filtered = Filter<'bar', string>; //=> never ``` @example ``` type Filtered = Filter<'bar', 'foo'>; //=> 'bar' ``` @see {Except} */ type Filter = IsEqual extends true ? never : (KeyType extends ExcludeType ? never : KeyType); type ExceptOptions = { /** Disallow assigning non-specified properties. Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`. @default false */ requireExactProps?: boolean; }; /** Create a type from an object type without certain keys. We recommend setting the `requireExactProps` option to `true`. This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically. This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)). @example ``` import type {Except} from 'type-fest'; type Foo = { a: number; b: string; }; type FooWithoutA = Except; //=> {b: string} const fooWithoutA: FooWithoutA = {a: 1, b: '2'}; //=> errors: 'a' does not exist in type '{ b: string; }' type FooWithoutB = Except; //=> {a: number} & Partial> const fooWithoutB: FooWithoutB = {a: 1, b: '2'}; //=> errors at 'b': Type 'string' is not assignable to type 'undefined'. // The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures. // Consider the following example: type UserData = { [metadata: string]: string; email: string; name: string; role: 'admin' | 'user'; }; // `Omit` clearly doesn't behave as expected in this case: type PostPayload = Omit; //=> type PostPayload = { [x: string]: string; [x: number]: string; } // In situations like this, `Except` works better. // It simply removes the `email` key while preserving all the other keys. type PostPayload = Except; //=> type PostPayload = { [x: string]: string; name: string; role: 'admin' | 'user'; } ``` @category Object */ type Except = { [KeyType in keyof ObjectType as Filter]: ObjectType[KeyType]; } & (Options['requireExactProps'] extends true ? Partial> : {}); /** Returns a boolean for whether the given type is `never`. @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919 @link https://stackoverflow.com/a/53984913/10292952 @link https://www.zhenghao.io/posts/ts-never Useful in type utilities, such as checking if something does not occur. @example ``` import type {IsNever, And} from 'type-fest'; // https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts type AreStringsEqual = And< IsNever> extends true ? true : false, IsNever> extends true ? true : false >; type EndIfEqual = AreStringsEqual extends true ? never : void; function endIfEqual(input: I, output: O): EndIfEqual { if (input === output) { process.exit(0); } } endIfEqual('abc', 'abc'); //=> never endIfEqual('abc', '123'); //=> void ``` @category Type Guard @category Utilities */ type IsNever = [T] extends [never] ? true : false; /** An if-else-like type that resolves depending on whether the given type is `never`. @see {@link IsNever} @example ``` import type {IfNever} from 'type-fest'; type ShouldBeTrue = IfNever; //=> true type ShouldBeBar = IfNever<'not never', 'foo', 'bar'>; //=> 'bar' ``` @category Type Guard @category Utilities */ type IfNever = ( IsNever extends true ? TypeIfNever : TypeIfNotNever ); /** Extract the keys from a type where the value type of the key extends the given `Condition`. Internally this is used for the `ConditionalPick` and `ConditionalExcept` types. @example ``` import type {ConditionalKeys} from 'type-fest'; interface Example { a: string; b: string | number; c?: string; d: {}; } type StringKeysOnly = ConditionalKeys; //=> 'a' ``` To support partial types, make sure your `Condition` is a union of undefined (for example, `string | undefined`) as demonstrated below. @example ``` import type {ConditionalKeys} from 'type-fest'; type StringKeysAndUndefined = ConditionalKeys; //=> 'a' | 'c' ``` @category Object */ type ConditionalKeys = { // Map through all the keys of the given base type. [Key in keyof Base]-?: // Pick only keys with types extending the given `Condition` type. Base[Key] extends Condition // Retain this key // If the value for the key extends never, only include it if `Condition` also extends never ? IfNever, Key> // Discard this key since the condition fails. : never; // Convert the produced object into a union type of the keys which passed the conditional test. }[keyof Base]; /** Exclude keys from a shape that matches the given `Condition`. This is useful when you want to create a new type with a specific set of keys from a shape. For example, you might want to exclude all the primitive properties from a class and form a new shape containing everything but the primitive properties. @example ``` import type {Primitive, ConditionalExcept} from 'type-fest'; class Awesome { name: string; successes: number; failures: bigint; run() {} } type ExceptPrimitivesFromAwesome = ConditionalExcept; //=> {run: () => void} ``` @example ``` import type {ConditionalExcept} from 'type-fest'; interface Example { a: string; b: string | number; c: () => void; d: {}; } type NonStringKeysOnly = ConditionalExcept; //=> {b: string | number; c: () => void; d: {}} ``` @category Object */ type ConditionalExcept = Except< Base, ConditionalKeys >; /** * Descriptors are objects that describe the API of a module, and the module * can either be a REST module or a host module. * This type is recursive, so it can describe nested modules. */ type Descriptors = RESTFunctionDescriptor | AmbassadorFunctionDescriptor | HostModule | EventDefinition | ServicePluginDefinition | { [key: string]: Descriptors | PublicMetadata | any; }; /** * This type takes in a descriptors object of a certain Host (including an `unknown` host) * and returns an object with the same structure, but with all descriptors replaced with their API. * Any non-descriptor properties are removed from the returned object, including descriptors that * do not match the given host (as they will not work with the given host). */ type BuildDescriptors | undefined, Depth extends number = 5> = { done: T; recurse: T extends { __type: typeof SERVICE_PLUGIN_ERROR_TYPE; } ? never : T extends AmbassadorFunctionDescriptor ? BuildAmbassadorFunction : T extends RESTFunctionDescriptor ? BuildRESTFunction : T extends EventDefinition ? BuildEventDefinition : T extends ServicePluginDefinition ? BuildServicePluginDefinition : T extends HostModule ? HostModuleAPI : ConditionalExcept<{ [Key in keyof T]: T[Key] extends Descriptors ? BuildDescriptors : never; }, EmptyObject>; }[Depth extends -1 ? 'done' : 'recurse']; type PublicMetadata = { PACKAGE_NAME?: string; }; declare global { interface ContextualClient { } } /** * A type used to create concerete types from SDK descriptors in * case a contextual client is available. */ type MaybeContext = globalThis.ContextualClient extends { host: Host$1; } ? BuildDescriptors : T; declare global { /** * A global interface to set the exposure toggle for the SDK. * @example * ```ts * declare global { * interface SDKExposureToggle { * alpha: true; * } * } */ interface SDKExposureToggle { } } type WixNamespace = string; interface Channel$1 { observeState(callback: (props: unknown, environment: Environment) => unknown): { disconnect: () => void; } | Promise<{ disconnect: () => void; }>; } interface WebsiteChannel extends Channel$1 { invoke: (args: { namespace: WixNamespace; method: string; args: unknown[]; }) => Promise; getAccessToken: () => Promise; } type Host = { channel: WebsiteChannel; environment?: Environment; }; /** * An object representing a channel or channel resource. * Site visitors can subscribe to a channel or channel resource to receive the * messages that are published on it. When site visitors subscribe to a channel, they do not * receive messages published to a resource on that same channel. Similarly, * when site visitors subscribe to a channel resource, they do not * receive messages published to that same channel without a specified resource. * Channel resources inherit their parent channel's permissions, unless specified * otherwise. */ interface Channel { /** * Channel name. Cannot exceed 140 characters. * @requiredField name */ name: string; /** * ID of a specific channel resource. */ resourceId?: string; } /** * An object representing an error. */ interface Error { /** * Error code. * * One of: * * + `1`: Connection error * + `2`: Subscription error (error will also include a channel value) * + `3`: Bad input * @requiredField errorCode */ errorCode: number; /** * Error message. * @requiredField message */ message: string; /** * Channel related to the error. * @servicePath wix-realtime-frontend.Channel */ channel?: Channel; } /** * An object representing a published message. */ interface Message { /** * Message payload. * Max: 10kb * @requiredField payload */ payload: any; /** * Message publisher, if sent. * @servicePath wix-realtime-frontend.Publisher */ publisher?: Publisher; } /** * An object representing a publisher. */ interface Publisher { /** * ID of the publisher. * @requiredField id */ id: string; } /** * An object containing options to be used when unsubscribing from a * channel or channel resource. */ interface UnsubscribeOptions { /** * The channel, and optionally the resource, to * unsubscribe from. Use this property when unsubscribing from all subscriptions to a channel * or channel resource. * @servicePath wix-realtime-frontend.Channel */ channel?: Channel; /** * ID of the subscription to unsubscribe from. Use this * property when unsubscribing from one of multiple subscriptions to a channel or channel * resource. */ subscriptionId?: string; } /** * undefined * * Handles connections. */ type ConnectionHandler = () => void; /** * undefined * * Handles disconnections. */ type DisconnectionHandler = () => void; /** * undefined * * Handles realtime errors. * @param error - The error that occurred. * @requiredField error * @servicePath wix-realtime-frontend.Error */ type ErrorHandler = (error: Error) => void; /** * undefined * * Handles a message published to a channel or channel resource. * @param message - The message that was published. * @requiredField message * @servicePath wix-realtime-frontend.Message * @param channel - The channel the message was published on. * @requiredField channel * @servicePath wix-realtime-frontend.Channel */ type MessageHandler = (message: Message, channel: Channel) => void; /** * Adds an event handler that runs when a connection or reconnection * occurs. * * A connection occurs on the first subscription to a channel or channel resource or * when an existing connection is lost and then restored. * @param handler - The name of the function or * the function expression to run when a connection occurs. * @requiredField handler * @servicePath wix-realtime-frontend.ConnectionHandler */ declare function onConnected(handler: ConnectionHandler): Promise; /** * Adds an event handler that runs when a disconnection occurs. * * A disconnection can occur, for example, if there is a network issue. * @param handler - The name of the function or * the function expression to run when a disconnection occurs. * @requiredField handler * @servicePath wix-realtime-frontend.DisconnectionHandler */ declare function onDisconnected(handler: DisconnectionHandler): Promise; /** * Adds an event handler that runs when an error occurs. * * An error can occur when attempting to resubscribe after a disconnection. * Errors that occur during the initial subscription process cause the * Promise returned by the [`subscribe()`](#subscribe) function to reject * and do not trigger `onError()` event handlers. * @param handler - The name of the function or * the function expression to run when an error occurs. * @requiredField handler * @servicePath wix-realtime-frontend.ErrorHandler */ declare function onError(handler: ErrorHandler): Promise; /** * Subscribes to a channel or channel resource. * * The `subscribe()` function subscribes to receive messages published on the * specified channel or channel resource and sets a function that handles * incoming messages when they are published to the channel. * * When you subscribe to a channel you do not receive messages published to * a resource on that same channel. To receive those messages, you must * explicitly subscribe to the specific resource. * * The specified message handler is run each time a message is published on * the given channel or channel resource. Use it to define what happens when * messages are received. * * You can subscribe to a channel or channel resource more than once to add * multiple message handlers. Each subscription returns a unique subscription * ID which can be used later to unsubscribe from the specific subscription * with that ID, without affecting the other subscriptions on the same channel * or channel resource. * @param channel - The channel, and optionally the resource, to * subscribe to. * @requiredField channel * @servicePath wix-realtime-frontend.Channel * @param handler - The name of the function or * the function expression to run when something is published to the subscription's * channel or channel resource. * @requiredField handler * @servicePath wix-realtime-frontend.MessageHandler * @returns Fulfilled - An ID representing the subscription, used for unsubscribing. * Rejected - Error that caused the rejection, such as insufficient * permissions. */ declare function subscribe(channel: Channel, handler: MessageHandler): Promise; /** * Unsubscribes from a channel or channel resource. * * The `unsubscribe()` function unsubscribes from receiving messages published * on the specified channel or channel resource. * * + Use the `channel` property of the `UnsubscribeOptions` object * passed to the `options` parameter to unsubscribe from all subscriptions to a * specific channel or channel resource. * * When you unsubscribe from a channel you do not unsubscribe from the * resources on that same channel. To no longer receive messages on a * channel resource, you must explicitly unsubscribe from the specific resource. * * + Use the `subscriptionId` property of the `UnsubscribeOptions` object * passed to the `options` parameter to unsubscribe from a specific subscription. * * This option is typically used when you have more than one subscription to the same * channel or channel resource and you only want to unsubscribe from one of those subscriptions. * * Get a subscription's `subscriptionId` from the resolution of the Promise returned * when creating the subscription with the [`subscribe()`](#subscribe) function. * @param options - Options to use when unsubscribing. * @requiredField options * @servicePath wix-realtime-frontend.UnsubscribeOptions * @returns Fulfilled - When unsubscribed from the channel or channel resource. * Rejected - Error that caused the rejection. */ declare function unsubscribe(options: UnsubscribeOptions): Promise; declare const realtimeSdkModuleRuntime_onConnected: typeof onConnected; declare const realtimeSdkModuleRuntime_onDisconnected: typeof onDisconnected; declare const realtimeSdkModuleRuntime_onError: typeof onError; declare const realtimeSdkModuleRuntime_subscribe: typeof subscribe; declare const realtimeSdkModuleRuntime_unsubscribe: typeof unsubscribe; declare namespace realtimeSdkModuleRuntime { export { realtimeSdkModuleRuntime_onConnected as onConnected, realtimeSdkModuleRuntime_onDisconnected as onDisconnected, realtimeSdkModuleRuntime_onError as onError, realtimeSdkModuleRuntime_subscribe as subscribe, realtimeSdkModuleRuntime_unsubscribe as unsubscribe }; } type Methods = { [P in keyof T as T[P] extends Function ? P : never]: T[P]; }; declare const realtimeRuntime: MaybeContext, Host> & Methods>; export { realtimeRuntime as realtime };