import { createCommandRequestId } from "./request-id.js"; import type { ClientMeta, CommandEnvelope, CommandEnvelopeWithInstanceId, PublicCommandPayload, } from "./sdk-types.js"; export type CreateCommandEnvelopeInput< Command extends PublicCommandPayload = PublicCommandPayload, > = { command: Command; requestId?: string | undefined; idempotencyKey?: string | undefined; instanceId?: string | undefined; clientMeta?: ClientMeta | undefined; }; const normalizeOptionalString = (value?: string): string | undefined => { if (value === undefined) { return undefined; } const normalized = value.trim(); return normalized.length > 0 ? normalized : undefined; }; export const createCommandEnvelope = ( input: CreateCommandEnvelopeInput, ): Omit & { command: Command } => { const requestId = normalizeOptionalString(input.requestId) ?? createCommandRequestId(); const idempotencyKey = normalizeOptionalString(input.idempotencyKey) ?? requestId; const instanceId = normalizeOptionalString(input.instanceId); return { version: "1", command: input.command, requestId, idempotencyKey, ...(instanceId !== undefined ? { instanceId } : {}), ...(input.clientMeta !== undefined ? { clientMeta: input.clientMeta } : {}), }; }; export const createCommandEnvelopeWithInstanceId = < Command extends PublicCommandPayload, >( input: CreateCommandEnvelopeInput & { instanceId: string }, ): Omit & { command: Command } => { const envelope = createCommandEnvelope(input); if (envelope.instanceId === undefined) { throw new Error("instanceId must be a non-empty string"); } return { ...envelope, instanceId: envelope.instanceId, }; }; export type { CommandEnvelope, CommandEnvelopeWithInstanceId };