@assistant-ui/store 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +9 -10
  2. package/dist/AuiIf.d.ts +1 -1
  3. package/dist/AuiIf.d.ts.map +1 -1
  4. package/dist/AuiIf.js.map +1 -1
  5. package/dist/index.d.ts +3 -9
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +4 -10
  8. package/dist/index.js.map +1 -1
  9. package/dist/scope-registry-forward.d.ts +6 -0
  10. package/dist/scope-registry-forward.d.ts.map +1 -0
  11. package/dist/scope-registry-forward.js +2 -0
  12. package/dist/scope-registry-forward.js.map +1 -0
  13. package/dist/scope-registry.d.ts +17 -0
  14. package/dist/scope-registry.d.ts.map +1 -0
  15. package/dist/scope-registry.js +2 -0
  16. package/dist/scope-registry.js.map +1 -0
  17. package/dist/useAui.d.ts +3 -5
  18. package/dist/useAui.d.ts.map +1 -1
  19. package/dist/useAui.js +6 -11
  20. package/dist/useAui.js.map +1 -1
  21. package/dist/useAuiEvent.d.ts +1 -1
  22. package/dist/useAuiEvent.d.ts.map +1 -1
  23. package/dist/useAuiEvent.js +1 -1
  24. package/dist/useAuiEvent.js.map +1 -1
  25. package/dist/useAuiState.d.ts +1 -1
  26. package/dist/useAuiState.d.ts.map +1 -1
  27. package/dist/useAuiState.js +1 -1
  28. package/dist/useAuiState.js.map +1 -1
  29. package/dist/utils/react-assistant-context.d.ts +1 -1
  30. package/dist/utils/react-assistant-context.d.ts.map +1 -1
  31. package/dist/utils/react-assistant-context.js +1 -2
  32. package/dist/utils/react-assistant-context.js.map +1 -1
  33. package/package.json +10 -3
  34. package/src/{AuiIf.tsx → AuiIf.ts} +1 -1
  35. package/src/__tests__/hooks.test.tsx +126 -0
  36. package/src/index.ts +25 -32
  37. package/src/scope-registry-forward.ts +6 -0
  38. package/src/scope-registry.ts +15 -0
  39. package/src/{useAui.tsx → useAui.ts} +24 -27
  40. package/src/useAuiEvent.ts +2 -2
  41. package/src/{useAuiState.tsx → useAuiState.ts} +3 -3
  42. package/src/utils/react-assistant-context.tsx +7 -3
  43. package/dist/Derived.d.ts +0 -34
  44. package/dist/Derived.d.ts.map +0 -1
  45. package/dist/Derived.js +0 -24
  46. package/dist/Derived.js.map +0 -1
  47. package/dist/attachDefaultPeers.d.ts +0 -56
  48. package/dist/attachDefaultPeers.d.ts.map +0 -1
  49. package/dist/attachDefaultPeers.js +0 -51
  50. package/dist/attachDefaultPeers.js.map +0 -1
  51. package/dist/tapClientList.d.ts +0 -24
  52. package/dist/tapClientList.d.ts.map +0 -1
  53. package/dist/tapClientList.js +0 -68
  54. package/dist/tapClientList.js.map +0 -1
  55. package/dist/tapClientLookup.d.ts +0 -11
  56. package/dist/tapClientLookup.d.ts.map +0 -1
  57. package/dist/tapClientLookup.js +0 -42
  58. package/dist/tapClientLookup.js.map +0 -1
  59. package/dist/tapClientResource.d.ts +0 -28
  60. package/dist/tapClientResource.d.ts.map +0 -1
  61. package/dist/tapClientResource.js +0 -122
  62. package/dist/tapClientResource.js.map +0 -1
  63. package/dist/types/client.d.ts +0 -119
  64. package/dist/types/client.d.ts.map +0 -1
  65. package/dist/types/client.js +0 -2
  66. package/dist/types/client.js.map +0 -1
  67. package/dist/types/events.d.ts +0 -33
  68. package/dist/types/events.d.ts.map +0 -1
  69. package/dist/types/events.js +0 -8
  70. package/dist/types/events.js.map +0 -1
  71. package/dist/utils/BaseProxyHandler.d.ts +0 -23
  72. package/dist/utils/BaseProxyHandler.d.ts.map +0 -1
  73. package/dist/utils/BaseProxyHandler.js +0 -46
  74. package/dist/utils/BaseProxyHandler.js.map +0 -1
  75. package/dist/utils/NotificationManager.d.ts +0 -11
  76. package/dist/utils/NotificationManager.d.ts.map +0 -1
  77. package/dist/utils/NotificationManager.js +0 -84
  78. package/dist/utils/NotificationManager.js.map +0 -1
  79. package/dist/utils/proxied-assistant-state.d.ts +0 -8
  80. package/dist/utils/proxied-assistant-state.d.ts.map +0 -1
  81. package/dist/utils/proxied-assistant-state.js +0 -34
  82. package/dist/utils/proxied-assistant-state.js.map +0 -1
  83. package/dist/utils/splitClients.d.ts +0 -10
  84. package/dist/utils/splitClients.d.ts.map +0 -1
  85. package/dist/utils/splitClients.js +0 -83
  86. package/dist/utils/splitClients.js.map +0 -1
  87. package/dist/utils/tap-assistant-context.d.ts +0 -19
  88. package/dist/utils/tap-assistant-context.d.ts.map +0 -1
  89. package/dist/utils/tap-assistant-context.js +0 -23
  90. package/dist/utils/tap-assistant-context.js.map +0 -1
  91. package/dist/utils/tap-client-stack-context.d.ts +0 -23
  92. package/dist/utils/tap-client-stack-context.d.ts.map +0 -1
  93. package/dist/utils/tap-client-stack-context.js +0 -28
  94. package/dist/utils/tap-client-stack-context.js.map +0 -1
  95. package/dist/wrapperResource.d.ts +0 -3
  96. package/dist/wrapperResource.d.ts.map +0 -1
  97. package/dist/wrapperResource.js +0 -11
  98. package/dist/wrapperResource.js.map +0 -1
  99. package/src/Derived.ts +0 -46
  100. package/src/attachDefaultPeers.ts +0 -78
  101. package/src/tapClientList.ts +0 -118
  102. package/src/tapClientLookup.ts +0 -76
  103. package/src/tapClientResource.ts +0 -182
  104. package/src/types/client.ts +0 -186
  105. package/src/types/events.ts +0 -77
  106. package/src/utils/BaseProxyHandler.ts +0 -50
  107. package/src/utils/NotificationManager.ts +0 -114
  108. package/src/utils/proxied-assistant-state.tsx +0 -53
  109. package/src/utils/splitClients.ts +0 -130
  110. package/src/utils/tap-assistant-context.ts +0 -58
  111. package/src/utils/tap-client-stack-context.ts +0 -51
  112. package/src/wrapperResource.ts +0 -17
@@ -1,182 +0,0 @@
1
- import {
2
- tapEffect,
3
- tapMemo,
4
- tapRef,
5
- type ResourceElement,
6
- tapResource,
7
- tapInlineResource,
8
- } from "@assistant-ui/tap";
9
- import type { ClientMethods, ClientOutputOf } from "./types/client";
10
- import {
11
- tapClientStack,
12
- tapWithClientStack,
13
- SYMBOL_CLIENT_INDEX,
14
- } from "./utils/tap-client-stack-context";
15
- import {
16
- BaseProxyHandler,
17
- handleIntrospectionProp,
18
- } from "./utils/BaseProxyHandler";
19
- import { wrapperResource } from "./wrapperResource";
20
-
21
- /**
22
- * Symbol used internally to get state from ClientProxy.
23
- * This allows getState() to be optional in the user-facing client.
24
- */
25
- const SYMBOL_GET_OUTPUT = Symbol("assistant-ui.store.getValue");
26
-
27
- type ClientInternal = {
28
- [SYMBOL_GET_OUTPUT]: ClientOutputOf<unknown, ClientMethods>;
29
- };
30
-
31
- export const getClientState = (client: ClientMethods) => {
32
- const output = (client as unknown as ClientInternal)[SYMBOL_GET_OUTPUT];
33
- if (!output) {
34
- throw new Error(
35
- "Client scope contains a non-client resource. " +
36
- "Ensure your Derived get() returns a client created with tapClientResource(), not a plain resource.",
37
- );
38
- }
39
- return output.state;
40
- };
41
-
42
- // Global cache for function templates by field name
43
- const fieldAccessFns = new Map<
44
- string | symbol,
45
- (this: unknown, ...args: unknown[]) => unknown
46
- >();
47
-
48
- function getOrCreateProxyFn(prop: string | symbol) {
49
- let template = fieldAccessFns.get(prop);
50
- if (!template) {
51
- template = function (this: unknown, ...args: unknown[]) {
52
- if (!this || typeof this !== "object") {
53
- throw new Error(
54
- `Method "${String(prop)}" called without proper context. ` +
55
- `This may indicate the function was called incorrectly.`,
56
- );
57
- }
58
-
59
- const output = (this as ClientInternal)[SYMBOL_GET_OUTPUT];
60
- if (!output) {
61
- throw new Error(
62
- `Method "${String(prop)}" called on invalid client proxy. ` +
63
- `Ensure you are calling this method on a valid client instance.`,
64
- );
65
- }
66
-
67
- const method = output.methods[prop];
68
- if (!method)
69
- throw new Error(`Method "${String(prop)}" is not implemented.`);
70
- if (typeof method !== "function")
71
- throw new Error(`"${String(prop)}" is not a function.`);
72
- return method(...args);
73
- };
74
- fieldAccessFns.set(prop, template);
75
- }
76
- return template;
77
- }
78
-
79
- class ClientProxyHandler
80
- extends BaseProxyHandler
81
- implements ProxyHandler<object>
82
- {
83
- private boundFns: Map<string | symbol, Function> | undefined;
84
- private cachedReceiver: unknown;
85
-
86
- constructor(
87
- private readonly outputRef: {
88
- current: ClientOutputOf<unknown, ClientMethods>;
89
- },
90
- private readonly index: number,
91
- ) {
92
- super();
93
- }
94
-
95
- get(_: unknown, prop: string | symbol, receiver: unknown) {
96
- if (prop === SYMBOL_GET_OUTPUT) return this.outputRef.current;
97
- if (prop === SYMBOL_CLIENT_INDEX) return this.index;
98
- const introspection = handleIntrospectionProp(prop, "ClientProxy");
99
- if (introspection !== false) return introspection;
100
- const value = this.outputRef.current.methods[prop];
101
- if (typeof value === "function") {
102
- if (this.cachedReceiver !== receiver) {
103
- this.boundFns = new Map();
104
- this.cachedReceiver = receiver;
105
- }
106
- let bound = this.boundFns!.get(prop);
107
- if (!bound) {
108
- bound = getOrCreateProxyFn(prop).bind(receiver);
109
- this.boundFns!.set(prop, bound);
110
- }
111
- return bound;
112
- }
113
- return value;
114
- }
115
-
116
- ownKeys(): ArrayLike<string | symbol> {
117
- return Object.keys(this.outputRef.current.methods);
118
- }
119
-
120
- has(_: unknown, prop: string | symbol) {
121
- if (prop === SYMBOL_GET_OUTPUT) return true;
122
- if (prop === SYMBOL_CLIENT_INDEX) return true;
123
- return prop in this.outputRef.current.methods;
124
- }
125
- }
126
-
127
- /**
128
- * Resource that wraps a plain resource element to create a stable client proxy.
129
- *
130
- * Takes a ResourceElement that returns { state, methods } and
131
- * wraps it to produce a stable client proxy. This adds the client to the
132
- * client stack, enabling event scoping.
133
- *
134
- * Use this for 1:1 client mappings where you want event scoping to work correctly.
135
- *
136
- * @example
137
- * ```typescript
138
- * const MessageResource = resource(({ messageId }: { messageId: string }) => {
139
- * return tapInlineResource(
140
- * tapClientResource(InnerMessageResource({ messageId }))
141
- * );
142
- * });
143
- * ```
144
- */
145
- export const ClientResource = wrapperResource(
146
- <TState, TMethods extends ClientMethods>(
147
- element: ResourceElement<ClientOutputOf<TState, TMethods>>,
148
- ): ClientOutputOf<TState, TMethods> & {
149
- key: string | number | undefined;
150
- } => {
151
- const valueRef = tapRef(
152
- null as unknown as ClientOutputOf<TState, TMethods>,
153
- );
154
-
155
- const index = tapClientStack().length;
156
- const methods = tapMemo(
157
- () =>
158
- new Proxy<TMethods>(
159
- {} as TMethods,
160
- new ClientProxyHandler(valueRef, index),
161
- ),
162
- [index],
163
- );
164
-
165
- const value = tapWithClientStack(methods, () => tapResource(element));
166
- if (!valueRef.current) {
167
- valueRef.current = value;
168
- }
169
-
170
- tapEffect(() => {
171
- valueRef.current = value;
172
- });
173
-
174
- return { methods, state: value.state, key: element.key };
175
- },
176
- );
177
-
178
- export const tapClientResource = <TState, TMethods extends ClientMethods>(
179
- element: ResourceElement<ClientOutputOf<TState, TMethods>>,
180
- ) => {
181
- return tapInlineResource(ClientResource(element));
182
- };
@@ -1,186 +0,0 @@
1
- import type { ResourceElement } from "@assistant-ui/tap";
2
- import type {
3
- AssistantEventName,
4
- AssistantEventCallback,
5
- AssistantEventSelector,
6
- } from "./events";
7
-
8
- /**
9
- * Base type for methods that can be called on a client.
10
- */
11
- export interface ClientMethods {
12
- [key: string | symbol]: ((...args: any[]) => any) | ClientMethods;
13
- }
14
-
15
- type ClientMetaType = { source: ClientNames; query: Record<string, unknown> };
16
-
17
- /**
18
- * Schema of a client in the assistant system (internal type).
19
- * @template TState - The state type for this client
20
- * @template TMethods - The methods available on this client
21
- * @template TMeta - Source/query metadata (optional)
22
- * @template TEvents - Events that this client can emit (optional)
23
- * @internal
24
- */
25
- export type ClientSchema<
26
- TState = unknown,
27
- TMethods extends ClientMethods = ClientMethods,
28
- TMeta extends ClientMetaType = never,
29
- TEvents extends Record<string, unknown> = never,
30
- > = {
31
- state: TState;
32
- methods: TMethods;
33
- meta?: TMeta;
34
- events?: TEvents;
35
- };
36
-
37
- /**
38
- * Module augmentation interface for assistant-ui store type extensions.
39
- *
40
- * @example
41
- * ```typescript
42
- * declare module "@assistant-ui/store" {
43
- * interface ClientRegistry {
44
- * // Simple client (meta and events are optional)
45
- * foo: {
46
- * state: { bar: string };
47
- * methods: { updateBar: (bar: string) => void };
48
- * };
49
- * // Full client with meta and events
50
- * bar: {
51
- * state: { id: string };
52
- * methods: { update: () => void };
53
- * meta: { source: "fooList"; query: { index: number } };
54
- * events: {
55
- * "bar.updated": { id: string };
56
- * };
57
- * };
58
- * }
59
- * }
60
- * ```
61
- */
62
- export interface ClientRegistry {}
63
-
64
- type ClientEventsType<K extends ClientNames> = Record<
65
- `${K}.${string}`,
66
- unknown
67
- >;
68
-
69
- type ClientError<E extends string> = {
70
- state: E;
71
- methods: Record<E, () => E>;
72
- meta: { source: ClientNames; query: Record<E, E> };
73
- events: Record<`${E}.`, E>;
74
- };
75
-
76
- type ValidateClient<K extends keyof ClientRegistry> =
77
- ClientRegistry[K] extends { methods: ClientMethods }
78
- ? "meta" extends keyof ClientRegistry[K]
79
- ? ClientRegistry[K]["meta"] extends ClientMetaType
80
- ? "events" extends keyof ClientRegistry[K]
81
- ? ClientRegistry[K]["events"] extends ClientEventsType<K>
82
- ? ClientRegistry[K]
83
- : ClientError<`ERROR: ${K & string} has invalid events type`>
84
- : ClientRegistry[K]
85
- : ClientError<`ERROR: ${K & string} has invalid meta type`>
86
- : "events" extends keyof ClientRegistry[K]
87
- ? ClientRegistry[K]["events"] extends ClientEventsType<K>
88
- ? ClientRegistry[K]
89
- : ClientError<`ERROR: ${K & string} has invalid events type`>
90
- : ClientRegistry[K]
91
- : ClientError<`ERROR: ${K & string} has invalid methods type`>;
92
-
93
- type ClientSchemas = keyof ClientRegistry extends never
94
- ? {
95
- "ERROR: No clients were defined": ClientError<"ERROR: No clients were defined">;
96
- }
97
- : { [K in keyof ClientRegistry]: ValidateClient<K> };
98
-
99
- /**
100
- * Output type that client resources return with state and methods.
101
- *
102
- * @example
103
- * ```typescript
104
- * const FooResource = resource((): ClientResourceOutput<"foo"> => {
105
- * const [state, setState] = tapState({ bar: "hello" });
106
- * return {
107
- * state,
108
- * methods: {
109
- * updateBar: (b) => setState({ bar: b })
110
- * }
111
- * };
112
- * });
113
- * ```
114
- */
115
- export type ClientOutput<K extends ClientNames> = ClientOutputOf<
116
- ClientSchemas[K]["state"],
117
- ClientSchemas[K]["methods"] & ClientMethods
118
- >;
119
-
120
- /**
121
- * Generic version of ClientResourceOutput for library code.
122
- */
123
- export type ClientOutputOf<TState, TMethods extends ClientMethods> = {
124
- state: TState;
125
- methods: TMethods;
126
- };
127
-
128
- export type ClientNames = keyof ClientSchemas extends infer U ? U : never;
129
-
130
- export type ClientEvents<K extends ClientNames> =
131
- "events" extends keyof ClientSchemas[K]
132
- ? ClientSchemas[K]["events"] extends ClientEventsType<K>
133
- ? ClientSchemas[K]["events"]
134
- : never
135
- : never;
136
-
137
- export type ClientMeta<K extends ClientNames> =
138
- "meta" extends keyof ClientSchemas[K]
139
- ? Pick<
140
- ClientSchemas[K]["meta"] extends ClientMetaType
141
- ? ClientSchemas[K]["meta"]
142
- : never,
143
- "source" | "query"
144
- >
145
- : never;
146
-
147
- export type ClientElement<K extends ClientNames> = ResourceElement<
148
- ClientOutput<K>
149
- >;
150
-
151
- /**
152
- * Unsubscribe function type.
153
- */
154
- export type Unsubscribe = () => void;
155
-
156
- /**
157
- * State type extracted from all clients.
158
- */
159
- export type AssistantState = {
160
- [K in ClientNames]: ClientSchemas[K]["state"];
161
- };
162
-
163
- /**
164
- * Type for a client accessor - a function that returns the methods,
165
- * with source/query metadata attached (derived from meta).
166
- */
167
- export type AssistantClientAccessor<K extends ClientNames> =
168
- (() => ClientSchemas[K]["methods"]) &
169
- (
170
- | ClientMeta<K>
171
- | { source: "root"; query: Record<string, never> }
172
- | { source: null; query: null }
173
- ) & { name: K };
174
-
175
- /**
176
- * The assistant client type with all registered clients.
177
- */
178
- export type AssistantClient = {
179
- [K in ClientNames]: AssistantClientAccessor<K>;
180
- } & {
181
- subscribe(listener: () => void): Unsubscribe;
182
- on<TEvent extends AssistantEventName>(
183
- selector: AssistantEventSelector<TEvent>,
184
- callback: AssistantEventCallback<TEvent>,
185
- ): Unsubscribe;
186
- };
@@ -1,77 +0,0 @@
1
- import type {
2
- AssistantClientAccessor,
3
- ClientEvents,
4
- ClientNames,
5
- } from "./client";
6
-
7
- // --- Event Map Construction ---
8
- type UnionToIntersection<U> = (
9
- U extends unknown
10
- ? (x: U) => void
11
- : never
12
- ) extends (x: infer I) => void
13
- ? I
14
- : never;
15
-
16
- type ClientEventMap = UnionToIntersection<
17
- { [K in ClientNames]: ClientEvents<K> }[ClientNames]
18
- >;
19
-
20
- // --- Core Types ---
21
-
22
- type WildcardPayload = {
23
- [K in keyof ClientEventMap]: { event: K; payload: ClientEventMap[K] };
24
- }[keyof ClientEventMap];
25
-
26
- export type AssistantEventPayload = ClientEventMap & { "*": WildcardPayload };
27
-
28
- export type AssistantEventName = keyof AssistantEventPayload;
29
-
30
- type EventSource<T extends AssistantEventName> =
31
- T extends `${infer Source}.${string}` ? Source : never;
32
-
33
- // --- Scoping ---
34
-
35
- type ParentOf<K extends ClientNames> =
36
- AssistantClientAccessor<K> extends { source: infer S }
37
- ? S extends ClientNames
38
- ? S
39
- : never
40
- : never;
41
-
42
- type AncestorsOf<
43
- K extends ClientNames,
44
- Seen extends ClientNames = never,
45
- > = K extends Seen
46
- ? never
47
- : ParentOf<K> extends never
48
- ? never
49
- : ParentOf<K> | AncestorsOf<ParentOf<K>, Seen | K>;
50
-
51
- /** Valid scopes: `"*"` | event source | ancestors of event source */
52
- export type AssistantEventScope<TEvent extends AssistantEventName> =
53
- | "*"
54
- | EventSource<TEvent>
55
- | (EventSource<TEvent> extends ClientNames
56
- ? AncestorsOf<EventSource<TEvent>>
57
- : never);
58
-
59
- // --- Selection & Callbacks ---
60
-
61
- export type AssistantEventSelector<TEvent extends AssistantEventName> =
62
- | TEvent
63
- | { scope: AssistantEventScope<TEvent>; event: TEvent };
64
-
65
- export const normalizeEventSelector = <TEvent extends AssistantEventName>(
66
- selector: AssistantEventSelector<TEvent>,
67
- ) => {
68
- if (typeof selector === "string") {
69
- const source = selector.split(".")[0] as AssistantEventScope<TEvent>;
70
- return { scope: source, event: selector };
71
- }
72
- return { scope: selector.scope, event: selector.event };
73
- };
74
-
75
- export type AssistantEventCallback<TEvent extends AssistantEventName> = (
76
- payload: AssistantEventPayload[TEvent],
77
- ) => void;
@@ -1,50 +0,0 @@
1
- const INTROSPECTION_PROPS = new Set(["$$typeof", "nodeType", "then"]);
2
-
3
- /**
4
- * Handles common proxy introspection properties.
5
- * Returns the appropriate value for toStringTag, toJSON, and props that should return undefined.
6
- * Returns `false` if the prop should be handled by the subclass.
7
- */
8
- export const handleIntrospectionProp = (
9
- prop: string | symbol,
10
- name: string,
11
- ): unknown | false => {
12
- if (prop === Symbol.toStringTag) return name;
13
- if (typeof prop === "symbol") return undefined;
14
- if (prop === "toJSON") return () => name;
15
- if (INTROSPECTION_PROPS.has(prop)) return undefined;
16
- return false;
17
- };
18
-
19
- export abstract class BaseProxyHandler implements ProxyHandler<object> {
20
- abstract get(_: unknown, prop: string | symbol, receiver?: unknown): unknown;
21
- abstract ownKeys(): ArrayLike<string | symbol>;
22
- abstract has(_: unknown, prop: string | symbol): boolean;
23
-
24
- getOwnPropertyDescriptor(_: unknown, prop: string | symbol) {
25
- const value = this.get(_, prop);
26
- if (value === undefined) return undefined;
27
- return {
28
- value,
29
- writable: false,
30
- enumerable: true,
31
- configurable: false,
32
- };
33
- }
34
-
35
- set() {
36
- return false;
37
- }
38
- setPrototypeOf() {
39
- return false;
40
- }
41
- defineProperty() {
42
- return false;
43
- }
44
- deleteProperty() {
45
- return false;
46
- }
47
- preventExtensions(): boolean {
48
- return false;
49
- }
50
- }
@@ -1,114 +0,0 @@
1
- import { resource } from "@assistant-ui/tap";
2
- import type { ClientStack } from "./tap-client-stack-context";
3
- import type {
4
- AssistantEventName,
5
- AssistantEventPayload,
6
- } from "../types/events";
7
- import { Unsubscribe } from "../types/client";
8
- import { tapConst } from "@assistant-ui/tap";
9
-
10
- type InternalCallback = (payload: unknown, clientStack: ClientStack) => void;
11
-
12
- export type NotificationManager = {
13
- on<TEvent extends AssistantEventName>(
14
- event: TEvent,
15
- callback: (
16
- payload: AssistantEventPayload[TEvent],
17
- clientStack: ClientStack,
18
- ) => void,
19
- ): Unsubscribe;
20
- emit<TEvent extends Exclude<AssistantEventName, "*">>(
21
- event: TEvent,
22
- payload: AssistantEventPayload[TEvent],
23
- clientStack: ClientStack,
24
- ): void;
25
- subscribe(callback: () => void): Unsubscribe;
26
- notifySubscribers(): void;
27
- };
28
-
29
- export const NotificationManager = resource((): NotificationManager => {
30
- return tapConst(() => {
31
- const listeners = new Map<string, Set<InternalCallback>>();
32
- const wildcardListeners = new Set<InternalCallback>();
33
- const subscribers = new Set<() => void>();
34
-
35
- return {
36
- on(event, callback) {
37
- const cb = callback as InternalCallback;
38
- if (event === "*") {
39
- wildcardListeners.add(cb);
40
- return () => wildcardListeners.delete(cb);
41
- }
42
-
43
- let set = listeners.get(event);
44
- if (!set) {
45
- set = new Set();
46
- listeners.set(event, set);
47
- }
48
- set.add(cb);
49
-
50
- return () => {
51
- set!.delete(cb);
52
- if (set!.size === 0) listeners.delete(event);
53
- };
54
- },
55
-
56
- emit(event, payload, clientStack) {
57
- const eventListeners = listeners.get(event);
58
- if (!eventListeners && wildcardListeners.size === 0) return;
59
-
60
- queueMicrotask(() => {
61
- const errors = [];
62
- if (eventListeners) {
63
- for (const cb of eventListeners) {
64
- try {
65
- cb(payload, clientStack);
66
- } catch (e) {
67
- errors.push(e);
68
- }
69
- }
70
- }
71
- if (wildcardListeners.size > 0) {
72
- const wrapped = { event, payload };
73
- for (const cb of wildcardListeners) {
74
- try {
75
- cb(wrapped, clientStack);
76
- } catch (e) {
77
- errors.push(e);
78
- }
79
- }
80
- }
81
-
82
- if (errors.length > 0) {
83
- if (errors.length === 1) {
84
- throw errors[0];
85
- } else {
86
- for (const error of errors) {
87
- console.error(error);
88
- }
89
- throw new AggregateError(
90
- errors,
91
- "Errors occurred during event emission",
92
- );
93
- }
94
- }
95
- });
96
- },
97
-
98
- subscribe(callback) {
99
- subscribers.add(callback);
100
- return () => subscribers.delete(callback);
101
- },
102
-
103
- notifySubscribers() {
104
- for (const cb of subscribers) {
105
- try {
106
- cb();
107
- } catch (e) {
108
- console.error("NotificationManager: subscriber callback error", e);
109
- }
110
- }
111
- },
112
- };
113
- }, []);
114
- });
@@ -1,53 +0,0 @@
1
- "use client";
2
- import { getClientState } from "../tapClientResource";
3
- import type { AssistantClient, AssistantState } from "../types/client";
4
- import { BaseProxyHandler, handleIntrospectionProp } from "./BaseProxyHandler";
5
-
6
- export const PROXIED_ASSISTANT_STATE_SYMBOL = Symbol(
7
- "assistant-ui.store.proxiedAssistantState",
8
- );
9
-
10
- const isIgnoredKey = (key: string | symbol): key is "on" | "subscribe" => {
11
- return key === "on" || key === "subscribe" || typeof key === "symbol";
12
- };
13
-
14
- /**
15
- * Proxied state that lazily accesses scope states
16
- */
17
- export const createProxiedAssistantState = (
18
- client: AssistantClient,
19
- ): AssistantState => {
20
- class ProxiedAssistantStateProxyHandler
21
- extends BaseProxyHandler
22
- implements ProxyHandler<AssistantState>
23
- {
24
- get(_: unknown, prop: string | symbol) {
25
- const introspection = handleIntrospectionProp(prop, "AssistantState");
26
- if (introspection !== false) return introspection;
27
- const scope = prop as keyof AssistantClient;
28
- if (isIgnoredKey(scope)) return undefined;
29
- return getClientState(client[scope]());
30
- }
31
-
32
- ownKeys(): ArrayLike<string | symbol> {
33
- return Object.keys(client).filter((key) => !isIgnoredKey(key));
34
- }
35
-
36
- has(_: unknown, prop: string | symbol): boolean {
37
- return !isIgnoredKey(prop) && prop in client;
38
- }
39
- }
40
-
41
- return new Proxy<AssistantState>(
42
- {} as AssistantState,
43
- new ProxiedAssistantStateProxyHandler(),
44
- );
45
- };
46
-
47
- export const getProxiedAssistantState = (
48
- client: AssistantClient,
49
- ): AssistantState => {
50
- return (
51
- client as unknown as { [PROXIED_ASSISTANT_STATE_SYMBOL]: AssistantState }
52
- )[PROXIED_ASSISTANT_STATE_SYMBOL];
53
- };