@octanejs/xstate-store 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,49 @@
1
+ Octane XState Store binding
2
+ ===========================
3
+
4
+ MIT License
5
+
6
+ Copyright (c) 2026 Dominic Gannaway
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
25
+
26
+ @xstate/store-react-derived implementation and types
27
+ ====================================================
28
+
29
+ MIT License
30
+
31
+ Copyright (c) 2015 David Khourshid
32
+
33
+ Permission is hereby granted, free of charge, to any person obtaining a copy
34
+ of this software and associated documentation files (the "Software"), to deal
35
+ in the Software without restriction, including without limitation the rights
36
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
37
+ copies of the Software, and to permit persons to whom the Software is
38
+ furnished to do so, subject to the following conditions:
39
+
40
+ The above copyright notice and this permission notice shall be included in all
41
+ copies or substantial portions of the Software.
42
+
43
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
44
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
45
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
46
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
47
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
48
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @octanejs/xstate-store
2
+
3
+ XState Store for Octane — a port of [`@xstate/store-react@2.0.0`](https://github.com/statelyai/xstate/tree/main/packages/xstate-store-react).
4
+
5
+ The `@xstate/store` core is framework-neutral, so it is reused **unmodified** and
6
+ re-exported wholesale from this entry point, exactly as upstream does. Only the
7
+ React binding is ported. See [`UPSTREAM.md`](./UPSTREAM.md) for the pin, the
8
+ export crosswalk, and the disposition of every upstream test.
9
+
10
+ ```bash
11
+ pnpm add @octanejs/xstate-store
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```tsx
17
+ import { createStore, useSelector } from '@octanejs/xstate-store';
18
+
19
+ const store = createStore({
20
+ context: { count: 0 },
21
+ on: {
22
+ inc: (context, event: { by: number }) => ({
23
+ ...context,
24
+ count: context.count + event.by,
25
+ }),
26
+ },
27
+ });
28
+
29
+ export function Counter() @{
30
+ const count = useSelector(store, (s) => s.context.count);
31
+
32
+ <button onClick={() => store.trigger.inc({ by: 1 })}>{count as string}</button>
33
+ }
34
+ ```
35
+
36
+ `createStoreHook` bundles the store and its selector into one hook:
37
+
38
+ ```tsx
39
+ import { createStoreHook } from '@octanejs/xstate-store';
40
+
41
+ const useCountStore = createStoreHook({
42
+ context: { count: 0 },
43
+ on: { inc: (context, event: { by: number }) => ({ ...context, count: context.count + event.by }) },
44
+ });
45
+
46
+ export function Counter() @{
47
+ const [count, store] = useCountStore((s) => s.context.count);
48
+
49
+ <button onClick={() => store.trigger.inc({ by: 1 })}>{count as string}</button>
50
+ }
51
+ ```
52
+
53
+ ## Exports
54
+
55
+ Everything `@xstate/store@4.2.3` exports (`createStore`, `createStoreConfig`,
56
+ `createStoreLogic`, `createAtom`, `createAtomConfig`, `createAsyncAtom`,
57
+ `createReducerAtom`, `fromStore`, `shallowEqual`, and the full type surface),
58
+ plus the ported hooks `useSelector`, `useStore`, `useAtom`, `useAtomState`, and
59
+ `createStoreHook`.
60
+
61
+ ## Intentional differences from `@xstate/store-react` on React
62
+
63
+ - **Conditional hook calls are legal.** Upstream calls hooks inside `if` branches
64
+ in `useSelector` and `useAtom`. On React that only works because the branch is
65
+ stable for a given call site. Octane keys hooks by compiler-assigned call site
66
+ rather than call order, so the shape is sound here — and if a call site ever
67
+ did flip branches, Octane keeps independent hook cells per branch instead of
68
+ corrupting hook order.
69
+ - **`useSyncExternalStore` skips React's commit-time `getSnapshot` re-read** when
70
+ the rendered value was unchanged, because Octane's synchronous renderer closes
71
+ the concurrent-interleaving window React guards there.
72
+ - **Server snapshots.** `getServerSnapshot` is optional in Octane and falls back
73
+ to `getSnapshot`; React throws when it is missing. Every hook here supplies one.
package/UPSTREAM.md ADDED
@@ -0,0 +1,103 @@
1
+ # Upstream
2
+
3
+ ## Pin and oracle boundary
4
+
5
+ | Field | Value |
6
+ | --- | --- |
7
+ | Repository | https://github.com/statelyai/xstate |
8
+ | Release tag | `@xstate/store-react@2.0.0` |
9
+ | Commit | `ddca0ff8c53dc2e85f9173514cc686308d65bd2c` |
10
+ | Supported upstream range | exactly `@xstate/store-react@2.0.0` |
11
+ | Source root | `packages/xstate-store-react/src` |
12
+ | Test root | `packages/xstate-store-react/src` (upstream colocates its tests with the source) |
13
+ | Store core | `@xstate/store@4.2.3` (a direct dependency, as upstream) |
14
+ | React oracle | `react@19.2.3`, `react-dom@19.2.3`, `@types/react@19.2.17` |
15
+ | License | MIT |
16
+
17
+ The vendored tree under [`upstream/`](./upstream) is byte-exact at that commit.
18
+ `@xstate/store-react` ships no `LICENSE` of its own, so
19
+ [`upstream/LICENSE`](./upstream/LICENSE) is the sibling `@xstate/store` MIT
20
+ notice from the same commit. The tree is prettier-ignored and excluded from the
21
+ published `files`. [`upstream/SHA256SUMS`](./upstream/SHA256SUMS) pins every
22
+ vendored byte; `pnpm --dir packages/xstate-store upstream:verify` re-hashes the
23
+ tree and fails on any drift.
24
+
25
+ ## Source boundary
26
+
27
+ `@xstate/store` is **not** ported and **not** vendored. It is framework-neutral,
28
+ and upstream's binding re-exports it wholesale (`export * from '@xstate/store'`),
29
+ so it is consumed unmodified from npm as a direct dependency and re-exported the
30
+ same way. Only the React binding module is ported.
31
+
32
+ Upstream has no React-specific runtime dependencies to replace: it builds
33
+ directly on `useCallback`, `useRef`, and `useSyncExternalStore`, all of which are
34
+ first-class Octane hooks.
35
+
36
+ ## Module crosswalk
37
+
38
+ | Upstream module | Octane module | Disposition |
39
+ | --- | --- | --- |
40
+ | `src/index.ts` | [`src/index.ts`](./src/index.ts) | Ported |
41
+ | — | [`src/internal.ts`](./src/internal.ts) | Octane-only: `splitSlot`/`subSlot` hook-slot plumbing |
42
+
43
+ ## Export crosswalk
44
+
45
+ | Upstream export | Octane disposition | Evidence |
46
+ | --- | --- | --- |
47
+ | `export * from '@xstate/store'` | Re-exported unchanged | Types: `xstate-store-adapted-types`. Runtime: `xstate-store-adapted-upstream` |
48
+ | `useSelector` (both overloads) | Ported | Types: `xstate-store-adapted-types`. Runtime: `xstate-store-adapted-upstream` |
49
+ | `useStore` | Ported | Types: `xstate-store-adapted-types`. Runtime: `xstate-store-adapted-upstream` |
50
+ | `useAtom` (all three overloads) | Ported | Types: `xstate-store-adapted-types`. Runtime: `xstate-store-adapted-upstream` |
51
+ | `useAtomState` | Ported | Types: `xstate-store-adapted-types`. Runtime: `xstate-store-adapted-upstream` |
52
+ | `createStoreHook` | Ported | Types: `xstate-store-adapted-types`. Runtime: `xstate-store-adapted-upstream` |
53
+
54
+ Module-private helpers (`defaultCompare`, `identity`, `useSelectorWithCompare`,
55
+ `createStoreFromDefinition`, `isAtom`) are ported alongside their callers and are
56
+ not part of the published surface, matching upstream.
57
+
58
+ ## React-parity lanes
59
+
60
+ | Lane | Status |
61
+ | --- | --- |
62
+ | `xstate-store-pristine` | **Landed.** Runs the byte-exact `src/**/*.test.{ts,tsx}` suite against `@xstate/store-react@2.0.0` and `react@19.2.3` after re-hashing every vendored byte, in upstream's own `happy-dom` environment with its `development`/`browser` resolve conditions. 19 of 19 cases pass; the passing identities are pinned in [`audit/pristine-runtime.json`](./audit/pristine-runtime.json). |
63
+ | `xstate-store-adapted-upstream` | **Landed.** Runs the one-for-one adapted `src/index.test.tsx` suite on Octane: all 14 cases, names and assertions preserved, so the identity set equals the pristine lane's. Inventory: [`audit/adapted-runtime.json`](./audit/adapted-runtime.json); permitted transformations are listed in the lane's `notes` in [`audit/react-parity.json`](./audit/react-parity.json). |
64
+ | `xstate-store-pristine-types` | **Landed.** Compiles the vendored `src/types.test.tsx` together with the vendored `src/index.ts` using plain `tsc`. Config: [`audit/upstream-typetests/tsconfig.pristine.json`](./audit/upstream-typetests/tsconfig.pristine.json). |
65
+ | `xstate-store-adapted-types` | **Landed.** Compiles [`typetests/types.test-d.tsx`](./typetests/types.test-d.tsx) with `tsrx-tsc`. The file is byte-identical to the vendored upstream suite below its header apart from one line (the import root), and that is machine-checked rather than asserted: `react-parity:check` strips the header, undoes the transformation ledger in [`audit/type-parity.json`](./audit/type-parity.json), and requires the result to equal the vendored bytes. All thirteen `@ts-expect-error` markers are preserved, and dropping one fails the audit. |
66
+ | `xstate-store-runtime-differential` | **Out of scope for this port.** The four schema-required lanes above are landed and the adapted suite already reruns every upstream case on Octane. A differential lane would add a second oracle for the same 14 scenarios; `@octanejs/xstate` carries one because `createActorContext` has provider and selector interactions with no upstream runtime coverage, which this package's surface does not. |
67
+
68
+ ## Type suite evidence
69
+
70
+ Both type suites are inventoried at file and assertion-group granularity in
71
+ [`audit/pristine-types.json`](./audit/pristine-types.json) and
72
+ [`audit/adapted-types.json`](./audit/adapted-types.json): 19 assertion groups
73
+ each, of which 13 are `@ts-expect-error` negative assertions. The inventories
74
+ are regenerated with `node scripts/react-parity/xstate-types-inventory.mjs` and
75
+ a stale one fails the audit.
76
+
77
+ ## Runtime suite disposition
78
+
79
+ Both columns are evidence today: the pristine lane runs the vendored suite
80
+ unchanged against React, and the adapted lane runs the same cases on Octane.
81
+
82
+ | Upstream artifact | Cases | Pristine | Adapted |
83
+ | --- | --- | --- | --- |
84
+ | `src/index.test.tsx` | 14 | Runs unchanged, 14 passing | One-for-one |
85
+ | `src/types.test.tsx` | 5 | Runs unchanged, 5 passing | Pristine and adapted type lanes |
86
+ | `vitest.config.mts` | — | Support only; [`tests/upstream-vitest.config.ts`](./tests/upstream-vitest.config.ts) reuses its environment, `globals`, and resolve conditions. | Not applicable. |
87
+ | `tsconfig.json`, `package.json`, `README.md` | — | Support only | Not applicable |
88
+
89
+ Unlike `@xstate/react`, this suite is not parametrized over React StrictMode, so
90
+ every case has a single applicable mode.
91
+
92
+ ## Intentional divergences
93
+
94
+ Only the first row is attributable to this binding, so it is the only entry in
95
+ [`audit/react-parity.json`](./audit/react-parity.json). The other two are Octane
96
+ runtime behaviors this package cannot reach, recorded here for completeness with
97
+ a pointer to where they are pinned.
98
+
99
+ | Divergence | Consumer impact | Pinned by |
100
+ | --- | --- | --- |
101
+ | Upstream calls hooks inside `if` branches in `useSelector` and `useAtom`. React tolerates this only because the branch is stable per call site; Octane keys hooks by call site, so it is simply legal here. | If a call site does flip between the selector and no-selector branch, React corrupts hook order while Octane keeps independent hook cells per branch and unsubscribes the abandoned one. Octane is strictly better-behaved; no supported usage reaches it. | [`tests/conformance/binding.test.ts`](./tests/conformance/binding.test.ts) (`xstate-store-call-site-hook-slots`) |
102
+ | `useSyncExternalStore` skips React's commit-time `getSnapshot` re-read when the rendered value was unchanged | Only observable for a store that mutates without notifying between render and commit, which no store reachable through these hooks does | Octane runtime behavior, not this binding's. Pinned in [`@octanejs/xstate`](../xstate/tests/conformance/divergences.test.ts) rather than duplicated here. |
103
+ | Server `getServerSnapshot` is optional and falls back to `getSnapshot` where React throws | Unreachable here: every `useSyncExternalStore` call in `src/index.ts` passes an explicit third argument, so the fallback is never taken. | Octane runtime behavior, not this binding's. Pinned in [`@octanejs/xstate`](../xstate/tests/ssr/server.test.ts) rather than duplicated here. |
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@octanejs/xstate-store",
3
+ "version": "0.0.1",
4
+ "description": "XState Store for Octane — re-exports the framework-agnostic @xstate/store core unchanged and ports the @xstate/store-react 2.0.0 binding onto Octane hooks.",
5
+ "author": {
6
+ "name": "Dominic Gannaway",
7
+ "email": "dg@domgan.com"
8
+ },
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/octanejs/octane.git",
15
+ "directory": "packages/xstate-store"
16
+ },
17
+ "license": "MIT",
18
+ "type": "module",
19
+ "sideEffects": false,
20
+ "engines": {
21
+ "node": ">=22.22.2"
22
+ },
23
+ "octane": {
24
+ "hookSlots": {
25
+ "manual": [
26
+ "src"
27
+ ]
28
+ }
29
+ },
30
+ "main": "src/index.ts",
31
+ "module": "src/index.ts",
32
+ "types": "src/index.ts",
33
+ "exports": {
34
+ ".": "./src/index.ts",
35
+ "./package.json": "./package.json"
36
+ },
37
+ "files": [
38
+ "src",
39
+ "README.md",
40
+ "UPSTREAM.md",
41
+ "LICENSE"
42
+ ],
43
+ "dependencies": {
44
+ "@xstate/store": "4.2.3"
45
+ },
46
+ "peerDependencies": {
47
+ "octane": "0.1.43"
48
+ },
49
+ "devDependencies": {
50
+ "@testing-library/jest-dom": "^6.9.1",
51
+ "@testing-library/react": "16.3.1",
52
+ "@tsrx/react": "^0.2.58",
53
+ "@types/react": "19.2.17",
54
+ "@types/react-dom": "19.2.3",
55
+ "@xstate/store-react": "2.0.0",
56
+ "esbuild": "^0.28.1",
57
+ "happy-dom": "^20.11.0",
58
+ "react": "19.2.3",
59
+ "react-dom": "19.2.3",
60
+ "vitest": "^4.1.10",
61
+ "zod": "^4.4.3",
62
+ "@octanejs/testing-library": "0.1.40",
63
+ "octane": "0.1.43"
64
+ },
65
+ "scripts": {
66
+ "test": "vitest run",
67
+ "test:upstream": "node scripts/run-pristine-upstream.mjs",
68
+ "typecheck": "tsrx-tsc --noEmit -p tsconfig.json && tsrx-tsc --noEmit -p typetests/tsconfig.adapted.json",
69
+ "typecheck:pristine": "tsc --noEmit -p audit/upstream-typetests/tsconfig.pristine.json",
70
+ "upstream:verify": "node scripts/verify-upstream.mjs"
71
+ }
72
+ }
package/src/index.ts ADDED
@@ -0,0 +1,376 @@
1
+ // Ported from @xstate/store-react@2.0.0 src/index.ts
2
+ // (statelyai/xstate @ ddca0ff8c53dc2e85f9173514cc686308d65bd2c).
3
+ //
4
+ // The framework-agnostic `@xstate/store` core is re-exported unchanged, exactly
5
+ // as upstream does, so `createStore`, `createAtom`, `fromStore`, `shallowEqual`
6
+ // and every type reach consumers from this entry point.
7
+ //
8
+ // Slot plumbing: this package declares `octane.hookSlots.manual` for `src`, so
9
+ // every hook below takes the caller's compiler-assigned slot as a trailing
10
+ // argument (split with `splitSlot`, since the user arguments are optional) and
11
+ // derives a distinct sub-slot per composed hook.
12
+ //
13
+ // Upstream calls hooks inside `if` branches in `useSelector` and `useAtom`.
14
+ // That is a rules-of-hooks violation React tolerates only because the branch is
15
+ // stable for a given call site. Octane keys hooks by call site rather than call
16
+ // order, so the shape is kept verbatim and is simply legal here; see UPSTREAM.md
17
+ // for the one behavioral consequence when a branch does flip.
18
+ // OCTANE DIVERGENCE[xstate-store-call-site-hook-slots][ordinary:xstate-store-hook-slot-per-call-site]
19
+ export * from '@xstate/store';
20
+
21
+ import { useCallback, useRef, useSyncExternalStore } from 'octane';
22
+ import {
23
+ type AnyStoreConfig,
24
+ type AnyStoreLogicCreator,
25
+ type StoreFromStoreLogicCreator,
26
+ type StoreFromStoreConfig,
27
+ type InputFromStoreLogicCreator,
28
+ type Readable,
29
+ type AnyAtom,
30
+ type AnyAtomConfig,
31
+ type AtomConfig,
32
+ type BaseAtom,
33
+ type InputFromAtomConfig,
34
+ type ValueFromAtomConfig,
35
+ type StoreSnapshot,
36
+ type ContextFromStoreConfig,
37
+ createStore,
38
+ } from '@xstate/store';
39
+ import { splitSlot, subSlot } from './internal.ts';
40
+
41
+ function defaultCompare<T>(a: T | undefined, b: T) {
42
+ return a === b;
43
+ }
44
+
45
+ function identity<T>(snapshot: T): T {
46
+ return snapshot;
47
+ }
48
+
49
+ function useSelectorWithCompare<TSnapshot, T>(
50
+ selector: (snapshot: TSnapshot) => T,
51
+ compare: (a: T | undefined, b: T) => boolean,
52
+ slot: symbol | undefined,
53
+ ): (snapshot: TSnapshot) => T {
54
+ const previous = useRef<T | undefined>(undefined, slot);
55
+
56
+ return (snapshot) => {
57
+ const next = selector(snapshot);
58
+ return previous.current !== undefined && compare(previous.current, next)
59
+ ? previous.current
60
+ : (previous.current = next);
61
+ };
62
+ }
63
+
64
+ function createStoreFromDefinition<TDefinition extends AnyStoreConfig>(
65
+ definition: TDefinition,
66
+ ): StoreFromStoreConfig<TDefinition>;
67
+ function createStoreFromDefinition(definition: AnyStoreConfig) {
68
+ return createStore(definition);
69
+ }
70
+
71
+ type StoreDefinition = AnyStoreConfig | AnyStoreLogicCreator;
72
+
73
+ type StoreFromStoreDefinition<TDefinition extends StoreDefinition> =
74
+ TDefinition extends AnyStoreLogicCreator
75
+ ? StoreFromStoreLogicCreator<TDefinition>
76
+ : TDefinition extends AnyStoreConfig
77
+ ? StoreFromStoreConfig<TDefinition>
78
+ : never;
79
+
80
+ type UseStoreArgs<TDefinition extends StoreDefinition> = TDefinition extends AnyStoreLogicCreator
81
+ ? undefined extends InputFromStoreLogicCreator<TDefinition>
82
+ ? [logic: TDefinition, input?: InputFromStoreLogicCreator<TDefinition>]
83
+ : [logic: TDefinition, input: InputFromStoreLogicCreator<TDefinition>]
84
+ : [definition: TDefinition];
85
+
86
+ type AtomDefinition = BaseAtom<any> | AnyAtomConfig;
87
+
88
+ type AtomStateFromDefinition<TDefinition extends AtomDefinition> = TDefinition extends AnyAtomConfig
89
+ ? readonly [value: ValueFromAtomConfig<TDefinition>, atom: ReturnType<TDefinition['createAtom']>]
90
+ : TDefinition extends BaseAtom<infer TValue>
91
+ ? readonly [value: TValue, atom: TDefinition]
92
+ : never;
93
+
94
+ type UseAtomStateArgs<TDefinition extends AtomDefinition> = TDefinition extends AnyAtomConfig
95
+ ? undefined extends InputFromAtomConfig<TDefinition>
96
+ ? [config: TDefinition, input?: InputFromAtomConfig<TDefinition>]
97
+ : [config: TDefinition, input: InputFromAtomConfig<TDefinition>]
98
+ : [atom: TDefinition];
99
+
100
+ type AtomConfigInput<TInput> = undefined extends TInput ? [input?: TInput] : [input: TInput];
101
+
102
+ function isAtom(value: unknown): value is AnyAtom {
103
+ return (
104
+ typeof value === 'object' &&
105
+ value !== null &&
106
+ typeof (value as any).get === 'function' &&
107
+ typeof (value as any).subscribe === 'function'
108
+ );
109
+ }
110
+
111
+ /**
112
+ * An Octane hook that subscribes to the `store` and selects a value from the
113
+ * store's snapshot via a selector function, with an optional compare function.
114
+ *
115
+ * @example
116
+ *
117
+ * ```ts
118
+ * function Component() @{
119
+ * const count = useSelector(store, (s) => s.count);
120
+ *
121
+ * <div>{count as string}</div>
122
+ * }
123
+ * ```
124
+ *
125
+ * @param store The store, created from `createStore(…)`
126
+ * @param selector A function which takes in the `snapshot` and returns a
127
+ * selected value
128
+ * @param compare An optional function which compares the selected value to the
129
+ * previous value
130
+ * @returns The selected value
131
+ */
132
+ export function useSelector<TSnapshot, T>(
133
+ store: Readable<TSnapshot>,
134
+ selector: (snapshot: TSnapshot) => T,
135
+ compare?: (a: T | undefined, b: T) => boolean,
136
+ slot?: symbol,
137
+ ): T;
138
+ /**
139
+ * An Octane hook that subscribes to the `store` and selects a value from the
140
+ * store's snapshot via an optional selector function (identity by default),
141
+ * with an optional compare function.
142
+ *
143
+ * @example
144
+ *
145
+ * ```ts
146
+ * function Component() @{
147
+ * const countSnapshot = useSelector(store);
148
+ *
149
+ * <div>{countSnapshot.context.count as string}</div>
150
+ * }
151
+ * ```
152
+ *
153
+ * @param store The store, created from `createStore(…)`
154
+ * @param selector An optional function which takes in the `snapshot` and
155
+ * returns a selected value
156
+ * @param compare An optional function which compares the selected value to the
157
+ * previous value
158
+ * @returns The selected value
159
+ */
160
+ export function useSelector<TSnapshot>(
161
+ store: Readable<TSnapshot>,
162
+ selector?: undefined,
163
+ compare?: (a: TSnapshot | undefined, b: TSnapshot | undefined) => boolean,
164
+ slot?: symbol,
165
+ ): TSnapshot;
166
+ export function useSelector<TSnapshot, T>(
167
+ store: Readable<TSnapshot>,
168
+ ...rest: [
169
+ selector?: (snapshot: TSnapshot) => T,
170
+ compare?: (a: T | undefined, b: T) => boolean,
171
+ slot?: symbol,
172
+ ]
173
+ ): T | TSnapshot {
174
+ const [userArgs, slot] = splitSlot(rest as unknown[]);
175
+ const selector = userArgs[0] as ((snapshot: TSnapshot) => T) | undefined;
176
+ const compare =
177
+ (userArgs[1] as ((a: T | undefined, b: T) => boolean) | undefined) ?? defaultCompare;
178
+
179
+ const subscribe = useCallback(
180
+ (handleStoreChange: () => void) => store.subscribe(handleStoreChange).unsubscribe,
181
+ [store],
182
+ subSlot(slot, 'selector:subscribe'),
183
+ );
184
+
185
+ if (!selector) {
186
+ const selectorWithCompare = useSelectorWithCompare(
187
+ identity,
188
+ defaultCompare,
189
+ subSlot(slot, 'selector:identity-compare'),
190
+ );
191
+
192
+ return useSyncExternalStore(
193
+ subscribe,
194
+ () => selectorWithCompare(store.get()),
195
+ () => selectorWithCompare(store.get()),
196
+ subSlot(slot, 'selector:identity-store'),
197
+ );
198
+ }
199
+
200
+ const selectorWithCompare = useSelectorWithCompare(
201
+ selector,
202
+ compare,
203
+ subSlot(slot, 'selector:compare'),
204
+ );
205
+
206
+ return useSyncExternalStore(
207
+ subscribe,
208
+ () => selectorWithCompare(store.get()),
209
+ () => selectorWithCompare(store.get()),
210
+ subSlot(slot, 'selector:store'),
211
+ );
212
+ }
213
+
214
+ /**
215
+ * Creates a stable store instance for the lifetime of an Octane component.
216
+ *
217
+ * The public signature is upstream's rest tuple verbatim, with NO trailing
218
+ * `slot` element. Appending one turns the conditional `UseStoreArgs<TDefinition>`
219
+ * into a variadic tuple with a trailing member, and because this hook has no
220
+ * leading parameter to infer `TDefinition` from, TypeScript then falls back to
221
+ * the constraint and every schema inference in upstream's type suite collapses.
222
+ * Authored code never passes a slot — the compiler appends it after the program
223
+ * is typechecked — so the argument only has to exist at runtime, which
224
+ * `splitSlot` recovers below.
225
+ */
226
+ export function useStore<TDefinition extends StoreDefinition>(
227
+ ...[definition, input]: UseStoreArgs<TDefinition>
228
+ ): StoreFromStoreDefinition<TDefinition>;
229
+ export function useStore(...rest: unknown[]): unknown {
230
+ const [userArgs, slot] = splitSlot(rest);
231
+ const definition = userArgs[0] as StoreDefinition;
232
+ const input = userArgs[1];
233
+
234
+ const storeRef = useRef<any>(undefined, subSlot(slot, 'store:instance'));
235
+
236
+ if (!storeRef.current) {
237
+ storeRef.current =
238
+ 'createStore' in definition
239
+ ? (definition as AnyStoreLogicCreator).createStore(input as never)
240
+ : createStoreFromDefinition(definition as AnyStoreConfig);
241
+ }
242
+
243
+ return storeRef.current;
244
+ }
245
+
246
+ /**
247
+ * An Octane hook that subscribes to the `atom` and returns the current value of
248
+ * the atom.
249
+ *
250
+ * @param atom The atom, created from `createAtom(…)`
251
+ * @param selector An optional function which takes in the `snapshot` and
252
+ * returns a selected value
253
+ * @param compare An optional function which compares the selected value to the
254
+ * previous value
255
+ */
256
+ export function useAtom<T>(atom: BaseAtom<T>, slot?: symbol): T;
257
+ export function useAtom<TValue, TInput>(
258
+ config: AtomConfig<TValue, TInput>,
259
+ ...rest: [...AtomConfigInput<TInput>, slot?: symbol]
260
+ ): TValue;
261
+ export function useAtom<T, S>(
262
+ atom: BaseAtom<T>,
263
+ selector: (snapshot: T) => S,
264
+ compare?: (a: S, b: S) => boolean,
265
+ slot?: symbol,
266
+ ): S;
267
+ export function useAtom(
268
+ definition: AnyAtom | AtomConfig<any, any>,
269
+ ...rest: [selectorOrInput?: any, compare?: any, slot?: symbol]
270
+ ) {
271
+ const [userArgs, slot] = splitSlot(rest as unknown[]);
272
+ // Upstream's implementation signature is untyped here (`selectorOrInput?: any`)
273
+ // because the three overloads above give it three different meanings.
274
+ const selectorOrInput = userArgs[0] as any;
275
+ const compare = (userArgs[1] as any) ?? defaultCompare;
276
+
277
+ const atomRef = useRef<any>(undefined, subSlot(slot, 'atom:instance'));
278
+
279
+ if (isAtom(definition)) {
280
+ return useSelector(
281
+ definition,
282
+ selectorOrInput ?? identity,
283
+ compare,
284
+ subSlot(slot, 'atom:existing'),
285
+ );
286
+ }
287
+
288
+ if (!atomRef.current) {
289
+ atomRef.current = definition.createAtom(selectorOrInput);
290
+ }
291
+
292
+ const state = useSelector(atomRef.current, identity, compare, subSlot(slot, 'atom:created'));
293
+
294
+ return state;
295
+ }
296
+
297
+ /**
298
+ * Creates or subscribes to an atom for the lifetime of an Octane component.
299
+ *
300
+ * Pass an existing atom to receive `[value, atom]`, or pass an atom config
301
+ * created with `createAtomConfig(...)` to create a stable local atom.
302
+ */
303
+ export function useAtomState<TDefinition extends AtomDefinition>(
304
+ ...[definition]: UseAtomStateArgs<TDefinition>
305
+ ): AtomStateFromDefinition<TDefinition>;
306
+ // Declared as an overload for the same reason as `useStore` above: appending a
307
+ // trailing `slot` to the conditional rest tuple destroys `TDefinition`
308
+ // inference, and authored code never passes one.
309
+ export function useAtomState(...rest: unknown[]): unknown {
310
+ const [userArgs, slot] = splitSlot(rest);
311
+ const definition = userArgs[0] as AtomDefinition;
312
+ const input = userArgs[1];
313
+
314
+ const atomRef = useRef<any>(undefined, subSlot(slot, 'atom-state:instance'));
315
+
316
+ if (!atomRef.current) {
317
+ atomRef.current = isAtom(definition)
318
+ ? definition
319
+ : (definition as AnyAtomConfig).createAtom(input as never);
320
+ }
321
+
322
+ const value = useAtom(atomRef.current, subSlot(slot, 'atom-state:value'));
323
+
324
+ // The overload above carries the precise tuple type; the implementation
325
+ // signature is deliberately untyped, so it returns the erased shape.
326
+ return [value, atomRef.current];
327
+ }
328
+
329
+ /**
330
+ * Creates a custom hook that returns the selected value and the store from a
331
+ * store configuration object.
332
+ *
333
+ * @param definition The store configuration object
334
+ * @returns A custom hook that returns [selectedValue, store]
335
+ */
336
+ export function createStoreHook<TDefinition extends AnyStoreConfig>(definition: TDefinition) {
337
+ type TStore = StoreFromStoreConfig<TDefinition>;
338
+ type TSnapshot = StoreSnapshot<ContextFromStoreConfig<TDefinition>>;
339
+
340
+ const store = createStoreFromDefinition(definition);
341
+
342
+ function useStoreHook(slot?: symbol): [TSnapshot, TStore];
343
+ function useStoreHook<T>(
344
+ selector: (snapshot: TSnapshot) => T,
345
+ compare?: (a: T | undefined, b: T) => boolean,
346
+ slot?: symbol,
347
+ ): [T, TStore];
348
+ // The implementation signature has to admit a bare trailing slot in the first
349
+ // position, because `useStoreHook()` compiles to `useStoreHook(sym)`.
350
+ function useStoreHook<T>(...rest: any[]): [T | TSnapshot, TStore] {
351
+ const [userArgs, slot] = splitSlot(rest as unknown[]);
352
+ const selector = userArgs[0] as ((snapshot: TSnapshot) => T) | undefined;
353
+ const compare =
354
+ (userArgs[1] as ((a: T | undefined, b: T) => boolean) | undefined) ?? defaultCompare;
355
+
356
+ if (!selector) {
357
+ const snapshot = useSelector(
358
+ store as unknown as Readable<TSnapshot>,
359
+ undefined,
360
+ undefined,
361
+ subSlot(slot, 'store-hook:snapshot'),
362
+ );
363
+ return [snapshot, store];
364
+ }
365
+
366
+ const selectedValue = useSelector(
367
+ store as unknown as Readable<TSnapshot>,
368
+ selector,
369
+ compare,
370
+ subSlot(slot, 'store-hook:selected'),
371
+ );
372
+ return [selectedValue, store];
373
+ }
374
+
375
+ return useStoreHook;
376
+ }
@@ -0,0 +1,38 @@
1
+ // Slot mechanics for the binding's plain-`.ts` hooks. Octane injects a
2
+ // per-call-site Symbol into calls made by compiled components; the binding
3
+ // forwards that symbol and derives a distinct sub-slot for each hook it
4
+ // composes. This package declares `octane.hookSlots.manual` for `src`, so the
5
+ // compiler's plain-`.ts` slotting pass skips these modules and the forwarding
6
+ // below is the only thing that keeps two call sites of the same hook apart.
7
+ const subSlotCache = new Map<symbol, Map<string, symbol>>();
8
+ const bareTagCache = new Map<string, symbol>();
9
+
10
+ export function subSlot(slot: symbol | undefined, tag: string): symbol {
11
+ if (slot === undefined) {
12
+ let bare = bareTagCache.get(tag);
13
+ if (bare === undefined) {
14
+ bare = Symbol.for(`@octanejs/xstate-store:${tag}`);
15
+ bareTagCache.set(tag, bare);
16
+ }
17
+ return bare;
18
+ }
19
+
20
+ let byTag = subSlotCache.get(slot);
21
+ if (byTag === undefined) {
22
+ byTag = new Map();
23
+ subSlotCache.set(slot, byTag);
24
+ }
25
+
26
+ let child = byTag.get(tag);
27
+ if (child === undefined) {
28
+ child = Symbol.for(`${slot.description ?? ''}:${tag}`);
29
+ byTag.set(tag, child);
30
+ }
31
+ return child;
32
+ }
33
+
34
+ export function splitSlot(args: unknown[]): [unknown[], symbol | undefined] {
35
+ const tail = args[args.length - 1];
36
+ const slot = typeof tail === 'symbol' ? tail : undefined;
37
+ return [slot === undefined ? args : args.slice(0, -1), slot];
38
+ }