@codeinkit/dom-trigger 0.0.0-stage → 0.1.0-alpha.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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-alpha.0
4
+
5
+ First alpha. The client twin of `@codeinkit/http-trigger`, for `@codeinkit/flows` `^4.0.0-alpha.1`.
6
+
7
+ - `DomTrigger`: one delegated listener per `flows:<domain>.<verb>` event type on the document, runs the
8
+ matching UI flow with an `AbortSignal` and a `runId`.
9
+ - `register`, `registerModules` (same flow ids as `flows.registerModules`, optional `registerFlows`), `unregister`.
10
+ - `start` / `stop` (idempotent, restartable, a no-op without a document), `isRunning`, `getTarget`, `onStatus`.
11
+ - Concurrency per (flow, event): `drop` (default), `latest`, `queue`, `parallel`.
12
+ - Optional `input` schema (`safeParse` or `parse`) validates the event's `detail` before the flow runs.
13
+ - `createEmitter`: typed `emit`, `emitOnDocument` and `listen`.
14
+ - `createDomPort`: a port for flows so UI actions can announce events.
15
+ - `isEventName`, `EVENT_NAME_RE`, `DEFAULT_PREFIX`, and the `DomEventMap` type to augment `DocumentEventMap`.
16
+ - CommonJS and ES module builds, no runtime dependencies, safe to import on the server.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) codeinkit dev team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,315 @@
1
- # Temporary Holding Version
1
+ # @codeinkit/dom-trigger
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DOM CustomEvent trigger for [@codeinkit/flows](https://github.com/CodeInKit/flows): components dispatch
4
+ `flows:domain.verb` events, and a UI flow runs.
5
+
6
+ It is the client twin of `@codeinkit/http-trigger`. On the server an HTTP request starts a flow; in the
7
+ browser a DOM event does:
8
+
9
+ ```
10
+ <button> ── dispatches "flows:booking.submit" ──▶ bubbles to document ──▶ DomTrigger ──▶ flows.execute('booking/submit', …)
11
+ ```
12
+
13
+ - Components know nothing about flows. They dispatch an event from their own element and are done.
14
+ - One delegated listener per event type on `document`, however many components there are.
15
+ - Every run gets an `AbortSignal` and a `runId`, so searches can be cancelled and runs can be traced.
16
+ - Framework-agnostic (no React), safe to import on the server, no runtime dependencies.
17
+
18
+ > Alpha. The API may still change before `0.1.0`.
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ npm i @codeinkit/dom-trigger@next @codeinkit/flows@next
24
+ ```
25
+
26
+ `@codeinkit/flows` `^4.0.0-alpha.1` is a peer dependency.
27
+
28
+ ## Quick start
29
+
30
+ ```ts
31
+ // main.tsx
32
+ import { Flows } from '@codeinkit/flows/core'; // the browser entry
33
+ import { DomTrigger, createDomPort } from '@codeinkit/dom-trigger';
34
+
35
+ const flows = new Flows({ ports: { dom: createDomPort(), api } });
36
+ const trigger = new DomTrigger(flows);
37
+
38
+ // registers the flows and their dom triggers in one go
39
+ trigger.registerModules(import.meta.glob('./flows/**/*.ts', { eager: true }), {
40
+ base: './flows',
41
+ registerFlows: true,
42
+ });
43
+
44
+ const stop = trigger.start();
45
+
46
+ import.meta.hot?.dispose(stop); // HMR: no listener of the old module is left behind
47
+ ```
48
+
49
+ ```ts
50
+ // flows/booking/submit.ts -> flow id "booking/submit"
51
+ import { z } from 'zod';
52
+
53
+ export const triggers = [{ type: 'dom', event: 'booking.submit' }];
54
+
55
+ export const input = z.object({ slot: z.number() }); // optional, validates event.detail
56
+
57
+ export default [
58
+ async (data, unsafe, ctx) => {
59
+ const booking = await unsafe.api.createBooking(data.detail, { signal: ctx.signal });
60
+ return { booking };
61
+ },
62
+ (data, unsafe) => {
63
+ unsafe.dom.emit('booking.created', { id: data.booking.id });
64
+ return {};
65
+ },
66
+ ];
67
+ ```
68
+
69
+ ```tsx
70
+ // any component, any framework
71
+ import { emit } from './events';
72
+
73
+ <button onClick={(e) => emit(e.currentTarget, 'booking.submit', { slot: 3 })}>Book</button>;
74
+ ```
75
+
76
+ ## Event naming
77
+
78
+ The contract between components and flows is the event name:
79
+
80
+ - A name is `domain.verb`: lowercase segments (`a-z`, `0-9`, `-`, starting with a letter) separated by dots,
81
+ at least two of them. `booking.submit`, `search-box.query` and `booking.slot.pick` are valid;
82
+ `submit` and `Booking.Submit` are not. `isEventName(name)` and `EVENT_NAME_RE` check it.
83
+ - The DOM event type is the prefix plus the name: `flows:booking.submit`. The prefix is an option (default `'flows:'`).
84
+ - Invalid names throw when a trigger is registered and when an event is emitted.
85
+ - By convention (not validated), **commands** are in the present tense and ask for something
86
+ (`booking.submit`), and **announcements** are in the past tense and say that something happened
87
+ (`booking.created`). Components dispatch commands; flows dispatch announcements.
88
+
89
+ ## Flow files
90
+
91
+ A flow module exports its actions as `default`, and optionally `triggers` and `input`, the same shape
92
+ the http trigger reads:
93
+
94
+ ```ts
95
+ export const triggers = [
96
+ { type: 'http', method: 'post', path: '/search' }, // ignored by DomTrigger
97
+ { type: 'dom', event: 'search.query', concurrency: 'latest' },
98
+ ];
99
+ export const input = schema; // anything with safeParse(v) => { success, data?, error? }, or with parse(v)
100
+ export default [/* actions */];
101
+ ```
102
+
103
+ The first action receives:
104
+
105
+ ```ts
106
+ {
107
+ event: 'search.query',
108
+ detail: /* event.detail, or the parsed data of `input` */,
109
+ runId: '…',
110
+ source: { flowId: 'search/query', route: '/rooms' }, // route: location.pathname
111
+ }
112
+ ```
113
+
114
+ `detail` must be JSON-serializable, flows clones it between actions. There are no DOM nodes in the data;
115
+ when something outside of the flow needs the element, `trigger.getTarget(runId)` returns the event's
116
+ original target while the run is active.
117
+
118
+ When `input` fails, the flow does not run: the status is `invalid` and `onError` is called.
119
+
120
+ Without a glob, register by hand:
121
+
122
+ ```ts
123
+ flows.register('booking/submit', actions);
124
+ trigger.register('booking/submit', [{ type: 'dom', event: 'booking.submit' }], { input: schema });
125
+ ```
126
+
127
+ Several flows may listen to the same event, each of them runs. Registering the same flow twice for one
128
+ event throws.
129
+
130
+ ## Concurrency
131
+
132
+ What happens to an event that arrives while a run of the same flow for the same event is active:
133
+
134
+ | `concurrency` | behaviour | use for |
135
+ | ------------------ | ---------------------------------------------------------------------- | ----------------------------- |
136
+ | `'drop'` (default) | the new event is ignored, status `dropped` | commands: a double click |
137
+ | `'latest'` | the previous run is aborted (status `cancelled`), the new one starts | searches, autocomplete |
138
+ | `'queue'` | runs one after another, in order | ordered writes |
139
+ | `'parallel'` | every event runs at once | independent work, analytics |
140
+
141
+ Concurrency is per (flow, event) pair: other events of the same flow, and other flows on the same event,
142
+ are not affected.
143
+
144
+ ## Cancellation
145
+
146
+ Every run has its own `AbortController`. Its signal is `ctx.signal` in every action, and flows checks it
147
+ before every action, so a cancelled flow never continues with its next action.
148
+
149
+ A run is cancelled when a newer event replaces it (`latest`), when its flow is unregistered, and on
150
+ `stop()`. The abort reason is an `Error` named `AbortError` with the code `ABORT_ERR`. A cancelled run
151
+ gets the status `cancelled` at once and never reaches `onError`; whatever its flow still returns is ignored.
152
+
153
+ To stop the work that is already under way, pass the signal on:
154
+
155
+ ```ts
156
+ export default [
157
+ async (data, unsafe, ctx) => {
158
+ const res = await fetch(`/api/search?q=${encodeURIComponent(data.detail)}`, { signal: ctx.signal });
159
+ return { results: await res.json() };
160
+ },
161
+ ];
162
+ ```
163
+
164
+ `withTimeout` and `withRetry` of [`@codeinkit/flows-hoa`](https://github.com/amitmtrn/flows-hoa) honour
165
+ `ctx.signal`: the wrapped action gets a signal that aborts on timeout and when the trigger cancels the
166
+ run, and a retry does not start another attempt after an abort.
167
+
168
+ ```ts
169
+ import { withTimeout } from '@codeinkit/flows-hoa';
170
+
171
+ export default [withTimeout(search, { ms: 5000 })];
172
+ ```
173
+
174
+ ## Status
175
+
176
+ `onStatus` tells you about every run, which is all a store needs to show spinners and errors:
177
+
178
+ ```ts
179
+ const unsubscribe = trigger.onStatus(({ status, flowId, event, runId, output, error }) => {
180
+ store.setState((s) => ({ runs: { ...s.runs, [event]: { status, error } } }));
181
+ });
182
+ ```
183
+
184
+ | status | meaning | extra |
185
+ | ----------- | ----------------------------------------------------- | -------- |
186
+ | `running` | the flow started | |
187
+ | `done` | the flow resolved | `output` |
188
+ | `error` | the flow rejected. `onError` is called too | `error` |
189
+ | `cancelled` | the run was aborted (also runs still waiting in a queue) | `error`: the abort reason |
190
+ | `dropped` | ignored because of `concurrency: 'drop'` | |
191
+ | `invalid` | `input` rejected the detail. `onError` is called too | `error` |
192
+
193
+ A listener that throws never breaks the trigger. `trigger.isRunning(flowId?, event?)` answers without a subscription.
194
+
195
+ ## Options
196
+
197
+ ```ts
198
+ new DomTrigger(flows, {
199
+ target, // where to listen. Default: document, resolved in start()
200
+ prefix, // default 'flows:'
201
+ scope, // () => the unsafe scope of each run, default {}. Never put ports here, they belong to new Flows({ ports })
202
+ onError, // (error, { status, flowId, event, runId }) => void, for 'error' and 'invalid'. Default: console.error
203
+ route, // () => string | undefined, default: location.pathname
204
+ runId, // () => string, default: crypto.randomUUID() when available
205
+ });
206
+ ```
207
+
208
+ `flows` is anything with `execute(name, input, scope, { signal, runId })`: the `@codeinkit/flows/core`
209
+ entry, the Node entry, or a test double.
210
+
211
+ | method | |
212
+ | --- | --- |
213
+ | `register(flowId, triggers, { input }?)` | add the dom triggers of a registered flow. Returns its event names |
214
+ | `registerModules(modules, { base, registerFlows }?)` | the same for an eager glob, with the flow ids of `flows.registerModules`. Returns `[{ flowId, events }]` |
215
+ | `unregister(flowId)` | remove its triggers, abort its runs |
216
+ | `start()` | start listening. Returns `stop`. Calling it twice does not subscribe twice |
217
+ | `stop()` | remove the listeners, abort every run. `start()` works again afterwards |
218
+ | `isRunning(flowId?, event?)` | is a run active? |
219
+ | `getTarget(runId)` | the event's original target while the run is active, else `null` |
220
+ | `onStatus(listener)` | subscribe to run statuses. Returns the unsubscribe function |
221
+
222
+ ## Dispatching events
223
+
224
+ `createEmitter` is a typed wrapper around `dispatchEvent(new CustomEvent(...))`:
225
+
226
+ ```ts
227
+ // events.ts
228
+ import { createEmitter } from '@codeinkit/dom-trigger';
229
+
230
+ export type AppEvents = {
231
+ 'booking.submit': { slot: number };
232
+ 'booking.created': { id: string };
233
+ 'search.query': string;
234
+ };
235
+
236
+ export const { emit, emitOnDocument, listen } = createEmitter<AppEvents>();
237
+ ```
238
+
239
+ ```ts
240
+ emit(button, 'booking.submit', { slot: 3 }); // from an element, bubbles to the document
241
+ emitOnDocument('search.query', 'sea view'); // when there is no element at hand
242
+ emit(button, 'booking.submit', { slot: '3' }); // type error
243
+ emit(button, 'booking.sumbit', { slot: 3 }); // type error
244
+
245
+ const off = listen(document, 'booking.created', ({ id }) => navigate(`/bookings/${id}`));
246
+ ```
247
+
248
+ Events are `bubbles: true, composed: true, cancelable: true`, so they cross shadow roots. A DomTrigger
249
+ that handles an event calls `preventDefault()` on it, which is how `emit` knows: it returns `true` when
250
+ a trigger handled the event and `false` when nobody did (a typo, or a trigger that is not started).
251
+
252
+ You do not need the helper. This is the whole protocol:
253
+
254
+ ```ts
255
+ el.dispatchEvent(new CustomEvent('flows:booking.submit', { detail: { slot: 3 }, bubbles: true, composed: true, cancelable: true }));
256
+ ```
257
+
258
+ ### The DomTrigger port
259
+
260
+ Flows announce what happened through a port, so actions stay free of globals:
261
+
262
+ ```ts
263
+ import { createDomPort } from '@codeinkit/dom-trigger';
264
+
265
+ const flows = new Flows({ ports: { dom: createDomPort<AppEvents>() } });
266
+
267
+ // in an action
268
+ unsafe.dom.emit('booking.created', { id: booking.id });
269
+ ```
270
+
271
+ It dispatches on the document (or on `createDomPort({ target })`). Components hear it with `listen`, and
272
+ an announcement is an event like any other, so another flow can have a trigger for it.
273
+
274
+ ### Typing `addEventListener`
275
+
276
+ `DomEventMap` turns an event map into DOM event types, to augment `DocumentEventMap`:
277
+
278
+ ```ts
279
+ import type { DomEventMap } from '@codeinkit/dom-trigger';
280
+ import type { AppEvents } from './events';
281
+
282
+ declare global {
283
+ interface DocumentEventMap extends DomEventMap<AppEvents> {}
284
+ // the same as writing each of them:
285
+ // interface DocumentEventMap { 'flows:booking.created': CustomEvent<{ id: string }> }
286
+ }
287
+
288
+ document.addEventListener('flows:booking.created', (e) => e.detail.id); // typed
289
+ ```
290
+
291
+ ## SSR
292
+
293
+ Importing the package touches no browser global, and nothing happens until you call something:
294
+
295
+ - `start()` without a document does nothing and returns a no-op teardown.
296
+ - `emitOnDocument()` and `createDomPort().emit()` return `false` without a document.
297
+ - `register` and `registerModules` work anywhere.
298
+
299
+ So the same `main` module can run on the server and in the browser.
300
+
301
+ ## React StrictMode
302
+
303
+ Start the trigger outside of React, once, next to `createRoot` (see the quick start). In development
304
+ StrictMode mounts, unmounts and mounts every component again, and a trigger started in an effect would
305
+ abort its running flows on that first unmount.
306
+
307
+ If it has to live in a component, return the teardown and it stays correct, `start()` works again after `stop()`:
308
+
309
+ ```ts
310
+ useEffect(() => trigger.start(), []);
311
+ ```
312
+
313
+ ## License
314
+
315
+ MIT
@@ -0,0 +1,308 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DomTrigger = void 0;
4
+ const modules_js_1 = require("./modules.js");
5
+ const names_js_1 = require("./names.js");
6
+ const CONCURRENCY = ['drop', 'latest', 'queue', 'parallel'];
7
+ function abortError(message) {
8
+ return Object.assign(new Error(message), { name: 'AbortError', code: 'ABORT_ERR' });
9
+ }
10
+ let runCounter = 0;
11
+ function defaultRunId() {
12
+ const c = globalThis.crypto;
13
+ if (c && typeof c.randomUUID === 'function')
14
+ return c.randomUUID();
15
+ runCounter += 1;
16
+ return `${Date.now().toString(36)}-${runCounter.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
17
+ }
18
+ function defaultRoute() {
19
+ const location = globalThis.location;
20
+ return location ? location.pathname : undefined;
21
+ }
22
+ function defaultOnError(error, info) {
23
+ console.error(`[dom-trigger] ${info.status}: flow "${info.flowId}" on "${info.event}"`, error);
24
+ }
25
+ function isSchemaLike(value) {
26
+ const schema = value;
27
+ return !!schema && (typeof schema.safeParse === 'function' || typeof schema.parse === 'function');
28
+ }
29
+ function validate(schema, value) {
30
+ var _a;
31
+ try {
32
+ if (typeof schema.safeParse !== 'function')
33
+ return { ok: true, data: schema.parse(value) };
34
+ const result = schema.safeParse(value);
35
+ return result.success ? { ok: true, data: result.data } : { ok: false, error: (_a = result.error) !== null && _a !== void 0 ? _a : new Error('invalid input') };
36
+ }
37
+ catch (error) {
38
+ return { ok: false, error };
39
+ }
40
+ }
41
+ /** the valid dom triggers of a `triggers` list. Other trigger types are ignored, a bad dom trigger throws */
42
+ function parseTriggers(flowId, triggers, input) {
43
+ if (typeof flowId !== 'string' || flowId === '')
44
+ throw new TypeError('dom-trigger: flowId must be a non-empty string');
45
+ if (!Array.isArray(triggers))
46
+ throw new TypeError(`dom-trigger: triggers of flow "${flowId}" must be an array`);
47
+ const parsed = [];
48
+ for (const trigger of triggers) {
49
+ if (!trigger || trigger.type !== 'dom')
50
+ continue;
51
+ const { event, concurrency = 'drop' } = trigger;
52
+ (0, names_js_1.assertEventName)(event);
53
+ if (CONCURRENCY.indexOf(concurrency) === -1) {
54
+ throw new TypeError(`dom-trigger: invalid concurrency ${JSON.stringify(concurrency)} for "${event}" of flow "${flowId}", expected one of ${CONCURRENCY.join(', ')}`);
55
+ }
56
+ if (parsed.some((p) => p.event === event)) {
57
+ throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
58
+ }
59
+ parsed.push({ event, concurrency });
60
+ }
61
+ if (parsed.length > 0 && input !== undefined && !isSchemaLike(input)) {
62
+ throw new TypeError(`dom-trigger: input of flow "${flowId}" must have a safeParse() or a parse() method`);
63
+ }
64
+ return parsed;
65
+ }
66
+ class DomTrigger {
67
+ constructor(flows, options = {}) {
68
+ var _a;
69
+ /** event name => the flows that listen to it */
70
+ this.entries = new Map();
71
+ /** active runs by runId */
72
+ this.runs = new Map();
73
+ this.statusListeners = new Set();
74
+ /**
75
+ * start listening: one listener per event type on the target. Returns `stop`.
76
+ * Without a target (SSR, no document) nothing happens. Calling it twice does not subscribe twice.
77
+ */
78
+ this.start = () => {
79
+ var _a;
80
+ if (this.target)
81
+ return this.stop;
82
+ const target = (_a = this.options.target) !== null && _a !== void 0 ? _a : (0, names_js_1.getDocument)();
83
+ if (!target || typeof target.addEventListener !== 'function')
84
+ return this.stop;
85
+ this.target = target;
86
+ this.listeners = new AbortController();
87
+ for (const event of this.entries.keys())
88
+ this.listen(event);
89
+ return this.stop;
90
+ };
91
+ /** remove every listener and abort every running or queued run. `start()` works again afterwards */
92
+ this.stop = () => {
93
+ const { target, listeners } = this;
94
+ this.target = undefined;
95
+ this.listeners = undefined;
96
+ if (target && listeners) {
97
+ listeners.abort();
98
+ // for targets that do not know the `signal` option of addEventListener
99
+ for (const event of this.entries.keys())
100
+ target.removeEventListener(this.prefix + event, this.onEvent);
101
+ }
102
+ for (const list of [...this.entries.values()]) {
103
+ list.forEach((entry) => this.cancelRuns(entry, 'dom-trigger stopped'));
104
+ }
105
+ };
106
+ this.onEvent = (event) => {
107
+ const entries = this.entries.get(event.type.slice(this.prefix.length));
108
+ if (!this.target || !entries || entries.length === 0)
109
+ return;
110
+ // tells the dispatcher that somebody handled it: `dispatchEvent` returns false
111
+ event.preventDefault();
112
+ const detail = event.detail;
113
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
114
+ const target = path[0] || event.target;
115
+ for (const entry of [...entries])
116
+ this.handle(entry, detail, target);
117
+ };
118
+ if (!flows || typeof flows.execute !== 'function') {
119
+ throw new TypeError('dom-trigger: flows must have an execute() method');
120
+ }
121
+ this.flows = flows;
122
+ this.options = options;
123
+ this.prefix = (_a = options.prefix) !== null && _a !== void 0 ? _a : names_js_1.DEFAULT_PREFIX;
124
+ }
125
+ /** add the dom triggers of an already registered flow. Returns the event names it now listens to */
126
+ register(flowId, triggers, opts = {}) {
127
+ const parsed = parseTriggers(flowId, triggers, opts.input);
128
+ this.assertNew(flowId, parsed);
129
+ return this.add(flowId, parsed, opts.input);
130
+ }
131
+ /**
132
+ * register the dom triggers of every flow module of an eager glob:
133
+ * `registerModules(import.meta.glob('./flows/**\/*.ts', { eager: true }), { base: './flows', registerFlows: true })`.
134
+ * Flow ids are computed exactly like `flows.registerModules` does. Nothing is registered when a module is invalid.
135
+ */
136
+ registerModules(modules, opts = {}) {
137
+ const seen = new Set();
138
+ const plan = (0, modules_js_1.resolveFlowModules)(modules, opts.base).map(({ flowId, module }) => {
139
+ const parsed = parseTriggers(flowId, module.triggers === undefined ? [] : module.triggers, module.input);
140
+ this.assertNew(flowId, parsed, seen);
141
+ return { flowId, parsed, input: parsed.length > 0 ? module.input : undefined };
142
+ });
143
+ if (opts.registerFlows && typeof this.flows.registerModules === 'function') {
144
+ this.flows.registerModules(modules, opts.base === undefined ? {} : { base: opts.base });
145
+ }
146
+ return plan.map(({ flowId, parsed, input }) => ({ flowId, events: this.add(flowId, parsed, input) }));
147
+ }
148
+ /** remove the triggers of a flow, abort its running and queued runs, drop the listeners nobody needs any more */
149
+ unregister(flowId) {
150
+ for (const [event, list] of [...this.entries]) {
151
+ const removed = list.filter((entry) => entry.flowId === flowId);
152
+ if (removed.length === 0)
153
+ continue;
154
+ const kept = list.filter((entry) => entry.flowId !== flowId);
155
+ if (kept.length > 0) {
156
+ this.entries.set(event, kept);
157
+ }
158
+ else {
159
+ this.entries.delete(event);
160
+ if (this.target)
161
+ this.target.removeEventListener(this.prefix + event, this.onEvent);
162
+ }
163
+ removed.forEach((entry) => this.cancelRuns(entry, 'flow unregistered'));
164
+ }
165
+ }
166
+ /** is a run active (running or queued)? Optionally only of one flow, or of one flow's event */
167
+ isRunning(flowId, event) {
168
+ for (const { entry } of this.runs.values()) {
169
+ if ((flowId === undefined || entry.flowId === flowId) && (event === undefined || entry.event === event))
170
+ return true;
171
+ }
172
+ return false;
173
+ }
174
+ /** the element the event of an active run was dispatched on, null once the run ended */
175
+ getTarget(runId) {
176
+ const run = this.runs.get(runId);
177
+ return run ? run.target : null;
178
+ }
179
+ /** subscribe to the status of every run. Returns the unsubscribe function */
180
+ onStatus(listener) {
181
+ this.statusListeners.add(listener);
182
+ return () => {
183
+ this.statusListeners.delete(listener);
184
+ };
185
+ }
186
+ assertNew(flowId, parsed, seen) {
187
+ for (const { event } of parsed) {
188
+ const key = `${flowId}\n${event}`;
189
+ const registered = (this.entries.get(event) || []).some((entry) => entry.flowId === flowId);
190
+ if (registered || (seen && seen.has(key))) {
191
+ throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
192
+ }
193
+ if (seen)
194
+ seen.add(key);
195
+ }
196
+ }
197
+ add(flowId, parsed, input) {
198
+ for (const { event, concurrency } of parsed) {
199
+ const entry = { flowId, event, concurrency, input, runs: new Set(), queue: [] };
200
+ const list = this.entries.get(event);
201
+ if (list) {
202
+ list.push(entry);
203
+ }
204
+ else {
205
+ this.entries.set(event, [entry]);
206
+ this.listen(event);
207
+ }
208
+ }
209
+ return parsed.map((p) => p.event);
210
+ }
211
+ listen(event) {
212
+ if (this.target && this.listeners) {
213
+ this.target.addEventListener(this.prefix + event, this.onEvent, { signal: this.listeners.signal });
214
+ }
215
+ }
216
+ handle(entry, rawDetail, target) {
217
+ const { flowId, event } = entry;
218
+ let runId = '';
219
+ try {
220
+ runId = (this.options.runId || defaultRunId)();
221
+ let detail = rawDetail;
222
+ if (entry.input) {
223
+ const result = validate(entry.input, detail);
224
+ if (!result.ok)
225
+ return this.report({ status: 'invalid', flowId, event, runId, error: result.error });
226
+ detail = result.data;
227
+ }
228
+ if (entry.concurrency === 'drop' && entry.runs.size > 0) {
229
+ return this.report({ status: 'dropped', flowId, event, runId });
230
+ }
231
+ const route = (this.options.route || defaultRoute)();
232
+ const data = { event, detail, runId, source: { flowId, route } };
233
+ const run = { runId, entry, data, target, controller: new AbortController(), started: false };
234
+ if (entry.concurrency === 'latest')
235
+ this.cancelRuns(entry, 'superseded by a newer event');
236
+ entry.runs.add(run);
237
+ this.runs.set(runId, run);
238
+ if (entry.concurrency === 'queue' && entry.runs.size > 1)
239
+ entry.queue.push(run);
240
+ else
241
+ this.launch(run);
242
+ }
243
+ catch (error) {
244
+ // a throwing runId() or route() option
245
+ this.report({ status: 'error', flowId, event, runId, error });
246
+ }
247
+ }
248
+ launch(run) {
249
+ const { entry, runId } = run;
250
+ let result;
251
+ run.started = true;
252
+ this.report({ status: 'running', flowId: entry.flowId, event: entry.event, runId });
253
+ try {
254
+ const scope = (this.options.scope ? this.options.scope() : undefined) || {};
255
+ result = Promise.resolve(this.flows.execute(entry.flowId, run.data, scope, { signal: run.controller.signal, runId }));
256
+ }
257
+ catch (error) {
258
+ result = Promise.reject(error);
259
+ }
260
+ // `settle` never throws, so this chain never rejects
261
+ result.then((output) => this.settle(run, 'done', output), (error) => this.settle(run, 'error', error));
262
+ }
263
+ /** end a run once. A run that was cancelled is already settled, whatever its flow does later is ignored */
264
+ settle(run, status, value) {
265
+ if (this.runs.get(run.runId) !== run)
266
+ return;
267
+ const { entry, runId } = run;
268
+ const { flowId, event } = entry;
269
+ this.runs.delete(runId);
270
+ entry.runs.delete(run);
271
+ this.report(status === 'done' ? { status, flowId, event, runId, output: value } : { status, flowId, event, runId, error: value });
272
+ if (entry.concurrency === 'queue' && run.started) {
273
+ const next = entry.queue.shift();
274
+ if (next)
275
+ this.launch(next);
276
+ }
277
+ }
278
+ cancelRuns(entry, message) {
279
+ const reason = abortError(message);
280
+ const runs = [...entry.runs];
281
+ entry.queue.length = 0;
282
+ for (const run of runs) {
283
+ run.controller.abort(reason);
284
+ this.settle(run, 'cancelled', reason);
285
+ }
286
+ }
287
+ /** tell the status listeners, and `onError` for 'error' and 'invalid'. Never throws */
288
+ report(status) {
289
+ for (const listener of [...this.statusListeners]) {
290
+ try {
291
+ listener(status);
292
+ }
293
+ catch (e) {
294
+ // a status listener must never break the trigger
295
+ }
296
+ }
297
+ if (status.status !== 'error' && status.status !== 'invalid')
298
+ return;
299
+ try {
300
+ const { flowId, event, runId } = status;
301
+ (this.options.onError || defaultOnError)(status.error, { status: status.status, flowId, event, runId });
302
+ }
303
+ catch (e) {
304
+ // neither must onError
305
+ }
306
+ }
307
+ }
308
+ exports.DomTrigger = DomTrigger;