@sylwellsoftware/glue 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ # Glue experimental APIs
2
+
3
+ Everything imported from `@sylwellsoftware/glue/experimental` is outside Glue's
4
+ stable alpha compatibility surface. It may change in any `0.x` release without
5
+ a deprecation window. The stable package root does not export these symbols.
6
+
7
+ ## `AsyncCommand`
8
+
9
+ `AsyncCommand<TArguments, TResult, TError>` owns one abortable asynchronous
10
+ mutation lifecycle. The command itself is a readable emitter whose value is the
11
+ last successful result and whose fetch state/error describe the current or
12
+ latest run. `isRunning` is a read-only boolean emitter for presentation logic.
13
+
14
+ ```ts
15
+ import {AsyncCommand} from '@sylwellsoftware/glue/experimental'
16
+
17
+ const save = new AsyncCommand<{id: string}, {saved: boolean}>({
18
+ async execute({id}, {signal}) {
19
+ const response = await fetch(`/api/records/${id}`, {method: 'POST', signal})
20
+ return {saved: response.ok}
21
+ },
22
+ })
23
+
24
+ const result = await save.run({id: 'record-1'})
25
+ save.abort()
26
+ save.reset()
27
+ save.dispose()
28
+ ```
29
+
30
+ The default concurrency policy is `ignore`: an overlapping `run()` returns the
31
+ active promise without executing the new arguments. `replace` aborts and
32
+ supersedes the active run; `reject` rejects only the overlapping invocation
33
+ with `AsyncCommandConcurrencyError`. Executors always receive the current
34
+ abort signal and optional causal event.
35
+
36
+ Successful runs resolve their result. Failed, aborted, stale, or disposed runs
37
+ resolve `undefined`; failures remain observable through `getError()` and
38
+ `FetchState.Error`. The last successful result remains visible while loading
39
+ and after an error. `reset()` aborts active work and returns the snapshot to
40
+ `FetchState.Initial`. `dispose()` is idempotent and permanently suppresses
41
+ late settlement.
42
+
43
+ The command does not queue, retry, report notifications, or own DOM behavior.
44
+ Batch progress and partial-result aggregation remain application concerns.
package/LICENSE ADDED
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Glue
2
+ Copyright 2026 Sylwell Software
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # Glue
2
+
3
+ Glue is the platform-neutral reactive core used by Fray. The experimental
4
+ `0.1.0-alpha.1` candidate is not yet published. Its implementation and tests
5
+ are strict TypeScript; the ESM build includes declarations and declaration
6
+ maps.
7
+
8
+ After publication, install it with pnpm:
9
+
10
+ ```bash
11
+ pnpm add @sylwellsoftware/glue
12
+ ```
13
+
14
+ Glue is ESM-only. Core emitters, derived state, and diagnostics support Node 22+
15
+ and modern ESM runtimes without a DOM. `LiveQuery` needs `AbortController`, and
16
+ `RestQueryHandler` needs Fetch and URL capabilities unless they are injected.
17
+
18
+ ## Emitters
19
+
20
+ ```ts
21
+ import {DerivedEmitter, Emitter, FetchState} from '@sylwellsoftware/glue'
22
+
23
+ const count = new Emitter(1, {purpose: 'count'})
24
+ const doubled = new DerivedEmitter([count], ([value]) => value * 2)
25
+
26
+ const unsubscribe = doubled.subscribe(({value, fetchState, error, event}) => {
27
+ console.log({value, fetchState, error, event})
28
+ })
29
+
30
+ count.set(2)
31
+ unsubscribe()
32
+ doubled.dispose()
33
+ ```
34
+
35
+ A local `Emitter` defaults to `FetchState.Ready`. `setWithState()` notifies when
36
+ the value, fetch state, or error changes. Values use `Object.is` equality unless
37
+ the `equals` option supplies a comparator. `subscribe()` emits the current
38
+ snapshot by default; `subscribe(listener, {emitCurrent: false})` and
39
+ `subscribeFutureValues(listener)` observe only future snapshots. Unsubscribe
40
+ functions and `dispose()` are idempotent.
41
+
42
+ Every notification has one shape:
43
+
44
+ ```ts
45
+ { value, fetchState, error, event }
46
+ ```
47
+
48
+ `DerivedEmitter` passes source values—including `null` and `undefined`—to its
49
+ compute function in source order. With no sources it computes once with `[]` and
50
+ is ready. A thrown compute function produces error state. Source errors are a
51
+ stable array of `{sourceIndex, error}` entries; a compute failure uses
52
+ `sourceIndex: null`. State precedence is `error > loading > initial > ready`.
53
+ Replacing sources releases every old subscription, and disposal releases the
54
+ current ones.
55
+
56
+ `emitter.map(fn)` transforms the complete value. `emitter.mapEach(fn)` requires
57
+ an array and transforms its non-nullish members.
58
+
59
+ ## Live queries
60
+
61
+ ```js
62
+ import {Emitter, LiveQuery, RestQueryHandler} from '@sylwellsoftware/glue'
63
+
64
+ const search = new Emitter('ada')
65
+ const handler = new RestQueryHandler({
66
+ url: '/api/users',
67
+ baseUrl: 'https://example.test/',
68
+ fetch: globalThis.fetch,
69
+ })
70
+
71
+ const users = new LiveQuery({handler, args: {search}})
72
+ ```
73
+
74
+ Arguments are a named record of emitters. Construction fetches immediately
75
+ unless `autoFetch: false`; `refresh()` and `retry()` return the active request
76
+ promise. A newer request aborts and supersedes the older request, and stale
77
+ results cannot overwrite current state. `dispose()` aborts the active request
78
+ and releases argument subscriptions.
79
+
80
+ By default the last successful value remains visible while refreshing and after
81
+ a refresh error. Set `keepPreviousValue: false` to clear it while loading or in
82
+ error state.
83
+
84
+ The REST adapter accepts injected `fetch`, `baseUrl`, and `serialize` behavior.
85
+ Its generic serializer omits `undefined` and empty arrays, encodes `null` as an
86
+ empty value, repeats keys for arrays, JSON-encodes objects, and stringifies
87
+ scalars. Application-specific table filter/sort formats belong in an injected
88
+ serializer, not Glue. A `RestQueryHandler` result generic declares the expected
89
+ JSON shape but does not validate it at runtime; validate untrusted responses at
90
+ the application boundary.
91
+
92
+ ## Optional tracing
93
+
94
+ Tracing allocates no event when an emitter has `trace: false`, no diagnostic
95
+ observer is subscribed, and no parent event is supplied. Subscribe with
96
+ `EventBus.subscribe(listener)` to observe top-level events. Events have stable
97
+ process-local IDs, timestamps, weak owner references where supported, and
98
+ explicit parent/child causality. The bus retains neither event history nor
99
+ owners; its unsubscribe function is idempotent.
100
+
101
+ ## Experimental commands
102
+
103
+ `@sylwellsoftware/glue/experimental` exports `AsyncCommand`, an abortable
104
+ mutation lifecycle with explicit `ignore`, `replace`, and `reject` concurrency
105
+ policies. It exposes the last result/error through the standard emitter
106
+ snapshot and a read-only `isRunning` view. It deliberately does not own batch
107
+ progress, retries, notifications, or UI behavior. See
108
+ [EXPERIMENTAL.md](EXPERIMENTAL.md) for the provisional contract.
109
+
110
+ ## Local checks
111
+
112
+ ```text
113
+ pnpm --filter @sylwellsoftware/glue test
114
+ pnpm --filter @sylwellsoftware/glue typecheck
115
+ pnpm --filter @sylwellsoftware/glue build
116
+ pnpm --filter @sylwellsoftware/glue test:types:consumer
117
+ ```
118
+
119
+ Glue intentionally does not own a DOM renderer, component lifecycle,
120
+ application-specific query encoding, persistent event history, CommonJS build,
121
+ or framework adapter. Fray consumes Glue as a peer; browser UI belongs there.
122
+
123
+ See the [workspace overview](../../README.md), [alpha API
124
+ surface](../../docs/API_SURFACE.md), [changelog](../../CHANGELOG.md),
125
+ [contribution guide](../../CONTRIBUTING.md), and [security
126
+ policy](../../SECURITY.md).
@@ -0,0 +1,43 @@
1
+ import { EventBubble } from '../debugging/eventBubble.js';
2
+ import { BaseEmitter } from '../emitters/baseEmitter.js';
3
+ import type { ReadableEmitter } from '../emitters/baseEmitter.js';
4
+ import type { AbortSignalLike } from '../queryhandling/queryHandler.js';
5
+ export type AsyncCommandConcurrency = 'ignore' | 'replace' | 'reject';
6
+ export interface AsyncCommandContext {
7
+ readonly signal: AbortSignalLike;
8
+ readonly event: EventBubble<unknown> | null;
9
+ }
10
+ export type AsyncCommandExecutor<TArguments, TResult> = (arguments_: TArguments, context: AsyncCommandContext) => TResult | PromiseLike<TResult>;
11
+ export interface AsyncCommandOptions<TArguments, TResult, TError = unknown> {
12
+ execute: AsyncCommandExecutor<TArguments, TResult>;
13
+ concurrency?: AsyncCommandConcurrency;
14
+ mapError?: (error: unknown) => TError;
15
+ owner?: unknown;
16
+ purpose?: string;
17
+ trace?: boolean;
18
+ }
19
+ export declare class AsyncCommandConcurrencyError extends Error {
20
+ constructor();
21
+ }
22
+ /** Experimental abortable mutation state with an explicit concurrency policy. */
23
+ export declare class AsyncCommand<TArguments, TResult, TError = unknown> extends BaseEmitter<TResult | undefined, TError> {
24
+ readonly execute: AsyncCommandExecutor<TArguments, TResult>;
25
+ readonly concurrency: AsyncCommandConcurrency;
26
+ readonly isRunning: ReadableEmitter<boolean, never>;
27
+ private readonly mapError;
28
+ private readonly runningEmitter;
29
+ private requestId;
30
+ private abortController;
31
+ private lastSuccessfulValue;
32
+ private hasSuccessfulValue;
33
+ /** Exposed for deterministic tests; consumers should use run()/abort(). */
34
+ _activeRequest: Promise<TResult | undefined> | null;
35
+ constructor(options: AsyncCommandOptions<TArguments, TResult, TError>);
36
+ run(arguments_: TArguments, eventOrCause?: EventBubble<unknown> | unknown): Promise<TResult | undefined>;
37
+ abort(eventOrCause?: EventBubble<unknown> | unknown): boolean;
38
+ reset(eventOrCause?: EventBubble<unknown> | unknown): void;
39
+ dispose(): void;
40
+ private isCurrentRequest;
41
+ private mapCommandError;
42
+ }
43
+ //# sourceMappingURL=asyncCommand.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asyncCommand.d.ts","sourceRoot":"","sources":["../../src/commands/asyncCommand.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACvD,OAAO,EAAC,WAAW,EAAC,MAAM,4BAA4B,CAAA;AACtD,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,4BAA4B,CAAA;AAG/D,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,kCAAkC,CAAA;AAErE,MAAM,MAAM,uBAAuB,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAA;AAErE,MAAM,WAAW,mBAAmB;IAChC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;IAChC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;CAC9C;AAED,MAAM,MAAM,oBAAoB,CAAC,UAAU,EAAE,OAAO,IAAI,CACpD,UAAU,EAAE,UAAU,EACtB,OAAO,EAAE,mBAAmB,KAC3B,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,CAAA;AAEnC,MAAM,WAAW,mBAAmB,CAAC,UAAU,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO;IACtE,OAAO,EAAE,oBAAoB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;IAClD,WAAW,CAAC,EAAE,uBAAuB,CAAA;IACrC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,MAAM,CAAA;IACrC,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,KAAK,CAAC,EAAE,OAAO,CAAA;CAClB;AAWD,qBAAa,4BAA6B,SAAQ,KAAK;;CAKtD;AAED,iFAAiF;AACjF,qBAAa,YAAY,CAAC,UAAU,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAC3D,SAAQ,WAAW,CAAC,OAAO,GAAG,SAAS,EAAE,MAAM,CAAC;IAChD,QAAQ,CAAC,OAAO,EAAE,oBAAoB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;IAC3D,QAAQ,CAAC,WAAW,EAAE,uBAAuB,CAAA;IAC7C,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IACnD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA4B;IACrD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAyB;IACxD,OAAO,CAAC,SAAS,CAAI;IACrB,OAAO,CAAC,eAAe,CAAmC;IAC1D,OAAO,CAAC,mBAAmB,CAAqB;IAChD,OAAO,CAAC,kBAAkB,CAAQ;IAClC,2EAA2E;IAC3E,cAAc,EAAE,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,GAAG,IAAI,CAAO;gBAE9C,OAAO,EAAE,mBAAmB,CAAC,UAAU,EAAE,OAAO,EAAE,MAAM,CAAC;IAgCrE,GAAG,CACC,UAAU,EAAE,UAAU,EACtB,YAAY,GAAE,WAAW,CAAC,OAAO,CAAC,GAAG,OAAuB,GAC7D,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC;IAiE/B,KAAK,CAAC,YAAY,GAAE,WAAW,CAAC,OAAO,CAAC,GAAG,OAA2B,GAAG,OAAO;IAmBhF,KAAK,CAAC,YAAY,GAAE,WAAW,CAAC,OAAO,CAAC,GAAG,OAAyB,GAAG,IAAI;IAelE,OAAO,IAAI,IAAI;IAWxB,OAAO,CAAC,gBAAgB;IAOxB,OAAO,CAAC,eAAe;CAO1B"}
@@ -0,0 +1,26 @@
1
+ export interface EventOptions<TValue = unknown> {
2
+ owner?: unknown;
3
+ purpose?: string;
4
+ value?: TValue;
5
+ cause?: unknown;
6
+ parent?: EventBubble<unknown> | null;
7
+ timestamp?: number;
8
+ }
9
+ /** A causal diagnostic event. EventBus deliberately stores no history. */
10
+ export declare class EventBubble<TValue = unknown> {
11
+ readonly id: string;
12
+ readonly timestamp: number;
13
+ readonly purpose: string;
14
+ readonly cause: unknown;
15
+ readonly value: TValue | undefined;
16
+ readonly parent: EventBubble<unknown> | null;
17
+ readonly parentBubble: EventBubble<unknown> | null;
18
+ readonly children: EventBubble<unknown>[];
19
+ readonly ownerType: string | null;
20
+ private readonly ownerRef;
21
+ private readonly strongOwner;
22
+ constructor(options?: EventOptions<TValue>);
23
+ get owner(): unknown;
24
+ registerChild(child: EventBubble<unknown>): void;
25
+ }
26
+ //# sourceMappingURL=eventBubble.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventBubble.d.ts","sourceRoot":"","sources":["../../src/debugging/eventBubble.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,YAAY,CAAC,MAAM,GAAG,OAAO;IAC1C,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;IACpC,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,0EAA0E;AAC1E,qBAAa,WAAW,CAAC,MAAM,GAAG,OAAO;IACrC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAA;IAClC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;IAC5C,QAAQ,CAAC,YAAY,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;IAClD,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,CAAK;IAC9C,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;IACjC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAwB;IACjD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;gBAEzB,OAAO,GAAE,YAAY,CAAC,MAAM,CAAM;IA4B9C,IAAI,KAAK,IAAI,OAAO,CAEnB;IAED,aAAa,CAAC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI;CAMnD"}
@@ -0,0 +1,18 @@
1
+ import type { EventBubble } from './eventBubble.js';
2
+ export type EventListener = (event: EventBubble<unknown>) => void;
3
+ export interface BubbleGraph {
4
+ addBubble(event: EventBubble<unknown>): void;
5
+ }
6
+ declare function subscribe(listener: EventListener): () => void;
7
+ declare function emit(event: EventBubble<unknown>): void;
8
+ /** Process-local diagnostic observer that retains no event history. */
9
+ export declare const EventBus: Readonly<{
10
+ subscribe: typeof subscribe;
11
+ emit: typeof emit;
12
+ emitBubble: typeof emit;
13
+ registerBubbleGraph(graph: BubbleGraph): () => void;
14
+ readonly hasSubscribers: boolean;
15
+ readonly subscriberCount: number;
16
+ }>;
17
+ export {};
18
+ //# sourceMappingURL=eventBus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventBus.d.ts","sourceRoot":"","sources":["../../src/debugging/eventBus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,kBAAkB,CAAA;AAEjD,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,KAAK,IAAI,CAAA;AAEjE,MAAM,WAAW,WAAW;IACxB,SAAS,CAAC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;CAC/C;AAID,iBAAS,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,IAAI,CAYtD;AAED,iBAAS,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAE/C;AAED,uEAAuE;AACvE,eAAO,MAAM,QAAQ;;;;+BAIU,WAAW,GAAG,MAAM,IAAI;6BAM7B,OAAO;8BAGN,MAAM;EAG/B,CAAA"}
@@ -0,0 +1,293 @@
1
+ var T = Object.defineProperty;
2
+ var O = (r, e, t) => e in r ? T(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
3
+ var i = (r, e, t) => O(r, typeof e != "symbol" ? e + "" : e, t);
4
+ let D = 1;
5
+ class b {
6
+ constructor(e = {}) {
7
+ i(this, "id");
8
+ i(this, "timestamp");
9
+ i(this, "purpose");
10
+ i(this, "cause");
11
+ i(this, "value");
12
+ i(this, "parent");
13
+ i(this, "parentBubble");
14
+ i(this, "children", []);
15
+ i(this, "ownerType");
16
+ i(this, "ownerRef");
17
+ i(this, "strongOwner");
18
+ var s;
19
+ if (e == null || typeof e != "object" || Array.isArray(e))
20
+ throw new TypeError("EventBubble options must be an object");
21
+ this.id = `event-${D++}`, this.timestamp = e.timestamp ?? Date.now(), this.purpose = e.purpose ?? "unspecified", this.cause = e.cause ?? null, this.value = e.value, this.parent = e.parent ?? null, this.parentBubble = this.parent;
22
+ const t = e.owner;
23
+ this.ownerType = t == null ? null : q(t) ?? typeof t, A(t) && typeof WeakRef == "function" ? (this.ownerRef = new WeakRef(t), this.strongOwner = void 0) : (this.ownerRef = null, this.strongOwner = t), (s = this.parent) == null || s.registerChild(this);
24
+ }
25
+ get owner() {
26
+ var e;
27
+ return ((e = this.ownerRef) == null ? void 0 : e.deref()) ?? this.strongOwner;
28
+ }
29
+ registerChild(e) {
30
+ if (!(e instanceof b))
31
+ throw new TypeError("EventBubble children must be EventBubble instances");
32
+ this.children.includes(e) || this.children.push(e);
33
+ }
34
+ }
35
+ function A(r) {
36
+ return typeof r == "object" && r !== null || typeof r == "function";
37
+ }
38
+ function q(r) {
39
+ const e = Reflect.get(r, "constructor");
40
+ if (e == null || typeof e != "object" && typeof e != "function")
41
+ return;
42
+ const t = Reflect.get(e, "name");
43
+ return typeof t == "string" ? t : void 0;
44
+ }
45
+ const f = /* @__PURE__ */ new Set();
46
+ function y(r) {
47
+ if (typeof r != "function")
48
+ throw new TypeError("EventBus.subscribe requires a function");
49
+ f.add(r);
50
+ let e = !0;
51
+ return () => {
52
+ e && (e = !1, f.delete(r));
53
+ };
54
+ }
55
+ function E(r) {
56
+ for (const e of [...f]) e(r);
57
+ }
58
+ const g = Object.freeze({
59
+ subscribe: y,
60
+ emit: E,
61
+ emitBubble: E,
62
+ registerBubbleGraph(r) {
63
+ if (r == null || typeof r.addBubble != "function")
64
+ throw new TypeError("registerBubbleGraph requires an addBubble() method");
65
+ return y((e) => r.addBubble(e));
66
+ },
67
+ get hasSubscribers() {
68
+ return f.size > 0;
69
+ },
70
+ get subscriberCount() {
71
+ return f.size;
72
+ }
73
+ }), c = Object.freeze({
74
+ Error: "error",
75
+ Loading: "loading",
76
+ Initial: "initial",
77
+ Ready: "ready"
78
+ }), d = /* @__PURE__ */ new Map([
79
+ [c.Ready, 1],
80
+ [c.Initial, 2],
81
+ [c.Loading, 3],
82
+ [c.Error, 4]
83
+ ]);
84
+ function S(r) {
85
+ let e = c.Ready;
86
+ for (const t of r) {
87
+ if (!d.has(t))
88
+ throw new TypeError(`Unknown fetch state: ${String(t)}`);
89
+ if ((d.get(t) ?? 0) > (d.get(e) ?? 0) && (e = t), e === c.Error) break;
90
+ }
91
+ return e;
92
+ }
93
+ class j {
94
+ constructor(e, t = {}) {
95
+ i(this, "subscribers", /* @__PURE__ */ new Set());
96
+ i(this, "value");
97
+ i(this, "fetchState");
98
+ i(this, "error");
99
+ i(this, "equals");
100
+ i(this, "isDisposed", !1);
101
+ i(this, "owner");
102
+ i(this, "purpose");
103
+ i(this, "trace");
104
+ if (t == null || typeof t != "object" || Array.isArray(t))
105
+ throw new TypeError("Emitter options must be an object");
106
+ if (this.value = e, this.fetchState = t.fetchState ?? c.Ready, this.error = t.error ?? null, this.equals = t.equals ?? Object.is, this.owner = t.owner, this.purpose = t.purpose ?? this.constructor.name, this.trace = t.trace ?? !1, typeof this.equals != "function")
107
+ throw new TypeError("Emitter equals option must be a function");
108
+ m(this.fetchState);
109
+ }
110
+ subscribe(e, t = {}) {
111
+ if (this.isDisposed) throw new Error("Cannot subscribe to a disposed emitter");
112
+ if (typeof e != "function")
113
+ throw new TypeError("subscribe requires a function");
114
+ if (t == null || typeof t != "object" || Array.isArray(t))
115
+ throw new TypeError("subscribe options must be an object");
116
+ const { emitCurrent: s = !0, parentEvent: n = null } = t;
117
+ if (this.subscribers.add(e), s) {
118
+ const u = this.createEvent("subscribed", n, this.value);
119
+ e(this.notification(u));
120
+ }
121
+ let o = !0;
122
+ return () => {
123
+ o && (o = !1, this.subscribers.delete(e));
124
+ };
125
+ }
126
+ subscribeFutureValues(e) {
127
+ return this.subscribe(e, { emitCurrent: !1 });
128
+ }
129
+ get() {
130
+ return this.value;
131
+ }
132
+ getError() {
133
+ return this.error;
134
+ }
135
+ getFetchState() {
136
+ return this.fetchState;
137
+ }
138
+ get disposed() {
139
+ return this.isDisposed;
140
+ }
141
+ get subscriberCount() {
142
+ return this.subscribers.size;
143
+ }
144
+ map(e, t = {}) {
145
+ if (typeof e != "function") throw new TypeError("map requires a function");
146
+ return new v(
147
+ [this],
148
+ ([s]) => e(s),
149
+ {
150
+ ...t,
151
+ owner: t.owner ?? this.owner,
152
+ purpose: t.purpose ?? `${this.purpose}:map`,
153
+ trace: t.trace ?? this.trace
154
+ }
155
+ );
156
+ }
157
+ mapEach(e, t = {}) {
158
+ if (typeof e != "function") throw new TypeError("mapEach requires a function");
159
+ return new v([this], ([s]) => {
160
+ if (s == null) return s;
161
+ if (!Array.isArray(s))
162
+ throw new TypeError("mapEach source value must be an array");
163
+ return s.map((o, u) => o == null ? o : e(o, u));
164
+ }, {
165
+ ...t,
166
+ purpose: t.purpose ?? `${this.purpose}:mapEach`
167
+ });
168
+ }
169
+ dispose() {
170
+ this.isDisposed || (this.isDisposed = !0, this.subscribers.clear());
171
+ }
172
+ notification(e = null) {
173
+ return Object.freeze({
174
+ value: this.value,
175
+ fetchState: this.fetchState,
176
+ error: this.error,
177
+ event: e
178
+ });
179
+ }
180
+ notify(e = null) {
181
+ if (this.isDisposed) return;
182
+ const t = this.notification(e);
183
+ for (const s of [...this.subscribers]) s(t);
184
+ }
185
+ setSnapshot(e = {}) {
186
+ if (this.isDisposed) return !1;
187
+ const t = Object.hasOwn(e, "value") ? e.value : this.value, s = e.fetchState ?? this.fetchState, n = Object.hasOwn(e, "error") ? e.error : this.error, o = e.cause ?? "state changed", u = e.parentEvent ?? null;
188
+ if (m(s), !(!this.equals(this.value, t) || this.fetchState !== s || !Object.is(this.error, n))) return !1;
189
+ this.value = t, this.fetchState = s, this.error = n;
190
+ const h = this.createEvent(o, u, t);
191
+ return this.notify(h), !0;
192
+ }
193
+ createEvent(e, t = null, s = this.value) {
194
+ if (!this.trace && !t && !g.hasSubscribers) return null;
195
+ const n = new b({
196
+ owner: this.owner ?? this,
197
+ purpose: this.purpose,
198
+ value: s,
199
+ cause: e,
200
+ parent: t
201
+ });
202
+ return t || g.emit(n), n;
203
+ }
204
+ }
205
+ class v extends j {
206
+ constructor(t, s, n = {}) {
207
+ const { computeFetchState: o = S, ...u } = n;
208
+ super(void 0, {
209
+ ...u,
210
+ fetchState: c.Initial,
211
+ error: null
212
+ });
213
+ i(this, "sources");
214
+ i(this, "sourceUnsubscribers", []);
215
+ i(this, "compute");
216
+ i(this, "computeFetchState");
217
+ this.sources = [], this.compute = s, this.computeFetchState = o, this.setSourcesAndCompute(t, s, { notify: !1 });
218
+ }
219
+ setSourcesAndCompute(t, s = this.compute, n = {}) {
220
+ if (this.isDisposed) throw new Error("Cannot update a disposed derived emitter");
221
+ if (!Array.isArray(t) || t.some((o) => !C(o)))
222
+ throw new TypeError("DerivedEmitter sources must be an array of emitters");
223
+ if (typeof s != "function")
224
+ throw new TypeError("DerivedEmitter compute must be a function");
225
+ return this.releaseSources(), this.sources = [...t], this.compute = s, this.sourceUnsubscribers = this.sources.map(
226
+ (o) => o.subscribe(({ event: u }) => this.recompute(u), { emitCurrent: !1 })
227
+ ), this.recompute(n.parentEvent ?? null, n.notify ?? !0), this;
228
+ }
229
+ dispose() {
230
+ this.isDisposed || (this.releaseSources(), super.dispose());
231
+ }
232
+ releaseSources() {
233
+ for (const t of this.sourceUnsubscribers) t();
234
+ this.sourceUnsubscribers = [];
235
+ }
236
+ recompute(t = null, s = !0) {
237
+ const n = this.sources.map((a) => a.get()), o = this.sources.map((a) => a.getFetchState()), u = this.sources.map((a, B) => ({ sourceIndex: B, error: a.getError() })).filter((a) => a.error != null);
238
+ let l, h = null;
239
+ try {
240
+ l = this.compute(n);
241
+ } catch (a) {
242
+ h = a, l = void 0;
243
+ }
244
+ const R = h == null ? u : [...u, { sourceIndex: null, error: h }], w = F(this.error, R);
245
+ let p = this.computeFetchState(o);
246
+ if (m(p), (h != null || u.length > 0) && (p = c.Error), !s) {
247
+ this.value = l, this.fetchState = p, this.error = w;
248
+ return;
249
+ }
250
+ this.setSnapshot({
251
+ value: l,
252
+ fetchState: p,
253
+ error: w,
254
+ cause: "derived source changed",
255
+ parentEvent: t
256
+ });
257
+ }
258
+ }
259
+ function F(r, e) {
260
+ return e.length === 0 ? null : r != null && r.length === e.length && r.every((t, s) => {
261
+ var n, o;
262
+ return t.sourceIndex === ((n = e[s]) == null ? void 0 : n.sourceIndex) && Object.is(t.error, (o = e[s]) == null ? void 0 : o.error);
263
+ }) ? r : Object.freeze(e.map((t) => Object.freeze(t)));
264
+ }
265
+ function C(r) {
266
+ return (typeof r != "object" || r === null) && typeof r != "function" ? !1 : typeof Reflect.get(r, "get") == "function" && typeof Reflect.get(r, "getFetchState") == "function" && typeof Reflect.get(r, "getError") == "function" && typeof Reflect.get(r, "subscribe") == "function";
267
+ }
268
+ function m(r) {
269
+ S([r]);
270
+ }
271
+ class I extends j {
272
+ constructor(e, t = {}) {
273
+ super(e, t);
274
+ }
275
+ setWithState(e, t = c.Ready, s = null, n = null) {
276
+ const o = n instanceof b ? n : null, u = o ? "set called" : n ?? "set called";
277
+ return this.setSnapshot({ value: e, fetchState: t, error: s, cause: u, parentEvent: o });
278
+ }
279
+ set(e, t = null) {
280
+ return this.setWithState(e, c.Ready, null, t);
281
+ }
282
+ }
283
+ export {
284
+ j as B,
285
+ v as D,
286
+ I as E,
287
+ c as F,
288
+ b as a,
289
+ g as b,
290
+ d as c,
291
+ S as d
292
+ };
293
+ //# sourceMappingURL=emitter-upM7NC28.js.map