@typewirets/react 0.1.0 → 0.2.0-rc.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.
@@ -1,14 +1,247 @@
1
+ /**
2
+ * TypeWire React Integration
3
+ *
4
+ * Provides React bindings for TypeWire dependency injection, enabling
5
+ * context-based dependency resolution within React component trees.
6
+ *
7
+ * Key exports:
8
+ * - {@link ReactResolutionContext} — Wraps a `ResolutionContext` with error caching, so a failed resolution doesn't loop under Suspense
9
+ * - {@link ContainerContext} — React Context holding the active resolution context
10
+ * - {@link useContainer} — Hook to access the current resolution context
11
+ * - {@link useTypeWire} — Hook to resolve a TypeWire with React Suspense support
12
+ * - {@link usePreload} — Hook that suspends a subtree once until a set of wires is created
13
+ * - {@link ResolutionContextProvider} — Component that provides a resolution context to the tree
14
+ *
15
+ * @packageDocumentation
16
+ */
1
17
  import * as React from "react";
2
- import { type ResolutionContext, type TypeSymbol, type TypeWire } from "@typewirets/core";
18
+ import { type AnyTypeSymbol, type AnyTypeWire, type ResolutionContext, type TypeSymbol, type TypeWire } from "@typewirets/core";
19
+ /**
20
+ * A React-aware wrapper around {@link ResolutionContext} that caches resolution
21
+ * errors.
22
+ *
23
+ * When a component suspends on a resolution that then fails, React renders it
24
+ * again, and that render would start a new creation, suspend, fail and repeat
25
+ * forever. To stop that loop, the error from a failed `get` is cached, and
26
+ * later `get` and `getSync` calls for the same `TypeSymbol` throw it without
27
+ * calling the underlying context.
28
+ *
29
+ * A cached error lasts until {@link ReactResolutionContext.clearErrors} is
30
+ * called, even across `unbind` and a re-apply: this class only sees a
31
+ * `ResolutionContext`, so it cannot tell that a binding changed. To retry
32
+ * after replacing a binding, call `clearErrors` and then reset the error
33
+ * boundary that caught the error.
34
+ *
35
+ * Calls that run while a resolution is in flight are not deduplicated here.
36
+ * The underlying context must share one in-flight creation per singleton
37
+ * itself, or readers may get different instances. `TypeWireContainer` does,
38
+ * and never hands a creation started before `unbind` to new callers. So does
39
+ * the `@typewirets/inversify` adapter, because Inversify 7 shares concurrent
40
+ * singleton `getAsync` calls. A custom `ResolutionContext` must do the same.
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * const container = new TypeWireContainer();
45
+ * const context = new ReactResolutionContext(container);
46
+ * const value = await context.get(MySymbol);
47
+ *
48
+ * // After replacing the binding for MySymbol:
49
+ * context.clearErrors(MySymbol);
50
+ * ```
51
+ */
3
52
  export declare class ReactResolutionContext {
4
53
  #private;
5
54
  constructor(resolutionContext: ResolutionContext);
55
+ /**
56
+ * Synchronously retrieves a resolved instance for the given type symbol.
57
+ *
58
+ * @template T The type of the resolved instance
59
+ * @param typeSymbol - The typed symbol identifying the dependency to resolve
60
+ * @returns The resolved instance
61
+ * @throws Re-throws the cached error if a previous async resolution for this symbol failed
62
+ * @throws Throws if the instance has not been resolved yet (see {@link ResolutionContext.getSync})
63
+ */
6
64
  getSync<T>(typeSymbol: TypeSymbol<T>): T;
65
+ /**
66
+ * Asynchronously resolves an instance for the given type symbol.
67
+ *
68
+ * If a previous resolution for this symbol failed, the cached error is
69
+ * thrown immediately. Otherwise the call goes to the underlying context,
70
+ * which joins a creation already in flight for a singleton.
71
+ *
72
+ * @template T The type of the resolved instance
73
+ * @param typeSymbol - The typed symbol identifying the dependency to resolve
74
+ * @returns A promise that resolves to the instance
75
+ * @throws Re-throws the cached error if a previous resolution for this symbol failed
76
+ */
7
77
  get<T>(typeSymbol: TypeSymbol<T>): Promise<T>;
78
+ /**
79
+ * Forgets cached resolution errors, so the next `get` or `getSync` asks the
80
+ * underlying context again.
81
+ *
82
+ * Call it after replacing a failed binding (`unbind`, then apply the wire
83
+ * again), then reset the error boundary that shows the error. A failure that
84
+ * was still in flight when you call this is not cached when it settles.
85
+ *
86
+ * @param typeSymbol - The symbol whose error to forget. Omit to forget all.
87
+ */
88
+ clearErrors(typeSymbol?: AnyTypeSymbol): void;
8
89
  }
90
+ /**
91
+ * React Context that holds the active {@link ResolutionContext} for the component tree.
92
+ *
93
+ * The default value is an empty {@link TypeWireContainer} wrapped in a
94
+ * {@link ReactResolutionContext}. In practice, you should provide your own
95
+ * container via {@link ResolutionContextProvider}.
96
+ */
9
97
  export declare const ContainerContext: React.Context<ResolutionContext>;
98
+ /**
99
+ * Hook to access the current {@link ResolutionContext} from the nearest
100
+ * {@link ResolutionContextProvider}.
101
+ *
102
+ * @returns The current resolution context
103
+ *
104
+ * @example
105
+ * ```tsx
106
+ * function MyComponent() {
107
+ * const container = useContainer();
108
+ * // Use container for manual resolution if needed
109
+ * }
110
+ * ```
111
+ */
10
112
  export declare function useContainer(): ResolutionContext;
11
- export declare function useTypeWire<T>(typeWire: TypeWire<T>): T;
113
+ /**
114
+ * Options for {@link useTypeWire}.
115
+ */
116
+ export interface UseTypeWireOpts {
117
+ /**
118
+ * What to do when the value isn't created yet. `true` (the default)
119
+ * suspends until it is, so the nearest `<Suspense>` shows its fallback.
120
+ * `false` throws a `TypeWireError` with reason `NotPreloaded` naming the
121
+ * wire instead, for apps that preload every phase and never want a
122
+ * fallback: a forgotten preload then shows up at once, in development.
123
+ */
124
+ suspend?: boolean;
125
+ }
126
+ /**
127
+ * Hook that resolves a {@link TypeWire} within the current container context,
128
+ * with React Suspense integration.
129
+ *
130
+ * Resolution behavior:
131
+ * 1. **Sync available** — If the wire can be resolved synchronously (e.g., a singleton
132
+ * that was already created or preloaded), the value is returned immediately,
133
+ * including falsy values such as `0`, `""`, `false` and `null`.
134
+ * 2. **Async pending** — If sync resolution fails with a retriable error, the hook
135
+ * starts an async resolution and throws the promise to trigger React Suspense.
136
+ * With `{ suspend: false }` it throws a `TypeWireError` with reason
137
+ * `NotPreloaded` instead.
138
+ * 3. **Error** — If sync resolution fails with a non-retriable error, it is re-thrown.
139
+ *
140
+ * To render without a fallback, preload the wires first, with
141
+ * `container.preload` before rendering or {@link usePreload} higher in the
142
+ * tree. A wire nobody preloaded suspends, so this hook must be used inside a
143
+ * `<Suspense>` boundary unless you pass `{ suspend: false }`.
144
+ *
145
+ * @template T The type of the resolved instance
146
+ * @param typeWire - The TypeWire to resolve
147
+ * @param opts - Optional settings; see {@link UseTypeWireOpts}
148
+ * @returns The resolved instance
149
+ * @throws The resolution promise when the value is not yet available (for Suspense)
150
+ * @throws {@link TypeWireError} with reason `NotPreloaded` when the value is not yet available and `suspend` is `false`
151
+ * @throws {@link TypeWireError} if synchronous resolution fails with a non-retriable error
152
+ *
153
+ * @example
154
+ * ```tsx
155
+ * function UserProfile() {
156
+ * const userService = useTypeWire(UserServiceWire);
157
+ * return <div>{userService.getName()}</div>;
158
+ * }
159
+ *
160
+ * // Preloaded before rendering: no fallback.
161
+ * await container.preload({ wires: [UserServiceWire] });
162
+ *
163
+ * // Or wrap in Suspense for wires that may not be ready yet.
164
+ * <Suspense fallback={<Loading />}>
165
+ * <UserProfile />
166
+ * </Suspense>
167
+ * ```
168
+ */
169
+ export declare function useTypeWire<T>(typeWire: TypeWire<T>, opts?: UseTypeWireOpts): T;
170
+ /**
171
+ * Options for {@link usePreload}.
172
+ */
173
+ export interface UsePreloadOpts {
174
+ /**
175
+ * The wires to create before the calling component renders. Their imports
176
+ * are created with them. Wires that aren't singletons are skipped. To
177
+ * preload a group, pass its `wires`.
178
+ */
179
+ wires: readonly AnyTypeWire[];
180
+ }
181
+ /**
182
+ * Hook that suspends the calling component until every singleton in
183
+ * `opts.wires` is created, so components below it read them with
184
+ * {@link useTypeWire} without suspending.
185
+ *
186
+ * Use it where a part of the app starts (a route, a panel, a feature), under
187
+ * one `<Suspense>` boundary: the fallback shows once for the whole set, and
188
+ * the creations run in parallel. A creation that fails reaches the nearest
189
+ * error boundary.
190
+ *
191
+ * It works with any resolution context, including the Inversify adapter.
192
+ * Outside React, use `container.preload` instead.
193
+ *
194
+ * @param opts - The wires to preload; see {@link UsePreloadOpts}
195
+ * @throws A promise while any of the wires is still being created (for Suspense)
196
+ * @throws The creation's error, once one has failed
197
+ *
198
+ * @example
199
+ * ```tsx
200
+ * function ReportsRoute() {
201
+ * usePreload({ wires: [reportsServiceWire, chartsWire] });
202
+ * return <ReportsPage />;
203
+ * }
204
+ *
205
+ * <Suspense fallback={<Loading />}>
206
+ * <ReportsRoute />
207
+ * </Suspense>
208
+ * ```
209
+ */
210
+ export declare function usePreload(opts: UsePreloadOpts): void;
211
+ /**
212
+ * React component that provides a {@link ResolutionContext} to the component tree.
213
+ *
214
+ * If the given `resolutionContext` is not already a {@link ReactResolutionContext},
215
+ * it is wrapped in one, so a failed resolution reaches an error boundary
216
+ * instead of retrying under Suspense. Each plain context gets one wrapper,
217
+ * reused on every render and every mount, so re-rendering the provider keeps
218
+ * cached errors and gives consumers the same context value.
219
+ *
220
+ * A cached error lasts until `clearErrors` is called, even after `unbind` and
221
+ * a re-apply. To be able to retry, create the {@link ReactResolutionContext}
222
+ * yourself, pass it here, and call its `clearErrors` after replacing the
223
+ * binding.
224
+ *
225
+ * The context must share one in-flight creation per singleton (as
226
+ * `TypeWireContainer` does); see {@link ReactResolutionContext}.
227
+ *
228
+ * @param props.resolutionContext - The resolution context to provide to descendants
229
+ * @param props.children - Child components that will have access to the context
230
+ *
231
+ * @example
232
+ * ```tsx
233
+ * async function main() {
234
+ * const container = new TypeWireContainer();
235
+ * await AppWireGroup.apply(container);
236
+ *
237
+ * createRoot(document.getElementById('root')!).render(
238
+ * <ResolutionContextProvider resolutionContext={container}>
239
+ * <App />
240
+ * </ResolutionContextProvider>
241
+ * );
242
+ * }
243
+ * ```
244
+ */
12
245
  export declare function ResolutionContextProvider(props: {
13
246
  resolutionContext: ResolutionContext;
14
247
  children?: React.ReactNode;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,UAAU,EACf,KAAK,QAAQ,EAGd,MAAM,kBAAkB,CAAC;AAE1B,qBAAa,sBAAsB;;gBAKrB,iBAAiB,EAAE,iBAAiB;IAIhD,OAAO,CAAC,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC;IAOlC,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAqBpD;AAED,eAAO,MAAM,gBAAgB,kCAE5B,CAAC;AAEF,wBAAgB,YAAY,sBAG3B;AAED,wBAAgB,WAAW,CAAC,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAsCvD;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE;IAC/C,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;CAC5B,2CAUA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,iBAAiB,EACtB,KAAK,UAAU,EACf,KAAK,QAAQ,EAGd,MAAM,kBAAkB,CAAC;AAE1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,sBAAsB;;gBAYrB,iBAAiB,EAAE,iBAAiB;IAIhD;;;;;;;;OAQG;IACH,OAAO,CAAC,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC;IAOxC;;;;;;;;;;;OAWG;IACG,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAmBnD;;;;;;;;;OASG;IACH,WAAW,CAAC,UAAU,CAAC,EAAE,aAAa,GAAG,IAAI;CAoB9C;AA2BD;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,kCAE5B,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,sBAG3B;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AA6CD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAC3B,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,EACrB,IAAI,CAAC,EAAE,eAAe,GACrB,CAAC,CA6CH;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;OAIG;IACH,KAAK,EAAE,SAAS,WAAW,EAAE,CAAC;CAC/B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAgBrD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE;IAC/C,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;CAC5B,2CAOA"}
package/dist/esm/index.js CHANGED
@@ -9,88 +9,383 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _ReactResolutionContext_resolutionContext, _ReactResolutionContext_resolutions, _ReactResolutionContext_resolutionErrors;
12
+ var _ReactResolutionContext_instances, _ReactResolutionContext_resolutionContext, _ReactResolutionContext_resolutionErrors, _ReactResolutionContext_generation, _ReactResolutionContext_allClearedAt, _ReactResolutionContext_clearedAt, _ReactResolutionContext_clearedSince;
13
13
  import { jsx as _jsx } from "react/jsx-runtime";
14
+ /**
15
+ * TypeWire React Integration
16
+ *
17
+ * Provides React bindings for TypeWire dependency injection, enabling
18
+ * context-based dependency resolution within React component trees.
19
+ *
20
+ * Key exports:
21
+ * - {@link ReactResolutionContext} — Wraps a `ResolutionContext` with error caching, so a failed resolution doesn't loop under Suspense
22
+ * - {@link ContainerContext} — React Context holding the active resolution context
23
+ * - {@link useContainer} — Hook to access the current resolution context
24
+ * - {@link useTypeWire} — Hook to resolve a TypeWire with React Suspense support
25
+ * - {@link usePreload} — Hook that suspends a subtree once until a set of wires is created
26
+ * - {@link ResolutionContextProvider} — Component that provides a resolution context to the tree
27
+ *
28
+ * @packageDocumentation
29
+ */
14
30
  import * as React from "react";
15
31
  import { TypeWireError, TypeWireContainer, } from "@typewirets/core";
32
+ /**
33
+ * A React-aware wrapper around {@link ResolutionContext} that caches resolution
34
+ * errors.
35
+ *
36
+ * When a component suspends on a resolution that then fails, React renders it
37
+ * again, and that render would start a new creation, suspend, fail and repeat
38
+ * forever. To stop that loop, the error from a failed `get` is cached, and
39
+ * later `get` and `getSync` calls for the same `TypeSymbol` throw it without
40
+ * calling the underlying context.
41
+ *
42
+ * A cached error lasts until {@link ReactResolutionContext.clearErrors} is
43
+ * called, even across `unbind` and a re-apply: this class only sees a
44
+ * `ResolutionContext`, so it cannot tell that a binding changed. To retry
45
+ * after replacing a binding, call `clearErrors` and then reset the error
46
+ * boundary that caught the error.
47
+ *
48
+ * Calls that run while a resolution is in flight are not deduplicated here.
49
+ * The underlying context must share one in-flight creation per singleton
50
+ * itself, or readers may get different instances. `TypeWireContainer` does,
51
+ * and never hands a creation started before `unbind` to new callers. So does
52
+ * the `@typewirets/inversify` adapter, because Inversify 7 shares concurrent
53
+ * singleton `getAsync` calls. A custom `ResolutionContext` must do the same.
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * const container = new TypeWireContainer();
58
+ * const context = new ReactResolutionContext(container);
59
+ * const value = await context.get(MySymbol);
60
+ *
61
+ * // After replacing the binding for MySymbol:
62
+ * context.clearErrors(MySymbol);
63
+ * ```
64
+ */
16
65
  export class ReactResolutionContext {
17
66
  constructor(resolutionContext) {
67
+ _ReactResolutionContext_instances.add(this);
68
+ /** The underlying resolution context that performs actual dependency resolution. */
18
69
  _ReactResolutionContext_resolutionContext.set(this, void 0);
19
- _ReactResolutionContext_resolutions.set(this, new Map());
70
+ /** Cached resolution errors, keyed by symbol, to fail fast on repeated access. */
20
71
  _ReactResolutionContext_resolutionErrors.set(this, new Map());
72
+ /** Counts `clearErrors` calls, so a `get` can tell if one ran while it waited. */
73
+ _ReactResolutionContext_generation.set(this, 0);
74
+ /** The generation of the last `clearErrors()` call that cleared every symbol. */
75
+ _ReactResolutionContext_allClearedAt.set(this, 0);
76
+ /** The generation of the last `clearErrors(typeSymbol)` call, per symbol. */
77
+ _ReactResolutionContext_clearedAt.set(this, new Map());
21
78
  __classPrivateFieldSet(this, _ReactResolutionContext_resolutionContext, resolutionContext, "f");
22
79
  }
80
+ /**
81
+ * Synchronously retrieves a resolved instance for the given type symbol.
82
+ *
83
+ * @template T The type of the resolved instance
84
+ * @param typeSymbol - The typed symbol identifying the dependency to resolve
85
+ * @returns The resolved instance
86
+ * @throws Re-throws the cached error if a previous async resolution for this symbol failed
87
+ * @throws Throws if the instance has not been resolved yet (see {@link ResolutionContext.getSync})
88
+ */
23
89
  getSync(typeSymbol) {
24
90
  if (__classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").has(typeSymbol.symbol)) {
25
91
  throw __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").get(typeSymbol.symbol);
26
92
  }
27
93
  return __classPrivateFieldGet(this, _ReactResolutionContext_resolutionContext, "f").getSync(typeSymbol);
28
94
  }
95
+ /**
96
+ * Asynchronously resolves an instance for the given type symbol.
97
+ *
98
+ * If a previous resolution for this symbol failed, the cached error is
99
+ * thrown immediately. Otherwise the call goes to the underlying context,
100
+ * which joins a creation already in flight for a singleton.
101
+ *
102
+ * @template T The type of the resolved instance
103
+ * @param typeSymbol - The typed symbol identifying the dependency to resolve
104
+ * @returns A promise that resolves to the instance
105
+ * @throws Re-throws the cached error if a previous resolution for this symbol failed
106
+ */
29
107
  async get(typeSymbol) {
30
- if (__classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").has(typeSymbol.symbol)) {
31
- throw __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").get(typeSymbol.symbol);
108
+ const symbol = typeSymbol.symbol;
109
+ if (__classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").has(symbol)) {
110
+ throw __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").get(symbol);
32
111
  }
33
- const promise = __classPrivateFieldGet(this, _ReactResolutionContext_resolutions, "f").get(typeSymbol.symbol);
34
- if (promise) {
35
- return promise;
112
+ const startedAt = __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f");
113
+ try {
114
+ return await __classPrivateFieldGet(this, _ReactResolutionContext_resolutionContext, "f").get(typeSymbol);
36
115
  }
37
- const newResolution = __classPrivateFieldGet(this, _ReactResolutionContext_resolutionContext, "f").get(typeSymbol);
38
- __classPrivateFieldGet(this, _ReactResolutionContext_resolutions, "f").set(typeSymbol.symbol, newResolution);
39
- return newResolution
40
- .catch((err) => {
41
- __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").set(typeSymbol.symbol, err);
116
+ catch (err) {
117
+ // A failure that settles after `clearErrors` belongs to the attempt the
118
+ // caller just discarded: hand it to this caller, but don't cache it.
119
+ if (!__classPrivateFieldGet(this, _ReactResolutionContext_instances, "m", _ReactResolutionContext_clearedSince).call(this, symbol, startedAt)) {
120
+ __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").set(symbol, err);
121
+ }
42
122
  throw err;
43
- })
44
- .finally(() => {
45
- __classPrivateFieldGet(this, _ReactResolutionContext_resolutions, "f").delete(typeSymbol.symbol);
46
- });
123
+ }
47
124
  }
125
+ /**
126
+ * Forgets cached resolution errors, so the next `get` or `getSync` asks the
127
+ * underlying context again.
128
+ *
129
+ * Call it after replacing a failed binding (`unbind`, then apply the wire
130
+ * again), then reset the error boundary that shows the error. A failure that
131
+ * was still in flight when you call this is not cached when it settles.
132
+ *
133
+ * @param typeSymbol - The symbol whose error to forget. Omit to forget all.
134
+ */
135
+ clearErrors(typeSymbol) {
136
+ __classPrivateFieldSet(this, _ReactResolutionContext_generation, __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f") + 1, "f");
137
+ if (typeSymbol) {
138
+ __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").delete(typeSymbol.symbol);
139
+ __classPrivateFieldGet(this, _ReactResolutionContext_clearedAt, "f").set(typeSymbol.symbol, __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f"));
140
+ return;
141
+ }
142
+ __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").clear();
143
+ __classPrivateFieldGet(this, _ReactResolutionContext_clearedAt, "f").clear();
144
+ __classPrivateFieldSet(this, _ReactResolutionContext_allClearedAt, __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f"), "f");
145
+ }
146
+ }
147
+ _ReactResolutionContext_resolutionContext = new WeakMap(), _ReactResolutionContext_resolutionErrors = new WeakMap(), _ReactResolutionContext_generation = new WeakMap(), _ReactResolutionContext_allClearedAt = new WeakMap(), _ReactResolutionContext_clearedAt = new WeakMap(), _ReactResolutionContext_instances = new WeakSet(), _ReactResolutionContext_clearedSince = function _ReactResolutionContext_clearedSince(symbol, generation) {
148
+ const clearedAt = Math.max(__classPrivateFieldGet(this, _ReactResolutionContext_allClearedAt, "f"), __classPrivateFieldGet(this, _ReactResolutionContext_clearedAt, "f").get(symbol) ?? 0);
149
+ return clearedAt > generation;
150
+ };
151
+ /**
152
+ * The wrapper {@link ResolutionContextProvider} uses for each plain context, so
153
+ * every render and every mount of a provider for that context share one error
154
+ * cache and one context value.
155
+ */
156
+ const reactResolutionContexts = new WeakMap();
157
+ function reactResolutionContextFor(resolutionContext) {
158
+ if (resolutionContext instanceof ReactResolutionContext) {
159
+ return resolutionContext;
160
+ }
161
+ let wrapper = reactResolutionContexts.get(resolutionContext);
162
+ if (!wrapper) {
163
+ wrapper = new ReactResolutionContext(resolutionContext);
164
+ reactResolutionContexts.set(resolutionContext, wrapper);
165
+ }
166
+ return wrapper;
48
167
  }
49
- _ReactResolutionContext_resolutionContext = new WeakMap(), _ReactResolutionContext_resolutions = new WeakMap(), _ReactResolutionContext_resolutionErrors = new WeakMap();
168
+ /**
169
+ * React Context that holds the active {@link ResolutionContext} for the component tree.
170
+ *
171
+ * The default value is an empty {@link TypeWireContainer} wrapped in a
172
+ * {@link ReactResolutionContext}. In practice, you should provide your own
173
+ * container via {@link ResolutionContextProvider}.
174
+ */
50
175
  export const ContainerContext = React.createContext(new ReactResolutionContext(new TypeWireContainer()));
176
+ /**
177
+ * Hook to access the current {@link ResolutionContext} from the nearest
178
+ * {@link ResolutionContextProvider}.
179
+ *
180
+ * @returns The current resolution context
181
+ *
182
+ * @example
183
+ * ```tsx
184
+ * function MyComponent() {
185
+ * const container = useContainer();
186
+ * // Use container for manual resolution if needed
187
+ * }
188
+ * ```
189
+ */
51
190
  export function useContainer() {
52
191
  const container = React.useContext(ContainerContext);
53
192
  return container;
54
193
  }
55
- export function useTypeWire(typeWire) {
194
+ /** Error reason thrown by {@link useTypeWire} with `{ suspend: false }`. */
195
+ const ReasonNotPreloaded = "NotPreloaded";
196
+ const ScopeSingleton = "singleton";
197
+ /** Marks a state that has no value yet, so falsy values still count as values. */
198
+ const NotReady = Symbol("NotReady");
199
+ /**
200
+ * Reads a wire synchronously. Returns `NotReady` when the value isn't
201
+ * created yet and can be waited for; rethrows any other error.
202
+ */
203
+ function readSync(typeWire, container) {
204
+ try {
205
+ return typeWire.getInstanceSync(container);
206
+ }
207
+ catch (err) {
208
+ if (err instanceof TypeWireError && err.retriable) {
209
+ return NotReady;
210
+ }
211
+ throw err;
212
+ }
213
+ }
214
+ function notPreloaded(typeWire, cause) {
215
+ const name = typeWire.type.symbol.description ?? "(unnamed wire)";
216
+ const err = new TypeWireError(ReasonNotPreloaded, `${name} is not ready. It was rendered with { suspend: false } before it was created: preload it (container.preload or usePreload) before this component renders.`);
217
+ err.retriable = false;
218
+ Object.defineProperty(err, "cause", {
219
+ value: cause,
220
+ enumerable: false,
221
+ writable: true,
222
+ configurable: true,
223
+ });
224
+ return err;
225
+ }
226
+ /**
227
+ * Hook that resolves a {@link TypeWire} within the current container context,
228
+ * with React Suspense integration.
229
+ *
230
+ * Resolution behavior:
231
+ * 1. **Sync available** — If the wire can be resolved synchronously (e.g., a singleton
232
+ * that was already created or preloaded), the value is returned immediately,
233
+ * including falsy values such as `0`, `""`, `false` and `null`.
234
+ * 2. **Async pending** — If sync resolution fails with a retriable error, the hook
235
+ * starts an async resolution and throws the promise to trigger React Suspense.
236
+ * With `{ suspend: false }` it throws a `TypeWireError` with reason
237
+ * `NotPreloaded` instead.
238
+ * 3. **Error** — If sync resolution fails with a non-retriable error, it is re-thrown.
239
+ *
240
+ * To render without a fallback, preload the wires first, with
241
+ * `container.preload` before rendering or {@link usePreload} higher in the
242
+ * tree. A wire nobody preloaded suspends, so this hook must be used inside a
243
+ * `<Suspense>` boundary unless you pass `{ suspend: false }`.
244
+ *
245
+ * @template T The type of the resolved instance
246
+ * @param typeWire - The TypeWire to resolve
247
+ * @param opts - Optional settings; see {@link UseTypeWireOpts}
248
+ * @returns The resolved instance
249
+ * @throws The resolution promise when the value is not yet available (for Suspense)
250
+ * @throws {@link TypeWireError} with reason `NotPreloaded` when the value is not yet available and `suspend` is `false`
251
+ * @throws {@link TypeWireError} if synchronous resolution fails with a non-retriable error
252
+ *
253
+ * @example
254
+ * ```tsx
255
+ * function UserProfile() {
256
+ * const userService = useTypeWire(UserServiceWire);
257
+ * return <div>{userService.getName()}</div>;
258
+ * }
259
+ *
260
+ * // Preloaded before rendering: no fallback.
261
+ * await container.preload({ wires: [UserServiceWire] });
262
+ *
263
+ * // Or wrap in Suspense for wires that may not be ready yet.
264
+ * <Suspense fallback={<Loading />}>
265
+ * <UserProfile />
266
+ * </Suspense>
267
+ * ```
268
+ */
269
+ export function useTypeWire(typeWire, opts) {
56
270
  const container = useContainer();
57
- const [value, setValue] = React.useState(() => {
271
+ const suspend = opts?.suspend ?? true;
272
+ const [state, setState] = React.useState(() => ({ value: readSync(typeWire, container) }));
273
+ if (state.value === NotReady && !suspend) {
274
+ let cause;
58
275
  try {
59
- return typeWire.getInstanceSync(container);
276
+ typeWire.getInstanceSync(container);
60
277
  }
61
278
  catch (err) {
62
- if (err instanceof TypeWireError && err.retriable) {
63
- return null;
64
- }
65
- throw err;
279
+ cause = err;
66
280
  }
67
- });
281
+ throw notPreloaded(typeWire, cause);
282
+ }
68
283
  const promise = typeWire.getInstance(container);
69
284
  React.useEffect(() => {
70
- let mounted = false;
285
+ let mounted = true;
71
286
  promise
72
287
  .then((value) => {
73
288
  if (mounted) {
74
- console.log("we got the value", value);
75
- setValue(() => value);
289
+ // Keep the same state object for the same value, so React skips the
290
+ // re-render; a new object here would re-render, start a new
291
+ // `getInstance` and run this effect again, forever.
292
+ setState((prev) => (Object.is(prev.value, value) ? prev : { value }));
76
293
  }
77
294
  })
78
295
  .catch((err) => {
79
- console.error(err);
296
+ if (mounted) {
297
+ console.error(err);
298
+ }
80
299
  });
81
300
  return () => {
82
301
  mounted = false;
83
302
  };
84
303
  }, [promise]);
85
- if (value) {
86
- return value;
304
+ if (state.value !== NotReady) {
305
+ return state.value;
87
306
  }
88
307
  throw promise;
89
308
  }
309
+ /**
310
+ * Hook that suspends the calling component until every singleton in
311
+ * `opts.wires` is created, so components below it read them with
312
+ * {@link useTypeWire} without suspending.
313
+ *
314
+ * Use it where a part of the app starts (a route, a panel, a feature), under
315
+ * one `<Suspense>` boundary: the fallback shows once for the whole set, and
316
+ * the creations run in parallel. A creation that fails reaches the nearest
317
+ * error boundary.
318
+ *
319
+ * It works with any resolution context, including the Inversify adapter.
320
+ * Outside React, use `container.preload` instead.
321
+ *
322
+ * @param opts - The wires to preload; see {@link UsePreloadOpts}
323
+ * @throws A promise while any of the wires is still being created (for Suspense)
324
+ * @throws The creation's error, once one has failed
325
+ *
326
+ * @example
327
+ * ```tsx
328
+ * function ReportsRoute() {
329
+ * usePreload({ wires: [reportsServiceWire, chartsWire] });
330
+ * return <ReportsPage />;
331
+ * }
332
+ *
333
+ * <Suspense fallback={<Loading />}>
334
+ * <ReportsRoute />
335
+ * </Suspense>
336
+ * ```
337
+ */
338
+ export function usePreload(opts) {
339
+ const container = useContainer();
340
+ const pending = [];
341
+ for (const wire of opts.wires) {
342
+ if ((wire.scope ?? ScopeSingleton) !== ScopeSingleton) {
343
+ continue;
344
+ }
345
+ if (readSync(wire, container) === NotReady) {
346
+ pending.push(wire.getInstance(container));
347
+ }
348
+ }
349
+ if (pending.length > 0) {
350
+ throw Promise.all(pending);
351
+ }
352
+ }
353
+ /**
354
+ * React component that provides a {@link ResolutionContext} to the component tree.
355
+ *
356
+ * If the given `resolutionContext` is not already a {@link ReactResolutionContext},
357
+ * it is wrapped in one, so a failed resolution reaches an error boundary
358
+ * instead of retrying under Suspense. Each plain context gets one wrapper,
359
+ * reused on every render and every mount, so re-rendering the provider keeps
360
+ * cached errors and gives consumers the same context value.
361
+ *
362
+ * A cached error lasts until `clearErrors` is called, even after `unbind` and
363
+ * a re-apply. To be able to retry, create the {@link ReactResolutionContext}
364
+ * yourself, pass it here, and call its `clearErrors` after replacing the
365
+ * binding.
366
+ *
367
+ * The context must share one in-flight creation per singleton (as
368
+ * `TypeWireContainer` does); see {@link ReactResolutionContext}.
369
+ *
370
+ * @param props.resolutionContext - The resolution context to provide to descendants
371
+ * @param props.children - Child components that will have access to the context
372
+ *
373
+ * @example
374
+ * ```tsx
375
+ * async function main() {
376
+ * const container = new TypeWireContainer();
377
+ * await AppWireGroup.apply(container);
378
+ *
379
+ * createRoot(document.getElementById('root')!).render(
380
+ * <ResolutionContextProvider resolutionContext={container}>
381
+ * <App />
382
+ * </ResolutionContextProvider>
383
+ * );
384
+ * }
385
+ * ```
386
+ */
90
387
  export function ResolutionContextProvider(props) {
91
- const resolutionContext = props.resolutionContext instanceof ReactResolutionContext
92
- ? props.resolutionContext
93
- : new ReactResolutionContext(props.resolutionContext);
388
+ const resolutionContext = reactResolutionContextFor(props.resolutionContext);
94
389
  return (_jsx(ContainerContext, { value: resolutionContext, children: props.children }));
95
390
  }
96
391
  //# sourceMappingURL=index.js.map