@abloatai/humans 0.63.1 → 0.64.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.
Files changed (87) hide show
  1. package/dist/Ablo.d.ts +6 -0
  2. package/dist/client.d.ts +12 -32
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +1 -0
  5. package/dist/local/client/createModelOperations.d.ts +3 -3
  6. package/dist/local/client/createModelOperations.js +1 -1
  7. package/dist/local/client/reactiveEngine.js +7 -8
  8. package/dist/{react/useSyncStatus.d.ts → local/client/status.d.ts} +4 -3
  9. package/dist/local/client/status.js +14 -0
  10. package/dist/local/client/storeLifecycle.js +2 -2
  11. package/dist/local/mutators/defineMutators.d.ts +3 -48
  12. package/dist/local/mutators/defineMutators.js +0 -15
  13. package/dist/local/storeAccess.d.ts +7 -0
  14. package/dist/local/storeAccess.js +6 -0
  15. package/dist/local/storeContract.d.ts +3 -4
  16. package/dist/presence/index.d.ts +2 -2
  17. package/dist/presence/index.js +8 -4
  18. package/dist/react/AbloProvider.d.ts +57 -121
  19. package/dist/react/AbloProvider.js +55 -160
  20. package/dist/react/context.d.ts +6 -45
  21. package/dist/react/context.js +8 -20
  22. package/dist/react/createAbloReact.d.ts +13 -48
  23. package/dist/react/createAbloReact.js +8 -54
  24. package/dist/react/internalContext.d.ts +1 -27
  25. package/dist/react/snapshot.d.ts +4 -0
  26. package/dist/react/snapshot.js +75 -0
  27. package/dist/react/useAblo.d.ts +28 -92
  28. package/dist/react/useAblo.js +36 -93
  29. package/dist/react/useAbloClient.d.ts +5 -0
  30. package/dist/react/useAbloClient.js +9 -0
  31. package/dist/react/useMutationFailure.d.ts +6 -0
  32. package/dist/react/useMutationFailure.js +11 -0
  33. package/dist/react/useMutators.d.ts +22 -19
  34. package/dist/react/useMutators.js +3 -3
  35. package/dist/react/usePresence.d.ts +9 -9
  36. package/dist/react/usePresence.js +8 -11
  37. package/dist/react/useReactive.d.ts +12 -0
  38. package/dist/react/useReactive.js +57 -0
  39. package/dist/react/useUndoScope.d.ts +16 -30
  40. package/dist/react/useUndoScope.js +21 -4
  41. package/dist/react.d.ts +9 -19
  42. package/dist/react.js +9 -15
  43. package/dist/reactRuntime.d.ts +1 -1
  44. package/dist/reactRuntime.js +1 -1
  45. package/package.json +4 -3
  46. package/src/Ablo.ts +7 -0
  47. package/src/client.ts +13 -32
  48. package/src/index.ts +2 -0
  49. package/src/local/client/createModelOperations.ts +4 -4
  50. package/src/local/client/reactiveEngine.ts +7 -8
  51. package/src/local/client/status.ts +20 -0
  52. package/src/local/client/storeLifecycle.ts +2 -2
  53. package/src/local/mutators/defineMutators.ts +3 -51
  54. package/src/local/storeAccess.ts +10 -0
  55. package/src/local/storeContract.ts +3 -4
  56. package/src/presence/index.ts +10 -5
  57. package/src/react/AbloProvider.tsx +88 -263
  58. package/src/react/context.ts +10 -61
  59. package/src/react/createAbloReact.ts +16 -125
  60. package/src/react/internalContext.ts +1 -27
  61. package/src/react/snapshot.ts +67 -0
  62. package/src/react/useAblo.ts +73 -209
  63. package/src/react/useAbloClient.ts +14 -0
  64. package/src/react/useMutationFailure.ts +17 -0
  65. package/src/react/useMutators.ts +36 -32
  66. package/src/react/usePresence.ts +22 -27
  67. package/src/react/useReactive.ts +56 -0
  68. package/src/react/useUndoScope.ts +24 -20
  69. package/src/react.ts +9 -69
  70. package/src/reactRuntime.ts +2 -2
  71. package/dist/react/ClientSideSuspense.d.ts +0 -36
  72. package/dist/react/ClientSideSuspense.js +0 -17
  73. package/dist/react/useCurrentUserId.d.ts +0 -2
  74. package/dist/react/useCurrentUserId.js +0 -12
  75. package/dist/react/useErrorListener.d.ts +0 -2
  76. package/dist/react/useErrorListener.js +0 -14
  77. package/dist/react/useMutationFailureListener.d.ts +0 -8
  78. package/dist/react/useMutationFailureListener.js +0 -19
  79. package/dist/react/useSyncStatus.js +0 -48
  80. package/dist/useReactive.d.ts +0 -6
  81. package/dist/useReactive.js +0 -41
  82. package/src/react/ClientSideSuspense.tsx +0 -57
  83. package/src/react/useCurrentUserId.ts +0 -17
  84. package/src/react/useErrorListener.ts +0 -22
  85. package/src/react/useMutationFailureListener.ts +0 -34
  86. package/src/react/useSyncStatus.ts +0 -53
  87. package/src/useReactive.ts +0 -49
@@ -1,54 +1,19 @@
1
- /**
2
- * The typed react binding — the schema generic is captured ONCE, at a factory
3
- * call in app code, and every hook the factory returns is born typed. This is
4
- * a schema-bound shape with no module augmentation or generic parameters at call sites,
5
- * and — once the legacy generic erasure retires — no casts anywhere on the
6
- * path from context to component.
7
- *
8
- * The app's one binding file, by convention:
9
- *
10
- * ```ts
11
- * // lib/ablo.ts
12
- * import { createAbloReact } from '@abloatai/ablo/react';
13
- * import { schema } from './schema';
14
- *
15
- * export const { AbloProvider, useAblo } = createAbloReact(schema);
16
- * ```
17
- *
18
- * Components then import `useAblo` from `lib/ablo` and never spell a type
19
- * argument; `useAblo()` is `Ablo<S> | null`, and a selector's `ablo`
20
- * parameter is the reactive-read view of the same `S`.
21
- */
22
- import { type ReactElement } from 'react';
23
- import { type AbloProviderProps } from './AbloProvider.js';
24
- import { type AbloSelector, type ModelClientSelector, type UseAbloHydratedModelResult, type UseAbloModelOptions, type UseAbloModelResult } from './useAblo.js';
1
+ import type { ReactElement } from 'react';
2
+ import { useMutationFailure } from './useMutationFailure.js';
3
+ import { AbloProvider } from './AbloProvider.js';
4
+ import { useAblo } from './useAblo.js';
25
5
  import type { AbloClient as Ablo } from '../client.js';
26
- import type { ModelOperations } from '../local/client/createModelOperations.js';
27
6
  import type { Schema, SchemaRecord } from '@abloatai/transaction/schema/schema';
28
- import { type PresenceModelSelector } from './usePresence.js';
29
- import type { PresenceSession } from '@abloatai/transaction/presence';
30
- /** What a binding returns: the provider and the hook, with `S` fixed. */
7
+ import { usePresence } from './usePresence.js';
8
+ /** Shared provider and hooks specialized to one schema. */
31
9
  export interface AbloReactBinding<S extends SchemaRecord> {
32
- /** `AbloProvider` with its `client` prop typed `Ablo<S>` — same component,
33
- * no per-app generics. */
34
- AbloProvider: (props: AbloProviderProps<S>) => ReactElement;
35
- /** `useAblo` with the schema bound — the same overloads as the global
36
- * hook, minus the type arguments. */
37
- useAblo: {
38
- (): Ablo<S> | null;
39
- <T>(select: AbloSelector<S, T>): T | undefined;
40
- <T, C>(modelClientOrSelect: ModelOperations<T, C> | ModelClientSelector<S, T, C>, id: string, options: UseAbloModelOptions<T> & {
41
- readonly initial: T;
42
- }): UseAbloHydratedModelResult<T>;
43
- <T, C>(modelClientOrSelect: ModelOperations<T, C> | ModelClientSelector<S, T, C>, id: string, options?: UseAbloModelOptions<T>): UseAbloModelResult<T>;
44
- };
10
+ AbloProvider: (props: AbloProvider.Props<S>) => ReactElement;
11
+ useAblo: useAblo.Bound<S>;
12
+ /** Writable client for actions; useAblo(selector) supplies render snapshots. */
13
+ useAbloClient: () => Ablo<S> | null;
14
+ useMutationFailure: typeof useMutationFailure;
45
15
  /** Declare and reactively read record presence with the same model clients. */
46
- usePresence: <T, C>(modelOrSelect: ModelOperations<T, C> | PresenceModelSelector<S, T, C>, recordId: string) => readonly PresenceSession[];
16
+ usePresence: usePresence.Bound<S>;
47
17
  }
48
- /**
49
- * Bind the react surface to one schema. The schema value is taken for
50
- * inference — write `createAbloReact(schema)`, never a hand-spelled type
51
- * argument — and it is the seam where the binding's own typed context arrives
52
- * when the legacy erasure retires (docs/plans/typed-react-binding.md, step 3).
53
- */
18
+ /** Bind the existing React functions to one schema's types. */
54
19
  export declare function createAbloReact<S extends SchemaRecord>(schema: Schema<S>): AbloReactBinding<S>;
@@ -1,58 +1,12 @@
1
1
  'use client';
2
- /**
3
- * The typed react binding — the schema generic is captured ONCE, at a factory
4
- * call in app code, and every hook the factory returns is born typed. This is
5
- * a schema-bound shape with no module augmentation or generic parameters at call sites,
6
- * and — once the legacy generic erasure retires — no casts anywhere on the
7
- * path from context to component.
8
- *
9
- * The app's one binding file, by convention:
10
- *
11
- * ```ts
12
- * // lib/ablo.ts
13
- * import { createAbloReact } from '@abloatai/ablo/react';
14
- * import { schema } from './schema';
15
- *
16
- * export const { AbloProvider, useAblo } = createAbloReact(schema);
17
- * ```
18
- *
19
- * Components then import `useAblo` from `lib/ablo` and never spell a type
20
- * argument; `useAblo()` is `Ablo<S> | null`, and a selector's `ablo`
21
- * parameter is the reactive-read view of the same `S`.
22
- */
23
- import { createContext, createElement, useContext } from 'react';
24
- import { AbloProvider, } from './AbloProvider.js';
25
- import { useAbloImpl, useAbloClientImpl, } from './useAblo.js';
26
- import { usePresenceImpl, } from './usePresence.js';
27
- /**
28
- * Bind the react surface to one schema. The schema value is taken for
29
- * inference — write `createAbloReact(schema)`, never a hand-spelled type
30
- * argument — and it is the seam where the binding's own typed context arrives
31
- * when the legacy erasure retires (docs/plans/typed-react-binding.md, step 3).
32
- */
2
+ import { useAbloClient } from './useAbloClient.js';
3
+ import { useMutationFailure } from './useMutationFailure.js';
4
+ import { AbloProvider } from './AbloProvider.js';
5
+ import { useAblo } from './useAblo.js';
6
+ import { usePresence } from './usePresence.js';
7
+ /** Bind the existing React functions to one schema's types. */
33
8
  export function createAbloReact(schema) {
34
9
  void schema;
35
- // The binding's own context — created here, AFTER the schema generic is
36
- // known, so it is typed `Ablo<S>` from birth. A hook that reads it never rebinds and
37
- // never casts; a binding hook mounted under a legacy provider (no bound
38
- // provider in the tree) reads `null` here and falls through to the shared
39
- // implementation's internal-context fallback.
40
- const BoundClientContext = createContext(null);
41
- function BoundAbloProvider(props) {
42
- return createElement(BoundClientContext.Provider, { value: props.client }, createElement((AbloProvider), props));
43
- }
44
- function useBoundAblo(modelOrSelect, id, options) {
45
- const bound = useContext(BoundClientContext);
46
- return useAbloImpl(bound, modelOrSelect, id, options);
47
- }
48
- function useBoundPresence(modelOrSelect, recordId) {
49
- const bound = useContext(BoundClientContext);
50
- const engine = useAbloClientImpl(bound);
51
- return usePresenceImpl(engine, modelOrSelect, recordId);
52
- }
53
- return {
54
- AbloProvider: BoundAbloProvider,
55
- useAblo: useBoundAblo,
56
- usePresence: useBoundPresence,
57
- };
10
+ // Specialize the shared functions without creating new contexts or identities.
11
+ return { AbloProvider, useAblo, useAbloClient, useMutationFailure, usePresence };
58
12
  }
@@ -1,33 +1,7 @@
1
1
  import type { AbloClient as Ablo } from '../client.js';
2
2
  import type { SchemaRecord } from '@abloatai/transaction/schema/schema';
3
- /**
4
- * The context that `<AbloProvider>` populates for its own hooks. It is kept
5
- * separate from the data-hook context, which carries the store and schema,
6
- * because these fields belong to the provider rather than to the store. Read
7
- * them through the typed hooks such as `useCurrentUserId` and
8
- * `useErrorListener` rather than reaching into this context directly.
9
- */
3
+ /** The provider owns only the reference to the application-owned client. */
10
4
  export interface AbloInternalContextValue {
11
- /**
12
- * The application user id, when your app passed one to `<AbloProvider>`. Sync
13
- * identity is derived on the server from the API key, so this is `null`
14
- * unless you set it, and it is not required for sync to work.
15
- */
16
- currentUserId: string | null;
17
- /** Subscribe to provider-level errors: engine errors, bootstrap failures, and session issues. */
18
- subscribeError: (listener: (error: Error) => void) => () => void;
19
- /** Emit an error to every subscribed listener. The provider calls this for you. */
20
- emitError: (error: Error) => void;
21
- /**
22
- * The typed `Ablo` client for this provider, or `null` until the first sync
23
- * bootstrap resolves. It is held here so `useSync()` can return it without
24
- * reaching into the store; the client and the store are sibling objects, and
25
- * neither is derived from the other.
26
- *
27
- * It is typed loosely as `Ablo<SchemaRecord>` because generics do not flow
28
- * through React context. `useSync<R>()` restores the precise type through its
29
- * own generic; the runtime value is the fully typed client.
30
- */
31
5
  engine: Ablo<SchemaRecord> | null;
32
6
  }
33
7
  export declare const AbloInternalContext: import("react").Context<AbloInternalContextValue | null>;
@@ -0,0 +1,4 @@
1
+ /** Read and detach selected data while the enclosing reaction tracks its fields. */
2
+ export declare function snapshotValue<T>(value: T): T;
3
+ /** Compare data snapshots, including non-enumerable schema-derived fields. */
4
+ export declare function equalSnapshots(a: unknown, b: unknown): boolean;
@@ -0,0 +1,75 @@
1
+ import { isObservableObject } from 'mobx';
2
+ import { Model } from '../local/Model.js';
3
+ import { getModelClientMeta } from '../local/client/createModelOperations.js';
4
+ function isRecord(value) {
5
+ return Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null;
6
+ }
7
+ /** Read and detach selected data while the enclosing reaction tracks its fields. */
8
+ export function snapshotValue(value) {
9
+ const seen = new WeakMap();
10
+ function visit(input) {
11
+ if (input === null || typeof input !== 'object')
12
+ return input;
13
+ if (seen.has(input))
14
+ return seen.get(input);
15
+ // A selected model namespace is an API handle, not row data. Preserve its
16
+ // identity so it can still be passed to presence and other core operations.
17
+ if (getModelClientMeta(input))
18
+ return input;
19
+ if (input instanceof Date) {
20
+ const date = new Date(input.getTime());
21
+ seen.set(input, date);
22
+ return Object.freeze(date);
23
+ }
24
+ if (Array.isArray(input)) {
25
+ const array = new Array(input.length);
26
+ seen.set(input, array);
27
+ input.forEach((item, index) => { array[index] = visit(item); });
28
+ return Object.freeze(array);
29
+ }
30
+ const source = input instanceof Model ? input.toReactiveSnapshot() : input;
31
+ if (!isRecord(source))
32
+ return input;
33
+ const result = Object.getPrototypeOf(source) === null ? Object.create(null) : {};
34
+ seen.set(input, result);
35
+ // MobX's own symbols describe its administration, not selected application data.
36
+ const keys = isObservableObject(source) ? Object.keys(source) : Reflect.ownKeys(source);
37
+ for (const key of keys) {
38
+ Object.defineProperty(result, key, {
39
+ value: visit(Reflect.get(source, key)),
40
+ enumerable: Object.prototype.propertyIsEnumerable.call(source, key),
41
+ });
42
+ }
43
+ return Object.freeze(result);
44
+ }
45
+ return visit(value);
46
+ }
47
+ /** Compare data snapshots, including non-enumerable schema-derived fields. */
48
+ export function equalSnapshots(a, b) {
49
+ const seen = new WeakMap();
50
+ function equal(left, right) {
51
+ if (Object.is(left, right))
52
+ return true;
53
+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object')
54
+ return false;
55
+ if (left instanceof Date || right instanceof Date) {
56
+ return left instanceof Date && right instanceof Date && Object.is(left.getTime(), right.getTime());
57
+ }
58
+ if (Array.isArray(left) !== Array.isArray(right))
59
+ return false;
60
+ if (!Array.isArray(left) && (!isRecord(left) || !isRecord(right)))
61
+ return false;
62
+ if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right))
63
+ return false;
64
+ if (seen.has(left))
65
+ return seen.get(left) === right;
66
+ seen.set(left, right);
67
+ const keys = Reflect.ownKeys(left);
68
+ if (keys.length !== Reflect.ownKeys(right).length)
69
+ return false;
70
+ return keys.every(key => Object.prototype.hasOwnProperty.call(right, key)
71
+ && Object.prototype.propertyIsEnumerable.call(left, key) === Object.prototype.propertyIsEnumerable.call(right, key)
72
+ && equal(Reflect.get(left, key), Reflect.get(right, key)));
73
+ }
74
+ return equal(a, b);
75
+ }
@@ -1,98 +1,34 @@
1
- import type { AbloClient as Ablo, AbloReads } from '../client.js';
1
+ import type { AbloReads } from '../client.js';
2
2
  import type { ModelClaim } from '@abloatai/transaction/coordination';
3
3
  import { type ModelOperations } from '../local/client/createModelOperations.js';
4
4
  import type { SchemaRecord } from '@abloatai/transaction/schema/schema';
5
- import type { ResolveSchema } from '@abloatai/transaction/types/global';
6
- /**
7
- * The app's resolved schema-record type. It reads your `Register` module
8
- * augmentation when you declare one and falls back to the loose
9
- * {@link SchemaRecord} otherwise, so `useAblo()` returns a fully typed client
10
- * without you passing `<(typeof schema)['models']>` at every call site.
11
- */
12
- type DefaultModels = ResolveSchema extends {
13
- models: infer M;
14
- } ? M extends SchemaRecord ? M : SchemaRecord : SchemaRecord;
5
+ import type { ResolveModels as DefaultModels } from '@abloatai/transaction/types/global';
15
6
  export type ModelClientSelector<R extends SchemaRecord, T, C> = (ablo: AbloReads<R>) => ModelOperations<T, C>;
16
7
  export type AbloSelector<R extends SchemaRecord, T> = (ablo: AbloReads<R>) => T;
17
- export interface UseAbloModelOptions<T> {
18
- /**
19
- * An initial row, usually from a server component or a route loader. The hook
20
- * returns it until sync delivers a newer row for the same id.
21
- */
22
- readonly initial?: T;
23
- }
24
- export interface UseAbloModelResult<T> {
25
- /** The current row for the id, or `initial` until the row has synced. */
26
- readonly data: T | undefined;
27
- /** The work claims currently held on this row by any participant. */
28
- readonly claims: readonly ModelClaim[];
29
- /** True while another participant holds a claim — handy for disabling UI. */
30
- readonly claimed: boolean;
31
- }
32
- export type UseAbloHydratedModelResult<T> = Omit<UseAbloModelResult<T>, 'data'> & {
33
- readonly data: T;
34
- };
35
- /**
36
- * Reads Ablo from inside an `<AbloProvider>` subtree. Called with no arguments
37
- * it returns the typed client for use in callbacks and effects; called with a
38
- * selector it subscribes the component to a reactive read — such as one
39
- * `ablo.<model>` row — and re-renders when that read changes.
40
- *
41
- * You can call it with no type arguments once you declare the `Register` module
42
- * augmentation (`declare module '@abloatai/ablo' { interface Register {
43
- * Schema: typeof schema } }`); the default type then resolves through your
44
- * schema's models, so call sites stay clean:
45
- *
46
- * **Prefer the binding.** `createAbloReact(schema)` captures the schema once
47
- * in your app's binding file and returns a `useAblo` that needs none of the
48
- * typing arrangements below — no type argument, no `Register` declaration
49
- * (see `react.md`). Passing an explicit schema type argument to THIS hook is
50
- * deprecated in favor of that binding; it keeps working for shared packages
51
- * that cannot bind a concrete schema.
52
- *
53
- * ```ts
54
- * // With the Register augmentation (recommended):
55
- * const ablo = useAblo();
56
- * if (!ablo) return <Loading />;
57
- * const doc = await ablo.records.get({ id }); // observational async server read
58
- *
59
- * // Reactive selector (a synchronous local snapshot). The selector's reads
60
- * // are typed as snapshot rows — data fields + computeds, no relation
61
- * // accessors — matching what the hook actually returns:
62
- * const doc = useAblo((ablo) => ablo.records.local.get(id)) ?? serverDoc;
63
- * const { claimed } = useAblo((ablo) => ablo.records, id);
64
- *
65
- * // Without the augmentation, pass the schema as a type argument:
66
- * const ablo = useAblo<(typeof schema)['models']>();
67
- * ```
68
- *
69
- * The no-argument form returns `null` while the engine is still bootstrapping.
70
- * Branch on `null` and render a loading state — or gate on `useSyncStatus()`
71
- * reaching `'connected'` — before calling model methods.
72
- */
73
- export declare function useAblo<R extends SchemaRecord = DefaultModels>(): Ablo<R> | null;
8
+ /** Select a reactive snapshot or read a row with its current claims. */
74
9
  export declare function useAblo<R extends SchemaRecord = DefaultModels, T = unknown>(select: AbloSelector<R, T>): T | undefined;
75
- export declare function useAblo<T, C>(modelClient: ModelOperations<T, C>, id: string, options: UseAbloModelOptions<T> & {
76
- readonly initial: T;
77
- }): UseAbloHydratedModelResult<T>;
78
- export declare function useAblo<R extends SchemaRecord = DefaultModels, T = Record<string, unknown>, C = unknown>(select: ModelClientSelector<R, T, C>, id: string, options: UseAbloModelOptions<T> & {
79
- readonly initial: T;
80
- }): UseAbloHydratedModelResult<T>;
81
- export declare function useAblo<T, C>(modelClient: ModelOperations<T, C>, id: string, options?: UseAbloModelOptions<T>): UseAbloModelResult<T>;
82
- export declare function useAblo<R extends SchemaRecord = DefaultModels, T = Record<string, unknown>, C = unknown>(select: ModelClientSelector<R, T, C>, id: string, options?: UseAbloModelOptions<T>): UseAbloModelResult<T>;
83
- /**
84
- * @internal The one implementation behind `useAblo` and the bound hooks a
85
- * `createAbloReact` binding returns — written once so the reactive read path
86
- * cannot fork between the global hook and a factory's.
87
- *
88
- * `boundClient` is a binding's own context value — typed `Ablo<S>` at the
89
- * factory, so that path never rebinds and never casts. `null` means "no
90
- * binding provider in this tree": the global hook always passes it, and a
91
- * binding hook mounted under a legacy provider falls through to the erased
92
- * internal context, which is what keeps both mounts working while the last
93
- * legacy mount migrates.
94
- */
95
- export declare function useAbloImpl<R extends SchemaRecord, T = Record<string, unknown>, C = unknown>(boundClient: Ablo<R> | null, modelOrSelect?: ModelOperations<T, C> | ModelClientSelector<R, T, C> | AbloSelector<R, T>, id?: string, options?: UseAbloModelOptions<T>): Ablo<R> | null | UseAbloModelResult<T> | T | undefined;
96
- /** @internal Resolve the bound or legacy provider client through one rebind seam. */
97
- export declare function useAbloClientImpl<R extends SchemaRecord>(boundClient: Ablo<R> | null): Ablo<R> | null;
98
- export {};
10
+ export declare function useAblo<T, C>(modelClient: ModelOperations<T, C>, id: string, options?: useAblo.Options<T>): useAblo.Result<T>;
11
+ export declare function useAblo<R extends SchemaRecord = DefaultModels, T = Record<string, unknown>, C = unknown>(select: ModelClientSelector<R, T, C>, id: string, options?: useAblo.Options<T>): useAblo.Result<T>;
12
+ /** Type annotations belong to the operation; most callers rely on inference. */
13
+ export declare namespace useAblo {
14
+ interface Bound<S extends SchemaRecord> {
15
+ <T>(select: AbloSelector<S, T>): T | undefined;
16
+ <T, C>(model: ModelOperations<T, C> | ModelClientSelector<S, T, C>, id: string, options?: Options<T>): Result<T>;
17
+ }
18
+ interface Options<T> {
19
+ /**
20
+ * An initial row, usually from a server component or a route loader. The hook
21
+ * uses it for hydration and until a local row has been observed. A later
22
+ * local removal returns undefined instead of restoring this seed.
23
+ */
24
+ readonly initial?: T;
25
+ }
26
+ interface Result<T> {
27
+ /** The local row or its initial seed. Undefined is a local cache miss, not proof of server absence. */
28
+ readonly data: T | undefined;
29
+ /** The work claims currently held on this row by any participant. */
30
+ readonly claims: readonly ModelClaim[];
31
+ /** True while another participant holds a claim — handy for disabling UI. */
32
+ readonly claimed: boolean;
33
+ }
34
+ }
@@ -1,25 +1,10 @@
1
1
  'use client';
2
- import { useContext, useEffect, useState } from 'react';
3
- import { AbloInternalContext } from './internalContext.js';
2
+ import { useCallback, useEffect, useMemo } from 'react';
3
+ import { useAbloClient } from './useAbloClient.js';
4
4
  import { getModelClientMeta, } from '../local/client/createModelOperations.js';
5
- import { Model } from '../local/Model.js';
6
- import { useReactive } from '../useReactive.js';
5
+ import { useReactive } from './useReactive.js';
7
6
  const EMPTY_CLAIMS = Object.freeze([]);
8
- /**
9
- * Restore the caller's schema generics on the context-held engine. React
10
- * context erases generics (see `AbloInternalContextValue.engine`), so this is
11
- * the one deliberate rebind point: the runtime value is the fully typed
12
- * client, and `R` is the compile-time view the calling hook declared.
13
- */
14
- function rebindEngine(engine) {
15
- return engine;
16
- }
17
- /**
18
- * The reactive-read view of a client — the identical runtime object, with
19
- * model reads typed as snapshot rows, because everything a selector returns
20
- * is converted through `snapshotValue` before the hook hands it back. Same
21
- * generic in and out, so this compiles with no schema rebinding.
22
- */
7
+ // Selector results are detached snapshots with no model methods or relations.
23
8
  function reactiveReads(engine) {
24
9
  return engine;
25
10
  }
@@ -27,50 +12,15 @@ function readModelResult(engine, modelClient, id, initial) {
27
12
  if (!modelClient || id === undefined) {
28
13
  return { data: initial, claims: EMPTY_CLAIMS, claimed: false };
29
14
  }
30
- const data = snapshotValue(modelClient.local.get(id) ?? initial);
15
+ const data = modelClient.local.get(id) ?? initial;
31
16
  const meta = getModelClientMeta(modelClient);
32
17
  const claims = meta && engine
33
18
  ? engine.claims.list({ model: meta.key, id })
34
19
  : EMPTY_CLAIMS;
35
20
  return { data, claims, claimed: claims.length > 0 };
36
21
  }
37
- /**
38
- * Projects a reactive read into the value that `useReactive` caches and
39
- * returns.
40
- *
41
- * For a `Model`, this reads the row's fields through `toReactiveSnapshot`
42
- * rather than returning the instance itself. Property access is what subscribes
43
- * the reaction to those fields, so the read has to happen inside this tracked
44
- * function; returning the live instance without reading its fields would leave
45
- * the component blind to later edits. The fresh object it produces also lets
46
- * `useReactive`'s equality check detect an in-place update.
47
- */
48
- function snapshotValue(value) {
49
- if (value instanceof Model) {
50
- return value.toReactiveSnapshot();
51
- }
52
- if (Array.isArray(value)) {
53
- return value.map((item) => snapshotValue(item));
54
- }
55
- return value;
56
- }
57
22
  export function useAblo(modelOrSelect, id, options) {
58
- return useAbloImpl(null, modelOrSelect, id, options);
59
- }
60
- /**
61
- * @internal The one implementation behind `useAblo` and the bound hooks a
62
- * `createAbloReact` binding returns — written once so the reactive read path
63
- * cannot fork between the global hook and a factory's.
64
- *
65
- * `boundClient` is a binding's own context value — typed `Ablo<S>` at the
66
- * factory, so that path never rebinds and never casts. `null` means "no
67
- * binding provider in this tree": the global hook always passes it, and a
68
- * binding hook mounted under a legacy provider falls through to the erased
69
- * internal context, which is what keeps both mounts working while the last
70
- * legacy mount migrates.
71
- */
72
- export function useAbloImpl(boundClient, modelOrSelect, id, options) {
73
- const engine = useAbloClientImpl(boundClient);
23
+ const engine = useAbloClient();
74
24
  const initial = options?.initial;
75
25
  const isSelectorOnly = typeof modelOrSelect === 'function' && id === undefined;
76
26
  const modelClient = typeof modelOrSelect === 'function' && id !== undefined
@@ -80,43 +30,36 @@ export function useAbloImpl(boundClient, modelOrSelect, id, options) {
80
30
  : typeof modelOrSelect === 'function'
81
31
  ? undefined
82
32
  : modelOrSelect;
83
- // Claims arrive through an event emitter (engine.claims), not through MobX, so
84
- // the useReactive reactions below cannot track them; we bridge changes with a
85
- // setState bump instead. Subscribe the model-row form (`id !== undefined`)
86
- // to claims. Selector-only reads track MobX model data; callers displaying
87
- // ownership use the row form's `claims` / `claimed` result.
88
- const [claimVersion, setClaimVersion] = useState(0);
89
- useEffect(() => {
90
- if (!engine || id === undefined)
91
- return;
92
- return engine.claims.onChange(() => { setClaimVersion((version) => version + 1); });
93
- }, [engine, id]);
94
- const selected = useReactive(() => {
95
- if (!engine || !isSelectorOnly || typeof modelOrSelect !== 'function') {
96
- return undefined;
33
+ // The initial row is a seed for this client/model/id, not a permanent
34
+ // fallback: once local data has been committed to the UI, its removal must
35
+ // not resurrect the seed. Only committed effects change this marker.
36
+ // These dependencies define when the seed belongs to a different row.
37
+ // eslint-disable-next-line react-hooks/exhaustive-deps
38
+ const seed = useMemo(() => ({ received: false }), [engine, modelClient, id]);
39
+ const subscribe = useCallback((notify) => {
40
+ if (!engine)
41
+ return () => undefined;
42
+ return engine.claims.onChange(notify);
43
+ }, [engine]);
44
+ const value = useReactive(() => {
45
+ if (isSelectorOnly && typeof modelOrSelect === 'function') {
46
+ return engine ? modelOrSelect(reactiveReads(engine)) : undefined;
97
47
  }
98
- // The selector runs against the real engine — reads inside it return the
99
- // pool's model instances. `snapshotValue` then converts the RESULT to
100
- // plain snapshot rows, which is what the selector's `AbloReads`
101
- // parameter type already promised.
102
- return snapshotValue(modelOrSelect(reactiveReads(engine)));
103
- });
104
- const modelResult = useReactive(() => {
105
- void claimVersion;
106
- return readModelResult(engine, modelClient, id, initial);
48
+ if (modelOrSelect) {
49
+ return readModelResult(engine, modelClient, id, seed.received ? undefined : initial);
50
+ }
51
+ return undefined;
52
+ }, {
53
+ subscribe,
54
+ // The same seed produces the server HTML and the first hydration render,
55
+ // even if the browser already has a newer row or claim in its local cache.
56
+ ...(id !== undefined && initial !== undefined ? {
57
+ serverSnapshot: () => ({ data: initial, claims: EMPTY_CLAIMS, claimed: false }),
58
+ } : {}),
107
59
  });
108
- if (isSelectorOnly)
109
- return selected;
110
- if (modelOrSelect)
111
- return modelResult;
112
- return engine;
113
- }
114
- /** @internal Resolve the bound or legacy provider client through one rebind seam. */
115
- export function useAbloClientImpl(boundClient) {
116
- const ctx = useContext(AbloInternalContext);
117
- // The bound client wins — it is already `Ablo<R>`, no rebinding. The
118
- // fallback is the ONE remaining schema rebind in the SDK; it retires with
119
- // the last legacy provider mount (docs/plans/typed-react-binding.md).
120
- const engine = boundClient ?? (ctx?.engine ? rebindEngine(ctx.engine) : null);
121
- return engine;
60
+ useEffect(() => {
61
+ if (id !== undefined && modelClient?.local.get(id) !== undefined)
62
+ seed.received = true;
63
+ }, [seed, modelClient, id, value]);
64
+ return value;
122
65
  }
@@ -0,0 +1,5 @@
1
+ import type { AbloClient } from '../client.js';
2
+ import type { SchemaRecord } from '@abloatai/transaction/schema/schema';
3
+ import type { ResolveModels } from '@abloatai/transaction/types/global';
4
+ /** Writable client for event handlers. Available before ready(); null without a provider. */
5
+ export declare function useAbloClient<S extends SchemaRecord = ResolveModels>(): AbloClient<S> | null;
@@ -0,0 +1,9 @@
1
+ 'use client';
2
+ import { useContext } from 'react';
3
+ import { AbloInternalContext } from './internalContext.js';
4
+ /** Writable client for event handlers. Available before ready(); null without a provider. */
5
+ export function useAbloClient() {
6
+ const client = useContext(AbloInternalContext)?.engine;
7
+ // React context erases the schema; the application binding restores it.
8
+ return client ? client : null;
9
+ }
@@ -0,0 +1,6 @@
1
+ import type { AbloClient } from '../client.js';
2
+ import type { SchemaRecord } from '@abloatai/transaction/schema/schema';
3
+ /** Subscribe for this component's lifetime using the latest committed listener.
4
+ * Replacing the provider client moves the subscription; unmount removes it.
5
+ */
6
+ export declare function useMutationFailure(listener: Parameters<AbloClient<SchemaRecord>['onMutationFailure']>[0]): void;
@@ -0,0 +1,11 @@
1
+ 'use client';
2
+ import { useEffect, useEffectEvent } from 'react';
3
+ import { useAbloClient } from './useAbloClient.js';
4
+ /** Subscribe for this component's lifetime using the latest committed listener.
5
+ * Replacing the provider client moves the subscription; unmount removes it.
6
+ */
7
+ export function useMutationFailure(listener) {
8
+ const client = useAbloClient();
9
+ const onFailure = useEffectEvent(listener);
10
+ useEffect(() => client?.onMutationFailure(onFailure), [client]);
11
+ }