@geonosis/events 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,217 @@
1
+ # `@geonosis/events`
2
+
3
+ An event declares its type, its payload schema and what it is **about**, once. A registry that
4
+ refuses a duplicate name. A totality type that makes every event answerable before it can ship. An
5
+ outbox port.
6
+
7
+ The engines' own facts live behind their own doors — `@geonosis/events/medusa` and
8
+ `@geonosis/events/cloudflare-queues` — and neither adapter imports the engine it adapts.
9
+
10
+ Zero runtime dependencies.
11
+
12
+ ```bash
13
+ pnpm add @geonosis/events
14
+ ```
15
+
16
+ ## The core
17
+
18
+ ```ts
19
+ import { createEventRegistry, defineEvent } from '@geonosis/events'
20
+ import { z } from 'zod'
21
+
22
+ export const workflowCompleted = defineEvent(
23
+ 'workflow.completed',
24
+ z.object({ name: z.string().min(1), runId: z.string().min(1) }),
25
+ (payload) => ({ kind: 'workflow-run', id: payload.runId }),
26
+ )
27
+
28
+ const registry = createEventRegistry([workflowCompleted, workflowCompensated])
29
+ ```
30
+
31
+ The third argument is a **function**, not a string. It derives the subject from the payload, which
32
+ is what lets one call validate a payload and name its subject together:
33
+
34
+ ```ts
35
+ registry.describe('workflow.completed', raw)
36
+ // { ok: true, payload: {...}, subject: { kind: 'workflow-run', id: 'r-1' } }
37
+ // { ok: false, reason: 'unknown-type' } — a producer nobody deployed
38
+ // { ok: false, reason: 'invalid-payload' } — a payload that drifted from its name
39
+ ```
40
+
41
+ Those two failures are told apart because the answers are different: one is a name nothing answers
42
+ to, the other is drift under a name that is still declared.
43
+
44
+ ### There is no `attempts` and no `priority` here
45
+
46
+ Both are facts about **Medusa's redis bus**, which has no dead-letter queue and treats only
47
+ `attempts > 1` as retry-configured. Measured: neither appears anywhere in during.day. Putting them
48
+ in a runtime-agnostic core would import one engine's failure mode into the contract the other engine
49
+ also has to hold. They live in `@geonosis/events/medusa`, and so does `subscriberId`.
50
+
51
+ ## Totality — the type is the instrument, the check is the backstop
52
+
53
+ during.day's totality is a **compile-time** fact, and — this is the part worth being exact about —
54
+ `defineEvent` enforces none of it. Adding a contract widens the union of declared types, and that
55
+ widening breaks two total maps somewhere else entirely:
56
+
57
+ | Map | Where | How |
58
+ |---|---|---|
59
+ | narration | `packages/domains/src/events/narration.ts:12` | `{ [Type in DomainEventType]: (payload) => EventNarration }` |
60
+ | notification channel | `packages/domains/src/notification/dispatch.ts:15` | `Record<DomainEventType, NotificationChannel>` |
61
+
62
+ A new event cannot ship until someone has written words for it and decided how it notifies —
63
+ enforced by the checker, in the files that own those answers, at no runtime cost and with no way to
64
+ forget. That is the instrument this package leads with:
65
+
66
+ ```ts
67
+ import type { EventTypeOf, TotalOver } from '@geonosis/events'
68
+
69
+ const events = [workflowCompleted, workflowCompensated] as const
70
+ type DomainEventType = EventTypeOf<typeof events>
71
+
72
+ const narrators: TotalOver<DomainEventType, Narrator> = { ... } // missing one → does not compile
73
+ ```
74
+
75
+ `assertTotal` is the **backstop**, for a map assembled from configuration or built where the checker
76
+ cannot follow. It reports both directions — a type nothing answers for, and an entry answering for a
77
+ type no event declares, which is how a map keeps a handler for an event renamed two releases ago:
78
+
79
+ ```ts
80
+ assertTotal(registry, 'notification', channels)
81
+ ```
82
+
83
+ Sold as equivalent to the type, this would be a downgrade dressed as a feature. It is documented
84
+ here as second best because it is second best.
85
+
86
+ ## The outbox is a port, and only a port
87
+
88
+ ```ts
89
+ export type Outbox<Envelope> = {
90
+ enqueue: (batch: readonly Envelope[]) => Promise<void>
91
+ listUndispatched: (params: { before: number; limit: number }) => Promise<readonly Envelope[]>
92
+ markDispatched: (params: { ids: readonly string[]; dispatchedAt?: number }) => Promise<void>
93
+ deleteDispatchedBefore: (params: { before: number }) => Promise<number>
94
+ }
95
+ ```
96
+
97
+ **No adapter ships here, and the reason is a measurement.** during.day is usually described —
98
+ including in this kit's own law — as "Cloudflare Workers + D1". It is hybrid: the **tenant** plane is
99
+ Postgres (`pgTable` in all 13 files under `schema/tenant/`, and the outbox is one of them), and only
100
+ the **control** plane is D1 (`sqliteTable` in three files under `schema/control/`). A D1 outbox
101
+ adapter would have been written for the wrong half of the only repo that has an outbox at all.
102
+
103
+ **Four operations, not two.** Plan 022 described the port as `enqueue(batch)` + `sweep(now)`.
104
+ during.day spells it across three files, and the spread is deliberate:
105
+ `deleteDispatchedEventsBefore` removes only *delivered* rows however old, because "an undelivered
106
+ row is a committed mutation's only trail". Collapsed into one `sweep`, listing, marking and deleting
107
+ share a name while failing in three different ways.
108
+
109
+ `enqueue` is a port method because the write belongs inside the caller's own transaction — in
110
+ during.day, the batch that closes a run. That transaction is the consumer's database's, not this
111
+ package's, which is the whole reason this is an interface.
112
+
113
+ ## `@geonosis/events/medusa`
114
+
115
+ dielime's `retryableEvent`, generalised, with its source proof intact:
116
+ `@medusajs/event-bus-redis` 2.19 defaults every job to `attempts: 1`; the worker computes
117
+ `isRetriesConfigured = configuredAttempts > 1`; and when a subscriber throws with retrying not
118
+ configured it logs a warning and **returns**, so the job completes. The work is dropped and the only
119
+ trace is a warn line.
120
+
121
+ ```ts
122
+ import { createMedusaEmitter } from '@geonosis/events/medusa'
123
+ import { emitEventStep } from '@medusajs/medusa/core-flows'
124
+
125
+ const emit = createMedusaEmitter({ emitEventStep, droppable: [/^search\./, /^telemetry\./] })
126
+
127
+ emit(orderPlaced, { orderId }) // options.attempts = 3, exponential backoff, always
128
+ ```
129
+
130
+ `retryableEvent` throws on `attempts <= 1` rather than accepting it: one attempt is exactly the
131
+ configuration it exists to prevent, and a caller passing it has misunderstood the option rather than
132
+ chosen it. `defaultAttempts` is a repo option — three is a choice, not a law — and a repo default of
133
+ one is refused for the same reason.
134
+
135
+ `droppable` is a **deny** list and empty by default, so a repo that configures nothing drops nothing.
136
+ That direction is dielime's, written down after an allow-list of load-bearing prefixes was tried
137
+ first: it misclassified half the catalogue, because event names are `<plugin>.<entity>.<verb>` as
138
+ often as `<entity>.<verb>` — and worse, it failed OPEN, so an event nobody thought to list was
139
+ silently droppable.
140
+
141
+ `defineSubscriber` requires `subscriberId`. Medusa infers one from the filename otherwise, and the
142
+ bus keys its already-succeeded set on that id, so a rename silently re-runs a subscriber that had
143
+ already done its work.
144
+
145
+ ### The 132-line test this replaces
146
+
147
+ dielime holds the invariant across **56** `emitEventStep` call sites with **56** `retryableEvent`
148
+ calls, policed by `packages/shared/src/events/emits-are-retryable.test.ts` — a source walker with
149
+ its own brace matcher, and a comment recording that its first version omitted `apps/backend` and so
150
+ "reported green for the wrong reason". That is a lint rule wearing a test's clothes. The rule it
151
+ should be is `biological-architecture/emit-declares-attempts`, in this kit's plugin, and the proof
152
+ that it covers all 56 sites is in `proofs/022-W5-consumers/`.
153
+
154
+ ## `@geonosis/events/cloudflare-queues`
155
+
156
+ during.day's `EventSink` is `sendBatch`-only by declaration, and there is no `send`. Adding one
157
+ would let a caller put a single message on the queue with a round trip per event — the shape a queue
158
+ producer exists to avoid, and the outbox already hands work over in batches.
159
+
160
+ ```ts
161
+ import { createQueueSink } from '@geonosis/events/cloudflare-queues'
162
+
163
+ const sink = createQueueSink(env.EVENTS)
164
+ await sink.send(envelopes) // batched at 100, Cloudflare's ceiling; no call at all for an empty list
165
+ ```
166
+
167
+ The binding is injected rather than imported: `@cloudflare/workers-types` is types only, the queue is
168
+ handed to the worker by the runtime, and a package that imported either would be unusable in a test.
169
+
170
+ ## Migration — dielime, five lines
171
+
172
+ ```diff
173
+ -import { retryableEvent } from '@dielime/shared/events/retry'
174
+ -emitEventStep({ eventName: 'order.placed', data, options: retryableEvent({ priority: 10 }) })
175
+ +import { createMedusaEmitter } from '@geonosis/events/medusa'
176
+ +const emit = createMedusaEmitter({ emitEventStep })
177
+ +emit(orderPlaced, data, { priority: 10 })
178
+ ```
179
+
180
+ `packages/shared/src/events/retry.ts` and its 132-line audit test both go. The event name stops being
181
+ a string at the call site, so `emit-declares-attempts` and the contract check the same fact.
182
+
183
+ ## Migration — during.day, five lines
184
+
185
+ ```diff
186
+ -import { defineEvent } from '@during/domains/events'
187
+ +import { defineEvent } from '@geonosis/events'
188
+ export const workflowCompletedEvent = defineEvent('workflow.completed', z.object({...}), (p) => ({...}))
189
+
190
+ -const narrators: EventNarrators = { ... }
191
+ +const narrators: TotalOver<EventTypeOf<typeof eventContracts>, Narrator> = { ... }
192
+ ```
193
+
194
+ The declarations do not change — the signature is during.day's. `indexEventContracts` becomes
195
+ `createEventRegistry`, which throws the same "two event contracts are declared for X". The envelope
196
+ stays in during.day: it carries `orgId`, a tenant key this package cannot assume.
197
+
198
+ ## Equivalence status (D-027)
199
+
200
+ | Piece | Status |
201
+ |---|---|
202
+ | `defineEvent(type, payload, subjectOf)` | **extracted** — during.day's signature, argument for argument |
203
+ | `createEventRegistry` duplicate refusal | **extracted** — `indexEventContracts`, same error text |
204
+ | `retryableEvent` + the `attempts > 1` refusal | **extracted** — dielime's, generalised with `defaultAttempts` |
205
+ | `defineSubscriber` requiring an id | **extracted** — dielime's convention, Medusa's inference the reason |
206
+ | `droppable` deny-list | **extracted** — dielime's `DROPPABLE_EVENT_PATTERNS`, defaulted to empty so it is opt-in |
207
+ | `sendBatch`-only sink | **extracted** — during.day's `EventSink`, plus the 100-message chunking |
208
+ | `TotalOver` / `EventTypeOf` | **named here** — the idiom is during.day's (`{ [T in DomainEventType]: … }`); this gives it a name and an export |
209
+ | `assertTotal` | **written here** — a backstop neither consumer needs; both use the type |
210
+ | `Outbox` port | **extracted as an interface** — during.day's four operations. No adapter, deliberately |
211
+
212
+ **Adopted by:** nobody yet. Published with contract tests over both consumers' measured shapes; not
213
+ a migration that has happened.
214
+
215
+ ## Licence
216
+
217
+ Apache-2.0
@@ -0,0 +1,25 @@
1
+ /**
2
+ * during.day's `EventSink`, honoured exactly: `sendBatch`-only.
3
+ *
4
+ * `{ sendBatch: (messages: { body: EventEnvelope }[]) => Promise<unknown> }` is declared beside the
5
+ * envelope it carries, and there is no `send`. Adding one would let a caller put a single message
6
+ * on the queue with a round trip per event, which is the shape a Cloudflare queue producer exists
7
+ * to avoid — and the outbox already hands work over in batches.
8
+ *
9
+ * The adapter takes the queue rather than importing one: `@cloudflare/workers-types` is a type
10
+ * package, the binding is injected by the runtime, and a package that imported either would be
11
+ * unusable in a test and in every other runtime.
12
+ */
13
+ type QueueLike<Envelope> = {
14
+ sendBatch: (messages: {
15
+ body: Envelope;
16
+ }[]) => Promise<unknown>;
17
+ };
18
+ type QueueSink<Envelope> = {
19
+ send: (envelopes: readonly Envelope[]) => Promise<void>;
20
+ };
21
+ declare const createQueueSink: <Envelope>(queue: QueueLike<Envelope>, options?: {
22
+ maxPerBatch?: number;
23
+ }) => QueueSink<Envelope>;
24
+
25
+ export { type QueueLike, type QueueSink, createQueueSink };
@@ -0,0 +1,15 @@
1
+ // src/cloudflare-queues/index.ts
2
+ var MAX_MESSAGES_PER_BATCH = 100;
3
+ var createQueueSink = (queue, options = {}) => {
4
+ const maxPerBatch = options.maxPerBatch ?? MAX_MESSAGES_PER_BATCH;
5
+ return {
6
+ send: async (envelopes) => {
7
+ for (let at = 0; at < envelopes.length; at += maxPerBatch) {
8
+ await queue.sendBatch(envelopes.slice(at, at + maxPerBatch).map((body) => ({ body })));
9
+ }
10
+ }
11
+ };
12
+ };
13
+ export {
14
+ createQueueSink
15
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * One event: its type, the schema of its payload, and what it is ABOUT — declared together, once.
3
+ *
4
+ * This is during.day's `defineEvent(type, payload, subject)` shape, and the third argument being a
5
+ * FUNCTION rather than a string is the part worth keeping. It derives the subject from the payload,
6
+ * which is what lets `describe()` validate a payload and name its subject in a single act. Split
7
+ * across two fields, the pairing is lost and an audit row can name a subject its payload never had.
8
+ *
9
+ * There is deliberately no `attempts` and no `priority`. Both are facts about Medusa's redis event
10
+ * bus, which has no dead-letter queue and treats only `attempts > 1` as retry-configured; neither
11
+ * appears anywhere in during.day. Putting them here would import one engine's failure mode into the
12
+ * contract the other engine also has to hold. They live in `@geonosis/events/medusa`.
13
+ */
14
+ /** A schema, recognised by what it does. See `@geonosis/integrations` for why this is structural. */
15
+ type SchemaLike<Value = unknown> = {
16
+ safeParse: (value: unknown) => {
17
+ data: Value;
18
+ success: true;
19
+ } | {
20
+ success: false;
21
+ };
22
+ };
23
+ type EventSubject = {
24
+ id: string;
25
+ kind: string;
26
+ };
27
+ type Described<Payload> = {
28
+ ok: false;
29
+ } | {
30
+ ok: true;
31
+ payload: Payload;
32
+ subject: EventSubject;
33
+ };
34
+ type EventContract<Type extends string, Payload> = {
35
+ describe: (value: unknown) => Described<Payload>;
36
+ payload: SchemaLike<Payload>;
37
+ subject: (payload: Payload) => EventSubject;
38
+ type: Type;
39
+ };
40
+ /**
41
+ * Any contract, as a constraint. `subject` is typed `(payload: never) => …` deliberately: a
42
+ * function's parameter is contravariant, so that is the one annotation every concrete contract
43
+ * satisfies. Writing `unknown` there instead makes `EventContract<'x', {id: string}>` fail to
44
+ * satisfy its own umbrella type, which is how a registry generic ends up needing a cast.
45
+ */
46
+ type AnyEventContract = {
47
+ describe: (value: unknown) => Described<unknown>;
48
+ payload: SchemaLike<unknown>;
49
+ subject: (payload: never) => EventSubject;
50
+ type: string;
51
+ };
52
+ declare const isEventContract: (value: unknown) => value is AnyEventContract;
53
+ declare const defineEvent: <const Type extends string, Payload>(type: Type, payload: SchemaLike<Payload>, subject: (payload: Payload) => EventSubject) => EventContract<Type, Payload>;
54
+
55
+ export { type AnyEventContract as A, type Described as D, type EventContract as E, type SchemaLike as S, type EventSubject as a, defineEvent as d, isEventContract as i };
@@ -0,0 +1,100 @@
1
+ import { A as AnyEventContract, D as Described, E as EventContract } from './define-CAjVcMva.js';
2
+ export { a as EventSubject, S as SchemaLike, d as defineEvent, i as isEventContract } from './define-CAjVcMva.js';
3
+
4
+ /**
5
+ * The transactional outbox as a PORT, and nothing else. There is no adapter in this package.
6
+ *
7
+ * The measurement that decided it: during.day's outbox is `pgTable('event_outbox', …)` on the
8
+ * TENANT plane, and that plane is Postgres — `pgTable` in all 13 files under `schema/tenant/`. Only
9
+ * the CONTROL plane is D1 (`sqliteTable` in three files under `schema/control/`). A D1 outbox
10
+ * adapter, which is what "Cloudflare Workers + D1" would have led to, would have been written for
11
+ * the wrong half of the only repo that has an outbox at all.
12
+ *
13
+ * Four operations, not two. Plan 022 described the port as `enqueue(batch)` + `sweep(now)`; during
14
+ * .day spells it across three files, and the spread is deliberate — `deleteDispatchedEventsBefore`
15
+ * removes ONLY delivered rows however old, because "an undelivered row is a committed mutation's
16
+ * only trail". Collapsed into one `sweep`, listing, marking and deleting share a name while failing
17
+ * in three different ways.
18
+ *
19
+ * `enqueue` is a port method here and is written inside the caller's own transaction — in
20
+ * during.day, in the batch that closes a run. That is the whole point of an outbox, and it is why
21
+ * this is an interface: the transaction belongs to the consumer's database, not to this package.
22
+ */
23
+ type Outbox<Envelope> = {
24
+ /** Delivered rows only, however old. */
25
+ deleteDispatchedBefore: (params: {
26
+ before: number;
27
+ }) => Promise<number>;
28
+ /** Written in the same transaction as the mutation that produced the events. */
29
+ enqueue: (batch: readonly Envelope[]) => Promise<void>;
30
+ /** `before` is the grace for a run that is about to drain its own events. */
31
+ listUndispatched: (params: {
32
+ before: number;
33
+ limit: number;
34
+ }) => Promise<readonly Envelope[]>;
35
+ markDispatched: (params: {
36
+ dispatchedAt?: number;
37
+ ids: readonly string[];
38
+ }) => Promise<void>;
39
+ };
40
+ /**
41
+ * The consumer's other half. Delivery is at-least-once and the envelope id is the only thing known
42
+ * before a message is read, so this is the one question a queue consumer asks before doing work.
43
+ */
44
+ type SeenBefore = (id: string) => Promise<boolean>;
45
+
46
+ /**
47
+ * The name index, with the one invariant a name registry has to hold: two contracts may not be
48
+ * declared for one type. during.day's `indexEventContracts` already throws exactly that, and it is
49
+ * the reason its consumer door can trust the name it looked up.
50
+ *
51
+ * What is added here is the ability to ASK the registry what it knows. during.day never needs to —
52
+ * a mapped type over the union covers it at compile time — but a runtime totality check has to
53
+ * compare a map against something, and a map loaded from configuration has no union to check.
54
+ */
55
+ type DescribeFailure = {
56
+ ok: false;
57
+ reason: 'invalid-payload' | 'unknown-type';
58
+ };
59
+ type EventRegistry<Contract extends AnyEventContract> = {
60
+ describe: (type: string, payload: unknown) => Described<unknown> | DescribeFailure;
61
+ get: (type: string) => Contract;
62
+ has: (type: string) => boolean;
63
+ list: () => readonly Contract[];
64
+ types: () => readonly string[];
65
+ };
66
+ declare const createEventRegistry: <const Contract extends AnyEventContract>(contracts: readonly Contract[]) => EventRegistry<Contract>;
67
+
68
+ /**
69
+ * The instrument during.day actually uses, and the one this package leads with.
70
+ *
71
+ * Its totality is a COMPILE-TIME fact, and — this is the part worth being precise about —
72
+ * `defineEvent` enforces none of it. Adding a contract widens the union of declared types, and the
73
+ * widening breaks two total maps somewhere else entirely: `events/narration.ts:12` declares
74
+ * `{ [Type in DomainEventType]: (payload) => EventNarration }` and `notification/dispatch.ts:15`
75
+ * declares `Record<DomainEventType, NotificationChannel>`. A new event therefore cannot ship until
76
+ * someone has written words for it and decided how it notifies — enforced by the checker, in the
77
+ * files that own those answers, with no runtime cost and no way to forget.
78
+ *
79
+ * `assertTotal` below is the BACKSTOP, not the equivalent: for a map assembled from configuration,
80
+ * loaded at runtime, or built somewhere the checker cannot follow. Advertised as equivalent it
81
+ * would be a downgrade sold as a feature.
82
+ */
83
+ /** The union of types a contract list declares — during.day's `DomainEventType`. */
84
+ type EventTypeOf<Contracts extends readonly AnyEventContract[]> = Contracts[number]['type'];
85
+ /** One entry per type, or it does not compile. The `satisfies Record<…>` idiom, named. */
86
+ type TotalOver<Type extends string, Value> = {
87
+ [Key in Type]: Value;
88
+ };
89
+ /** The payload a given type carries, so a total map can be typed per entry. */
90
+ type PayloadOf<Contracts extends readonly AnyEventContract[], Type extends EventTypeOf<Contracts>> = Extract<Contracts[number], {
91
+ type: Type;
92
+ }> extends EventContract<string, infer Payload> ? Payload : never;
93
+ /**
94
+ * Both directions. A type nothing answers for is the failure everyone expects; an entry answering
95
+ * for a type no event declares is the other one, and it is how a map keeps a handler for an event
96
+ * that was renamed two releases ago.
97
+ */
98
+ declare const assertTotal: (registry: EventRegistry<AnyEventContract>, channel: string, handled: Record<string, unknown>) => void;
99
+
100
+ export { AnyEventContract, type DescribeFailure, Described, EventContract, type EventRegistry, type EventTypeOf, type Outbox, type PayloadOf, type SeenBefore, type TotalOver, assertTotal, createEventRegistry };
package/dist/index.js ADDED
@@ -0,0 +1,91 @@
1
+ // src/define.ts
2
+ var DECLARED = /* @__PURE__ */ Symbol.for("geonosis.events.declared");
3
+ var isEventContract = (value) => typeof value === "object" && value !== null && value[DECLARED] === true;
4
+ var defineEvent = (type, payload, subject) => {
5
+ if (typeof type !== "string" || type === "") {
6
+ throw new TypeError(
7
+ "defineEvent: `type` must be a non-empty string. The type is how a consumer finds the contract that reads a message, so an event without one cannot be delivered to anything."
8
+ );
9
+ }
10
+ if (typeof payload?.safeParse !== "function") {
11
+ throw new TypeError(
12
+ `defineEvent("${type}"): the payload schema must expose \`safeParse\`. A queue carries whatever anyone put on it \u2014 an older producer, a hand-sent message, a payload that drifted \u2014 so the schema is the only thing standing between that and the audit log.`
13
+ );
14
+ }
15
+ if (typeof subject !== "function") {
16
+ throw new TypeError(
17
+ `defineEvent("${type}"): \`subject\` must be a function of the payload. Naming what an event is about is derived from the payload, not declared beside it \u2014 otherwise a row can name a subject its payload never carried.`
18
+ );
19
+ }
20
+ return {
21
+ [DECLARED]: true,
22
+ describe: (value) => {
23
+ const parsed = payload.safeParse(value);
24
+ if (!parsed.success) return { ok: false };
25
+ return { ok: true, payload: parsed.data, subject: subject(parsed.data) };
26
+ },
27
+ payload,
28
+ subject,
29
+ type
30
+ };
31
+ };
32
+
33
+ // src/registry.ts
34
+ var createEventRegistry = (contracts) => {
35
+ const byType = /* @__PURE__ */ new Map();
36
+ for (const contract of contracts ?? []) {
37
+ if (!isEventContract(contract)) {
38
+ throw new TypeError(
39
+ "createEventRegistry: every entry must come from `defineEvent`. A hand-written contract skips the checks on the type, the schema and the subject, and the registry is what the consumer door trusts."
40
+ );
41
+ }
42
+ if (byType.has(contract.type)) {
43
+ throw new Error(`two event contracts are declared for "${contract.type}"`);
44
+ }
45
+ byType.set(contract.type, contract);
46
+ }
47
+ const get = (type) => {
48
+ const found = byType.get(type);
49
+ if (found === void 0) {
50
+ throw new Error(`no event contract is declared for "${type}"`);
51
+ }
52
+ return found;
53
+ };
54
+ return {
55
+ // Two of the three failures happen to a message that is otherwise well formed — a name nothing
56
+ // answers to, and a payload that no longer fits the name it came under — and they are told
57
+ // apart because the answers differ: one is a producer nobody deployed, the other is drift.
58
+ describe: (type, payload) => {
59
+ const contract = byType.get(type);
60
+ if (contract === void 0) return { ok: false, reason: "unknown-type" };
61
+ const described = contract.describe(payload);
62
+ return described.ok ? described : { ok: false, reason: "invalid-payload" };
63
+ },
64
+ get,
65
+ has: (type) => byType.has(type),
66
+ list: () => [...byType.values()],
67
+ types: () => [...byType.keys()]
68
+ };
69
+ };
70
+
71
+ // src/totality.ts
72
+ var assertTotal = (registry, channel, handled) => {
73
+ const declared = new Set(registry.types());
74
+ const answered = new Set(Object.keys(handled ?? {}));
75
+ const missing = [...declared].filter((type) => !answered.has(type)).toSorted();
76
+ const stray = [...answered].filter((type) => !declared.has(type)).toSorted();
77
+ if (missing.length === 0 && stray.length === 0) return;
78
+ const parts = [
79
+ missing.length > 0 ? `nothing answers for ${missing.join(", ")}` : "",
80
+ stray.length > 0 ? `${stray.join(", ")} is answered for but declared by no event` : ""
81
+ ].filter((part) => part !== "");
82
+ throw new Error(
83
+ `the "${channel}" channel is not total over the declared events: ${parts.join("; ")}. Prefer the compile-time form \u2014 \`TotalOver<EventTypeOf<typeof events>, Handler>\` \u2014 and keep this check for a map the checker cannot see into.`
84
+ );
85
+ };
86
+ export {
87
+ assertTotal,
88
+ createEventRegistry,
89
+ defineEvent,
90
+ isEventContract
91
+ };
@@ -0,0 +1,66 @@
1
+ import { E as EventContract } from '../define-CAjVcMva.js';
2
+
3
+ /**
4
+ * Medusa's own silence, made impossible to keep by accident. dielime's `retryableEvent`, generalised.
5
+ *
6
+ * The source proof, against `@medusajs/event-bus-redis` 2.19: `buildEvents()` defaults every job to
7
+ * `attempts: 1`; the worker computes `isRetriesConfigured = configuredAttempts > 1`; and when a
8
+ * subscriber throws with retrying not configured it logs "One or more subscribers of <name> failed.
9
+ * Retrying is not configured." at WARN and RETURNS — so the job completes successfully. The work is
10
+ * dropped and the only trace is a warn line. For a quote that never expires or a shipment exception
11
+ * nobody is told about, that is a silent business failure.
12
+ *
13
+ * With `attempts > 1` the same worker stores `completedSubscriberIds` on the job before throwing to
14
+ * trigger the retry and filters them out of the next attempt, so a subscriber that already
15
+ * succeeded is not re-run. Configuring attempts buys retry for the failed one AND exactly-once
16
+ * delivery for the ones that worked.
17
+ *
18
+ * This is the adapter, not the core, because none of it is true of the other engine: during.day has
19
+ * a transactional outbox and a queue consumer that dedupes on the envelope id, and carries neither
20
+ * `attempts` nor `priority` anywhere.
21
+ */
22
+ /** Three: the first failure is usually a blip, the third is usually real. */
23
+ declare const DEFAULT_EVENT_ATTEMPTS = 3;
24
+ type EventRetryOptions = {
25
+ attempts?: number;
26
+ [option: string]: unknown;
27
+ };
28
+ type RetryDefaults = {
29
+ defaultAttempts?: number;
30
+ };
31
+ /**
32
+ * Throws on `attempts <= 1` rather than accepting it: one attempt is exactly the configuration this
33
+ * function exists to prevent, and a caller passing it has misunderstood the option rather than
34
+ * chosen it.
35
+ */
36
+ declare const retryableEvent: (options?: EventRetryOptions, defaults?: RetryDefaults) => Record<string, unknown>;
37
+ type EmitEventStep = (input: {
38
+ data: unknown;
39
+ eventName: string;
40
+ options: Record<string, unknown>;
41
+ }) => unknown;
42
+ type EmitterOptions = {
43
+ defaultAttempts?: number;
44
+ /**
45
+ * The events this repo is willing to lose — a DENY list, and the direction is the whole point.
46
+ * dielime tried an allow-list of load-bearing prefixes first and it misclassified half the
47
+ * catalogue, because event names are `<plugin>.<entity>.<verb>` as often as `<entity>.<verb>`.
48
+ * Worse, it fails OPEN: an event nobody thought to list is silently droppable. Empty by default,
49
+ * so a repo that configures nothing drops nothing.
50
+ */
51
+ droppable?: readonly RegExp[];
52
+ emitEventStep: EmitEventStep;
53
+ };
54
+ declare const createMedusaEmitter: (options: EmitterOptions) => <Type extends string, Payload>(contract: EventContract<Type, Payload>, data: Payload, emitOptions?: EventRetryOptions) => unknown;
55
+ type Subscriber = {
56
+ handler: (...args: never[]) => Promise<void>;
57
+ subscriberId: string;
58
+ };
59
+ /**
60
+ * Medusa infers a subscriber's id from its filename when none is given, so two subscribers that
61
+ * move or get renamed can silently become one registration — or stop being the one the bus
62
+ * remembers has already succeeded, which is what `completedSubscriberIds` is keyed on.
63
+ */
64
+ declare const defineSubscriber: <const S extends Subscriber>(subscriber: S) => S;
65
+
66
+ export { DEFAULT_EVENT_ATTEMPTS, type EmitEventStep, type EmitterOptions, type EventRetryOptions, type RetryDefaults, type Subscriber, createMedusaEmitter, defineSubscriber, retryableEvent };
@@ -0,0 +1,50 @@
1
+ // src/medusa/index.ts
2
+ var DEFAULT_EVENT_ATTEMPTS = 3;
3
+ var DEFAULT_BACKOFF = { delay: 1e3, type: "exponential" };
4
+ var NO_RETRY = 1;
5
+ var retryableEvent = (options = {}, defaults = {}) => {
6
+ const fallback = defaults.defaultAttempts ?? DEFAULT_EVENT_ATTEMPTS;
7
+ if (fallback <= NO_RETRY) {
8
+ throw new Error(
9
+ `retryableEvent: \`defaultAttempts\` must be > 1 (got ${fallback}). A repo default of one attempt makes every emit droppable while every call site looks configured.`
10
+ );
11
+ }
12
+ const { attempts = fallback, ...rest } = options;
13
+ if (attempts <= NO_RETRY) {
14
+ throw new Error(
15
+ `retryableEvent: \`attempts\` must be > 1 (got ${attempts}). One attempt IS "retrying is not configured" to the redis bus, which is the failure this helper exists to prevent.`
16
+ );
17
+ }
18
+ return { attempts, backoff: { ...DEFAULT_BACKOFF }, ...rest };
19
+ };
20
+ var createMedusaEmitter = (options) => {
21
+ const { defaultAttempts, droppable = [], emitEventStep } = options;
22
+ return (contract, data, emitOptions = {}) => {
23
+ const parsed = contract.payload.safeParse(data);
24
+ if (!parsed.success) {
25
+ throw new Error(
26
+ `emit("${contract.type}"): the payload does not satisfy the contract's own schema. The bus carries whatever it is handed, so this is the last place the shape can be refused.`
27
+ );
28
+ }
29
+ const isDroppable = droppable.some((pattern) => pattern.test(contract.type));
30
+ return emitEventStep({
31
+ data: parsed.data,
32
+ eventName: contract.type,
33
+ options: isDroppable ? { ...emitOptions } : retryableEvent(emitOptions, defaultAttempts === void 0 ? {} : { defaultAttempts })
34
+ });
35
+ };
36
+ };
37
+ var defineSubscriber = (subscriber) => {
38
+ if (typeof subscriber?.subscriberId !== "string" || subscriber.subscriberId === "") {
39
+ throw new TypeError(
40
+ "defineSubscriber: `subscriberId` is required. Medusa infers it from the filename otherwise, and the bus keys its already-succeeded set on that id \u2014 so a rename silently re-runs a subscriber that had already done its work."
41
+ );
42
+ }
43
+ return subscriber;
44
+ };
45
+ export {
46
+ DEFAULT_EVENT_ATTEMPTS,
47
+ createMedusaEmitter,
48
+ defineSubscriber,
49
+ retryableEvent
50
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@geonosis/events",
3
+ "version": "1.0.0",
4
+ "description": "An event declares its type, its payload schema and what it is about, once. A registry that refuses a duplicate name, a totality type that makes every event answerable, and an outbox port — with the engines' own facts kept in their adapters.",
5
+ "keywords": [
6
+ "events",
7
+ "outbox",
8
+ "registry",
9
+ "zod",
10
+ "medusa",
11
+ "cloudflare-queues"
12
+ ],
13
+ "homepage": "https://github.com/microcompanies/geonosis/tree/main/packages/events",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/microcompanies/geonosis.git",
17
+ "directory": "packages/events"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "type": "module",
21
+ "main": "dist/index.js",
22
+ "exports": {
23
+ ".": "./dist/index.js",
24
+ "./medusa": "./dist/medusa/index.js",
25
+ "./cloudflare-queues": "./dist/cloudflare-queues/index.js"
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "peerDependencies": {
31
+ "zod": "^4.0.0"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "zod": {
35
+ "optional": true
36
+ }
37
+ },
38
+ "devDependencies": {
39
+ "zod": "^4.0.0"
40
+ },
41
+ "engines": {
42
+ "node": ">=22"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "build": "tsup",
49
+ "typecheck": "tsc --noEmit"
50
+ }
51
+ }