/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { ClientRequest } from "#action/client/ClientRequest.js"; import { SessionParameters } from "#session/SessionParameters.js"; import { Diagnostic, Duration, isObject } from "@matter/general"; import { Specification } from "@matter/model"; import { ClusterType, CommandData, CommandId, DelayReportData, EndpointNumber, InvokeRequest, ObjectSchema, TlvOfModel, TlvSchema, TlvVoid, } from "@matter/types"; import { MalformedRequestError } from "./MalformedRequestError.js"; import { resolvePathForSpecifier, Specifier } from "./Specifier.js"; export interface InvokeCommandData extends CommandData { timed?: boolean; } export interface Invoke extends InvokeRequest { /** Timeout only relevant for Client Interactions */ timeout?: Duration; /** Expected processing time of the command on the server side to calculated response timeout */ expectedProcessingTime?: Duration; /** Whether to use extended timeout for fail-safe messages. Ignored when expectedProcessingTime is set */ useExtendedFailSafeMessageResponseTimeout?: boolean; /** * Controls automatic command batching for single-command invokes. * * - `undefined` — batch with zero delay (commands in the same timer tick are combined) * - `Duration` — batch with the specified collection window * - `false` — disable batching; execute immediately * * A request that sets other per-request options, such as {@link expectedProcessingTime}, is never batched and * executes immediately. Batches only combine commands for the same network. */ batchDuration?: false | Duration; /** * Server only: called after the request's paths are validated and before any command runs, with the endpoints at * least one command of the request dispatches to. */ beforeDispatch?: (endpoints: ReadonlySet) => void; } export interface CommandDecodeDetails { responseSchema: TlvSchema; [Diagnostic.value]: () => unknown; } export interface ClientInvoke extends Invoke, ClientRequest { commands: Map; skipValidation?: boolean; } /** * Request invocation of one or more commands. */ export function Invoke(options: Invoke.Definition): ClientInvoke; /** * Request invocation multiple commands with defined options */ export function Invoke(options: Invoke.Definition, ...commands: Invoke.CommandRequest[]): ClientInvoke; /** * Request invocation multiple commands as list of Commands with default options. */ export function Invoke(...commands: Invoke.CommandRequest[]): ClientInvoke; export function Invoke( optionsOrData: Invoke.Definition | Invoke.CommandRequest, ...commands: (Invoke.CommandRequest | Invoke.LegacyCommandRequest)[] ): ClientInvoke { if (optionsOrData === undefined) { throw new MalformedRequestError(`Invocation requires at least one command`); } let options; if ("commands" in optionsOrData) { options = optionsOrData; commands = [...optionsOrData.commands, ...commands]; } else { commands = [optionsOrData, ...commands]; options = {}; } const { interactionModelRevision = SessionParameters.fallbacks.interactionModelRevision, suppressResponse = false, timeout, expectedProcessingTime, useExtendedFailSafeMessageResponseTimeout = false, skipValidation = false, delayReportData, } = options; if (delayReportData !== undefined && !Specification.isForwardFeatureEnabled("delay-report-data")) { throw new MalformedRequestError("DelayReportData requires the delay-report-data forward feature"); } let timedRequest = !!options.timed || !!timeout; if (!commands?.length) { throw new MalformedRequestError(`Invocation requires at least one command`); } if (commands.length > 1) { const commandRefs = new Set(); for (const { commandRef } of commands) { if (commandRef === undefined) { throw new MalformedRequestError(`CommandRef required when invoking multiple commands`); } if (commandRefs.has(commandRef)) { throw new MalformedRequestError(`Duplicate commandRef ${commandRef} in multiple command invoke`); } commandRefs.add(commandRef); } } const commandMap = new Map(); const invokeRequests: InvokeCommandData[] = commands.map(cmd => { const cmdData = Invoke.Command(cmd, skipValidation); if (options.timed !== false) { // When timed in options are set to false, we respect that even if we know it better timedRequest ||= !!cmdData.timed; } commandMap.set(cmdData.commandRef, cmd); return cmdData; }); return { timedRequest, timeout, invokeRequests, interactionModelRevision, suppressResponse, expectedProcessingTime, useExtendedFailSafeMessageResponseTimeout, delayReportData, // Additional meta-data for client side processing skipValidation, commands: commandMap, [Diagnostic.value]: () => Diagnostic.list( commands.map(cmd => { const { commandRef } = cmd; const fields = "fields" in cmd ? cmd.fields : undefined; return [ Diagnostic.strong(Invoke.isLegacy(cmd) ? "(legacy)" : resolvePathForSpecifier(cmd)), "with", isObject(fields) ? Diagnostic.dict(fields) : "(no payload)", commandRef !== undefined && commands.length > 1 ? `(ref ${commandRef})` : "", ]; }), ), } as ClientInvoke; } export namespace Invoke { export interface Definition { /** List of commands to invoke */ commands: (Invoke.CommandRequest | Invoke.LegacyCommandRequest)[]; /** Tell the server to not send a response */ suppressResponse?: boolean; /** Whether this is sent as a timed request, if no timeout is specified a default is used */ timed?: boolean; /** Timeout when sent as a timed request, if timed flag is not set it will be set automatically */ timeout?: Duration; /** Interaction model revision to use, if not specified a default is used */ interactionModelRevision?: number; /** Processing time of the command of the server assumed for this invoke. If not set a default is used */ expectedProcessingTime?: Duration; /** Whether to use extended timeout for fail-safe messages. Ignored when expectedProcessingTime is set */ useExtendedFailSafeMessageResponseTimeout?: boolean; /** Whether to skip validation of command fields against schema */ skipValidation?: boolean; /** * Ask the server to hold off the next Report Data of the subscriptions on the endpoints the commands target. */ delayReportData?: DelayReportData; } export function Command( request: Invoke.CommandRequest, skipValidation?: boolean, ): InvokeCommandData; /** * @deprecated Scheduled for removal in 0.19. * Use {@link CommandRequest} with {@link ClusterType.Command}. */ export function Command(request: Invoke.LegacyCommandRequest, skipValidation?: boolean): InvokeCommandData; export function Command(request: Invoke.AnyCommandRequest, skipValidation?: boolean): InvokeCommandData; export function Command( request: Invoke.CommandRequest | Invoke.LegacyCommandRequest, skipValidation = false, ): InvokeCommandData { let requestSchema: TlvSchema; let requestId: CommandId; let timed: boolean; if (typeof request.command !== "string" && "requestId" in request.command) { // Legacy ClusterTypeCommand — extract fields directly const legacy = request.command as Specifier.ClusterTypeCommand; requestSchema = legacy.requestSchema; requestId = legacy.requestId; timed = legacy.timed; } else { const command = Invoke.commandOf(request as CommandRequest); requestSchema = TlvOfModel(command.schema) ?? TlvVoid; requestId = command.id; timed = command.schema.effectiveAccess.timed === true; } const { commandRef } = request; let fields: any = "fields" in request ? request.fields : undefined; if (requestSchema instanceof ObjectSchema && fields === undefined) { // If developer did not provide a request object, create an empty one if it needs to be an object // This can happen when all object properties are optional fields = {}; } if (!skipValidation) { requestSchema.validate(fields); } const commandFields = requestSchema.encodeTlv(fields); const result: InvokeCommandData = { commandPath: { // Endpoint id is added below if not wildcard clusterId: Specifier.clusterFor(request.cluster).id, commandId: requestId, }, commandFields, timed: timed ?? false, commandRef, }; // Optional endpoint is handled by the Specifier utility, so we can just cast here const endpointId = Specifier.endpointIdOf(request as ConcreteCommandRequest); if (endpointId !== undefined) { result.commandPath.endpointId = endpointId; } return result; } /** * @deprecated Scheduled for removal in 0.19. * Legacy command request using ClusterType commands. Use {@link CommandRequest} with * {@link ClusterType.Command}. */ export interface LegacyCommandRequest { cluster: Specifier.Cluster; command: Specifier.ClusterTypeCommand; endpoint?: Specifier.Endpoint; fields?: unknown; commandName?: string; commandRef?: number; } /** * Union of new-style and legacy command requests. */ export type AnyCommandRequest = CommandRequest | LegacyCommandRequest; /** * Type guard for legacy command requests. */ export function isLegacy(request: AnyCommandRequest): request is LegacyCommandRequest { return typeof request.command !== "string" && "requestId" in request.command; } export type CommandRequest< C extends Specifier.Cluster = Specifier.Cluster, CMD extends Specifier.Command> = Specifier.Command>, > = ConcreteCommandRequest | WildcardCommandRequest; export type ConcreteCommandRequest< C extends Specifier.Cluster = Specifier.Cluster, CMD extends Specifier.Command> = Specifier.Command>, > = WildcardCommandRequest & { endpoint: Specifier.Endpoint }; /** * @deprecated Scheduled for removal in 0.19. * Use the overload accepting {@link ConcreteCommandRequest}. */ export function ConcreteCommandRequest(data: Invoke.LegacyCommandRequest): Invoke.LegacyCommandRequest; export function ConcreteCommandRequest( data: Invoke.ConcreteCommandRequest, ): Invoke.ConcreteCommandRequest; export function ConcreteCommandRequest( data: Invoke.ConcreteCommandRequest | Invoke.LegacyCommandRequest, ): Invoke.ConcreteCommandRequest | Invoke.LegacyCommandRequest { if (data.endpoint === undefined) { throw new MalformedRequestError(`ConcreteCommandRequest requires an endpoint`); } return data; } export type WildcardCommandRequest< C extends Specifier.Cluster = Specifier.Cluster, CMD extends Specifier.Command> = Specifier.Command>, > = { cluster: C; command: CMD; commandName?: string; commandRef?: number; } & Fields, CMD>>; /** * @deprecated Scheduled for removal in 0.19. * Use the overload accepting {@link WildcardCommandRequest}. */ export function WildcardCommandRequest(data: Invoke.LegacyCommandRequest): Invoke.LegacyCommandRequest; export function WildcardCommandRequest( data: Invoke.WildcardCommandRequest, ): Invoke.WildcardCommandRequest; export function WildcardCommandRequest( data: Invoke.WildcardCommandRequest | Invoke.LegacyCommandRequest, ): Invoke.WildcardCommandRequest | Invoke.LegacyCommandRequest { if ("endpoint" in data && data.endpoint !== undefined) { throw new MalformedRequestError(`ConcreteCommandRequest must not have an endpoint`); } return data; } /** * Extract the command element from a command request. */ export function commandOf(request: R): ClusterType.Command { if (typeof request.command === "string") { const cluster = Specifier.clusterFor(request.cluster); const command = cluster.commands?.[request.command]; if (command === undefined) { throw new MalformedRequestError(`Cluster ${cluster.name} does not define command ${request.command}`); } return command; } return request.command; } /** * Extract the request type from a command's function signature phantom type. */ export type RequestOf = C extends ClusterType.Command ? F extends (request: infer R, ...args: unknown[]) => unknown ? R : void : void; export type Fields = RequestOf extends void ? {} : undefined extends RequestOf ? { fields?: RequestOf } : { fields: RequestOf }; }