@relaybus/core 0.4.1 → 1.0.0-next.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/internal/validation.ts","../../src/internal/field-extractors.ts","../../src/internal/cloudevents.ts","../../src/internal/json-envelope-wire-types.ts","../../src/internal/json-envelope-plan.ts","../../src/internal/json-envelope-other-fields.ts","../../src/internal/json-envelope-read.ts","../../src/internal/json-envelope-write.ts","../../src/internal/json-envelope.ts","../../src/store-kit/handed-out-ledger.ts","../../src/store-kit/owner-serialized-claims.ts","../../src/transport-kit/decoded-event-reader.ts","../../src/transport-kit/subscribing-transport.ts","../../src/values/bounded-integer.ts","../../src/values/exponential-backoff.ts","../../src/values/lane-lease-token.ts","../../src/values/non-empty-text.ts"],"names":["time","MILLISECONDS_PER_SECOND"],"mappings":";;;;AAGO,SAAS,qBAAA,CAAsB,OAAe,IAAA,EAAsB;AACzE,EAAA,OAAO,eAAA,CAAgB,EAAA,CAAG,KAAA,EAAO,IAAI,CAAA;AACvC;;;ACQO,SAAS,WACd,IAAA,EACqE;AACrE,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACrB,IAAA,MAAM,IAAI,mBAAmB,gCAAgC,CAAA;AAAA,EAC/D;AACA,EAAA,OAAO,CAAC,OAAA,KAAa,MAAA,CAAO,MAAA,CAAO,OAAA,CAAQ,OAAA,EAAS,IAAI,CAAA,GAAI,OAAA,CAAQ,OAAA,CAAQ,IAAI,CAAA,GAAI,MAAA;AACtF;AAcO,SAAS,iBACd,IAAA,EACgE;AAChE,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC/B,EAAA,IAAI,SAAS,IAAA,CAAK,CAAC,YAAY,OAAA,CAAQ,MAAA,KAAW,CAAC,CAAA,EAAG;AACpD,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,sEAAsE,IAAI,CAAA,CAA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,EAAM,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA,EAAG,KAAA,EAAO,KAAA,CAAM,CAAC,GAAI,MAAA,EAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA,EAAE;AAAA,EAC9E;AACF;;;AC/CO,IAAe,YAAA,GAAf,MAAe,aAAA,CAAa;AAAA,EACjC,OAAO,EAAA,CAAG,KAAA,EAAe,IAAA,EAAsB;AAC7C,IAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,MAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,EAAG,IAAI,CAAA,kBAAA,CAAoB,CAAA;AAAA,IAC1D;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA,EAGA,OAAO,QAAA,CAAS,KAAA,EAA2B,IAAA,EAAkC;AAC3E,IAAA,OAAO,UAAU,MAAA,GAAY,MAAA,GAAY,aAAA,CAAa,EAAA,CAAG,OAAO,IAAI,CAAA;AAAA,EACtE;AACF","file":"index.js","sourcesContent":["import { PositiveInteger } from '../values/positive-integer.js';\n\n/** Returns `value` when it is an integer of at least 1, else throws a {@link ConfigurationError} naming the option. */\nexport function assertPositiveInteger(value: number, name: string): number {\n return PositiveInteger.of(value, name);\n}\n","import { ConfigurationError } from '../errors.js';\nimport type { EventHeaders } from '../event.js';\n\n/**\n * Reads one header of an incoming message, for the `type`, `id`, `key` or\n * `source` option of {@link plainJsonDecoder}. Header names are compared\n * exactly (Kafka and AMQP header names are case-sensitive). Returns undefined when the\n * header is absent, so the decoder falls back to its default.\n *\n * ```ts\n * plainJsonDecoder({ type: fromHeader('event-type'), id: fromHeader('message-id') })\n * ```\n */\nexport function fromHeader(\n name: string,\n): (message: { readonly headers: EventHeaders }) => string | undefined {\n if (name.length === 0) {\n throw new ConfigurationError('fromHeader needs a header name');\n }\n return (message) => (Object.hasOwn(message.headers, name) ? message.headers[name] : undefined);\n}\n\n/**\n * Reads a field of the JSON payload by a dotted path (`'meta.eventType'`), for\n * the `type`, `id`, `key` or `source` option of {@link plainJsonDecoder}. A\n * string is returned as is and a safe integer as its decimal text (numeric ids\n * are common). Anything else returns undefined so the decoder falls back to its\n * default: a missing field, and also a fraction or an integer beyond 2^53, which\n * JSON parsing may already have rounded, so two different ids could collide.\n *\n * ```ts\n * plainJsonDecoder({ type: fromPayloadField('eventType'), key: fromPayloadField('order.id') })\n * ```\n */\nexport function fromPayloadField(\n path: string,\n): (message: { readonly payload: unknown }) => string | undefined {\n const segments = path.split('.');\n if (segments.some((segment) => segment.length === 0)) {\n throw new ConfigurationError(\n `fromPayloadField needs a dotted path of non-empty names, received '${path}'`,\n );\n }\n return (message) => {\n let value = message.payload;\n for (const segment of segments) {\n if (typeof value !== 'object' || value === null || !Object.hasOwn(value, segment)) {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n if (typeof value === 'string') {\n return value;\n }\n return Number.isSafeInteger(value) ? String(value) : undefined;\n };\n}\n","import { assertEventType, type EventEnvelope } from '../event.js';\n\n/** The media type of a content type, without parameters and lower-cased; undefined for anything but a string. */\nexport function mediaTypeOf(contentType: unknown): string | undefined {\n return typeof contentType === 'string'\n ? contentType.split(';')[0]!.trim().toLowerCase()\n : undefined;\n}\n\nexport function isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Readers of structured CloudEvent attributes that fail with the error of the calling transport. */\nexport interface CloudEventReaders {\n readonly optionalAttribute: (body: Record<string, unknown>, name: string) => string | undefined;\n readonly requiredAttribute: (body: Record<string, unknown>, name: string) => string;\n readonly assertValidType: (type: string, label: string) => void;\n readonly assertJsonDataContentType: (dataContentType: string | undefined) => void;\n}\n\nexport function createCloudEventReaders(invalid: (reason: string) => Error): CloudEventReaders {\n const optionalAttribute = (body: Record<string, unknown>, name: string): string | undefined => {\n const value = body[name];\n if (value !== undefined && typeof value !== 'string') {\n throw invalid(`Attribute '${name}' must be a string`);\n }\n return value;\n };\n return {\n optionalAttribute,\n requiredAttribute: (body, name) => {\n const value = optionalAttribute(body, name);\n if (value === undefined || value.length === 0) {\n throw invalid(`Attribute '${name}' is missing or empty`);\n }\n return value;\n },\n assertValidType: (type, label) => {\n try {\n assertEventType(type);\n } catch (error) {\n throw invalid(`${label} is not a valid event type: ${(error as Error).message}`);\n }\n },\n assertJsonDataContentType: (dataContentType) => {\n const mediaType = mediaTypeOf(dataContentType);\n if (\n mediaType !== undefined &&\n mediaType !== 'application/json' &&\n mediaType !== 'text/json' &&\n !mediaType.endsWith('+json')\n ) {\n throw invalid(`datacontenttype must be JSON, received '${dataContentType}'`);\n }\n },\n };\n}\n\n/**\n * The JSON text of a CloudEvents 1.0 structured-mode event: the attributes (the key as `subject`,\n * correlation and causation ids as extension attributes), then `data`, the already serialized\n * payload, so the payload is serialized only once.\n */\nexport function writeStructuredCloudEvent(\n envelope: EventEnvelope,\n { time, data }: { readonly time: string; readonly data: string },\n): string {\n const attributes = {\n specversion: '1.0',\n id: envelope.id,\n type: envelope.type,\n source: envelope.source,\n time,\n datacontenttype: 'application/json',\n ...(envelope.key === null ? {} : { subject: envelope.key }),\n ...(envelope.correlationId === null ? {} : { correlationid: envelope.correlationId }),\n ...(envelope.causationId === null ? {} : { causationid: envelope.causationId }),\n };\n return `${JSON.stringify(attributes).slice(0, -1)},\"data\":${data}}`;\n}\n","import { ConfigurationError } from '../errors.js';\nimport { assertEventType, type EventEnvelope } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport type { Context } from './json-envelope-plan.js';\n\n// The type names a format uses on the wire instead of relaybus event types (`wireTypes`).\n\n/** Event type to wire name, and wire name back to event type. */\nexport type WireTypePlan = {\n readonly wireTypes: ReadonlyMap<string, string>;\n readonly eventTypes: ReadonlyMap<string, string>;\n};\n\n/**\n * Compiles `wireTypes`: every key a valid event type, every value a non-empty name no other type\n * uses, and none with a fixed type, which is written nowhere.\n */\nexport function compileWireTypes(\n wireTypes: unknown,\n { fixed }: { readonly fixed: boolean },\n): WireTypePlan {\n if (wireTypes === undefined) {\n return { wireTypes: new Map(), eventTypes: new Map() };\n }\n if (!isJsonObject(wireTypes) || fixed) {\n throw new ConfigurationError(\n 'jsonEnvelope wireTypes must be an object of event type to wire name, with a type at { body } or { header }',\n );\n }\n const entries = Object.entries(wireTypes);\n const eventTypes = new Map<string, string>();\n for (const [type, wire] of entries) {\n assertEventType(type);\n if (typeof wire !== 'string' || wire.length === 0 || eventTypes.has(wire)) {\n throw new ConfigurationError(\n `jsonEnvelope wireTypes needs a non-empty wire name for '${type}' that no other type uses`,\n );\n }\n eventTypes.set(wire, type);\n }\n return { wireTypes: new Map(entries as [string, string][]), eventTypes };\n}\n\n/** The type as the wire carries it; an unlisted type that another type's wire name equals is refused. */\nexport function wireTypeOf(envelope: EventEnvelope, { plan, failures }: Context): string {\n const wire = plan.wireTypes.get(envelope.type);\n if (wire !== undefined) {\n return wire;\n }\n const other = plan.eventTypes.get(envelope.type);\n if (other !== undefined) {\n throw failures.unencodable(\n `Event ${envelope.id} has type '${envelope.type}', which wireTypes uses as the wire name of '${other}'`,\n );\n }\n return envelope.type;\n}\n\n/** The event type a wire type value names: a listed wire name, or a valid event type itself. */\nexport function eventTypeOf(wire: string, { plan, failures }: Context): string {\n const type = plan.eventTypes.get(wire);\n if (type !== undefined) {\n return type;\n }\n try {\n assertEventType(wire);\n } catch (error) {\n throw failures.invalid(`The event type is not a valid event type: ${(error as Error).message}`);\n }\n return wire;\n}\n","import { ConfigurationError } from '../errors.js';\nimport { assertEventType } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport { compileWireTypes, type WireTypePlan } from './json-envelope-wire-types.js';\nimport type {\n ExtraValue,\n FixedType,\n JsonConstant,\n JsonEnvelopeFailures,\n JsonEnvelopeMapping,\n TimeFormat,\n} from './json-envelope.js';\n\n// Compiling a jsonEnvelope mapping into the plan that writing and reading follow.\n\nexport type Location =\n | { readonly label: string; readonly header: string }\n | { readonly label: string; readonly path: readonly string[] };\n\nexport type OptionalName = 'key' | 'source' | 'occurredAt' | 'correlationId' | 'causationId';\nexport const OPTIONAL_NAMES: readonly OptionalName[] = [\n 'key',\n 'source',\n 'occurredAt',\n 'correlationId',\n 'causationId',\n];\n\nexport type Plan = {\n readonly type: Location | FixedType;\n /** Undefined when the transport supplies the id. */\n readonly id: Location | undefined;\n /** Whether a message without the mapped id gets the transport's own id instead. */\n readonly idWhenMissing: boolean;\n readonly optional: Readonly<Partial<Record<OptionalName, Location>>>;\n /** Undefined when the payload is the whole body. */\n readonly payload: readonly string[] | undefined;\n /** Undefined when event headers are the unmapped message headers or top-level fields. */\n readonly headers: readonly string[] | undefined;\n /** Whether event headers are spread over the top level of the body. */\n readonly topLevelHeaders: boolean;\n /** Top-level body names a mapped, payload, headers or extra value uses. */\n readonly topLevelNames: ReadonlySet<string>;\n /** Headers the mapping writes itself: the mapped ones and the extra ones. */\n readonly mappedHeaders: ReadonlySet<string>;\n readonly timeFormat: TimeFormat;\n readonly extraBody: readonly ExtraBodyValue[];\n readonly extraHeaders: readonly (readonly [string, ExtraValue<string>])[];\n readonly bodyOrder: readonly string[];\n /** The payload field that keeps the unused top-level fields; undefined when they are left out. */\n readonly otherFields: string | undefined;\n} & WireTypePlan;\n\n/** An extra body value at its path. */\nexport type ExtraBodyValue = {\n readonly path: readonly string[];\n readonly value: ExtraValue<JsonConstant>;\n};\n\nconst TIME_FORMATS: readonly TimeFormat[] = ['rfc3339', 'epoch-millis', 'epoch-seconds'];\n\nexport const ARRAY_INDEX = /^(?:0|[1-9]\\d*)$/;\n\n/** A compiled mapping with the errors of the calling transport. */\nexport type Context = { readonly plan: Plan; readonly failures: JsonEnvelopeFailures };\n\nexport function compile(\n mapping: JsonEnvelopeMapping<string>,\n transportIds: readonly string[],\n): Plan {\n if (!isJsonObject(mapping)) {\n throw new ConfigurationError('jsonEnvelope needs a mapping object');\n }\n const optional: Partial<Record<OptionalName, Location>> = {};\n for (const name of OPTIONAL_NAMES) {\n const field = mapping[name];\n if (field !== undefined) {\n optional[name] = toLocation(field, name);\n }\n }\n const payload = compilePayload(mapping.payload);\n const topLevelHeaders = mapping.headers === 'top-level-fields';\n if (topLevelHeaders && payload === undefined) {\n throw new ConfigurationError(\"jsonEnvelope headers 'top-level-fields' needs a body payload\");\n }\n const type = compileType(mapping.type);\n const plan: Plan = {\n type,\n id: compileId(mapping.id, transportIds),\n idWhenMissing: isJsonObject(mapping.id) && 'whenMissing' in mapping.id,\n optional,\n payload,\n headers: topLevelHeaders ? undefined : compileHeaders(mapping.headers),\n topLevelHeaders,\n topLevelNames: new Set(),\n mappedHeaders: new Set(),\n timeFormat: compileTimeFormat(mapping.occurredAt),\n otherFields: compileOtherFields(mapping, payload !== undefined),\n ...compileWireTypes(mapping.wireTypes, { fixed: 'fixed' in type }),\n ...compileExtras(mapping, payload !== undefined),\n };\n return assertDisjoint(plan);\n}\n\nfunction compileTimeFormat(field: unknown): TimeFormat {\n const format = isJsonObject(field) ? field['format'] : undefined;\n if (format === undefined) {\n return 'rfc3339';\n }\n if (!TIME_FORMATS.includes(format as TimeFormat)) {\n throw new ConfigurationError(\n `jsonEnvelope occurredAt format must be one of ${TIME_FORMATS.map((name) => `'${name}'`).join(', ')}`,\n );\n }\n return format as TimeFormat;\n}\n\n/** The extra values and the body order; a payload-only mapping has no body to put them in. */\nfunction compileExtras(\n mapping: JsonEnvelopeMapping<string>,\n hasBody: boolean,\n): Pick<Plan, 'extraBody' | 'extraHeaders' | 'bodyOrder'> {\n const extra = (mapping.extra ?? {}) as {\n readonly body?: Readonly<Record<string, ExtraValue<JsonConstant>>>;\n readonly headers?: Readonly<Record<string, ExtraValue<string>>>;\n };\n const bodyOrder = (mapping as { readonly bodyOrder?: readonly string[] }).bodyOrder ?? [];\n if (!hasBody && (extra.body !== undefined || bodyOrder.length > 0)) {\n throw new ConfigurationError(\n 'jsonEnvelope with a whole-body payload has no body for extra values or a body order',\n );\n }\n return {\n extraBody: Object.entries(extra.body ?? {}).map(([path, value]) => ({\n path: toPath(path, 'extra body value'),\n value,\n })),\n extraHeaders: Object.entries(extra.headers ?? {}),\n bodyOrder,\n };\n}\n\nfunction compileOtherFields(\n mapping: JsonEnvelopeMapping<string>,\n hasBody: boolean,\n): string | undefined {\n const otherFields: unknown = (mapping as { readonly otherFields?: unknown }).otherFields;\n if (otherFields === undefined) {\n return undefined;\n }\n if (!hasBody) {\n throw new ConfigurationError('jsonEnvelope otherFields needs a body payload');\n }\n const field = isJsonObject(otherFields) ? otherFields['payloadField'] : undefined;\n if (typeof field !== 'string' || field.length === 0) {\n throw new ConfigurationError(\"jsonEnvelope otherFields must be { payloadField: '<name>' }\");\n }\n return field;\n}\n\nfunction compileType(type: unknown): Location | FixedType {\n if (isJsonObject(type) && typeof type['fixed'] === 'string') {\n assertEventType(type['fixed']);\n return { fixed: type['fixed'] };\n }\n if (type === undefined) {\n throw new ConfigurationError('jsonEnvelope needs a type: { body }, { header } or { fixed }');\n }\n return toLocation(type, 'type');\n}\n\nfunction compileId(id: unknown, transportIds: readonly string[]): Location | undefined {\n if (typeof id === 'string' && transportIds.includes(id)) {\n return undefined;\n }\n const names = transportIds.map((name) => `'${name}'`).join(', ');\n if (!isJsonObject(id)) {\n throw new ConfigurationError(\n `jsonEnvelope needs an id: { body }, { header } or one of ${names}`,\n );\n }\n if ('whenMissing' in id && !transportIds.includes(id['whenMissing'] as string)) {\n throw new ConfigurationError(`jsonEnvelope id whenMissing must be one of ${names}`);\n }\n return toLocation(id, 'id');\n}\n\nfunction compilePayload(payload: unknown): readonly string[] | undefined {\n if (payload === 'whole-body') {\n return undefined;\n }\n if (!isJsonObject(payload) || typeof payload['body'] !== 'string') {\n throw new ConfigurationError(\n \"jsonEnvelope needs a payload: { body: '<path>' } or 'whole-body'\",\n );\n }\n return toPath(payload['body'], 'payload');\n}\n\nfunction compileHeaders(headers: unknown): readonly string[] | undefined {\n if (headers === undefined || headers === 'message-headers') {\n return undefined;\n }\n if (!isJsonObject(headers) || typeof headers['body'] !== 'string') {\n throw new ConfigurationError(\n \"jsonEnvelope headers must be { body: '<path>' } or 'message-headers'\",\n );\n }\n return toPath(headers['body'], 'headers');\n}\n\nfunction toLocation(field: unknown, label: string): Location {\n if (isJsonObject(field) && typeof field['header'] === 'string' && field['header'].length > 0) {\n return { label, header: field['header'] };\n }\n if (isJsonObject(field) && typeof field['body'] === 'string') {\n return { label, path: toPath(field['body'], label) };\n }\n throw new ConfigurationError(\n `jsonEnvelope ${label} must be { body: '<path>' } or { header: '<name>' }`,\n );\n}\n\nfunction toPath(path: string, label: string): readonly string[] {\n const segments = path.split('.');\n if (segments.some((segment) => segment.length === 0)) {\n throw new ConfigurationError(\n `jsonEnvelope ${label} needs a dotted path of non-empty names, received '${path}'`,\n );\n }\n return segments;\n}\n\n/** Collects the mapped headers and refuses overlapping locations, which would overwrite each other. */\nfunction assertDisjoint(plan: Plan): Plan {\n const locations = [plan.type, plan.id, ...Object.values(plan.optional)].filter(\n (location): location is Location => location !== undefined && !('fixed' in location),\n );\n const headers = [\n ...locations.flatMap((location) => ('header' in location ? [location.header] : [])),\n ...plan.extraHeaders.map(([name]) => name),\n ];\n const duplicate = headers.find((name, index) => headers.indexOf(name) !== index);\n if (duplicate !== undefined) {\n throw new ConfigurationError(`jsonEnvelope maps header '${duplicate}' twice`);\n }\n const paths = [\n ...locations.flatMap((location) => ('path' in location ? [location.path] : [])),\n ...[plan.payload, plan.headers].filter((path) => path !== undefined),\n ...plan.extraBody.map(({ path }) => path),\n ];\n assertNoNestedPaths(paths);\n return {\n ...plan,\n mappedHeaders: new Set(headers),\n topLevelNames: new Set(paths.map((path) => path[0]!)),\n };\n}\n\nfunction assertNoNestedPaths(paths: readonly (readonly string[])[]): void {\n paths.forEach((path, index) => {\n for (const other of paths.slice(index + 1)) {\n assertCompatiblePaths(path, other);\n }\n });\n}\n\n/** Two body paths must part ways, and where they do, both index an array or both name a field. */\nfunction assertCompatiblePaths(path: readonly string[], other: readonly string[]): void {\n const parting = path.findIndex((segment, position) => segment !== other[position]);\n const both = `'${path.join('.')}' and '${other.join('.')}'`;\n if (parting === -1 || parting === other.length) {\n throw new ConfigurationError(`jsonEnvelope body paths ${both} overlap`);\n }\n if (ARRAY_INDEX.test(path[parting]!) !== ARRAY_INDEX.test(other[parting]!)) {\n throw new ConfigurationError(`jsonEnvelope body paths ${both} mix an array index and a name`);\n }\n}\n","import type { EventEnvelope } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport type { Context } from './json-envelope-plan.js';\n\n// The top-level body fields no mapped value uses, kept under one payload field (`otherFields`).\n\n/** The top-level fields of `body` no other value uses and that are not read as event headers. */\nfunction unusedFields(body: Record<string, unknown>, { plan }: Context): [string, unknown][] {\n return Object.entries(body).filter(\n ([name, value]) =>\n !plan.topLevelNames.has(name) && !(plan.topLevelHeaders && typeof value === 'string'),\n );\n}\n\n/**\n * The payload read from `body` with the unused top-level fields under the `otherFields` field. An\n * object payload always gets the field (empty when there are none), so its shape does not depend on\n * the message; a payload that is not an object stays as it is when there is nothing to keep.\n */\nexport function withOtherFields(\n payload: unknown,\n { body, context }: { readonly body: Record<string, unknown>; readonly context: Context },\n): unknown {\n const field = context.plan.otherFields;\n if (field === undefined) {\n return payload;\n }\n const fields = unusedFields(body, context);\n if (!isJsonObject(payload) && fields.length === 0) {\n return payload;\n }\n if (!isJsonObject(payload) || Object.hasOwn(payload, field)) {\n throw context.failures.invalid(\n `otherFields keeps the unused top-level fields under the payload field '${field}', but the payload is not an object without that field`,\n );\n }\n return Object.fromEntries([...Object.entries(payload), [field, Object.fromEntries(fields)]]);\n}\n\n/** The payload to write and the fields to spread over the top level, split at `otherFields`. */\nexport function splitOtherFields(\n envelope: EventEnvelope,\n context: Context,\n): { readonly payload: unknown; readonly fields: readonly [string, unknown][] } {\n const field = context.plan.otherFields;\n const { payload } = envelope;\n if (field === undefined || !isJsonObject(payload) || !Object.hasOwn(payload, field)) {\n return { payload, fields: [] };\n }\n const others = payload[field];\n if (!isJsonObject(others)) {\n throw context.failures.unencodable(\n `Event ${envelope.id} has a payload field '${field}' that is not an object of top-level fields`,\n );\n }\n const fields = Object.entries(others);\n const refused = fields.find((entry) => isRefused(entry, context));\n if (refused !== undefined) {\n throw context.failures.unencodable(\n `Event ${envelope.id} keeps a top-level field '${refused[0]}' under '${field}' that the mapping reads as another value`,\n );\n }\n return {\n payload: Object.fromEntries(Object.entries(payload).filter(([name]) => name !== field)),\n fields,\n };\n}\n\n/** A name another value uses, or text that would read back as an event header. */\nfunction isRefused([name, value]: readonly [string, unknown], { plan }: Context): boolean {\n return plan.topLevelNames.has(name) || (plan.topLevelHeaders && typeof value === 'string');\n}\n","import type { EventHeaders } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport type { JsonEnvelopeFailures, JsonEnvelopeFields, JsonWireMessage } from './json-envelope.js';\nimport type { Context, Location, Plan } from './json-envelope-plan.js';\nimport { withOtherFields } from './json-envelope-other-fields.js';\nimport { eventTypeOf } from './json-envelope-wire-types.js';\n\n// Reading the envelope fields of a JSON message by a compiled mapping.\n\nconst RFC3339_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/i;\nconst EPOCH_PATTERN = /^\\d+$/;\nconst MILLISECONDS_PER_SECOND = 1000;\n\nexport function readMessage(message: JsonWireMessage, context: Context): JsonEnvelopeFields {\n const { plan, failures } = context;\n if (plan.payload !== undefined && !isJsonObject(message.body)) {\n throw failures.invalid('The message body must be a JSON object');\n }\n const read = (location: Location | undefined): string | undefined =>\n location === undefined ? undefined : readText(message, { location, failures });\n const fields: Record<string, unknown> = {\n id: readId(read(plan.id), context),\n type: readType(message, context),\n payload: readPayload(message.body, context),\n key: read(plan.optional.key),\n source: read(plan.optional.source),\n headers: readEventHeaders(message, plan),\n correlationId: read(plan.optional.correlationId) ?? null,\n causationId: read(plan.optional.causationId) ?? null,\n occurredAt: readTime(read(plan.optional.occurredAt), context),\n };\n return Object.fromEntries(\n Object.entries(fields).filter((entry) => entry[1] !== undefined),\n ) as JsonEnvelopeFields;\n}\n\nfunction readId(id: string | undefined, { plan, failures }: Context): string | undefined {\n if (plan.id === undefined || plan.idWhenMissing) {\n return id;\n }\n return requireText(id, { location: plan.id, failures });\n}\n\nfunction readType(message: JsonWireMessage, { plan, failures }: Context): string {\n if ('fixed' in plan.type) {\n return plan.type.fixed;\n }\n const location = plan.type;\n const wire = requireText(readText(message, { location, failures }), { location, failures });\n return eventTypeOf(wire, { plan, failures });\n}\n\nfunction readPayload(body: unknown, { plan, failures }: Context): unknown {\n if (plan.payload === undefined) {\n return body;\n }\n const payload = valueAt(body, plan.payload);\n if (payload === undefined) {\n throw failures.invalid(`The message has no payload at '${plan.payload.join('.')}'`);\n }\n return withOtherFields(payload, {\n body: body as Record<string, unknown>,\n context: { plan, failures },\n });\n}\n\nfunction readEventHeaders(message: JsonWireMessage, plan: Plan): EventHeaders {\n if (plan.topLevelHeaders) {\n return textEntries(\n Object.entries(message.body as Record<string, unknown>).filter(\n ([name]) => !plan.topLevelNames.has(name),\n ),\n );\n }\n if (plan.headers === undefined) {\n return Object.fromEntries(\n Object.entries(message.headers).filter(([name]) => !plan.mappedHeaders.has(name)),\n );\n }\n const headers = valueAt(message.body, plan.headers);\n return isJsonObject(headers) ? textEntries(Object.entries(headers)) : {};\n}\n\nfunction textEntries(entries: readonly [string, unknown][]): EventHeaders {\n return Object.fromEntries(\n entries.filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n );\n}\n\nfunction readTime(text: string | undefined, { plan, failures }: Context): Date | undefined {\n if (text === undefined) {\n return undefined;\n }\n if (plan.timeFormat !== 'rfc3339') {\n const time = new Date(\n Number(text) * (plan.timeFormat === 'epoch-seconds' ? MILLISECONDS_PER_SECOND : 1),\n );\n if (!EPOCH_PATTERN.test(text) || Number.isNaN(time.getTime())) {\n throw failures.invalid(`The event time is not a whole ${plan.timeFormat} number: '${text}'`);\n }\n return time;\n }\n const time = new Date(text);\n if (!RFC3339_PATTERN.test(text) || Number.isNaN(time.getTime())) {\n throw failures.invalid(`The event time is not an RFC 3339 timestamp: '${text}'`);\n }\n return time;\n}\n\n/** A string, or a safe integer as its decimal text; undefined when absent, null or empty. */\nfunction readText(\n message: JsonWireMessage,\n { location, failures }: { readonly location: Location; readonly failures: JsonEnvelopeFailures },\n): string | undefined {\n const value =\n 'header' in location\n ? Object.hasOwn(message.headers, location.header)\n ? message.headers[location.header]\n : undefined\n : valueAt(message.body, location.path);\n if (value === undefined || value === null || value === '') {\n return undefined;\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' && Number.isSafeInteger(value)) {\n return String(value);\n }\n throw failures.invalid(`The ${location.label} at ${describe(location)} must be a string`);\n}\n\nfunction requireText(\n value: string | undefined,\n { location, failures }: { readonly location: Location; readonly failures: JsonEnvelopeFailures },\n): string {\n if (value === undefined) {\n throw failures.invalid(`The message has no ${location.label} at ${describe(location)}`);\n }\n return value;\n}\n\nfunction describe(location: Location): string {\n return 'header' in location ? `header '${location.header}'` : `'${location.path.join('.')}'`;\n}\n\nfunction valueAt(body: unknown, path: readonly string[]): unknown {\n let value = body;\n for (const segment of path) {\n if (typeof value !== 'object' || value === null || !Object.hasOwn(value, segment)) {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n}\n","import type { EventEnvelope } from '../event.js';\nimport type { JsonEnvelopeFailures, JsonWireMessage, TimeFormat } from './json-envelope.js';\nimport {\n ARRAY_INDEX,\n type Context,\n type Location,\n type OptionalName,\n type Plan,\n} from './json-envelope-plan.js';\nimport { splitOtherFields } from './json-envelope-other-fields.js';\nimport { wireTypeOf } from './json-envelope-wire-types.js';\n\n// Writing an envelope as a JSON message by a compiled mapping.\n\n/** RFC 3339 years have four digits. */\nconst MAXIMUM_RFC3339_YEAR = 9999;\nconst MILLISECONDS_PER_SECOND = 1000;\n\nexport function writeMessage(\n envelope: EventEnvelope,\n { plan, failures }: Context,\n): JsonWireMessage {\n const root: Record<string, unknown> = {};\n const headers: [string, string][] = [];\n const put = (location: Location, value: string | number): void => {\n if ('header' in location) {\n headers.push([location.header, String(value)]);\n } else {\n setAt(root, { path: location.path, value });\n }\n };\n const typeAt = typeLocation(envelope, { plan, failures });\n if (typeAt !== undefined) {\n put(typeAt, wireTypeOf(envelope, { plan, failures }));\n }\n if (plan.id !== undefined) {\n put(plan.id, envelope.id);\n }\n for (const [name, value] of optionalValues(envelope, { plan, failures })) {\n const location = plan.optional[name];\n if (location !== undefined && value !== null) {\n put(location, value);\n }\n }\n return {\n body: writeBody(envelope, { plan, failures, root }),\n headers: Object.fromEntries([\n ...eventHeaderEntries(envelope, { plan, failures }),\n ...headers,\n ...extraHeaderEntries(envelope, plan),\n ]),\n };\n}\n\n/** Where the type is written; a fixed type is written nowhere and refuses any other type. */\nfunction typeLocation(envelope: EventEnvelope, { plan, failures }: Context): Location | undefined {\n if (!('fixed' in plan.type)) {\n return plan.type;\n }\n if (envelope.type !== plan.type.fixed) {\n throw failures.unencodable(\n `Event ${envelope.id} has type '${envelope.type}', but this route carries only '${plan.type.fixed}'`,\n );\n }\n return undefined;\n}\n\nfunction extraHeaderEntries(envelope: EventEnvelope, plan: Plan): [string, string][] {\n return plan.extraHeaders.map(([name, value]) => [\n name,\n typeof value === 'function' ? value(envelope) : value,\n ]);\n}\n\nfunction optionalValues(\n envelope: EventEnvelope,\n { plan, failures }: Context,\n): [OptionalName, string | number | null][] {\n return [\n ['key', envelope.key],\n ['source', envelope.source],\n [\n 'occurredAt',\n timeValue(formatTime(envelope, failures), { envelope, format: plan.timeFormat }),\n ],\n ['correlationId', envelope.correlationId],\n ['causationId', envelope.causationId],\n ];\n}\n\n/** The body: the payload alone, or every mapped, extra, header and kept field in body order. */\nfunction writeBody(\n envelope: EventEnvelope,\n { plan, failures, root }: Context & { readonly root: Record<string, unknown> },\n): unknown {\n const { payload, fields } = splitOtherFields(envelope, { plan, failures });\n if (plan.payload === undefined) {\n return payload;\n }\n setAt(root, { path: plan.payload, value: payload });\n if (plan.headers !== undefined) {\n setAt(root, {\n path: plan.headers,\n value: Object.fromEntries(Object.entries(envelope.headers)),\n });\n }\n for (const { path, value } of plan.extraBody) {\n setAt(root, { path, value: typeof value === 'function' ? value(envelope) : value });\n }\n if (plan.topLevelHeaders) {\n spreadHeaders(envelope, { plan, failures, root });\n }\n spreadOtherFields(envelope, { failures, fields, root });\n return ordered(root, plan.bodyOrder);\n}\n\n/** Event headers spread over the top level of the body, last; a name another value uses is refused. */\nfunction spreadHeaders(\n envelope: EventEnvelope,\n { plan, failures, root }: Context & { readonly root: Record<string, unknown> },\n): void {\n for (const [name, value] of Object.entries(envelope.headers)) {\n if (plan.topLevelNames.has(name)) {\n throw failures.unencodable(\n `Event ${envelope.id} has a header '${name}', which the mapping uses for another body field`,\n );\n }\n setAt(root, { path: [name], value });\n }\n}\n\n/** The fields `otherFields` kept, spread over the top level after everything else; a taken name is refused. */\nfunction spreadOtherFields(\n envelope: EventEnvelope,\n {\n failures,\n fields,\n root,\n }: {\n readonly failures: JsonEnvelopeFailures;\n readonly fields: readonly [string, unknown][];\n readonly root: Record<string, unknown>;\n },\n): void {\n for (const [name, value] of fields) {\n if (Object.hasOwn(root, name)) {\n throw failures.unencodable(\n `Event ${envelope.id} keeps a top-level field '${name}' that an event header also writes`,\n );\n }\n setAt(root, { path: [name], value });\n }\n}\n\n/** The time as the format writes it; the RFC 3339 text is checked first either way. */\nfunction timeValue(\n text: string,\n { envelope, format }: { readonly envelope: EventEnvelope; readonly format: TimeFormat },\n): string | number {\n const milliseconds = envelope.occurredAt.getTime();\n if (format === 'epoch-millis') {\n return milliseconds;\n }\n return format === 'epoch-seconds' ? Math.floor(milliseconds / MILLISECONDS_PER_SECOND) : text;\n}\n\n/** The body with the listed top-level fields first, in the listed order, spread headers and kept fields included. */\nfunction ordered(root: Record<string, unknown>, order: readonly string[]): Record<string, unknown> {\n if (order.length === 0) {\n return root;\n }\n const result: Record<string, unknown> = {};\n const names = [...order.filter((name) => Object.hasOwn(root, name)), ...Object.keys(root)];\n for (const name of names) {\n if (!Object.hasOwn(result, name)) {\n defineValue(result, { name, value: root[name] });\n }\n }\n return result;\n}\n\n/** The event headers that travel as message headers; a name a mapped field uses is refused. */\nfunction eventHeaderEntries(\n envelope: EventEnvelope,\n { plan, failures }: Context,\n): [string, string][] {\n if (plan.headers !== undefined || plan.topLevelHeaders) {\n return [];\n }\n const entries = Object.entries(envelope.headers);\n const taken = entries.find(([name]) => plan.mappedHeaders.has(name));\n if (taken !== undefined) {\n throw failures.unencodable(\n `Event ${envelope.id} has a header '${taken[0]}', which the mapping uses for another field`,\n );\n }\n return entries;\n}\n\nfunction formatTime(envelope: EventEnvelope, failures: JsonEnvelopeFailures): string {\n const year = envelope.occurredAt.getUTCFullYear();\n if (Number.isNaN(year) || year < 0 || year > MAXIMUM_RFC3339_YEAR) {\n throw failures.unencodable(\n `Event ${envelope.id} has an occurredAt that is not an RFC 3339 instant (invalid date or year outside 0..9999)`,\n );\n }\n return envelope.occurredAt.toISOString();\n}\n\n/** Sets a value at a path, creating objects (arrays before an index segment) as own properties. */\nfunction setAt(\n root: Record<string, unknown>,\n { path, value }: { readonly path: readonly string[]; readonly value: unknown },\n): void {\n let container = root;\n for (const [index, segment] of path.slice(0, -1).entries()) {\n if (!Object.hasOwn(container, segment)) {\n defineValue(container, {\n name: segment,\n value: ARRAY_INDEX.test(path[index + 1]!) ? [] : {},\n });\n }\n container = container[segment] as Record<string, unknown>;\n }\n defineValue(container, { name: path.at(-1)!, value });\n}\n\n/** defineProperty, because assigning `__proto__` would set the prototype instead of a field. */\nfunction defineValue(\n target: Record<string, unknown>,\n { name, value }: { readonly name: string; readonly value: unknown },\n): void {\n Object.defineProperty(target, name, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n","import type { EventEnvelope, EventHeaders } from '../event.js';\nimport { compile } from './json-envelope-plan.js';\nimport { readMessage } from './json-envelope-read.js';\nimport { writeMessage } from './json-envelope-write.js';\n\n/**\n * A field of the JSON body, by dotted path: `'eventName'`, `'meta.correlationId'`. A segment that\n * is a whole number indexes an array: `'messageType.0'` is the first element of `messageType`.\n */\nexport type BodyField = { readonly body: string };\n/** A message header (Kafka record header, AMQP message header), by exact name. */\nexport type HeaderField = { readonly header: string };\n/** Where one envelope value lives on the wire. */\nexport type WireField = BodyField | HeaderField;\n/** The one event type every message of the route carries: written nowhere, used for every message read. */\nexport type FixedType = { readonly fixed: string };\n\n/**\n * How `occurredAt` travels: RFC 3339 text (default), or whole epoch milliseconds or seconds, a\n * number in the body and decimal text in a header. Epoch seconds drop the milliseconds.\n */\nexport type TimeFormat = 'rfc3339' | 'epoch-millis' | 'epoch-seconds';\n/** Where the event time lives, and in which format. */\nexport type TimeField<TField extends WireField> = TField & { readonly format?: TimeFormat };\n\n/** A JSON value written as it is. */\nexport type JsonConstant =\n | string\n | number\n | boolean\n | null\n | readonly JsonConstant[]\n | { readonly [name: string]: JsonConstant };\n/** A value written with every message: a constant, or derived from the event. */\nexport type ExtraValue<TValue> = TValue | ((envelope: EventEnvelope) => TValue);\n/** Extra message headers, by name. */\nexport type ExtraHeaders = Readonly<Record<string, ExtraValue<string>>>;\n/** Extra body values, by dotted path. */\nexport type ExtraBody = Readonly<Record<string, ExtraValue<JsonConstant>>>;\n\ntype MappingFields<TField extends WireField, TTransportId extends string> = {\n /** Where the event type lives, or the one type of the route. Required. */\n readonly type: TField | FixedType;\n /**\n * Where the event id lives, or the transport's own message identity (see the transport's\n * mapping type). Required, so the inbox dedup key is always a deliberate choice. A message\n * whose mapped id is missing is malformed, unless `whenMissing` names the transport's own id\n * to use instead: `{ body: 'id', whenMissing: 'record-position' }`.\n */\n readonly id: TField | TTransportId | (TField & { readonly whenMissing: TTransportId });\n /** Ordering key. Default: the transport's own (the Kafka record key; none on RabbitMQ). */\n readonly key?: TField;\n /** Producing service. Default: the transport's own (Kafka topic; RabbitMQ `appId`, else the routing key). */\n readonly source?: TField;\n /**\n * Event time, RFC 3339 unless `format` says otherwise. Default: the transport's own (Kafka\n * record timestamp; RabbitMQ `timestamp`, seconds).\n */\n readonly occurredAt?: TimeField<TField>;\n readonly correlationId?: TField;\n readonly causationId?: TField;\n /** Media type written with the message. Default `application/json`. Not checked on read. */\n readonly contentType?: string;\n /**\n * Wire names of event types, for a format whose type values are not relaybus event types or\n * name them otherwise: `{ 'transfer.auto-dispatched.v1': 'Transfer Auto Dispatched' }`. A listed\n * type is written as its wire name and read back from it; any other type travels as itself. One\n * route then carries many types without a `fixed` type per transport. Not with a `fixed` type.\n */\n readonly wireTypes?: WireTypes;\n};\n\n/** Event type to the name the wire uses for it; see `wireTypes` of a jsonEnvelope mapping. */\nexport type WireTypes = Readonly<Record<string, string>>;\n\n/**\n * A JSON object that wraps the payload with event metadata, such as\n * `{ \"eventName\": ..., \"messageId\": ..., \"data\": {...}, \"meta\": {...} }`.\n * Each value lives at a body path or in a header.\n */\nexport type BodyEnvelopeMapping<TTransportId extends string> = MappingFields<\n WireField,\n TTransportId\n> & {\n /** Body path of the payload. Required. */\n readonly payload: BodyField;\n /**\n * Event headers: a body path holding an object of strings, `'message-headers'` (default),\n * every message header that no other field maps, or `'top-level-fields'`, spread over the top\n * level of the body: every top-level text field that no other value uses is read as one.\n */\n readonly headers?: BodyField | 'message-headers' | 'top-level-fields';\n /**\n * Values written with every message besides the mapped ones, such as a constant\n * `provider: 'orders-api'` or a second copy of the time. They are never read; extra headers\n * are left out of the event headers on read.\n */\n readonly extra?: { readonly body?: ExtraBody; readonly headers?: ExtraHeaders };\n /**\n * Top-level body fields to write first, in this order; the others follow in the order they\n * are written. Only the bytes change, for formats compared byte for byte.\n */\n readonly bodyOrder?: readonly string[];\n /**\n * Keeps the top-level body fields that no other value uses (and that are not read as event\n * headers) with every JSON type, in body order, as one object under `payloadField` of the\n * payload: `{ payloadField: 'wire' }` reads `{ \"data\": { \"a\": 1 }, \"attempt\": 2 }` as the payload\n * `{ \"a\": 1, \"wire\": { \"attempt\": 2 } }`, so the handler's schema validates them with the payload.\n * Writing spreads that object back over the top level. Default: such fields are left out on read.\n */\n readonly otherFields?: OtherFields;\n};\n\n/** Where {@link BodyEnvelopeMapping.otherFields} keeps the unused top-level fields. */\nexport type OtherFields = { readonly payloadField: string };\n\n/**\n * The body is the payload itself, as a plain JSON producer writes it; every other value lives in\n * a header, so body paths are a compile error here.\n */\nexport type PayloadOnlyMapping<TTransportId extends string> = MappingFields<\n HeaderField,\n TTransportId\n> & {\n readonly payload: 'whole-body';\n /** Event headers: every message header that no other field maps. */\n readonly headers?: 'message-headers';\n /** Message headers written with every message; never read, and left out of the event headers. */\n readonly extra?: { readonly headers?: ExtraHeaders };\n};\n\n/** Where every envelope value lives in a JSON message. `type`, `id` and `payload` are required. */\nexport type JsonEnvelopeMapping<TTransportId extends string> =\n BodyEnvelopeMapping<TTransportId> | PayloadOnlyMapping<TTransportId>;\n\n/** A JSON message: the parsed body and the text headers. */\nexport type JsonWireMessage = { readonly body: unknown; readonly headers: EventHeaders };\n\n/** The values read from a message. An absent optional value is left to the transport's default. */\nexport type JsonEnvelopeFields = {\n readonly id?: string;\n readonly type: string;\n readonly payload: unknown;\n readonly key?: string;\n readonly source?: string;\n readonly headers: EventHeaders;\n readonly correlationId: string | null;\n readonly causationId: string | null;\n readonly occurredAt?: Date;\n};\n\n/** The errors of the calling transport. */\nexport type JsonEnvelopeFailures = {\n /** For a message that cannot be read: it goes to the invalid-message path. */\n readonly invalid: (reason: string) => Error;\n /** For an event that cannot be written: never retried. */\n readonly unencodable: (reason: string) => Error;\n};\n\n/** Writes and reads one mapping. Created once per codec; both methods are pure. */\nexport interface JsonEnvelopeFormat {\n /** The mapped headers and the body; the id is left out when the transport supplies it. */\n write(envelope: EventEnvelope): JsonWireMessage;\n read(message: JsonWireMessage): JsonEnvelopeFields;\n}\n\n/**\n * Compiles `mapping` once. `transportIds` lists the transport's own id strategies.\n *\n * @throws ConfigurationError for a mapping that is incomplete, names a header twice, nests one\n * body path inside another or mixes array indexes and names under one body field.\n */\nexport function createJsonEnvelopeFormat(\n mapping: JsonEnvelopeMapping<string>,\n {\n transportIds,\n failures,\n }: { readonly transportIds: readonly string[]; readonly failures: JsonEnvelopeFailures },\n): JsonEnvelopeFormat {\n const plan = compile(mapping, transportIds);\n return {\n write: (envelope) => writeMessage(envelope, { plan, failures }),\n read: (message) => readMessage(message, { plan, failures }),\n };\n}\n","import type { LeaseReference } from '../event-store.js';\nimport { DeliveryLeaseIdentity } from '../values/delivery-lease-identity.js';\n\n/** What a ledger remembers of a claim: at least who it was handed to and which delivery. */\nexport interface HandedOutEntry {\n readonly owner: string;\n readonly deliveryId: string;\n}\n\n/**\n * The claims a store instance handed out and has not seen settled, keyed by\n * {@link DeliveryLeaseIdentity} (delivery id and exact lease token). After a failed claim the\n * store keeps exactly these listed as running and gives the rest back.\n */\nexport class HandedOutLedger<TEntry extends HandedOutEntry> {\n readonly #entries = new Map<string, TEntry>();\n\n register(lease: LeaseReference, entry: TEntry): void {\n this.#entries.set(DeliveryLeaseIdentity.of(lease.deliveryId, lease.leaseToken), entry);\n }\n\n /** Whether the claim with this identity ({@link DeliveryLeaseIdentity.of}) is handed out. */\n has(identity: string): boolean {\n return this.#entries.has(identity);\n }\n\n forget(lease: LeaseReference): void {\n this.#entries.delete(DeliveryLeaseIdentity.of(lease.deliveryId, lease.leaseToken));\n }\n\n /** Forgets every entry `settled` says is settled. */\n forgetWhere(settled: (entry: TEntry, identity: string) => boolean): void {\n for (const [identity, entry] of this.#entries) {\n if (settled(entry, identity)) {\n this.#entries.delete(identity);\n }\n }\n }\n\n /** The entries handed out to `owner`. */\n entriesOf(owner: string): TEntry[] {\n return [...this.#entries.values()].filter((entry) => entry.owner === owner);\n }\n}\n","import type { ClaimRequest, ClaimedDelivery } from '../event-store.js';\n\n/**\n * The claim skeleton of the database stores: a request for no handlers or no deliveries claims\n * nothing, and the claims of one owner run one after the other. Claims of one owner read the same\n * held lanes and the same bookkeeping of what was handed out, so they must not overlap (the\n * dispatcher claims one batch at a time anyway; `runOnce` next to a running dispatcher is what\n * this guards against). A store supplies only {@link OwnerSerializedClaims.claimInTurn}.\n */\nexport abstract class OwnerSerializedClaims {\n /** The last claim of each owner still running; the next one waits for it. */\n readonly #queues = new Map<string, Promise<void>>();\n\n claim(request: ClaimRequest): Promise<ClaimedDelivery[]> {\n if (this.claimsNothing(request)) {\n return Promise.resolve([]);\n }\n return this.#serialized(request.leaseOwner, () => this.claimInTurn(request));\n }\n\n /** Whether the request cannot claim anything: no handlers, or a limit that is not above 0. */\n protected claimsNothing(request: ClaimRequest): boolean {\n return request.handlers.length === 0 || !(request.limit > 0);\n }\n\n /** Claims for `request` once the earlier claims of its owner settled. */\n protected abstract claimInTurn(request: ClaimRequest): Promise<ClaimedDelivery[]>;\n\n #serialized<T>(owner: string, work: () => Promise<T>): Promise<T> {\n const previous = this.#queues.get(owner) ?? Promise.resolve();\n const run = previous.then(work, work);\n const tail = run.then(\n () => undefined,\n () => undefined,\n );\n this.#queues.set(owner, tail);\n void tail.then(() => {\n if (this.#queues.get(owner) === tail) {\n this.#queues.delete(owner);\n }\n });\n return run;\n }\n}\n","import type { EventEnvelope, EventHeaders } from '../event.js';\n\n/** The event a transport's decoder extracted from a message; see the transport's `DecodedEvent`. */\nexport interface DecodedEventFields {\n readonly id: string;\n readonly type: string;\n readonly payload: unknown;\n readonly source?: string;\n readonly key?: string | null;\n readonly headers?: EventHeaders;\n readonly correlationId?: string | null;\n readonly causationId?: string | null;\n readonly occurredAt?: Date;\n}\n\n/** A fixed value, or an extractor that reads it from a plain message. */\nexport type TextOption<TPlain, TValue extends string | null> =\n TValue | ((message: TPlain) => TValue | undefined) | undefined;\n\n/**\n * Observes the rejection of a promise an async decoder or extractor returned by\n * mistake: the value is refused as malformed, and an unobserved rejection would\n * otherwise crash the process.\n */\nexport function observeRejection(value: unknown): void {\n if (typeof value === 'object' && value !== null && 'then' in value) {\n Promise.resolve(value).catch(() => undefined);\n }\n}\n\n/**\n * The inbound plumbing a transport shares with every other: completing what a user decoder\n * returned and reading the extractor options of a plain JSON decoder. A transport supplies only its\n * malformed-message error and the defaults its messages carry (source, key, time).\n */\nexport abstract class DecodedEventReader<TMessage, TPlain> {\n /**\n * Fills the fields a decoder left out and guards against a decoder that returned no object,\n * which would otherwise surface as a retried `TypeError` instead of a malformed message.\n */\n complete(decoded: unknown, message: TMessage): EventEnvelope {\n if (typeof decoded !== 'object' || decoded === null) {\n throw this.invalid('The decoder must return an event object synchronously');\n }\n if ('then' in decoded) {\n observeRejection(decoded);\n throw this.invalid('The decoder must return an event object synchronously');\n }\n const event = decoded as DecodedEventFields;\n return {\n id: event.id,\n type: event.type,\n source: event.source ?? this.defaultSource(message),\n key: event.key === undefined ? this.defaultKey(message) : event.key,\n payload: event.payload,\n headers: event.headers ?? {},\n correlationId: event.correlationId ?? null,\n causationId: event.causationId ?? null,\n occurredAt: event.occurredAt ?? this.defaultTime(message),\n };\n }\n\n /** The text an option gives for `plain`; undefined when it gives none or `''`. */\n text<TValue extends string | null>(\n option: TextOption<TPlain, TValue>,\n { plain, name }: { readonly plain: TPlain; readonly name: string },\n ): string | undefined {\n const value: unknown = typeof option === 'function' ? option(plain) : option;\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== 'string') {\n observeRejection(value);\n throw this.invalid(`The ${name} option returned ${typeof value}, expected a string`);\n }\n return value.length === 0 ? undefined : value;\n }\n\n /** The error of a malformed message, which the transport dead-letters instead of retrying. */\n abstract invalid(reason: string): Error;\n\n protected abstract defaultSource(message: TMessage): string;\n\n protected abstract defaultKey(message: TMessage): string | null;\n\n protected abstract defaultTime(message: TMessage): Date;\n}\n","import type { EventEnvelope } from '../event.js';\nimport type { CloseOptions } from '../event-store.js';\nimport type {\n Transport,\n TransportMessageHandler,\n TransportSubscriptionHooks,\n} from '../transport.js';\n\n/** One subscription of a transport: what it consumes and where the messages go. */\nexport interface TransportSubscription {\n readonly destinations: readonly string[];\n readonly onMessage: TransportMessageHandler;\n readonly hooks: TransportSubscriptionHooks | undefined;\n}\n\n/**\n * The skeleton of a broker transport that publishes and subscribes: the {@link Transport} port\n * with its subscribe signature in one place. A transport supplies how it publishes, opens its one\n * subscription, reports readiness and closes.\n */\nexport abstract class SubscribingTransport implements Transport {\n abstract readonly name: string;\n abstract readonly system: string;\n\n /**\n * Subscribes to `destinations`. Not async itself: the subscription's own promise is returned\n * as it is, so its checks reject rather than throw.\n */\n // eslint-disable-next-line relaybus/max-two-params -- the Transport.subscribe signature\n subscribe(\n destinations: readonly string[],\n onMessage: TransportMessageHandler,\n hooks?: TransportSubscriptionHooks,\n ): Promise<void> {\n return this.openSubscription({ destinations, onMessage, hooks });\n }\n\n abstract publish(envelope: EventEnvelope, destination: string): Promise<void>;\n\n abstract isReady(): boolean;\n\n abstract close(options?: CloseOptions): Promise<void>;\n\n /** Opens the transport's one subscription; rejects when it cannot. */\n protected abstract openSubscription(subscription: TransportSubscription): Promise<void>;\n}\n","import { ConfigurationError } from '../errors.js';\n\n/** The range a {@link BoundedInteger} option allows. */\nexport interface IntegerBounds {\n readonly name: string;\n readonly minimum: number;\n readonly maximum: number;\n}\n\n/** An integer option with fixed lower and upper bounds. */\nexport abstract class BoundedInteger {\n /** Returns `value` when it is an integer within the bounds, else throws a {@link ConfigurationError}. */\n static of(value: number, { name, minimum, maximum }: IntegerBounds): number {\n if (!Number.isInteger(value) || value < minimum || value > maximum) {\n throw new ConfigurationError(\n `${name} must be an integer from ${minimum} to ${maximum}, received ${value}`,\n );\n }\n return value;\n }\n}\n","/**\n * Delays that double with every attempt, from `initialMs` up to `maxMs`: the first retry waits\n * `initialMs`, the second twice that, and so on. Without jitter, for in-process retries.\n */\nexport class ExponentialBackoff {\n readonly initialMs: number;\n readonly maxMs: number;\n\n constructor({ initialMs, maxMs }: { readonly initialMs: number; readonly maxMs: number }) {\n this.initialMs = initialMs;\n this.maxMs = maxMs;\n }\n\n /** The delay after failed attempt `attempt` (1-based). */\n delayFor(attempt: number): number {\n return Math.min(this.initialMs * 2 ** (attempt - 1), this.maxMs);\n }\n}\n","/** The claim a lane lease token names, as written in the token. */\nexport interface LaneLeaseTokenParts {\n readonly lane: number;\n /** The lane's epoch, as decimal text: PostgreSQL epochs exceed the safe integers. */\n readonly epoch: string;\n /** The claim generation of the delivery. */\n readonly claims: number;\n}\n\n/** How many digits each part of a token may have, and how many lanes there are. */\nexport interface LaneLeaseTokenLimits {\n readonly laneCount: number;\n readonly epochDigits: number;\n readonly claimsDigits: number;\n}\n\n/** Largest number of digits of a lane number. */\nconst LANE_DIGITS = 3;\n\n/**\n * The fencing token of a claim in a lane-leased store: `<lane>:<epoch>:<claims>`. Every state\n * change checks the lane epoch and the delivery's claim generation it names. A store creates one\n * format with its own digit limits and parses only the tokens it can have issued.\n */\nexport class LaneLeaseTokenFormat {\n readonly #pattern: RegExp;\n readonly #laneCount: number;\n\n constructor(limits: LaneLeaseTokenLimits) {\n this.#laneCount = limits.laneCount;\n this.#pattern = new RegExp(\n `^(\\\\d{1,${LANE_DIGITS}}):(\\\\d{1,${limits.epochDigits}}):(\\\\d{1,${limits.claimsDigits}})$`,\n );\n }\n\n format(\n lane: number,\n { epoch, claims }: { readonly epoch: string | number; readonly claims: number },\n ): string {\n return `${lane}:${epoch}:${claims}`;\n }\n\n /** The parts of `token`; undefined when the store cannot have issued it. */\n parse(token: string): LaneLeaseTokenParts | undefined {\n const match = this.#pattern.exec(token);\n if (match === null || Number(match[1]) >= this.#laneCount) {\n return undefined;\n }\n return { lane: Number(match[1]), epoch: match[2]!, claims: Number(match[3]) };\n }\n}\n","import { ConfigurationError } from '../errors.js';\n\n/** A text option that must not be empty: a name, an exchange, a queue. */\nexport abstract class NonEmptyText {\n static of(value: string, name: string): string {\n if (value.length === 0) {\n throw new ConfigurationError(`${name} must not be empty`);\n }\n return value;\n }\n\n /** Like {@link NonEmptyText.of}, for an option that may be left out. */\n static optional(value: string | undefined, name: string): string | undefined {\n return value === undefined ? undefined : NonEmptyText.of(value, name);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/internal/validation.ts","../../src/internal/field-extractors.ts","../../src/internal/cloudevents.ts","../../src/internal/json-envelope-wire-types.ts","../../src/internal/json-envelope-plan.ts","../../src/internal/json-envelope-other-fields.ts","../../src/internal/json-envelope-read.ts","../../src/internal/json-envelope-write.ts","../../src/internal/json-envelope.ts","../../src/store-kit/handed-out-ledger.ts","../../src/store-kit/owner-serialized-claims.ts","../../src/transport-kit/decoded-event-reader.ts","../../src/transport-kit/subscribing-transport.ts","../../src/values/bounded-integer.ts","../../src/values/exponential-backoff.ts","../../src/values/lane-lease-token.ts","../../src/values/non-empty-text.ts"],"names":["time","MILLISECONDS_PER_SECOND"],"mappings":";;;;AAGO,SAAS,qBAAA,CAAsB,OAAe,IAAA,EAAsB;AACzE,EAAA,OAAO,eAAA,CAAgB,EAAA,CAAG,KAAA,EAAO,IAAI,CAAA;AACvC;;;ACQO,SAAS,WACd,IAAA,EACqE;AACrE,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACrB,IAAA,MAAM,IAAI,mBAAmB,gCAAgC,CAAA;AAAA,EAC/D;AACA,EAAA,OAAO,CAAC,OAAA,KAAa,MAAA,CAAO,MAAA,CAAO,OAAA,CAAQ,OAAA,EAAS,IAAI,CAAA,GAAI,OAAA,CAAQ,OAAA,CAAQ,IAAI,CAAA,GAAI,MAAA;AACtF;AAcO,SAAS,iBACd,IAAA,EACgE;AAChE,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC/B,EAAA,IAAI,SAAS,IAAA,CAAK,CAAC,YAAY,OAAA,CAAQ,MAAA,KAAW,CAAC,CAAA,EAAG;AACpD,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,sEAAsE,IAAI,CAAA,CAAA;AAAA,KAC5E;AAAA,EACF;AACA,EAAA,OAAO,CAAC,OAAA,KAAY;AAClB,IAAA,IAAI,QAAQ,OAAA,CAAQ,OAAA;AACpB,IAAA,KAAA,MAAW,WA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KAAK,CAAA;AACtC,IAAA,IAAI,KAAA,KAAU,QAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA,IAAK,KAAK,UAAA,EAAY;AACzD,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA,EAAG,KAAA,EAAO,KAAA,CAAM,CAAC,GAAI,MAAA,EAAQ,MAAA,CAAO,KAAA,CAAM,CAAC,CAAC,CAAA,EAAE;AAAA,EAC9E;AACF;;;AC/CO,IAAe,YAAA,GAAf,MAAe,aAAA,CAAa;AAAA,EACjC,OAAO,EAAA,CAAG,KAAA,EAAe,IAAA,EAAsB;AAC7C,IAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,MAAA,MAAM,IAAI,kBAAA,CAAmB,CAAA,EAAG,IAAI,CAAA,kBAAA,CAAoB,CAAA;AAAA,IAC1D;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA,EAGA,OAAO,QAAA,CAAS,KAAA,EAA2B,IAAA,EAAkC;AAC3E,IAAA,OAAO,UAAU,MAAA,GAAY,MAAA,GAAY,aAAA,CAAa,EAAA,CAAG,OAAO,IAAI,CAAA;AAAA,EACtE;AACF","file":"index.js","sourcesContent":["import { PositiveInteger } from '../values/positive-integer.js';\n\n/** Returns `value` when it is an integer of at least 1, else throws a {@link ConfigurationError} naming the option. */\nexport function assertPositiveInteger(value: number, name: string): number {\n return PositiveInteger.of(value, name);\n}\n","import { ConfigurationError } from '../errors.js';\nimport type { EventHeaders } from '../event.js';\n\n/**\n * Reads one header of an incoming message, for the `type`, `id`, `key` or\n * `source` option of {@link plainJsonDecoder}. Header names are compared\n * exactly (Kafka and AMQP header names are case-sensitive). Returns undefined when the\n * header is absent, so the decoder falls back to its default.\n *\n * ```ts\n * plainJsonDecoder({ type: fromHeader('event-type'), id: fromHeader('message-id') })\n * ```\n */\nexport function fromHeader(\n name: string,\n): (message: { readonly headers: EventHeaders }) => string | undefined {\n if (name.length === 0) {\n throw new ConfigurationError('fromHeader needs a header name');\n }\n return (message) => (Object.hasOwn(message.headers, name) ? message.headers[name] : undefined);\n}\n\n/**\n * Reads a field of the JSON payload by a dotted path (`'meta.eventType'`), for\n * the `type`, `id`, `key` or `source` option of {@link plainJsonDecoder}. A\n * string is returned as is and a safe integer as its decimal text (numeric ids\n * are common). Anything else returns undefined so the decoder falls back to its\n * default: a missing field, and also a fraction or an integer beyond 2^53, which\n * JSON parsing may already have rounded, so two different ids could collide.\n *\n * ```ts\n * plainJsonDecoder({ type: fromPayloadField('eventType'), key: fromPayloadField('order.id') })\n * ```\n */\nexport function fromPayloadField(\n path: string,\n): (message: { readonly payload: unknown }) => string | undefined {\n const segments = path.split('.');\n if (segments.some((segment) => segment.length === 0)) {\n throw new ConfigurationError(\n `fromPayloadField needs a dotted path of non-empty names, received '${path}'`,\n );\n }\n return (message) => {\n let value = message.payload;\n for (const segment of segments) {\n if (typeof value !== 'object' || value === null || !Object.hasOwn(value, segment)) {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n if (typeof value === 'string') {\n return value;\n }\n return Number.isSafeInteger(value) ? String(value) : undefined;\n };\n}\n","import { assertEventType, type EventEnvelope } from '../event.js';\n\n/** The media type of a content type, without parameters and lower-cased; undefined for anything but a string. */\nexport function mediaTypeOf(contentType: unknown): string | undefined {\n return typeof contentType === 'string'\n ? contentType.split(';')[0]!.trim().toLowerCase()\n : undefined;\n}\n\nexport function isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Readers of structured CloudEvent attributes that fail with the error of the calling transport. */\nexport interface CloudEventReaders {\n readonly optionalAttribute: (body: Record<string, unknown>, name: string) => string | undefined;\n readonly requiredAttribute: (body: Record<string, unknown>, name: string) => string;\n readonly assertValidType: (type: string, label: string) => void;\n readonly assertJsonDataContentType: (dataContentType: string | undefined) => void;\n}\n\nexport function createCloudEventReaders(invalid: (reason: string) => Error): CloudEventReaders {\n const optionalAttribute = (body: Record<string, unknown>, name: string): string | undefined => {\n const value = body[name];\n if (value !== undefined && typeof value !== 'string') {\n throw invalid(`Attribute '${name}' must be a string`);\n }\n return value;\n };\n return {\n optionalAttribute,\n requiredAttribute: (body, name) => {\n const value = optionalAttribute(body, name);\n if (value === undefined || value.length === 0) {\n throw invalid(`Attribute '${name}' is missing or empty`);\n }\n return value;\n },\n assertValidType: (type, label) => {\n try {\n assertEventType(type);\n } catch (error) {\n throw invalid(`${label} is not a valid event type: ${(error as Error).message}`);\n }\n },\n assertJsonDataContentType: (dataContentType) => {\n const mediaType = mediaTypeOf(dataContentType);\n if (\n mediaType !== undefined &&\n mediaType !== 'application/json' &&\n mediaType !== 'text/json' &&\n !mediaType.endsWith('+json')\n ) {\n throw invalid(`datacontenttype must be JSON, received '${dataContentType}'`);\n }\n },\n };\n}\n\n/**\n * The JSON text of a CloudEvents 1.0 structured-mode event: the attributes (the key as `subject`,\n * correlation and causation ids as extension attributes), then `data`, the already serialized\n * payload, so the payload is serialized only once.\n */\nexport function writeStructuredCloudEvent(\n envelope: EventEnvelope,\n { time, data }: { readonly time: string; readonly data: string },\n): string {\n const attributes = {\n specversion: '1.0',\n id: envelope.id,\n type: envelope.type,\n source: envelope.source,\n time,\n datacontenttype: 'application/json',\n ...(envelope.key === null ? {} : { subject: envelope.key }),\n ...(envelope.correlationId === null ? {} : { correlationid: envelope.correlationId }),\n ...(envelope.causationId === null ? {} : { causationid: envelope.causationId }),\n };\n return `${JSON.stringify(attributes).slice(0, -1)},\"data\":${data}}`;\n}\n","import {\n ConfigurationError,\n WireTypeCollisionError,\n WireTypesUnsupportedError,\n} from '../errors.js';\nimport { assertEventType, type EventEnvelope } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport type { WireTypes } from './json-envelope.js';\nimport type { Context } from './json-envelope-plan.js';\n\n// The type names a format uses on the wire instead of relaybus event types (`wireTypes`).\n\n/** Event type to wire name, and wire name back to event type. */\nexport type WireTypePlan = {\n readonly wireTypes: ReadonlyMap<string, string>;\n readonly eventTypes: ReadonlyMap<string, string>;\n};\n\n/**\n * Compiles `wireTypes`: every key a valid event type, every value a non-empty name no other type\n * uses, and none with a fixed type, which is written nowhere.\n */\nexport function compileWireTypes(\n wireTypes: unknown,\n { fixed }: { readonly fixed: boolean },\n): WireTypePlan {\n if (wireTypes === undefined) {\n return { wireTypes: new Map(), eventTypes: new Map() };\n }\n if (!isJsonObject(wireTypes) || fixed) {\n throw new ConfigurationError(\n 'jsonEnvelope wireTypes must be an object of event type to wire name, with a type at { body } or { header }',\n );\n }\n const entries = Object.entries(wireTypes);\n const eventTypes = new Map<string, string>();\n for (const [type, wire] of entries) {\n assertEventType(type);\n if (typeof wire !== 'string' || wire.length === 0 || eventTypes.has(wire)) {\n throw new ConfigurationError(\n `jsonEnvelope wireTypes needs a non-empty wire name for '${type}' that no other type uses`,\n );\n }\n eventTypes.set(wire, type);\n }\n return { wireTypes: new Map(entries as [string, string][]), eventTypes };\n}\n\n/** The type as the wire carries it; an unlisted type that another type's wire name equals is refused. */\nexport function wireTypeOf(envelope: EventEnvelope, { plan, failures }: Context): string {\n const wire = plan.wireTypes.get(envelope.type);\n if (wire !== undefined) {\n return wire;\n }\n const other = plan.eventTypes.get(envelope.type);\n if (other !== undefined) {\n throw failures.unencodable(\n `Event ${envelope.id} has type '${envelope.type}', which wireTypes uses as the wire name of '${other}'`,\n );\n }\n return envelope.type;\n}\n\n/** The event type a wire type value names: a listed wire name, or a valid event type itself. */\nexport function eventTypeOf(wire: string, { plan, failures }: Context): string {\n const type = plan.eventTypes.get(wire);\n if (type !== undefined) {\n return type;\n }\n try {\n assertEventType(wire);\n } catch (error) {\n throw failures.invalid(`The event type is not a valid event type: ${(error as Error).message}`);\n }\n return wire;\n}\n\n/** A wire format that can take more wire names after it was created; see `declareWireTypes`. */\nexport type WireTypeAware<TCodec> = {\n readonly withWireTypes?: (wireTypes: Readonly<Record<string, string>>) => TCodec;\n};\n\n/**\n * The codec with `wireTypes` added to its own, for a transport's `declareWireTypes`. Throws\n * {@link WireTypesUnsupportedError} for a codec that cannot map type names.\n */\nexport function withDeclaredWireTypes<TCodec extends WireTypeAware<TCodec>>(\n codec: TCodec,\n {\n wireTypes,\n transport,\n }: { readonly wireTypes: Readonly<Record<string, string>>; readonly transport: string },\n): TCodec {\n if (codec.withWireTypes === undefined) {\n throw new WireTypesUnsupportedError(\n `The codec of transport '${transport}' cannot map event types to wire names; use jsonEnvelope with a type at { body } or { header }`,\n );\n }\n return codec.withWireTypes(wireTypes);\n}\n\n/**\n * The `wireTypes` of a mapping together with `declared` ones, for the `withWireTypes` of a\n * `jsonEnvelope` codec. A type may be declared again with the name it has; any other clash, or a\n * mapping with a fixed type, throws.\n */\nexport function mergeWireTypes(\n mapping: { readonly type: unknown; readonly wireTypes?: WireTypes | undefined },\n declared: Readonly<Record<string, string>>,\n): WireTypes {\n if (isJsonObject(mapping.type) && 'fixed' in mapping.type) {\n throw new WireTypesUnsupportedError(\n 'A jsonEnvelope with a fixed type writes no type, so it has no wire names to declare',\n );\n }\n const merged = new Map(Object.entries(mapping.wireTypes ?? {}));\n for (const [type, wire] of Object.entries(declared)) {\n assertDeclarable(merged, { type, wire });\n merged.set(type, wire);\n }\n return Object.fromEntries(merged);\n}\n\nfunction assertDeclarable(\n wireTypes: ReadonlyMap<string, string>,\n { type, wire }: { readonly type: string; readonly wire: string },\n): void {\n const current = wireTypes.get(type);\n if (current !== undefined && current !== wire) {\n throw new WireTypeCollisionError(\n `Event type '${type}' has the wire name '${current}' in the wireTypes of the codec and '${wire}' from a route or catalog`,\n );\n }\n const owner = [...wireTypes].find(([other, name]) => name === wire && other !== type);\n if (owner !== undefined) {\n throw new WireTypeCollisionError(\n `Event types '${owner[0]}' and '${type}' share the wire name '${wire}' in the codec and a route or catalog`,\n );\n }\n}\n","import { ConfigurationError } from '../errors.js';\nimport { assertEventType } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport { compileWireTypes, type WireTypePlan } from './json-envelope-wire-types.js';\nimport type {\n ExtraValue,\n FixedType,\n JsonConstant,\n JsonEnvelopeFailures,\n JsonEnvelopeMapping,\n TimeFormat,\n} from './json-envelope.js';\n\n// Compiling a jsonEnvelope mapping into the plan that writing and reading follow.\n\nexport type Location =\n | { readonly label: string; readonly header: string }\n | { readonly label: string; readonly path: readonly string[] };\n\nexport type OptionalName = 'key' | 'source' | 'occurredAt' | 'correlationId' | 'causationId';\nexport const OPTIONAL_NAMES: readonly OptionalName[] = [\n 'key',\n 'source',\n 'occurredAt',\n 'correlationId',\n 'causationId',\n];\n\nexport type Plan = {\n readonly type: Location | FixedType;\n /** Undefined when the transport supplies the id. */\n readonly id: Location | undefined;\n /** Whether a message without the mapped id gets the transport's own id instead. */\n readonly idWhenMissing: boolean;\n readonly optional: Readonly<Partial<Record<OptionalName, Location>>>;\n /** Undefined when the payload is the whole body. */\n readonly payload: readonly string[] | undefined;\n /** Undefined when event headers are the unmapped message headers or top-level fields. */\n readonly headers: readonly string[] | undefined;\n /** Whether event headers are spread over the top level of the body. */\n readonly topLevelHeaders: boolean;\n /** Top-level body names a mapped, payload, headers or extra value uses. */\n readonly topLevelNames: ReadonlySet<string>;\n /** Headers the mapping writes itself: the mapped ones and the extra ones. */\n readonly mappedHeaders: ReadonlySet<string>;\n readonly timeFormat: TimeFormat;\n readonly extraBody: readonly ExtraBodyValue[];\n readonly extraHeaders: readonly (readonly [string, ExtraValue<string>])[];\n readonly bodyOrder: readonly string[];\n /** The payload field that keeps the unused top-level fields; undefined when they are left out. */\n readonly otherFields: string | undefined;\n} & WireTypePlan;\n\n/** An extra body value at its path. */\nexport type ExtraBodyValue = {\n readonly path: readonly string[];\n readonly value: ExtraValue<JsonConstant>;\n};\n\nconst TIME_FORMATS: readonly TimeFormat[] = ['rfc3339', 'epoch-millis', 'epoch-seconds'];\n\nexport const ARRAY_INDEX = /^(?:0|[1-9]\\d*)$/;\n\n/** A compiled mapping with the errors of the calling transport. */\nexport type Context = { readonly plan: Plan; readonly failures: JsonEnvelopeFailures };\n\nexport function compile(\n mapping: JsonEnvelopeMapping<string>,\n transportIds: readonly string[],\n): Plan {\n if (!isJsonObject(mapping)) {\n throw new ConfigurationError('jsonEnvelope needs a mapping object');\n }\n const optional: Partial<Record<OptionalName, Location>> = {};\n for (const name of OPTIONAL_NAMES) {\n const field = mapping[name];\n if (field !== undefined) {\n optional[name] = toLocation(field, name);\n }\n }\n const payload = compilePayload(mapping.payload);\n const topLevelHeaders = mapping.headers === 'top-level-fields';\n if (topLevelHeaders && payload === undefined) {\n throw new ConfigurationError(\"jsonEnvelope headers 'top-level-fields' needs a body payload\");\n }\n const type = compileType(mapping.type);\n const plan: Plan = {\n type,\n id: compileId(mapping.id, transportIds),\n idWhenMissing: isJsonObject(mapping.id) && 'whenMissing' in mapping.id,\n optional,\n payload,\n headers: topLevelHeaders ? undefined : compileHeaders(mapping.headers),\n topLevelHeaders,\n topLevelNames: new Set(),\n mappedHeaders: new Set(),\n timeFormat: compileTimeFormat(mapping.occurredAt),\n otherFields: compileOtherFields(mapping, payload !== undefined),\n ...compileWireTypes(mapping.wireTypes, { fixed: 'fixed' in type }),\n ...compileExtras(mapping, payload !== undefined),\n };\n return assertDisjoint(plan);\n}\n\nfunction compileTimeFormat(field: unknown): TimeFormat {\n const format = isJsonObject(field) ? field['format'] : undefined;\n if (format === undefined) {\n return 'rfc3339';\n }\n if (!TIME_FORMATS.includes(format as TimeFormat)) {\n throw new ConfigurationError(\n `jsonEnvelope occurredAt format must be one of ${TIME_FORMATS.map((name) => `'${name}'`).join(', ')}`,\n );\n }\n return format as TimeFormat;\n}\n\n/** The extra values and the body order; a payload-only mapping has no body to put them in. */\nfunction compileExtras(\n mapping: JsonEnvelopeMapping<string>,\n hasBody: boolean,\n): Pick<Plan, 'extraBody' | 'extraHeaders' | 'bodyOrder'> {\n const extra = (mapping.extra ?? {}) as {\n readonly body?: Readonly<Record<string, ExtraValue<JsonConstant>>>;\n readonly headers?: Readonly<Record<string, ExtraValue<string>>>;\n };\n const bodyOrder = (mapping as { readonly bodyOrder?: readonly string[] }).bodyOrder ?? [];\n if (!hasBody && (extra.body !== undefined || bodyOrder.length > 0)) {\n throw new ConfigurationError(\n 'jsonEnvelope with a whole-body payload has no body for extra values or a body order',\n );\n }\n return {\n extraBody: Object.entries(extra.body ?? {}).map(([path, value]) => ({\n path: toPath(path, 'extra body value'),\n value,\n })),\n extraHeaders: Object.entries(extra.headers ?? {}),\n bodyOrder,\n };\n}\n\nfunction compileOtherFields(\n mapping: JsonEnvelopeMapping<string>,\n hasBody: boolean,\n): string | undefined {\n const otherFields: unknown = (mapping as { readonly otherFields?: unknown }).otherFields;\n if (otherFields === undefined) {\n return undefined;\n }\n if (!hasBody) {\n throw new ConfigurationError('jsonEnvelope otherFields needs a body payload');\n }\n const field = isJsonObject(otherFields) ? otherFields['payloadField'] : undefined;\n if (typeof field !== 'string' || field.length === 0) {\n throw new ConfigurationError(\"jsonEnvelope otherFields must be { payloadField: '<name>' }\");\n }\n return field;\n}\n\nfunction compileType(type: unknown): Location | FixedType {\n if (isJsonObject(type) && typeof type['fixed'] === 'string') {\n assertEventType(type['fixed']);\n return { fixed: type['fixed'] };\n }\n if (type === undefined) {\n throw new ConfigurationError('jsonEnvelope needs a type: { body }, { header } or { fixed }');\n }\n return toLocation(type, 'type');\n}\n\nfunction compileId(id: unknown, transportIds: readonly string[]): Location | undefined {\n if (typeof id === 'string' && transportIds.includes(id)) {\n return undefined;\n }\n const names = transportIds.map((name) => `'${name}'`).join(', ');\n if (!isJsonObject(id)) {\n throw new ConfigurationError(\n `jsonEnvelope needs an id: { body }, { header } or one of ${names}`,\n );\n }\n if ('whenMissing' in id && !transportIds.includes(id['whenMissing'] as string)) {\n throw new ConfigurationError(`jsonEnvelope id whenMissing must be one of ${names}`);\n }\n return toLocation(id, 'id');\n}\n\nfunction compilePayload(payload: unknown): readonly string[] | undefined {\n if (payload === 'whole-body') {\n return undefined;\n }\n if (!isJsonObject(payload) || typeof payload['body'] !== 'string') {\n throw new ConfigurationError(\n \"jsonEnvelope needs a payload: { body: '<path>' } or 'whole-body'\",\n );\n }\n return toPath(payload['body'], 'payload');\n}\n\nfunction compileHeaders(headers: unknown): readonly string[] | undefined {\n if (headers === undefined || headers === 'message-headers') {\n return undefined;\n }\n if (!isJsonObject(headers) || typeof headers['body'] !== 'string') {\n throw new ConfigurationError(\n \"jsonEnvelope headers must be { body: '<path>' } or 'message-headers'\",\n );\n }\n return toPath(headers['body'], 'headers');\n}\n\nfunction toLocation(field: unknown, label: string): Location {\n if (isJsonObject(field) && typeof field['header'] === 'string' && field['header'].length > 0) {\n return { label, header: field['header'] };\n }\n if (isJsonObject(field) && typeof field['body'] === 'string') {\n return { label, path: toPath(field['body'], label) };\n }\n throw new ConfigurationError(\n `jsonEnvelope ${label} must be { body: '<path>' } or { header: '<name>' }`,\n );\n}\n\nfunction toPath(path: string, label: string): readonly string[] {\n const segments = path.split('.');\n if (segments.some((segment) => segment.length === 0)) {\n throw new ConfigurationError(\n `jsonEnvelope ${label} needs a dotted path of non-empty names, received '${path}'`,\n );\n }\n return segments;\n}\n\n/** Collects the mapped headers and refuses overlapping locations, which would overwrite each other. */\nfunction assertDisjoint(plan: Plan): Plan {\n const locations = [plan.type, plan.id, ...Object.values(plan.optional)].filter(\n (location): location is Location => location !== undefined && !('fixed' in location),\n );\n const headers = [\n ...locations.flatMap((location) => ('header' in location ? [location.header] : [])),\n ...plan.extraHeaders.map(([name]) => name),\n ];\n const duplicate = headers.find((name, index) => headers.indexOf(name) !== index);\n if (duplicate !== undefined) {\n throw new ConfigurationError(`jsonEnvelope maps header '${duplicate}' twice`);\n }\n const paths = [\n ...locations.flatMap((location) => ('path' in location ? [location.path] : [])),\n ...[plan.payload, plan.headers].filter((path) => path !== undefined),\n ...plan.extraBody.map(({ path }) => path),\n ];\n assertNoNestedPaths(paths);\n return {\n ...plan,\n mappedHeaders: new Set(headers),\n topLevelNames: new Set(paths.map((path) => path[0]!)),\n };\n}\n\nfunction assertNoNestedPaths(paths: readonly (readonly string[])[]): void {\n paths.forEach((path, index) => {\n for (const other of paths.slice(index + 1)) {\n assertCompatiblePaths(path, other);\n }\n });\n}\n\n/** Two body paths must part ways, and where they do, both index an array or both name a field. */\nfunction assertCompatiblePaths(path: readonly string[], other: readonly string[]): void {\n const parting = path.findIndex((segment, position) => segment !== other[position]);\n const both = `'${path.join('.')}' and '${other.join('.')}'`;\n if (parting === -1 || parting === other.length) {\n throw new ConfigurationError(`jsonEnvelope body paths ${both} overlap`);\n }\n if (ARRAY_INDEX.test(path[parting]!) !== ARRAY_INDEX.test(other[parting]!)) {\n throw new ConfigurationError(`jsonEnvelope body paths ${both} mix an array index and a name`);\n }\n}\n","import type { EventEnvelope } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport type { Context } from './json-envelope-plan.js';\n\n// The top-level body fields no mapped value uses, kept under one payload field (`otherFields`).\n\n/** The top-level fields of `body` no other value uses and that are not read as event headers. */\nfunction unusedFields(body: Record<string, unknown>, { plan }: Context): [string, unknown][] {\n return Object.entries(body).filter(\n ([name, value]) =>\n !plan.topLevelNames.has(name) && !(plan.topLevelHeaders && typeof value === 'string'),\n );\n}\n\n/**\n * The payload read from `body` with the unused top-level fields under the `otherFields` field. An\n * object payload always gets the field (empty when there are none), so its shape does not depend on\n * the message; a payload that is not an object stays as it is when there is nothing to keep.\n */\nexport function withOtherFields(\n payload: unknown,\n { body, context }: { readonly body: Record<string, unknown>; readonly context: Context },\n): unknown {\n const field = context.plan.otherFields;\n if (field === undefined) {\n return payload;\n }\n const fields = unusedFields(body, context);\n if (!isJsonObject(payload) && fields.length === 0) {\n return payload;\n }\n if (!isJsonObject(payload) || Object.hasOwn(payload, field)) {\n throw context.failures.invalid(\n `otherFields keeps the unused top-level fields under the payload field '${field}', but the payload is not an object without that field`,\n );\n }\n return Object.fromEntries([...Object.entries(payload), [field, Object.fromEntries(fields)]]);\n}\n\n/** The payload to write and the fields to spread over the top level, split at `otherFields`. */\nexport function splitOtherFields(\n envelope: EventEnvelope,\n context: Context,\n): { readonly payload: unknown; readonly fields: readonly [string, unknown][] } {\n const field = context.plan.otherFields;\n const { payload } = envelope;\n if (field === undefined || !isJsonObject(payload) || !Object.hasOwn(payload, field)) {\n return { payload, fields: [] };\n }\n const others = payload[field];\n if (!isJsonObject(others)) {\n throw context.failures.unencodable(\n `Event ${envelope.id} has a payload field '${field}' that is not an object of top-level fields`,\n );\n }\n const fields = Object.entries(others);\n const refused = fields.find((entry) => isRefused(entry, context));\n if (refused !== undefined) {\n throw context.failures.unencodable(\n `Event ${envelope.id} keeps a top-level field '${refused[0]}' under '${field}' that the mapping reads as another value`,\n );\n }\n return {\n payload: Object.fromEntries(Object.entries(payload).filter(([name]) => name !== field)),\n fields,\n };\n}\n\n/** A name another value uses, or text that would read back as an event header. */\nfunction isRefused([name, value]: readonly [string, unknown], { plan }: Context): boolean {\n return plan.topLevelNames.has(name) || (plan.topLevelHeaders && typeof value === 'string');\n}\n","import type { EventHeaders } from '../event.js';\nimport { isJsonObject } from './cloudevents.js';\nimport type { JsonEnvelopeFailures, JsonEnvelopeFields, JsonWireMessage } from './json-envelope.js';\nimport type { Context, Location, Plan } from './json-envelope-plan.js';\nimport { withOtherFields } from './json-envelope-other-fields.js';\nimport { eventTypeOf } from './json-envelope-wire-types.js';\n\n// Reading the envelope fields of a JSON message by a compiled mapping.\n\nconst RFC3339_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/i;\nconst EPOCH_PATTERN = /^\\d+$/;\nconst MILLISECONDS_PER_SECOND = 1000;\n\nexport function readMessage(message: JsonWireMessage, context: Context): JsonEnvelopeFields {\n const { plan, failures } = context;\n if (plan.payload !== undefined && !isJsonObject(message.body)) {\n throw failures.invalid('The message body must be a JSON object');\n }\n const read = (location: Location | undefined): string | undefined =>\n location === undefined ? undefined : readText(message, { location, failures });\n const fields: Record<string, unknown> = {\n id: readId(read(plan.id), context),\n type: readType(message, context),\n payload: readPayload(message.body, context),\n key: read(plan.optional.key),\n source: read(plan.optional.source),\n headers: readEventHeaders(message, plan),\n correlationId: read(plan.optional.correlationId) ?? null,\n causationId: read(plan.optional.causationId) ?? null,\n occurredAt: readTime(read(plan.optional.occurredAt), context),\n };\n return Object.fromEntries(\n Object.entries(fields).filter((entry) => entry[1] !== undefined),\n ) as JsonEnvelopeFields;\n}\n\nfunction readId(id: string | undefined, { plan, failures }: Context): string | undefined {\n if (plan.id === undefined || plan.idWhenMissing) {\n return id;\n }\n return requireText(id, { location: plan.id, failures });\n}\n\nfunction readType(message: JsonWireMessage, { plan, failures }: Context): string {\n if ('fixed' in plan.type) {\n return plan.type.fixed;\n }\n const location = plan.type;\n const wire = requireText(readText(message, { location, failures }), { location, failures });\n return eventTypeOf(wire, { plan, failures });\n}\n\nfunction readPayload(body: unknown, { plan, failures }: Context): unknown {\n if (plan.payload === undefined) {\n return body;\n }\n const payload = valueAt(body, plan.payload);\n if (payload === undefined) {\n throw failures.invalid(`The message has no payload at '${plan.payload.join('.')}'`);\n }\n return withOtherFields(payload, {\n body: body as Record<string, unknown>,\n context: { plan, failures },\n });\n}\n\nfunction readEventHeaders(message: JsonWireMessage, plan: Plan): EventHeaders {\n if (plan.topLevelHeaders) {\n return textEntries(\n Object.entries(message.body as Record<string, unknown>).filter(\n ([name]) => !plan.topLevelNames.has(name),\n ),\n );\n }\n if (plan.headers === undefined) {\n return Object.fromEntries(\n Object.entries(message.headers).filter(([name]) => !plan.mappedHeaders.has(name)),\n );\n }\n const headers = valueAt(message.body, plan.headers);\n return isJsonObject(headers) ? textEntries(Object.entries(headers)) : {};\n}\n\nfunction textEntries(entries: readonly [string, unknown][]): EventHeaders {\n return Object.fromEntries(\n entries.filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n );\n}\n\nfunction readTime(text: string | undefined, { plan, failures }: Context): Date | undefined {\n if (text === undefined) {\n return undefined;\n }\n if (plan.timeFormat !== 'rfc3339') {\n const time = new Date(\n Number(text) * (plan.timeFormat === 'epoch-seconds' ? MILLISECONDS_PER_SECOND : 1),\n );\n if (!EPOCH_PATTERN.test(text) || Number.isNaN(time.getTime())) {\n throw failures.invalid(`The event time is not a whole ${plan.timeFormat} number: '${text}'`);\n }\n return time;\n }\n const time = new Date(text);\n if (!RFC3339_PATTERN.test(text) || Number.isNaN(time.getTime())) {\n throw failures.invalid(`The event time is not an RFC 3339 timestamp: '${text}'`);\n }\n return time;\n}\n\n/** A string, or a safe integer as its decimal text; undefined when absent, null or empty. */\nfunction readText(\n message: JsonWireMessage,\n { location, failures }: { readonly location: Location; readonly failures: JsonEnvelopeFailures },\n): string | undefined {\n const value =\n 'header' in location\n ? Object.hasOwn(message.headers, location.header)\n ? message.headers[location.header]\n : undefined\n : valueAt(message.body, location.path);\n if (value === undefined || value === null || value === '') {\n return undefined;\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' && Number.isSafeInteger(value)) {\n return String(value);\n }\n throw failures.invalid(`The ${location.label} at ${describe(location)} must be a string`);\n}\n\nfunction requireText(\n value: string | undefined,\n { location, failures }: { readonly location: Location; readonly failures: JsonEnvelopeFailures },\n): string {\n if (value === undefined) {\n throw failures.invalid(`The message has no ${location.label} at ${describe(location)}`);\n }\n return value;\n}\n\nfunction describe(location: Location): string {\n return 'header' in location ? `header '${location.header}'` : `'${location.path.join('.')}'`;\n}\n\nfunction valueAt(body: unknown, path: readonly string[]): unknown {\n let value = body;\n for (const segment of path) {\n if (typeof value !== 'object' || value === null || !Object.hasOwn(value, segment)) {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n}\n","import type { EventEnvelope } from '../event.js';\nimport type { JsonEnvelopeFailures, JsonWireMessage, TimeFormat } from './json-envelope.js';\nimport {\n ARRAY_INDEX,\n type Context,\n type Location,\n type OptionalName,\n type Plan,\n} from './json-envelope-plan.js';\nimport { splitOtherFields } from './json-envelope-other-fields.js';\nimport { wireTypeOf } from './json-envelope-wire-types.js';\n\n// Writing an envelope as a JSON message by a compiled mapping.\n\n/** RFC 3339 years have four digits. */\nconst MAXIMUM_RFC3339_YEAR = 9999;\nconst MILLISECONDS_PER_SECOND = 1000;\n\nexport function writeMessage(\n envelope: EventEnvelope,\n { plan, failures }: Context,\n): JsonWireMessage {\n const root: Record<string, unknown> = {};\n const headers: [string, string][] = [];\n const put = (location: Location, value: string | number): void => {\n if ('header' in location) {\n headers.push([location.header, String(value)]);\n } else {\n setAt(root, { path: location.path, value });\n }\n };\n const typeAt = typeLocation(envelope, { plan, failures });\n if (typeAt !== undefined) {\n put(typeAt, wireTypeOf(envelope, { plan, failures }));\n }\n if (plan.id !== undefined) {\n put(plan.id, envelope.id);\n }\n for (const [name, value] of optionalValues(envelope, { plan, failures })) {\n const location = plan.optional[name];\n if (location !== undefined && value !== null) {\n put(location, value);\n }\n }\n return {\n body: writeBody(envelope, { plan, failures, root }),\n headers: Object.fromEntries([\n ...eventHeaderEntries(envelope, { plan, failures }),\n ...headers,\n ...extraHeaderEntries(envelope, plan),\n ]),\n };\n}\n\n/** Where the type is written; a fixed type is written nowhere and refuses any other type. */\nfunction typeLocation(envelope: EventEnvelope, { plan, failures }: Context): Location | undefined {\n if (!('fixed' in plan.type)) {\n return plan.type;\n }\n if (envelope.type !== plan.type.fixed) {\n throw failures.unencodable(\n `Event ${envelope.id} has type '${envelope.type}', but this route carries only '${plan.type.fixed}'`,\n );\n }\n return undefined;\n}\n\nfunction extraHeaderEntries(envelope: EventEnvelope, plan: Plan): [string, string][] {\n return plan.extraHeaders.map(([name, value]) => [\n name,\n typeof value === 'function' ? value(envelope) : value,\n ]);\n}\n\nfunction optionalValues(\n envelope: EventEnvelope,\n { plan, failures }: Context,\n): [OptionalName, string | number | null][] {\n return [\n ['key', envelope.key],\n ['source', envelope.source],\n [\n 'occurredAt',\n timeValue(formatTime(envelope, failures), { envelope, format: plan.timeFormat }),\n ],\n ['correlationId', envelope.correlationId],\n ['causationId', envelope.causationId],\n ];\n}\n\n/** The body: the payload alone, or every mapped, extra, header and kept field in body order. */\nfunction writeBody(\n envelope: EventEnvelope,\n { plan, failures, root }: Context & { readonly root: Record<string, unknown> },\n): unknown {\n const { payload, fields } = splitOtherFields(envelope, { plan, failures });\n if (plan.payload === undefined) {\n return payload;\n }\n setAt(root, { path: plan.payload, value: payload });\n if (plan.headers !== undefined) {\n setAt(root, {\n path: plan.headers,\n value: Object.fromEntries(Object.entries(envelope.headers)),\n });\n }\n for (const { path, value } of plan.extraBody) {\n setAt(root, { path, value: typeof value === 'function' ? value(envelope) : value });\n }\n if (plan.topLevelHeaders) {\n spreadHeaders(envelope, { plan, failures, root });\n }\n spreadOtherFields(envelope, { failures, fields, root });\n return ordered(root, plan.bodyOrder);\n}\n\n/** Event headers spread over the top level of the body, last; a name another value uses is refused. */\nfunction spreadHeaders(\n envelope: EventEnvelope,\n { plan, failures, root }: Context & { readonly root: Record<string, unknown> },\n): void {\n for (const [name, value] of Object.entries(envelope.headers)) {\n if (plan.topLevelNames.has(name)) {\n throw failures.unencodable(\n `Event ${envelope.id} has a header '${name}', which the mapping uses for another body field`,\n );\n }\n setAt(root, { path: [name], value });\n }\n}\n\n/** The fields `otherFields` kept, spread over the top level after everything else; a taken name is refused. */\nfunction spreadOtherFields(\n envelope: EventEnvelope,\n {\n failures,\n fields,\n root,\n }: {\n readonly failures: JsonEnvelopeFailures;\n readonly fields: readonly [string, unknown][];\n readonly root: Record<string, unknown>;\n },\n): void {\n for (const [name, value] of fields) {\n if (Object.hasOwn(root, name)) {\n throw failures.unencodable(\n `Event ${envelope.id} keeps a top-level field '${name}' that an event header also writes`,\n );\n }\n setAt(root, { path: [name], value });\n }\n}\n\n/** The time as the format writes it; the RFC 3339 text is checked first either way. */\nfunction timeValue(\n text: string,\n { envelope, format }: { readonly envelope: EventEnvelope; readonly format: TimeFormat },\n): string | number {\n const milliseconds = envelope.occurredAt.getTime();\n if (format === 'epoch-millis') {\n return milliseconds;\n }\n return format === 'epoch-seconds' ? Math.floor(milliseconds / MILLISECONDS_PER_SECOND) : text;\n}\n\n/** The body with the listed top-level fields first, in the listed order, spread headers and kept fields included. */\nfunction ordered(root: Record<string, unknown>, order: readonly string[]): Record<string, unknown> {\n if (order.length === 0) {\n return root;\n }\n const result: Record<string, unknown> = {};\n const names = [...order.filter((name) => Object.hasOwn(root, name)), ...Object.keys(root)];\n for (const name of names) {\n if (!Object.hasOwn(result, name)) {\n defineValue(result, { name, value: root[name] });\n }\n }\n return result;\n}\n\n/** The event headers that travel as message headers; a name a mapped field uses is refused. */\nfunction eventHeaderEntries(\n envelope: EventEnvelope,\n { plan, failures }: Context,\n): [string, string][] {\n if (plan.headers !== undefined || plan.topLevelHeaders) {\n return [];\n }\n const entries = Object.entries(envelope.headers);\n const taken = entries.find(([name]) => plan.mappedHeaders.has(name));\n if (taken !== undefined) {\n throw failures.unencodable(\n `Event ${envelope.id} has a header '${taken[0]}', which the mapping uses for another field`,\n );\n }\n return entries;\n}\n\nfunction formatTime(envelope: EventEnvelope, failures: JsonEnvelopeFailures): string {\n const year = envelope.occurredAt.getUTCFullYear();\n if (Number.isNaN(year) || year < 0 || year > MAXIMUM_RFC3339_YEAR) {\n throw failures.unencodable(\n `Event ${envelope.id} has an occurredAt that is not an RFC 3339 instant (invalid date or year outside 0..9999)`,\n );\n }\n return envelope.occurredAt.toISOString();\n}\n\n/** Sets a value at a path, creating objects (arrays before an index segment) as own properties. */\nfunction setAt(\n root: Record<string, unknown>,\n { path, value }: { readonly path: readonly string[]; readonly value: unknown },\n): void {\n let container = root;\n for (const [index, segment] of path.slice(0, -1).entries()) {\n if (!Object.hasOwn(container, segment)) {\n defineValue(container, {\n name: segment,\n value: ARRAY_INDEX.test(path[index + 1]!) ? [] : {},\n });\n }\n container = container[segment] as Record<string, unknown>;\n }\n defineValue(container, { name: path.at(-1)!, value });\n}\n\n/** defineProperty, because assigning `__proto__` would set the prototype instead of a field. */\nfunction defineValue(\n target: Record<string, unknown>,\n { name, value }: { readonly name: string; readonly value: unknown },\n): void {\n Object.defineProperty(target, name, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n","import type { EventEnvelope, EventHeaders } from '../event.js';\nimport { compile } from './json-envelope-plan.js';\nimport { readMessage } from './json-envelope-read.js';\nimport { writeMessage } from './json-envelope-write.js';\n\n/**\n * A field of the JSON body, by dotted path: `'eventName'`, `'meta.correlationId'`. A segment that\n * is a whole number indexes an array: `'messageType.0'` is the first element of `messageType`.\n */\nexport type BodyField = { readonly body: string };\n/** A message header (Kafka record header, AMQP message header), by exact name. */\nexport type HeaderField = { readonly header: string };\n/** Where one envelope value lives on the wire. */\nexport type WireField = BodyField | HeaderField;\n/** The one event type every message of the route carries: written nowhere, used for every message read. */\nexport type FixedType = { readonly fixed: string };\n\n/**\n * How `occurredAt` travels: RFC 3339 text (default), or whole epoch milliseconds or seconds, a\n * number in the body and decimal text in a header. Epoch seconds drop the milliseconds.\n */\nexport type TimeFormat = 'rfc3339' | 'epoch-millis' | 'epoch-seconds';\n/** Where the event time lives, and in which format. */\nexport type TimeField<TField extends WireField> = TField & { readonly format?: TimeFormat };\n\n/** A JSON value written as it is. */\nexport type JsonConstant =\n | string\n | number\n | boolean\n | null\n | readonly JsonConstant[]\n | { readonly [name: string]: JsonConstant };\n/** A value written with every message: a constant, or derived from the event. */\nexport type ExtraValue<TValue> = TValue | ((envelope: EventEnvelope) => TValue);\n/** Extra message headers, by name. */\nexport type ExtraHeaders = Readonly<Record<string, ExtraValue<string>>>;\n/** Extra body values, by dotted path. */\nexport type ExtraBody = Readonly<Record<string, ExtraValue<JsonConstant>>>;\n\ntype MappingFields<TField extends WireField, TTransportId extends string> = {\n /** Where the event type lives, or the one type of the route. Required. */\n readonly type: TField | FixedType;\n /**\n * Where the event id lives, or the transport's own message identity (see the transport's\n * mapping type). Required, so the inbox dedup key is always a deliberate choice. A message\n * whose mapped id is missing is malformed, unless `whenMissing` names the transport's own id\n * to use instead: `{ body: 'id', whenMissing: 'record-position' }`.\n */\n readonly id: TField | TTransportId | (TField & { readonly whenMissing: TTransportId });\n /** Ordering key. Default: the transport's own (the Kafka record key; none on RabbitMQ). */\n readonly key?: TField;\n /** Producing service. Default: the transport's own (Kafka topic; RabbitMQ `appId`, else the routing key). */\n readonly source?: TField;\n /**\n * Event time, RFC 3339 unless `format` says otherwise. Default: the transport's own (Kafka\n * record timestamp; RabbitMQ `timestamp`, seconds).\n */\n readonly occurredAt?: TimeField<TField>;\n readonly correlationId?: TField;\n readonly causationId?: TField;\n /** Media type written with the message. Default `application/json`. Not checked on read. */\n readonly contentType?: string;\n /**\n * Wire names of event types, for a format whose type values are not relaybus event types or\n * name them otherwise: `{ 'transfer.auto-dispatched.v1': 'Transfer Auto Dispatched' }`. A listed\n * type is written as its wire name and read back from it; any other type travels as itself. One\n * route then carries many types without a `fixed` type per transport. Not with a `fixed` type.\n */\n readonly wireTypes?: WireTypes;\n};\n\n/** Event type to the name the wire uses for it; see `wireTypes` of a jsonEnvelope mapping. */\nexport type WireTypes = Readonly<Record<string, string>>;\n\n/**\n * A JSON object that wraps the payload with event metadata, such as\n * `{ \"eventName\": ..., \"messageId\": ..., \"data\": {...}, \"meta\": {...} }`.\n * Each value lives at a body path or in a header.\n */\nexport type BodyEnvelopeMapping<TTransportId extends string> = MappingFields<\n WireField,\n TTransportId\n> & {\n /** Body path of the payload. Required. */\n readonly payload: BodyField;\n /**\n * Event headers: a body path holding an object of strings, `'message-headers'` (default),\n * every message header that no other field maps, or `'top-level-fields'`, spread over the top\n * level of the body: every top-level text field that no other value uses is read as one.\n */\n readonly headers?: BodyField | 'message-headers' | 'top-level-fields';\n /**\n * Values written with every message besides the mapped ones, such as a constant\n * `provider: 'orders-api'` or a second copy of the time. They are never read; extra headers\n * are left out of the event headers on read.\n */\n readonly extra?: { readonly body?: ExtraBody; readonly headers?: ExtraHeaders };\n /**\n * Top-level body fields to write first, in this order; the others follow in the order they\n * are written. Only the bytes change, for formats compared byte for byte.\n */\n readonly bodyOrder?: readonly string[];\n /**\n * Keeps the top-level body fields that no other value uses (and that are not read as event\n * headers) with every JSON type, in body order, as one object under `payloadField` of the\n * payload: `{ payloadField: 'wire' }` reads `{ \"data\": { \"a\": 1 }, \"attempt\": 2 }` as the payload\n * `{ \"a\": 1, \"wire\": { \"attempt\": 2 } }`, so the handler's schema validates them with the payload.\n * Writing spreads that object back over the top level. Default: such fields are left out on read.\n */\n readonly otherFields?: OtherFields;\n};\n\n/** Where {@link BodyEnvelopeMapping.otherFields} keeps the unused top-level fields. */\nexport type OtherFields = { readonly payloadField: string };\n\n/**\n * The body is the payload itself, as a plain JSON producer writes it; every other value lives in\n * a header, so body paths are a compile error here.\n */\nexport type PayloadOnlyMapping<TTransportId extends string> = MappingFields<\n HeaderField,\n TTransportId\n> & {\n readonly payload: 'whole-body';\n /** Event headers: every message header that no other field maps. */\n readonly headers?: 'message-headers';\n /** Message headers written with every message; never read, and left out of the event headers. */\n readonly extra?: { readonly headers?: ExtraHeaders };\n};\n\n/** Where every envelope value lives in a JSON message. `type`, `id` and `payload` are required. */\nexport type JsonEnvelopeMapping<TTransportId extends string> =\n BodyEnvelopeMapping<TTransportId> | PayloadOnlyMapping<TTransportId>;\n\n/** A JSON message: the parsed body and the text headers. */\nexport type JsonWireMessage = { readonly body: unknown; readonly headers: EventHeaders };\n\n/** The values read from a message. An absent optional value is left to the transport's default. */\nexport type JsonEnvelopeFields = {\n readonly id?: string;\n readonly type: string;\n readonly payload: unknown;\n readonly key?: string;\n readonly source?: string;\n readonly headers: EventHeaders;\n readonly correlationId: string | null;\n readonly causationId: string | null;\n readonly occurredAt?: Date;\n};\n\n/** The errors of the calling transport. */\nexport type JsonEnvelopeFailures = {\n /** For a message that cannot be read: it goes to the invalid-message path. */\n readonly invalid: (reason: string) => Error;\n /** For an event that cannot be written: never retried. */\n readonly unencodable: (reason: string) => Error;\n};\n\n/** Writes and reads one mapping. Created once per codec; both methods are pure. */\nexport interface JsonEnvelopeFormat {\n /** The mapped headers and the body; the id is left out when the transport supplies it. */\n write(envelope: EventEnvelope): JsonWireMessage;\n read(message: JsonWireMessage): JsonEnvelopeFields;\n}\n\n/**\n * Compiles `mapping` once. `transportIds` lists the transport's own id strategies.\n *\n * @throws ConfigurationError for a mapping that is incomplete, names a header twice, nests one\n * body path inside another or mixes array indexes and names under one body field.\n */\nexport function createJsonEnvelopeFormat(\n mapping: JsonEnvelopeMapping<string>,\n {\n transportIds,\n failures,\n }: { readonly transportIds: readonly string[]; readonly failures: JsonEnvelopeFailures },\n): JsonEnvelopeFormat {\n const plan = compile(mapping, transportIds);\n return {\n write: (envelope) => writeMessage(envelope, { plan, failures }),\n read: (message) => readMessage(message, { plan, failures }),\n };\n}\n","import type { LeaseReference } from '../event-store.js';\nimport { DeliveryLeaseIdentity } from '../values/delivery-lease-identity.js';\n\n/** What a ledger remembers of a claim: at least who it was handed to and which delivery. */\nexport interface HandedOutEntry {\n readonly owner: string;\n readonly deliveryId: string;\n}\n\n/**\n * The claims a store instance handed out and has not seen settled, keyed by\n * {@link DeliveryLeaseIdentity} (delivery id and exact lease token). After a failed claim the\n * store keeps exactly these listed as running and gives the rest back.\n */\nexport class HandedOutLedger<TEntry extends HandedOutEntry> {\n readonly #entries = new Map<string, TEntry>();\n\n register(lease: LeaseReference, entry: TEntry): void {\n this.#entries.set(DeliveryLeaseIdentity.of(lease.deliveryId, lease.leaseToken), entry);\n }\n\n /** Whether the claim with this identity ({@link DeliveryLeaseIdentity.of}) is handed out. */\n has(identity: string): boolean {\n return this.#entries.has(identity);\n }\n\n forget(lease: LeaseReference): void {\n this.#entries.delete(DeliveryLeaseIdentity.of(lease.deliveryId, lease.leaseToken));\n }\n\n /** Forgets every entry `settled` says is settled. */\n forgetWhere(settled: (entry: TEntry, identity: string) => boolean): void {\n for (const [identity, entry] of this.#entries) {\n if (settled(entry, identity)) {\n this.#entries.delete(identity);\n }\n }\n }\n\n /** The entries handed out to `owner`. */\n entriesOf(owner: string): TEntry[] {\n return [...this.#entries.values()].filter((entry) => entry.owner === owner);\n }\n}\n","import type { ClaimRequest, ClaimedDelivery } from '../event-store.js';\n\n/**\n * The claim skeleton of the database stores: a request for no handlers or no deliveries claims\n * nothing, and the claims of one owner run one after the other. Claims of one owner read the same\n * held lanes and the same bookkeeping of what was handed out, so they must not overlap (the\n * dispatcher claims one batch at a time anyway; `runOnce` next to a running dispatcher is what\n * this guards against). A store supplies only {@link OwnerSerializedClaims.claimInTurn}.\n */\nexport abstract class OwnerSerializedClaims {\n /** The last claim of each owner still running; the next one waits for it. */\n readonly #queues = new Map<string, Promise<void>>();\n\n claim(request: ClaimRequest): Promise<ClaimedDelivery[]> {\n if (this.claimsNothing(request)) {\n return Promise.resolve([]);\n }\n return this.#serialized(request.leaseOwner, () => this.claimInTurn(request));\n }\n\n /** Whether the request cannot claim anything: no handlers, or a limit that is not above 0. */\n protected claimsNothing(request: ClaimRequest): boolean {\n return request.handlers.length === 0 || !(request.limit > 0);\n }\n\n /** Claims for `request` once the earlier claims of its owner settled. */\n protected abstract claimInTurn(request: ClaimRequest): Promise<ClaimedDelivery[]>;\n\n #serialized<T>(owner: string, work: () => Promise<T>): Promise<T> {\n const previous = this.#queues.get(owner) ?? Promise.resolve();\n const run = previous.then(work, work);\n const tail = run.then(\n () => undefined,\n () => undefined,\n );\n this.#queues.set(owner, tail);\n void tail.then(() => {\n if (this.#queues.get(owner) === tail) {\n this.#queues.delete(owner);\n }\n });\n return run;\n }\n}\n","import type { EventEnvelope, EventHeaders } from '../event.js';\n\n/** The event a transport's decoder extracted from a message; see the transport's `DecodedEvent`. */\nexport interface DecodedEventFields {\n readonly id: string;\n readonly type: string;\n readonly payload: unknown;\n readonly source?: string;\n readonly key?: string | null;\n readonly headers?: EventHeaders;\n readonly correlationId?: string | null;\n readonly causationId?: string | null;\n readonly occurredAt?: Date;\n}\n\n/** A fixed value, or an extractor that reads it from a plain message. */\nexport type TextOption<TPlain, TValue extends string | null> =\n TValue | ((message: TPlain) => TValue | undefined) | undefined;\n\n/**\n * Observes the rejection of a promise an async decoder or extractor returned by\n * mistake: the value is refused as malformed, and an unobserved rejection would\n * otherwise crash the process.\n */\nexport function observeRejection(value: unknown): void {\n if (typeof value === 'object' && value !== null && 'then' in value) {\n Promise.resolve(value).catch(() => undefined);\n }\n}\n\n/**\n * The inbound plumbing a transport shares with every other: completing what a user decoder\n * returned and reading the extractor options of a plain JSON decoder. A transport supplies only its\n * malformed-message error and the defaults its messages carry (source, key, time).\n */\nexport abstract class DecodedEventReader<TMessage, TPlain> {\n /**\n * Fills the fields a decoder left out and guards against a decoder that returned no object,\n * which would otherwise surface as a retried `TypeError` instead of a malformed message.\n */\n complete(decoded: unknown, message: TMessage): EventEnvelope {\n if (typeof decoded !== 'object' || decoded === null) {\n throw this.invalid('The decoder must return an event object synchronously');\n }\n if ('then' in decoded) {\n observeRejection(decoded);\n throw this.invalid('The decoder must return an event object synchronously');\n }\n const event = decoded as DecodedEventFields;\n return {\n id: event.id,\n type: event.type,\n source: event.source ?? this.defaultSource(message),\n key: event.key === undefined ? this.defaultKey(message) : event.key,\n payload: event.payload,\n headers: event.headers ?? {},\n correlationId: event.correlationId ?? null,\n causationId: event.causationId ?? null,\n occurredAt: event.occurredAt ?? this.defaultTime(message),\n };\n }\n\n /** The text an option gives for `plain`; undefined when it gives none or `''`. */\n text<TValue extends string | null>(\n option: TextOption<TPlain, TValue>,\n { plain, name }: { readonly plain: TPlain; readonly name: string },\n ): string | undefined {\n const value: unknown = typeof option === 'function' ? option(plain) : option;\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== 'string') {\n observeRejection(value);\n throw this.invalid(`The ${name} option returned ${typeof value}, expected a string`);\n }\n return value.length === 0 ? undefined : value;\n }\n\n /** The error of a malformed message, which the transport dead-letters instead of retrying. */\n abstract invalid(reason: string): Error;\n\n protected abstract defaultSource(message: TMessage): string;\n\n protected abstract defaultKey(message: TMessage): string | null;\n\n protected abstract defaultTime(message: TMessage): Date;\n}\n","import type { EventEnvelope } from '../event.js';\nimport type { CloseOptions } from '../event-store.js';\nimport type {\n Transport,\n TransportMessageHandler,\n TransportSubscriptionHooks,\n} from '../transport.js';\n\n/** One subscription of a transport: what it consumes and where the messages go. */\nexport interface TransportSubscription {\n readonly destinations: readonly string[];\n readonly onMessage: TransportMessageHandler;\n readonly hooks: TransportSubscriptionHooks | undefined;\n}\n\n/**\n * The skeleton of a broker transport that publishes and subscribes: the {@link Transport} port\n * with its subscribe signature in one place. A transport supplies how it publishes, opens its one\n * subscription, reports readiness and closes.\n */\nexport abstract class SubscribingTransport implements Transport {\n abstract readonly name: string;\n abstract readonly system: string;\n\n /**\n * Subscribes to `destinations`. Not async itself: the subscription's own promise is returned\n * as it is, so its checks reject rather than throw.\n */\n // eslint-disable-next-line relaybus/max-two-params -- the Transport.subscribe signature\n subscribe(\n destinations: readonly string[],\n onMessage: TransportMessageHandler,\n hooks?: TransportSubscriptionHooks,\n ): Promise<void> {\n return this.openSubscription({ destinations, onMessage, hooks });\n }\n\n abstract publish(envelope: EventEnvelope, destination: string): Promise<void>;\n\n abstract isReady(): boolean;\n\n abstract close(options?: CloseOptions): Promise<void>;\n\n /** Opens the transport's one subscription; rejects when it cannot. */\n protected abstract openSubscription(subscription: TransportSubscription): Promise<void>;\n}\n","import { ConfigurationError } from '../errors.js';\n\n/** The range a {@link BoundedInteger} option allows. */\nexport interface IntegerBounds {\n readonly name: string;\n readonly minimum: number;\n readonly maximum: number;\n}\n\n/** An integer option with fixed lower and upper bounds. */\nexport abstract class BoundedInteger {\n /** Returns `value` when it is an integer within the bounds, else throws a {@link ConfigurationError}. */\n static of(value: number, { name, minimum, maximum }: IntegerBounds): number {\n if (!Number.isInteger(value) || value < minimum || value > maximum) {\n throw new ConfigurationError(\n `${name} must be an integer from ${minimum} to ${maximum}, received ${value}`,\n );\n }\n return value;\n }\n}\n","/**\n * Delays that double with every attempt, from `initialMs` up to `maxMs`: the first retry waits\n * `initialMs`, the second twice that, and so on. Without jitter, for in-process retries.\n */\nexport class ExponentialBackoff {\n readonly initialMs: number;\n readonly maxMs: number;\n\n constructor({ initialMs, maxMs }: { readonly initialMs: number; readonly maxMs: number }) {\n this.initialMs = initialMs;\n this.maxMs = maxMs;\n }\n\n /** The delay after failed attempt `attempt` (1-based). */\n delayFor(attempt: number): number {\n return Math.min(this.initialMs * 2 ** (attempt - 1), this.maxMs);\n }\n}\n","/** The claim a lane lease token names, as written in the token. */\nexport interface LaneLeaseTokenParts {\n readonly lane: number;\n /** The lane's epoch, as decimal text: PostgreSQL epochs exceed the safe integers. */\n readonly epoch: string;\n /** The claim generation of the delivery. */\n readonly claims: number;\n}\n\n/** How many digits each part of a token may have, and how many lanes there are. */\nexport interface LaneLeaseTokenLimits {\n readonly laneCount: number;\n readonly epochDigits: number;\n readonly claimsDigits: number;\n}\n\n/** Largest number of digits of a lane number. */\nconst LANE_DIGITS = 3;\n\n/**\n * The fencing token of a claim in a lane-leased store: `<lane>:<epoch>:<claims>`. Every state\n * change checks the lane epoch and the delivery's claim generation it names. A store creates one\n * format with its own digit limits and parses only the tokens it can have issued.\n */\nexport class LaneLeaseTokenFormat {\n readonly #pattern: RegExp;\n readonly #laneCount: number;\n\n constructor(limits: LaneLeaseTokenLimits) {\n this.#laneCount = limits.laneCount;\n this.#pattern = new RegExp(\n `^(\\\\d{1,${LANE_DIGITS}}):(\\\\d{1,${limits.epochDigits}}):(\\\\d{1,${limits.claimsDigits}})$`,\n );\n }\n\n format(\n lane: number,\n { epoch, claims }: { readonly epoch: string | number; readonly claims: number },\n ): string {\n return `${lane}:${epoch}:${claims}`;\n }\n\n /** The parts of `token`; undefined when the store cannot have issued it. */\n parse(token: string): LaneLeaseTokenParts | undefined {\n const match = this.#pattern.exec(token);\n if (match === null || Number(match[1]) >= this.#laneCount) {\n return undefined;\n }\n return { lane: Number(match[1]), epoch: match[2]!, claims: Number(match[3]) };\n }\n}\n","import { ConfigurationError } from '../errors.js';\n\n/** A text option that must not be empty: a name, an exchange, a queue. */\nexport abstract class NonEmptyText {\n static of(value: string, name: string): string {\n if (value.length === 0) {\n throw new ConfigurationError(`${name} must not be empty`);\n }\n return value;\n }\n\n /** Like {@link NonEmptyText.of}, for an option that may be left out. */\n static optional(value: string | undefined, name: string): string | undefined {\n return value === undefined ? undefined : NonEmptyText.of(value, name);\n }\n}\n"]}
@@ -166,6 +166,35 @@ declare class ConfigurationError extends RelayBusError {
166
166
  name: string;
167
167
  readonly code: string;
168
168
  }
169
+ /**
170
+ * A catalog or a catalog route names an event that is not part of the catalog, for example a wire
171
+ * name for an event the catalog does not have.
172
+ */
173
+ declare class UnknownCatalogEventError extends ConfigurationError {
174
+ name: string;
175
+ readonly code: string;
176
+ }
177
+ /** A catalog route sends an event to a destination that another route already sends it to. */
178
+ declare class DuplicateRouteEventError extends ConfigurationError {
179
+ name: string;
180
+ readonly code: string;
181
+ }
182
+ /**
183
+ * Wire names clash: one event type has two wire names on a transport, or two event types share one,
184
+ * whether they come from catalogs, routes or the `wireTypes` of a codec.
185
+ */
186
+ declare class WireTypeCollisionError extends ConfigurationError {
187
+ name: string;
188
+ readonly code: string;
189
+ }
190
+ /**
191
+ * A route or catalog declares wire names for a transport whose codec cannot carry them: the
192
+ * transport has no `declareWireTypes`, or its codec is not a `jsonEnvelope` with a type to map.
193
+ */
194
+ declare class WireTypesUnsupportedError extends ConfigurationError {
195
+ name: string;
196
+ readonly code: string;
197
+ }
169
198
  /**
170
199
  * Thrown by `publish` when no transaction can be found and the bus runs with
171
200
  * `transactionMode: 'required'` (the default). Publishing outside a transaction
@@ -184,6 +213,16 @@ declare class TransactionTimeoutError extends RelayBusError {
184
213
  name: string;
185
214
  readonly code: string;
186
215
  }
216
+ /**
217
+ * A `@RelayBusTransaction({ isolationLevel })` method was called inside a transaction that was not
218
+ * opened by relaybus at that same level. The isolation level of a running transaction cannot be
219
+ * changed, so the method cannot join it: open the outer transaction at the level, or leave the
220
+ * level off the inner method.
221
+ */
222
+ declare class TransactionIsolationConflictError extends RelayBusError {
223
+ name: string;
224
+ readonly code: string;
225
+ }
187
226
  /**
188
227
  * Throw from a handler to dead-letter the delivery immediately, skipping the
189
228
  * remaining retry attempts.
@@ -277,6 +316,13 @@ declare function toErrorInfo(error: unknown): ErrorInfo;
277
316
  */
278
317
  type DeliveryStatus = 'pending' | 'processing' | 'completed' | 'dead';
279
318
  declare const DELIVERY_STATUSES: readonly DeliveryStatus[];
319
+ /**
320
+ * Isolation level of a `bus.transaction`, in the vocabulary of SQL. `repeatable read` and
321
+ * `serializable` can fail with a serialization failure that succeeds when the transaction runs
322
+ * again; the bus then reruns `work` (see {@link TransactionOptions}).
323
+ */
324
+ type TransactionIsolationLevel = 'read committed' | 'repeatable read' | 'serializable';
325
+ declare const TRANSACTION_ISOLATION_LEVELS: readonly TransactionIsolationLevel[];
280
326
  interface NewDelivery {
281
327
  readonly id: string;
282
328
  /** Stable handler id. Together with the event id it is unique. */
@@ -389,6 +435,12 @@ interface EventStoreTransactionOptions {
389
435
  * a transaction that still ran past the budget, so a store may also ignore it.
390
436
  */
391
437
  readonly timeoutMs: number;
438
+ /**
439
+ * Isolation level the transaction runs at, set before its first statement. Only passed when
440
+ * `bus.transaction` was given one, and only to a store that lists it in
441
+ * {@link EventStore.isolationLevels}.
442
+ */
443
+ readonly isolationLevel?: TransactionIsolationLevel;
392
444
  }
393
445
  /**
394
446
  * Storage port. Implementations persist events and deliveries in the same
@@ -404,6 +456,19 @@ interface EventStore<TTransaction = unknown> {
404
456
  * from `bus.transaction`; the store's own transactions and the dispatcher's pass none.
405
457
  */
406
458
  transaction<T>(work: (transaction: TTransaction) => Promise<T>, options?: EventStoreTransactionOptions): Promise<T>;
459
+ /**
460
+ * Optional. The isolation levels `transaction` can run at. `bus.transaction` with another
461
+ * `isolationLevel` is rejected with a {@link ConfigurationError} before it opens a transaction;
462
+ * a store without the list supports none. A store lists a level only when the database gives
463
+ * the guarantee the name promises.
464
+ */
465
+ readonly isolationLevels?: readonly TransactionIsolationLevel[];
466
+ /**
467
+ * Optional. True when `error`, raised by `transaction` (by `work`, or by the commit), means the
468
+ * database rolled the transaction back because of a conflict with a concurrent one and running
469
+ * it again can succeed (PostgreSQL SQLSTATE `40001`). Without it `bus.transaction` never reruns.
470
+ */
471
+ isSerializationFailure?(error: unknown): boolean;
407
472
  /**
408
473
  * Writes events and their deliveries inside `transaction`. Idempotent on
409
474
  * event id and on (event id, handler). Assigns a per-key sequence to keyed
@@ -517,6 +582,16 @@ interface Transport {
517
582
  */
518
583
  readonly system?: string;
519
584
  connect?(): Promise<void>;
585
+ /**
586
+ * Offered the wire names that routes and catalogs declare (event type to the name the wire
587
+ * format uses), once when the bus is created, before `connect` and `subscribe`. Check them
588
+ * without changing anything and return the function that applies them to the codec, so the bus
589
+ * can refuse a configuration before any transport changed. Throw
590
+ * {@link WireTypeCollisionError} when a name clashes with one the codec already has and
591
+ * {@link WireTypesUnsupportedError} when the codec cannot map type names or the transport
592
+ * already started. A transport without it refuses declared wire names at boot.
593
+ */
594
+ declareWireTypes?(wireTypes: Readonly<Record<string, string>>): () => void;
520
595
  publish(envelope: EventEnvelope, destination: string): Promise<void>;
521
596
  subscribe?(destinations: readonly string[], onMessage: TransportMessageHandler, hooks?: TransportSubscriptionHooks): Promise<void>;
522
597
  /**
@@ -532,5 +607,5 @@ interface Transport {
532
607
  close(options?: CloseOptions): Promise<void>;
533
608
  }
534
609
 
535
- export { toMilliseconds as $, LeaseLostError as F, LifecycleError as G, HandlerTimeoutError as H, InvalidEnvelopeError as I, NonRetryableError as J, TransactionRequiredError as K, MAX_TIMER_DELAY_MS as M, TransactionTimeoutError as O, RelayBusError as R, StandardSchemaV1 as S, assertEventType as X, defineEvent as Y, systemClock as Z, toErrorInfo as _, validatePayload as a0, AttemptsExhaustedError as o, ConfigurationError as q, DELIVERY_STATUSES as r, DispatcherStoppedError as v, DrainIncompleteError as w, EventValidationError as z };
536
- export type { AppendEntry as A, InvalidTransportMessage as B, ClaimedDelivery as C, Duration as D, EventEnvelope as E, LeaseReference as L, NewDelivery as N, PayloadOf as P, TransportMessage as Q, Transport as T, TransportMessageHandler as U, TransportSubscriptionHooks as V, ValidationIssue as W, DomainEvent as a, EventHeaders as b, EventStoreStatistics as c, ErrorInfo as d, PurgeResult as e, EventStore as f, EventReference as g, Clock as h, AppendResult as i, ClaimRequest as j, DeliveryQuery as k, DeliveryRecord as l, PurgeRequest as m, EventClass as n, CloseOptions as p, DefineEventKeyOptions as s, DefineEventOptions as t, DeliveryStatus as u, EventKeyFunction as x, EventStoreTransactionOptions as y };
610
+ export { EventValidationError as F, HandlerTimeoutError as H, InvalidEnvelopeError as I, LeaseLostError as J, LifecycleError as K, MAX_TIMER_DELAY_MS as M, NonRetryableError as O, TRANSACTION_ISOLATION_LEVELS as Q, RelayBusError as R, StandardSchemaV1 as S, TransactionIsolationConflictError as U, TransactionRequiredError as V, TransactionTimeoutError as W, UnknownCatalogEventError as _, WireTypeCollisionError as a0, WireTypesUnsupportedError as a1, assertEventType as a2, defineEvent as a3, systemClock as a4, toErrorInfo as a5, toMilliseconds as a6, validatePayload as a7, AttemptsExhaustedError as p, ConfigurationError as r, DELIVERY_STATUSES as s, DispatcherStoppedError as w, DrainIncompleteError as x, DuplicateRouteEventError as y };
611
+ export type { ValidationIssue as $, AppendEntry as A, EventStoreTransactionOptions as B, ClaimedDelivery as C, Duration as D, EventEnvelope as E, InvalidTransportMessage as G, LeaseReference as L, NewDelivery as N, PayloadOf as P, Transport as T, TransportMessage as X, TransportMessageHandler as Y, TransportSubscriptionHooks as Z, DomainEvent as a, EventHeaders as b, EventStoreStatistics as c, ErrorInfo as d, PurgeResult as e, EventReference as f, EventStore as g, Clock as h, TransactionIsolationLevel as i, AppendResult as j, ClaimRequest as k, DeliveryQuery as l, DeliveryRecord as m, PurgeRequest as n, EventClass as o, CloseOptions as q, DefineEventKeyOptions as t, DefineEventOptions as u, DeliveryStatus as v, EventKeyFunction as z };