@photon-grove/evt 0.0.0-stage → 0.1.0

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.
Files changed (124) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +122 -2
  3. package/dist/aggregate.d.ts +83 -0
  4. package/dist/aggregate.d.ts.map +1 -0
  5. package/dist/aggregate.js +92 -0
  6. package/dist/aggregate.js.map +1 -0
  7. package/dist/base64.d.ts +8 -0
  8. package/dist/base64.d.ts.map +1 -0
  9. package/dist/base64.js +67 -0
  10. package/dist/base64.js.map +1 -0
  11. package/dist/codec.d.ts +56 -0
  12. package/dist/codec.d.ts.map +1 -0
  13. package/dist/codec.js +90 -0
  14. package/dist/codec.js.map +1 -0
  15. package/dist/commit-id.d.ts +3 -0
  16. package/dist/commit-id.d.ts.map +1 -0
  17. package/dist/commit-id.js +43 -0
  18. package/dist/commit-id.js.map +1 -0
  19. package/dist/dynamodb/head.d.ts +34 -0
  20. package/dist/dynamodb/head.d.ts.map +1 -0
  21. package/dist/dynamodb/head.js +62 -0
  22. package/dist/dynamodb/head.js.map +1 -0
  23. package/dist/dynamodb/index.d.ts +2 -0
  24. package/dist/dynamodb/index.d.ts.map +1 -0
  25. package/dist/dynamodb/index.js +4 -0
  26. package/dist/dynamodb/index.js.map +1 -0
  27. package/dist/dynamodb/item.d.ts +68 -0
  28. package/dist/dynamodb/item.d.ts.map +1 -0
  29. package/dist/dynamodb/item.js +263 -0
  30. package/dist/dynamodb/item.js.map +1 -0
  31. package/dist/envelope.d.ts +15 -0
  32. package/dist/envelope.d.ts.map +1 -0
  33. package/dist/envelope.js +59 -0
  34. package/dist/envelope.js.map +1 -0
  35. package/dist/errors.d.ts +111 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/errors.js +139 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/event.d.ts +47 -0
  40. package/dist/event.d.ts.map +1 -0
  41. package/dist/event.js +64 -0
  42. package/dist/event.js.map +1 -0
  43. package/dist/fields.d.ts +31 -0
  44. package/dist/fields.d.ts.map +1 -0
  45. package/dist/fields.js +105 -0
  46. package/dist/fields.js.map +1 -0
  47. package/dist/index.d.ts +14 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +16 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/json.d.ts +47 -0
  52. package/dist/json.d.ts.map +1 -0
  53. package/dist/json.js +458 -0
  54. package/dist/json.js.map +1 -0
  55. package/dist/memory/index.d.ts +2 -0
  56. package/dist/memory/index.d.ts.map +1 -0
  57. package/dist/memory/index.js +3 -0
  58. package/dist/memory/index.js.map +1 -0
  59. package/dist/memory/repository.d.ts +34 -0
  60. package/dist/memory/repository.d.ts.map +1 -0
  61. package/dist/memory/repository.js +219 -0
  62. package/dist/memory/repository.js.map +1 -0
  63. package/dist/metadata.d.ts +47 -0
  64. package/dist/metadata.d.ts.map +1 -0
  65. package/dist/metadata.js +75 -0
  66. package/dist/metadata.js.map +1 -0
  67. package/dist/repository.d.ts +102 -0
  68. package/dist/repository.d.ts.map +1 -0
  69. package/dist/repository.js +131 -0
  70. package/dist/repository.js.map +1 -0
  71. package/dist/retry.d.ts +25 -0
  72. package/dist/retry.d.ts.map +1 -0
  73. package/dist/retry.js +50 -0
  74. package/dist/retry.js.map +1 -0
  75. package/dist/snapshots.d.ts +21 -0
  76. package/dist/snapshots.d.ts.map +1 -0
  77. package/dist/snapshots.js +35 -0
  78. package/dist/snapshots.js.map +1 -0
  79. package/dist/store.d.ts +103 -0
  80. package/dist/store.d.ts.map +1 -0
  81. package/dist/store.js +246 -0
  82. package/dist/store.js.map +1 -0
  83. package/dist/testing/equal.d.ts +22 -0
  84. package/dist/testing/equal.d.ts.map +1 -0
  85. package/dist/testing/equal.js +121 -0
  86. package/dist/testing/equal.js.map +1 -0
  87. package/dist/testing/index.d.ts +3 -0
  88. package/dist/testing/index.d.ts.map +1 -0
  89. package/dist/testing/index.js +5 -0
  90. package/dist/testing/index.js.map +1 -0
  91. package/dist/testing/scenario.d.ts +136 -0
  92. package/dist/testing/scenario.d.ts.map +1 -0
  93. package/dist/testing/scenario.js +307 -0
  94. package/dist/testing/scenario.js.map +1 -0
  95. package/dist/utf8.d.ts +17 -0
  96. package/dist/utf8.d.ts.map +1 -0
  97. package/dist/utf8.js +82 -0
  98. package/dist/utf8.js.map +1 -0
  99. package/package.json +56 -4
  100. package/src/aggregate.ts +196 -0
  101. package/src/base64.ts +80 -0
  102. package/src/codec.ts +139 -0
  103. package/src/commit-id.ts +50 -0
  104. package/src/dynamodb/head.ts +93 -0
  105. package/src/dynamodb/index.ts +21 -0
  106. package/src/dynamodb/item.ts +332 -0
  107. package/src/envelope.ts +67 -0
  108. package/src/errors.ts +214 -0
  109. package/src/event.ts +117 -0
  110. package/src/fields.ts +134 -0
  111. package/src/globals.d.ts +39 -0
  112. package/src/index.ts +75 -0
  113. package/src/json.ts +546 -0
  114. package/src/memory/index.ts +3 -0
  115. package/src/memory/repository.ts +313 -0
  116. package/src/metadata.ts +120 -0
  117. package/src/repository.ts +247 -0
  118. package/src/retry.ts +74 -0
  119. package/src/snapshots.ts +42 -0
  120. package/src/store.ts +377 -0
  121. package/src/testing/equal.ts +146 -0
  122. package/src/testing/index.ts +14 -0
  123. package/src/testing/scenario.ts +406 -0
  124. package/src/utf8.ts +92 -0
package/src/event.ts ADDED
@@ -0,0 +1,117 @@
1
+ // Serialized events and snapshots: the stored form every repository reads and writes, and their
2
+ // JSON encodings, which match Go's evt.SerializedEvent and evt.SerializedSnapshot.
3
+
4
+ import {
5
+ DOCUMENT,
6
+ bytesField,
7
+ int64Argument,
8
+ int64Field,
9
+ objectOrNull,
10
+ safeIntegerArgument,
11
+ safeIntegerField,
12
+ stringField,
13
+ type JsonObject,
14
+ } from './fields.js'
15
+ import {parseJson, stringifyJson} from './json.js'
16
+ import {type Metadata, metadataFromJson, metadataJson} from './metadata.js'
17
+
18
+ /** An event as it is stored. Its JSON is the `detail` of a stream envelope. */
19
+ export interface SerializedEvent {
20
+ /** `{entityId}:{sequence}`. */
21
+ id: string
22
+ /** The 1-based position of the event in its stream. */
23
+ sequence: bigint
24
+ /** The event kind, such as `account:opened`. */
25
+ type: string
26
+ /** The payload's schema version. */
27
+ version: number
28
+ /** The stream the event belongs to. */
29
+ entityId: string
30
+ /** The aggregate type of the entity. */
31
+ entityType: string
32
+ /**
33
+ * The payload bytes, stored verbatim. Null only when decoded from a JSON `null`, which is
34
+ * written back as `null`, as Go does.
35
+ */
36
+ payload: Uint8Array | null
37
+ metadata: Metadata
38
+ }
39
+
40
+ /** A snapshot of aggregate state. A stream keeps at most one, its latest. */
41
+ export interface SerializedSnapshot {
42
+ entityType: string
43
+ entityId: string
44
+ /** 1 for an entity's first snapshot, then one more for each. */
45
+ sequence: bigint
46
+ /** The last event sequence folded into the snapshot. */
47
+ eventSequence: bigint
48
+ /** The state's bytes, stored verbatim. Null only when decoded from a JSON `null`. */
49
+ payload: Uint8Array | null
50
+ }
51
+
52
+ /** The event ID for a sequence of a stream: `{entityId}:{sequence}`. */
53
+ export function eventId(entityId: string, sequence: bigint): string {
54
+ return `${entityId}:${sequence}`
55
+ }
56
+
57
+ /** Encodes an event as the JSON Go writes for it. */
58
+ export function encodeEvent(event: SerializedEvent): string {
59
+ return stringifyJson(eventJson(event))
60
+ }
61
+
62
+ /** Decodes an event's JSON leniently, as Go does. */
63
+ export function decodeEvent(json: string): SerializedEvent {
64
+ return eventFromJson(objectOrNull(parseJson(json, DOCUMENT), 'event'))
65
+ }
66
+
67
+ /** Encodes a snapshot as the JSON Go writes for it. Its entity ID key is `entityID`. */
68
+ export function encodeSnapshot(snapshot: SerializedSnapshot): string {
69
+ return stringifyJson({
70
+ entityType: snapshot.entityType,
71
+ entityID: snapshot.entityId,
72
+ sequence: int64Argument(snapshot.sequence, 'snapshot.sequence'),
73
+ eventSequence: int64Argument(snapshot.eventSequence, 'snapshot.eventSequence'),
74
+ payload: snapshot.payload,
75
+ })
76
+ }
77
+
78
+ /** Decodes a snapshot's JSON leniently, as Go does. */
79
+ export function decodeSnapshot(json: string): SerializedSnapshot {
80
+ const object = objectOrNull(parseJson(json, DOCUMENT), 'snapshot') ?? new Map()
81
+
82
+ return {
83
+ entityType: stringField(object, 'entityType', 'snapshot'),
84
+ entityId: stringField(object, 'entityID', 'snapshot'),
85
+ sequence: int64Field(object, 'sequence', 'snapshot'),
86
+ eventSequence: int64Field(object, 'eventSequence', 'snapshot'),
87
+ payload: bytesField(object, 'payload', 'snapshot'),
88
+ }
89
+ }
90
+
91
+ export function eventJson(event: SerializedEvent): object {
92
+ return {
93
+ id: event.id,
94
+ sequence: int64Argument(event.sequence, 'event.sequence'),
95
+ type: event.type,
96
+ version: safeIntegerArgument(event.version, 'event.version'),
97
+ entityId: event.entityId,
98
+ entityType: event.entityType,
99
+ payload: event.payload,
100
+ metadata: metadataJson(event.metadata),
101
+ }
102
+ }
103
+
104
+ export function eventFromJson(value: JsonObject | null): SerializedEvent {
105
+ const object = value ?? new Map()
106
+
107
+ return {
108
+ id: stringField(object, 'id', 'event'),
109
+ sequence: int64Field(object, 'sequence', 'event'),
110
+ type: stringField(object, 'type', 'event'),
111
+ version: safeIntegerField(object, 'version', 'event'),
112
+ entityId: stringField(object, 'entityId', 'event'),
113
+ entityType: stringField(object, 'entityType', 'event'),
114
+ payload: bytesField(object, 'payload', 'event'),
115
+ metadata: metadataFromJson(object.get('metadata')),
116
+ }
117
+ }
package/src/fields.ts ADDED
@@ -0,0 +1,134 @@
1
+ // Lenient decoding of engine documents by Go's rules: a missing field or null is the zero value,
2
+ // unknown fields are ignored, and a value of the wrong JSON type is an error. Field names match
3
+ // exactly, as in Rust (Go also matches them case-insensitively).
4
+
5
+ import {base64Decode} from './base64.js'
6
+ import {EvtError} from './errors.js'
7
+ import {JsonNumber, type JsonValue, type ParseOptions} from './json.js'
8
+
9
+ export type JsonObject = Map<string, JsonValue>
10
+
11
+ const INT64_MIN = -(2n ** 63n)
12
+
13
+ const INT64_MAX = 2n ** 63n - 1n
14
+
15
+ /** How evt parses its own documents: a repeated key is refused. */
16
+ export const DOCUMENT: ParseOptions = {duplicateKeys: 'refuse'}
17
+
18
+ export function invalid(message: string): EvtError {
19
+ return new EvtError('invalidRecord', message)
20
+ }
21
+
22
+ /** An object, or null for JSON null. */
23
+ export function objectOrNull(value: JsonValue | undefined, what: string): JsonObject | null {
24
+ if (value === undefined || value === null) {
25
+ return null
26
+ }
27
+ if (!(value instanceof Map)) {
28
+ throw invalid(`${what} is not an object`)
29
+ }
30
+
31
+ return value
32
+ }
33
+
34
+ /** A string field, `""` when missing or null. */
35
+ export function stringField(object: JsonObject, name: string, what: string): string {
36
+ return nullableString(object, name, what) ?? ''
37
+ }
38
+
39
+ /** A string field that may be null (a Go `*string`). */
40
+ export function nullableString(object: JsonObject, name: string, what: string): string | null {
41
+ const value = object.get(name)
42
+ if (value === undefined || value === null) {
43
+ return null
44
+ }
45
+ if (typeof value !== 'string') {
46
+ throw invalid(`${what}.${name} is not a string`)
47
+ }
48
+
49
+ return value
50
+ }
51
+
52
+ /** An int64 field, `0n` when missing or null. `1.0`, `1e3` and `"1"` are refused, as in Go. */
53
+ export function int64Field(object: JsonObject, name: string, what: string): bigint {
54
+ const value = object.get(name)
55
+ if (value === undefined || value === null) {
56
+ return 0n
57
+ }
58
+
59
+ return int64(value, `${what}.${name}`)
60
+ }
61
+
62
+ /** A small integer field, `0` when missing or null, refused if it isn't a safe integer. */
63
+ export function safeIntegerField(object: JsonObject, name: string, what: string): number {
64
+ const value = int64Field(object, name, what)
65
+ if (value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER)) {
66
+ throw invalid(`${what}.${name} is ${value}, past the integers this field holds`)
67
+ }
68
+
69
+ return Number(value)
70
+ }
71
+
72
+ /** Reads a JSON number as an int64. */
73
+ export function int64(value: JsonValue, what: string): bigint {
74
+ if (!(value instanceof JsonNumber) || !value.isInteger) {
75
+ throw invalid(`${what} is not an integer`)
76
+ }
77
+
78
+ return checkInt64(BigInt(value.text), what)
79
+ }
80
+
81
+ /** Refuses an integer outside int64. */
82
+ export function checkInt64(value: bigint, what: string): bigint {
83
+ if (value < INT64_MIN || value > INT64_MAX) {
84
+ throw invalid(`${what} is ${value}, outside int64`)
85
+ }
86
+
87
+ return value
88
+ }
89
+
90
+ /** Refuses to write an integer that no reader would read back as an int64. */
91
+ export function int64Argument(value: bigint, what: string): bigint {
92
+ if (value < INT64_MIN || value > INT64_MAX) {
93
+ throw new EvtError('invalidArgument', `${what} is ${value}, outside int64`)
94
+ }
95
+
96
+ return value
97
+ }
98
+
99
+ /** Refuses to write a small integer that isn't a safe integer, such as 1.5 or NaN. */
100
+ export function safeIntegerArgument(value: number, what: string): number {
101
+ if (!Number.isSafeInteger(value)) {
102
+ throw new EvtError('invalidArgument', `${what} is ${value}, not a safe integer`)
103
+ }
104
+
105
+ return value
106
+ }
107
+
108
+ /** A base64 field (a Go `[]byte`), null when missing or null. */
109
+ export function bytesField(object: JsonObject, name: string, what: string): Uint8Array | null {
110
+ const text = nullableString(object, name, what)
111
+
112
+ return text === null ? null : base64Decode(text)
113
+ }
114
+
115
+ /**
116
+ * A Go `map[string]string`: null for a missing or null map, and `""` for a null value.
117
+ */
118
+ export function stringMap(value: JsonValue | undefined, what: string): Map<string, string> | null {
119
+ const object = objectOrNull(value, what)
120
+ if (object === null) {
121
+ return null
122
+ }
123
+
124
+ const map = new Map<string, string>()
125
+ for (const [key, entry] of object) {
126
+ if (entry !== null && typeof entry !== 'string') {
127
+ throw invalid(`${what}.${key} is not a string`)
128
+ }
129
+
130
+ map.set(key, entry ?? '')
131
+ }
132
+
133
+ return map
134
+ }
@@ -0,0 +1,39 @@
1
+ // The only runtime globals the published code may use: web-standard APIs that Node, Bun, Deno,
2
+ // edge runtimes and browsers all provide (ADR 0009, section 3). tsconfig.json loads no DOM or Node
3
+ // types, so anything else, such as Buffer, process or document, is a type error. Declare a global
4
+ // here only when the code needs it and every target runtime has it, typed no looser than the
5
+ // runtimes' own declarations: tsconfig.test.json checks src/ against Node's types instead.
6
+
7
+ declare class TextEncoder {
8
+ readonly encoding: string
9
+ encode(input?: string): Uint8Array<ArrayBuffer>
10
+ }
11
+
12
+ declare class TextDecoder {
13
+ constructor(label?: string, options?: {fatal?: boolean; ignoreBOM?: boolean})
14
+ readonly encoding: string
15
+ readonly fatal: boolean
16
+ decode(input?: ArrayBuffer | ArrayBufferView, options?: {stream?: boolean}): string
17
+ }
18
+
19
+ interface AbortSignal {
20
+ readonly aborted: boolean
21
+ readonly reason: unknown
22
+ throwIfAborted(): void
23
+ addEventListener(type: 'abort', listener: () => void, options?: {once?: boolean}): void
24
+ removeEventListener(type: 'abort', listener: () => void): void
25
+ }
26
+
27
+ // Browsers define crypto.subtle only in secure contexts (HTTPS or localhost).
28
+ declare var crypto: {
29
+ getRandomValues<T extends Uint8Array>(array: T): T
30
+ readonly subtle: {
31
+ digest(algorithm: 'SHA-256', data: Uint8Array<ArrayBuffer>): Promise<ArrayBuffer>
32
+ }
33
+ }
34
+
35
+ declare function setTimeout(callback: () => void, ms?: number): unknown
36
+
37
+ declare function clearTimeout(id: unknown): void
38
+
39
+ declare function queueMicrotask(callback: () => void): void
package/src/index.ts ADDED
@@ -0,0 +1,75 @@
1
+ // @photon-grove/evt: event sourcing for TypeScript, wire-compatible with the Go and Rust evt
2
+ // implementations (docs/adr/0009-typescript-implementation.md). The storage contract is
3
+ // docs/reference/storage-format.md, and compat/fixtures holds its executable form.
4
+
5
+ export {
6
+ type Aggregate,
7
+ type AggregateDefinition,
8
+ type Decision,
9
+ type EventDefinition,
10
+ type EventDefinitions,
11
+ type EventOf,
12
+ type Rejection,
13
+ type Upcaster,
14
+ defineAggregate,
15
+ defineEvents,
16
+ jsonUpcaster,
17
+ } from './aggregate.js'
18
+ export {base64Decode, base64Encode} from './base64.js'
19
+ export {
20
+ type Codec,
21
+ type JsonOptions,
22
+ type StandardResult,
23
+ type StandardSchemaV1,
24
+ json,
25
+ } from './codec.js'
26
+ export {encodeEnvelope, decodeEnvelope, messageAttributes} from './envelope.js'
27
+ export {
28
+ CommitTooLargeError,
29
+ CompactionUncoveredError,
30
+ ConflictError,
31
+ EvtError,
32
+ type EvtErrorCode,
33
+ ReplayError,
34
+ ReservedEntityIdError,
35
+ SequenceGapError,
36
+ SnapshotError,
37
+ StreamHeadDriftError,
38
+ isConflict,
39
+ isRetryable,
40
+ } from './errors.js'
41
+ export {
42
+ type SerializedEvent,
43
+ type SerializedSnapshot,
44
+ decodeEvent,
45
+ decodeSnapshot,
46
+ encodeEvent,
47
+ encodeSnapshot,
48
+ eventId,
49
+ } from './event.js'
50
+ export {JsonNumber, type JsonValue, parseJson, stringifyJson} from './json.js'
51
+ export {
52
+ type Metadata,
53
+ type Origin,
54
+ decodeMetadata,
55
+ effectiveCausationId,
56
+ emptyMetadata,
57
+ encodeMetadata,
58
+ } from './metadata.js'
59
+ export type {CallOptions, Commit, NewSnapshot, Repository} from './repository.js'
60
+ export {
61
+ DEFAULT_RETRY_POLICY,
62
+ type RetryPolicy,
63
+ retryDelay,
64
+ } from './retry.js'
65
+ export {MAX_COMMIT_ITEM_BYTES, snapshotCommitSize, snapshotEventsDue} from './snapshots.js'
66
+ export {compareUtf8, utf8Length} from './utf8.js'
67
+ export {
68
+ DEFAULT_SNAPSHOT_INTERVAL,
69
+ type ExecuteOptions,
70
+ type ExecuteResult,
71
+ type Loaded,
72
+ type RetryOptions,
73
+ Store,
74
+ type StoreOptions,
75
+ } from './store.js'