use-everywhere 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ 'use client';
2
+
1
3
  // src/registry.ts
2
4
  import {
3
5
  createChannel,
@@ -0,0 +1,282 @@
1
+ 'use client';
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/devtools/index.ts
22
+ var devtools_exports = {};
23
+ __export(devtools_exports, {
24
+ Inspector: () => Inspector
25
+ });
26
+ module.exports = __toCommonJS(devtools_exports);
27
+
28
+ // src/devtools/inspector.tsx
29
+ var import_react2 = require("react");
30
+ var import_core2 = require("@use-everywhere/core");
31
+
32
+ // src/registry.ts
33
+ var import_core = require("@use-everywhere/core");
34
+ var stores = /* @__PURE__ */ new Map();
35
+ var presences = /* @__PURE__ */ new Map();
36
+ var storeConfig = /* @__PURE__ */ new Map();
37
+ var scopeOptions = {
38
+ everywhere: {},
39
+ tabs: { accept: (meta) => meta.kind !== "worker" },
40
+ tab: { transport: () => new import_core.NoopTransport() }
41
+ };
42
+ function getSharedStore(name = import_core.DEFAULT_NAME, scope = "everywhere") {
43
+ return getStore(name, scope);
44
+ }
45
+ function getStore(name, scope = "everywhere") {
46
+ const key = `${scope} ${name}`;
47
+ let store = stores.get(key);
48
+ if (!store) {
49
+ store = (0, import_core.createSharedStore)(name, {}, { ...scopeOptions[scope], ...storeConfig.get(key) });
50
+ stores.set(key, store);
51
+ }
52
+ return store;
53
+ }
54
+ function getPresence(name) {
55
+ let presence = presences.get(name);
56
+ if (!presence) {
57
+ presence = (0, import_core.createPresence)(name);
58
+ presences.set(name, presence);
59
+ }
60
+ return presence;
61
+ }
62
+
63
+ // src/use-peers.ts
64
+ var import_react = require("react");
65
+ var NO_PEERS = Object.freeze([]);
66
+ function usePeers(options) {
67
+ const presence = getPresence(options?.name ?? import_core.DEFAULT_NAME);
68
+ return (0, import_react.useSyncExternalStore)(
69
+ (0, import_react.useCallback)((onChange) => presence.subscribe(onChange), [presence]),
70
+ () => presence.getPeers(),
71
+ () => NO_PEERS
72
+ );
73
+ }
74
+
75
+ // src/devtools/styles.ts
76
+ var STYLES = `
77
+ .ue-ins {
78
+ position: fixed;
79
+ z-index: 2147483000;
80
+ font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
81
+ color: #e6edf3;
82
+ background: #0d1117;
83
+ border: 1px solid #30363d;
84
+ border-radius: 8px;
85
+ box-shadow: 0 8px 32px rgb(0 0 0 / 0.4);
86
+ max-width: min(420px, calc(100vw - 24px));
87
+ overflow: hidden;
88
+ }
89
+ .ue-ins--bottom-right { bottom: 12px; right: 12px; }
90
+ .ue-ins--bottom-left { bottom: 12px; left: 12px; }
91
+ .ue-ins--top-right { top: 12px; right: 12px; }
92
+ .ue-ins--top-left { top: 12px; left: 12px; }
93
+
94
+ .ue-ins__bar {
95
+ display: flex;
96
+ align-items: center;
97
+ gap: 8px;
98
+ width: 100%;
99
+ padding: 7px 10px;
100
+ background: #161b22;
101
+ border: 0;
102
+ color: inherit;
103
+ font: inherit;
104
+ cursor: pointer;
105
+ text-align: left;
106
+ }
107
+ .ue-ins__dot { width: 7px; height: 7px; border-radius: 50%; background: #3fb950; flex: none; }
108
+ .ue-ins__title { font-weight: 600; }
109
+ .ue-ins__muted { color: #8b949e; }
110
+ .ue-ins__crown { margin-left: auto; color: #d29922; }
111
+
112
+ .ue-ins__body { max-height: 60vh; overflow-y: auto; }
113
+ .ue-ins__section { border-top: 1px solid #21262d; padding: 8px 10px; }
114
+ .ue-ins__h {
115
+ color: #8b949e;
116
+ text-transform: uppercase;
117
+ letter-spacing: 0.06em;
118
+ font-size: 10px;
119
+ margin-bottom: 5px;
120
+ }
121
+ .ue-ins__row { display: flex; gap: 8px; padding: 1px 0; }
122
+ .ue-ins__k { color: #79c0ff; flex: none; }
123
+ .ue-ins__v { color: #e6edf3; overflow-wrap: anywhere; }
124
+ .ue-ins__ver { color: #6e7681; margin-left: auto; flex: none; }
125
+ .ue-ins__empty { color: #6e7681; }
126
+
127
+ .ue-ins__log { display: flex; flex-direction: column-reverse; max-height: 190px; overflow-y: auto; }
128
+ .ue-ins__wire { display: flex; gap: 7px; padding: 1px 0; white-space: nowrap; }
129
+ .ue-ins__dir { flex: none; width: 9px; }
130
+ .ue-ins__dir--out { color: #d29922; }
131
+ .ue-ins__dir--in { color: #3fb950; }
132
+ .ue-ins__scope { color: #e6edf3; }
133
+ .ue-ins__from { color: #6e7681; margin-left: auto; }
134
+ `;
135
+
136
+ // src/devtools/inspector.tsx
137
+ var import_jsx_runtime = require("react/jsx-runtime");
138
+ var short = (id) => id.slice(0, 6);
139
+ function wireLabel(wire) {
140
+ return `${wire.scope}/${wire.type}`;
141
+ }
142
+ function Inspector({
143
+ name = import_core2.DEFAULT_NAME,
144
+ position = "bottom-right",
145
+ limit = 50,
146
+ defaultOpen = false,
147
+ leaseMs = 3e3
148
+ } = {}) {
149
+ const [open, setOpen] = (0, import_react2.useState)(defaultOpen);
150
+ const [wires, setWires] = (0, import_react2.useState)([]);
151
+ const [crown, setCrown] = (0, import_react2.useState)(null);
152
+ const nextId = (0, import_react2.useRef)(0);
153
+ const crownAt = (0, import_react2.useRef)(0);
154
+ const peers = usePeers({ name });
155
+ const store = getSharedStore(name);
156
+ const subscribe = (0, import_react2.useCallback)((onChange) => store.subscribe(onChange), [store]);
157
+ const snapshot = (0, import_react2.useSyncExternalStore)(
158
+ subscribe,
159
+ () => store.getSnapshot(),
160
+ () => store.getSnapshot()
161
+ );
162
+ const versions = (0, import_react2.useSyncExternalStore)(
163
+ subscribe,
164
+ () => store.getVersions(),
165
+ () => store.getVersions()
166
+ );
167
+ (0, import_react2.useEffect)(() => {
168
+ return (0, import_core2.observeBus)(name, (event) => {
169
+ const { wire, direction } = event;
170
+ if (wire.scope === "leader") {
171
+ if (wire.type === "resign") {
172
+ setCrown(null);
173
+ crownAt.current = 0;
174
+ } else if (wire.type === "claim" || wire.type === "heartbeat") {
175
+ setCrown(wire.clientId);
176
+ crownAt.current = Date.now();
177
+ }
178
+ }
179
+ setWires(
180
+ (prev) => [
181
+ ...prev.slice(-(limit - 1)),
182
+ {
183
+ id: nextId.current++,
184
+ direction,
185
+ label: wireLabel(wire),
186
+ from: short(wire.clientId)
187
+ }
188
+ ].slice(-limit)
189
+ );
190
+ });
191
+ }, [name, limit]);
192
+ (0, import_react2.useEffect)(() => {
193
+ const timer = setInterval(
194
+ () => {
195
+ if (crownAt.current && Date.now() - crownAt.current > leaseMs) {
196
+ setCrown(null);
197
+ crownAt.current = 0;
198
+ }
199
+ },
200
+ // Quarter of the lease, so a vacated crown clears well within it. The
201
+ // floor is low enough that a short lease still works rather than being
202
+ // silently rounded up to something coarser than the lease itself.
203
+ Math.max(50, Math.floor(leaseMs / 4))
204
+ );
205
+ return () => clearInterval(timer);
206
+ }, [leaseMs]);
207
+ const selfId = store.clientId;
208
+ const entries = Object.entries(versions);
209
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: `ue-ins ue-ins--${position}`, "data-testid": "ue-inspector", children: [
210
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { children: STYLES }),
211
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
212
+ "button",
213
+ {
214
+ type: "button",
215
+ className: "ue-ins__bar",
216
+ onClick: () => setOpen((v) => !v),
217
+ "aria-expanded": open,
218
+ children: [
219
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__dot" }),
220
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__title", children: "use-everywhere" }),
221
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__muted", children: name }),
222
+ crown ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "ue-ins__crown", "data-testid": "ue-crown", children: [
223
+ "\u2654 ",
224
+ crown === selfId ? "this tab" : short(crown)
225
+ ] }) : null
226
+ ]
227
+ }
228
+ ),
229
+ open ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__body", children: [
230
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__section", children: [
231
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ue-ins__h", children: "This tab" }),
232
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__row", children: [
233
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__k", children: short(selfId) }),
234
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__v", children: crown === selfId ? "leader" : crown ? "follower" : "no leader" })
235
+ ] })
236
+ ] }),
237
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__section", children: [
238
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__h", children: [
239
+ "Peers (",
240
+ peers.length,
241
+ ")"
242
+ ] }),
243
+ peers.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ue-ins__empty", children: "nobody else here" }) : peers.map((peer) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__row", children: [
244
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__k", children: short(peer.id) }),
245
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__v", children: peer.kind })
246
+ ] }, peer.id))
247
+ ] }),
248
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__section", children: [
249
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__h", children: [
250
+ "State (",
251
+ entries.length,
252
+ ")"
253
+ ] }),
254
+ entries.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ue-ins__empty", children: "no keys yet" }) : entries.map(([key, version]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__row", children: [
255
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__k", children: key }),
256
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__v", children: JSON.stringify(snapshot[key]) }),
257
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "ue-ins__ver", children: [
258
+ version[0],
259
+ "\xB7",
260
+ short(version[1])
261
+ ] })
262
+ ] }, key))
263
+ ] }),
264
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__section", children: [
265
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__h", children: [
266
+ "Wires (",
267
+ wires.length,
268
+ ")"
269
+ ] }),
270
+ wires.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ue-ins__empty", children: "nothing yet" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ue-ins__log", children: wires.map((wire) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ue-ins__wire", children: [
271
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: `ue-ins__dir ue-ins__dir--${wire.direction}`, children: wire.direction === "out" ? "\u2192" : "\u2190" }),
272
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__scope", children: wire.label }),
273
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ue-ins__from", children: wire.from })
274
+ ] }, wire.id)) })
275
+ ] })
276
+ ] }) : null
277
+ ] });
278
+ }
279
+ // Annotate the CommonJS export names for ESM import in node:
280
+ 0 && (module.exports = {
281
+ Inspector
282
+ });
@@ -0,0 +1,35 @@
1
+ import * as react from 'react';
2
+
3
+ interface InspectorProps {
4
+ /** Which bus to watch. Defaults to the shared default name. */
5
+ name?: string;
6
+ /** Corner to dock in. Default 'bottom-right'. */
7
+ position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
8
+ /** How many wires to keep in the log. Default 50. */
9
+ limit?: number;
10
+ /** Start expanded. Default false. */
11
+ defaultOpen?: boolean;
12
+ /**
13
+ * How long a leader wire keeps the crown before it is treated as stale.
14
+ * Should match the Leader's leaseMs. Default 3000.
15
+ */
16
+ leaseMs?: number;
17
+ }
18
+
19
+ /**
20
+ * A floating panel showing what this tab is saying and hearing on the bus:
21
+ * peers, the leader, store keys with their version clocks, and a live wire log
22
+ * in both directions.
23
+ *
24
+ * It deliberately does **not** create a Leader. Under dynamic eligibility,
25
+ * mounting one with `eligible: false` would disable candidacy for the whole
26
+ * tab, and mounting a plain one would enrol a tab that never asked to be a
27
+ * candidate — a devtool must not change what it measures. Instead it reads the
28
+ * crown out of the wire log, which it already sees in both directions.
29
+ *
30
+ * Presence is fine to use: the bus heartbeats regardless of whether anything
31
+ * created a Presence, so usePeers observes rather than perturbs.
32
+ */
33
+ declare function Inspector({ name, position, limit, defaultOpen, leaseMs, }?: InspectorProps): react.JSX.Element;
34
+
35
+ export { Inspector, type InspectorProps };
@@ -1,7 +1,8 @@
1
+ 'use client';
1
2
  import {
2
3
  getSharedStore,
3
4
  usePeers
4
- } from "../chunk-Y67BCTU6.js";
5
+ } from "../chunk-PNFJW7QK.js";
5
6
 
6
7
  // src/devtools/inspector.tsx
7
8
  import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
package/dist/index.cjs ADDED
@@ -0,0 +1,287 @@
1
+ 'use client';
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+
22
+ // src/index.ts
23
+ var src_exports = {};
24
+ __export(src_exports, {
25
+ DEFAULT_NAME: () => import_core.DEFAULT_NAME,
26
+ defineChannel: () => defineChannel,
27
+ defineStore: () => defineStore,
28
+ getLeader: () => getLeader,
29
+ getSharedStore: () => getSharedStore,
30
+ useChannel: () => useChannel,
31
+ useClientId: () => useClientId,
32
+ useIsLeader: () => useIsLeader,
33
+ useLeader: () => useLeader,
34
+ useLeaderEffect: () => useLeaderEffect,
35
+ useMessage: () => useMessage,
36
+ useOpenedWindow: () => useOpenedWindow,
37
+ usePeers: () => usePeers,
38
+ useSend: () => useSend,
39
+ useSharedState: () => useSharedState
40
+ });
41
+ module.exports = __toCommonJS(src_exports);
42
+
43
+ // src/use-shared-state.ts
44
+ var import_react = require("react");
45
+
46
+ // src/registry.ts
47
+ var import_core = require("@use-everywhere/core");
48
+ var stores = /* @__PURE__ */ new Map();
49
+ var presences = /* @__PURE__ */ new Map();
50
+ var channels = /* @__PURE__ */ new Map();
51
+ var leaders = /* @__PURE__ */ new Map();
52
+ var storeConfig = /* @__PURE__ */ new Map();
53
+ var scopeOptions = {
54
+ everywhere: {},
55
+ tabs: { accept: (meta) => meta.kind !== "worker" },
56
+ tab: { transport: () => new import_core.NoopTransport() }
57
+ };
58
+ function getSharedStore(name = import_core.DEFAULT_NAME, scope = "everywhere") {
59
+ return getStore(name, scope);
60
+ }
61
+ function configureStore(name, scope, options) {
62
+ const key = `${scope} ${name}`;
63
+ if (stores.has(key)) {
64
+ throw new Error(
65
+ `defineStore('${name}') ran after that store was already created. Move it to module scope \u2014 configuring a live store would silently hand you one without persistence.`
66
+ );
67
+ }
68
+ storeConfig.set(key, options);
69
+ }
70
+ function getStore(name, scope = "everywhere") {
71
+ const key = `${scope} ${name}`;
72
+ let store = stores.get(key);
73
+ if (!store) {
74
+ store = (0, import_core.createSharedStore)(name, {}, { ...scopeOptions[scope], ...storeConfig.get(key) });
75
+ stores.set(key, store);
76
+ }
77
+ return store;
78
+ }
79
+ function getPresence(name) {
80
+ let presence = presences.get(name);
81
+ if (!presence) {
82
+ presence = (0, import_core.createPresence)(name);
83
+ presences.set(name, presence);
84
+ }
85
+ return presence;
86
+ }
87
+ function getLeader(name, options) {
88
+ let leader = leaders.get(name);
89
+ if (!leader) {
90
+ leader = (0, import_core.createLeader)(name, options);
91
+ leaders.set(name, leader);
92
+ }
93
+ return leader;
94
+ }
95
+ function getChannel(name) {
96
+ let channel = channels.get(name);
97
+ if (!channel) {
98
+ channel = (0, import_core.createChannel)(name);
99
+ channels.set(name, channel);
100
+ }
101
+ return channel;
102
+ }
103
+
104
+ // src/use-shared-state.ts
105
+ function useSharedState(key, initial, options) {
106
+ const store = getStore(options?.store ?? import_core.DEFAULT_NAME, options?.scope ?? "everywhere");
107
+ store.registerKey(key, initial);
108
+ const value = (0, import_react.useSyncExternalStore)(
109
+ (0, import_react.useCallback)((onChange) => store.subscribeKey(key, onChange), [store, key]),
110
+ () => store.getSnapshot()[key],
111
+ () => initial
112
+ );
113
+ const setValue = (0, import_react.useCallback)(
114
+ (next) => store.set(key, next),
115
+ [store, key]
116
+ );
117
+ return [value, setValue];
118
+ }
119
+
120
+ // src/use-message.ts
121
+ var import_react2 = require("react");
122
+ function useChannel(name) {
123
+ return getChannel(name);
124
+ }
125
+ function useMessage(channel, type, handler) {
126
+ const handlerRef = (0, import_react2.useRef)(handler);
127
+ (0, import_react2.useEffect)(() => {
128
+ handlerRef.current = handler;
129
+ });
130
+ (0, import_react2.useEffect)(
131
+ () => channel.on(type, (payload, meta) => handlerRef.current(payload, meta)),
132
+ [channel, type]
133
+ );
134
+ }
135
+ function useSend(channel) {
136
+ return channel.post;
137
+ }
138
+
139
+ // src/define-channel.ts
140
+ function defineChannel(name) {
141
+ const useBoundSend = () => useSend(useChannel(name));
142
+ const useBoundMessage = (type, handler) => useMessage(useChannel(name), type, handler);
143
+ return {
144
+ get: () => getChannel(name),
145
+ useSend: useBoundSend,
146
+ useMessage: useBoundMessage
147
+ };
148
+ }
149
+
150
+ // src/define-store.ts
151
+ function defineStore(name, options = {}) {
152
+ const scope = options.scope ?? "everywhere";
153
+ if (options.persist) {
154
+ configureStore(name, scope, {
155
+ persist: {
156
+ adapter: options.persist,
157
+ ...options.persistKeys ? { keys: options.persistKeys } : {},
158
+ ...options.persistDebounceMs === void 0 ? {} : { debounceMs: options.persistDebounceMs }
159
+ }
160
+ });
161
+ }
162
+ return {
163
+ get: () => getStore(name, scope),
164
+ useSharedState: (key, initial) => useSharedState(key, initial, { store: name, scope })
165
+ };
166
+ }
167
+
168
+ // src/use-peers.ts
169
+ var import_react3 = require("react");
170
+ var NO_PEERS = Object.freeze([]);
171
+ function usePeers(options) {
172
+ const presence = getPresence(options?.name ?? import_core.DEFAULT_NAME);
173
+ return (0, import_react3.useSyncExternalStore)(
174
+ (0, import_react3.useCallback)((onChange) => presence.subscribe(onChange), [presence]),
175
+ () => presence.getPeers(),
176
+ () => NO_PEERS
177
+ );
178
+ }
179
+ function useClientId(options) {
180
+ return getPresence(options?.name ?? import_core.DEFAULT_NAME).clientId;
181
+ }
182
+
183
+ // src/use-leader.ts
184
+ var import_react4 = require("react");
185
+ var NO_LEADER = Object.freeze({ leaderId: null, isLeader: false });
186
+ function useLeader(options) {
187
+ const leader = getLeader(options?.name ?? import_core.DEFAULT_NAME, options);
188
+ const eligible = options?.eligible;
189
+ (0, import_react4.useEffect)(() => {
190
+ if (eligible === void 0) return;
191
+ leader.setEligible(eligible);
192
+ }, [leader, eligible]);
193
+ return (0, import_react4.useSyncExternalStore)(
194
+ (0, import_react4.useCallback)((onChange) => leader.subscribe(onChange), [leader]),
195
+ () => leader.getSnapshot(),
196
+ () => NO_LEADER
197
+ );
198
+ }
199
+ function useIsLeader(options) {
200
+ return useLeader(options).isLeader;
201
+ }
202
+ function useLeaderEffect(effect, options) {
203
+ const { isLeader } = useLeader(options);
204
+ const effectRef = (0, import_react4.useRef)(effect);
205
+ (0, import_react4.useEffect)(() => {
206
+ effectRef.current = effect;
207
+ });
208
+ (0, import_react4.useEffect)(() => {
209
+ if (!isLeader) return;
210
+ return effectRef.current();
211
+ }, [isLeader]);
212
+ }
213
+
214
+ // src/use-opened-window.ts
215
+ var import_react5 = require("react");
216
+ var import_core2 = require("@use-everywhere/core");
217
+ function useOpenedWindow(factory) {
218
+ const [status, setStatus] = (0, import_react5.useState)("idle");
219
+ const [result, setResult] = (0, import_react5.useState)(void 0);
220
+ const [error, setError] = (0, import_react5.useState)(void 0);
221
+ const current = (0, import_react5.useRef)(null);
222
+ const factoryRef = (0, import_react5.useRef)(factory);
223
+ factoryRef.current = factory;
224
+ const open = (0, import_react5.useCallback)(() => {
225
+ current.current?.close();
226
+ let opened;
227
+ try {
228
+ opened = factoryRef.current();
229
+ } catch (err) {
230
+ setStatus("error");
231
+ setError(err);
232
+ return;
233
+ }
234
+ current.current = opened;
235
+ setStatus("opening");
236
+ setResult(void 0);
237
+ setError(void 0);
238
+ const fresh = () => current.current === opened;
239
+ opened.ready.then(
240
+ () => {
241
+ if (fresh()) setStatus((s) => s === "opening" ? "connected" : s);
242
+ },
243
+ () => {
244
+ }
245
+ // surfaced through result below
246
+ );
247
+ opened.result.then(
248
+ (value) => {
249
+ if (!fresh()) return;
250
+ setResult(value);
251
+ setStatus("done");
252
+ },
253
+ (err) => {
254
+ if (!fresh()) return;
255
+ setError(err);
256
+ setStatus(err instanceof import_core2.WindowClosedError ? "closed-early" : "error");
257
+ }
258
+ );
259
+ }, []);
260
+ const post = (0, import_react5.useCallback)((type, payload) => {
261
+ current.current?.post(type, payload);
262
+ }, []);
263
+ const close = (0, import_react5.useCallback)(() => current.current?.close(), []);
264
+ return { open, status, result, error, post, close };
265
+ }
266
+
267
+ // src/index.ts
268
+ __reExport(src_exports, require("@use-everywhere/core"), module.exports);
269
+ // Annotate the CommonJS export names for ESM import in node:
270
+ 0 && (module.exports = {
271
+ DEFAULT_NAME,
272
+ defineChannel,
273
+ defineStore,
274
+ getLeader,
275
+ getSharedStore,
276
+ useChannel,
277
+ useClientId,
278
+ useIsLeader,
279
+ useLeader,
280
+ useLeaderEffect,
281
+ useMessage,
282
+ useOpenedWindow,
283
+ usePeers,
284
+ useSend,
285
+ useSharedState,
286
+ ...require("@use-everywhere/core")
287
+ });
@@ -0,0 +1,152 @@
1
+ import { SharedStore, LeaderOptions, Leader, MessageMap, Channel, MessageMeta, PersistAdapter, Peer, LeaderSnapshot, OpenedWindow } from '@use-everywhere/core';
2
+ export * from '@use-everywhere/core';
3
+ export { DEFAULT_NAME } from '@use-everywhere/core';
4
+
5
+ /**
6
+ * How far a shared value travels:
7
+ * - 'everywhere' — every tab, window, and worker on this origin (default)
8
+ * - 'tabs' — tabs and windows only; writes coming from workers are ignored
9
+ * - 'tab' — this tab only (state is still shared between components)
10
+ */
11
+ type ShareScope = 'everywhere' | 'tabs' | 'tab';
12
+ interface UseSharedStateOptions {
13
+ /** Store name; keys live in a namespace per store. Default 'use-everywhere'. */
14
+ store?: string;
15
+ /** How much to share. Default 'everywhere'. */
16
+ scope?: ShareScope;
17
+ }
18
+
19
+ /**
20
+ * Like useState, but the value exists in every tab, window, and worker on
21
+ * this origin. Late-joining tabs hydrate to the current value; concurrent
22
+ * writes converge last-writer-wins. Pass options.scope to delimit how much
23
+ * is shared ('everywhere' | 'tabs' | 'tab').
24
+ */
25
+ declare function useSharedState<T>(key: string, initial: T, options?: UseSharedStateOptions): [T, (next: T | ((prev: T) => T)) => void];
26
+
27
+ /** Registry stores hold arbitrary keys — shape is decided by the hooks using them. */
28
+ type AnyStore = SharedStore<Record<string, unknown>>;
29
+
30
+ /** Imperative access to the store behind useSharedState (patch logs, non-React code). */
31
+ declare function getSharedStore(name?: string, scope?: ShareScope): AnyStore;
32
+ /**
33
+ * One Leader per name per tab. Eligibility is deliberately *not* part of the
34
+ * key: two Leaders on one name would share a bus and a clientId, and since a
35
+ * post never loops back locally, neither would ever see the other's claims.
36
+ * Timing options are first-wins, like every other engine here.
37
+ */
38
+ declare function getLeader(name: string, options?: LeaderOptions): Leader;
39
+
40
+ /** Get the page-wide typed channel for `name` (one instance per name). */
41
+ declare function useChannel<M extends MessageMap>(name: string): Channel<M>;
42
+ /**
43
+ * Subscribe to one message type. The handler is kept fresh without
44
+ * resubscribing, so it may close over render state.
45
+ */
46
+ declare function useMessage<M extends MessageMap, K extends keyof M & string>(channel: Channel<M>, type: K, handler: (payload: M[K], meta: MessageMeta) => void): void;
47
+ /** The channel's post function (stable identity per channel). */
48
+ declare function useSend<M extends MessageMap>(channel: Channel<M>): Channel<M>['post'];
49
+
50
+ /** A channel bound to a name and message map: typed hooks with no per-call generics. */
51
+ interface ChannelHooks<M extends MessageMap> {
52
+ /** The underlying channel instance (the same one the hooks use) — for non-React code. */
53
+ get: () => Channel<M>;
54
+ /** The channel's post function (stable identity). */
55
+ useSend: () => Channel<M>['post'];
56
+ /**
57
+ * Subscribe to one message type. Same contract as the standalone
58
+ * `useMessage`: the handler is kept fresh without resubscribing.
59
+ */
60
+ useMessage: <K extends keyof M & string>(type: K, handler: (payload: M[K], meta: MessageMeta) => void) => void;
61
+ }
62
+
63
+ /**
64
+ * Bind a channel name and message map once, at module level, and get fully
65
+ * typed hooks back. Sugar over useChannel/useMessage/useSend — the same
66
+ * page-wide channel singleton is shared, so mixing bound and standalone
67
+ * hooks for one name is safe.
68
+ */
69
+ declare function defineChannel<M extends MessageMap>(name: string): ChannelHooks<M>;
70
+
71
+ interface DefineStoreOptions {
72
+ /** Restore this store from disk on first use, and write it back as it changes. */
73
+ persist?: PersistAdapter;
74
+ /** Persist only these keys. Default: every key that has been written. */
75
+ persistKeys?: string[];
76
+ /** Coalesce disk writes for this long. Default 100. */
77
+ persistDebounceMs?: number;
78
+ /** How far this store is shared. Default 'everywhere'. */
79
+ scope?: ShareScope;
80
+ }
81
+ /** A store bound to a name and a shape: typed hooks with no per-call generics. */
82
+ interface StoreHooks<S extends Record<string, unknown>> {
83
+ /** The underlying store instance (the same one the hooks use) — for non-React code. */
84
+ get: () => AnyStore;
85
+ useSharedState: <K extends keyof S & string>(key: K, initial: S[K]) => [S[K], (next: S[K] | ((prev: S[K]) => S[K])) => void];
86
+ }
87
+
88
+ /**
89
+ * Bind a store name — and optionally persistence — once, at module level.
90
+ *
91
+ * Like defineChannel, this does not construct anything: it registers the
92
+ * options the registry will use when the store is first needed, so importing
93
+ * the module has no side effect. The store stays a singleton per name, so
94
+ * `defineStore('settings', { persist })` and a bare
95
+ * `useSharedState('theme', 'dark', { store: 'settings' })` elsewhere resolve to
96
+ * the same store, and both get persistence.
97
+ *
98
+ * Must run before that store exists. Module evaluation always precedes render,
99
+ * so intended usage is automatic; if it does run late it throws rather than
100
+ * quietly handing back a store with no persistence.
101
+ */
102
+ declare function defineStore<S extends Record<string, unknown> = Record<string, unknown>>(name: string, options?: DefineStoreOptions): StoreHooks<S>;
103
+
104
+ /** The other tabs/windows/workers currently alive on this origin. */
105
+ declare function usePeers(options?: {
106
+ name?: string;
107
+ }): readonly Peer[];
108
+ /** This client's own id on the presence bus (matches patch origin ids). */
109
+ declare function useClientId(options?: {
110
+ name?: string;
111
+ }): string;
112
+
113
+ interface UseLeaderOptions extends LeaderOptions {
114
+ /** Which bus to elect on. Defaults to the shared default name. */
115
+ name?: string;
116
+ }
117
+
118
+ /**
119
+ * Who currently holds the seat on this bus, and whether it is us. Exactly one
120
+ * tab leads; opening another does not steal it, and closing the leader hands it
121
+ * over at once.
122
+ */
123
+ declare function useLeader(options?: UseLeaderOptions): LeaderSnapshot;
124
+ /** Is this tab the leader? */
125
+ declare function useIsLeader(options?: UseLeaderOptions): boolean;
126
+ /**
127
+ * Run an effect only in the tab that holds the seat, and tear it down when the
128
+ * seat moves. The one place to put "exactly one tab owns the socket".
129
+ */
130
+ declare function useLeaderEffect(effect: () => void | (() => void), options?: UseLeaderOptions): void;
131
+
132
+ type OpenedWindowStatus = 'idle' | 'opening' | 'connected' | 'done' | 'closed-early' | 'error';
133
+ interface UseOpenedWindow<Out extends MessageMap, In extends MessageMap, R> {
134
+ /** Call from a click handler (popup blockers require a user gesture). */
135
+ open: () => void;
136
+ status: OpenedWindowStatus;
137
+ /** The child's finish() value, once status is 'done'. */
138
+ result: R | undefined;
139
+ error: unknown;
140
+ /** Post to the child; no-op while nothing is open. */
141
+ post: OpenedWindow<Out, In, R>['post'];
142
+ close: () => void;
143
+ }
144
+
145
+ /**
146
+ * Drive an openWindow() flow from a component: the factory is called on
147
+ * open(), and the child window's lifecycle is folded into render state.
148
+ * Reopening replaces the previous window; a stale window's outcome is ignored.
149
+ */
150
+ declare function useOpenedWindow<Out extends MessageMap, In extends MessageMap, R = unknown>(factory: () => OpenedWindow<Out, In, R>): UseOpenedWindow<Out, In, R>;
151
+
152
+ export { type AnyStore, type ChannelHooks, type DefineStoreOptions, type OpenedWindowStatus, type ShareScope, type StoreHooks, type UseLeaderOptions, type UseOpenedWindow, type UseSharedStateOptions, defineChannel, defineStore, getLeader, getSharedStore, useChannel, useClientId, useIsLeader, useLeader, useLeaderEffect, useMessage, useOpenedWindow, usePeers, useSend, useSharedState };
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ 'use client';
1
2
  import {
2
3
  DEFAULT_NAME,
3
4
  configureStore,
@@ -7,7 +8,7 @@ import {
7
8
  getStore,
8
9
  useClientId,
9
10
  usePeers
10
- } from "./chunk-Y67BCTU6.js";
11
+ } from "./chunk-PNFJW7QK.js";
11
12
 
12
13
  // src/use-shared-state.ts
13
14
  import { useCallback, useSyncExternalStore } from "react";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "use-everywhere",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "React hooks for state and messages shared across tabs, windows, and workers",
5
5
  "license": "MIT",
6
6
  "author": "Jonatan Kruszewski <jonakrusze@gmail.com>",
@@ -26,16 +26,29 @@
26
26
  },
27
27
  "type": "module",
28
28
  "sideEffects": false,
29
- "main": "./dist/index.js",
29
+ "main": "./dist/index.cjs",
30
+ "module": "./dist/index.js",
30
31
  "types": "./dist/index.d.ts",
31
32
  "exports": {
32
33
  ".": {
33
- "types": "./dist/index.d.ts",
34
- "import": "./dist/index.js"
34
+ "import": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ },
38
+ "require": {
39
+ "types": "./dist/index.d.cts",
40
+ "default": "./dist/index.cjs"
41
+ }
35
42
  },
36
43
  "./devtools": {
37
- "types": "./dist/devtools/index.d.ts",
38
- "import": "./dist/devtools/index.js"
44
+ "import": {
45
+ "types": "./dist/devtools/index.d.ts",
46
+ "default": "./dist/devtools/index.js"
47
+ },
48
+ "require": {
49
+ "types": "./dist/devtools/index.d.cts",
50
+ "default": "./dist/devtools/index.cjs"
51
+ }
39
52
  }
40
53
  },
41
54
  "files": [
@@ -92,23 +105,23 @@
92
105
  }
93
106
  ],
94
107
  "dependencies": {
95
- "@use-everywhere/core": "0.3.0"
108
+ "@use-everywhere/core": "0.4.0"
96
109
  },
97
110
  "peerDependencies": {
98
111
  "react": ">=18"
99
112
  },
100
113
  "devDependencies": {
101
- "@size-limit/preset-small-lib": "^12.1.0",
102
- "@testing-library/react": "^16.3.0",
103
- "@types/react": "^19.1.8",
114
+ "@size-limit/preset-small-lib": "^13.0.1",
115
+ "@testing-library/react": "^16.3.2",
116
+ "@types/react": "^19.2.17",
104
117
  "@types/react-dom": "^19.2.3",
105
118
  "@vitest/coverage-v8": "^4.1.10",
106
- "happy-dom": "^20.10.6",
107
- "react": "^19.1.0",
108
- "react-dom": "^19.1.0",
109
- "size-limit": "^12.1.0",
110
- "tsup": "^8.5.0",
111
- "typescript": "^5.8.3",
119
+ "happy-dom": "^20.11.1",
120
+ "react": "^19.2.8",
121
+ "react-dom": "^19.2.8",
122
+ "size-limit": "^13.0.1",
123
+ "tsup": "^8.5.1",
124
+ "typescript": "^6.0.3",
112
125
  "vitest": "^4.1.10"
113
126
  },
114
127
  "typesVersions": {