@codeinkit/dom-trigger 0.0.0-stage → 0.2.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.
@@ -0,0 +1,409 @@
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 toMatcher(selector, what) {
8
+ if (typeof selector === 'string')
9
+ return (flowId) => flowId.indexOf(selector) === 0;
10
+ if (typeof selector === 'function')
11
+ return (flowId) => !!selector(flowId);
12
+ if (Array.isArray(selector) && selector.every((id) => typeof id === 'string')) {
13
+ const ids = new Set(selector);
14
+ return (flowId) => ids.has(flowId);
15
+ }
16
+ throw new TypeError(`dom-trigger: ${what} must be a flow id prefix, an array of flow ids or a function`);
17
+ }
18
+ function abortError(message) {
19
+ return Object.assign(new Error(message), { name: 'AbortError', code: 'ABORT_ERR' });
20
+ }
21
+ let runCounter = 0;
22
+ function defaultRunId() {
23
+ const c = globalThis.crypto;
24
+ if (c && typeof c.randomUUID === 'function')
25
+ return c.randomUUID();
26
+ runCounter += 1;
27
+ return `${Date.now().toString(36)}-${runCounter.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
28
+ }
29
+ function defaultRoute() {
30
+ const location = globalThis.location;
31
+ return location ? location.pathname : undefined;
32
+ }
33
+ function defaultOnError(error, info) {
34
+ console.error(`[dom-trigger] ${info.status}: flow "${info.flowId}" on "${info.event}"`, error);
35
+ }
36
+ function isSchemaLike(value) {
37
+ const schema = value;
38
+ return !!schema && (typeof schema.safeParse === 'function' || typeof schema.parse === 'function');
39
+ }
40
+ function validate(schema, value) {
41
+ var _a;
42
+ try {
43
+ if (typeof schema.safeParse !== 'function')
44
+ return { ok: true, data: schema.parse(value) };
45
+ const result = schema.safeParse(value);
46
+ return result.success ? { ok: true, data: result.data } : { ok: false, error: (_a = result.error) !== null && _a !== void 0 ? _a : new Error('invalid input') };
47
+ }
48
+ catch (error) {
49
+ return { ok: false, error };
50
+ }
51
+ }
52
+ /** the valid dom triggers of a `triggers` list. Other trigger types are ignored, a bad dom trigger throws */
53
+ function parseTriggers(flowId, triggers, input) {
54
+ if (typeof flowId !== 'string' || flowId === '')
55
+ throw new TypeError('dom-trigger: flowId must be a non-empty string');
56
+ if (!Array.isArray(triggers))
57
+ throw new TypeError(`dom-trigger: triggers of flow "${flowId}" must be an array`);
58
+ const parsed = [];
59
+ for (const trigger of triggers) {
60
+ if (!trigger || trigger.type !== 'dom')
61
+ continue;
62
+ const { event, concurrency = 'drop' } = trigger;
63
+ (0, names_js_1.assertEventName)(event);
64
+ if (CONCURRENCY.indexOf(concurrency) === -1) {
65
+ throw new TypeError(`dom-trigger: invalid concurrency ${JSON.stringify(concurrency)} for "${event}" of flow "${flowId}", expected one of ${CONCURRENCY.join(', ')}`);
66
+ }
67
+ if (parsed.some((p) => p.event === event)) {
68
+ throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
69
+ }
70
+ parsed.push({ event, concurrency });
71
+ }
72
+ if (parsed.length > 0 && input !== undefined && !isSchemaLike(input)) {
73
+ throw new TypeError(`dom-trigger: input of flow "${flowId}" must have a safeParse() or a parse() method`);
74
+ }
75
+ return parsed;
76
+ }
77
+ class DomTrigger {
78
+ constructor(flows, options = {}) {
79
+ var _a;
80
+ /** event name => the flows that listen to it */
81
+ this.entries = new Map();
82
+ /** active runs by runId */
83
+ this.runs = new Map();
84
+ this.statusListeners = new Set();
85
+ /** flows registered with `scoped`, by flow id */
86
+ this.scopedFlows = new Map();
87
+ /** the scopes that are acquired right now */
88
+ this.holds = new Set();
89
+ /**
90
+ * start listening: one listener per event type on the target. Returns `stop`.
91
+ * Without a target (SSR, no document) nothing happens. Calling it twice does not subscribe twice.
92
+ */
93
+ this.start = () => {
94
+ var _a;
95
+ if (this.target)
96
+ return this.stop;
97
+ const target = (_a = this.options.target) !== null && _a !== void 0 ? _a : (0, names_js_1.getDocument)();
98
+ if (!target || typeof target.addEventListener !== 'function')
99
+ return this.stop;
100
+ this.target = target;
101
+ this.listeners = new AbortController();
102
+ for (const event of this.entries.keys())
103
+ this.listen(event);
104
+ return this.stop;
105
+ };
106
+ /** remove every listener and abort every running or queued run. `start()` works again afterwards */
107
+ this.stop = () => {
108
+ const { target, listeners } = this;
109
+ this.target = undefined;
110
+ this.listeners = undefined;
111
+ if (target && listeners) {
112
+ listeners.abort();
113
+ // for targets that do not know the `signal` option of addEventListener
114
+ for (const event of this.entries.keys())
115
+ target.removeEventListener(this.prefix + event, this.onEvent);
116
+ }
117
+ for (const list of [...this.entries.values()]) {
118
+ list.forEach((entry) => this.cancelRuns(entry, 'dom-trigger stopped'));
119
+ }
120
+ };
121
+ this.onEvent = (event) => {
122
+ const entries = this.entries.get(event.type.slice(this.prefix.length));
123
+ if (!this.target || !entries || entries.length === 0)
124
+ return;
125
+ // tells the dispatcher that somebody handled it: `dispatchEvent` returns false
126
+ event.preventDefault();
127
+ const detail = event.detail;
128
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
129
+ const target = path[0] || event.target;
130
+ for (const entry of [...entries])
131
+ this.handle(entry, detail, target);
132
+ };
133
+ if (!flows || typeof flows.execute !== 'function') {
134
+ throw new TypeError('dom-trigger: flows must have an execute() method');
135
+ }
136
+ this.flows = flows;
137
+ this.options = options;
138
+ this.prefix = (_a = options.prefix) !== null && _a !== void 0 ? _a : names_js_1.DEFAULT_PREFIX;
139
+ }
140
+ /**
141
+ * add the dom triggers of an already registered flow. Returns the event names it now listens to.
142
+ * With `{ scoped: true }` it only listens while a `scope()` that selects it is held.
143
+ */
144
+ register(flowId, triggers, opts = {}) {
145
+ const parsed = parseTriggers(flowId, triggers, opts.input);
146
+ this.assertNew(flowId, parsed);
147
+ if (!opts.scoped)
148
+ return this.add(flowId, parsed, opts.input);
149
+ return this.addScoped(flowId, parsed, opts.input, this.holdsOf(flowId));
150
+ }
151
+ /**
152
+ * register the dom triggers of every flow module of an eager glob:
153
+ * `registerModules(import.meta.glob('./flows/**\/*.ts', { eager: true }), { base: './flows', registerFlows: true })`.
154
+ * Flow ids are computed exactly like `flows.registerModules` does. Nothing is registered when a module is invalid.
155
+ * `scoped: true` registers all of them as scoped, a selector (prefix, flow ids or predicate) only the flows
156
+ * it selects: those listen only while a `scope()` holds them, and have `scoped: true` in the result.
157
+ */
158
+ registerModules(modules, opts = {}) {
159
+ const { scoped } = opts;
160
+ const isScoped = scoped === undefined || typeof scoped === 'boolean' ? () => scoped === true : toMatcher(scoped, 'the scoped option');
161
+ const seen = new Set();
162
+ const plan = (0, modules_js_1.resolveFlowModules)(modules, opts.base).map(({ flowId, module }) => {
163
+ const parsed = parseTriggers(flowId, module.triggers === undefined ? [] : module.triggers, module.input);
164
+ this.assertNew(flowId, parsed, seen);
165
+ return {
166
+ flowId,
167
+ parsed,
168
+ input: parsed.length > 0 ? module.input : undefined,
169
+ // user predicates run here, before anything is registered, so a throwing one registers nothing
170
+ holds: parsed.length > 0 && isScoped(flowId) ? this.holdsOf(flowId) : undefined,
171
+ };
172
+ });
173
+ if (opts.registerFlows && typeof this.flows.registerModules === 'function') {
174
+ this.flows.registerModules(modules, opts.base === undefined ? {} : { base: opts.base });
175
+ }
176
+ return plan.map(({ flowId, parsed, input, holds }) => holds ? { flowId, events: this.addScoped(flowId, parsed, input, holds), scoped: true } : { flowId, events: this.add(flowId, parsed, input) });
177
+ }
178
+ /** remove the triggers of a flow (scoped ones too), abort its running and queued runs, drop the listeners nobody needs any more */
179
+ unregister(flowId) {
180
+ this.scopedFlows.delete(flowId);
181
+ this.holds.forEach((hold) => hold.held.delete(flowId));
182
+ this.remove((entry) => entry.flowId === flowId, 'flow unregistered');
183
+ }
184
+ /**
185
+ * hold the scoped flows a selector picks: a flow id prefix (`'booking/'`), an array of flow ids, or a predicate.
186
+ * They listen while at least one scope holds them. Returns the release function (idempotent): the last release
187
+ * of a flow removes its listeners and aborts its running and queued runs (status `cancelled`).
188
+ * Flows that are not scoped are never affected. A scoped flow registered later joins the scopes that select it.
189
+ * Works while stopped too: `start()` attaches the scoped flows that are held at that moment.
190
+ */
191
+ scope(selector) {
192
+ const matches = toMatcher(selector, 'the scope selector');
193
+ const hold = { matches, held: new Set() };
194
+ for (const flowId of this.scopedFlows.keys()) {
195
+ if (matches(flowId))
196
+ hold.held.add(flowId);
197
+ }
198
+ this.holds.add(hold);
199
+ hold.held.forEach((flowId) => this.acquire(flowId));
200
+ return () => {
201
+ if (!this.holds.delete(hold))
202
+ return;
203
+ const held = [...hold.held];
204
+ hold.held.clear();
205
+ held.forEach((flowId) => this.release(flowId));
206
+ };
207
+ }
208
+ /** is a run active (running or queued)? Optionally only of one flow, or of one flow's event */
209
+ isRunning(flowId, event) {
210
+ for (const { entry } of this.runs.values()) {
211
+ if ((flowId === undefined || entry.flowId === flowId) && (event === undefined || entry.event === event))
212
+ return true;
213
+ }
214
+ return false;
215
+ }
216
+ /** the element the event of an active run was dispatched on, null once the run ended */
217
+ getTarget(runId) {
218
+ const run = this.runs.get(runId);
219
+ return run ? run.target : null;
220
+ }
221
+ /** subscribe to the status of every run. Returns the unsubscribe function */
222
+ onStatus(listener) {
223
+ this.statusListeners.add(listener);
224
+ return () => {
225
+ this.statusListeners.delete(listener);
226
+ };
227
+ }
228
+ assertNew(flowId, parsed, seen) {
229
+ for (const { event } of parsed) {
230
+ const key = `${flowId}\n${event}`;
231
+ const scoped = this.scopedFlows.get(flowId);
232
+ const registered = (this.entries.get(event) || []).some((entry) => entry.flowId === flowId) || (!!scoped && scoped.triggers.some((t) => t.event === event));
233
+ if (registered || (seen && seen.has(key))) {
234
+ throw new Error(`dom-trigger: flow "${flowId}" already listens to "${event}"`);
235
+ }
236
+ if (seen)
237
+ seen.add(key);
238
+ }
239
+ }
240
+ /** the acquired scopes a scoped flow that is about to be registered joins */
241
+ holdsOf(flowId) {
242
+ return [...this.holds].filter((hold) => hold.matches(flowId));
243
+ }
244
+ addScoped(flowId, parsed, input, holds) {
245
+ if (parsed.length === 0)
246
+ return [];
247
+ let flow = this.scopedFlows.get(flowId);
248
+ if (!flow) {
249
+ flow = { triggers: [], holders: 0 };
250
+ this.scopedFlows.set(flowId, flow);
251
+ // a known scoped flow is already held by every scope that selects it
252
+ for (const hold of holds) {
253
+ if (!this.holds.has(hold) || hold.held.has(flowId))
254
+ continue;
255
+ hold.held.add(flowId);
256
+ flow.holders += 1;
257
+ }
258
+ }
259
+ flow.triggers.push(...parsed.map((p) => ({ ...p, input })));
260
+ if (flow.holders > 0)
261
+ this.add(flowId, parsed, input, true);
262
+ return parsed.map((p) => p.event);
263
+ }
264
+ acquire(flowId) {
265
+ const flow = this.scopedFlows.get(flowId);
266
+ if (!flow)
267
+ return;
268
+ flow.holders += 1;
269
+ if (flow.holders === 1)
270
+ flow.triggers.forEach((t) => this.add(flowId, [t], t.input, true));
271
+ }
272
+ release(flowId) {
273
+ const flow = this.scopedFlows.get(flowId);
274
+ if (!flow)
275
+ return;
276
+ flow.holders -= 1;
277
+ if (flow.holders === 0)
278
+ this.remove((entry) => entry.scoped && entry.flowId === flowId, 'flow scope released');
279
+ }
280
+ /** drop the matching entries, the listeners nobody needs any more, and abort their runs */
281
+ remove(match, message) {
282
+ for (const [event, list] of [...this.entries]) {
283
+ const removed = list.filter(match);
284
+ if (removed.length === 0)
285
+ continue;
286
+ const kept = list.filter((entry) => !match(entry));
287
+ if (kept.length > 0) {
288
+ this.entries.set(event, kept);
289
+ }
290
+ else {
291
+ this.entries.delete(event);
292
+ if (this.target)
293
+ this.target.removeEventListener(this.prefix + event, this.onEvent);
294
+ }
295
+ removed.forEach((entry) => this.cancelRuns(entry, message));
296
+ }
297
+ }
298
+ add(flowId, parsed, input, scoped = false) {
299
+ for (const { event, concurrency } of parsed) {
300
+ const entry = { flowId, event, concurrency, input, scoped, runs: new Set(), queue: [] };
301
+ const list = this.entries.get(event);
302
+ if (list) {
303
+ list.push(entry);
304
+ }
305
+ else {
306
+ this.entries.set(event, [entry]);
307
+ this.listen(event);
308
+ }
309
+ }
310
+ return parsed.map((p) => p.event);
311
+ }
312
+ listen(event) {
313
+ if (this.target && this.listeners) {
314
+ this.target.addEventListener(this.prefix + event, this.onEvent, { signal: this.listeners.signal });
315
+ }
316
+ }
317
+ handle(entry, rawDetail, target) {
318
+ const { flowId, event } = entry;
319
+ let runId = '';
320
+ try {
321
+ runId = (this.options.runId || defaultRunId)();
322
+ let detail = rawDetail;
323
+ if (entry.input) {
324
+ const result = validate(entry.input, detail);
325
+ if (!result.ok)
326
+ return this.report({ status: 'invalid', flowId, event, runId, error: result.error });
327
+ detail = result.data;
328
+ }
329
+ if (entry.concurrency === 'drop' && entry.runs.size > 0) {
330
+ return this.report({ status: 'dropped', flowId, event, runId });
331
+ }
332
+ const route = (this.options.route || defaultRoute)();
333
+ const data = { event, detail, runId, source: { flowId, route } };
334
+ const run = { runId, entry, data, target, controller: new AbortController(), started: false };
335
+ if (entry.concurrency === 'latest')
336
+ this.cancelRuns(entry, 'superseded by a newer event');
337
+ entry.runs.add(run);
338
+ this.runs.set(runId, run);
339
+ if (entry.concurrency === 'queue' && entry.runs.size > 1)
340
+ entry.queue.push(run);
341
+ else
342
+ this.launch(run);
343
+ }
344
+ catch (error) {
345
+ // a throwing runId() or route() option
346
+ this.report({ status: 'error', flowId, event, runId, error });
347
+ }
348
+ }
349
+ launch(run) {
350
+ const { entry, runId } = run;
351
+ let result;
352
+ run.started = true;
353
+ this.report({ status: 'running', flowId: entry.flowId, event: entry.event, runId });
354
+ try {
355
+ const scope = (this.options.scope ? this.options.scope() : undefined) || {};
356
+ result = Promise.resolve(this.flows.execute(entry.flowId, run.data, scope, { signal: run.controller.signal, runId }));
357
+ }
358
+ catch (error) {
359
+ result = Promise.reject(error);
360
+ }
361
+ // `settle` never throws, so this chain never rejects
362
+ result.then((output) => this.settle(run, 'done', output), (error) => this.settle(run, 'error', error));
363
+ }
364
+ /** end a run once. A run that was cancelled is already settled, whatever its flow does later is ignored */
365
+ settle(run, status, value) {
366
+ if (this.runs.get(run.runId) !== run)
367
+ return;
368
+ const { entry, runId } = run;
369
+ const { flowId, event } = entry;
370
+ this.runs.delete(runId);
371
+ entry.runs.delete(run);
372
+ this.report(status === 'done' ? { status, flowId, event, runId, output: value } : { status, flowId, event, runId, error: value });
373
+ if (entry.concurrency === 'queue' && run.started) {
374
+ const next = entry.queue.shift();
375
+ if (next)
376
+ this.launch(next);
377
+ }
378
+ }
379
+ cancelRuns(entry, message) {
380
+ const reason = abortError(message);
381
+ const runs = [...entry.runs];
382
+ entry.queue.length = 0;
383
+ for (const run of runs) {
384
+ run.controller.abort(reason);
385
+ this.settle(run, 'cancelled', reason);
386
+ }
387
+ }
388
+ /** tell the status listeners, and `onError` for 'error' and 'invalid'. Never throws */
389
+ report(status) {
390
+ for (const listener of [...this.statusListeners]) {
391
+ try {
392
+ listener(status);
393
+ }
394
+ catch (e) {
395
+ // a status listener must never break the trigger
396
+ }
397
+ }
398
+ if (status.status !== 'error' && status.status !== 'invalid')
399
+ return;
400
+ try {
401
+ const { flowId, event, runId } = status;
402
+ (this.options.onError || defaultOnError)(status.error, { status: status.status, flowId, event, runId });
403
+ }
404
+ catch (e) {
405
+ // neither must onError
406
+ }
407
+ }
408
+ }
409
+ exports.DomTrigger = DomTrigger;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createEmitter = createEmitter;
4
+ exports.createDomPort = createDomPort;
5
+ const names_js_1 = require("./names.js");
6
+ /** the CustomEvent constructor of the target's own realm (iframes), else the global one, else none (SSR) */
7
+ function customEventCtor(target) {
8
+ var _a;
9
+ const t = target;
10
+ const view = (t.ownerDocument ? t.ownerDocument.defaultView : t.defaultView) || (t.window === t ? t : undefined);
11
+ const ctor = (_a = view === null || view === void 0 ? void 0 : view.CustomEvent) !== null && _a !== void 0 ? _a : globalThis.CustomEvent;
12
+ return typeof ctor === 'function' ? ctor : undefined;
13
+ }
14
+ /** true when a DomTrigger handled the event (it called `preventDefault()`) */
15
+ function dispatch(target, prefix, name, detail) {
16
+ (0, names_js_1.assertEventName)(name);
17
+ const Ctor = target && customEventCtor(target);
18
+ if (!target || !Ctor)
19
+ return false;
20
+ return !target.dispatchEvent(new Ctor(prefix + name, { detail, bubbles: true, composed: true, cancelable: true }));
21
+ }
22
+ function createEmitter(opts = {}) {
23
+ var _a;
24
+ const prefix = (_a = opts.prefix) !== null && _a !== void 0 ? _a : names_js_1.DEFAULT_PREFIX;
25
+ return {
26
+ emit: (target, name, detail) => dispatch(target, prefix, name, detail),
27
+ emitOnDocument: (name, detail) => dispatch((0, names_js_1.getDocument)(), prefix, name, detail),
28
+ listen(target, name, fn) {
29
+ (0, names_js_1.assertEventName)(name);
30
+ const type = prefix + name;
31
+ const listener = (event) => fn(event.detail, event);
32
+ target.addEventListener(type, listener);
33
+ return () => target.removeEventListener(type, listener);
34
+ },
35
+ };
36
+ }
37
+ /**
38
+ * A port for `new Flows({ ports: { dom: createDomPort() } })`, so UI actions can announce what
39
+ * happened: `unsafe.dom.emit('booking.created', { id })`. Dispatches on `target` (default: the
40
+ * document, resolved on every emit). The target lives in the closure, so freezing the port is safe.
41
+ */
42
+ function createDomPort(opts = {}) {
43
+ var _a;
44
+ const prefix = (_a = opts.prefix) !== null && _a !== void 0 ? _a : names_js_1.DEFAULT_PREFIX;
45
+ return {
46
+ emit: (name, detail) => { var _a; return dispatch((_a = opts.target) !== null && _a !== void 0 ? _a : (0, names_js_1.getDocument)(), prefix, name, detail); },
47
+ };
48
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isEventName = exports.DEFAULT_PREFIX = exports.EVENT_NAME_RE = exports.resolveFlowModules = exports.createDomPort = exports.createEmitter = exports.DomTrigger = void 0;
4
+ var dom_trigger_js_1 = require("./dom-trigger.js");
5
+ Object.defineProperty(exports, "DomTrigger", { enumerable: true, get: function () { return dom_trigger_js_1.DomTrigger; } });
6
+ var emitter_js_1 = require("./emitter.js");
7
+ Object.defineProperty(exports, "createEmitter", { enumerable: true, get: function () { return emitter_js_1.createEmitter; } });
8
+ Object.defineProperty(exports, "createDomPort", { enumerable: true, get: function () { return emitter_js_1.createDomPort; } });
9
+ var modules_js_1 = require("./modules.js");
10
+ Object.defineProperty(exports, "resolveFlowModules", { enumerable: true, get: function () { return modules_js_1.resolveFlowModules; } });
11
+ var names_js_1 = require("./names.js");
12
+ Object.defineProperty(exports, "EVENT_NAME_RE", { enumerable: true, get: function () { return names_js_1.EVENT_NAME_RE; } });
13
+ Object.defineProperty(exports, "DEFAULT_PREFIX", { enumerable: true, get: function () { return names_js_1.DEFAULT_PREFIX; } });
14
+ Object.defineProperty(exports, "isEventName", { enumerable: true, get: function () { return names_js_1.isEventName; } });
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveFlowModules = resolveFlowModules;
4
+ /** './flows/' | 'flows/' | './flows' => 'flows' */
5
+ function normalizeModulePath(p) {
6
+ return p.replace(/^(\.\/)+/, '').replace(/\/+$/, '');
7
+ }
8
+ function commonDirectory(keys) {
9
+ let common = null;
10
+ for (const key of keys) {
11
+ const dirs = key.split('/').slice(0, -1);
12
+ if (common === null) {
13
+ common = dirs;
14
+ continue;
15
+ }
16
+ let n = 0;
17
+ while (n < common.length && n < dirs.length && common[n] === dirs[n])
18
+ n++;
19
+ common = common.slice(0, n);
20
+ }
21
+ return common ? common.join('/') : '';
22
+ }
23
+ /**
24
+ * The flow modules of an eager `import.meta.glob` object with their flow ids.
25
+ * Must stay the same algorithm as `Flows#registerModules` of @codeinkit/flows 4.0.0-alpha.1
26
+ * (test/modules.test.ts has the parity test): modules without an array `default` are skipped.
27
+ */
28
+ function resolveFlowModules(modules, base) {
29
+ const keys = Object.keys(modules);
30
+ for (const key of keys) {
31
+ if (typeof modules[key] === 'function') {
32
+ throw new TypeError(`registerModules: "${key}" is a loader function, not a module. Use import.meta.glob(pattern, { eager: true })`);
33
+ }
34
+ }
35
+ const normalized = keys.map(normalizeModulePath);
36
+ const baseDir = base !== undefined ? normalizeModulePath(base) : commonDirectory(normalized);
37
+ const prefix = baseDir === '' ? '' : `${baseDir}/`;
38
+ const resolved = [];
39
+ keys.forEach((key, index) => {
40
+ const mod = modules[key];
41
+ if (!mod || !Array.isArray(mod.default))
42
+ return;
43
+ const filePath = normalized[index];
44
+ const relativeFilePath = filePath.indexOf(prefix) === 0 ? filePath.slice(prefix.length) : filePath;
45
+ resolved.push({ flowId: relativeFilePath.split('.')[0], module: mod });
46
+ });
47
+ return resolved;
48
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_PREFIX = exports.EVENT_NAME_RE = void 0;
4
+ exports.isEventName = isEventName;
5
+ exports.assertEventName = assertEventName;
6
+ exports.getDocument = getDocument;
7
+ /** `domain.verb`: lowercase segments separated by dots, at least two of them */
8
+ exports.EVENT_NAME_RE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
9
+ /** the DOM event type is `prefix + name`, e.g. `flows:booking.submit` */
10
+ exports.DEFAULT_PREFIX = 'flows:';
11
+ function isEventName(name) {
12
+ return typeof name === 'string' && exports.EVENT_NAME_RE.test(name);
13
+ }
14
+ function assertEventName(name) {
15
+ if (!isEventName(name)) {
16
+ throw new TypeError(`dom-trigger: invalid event name ${JSON.stringify(name)}, expected "domain.verb" (${exports.EVENT_NAME_RE})`);
17
+ }
18
+ }
19
+ /** `globalThis.document`, undefined on the server. Never read at import time */
20
+ function getDocument() {
21
+ return typeof document === 'undefined' ? undefined : document;
22
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs","sideEffects":false}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });