UNPKG

28.1 kBJavaScriptView Raw
1import { createContext, useState, useEffect, useDebugValue, useRef, createElement, useContext, useCallback, useReducer } from 'react';
2
3const SUSPENSE_PROMISE = Symbol();
4const isSuspensePromise = (promise) => !!promise[SUSPENSE_PROMISE];
5const isSuspensePromiseAlreadyCancelled = (suspensePromise) => !suspensePromise[SUSPENSE_PROMISE].c;
6const cancelSuspensePromise = (suspensePromise) => {
7 var _a, _b;
8 (_b = (_a = suspensePromise[SUSPENSE_PROMISE]).c) == null ? void 0 : _b.call(_a);
9};
10const isEqualSuspensePromise = (oldSuspensePromise, newSuspensePromise) => {
11 const oldOriginalPromise = oldSuspensePromise[SUSPENSE_PROMISE].o;
12 const newOriginalPromise = newSuspensePromise[SUSPENSE_PROMISE].o;
13 return oldOriginalPromise === newOriginalPromise || oldSuspensePromise === newOriginalPromise || isSuspensePromise(oldOriginalPromise) && isEqualSuspensePromise(oldOriginalPromise, newSuspensePromise);
14};
15const createSuspensePromise = (promise) => {
16 const objectToAttach = {
17 o: promise,
18 c: null
19 };
20 const suspensePromise = new Promise((resolve) => {
21 objectToAttach.c = () => {
22 objectToAttach.c = null;
23 resolve();
24 };
25 promise.then(objectToAttach.c, objectToAttach.c);
26 });
27 suspensePromise[SUSPENSE_PROMISE] = objectToAttach;
28 return suspensePromise;
29};
30
31var __defProp$1 = Object.defineProperty;
32var __defProps$1 = Object.defineProperties;
33var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
34var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
35var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
36var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
37var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
38var __spreadValues$1 = (a, b) => {
39 for (var prop in b || (b = {}))
40 if (__hasOwnProp$1.call(b, prop))
41 __defNormalProp$1(a, prop, b[prop]);
42 if (__getOwnPropSymbols$1)
43 for (var prop of __getOwnPropSymbols$1(b)) {
44 if (__propIsEnum$1.call(b, prop))
45 __defNormalProp$1(a, prop, b[prop]);
46 }
47 return a;
48};
49var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
50const hasInitialValue = (atom) => "init" in atom;
51const READ_ATOM = "r";
52const WRITE_ATOM = "w";
53const COMMIT_ATOM = "c";
54const SUBSCRIBE_ATOM = "s";
55const RESTORE_ATOMS = "h";
56const DEV_SUBSCRIBE_STATE = "n";
57const DEV_GET_MOUNTED_ATOMS = "l";
58const DEV_GET_ATOM_STATE = "a";
59const DEV_GET_MOUNTED = "m";
60const createStore = (initialValues) => {
61 const committedAtomStateMap = /* @__PURE__ */ new WeakMap();
62 const mountedMap = /* @__PURE__ */ new WeakMap();
63 const pendingMap = /* @__PURE__ */ new Map();
64 let stateListeners;
65 let mountedAtoms;
66 if ((import.meta.env && import.meta.env.MODE) !== "production") {
67 stateListeners = /* @__PURE__ */ new Set();
68 mountedAtoms = /* @__PURE__ */ new Set();
69 }
70 if (initialValues) {
71 for (const [atom, value] of initialValues) {
72 const atomState = { v: value, r: 0, d: /* @__PURE__ */ new Map() };
73 if ((import.meta.env && import.meta.env.MODE) !== "production") {
74 Object.freeze(atomState);
75 if (!hasInitialValue(atom)) {
76 console.warn("Found initial value for derived atom which can cause unexpected behavior", atom);
77 }
78 }
79 committedAtomStateMap.set(atom, atomState);
80 }
81 }
82 const suspensePromiseCacheMap = /* @__PURE__ */ new WeakMap();
83 const addSuspensePromiseToCache = (version, atom, suspensePromise) => {
84 let cache = suspensePromiseCacheMap.get(atom);
85 if (!cache) {
86 cache = /* @__PURE__ */ new Map();
87 suspensePromiseCacheMap.set(atom, cache);
88 }
89 suspensePromise.then(() => {
90 if (cache.get(version) === suspensePromise) {
91 cache.delete(version);
92 if (!cache.size) {
93 suspensePromiseCacheMap.delete(atom);
94 }
95 }
96 });
97 cache.set(version, suspensePromise);
98 };
99 const cancelAllSuspensePromiseInCache = (atom) => {
100 const versionSet = /* @__PURE__ */ new Set();
101 const cache = suspensePromiseCacheMap.get(atom);
102 if (cache) {
103 suspensePromiseCacheMap.delete(atom);
104 cache.forEach((suspensePromise, version) => {
105 cancelSuspensePromise(suspensePromise);
106 versionSet.add(version);
107 });
108 }
109 return versionSet;
110 };
111 const versionedAtomStateMapMap = /* @__PURE__ */ new WeakMap();
112 const getVersionedAtomStateMap = (version) => {
113 let versionedAtomStateMap = versionedAtomStateMapMap.get(version);
114 if (!versionedAtomStateMap) {
115 versionedAtomStateMap = /* @__PURE__ */ new Map();
116 versionedAtomStateMapMap.set(version, versionedAtomStateMap);
117 }
118 return versionedAtomStateMap;
119 };
120 const getAtomState = (version, atom) => {
121 if (version) {
122 const versionedAtomStateMap = getVersionedAtomStateMap(version);
123 let atomState = versionedAtomStateMap.get(atom);
124 if (!atomState) {
125 atomState = getAtomState(version.p, atom);
126 if (atomState) {
127 if ("p" in atomState) {
128 atomState.p.then(() => versionedAtomStateMap.delete(atom));
129 }
130 versionedAtomStateMap.set(atom, atomState);
131 }
132 }
133 return atomState;
134 }
135 return committedAtomStateMap.get(atom);
136 };
137 const setAtomState = (version, atom, atomState) => {
138 if ((import.meta.env && import.meta.env.MODE) !== "production") {
139 Object.freeze(atomState);
140 }
141 if (version) {
142 const versionedAtomStateMap = getVersionedAtomStateMap(version);
143 versionedAtomStateMap.set(atom, atomState);
144 } else {
145 const prevAtomState = committedAtomStateMap.get(atom);
146 committedAtomStateMap.set(atom, atomState);
147 if (!pendingMap.has(atom)) {
148 pendingMap.set(atom, prevAtomState);
149 }
150 }
151 };
152 const createReadDependencies = (version, prevReadDependencies = /* @__PURE__ */ new Map(), dependencies) => {
153 if (!dependencies) {
154 return prevReadDependencies;
155 }
156 const readDependencies = /* @__PURE__ */ new Map();
157 let changed = false;
158 dependencies.forEach((atom) => {
159 var _a;
160 const revision = ((_a = getAtomState(version, atom)) == null ? void 0 : _a.r) || 0;
161 readDependencies.set(atom, revision);
162 if (prevReadDependencies.get(atom) !== revision) {
163 changed = true;
164 }
165 });
166 if (prevReadDependencies.size === readDependencies.size && !changed) {
167 return prevReadDependencies;
168 }
169 return readDependencies;
170 };
171 const setAtomValue = (version, atom, value, dependencies, suspensePromise) => {
172 const atomState = getAtomState(version, atom);
173 if (atomState) {
174 if (suspensePromise && (!("p" in atomState) || !isEqualSuspensePromise(atomState.p, suspensePromise))) {
175 return atomState;
176 }
177 if ("p" in atomState) {
178 cancelSuspensePromise(atomState.p);
179 }
180 }
181 const nextAtomState = {
182 v: value,
183 r: (atomState == null ? void 0 : atomState.r) || 0,
184 d: createReadDependencies(version, atomState == null ? void 0 : atomState.d, dependencies)
185 };
186 if (!atomState || !("v" in atomState) || !Object.is(atomState.v, value)) {
187 ++nextAtomState.r;
188 if (nextAtomState.d.has(atom)) {
189 nextAtomState.d = new Map(nextAtomState.d).set(atom, nextAtomState.r);
190 }
191 } else if (nextAtomState.d !== atomState.d && (nextAtomState.d.size !== atomState.d.size || !Array.from(nextAtomState.d.keys()).every((a) => atomState.d.has(a)))) {
192 Promise.resolve().then(() => {
193 flushPending(version);
194 });
195 }
196 setAtomState(version, atom, nextAtomState);
197 return nextAtomState;
198 };
199 const setAtomReadError = (version, atom, error, dependencies, suspensePromise) => {
200 const atomState = getAtomState(version, atom);
201 if (atomState) {
202 if (suspensePromise && (!("p" in atomState) || !isEqualSuspensePromise(atomState.p, suspensePromise))) {
203 return atomState;
204 }
205 if ("p" in atomState) {
206 cancelSuspensePromise(atomState.p);
207 }
208 }
209 const nextAtomState = {
210 e: error,
211 r: (atomState == null ? void 0 : atomState.r) || 0,
212 d: createReadDependencies(version, atomState == null ? void 0 : atomState.d, dependencies)
213 };
214 setAtomState(version, atom, nextAtomState);
215 return nextAtomState;
216 };
217 const setAtomSuspensePromise = (version, atom, suspensePromise, dependencies) => {
218 const atomState = getAtomState(version, atom);
219 if (atomState && "p" in atomState) {
220 if (isEqualSuspensePromise(atomState.p, suspensePromise)) {
221 return atomState;
222 }
223 cancelSuspensePromise(atomState.p);
224 }
225 addSuspensePromiseToCache(version, atom, suspensePromise);
226 const nextAtomState = {
227 p: suspensePromise,
228 r: (atomState == null ? void 0 : atomState.r) || 0,
229 d: createReadDependencies(version, atomState == null ? void 0 : atomState.d, dependencies)
230 };
231 setAtomState(version, atom, nextAtomState);
232 return nextAtomState;
233 };
234 const setAtomPromiseOrValue = (version, atom, promiseOrValue, dependencies) => {
235 if (promiseOrValue instanceof Promise) {
236 const suspensePromise = createSuspensePromise(promiseOrValue.then((value) => {
237 setAtomValue(version, atom, value, dependencies, suspensePromise);
238 flushPending(version);
239 }).catch((e) => {
240 if (e instanceof Promise) {
241 if (isSuspensePromise(e)) {
242 return e.then(() => {
243 readAtomState(version, atom, true);
244 });
245 }
246 return e;
247 }
248 setAtomReadError(version, atom, e, dependencies, suspensePromise);
249 flushPending(version);
250 }));
251 return setAtomSuspensePromise(version, atom, suspensePromise, dependencies);
252 }
253 return setAtomValue(version, atom, promiseOrValue, dependencies);
254 };
255 const setAtomInvalidated = (version, atom) => {
256 const atomState = getAtomState(version, atom);
257 if (atomState) {
258 if ("p" in atomState) {
259 cancelSuspensePromise(atomState.p);
260 }
261 const nextAtomState = __spreadProps$1(__spreadValues$1({}, atomState), {
262 i: atomState.r
263 });
264 setAtomState(version, atom, nextAtomState);
265 } else if ((import.meta.env && import.meta.env.MODE) !== "production") {
266 console.warn("[Bug] could not invalidate non existing atom", atom);
267 }
268 };
269 const readAtomState = (version, atom, force) => {
270 if (!force) {
271 const atomState = getAtomState(version, atom);
272 if (atomState) {
273 if (atomState.r !== atomState.i && "p" in atomState && !isSuspensePromiseAlreadyCancelled(atomState.p)) {
274 return atomState;
275 }
276 atomState.d.forEach((_, a) => {
277 if (a !== atom) {
278 if (!mountedMap.has(a)) {
279 readAtomState(version, a);
280 } else {
281 const aState = getAtomState(version, a);
282 if (aState && aState.r === aState.i) {
283 readAtomState(version, a);
284 }
285 }
286 }
287 });
288 if (Array.from(atomState.d).every(([a, r]) => {
289 const aState = getAtomState(version, a);
290 return aState && "v" in aState && aState.r === r;
291 })) {
292 return atomState;
293 }
294 }
295 }
296 const dependencies = /* @__PURE__ */ new Set();
297 try {
298 const promiseOrValue = atom.read((a) => {
299 dependencies.add(a);
300 const aState = a === atom ? getAtomState(version, a) : readAtomState(version, a);
301 if (aState) {
302 if ("e" in aState) {
303 throw aState.e;
304 }
305 if ("p" in aState) {
306 throw aState.p;
307 }
308 return aState.v;
309 }
310 if (hasInitialValue(a)) {
311 return a.init;
312 }
313 throw new Error("no atom init");
314 });
315 return setAtomPromiseOrValue(version, atom, promiseOrValue, dependencies);
316 } catch (errorOrPromise) {
317 if (errorOrPromise instanceof Promise) {
318 const suspensePromise = createSuspensePromise(errorOrPromise);
319 return setAtomSuspensePromise(version, atom, suspensePromise, dependencies);
320 }
321 return setAtomReadError(version, atom, errorOrPromise, dependencies);
322 }
323 };
324 const readAtom = (readingAtom, version) => {
325 const atomState = readAtomState(version, readingAtom);
326 return atomState;
327 };
328 const addAtom = (addingAtom) => {
329 let mounted = mountedMap.get(addingAtom);
330 if (!mounted) {
331 mounted = mountAtom(addingAtom);
332 }
333 return mounted;
334 };
335 const canUnmountAtom = (atom, mounted) => !mounted.l.size && (!mounted.t.size || mounted.t.size === 1 && mounted.t.has(atom));
336 const delAtom = (deletingAtom) => {
337 const mounted = mountedMap.get(deletingAtom);
338 if (mounted && canUnmountAtom(deletingAtom, mounted)) {
339 unmountAtom(deletingAtom);
340 }
341 };
342 const invalidateDependents = (version, atom) => {
343 const mounted = mountedMap.get(atom);
344 mounted == null ? void 0 : mounted.t.forEach((dependent) => {
345 if (dependent !== atom) {
346 setAtomInvalidated(version, dependent);
347 invalidateDependents(version, dependent);
348 }
349 });
350 };
351 const writeAtomState = (version, atom, update) => {
352 let isSync = true;
353 const writeGetter = (a, options) => {
354 const aState = readAtomState(version, a);
355 if ("e" in aState) {
356 throw aState.e;
357 }
358 if ("p" in aState) {
359 if (options == null ? void 0 : options.unstable_promise) {
360 return aState.p.then(() => writeGetter(a, options));
361 }
362 if ((import.meta.env && import.meta.env.MODE) !== "production") {
363 console.info("Reading pending atom state in write operation. We throw a promise for now.", a);
364 }
365 throw aState.p;
366 }
367 if ("v" in aState) {
368 return aState.v;
369 }
370 if ((import.meta.env && import.meta.env.MODE) !== "production") {
371 console.warn("[Bug] no value found while reading atom in write operation. This is probably a bug.", a);
372 }
373 throw new Error("no value found");
374 };
375 const setter = (a, v) => {
376 let promiseOrVoid2;
377 if (a === atom) {
378 if (!hasInitialValue(a)) {
379 throw new Error("atom not writable");
380 }
381 const versionSet = cancelAllSuspensePromiseInCache(a);
382 versionSet.forEach((cancelledVersion) => {
383 if (cancelledVersion !== version) {
384 setAtomPromiseOrValue(cancelledVersion, a, v);
385 }
386 });
387 setAtomPromiseOrValue(version, a, v);
388 invalidateDependents(version, a);
389 } else {
390 promiseOrVoid2 = writeAtomState(version, a, v);
391 }
392 if (!isSync) {
393 flushPending(version);
394 }
395 return promiseOrVoid2;
396 };
397 const promiseOrVoid = atom.write(writeGetter, setter, update);
398 isSync = false;
399 version = void 0;
400 return promiseOrVoid;
401 };
402 const writeAtom = (writingAtom, update, version) => {
403 const promiseOrVoid = writeAtomState(version, writingAtom, update);
404 flushPending(version);
405 return promiseOrVoid;
406 };
407 const isActuallyWritableAtom = (atom) => !!atom.write;
408 const mountAtom = (atom, initialDependent) => {
409 const mounted = {
410 t: new Set(initialDependent && [initialDependent]),
411 l: /* @__PURE__ */ new Set()
412 };
413 mountedMap.set(atom, mounted);
414 if ((import.meta.env && import.meta.env.MODE) !== "production") {
415 mountedAtoms.add(atom);
416 }
417 const atomState = readAtomState(void 0, atom);
418 atomState.d.forEach((_, a) => {
419 const aMounted = mountedMap.get(a);
420 if (aMounted) {
421 aMounted.t.add(atom);
422 } else {
423 if (a !== atom) {
424 mountAtom(a, atom);
425 }
426 }
427 });
428 if (isActuallyWritableAtom(atom) && atom.onMount) {
429 const setAtom = (update) => writeAtom(atom, update);
430 const onUnmount = atom.onMount(setAtom);
431 if (onUnmount) {
432 mounted.u = onUnmount;
433 }
434 }
435 return mounted;
436 };
437 const unmountAtom = (atom) => {
438 var _a;
439 const onUnmount = (_a = mountedMap.get(atom)) == null ? void 0 : _a.u;
440 if (onUnmount) {
441 onUnmount();
442 }
443 mountedMap.delete(atom);
444 if ((import.meta.env && import.meta.env.MODE) !== "production") {
445 mountedAtoms.delete(atom);
446 }
447 const atomState = getAtomState(void 0, atom);
448 if (atomState) {
449 atomState.d.forEach((_, a) => {
450 if (a !== atom) {
451 const mounted = mountedMap.get(a);
452 if (mounted) {
453 mounted.t.delete(atom);
454 if (canUnmountAtom(a, mounted)) {
455 unmountAtom(a);
456 }
457 }
458 }
459 });
460 } else if ((import.meta.env && import.meta.env.MODE) !== "production") {
461 console.warn("[Bug] could not find atom state to unmount", atom);
462 }
463 };
464 const mountDependencies = (atom, atomState, prevReadDependencies) => {
465 const dependencies = new Set(atomState.d.keys());
466 prevReadDependencies == null ? void 0 : prevReadDependencies.forEach((_, a) => {
467 if (dependencies.has(a)) {
468 dependencies.delete(a);
469 return;
470 }
471 const mounted = mountedMap.get(a);
472 if (mounted) {
473 mounted.t.delete(atom);
474 if (canUnmountAtom(a, mounted)) {
475 unmountAtom(a);
476 }
477 }
478 });
479 dependencies.forEach((a) => {
480 const mounted = mountedMap.get(a);
481 if (mounted) {
482 mounted.t.add(atom);
483 } else if (mountedMap.has(atom)) {
484 mountAtom(a, atom);
485 }
486 });
487 };
488 const flushPending = (version) => {
489 if (version) {
490 const versionedAtomStateMap = getVersionedAtomStateMap(version);
491 versionedAtomStateMap.forEach((atomState, atom) => {
492 if (atomState !== committedAtomStateMap.get(atom)) {
493 const mounted = mountedMap.get(atom);
494 mounted == null ? void 0 : mounted.l.forEach((listener) => listener(version));
495 }
496 });
497 return;
498 }
499 while (pendingMap.size) {
500 const pending = Array.from(pendingMap);
501 pendingMap.clear();
502 pending.forEach(([atom, prevAtomState]) => {
503 const atomState = getAtomState(void 0, atom);
504 if (atomState && atomState.d !== (prevAtomState == null ? void 0 : prevAtomState.d)) {
505 mountDependencies(atom, atomState, prevAtomState == null ? void 0 : prevAtomState.d);
506 }
507 const mounted = mountedMap.get(atom);
508 mounted == null ? void 0 : mounted.l.forEach((listener) => listener());
509 });
510 }
511 if ((import.meta.env && import.meta.env.MODE) !== "production") {
512 stateListeners.forEach((l) => l());
513 }
514 };
515 const commitVersionedAtomStateMap = (version) => {
516 const versionedAtomStateMap = getVersionedAtomStateMap(version);
517 versionedAtomStateMap.forEach((atomState, atom) => {
518 const prevAtomState = committedAtomStateMap.get(atom);
519 if (atomState.r > ((prevAtomState == null ? void 0 : prevAtomState.r) || 0) || "v" in atomState && atomState.r === (prevAtomState == null ? void 0 : prevAtomState.r) && atomState.d !== (prevAtomState == null ? void 0 : prevAtomState.d)) {
520 committedAtomStateMap.set(atom, atomState);
521 if (atomState.d !== (prevAtomState == null ? void 0 : prevAtomState.d)) {
522 mountDependencies(atom, atomState, prevAtomState == null ? void 0 : prevAtomState.d);
523 }
524 }
525 });
526 };
527 const commitAtom = (_atom, version) => {
528 if (version) {
529 commitVersionedAtomStateMap(version);
530 }
531 flushPending(void 0);
532 };
533 const subscribeAtom = (atom, callback) => {
534 const mounted = addAtom(atom);
535 const listeners = mounted.l;
536 listeners.add(callback);
537 return () => {
538 listeners.delete(callback);
539 delAtom(atom);
540 };
541 };
542 const restoreAtoms = (values, version) => {
543 for (const [atom, value] of values) {
544 if (hasInitialValue(atom)) {
545 setAtomPromiseOrValue(version, atom, value);
546 invalidateDependents(version, atom);
547 }
548 }
549 flushPending(version);
550 };
551 if ((import.meta.env && import.meta.env.MODE) !== "production") {
552 return {
553 [READ_ATOM]: readAtom,
554 [WRITE_ATOM]: writeAtom,
555 [COMMIT_ATOM]: commitAtom,
556 [SUBSCRIBE_ATOM]: subscribeAtom,
557 [RESTORE_ATOMS]: restoreAtoms,
558 [DEV_SUBSCRIBE_STATE]: (l) => {
559 stateListeners.add(l);
560 return () => {
561 stateListeners.delete(l);
562 };
563 },
564 [DEV_GET_MOUNTED_ATOMS]: () => mountedAtoms.values(),
565 [DEV_GET_ATOM_STATE]: (a) => committedAtomStateMap.get(a),
566 [DEV_GET_MOUNTED]: (a) => mountedMap.get(a)
567 };
568 }
569 return {
570 [READ_ATOM]: readAtom,
571 [WRITE_ATOM]: writeAtom,
572 [COMMIT_ATOM]: commitAtom,
573 [SUBSCRIBE_ATOM]: subscribeAtom,
574 [RESTORE_ATOMS]: restoreAtoms
575 };
576};
577const createStoreForExport = (initialValues) => {
578 const store = createStore(initialValues);
579 const get = (atom) => {
580 const atomState = store[READ_ATOM](atom);
581 if ("e" in atomState) {
582 throw atomState.e;
583 }
584 if ("p" in atomState) {
585 return void 0;
586 }
587 return atomState.v;
588 };
589 const asyncGet = (atom) => new Promise((resolve, reject) => {
590 const atomState = store[READ_ATOM](atom);
591 if ("e" in atomState) {
592 reject(atomState.e);
593 } else if ("p" in atomState) {
594 resolve(atomState.p.then(() => asyncGet(atom)));
595 } else {
596 resolve(atomState.v);
597 }
598 });
599 const set = (atom, update) => store[WRITE_ATOM](atom, update);
600 const sub = (atom, callback) => store[SUBSCRIBE_ATOM](atom, callback);
601 return {
602 get,
603 asyncGet,
604 set,
605 sub,
606 SECRET_INTERNAL_store: store
607 };
608};
609
610const createScopeContainer = (initialValues, unstable_createStore) => {
611 const store = unstable_createStore ? unstable_createStore(initialValues).SECRET_INTERNAL_store : createStore(initialValues);
612 return { s: store };
613};
614const ScopeContextMap = /* @__PURE__ */ new Map();
615const getScopeContext = (scope) => {
616 if (!ScopeContextMap.has(scope)) {
617 ScopeContextMap.set(scope, createContext(createScopeContainer()));
618 }
619 return ScopeContextMap.get(scope);
620};
621
622var __defProp = Object.defineProperty;
623var __defProps = Object.defineProperties;
624var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
625var __getOwnPropSymbols = Object.getOwnPropertySymbols;
626var __hasOwnProp = Object.prototype.hasOwnProperty;
627var __propIsEnum = Object.prototype.propertyIsEnumerable;
628var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
629var __spreadValues = (a, b) => {
630 for (var prop in b || (b = {}))
631 if (__hasOwnProp.call(b, prop))
632 __defNormalProp(a, prop, b[prop]);
633 if (__getOwnPropSymbols)
634 for (var prop of __getOwnPropSymbols(b)) {
635 if (__propIsEnum.call(b, prop))
636 __defNormalProp(a, prop, b[prop]);
637 }
638 return a;
639};
640var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
641const atomToPrintable = (atom) => atom.debugLabel || atom.toString();
642const stateToPrintable = ([store, atoms]) => Object.fromEntries(atoms.flatMap((atom) => {
643 var _a, _b;
644 const mounted = (_a = store[DEV_GET_MOUNTED]) == null ? void 0 : _a.call(store, atom);
645 if (!mounted) {
646 return [];
647 }
648 const dependents = mounted.t;
649 const atomState = ((_b = store[DEV_GET_ATOM_STATE]) == null ? void 0 : _b.call(store, atom)) || {};
650 return [
651 [
652 atomToPrintable(atom),
653 __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, "e" in atomState && { error: atomState.e }), "p" in atomState && { promise: atomState.p }), "v" in atomState && { value: atomState.v }), {
654 dependents: Array.from(dependents).map(atomToPrintable)
655 })
656 ]
657 ];
658}));
659const useDebugState = (scopeContainer) => {
660 const { s: store } = scopeContainer;
661 const [atoms, setAtoms] = useState([]);
662 useEffect(() => {
663 var _a;
664 const callback = () => {
665 var _a2;
666 setAtoms(Array.from(((_a2 = store[DEV_GET_MOUNTED_ATOMS]) == null ? void 0 : _a2.call(store)) || []));
667 };
668 const unsubscribe = (_a = store[DEV_SUBSCRIBE_STATE]) == null ? void 0 : _a.call(store, callback);
669 callback();
670 return unsubscribe;
671 }, [store]);
672 useDebugValue([store, atoms], stateToPrintable);
673};
674
675const Provider = ({
676 children,
677 initialValues,
678 scope,
679 unstable_createStore,
680 unstable_enableVersionedWrite
681}) => {
682 const [version, setVersion] = useState();
683 useEffect(() => {
684 if (version) {
685 scopeContainerRef.current.s[COMMIT_ATOM](null, version);
686 delete version.p;
687 }
688 }, [version]);
689 const scopeContainerRef = useRef();
690 if (!scopeContainerRef.current) {
691 scopeContainerRef.current = createScopeContainer(initialValues, unstable_createStore);
692 if (unstable_enableVersionedWrite) {
693 scopeContainerRef.current.w = (write) => {
694 setVersion((parentVersion) => {
695 const nextVersion = parentVersion ? { p: parentVersion } : {};
696 write(nextVersion);
697 return nextVersion;
698 });
699 };
700 }
701 }
702 if ((import.meta.env && import.meta.env.MODE) !== "production" && !unstable_enableVersionedWrite) {
703 useDebugState(scopeContainerRef.current);
704 }
705 const ScopeContainerContext = getScopeContext(scope);
706 return createElement(ScopeContainerContext.Provider, {
707 value: scopeContainerRef.current
708 }, children);
709};
710
711let keyCount = 0;
712function atom(read, write) {
713 const key = `atom${++keyCount}`;
714 const config = {
715 toString: () => key
716 };
717 if (typeof read === "function") {
718 config.read = read;
719 } else {
720 config.init = read;
721 config.read = (get) => get(config);
722 config.write = (get, set, update) => set(config, typeof update === "function" ? update(get(config)) : update);
723 }
724 if (write) {
725 config.write = write;
726 }
727 return config;
728}
729
730function useAtomValue(atom, scope) {
731 const ScopeContext = getScopeContext(scope);
732 const { s: store } = useContext(ScopeContext);
733 const getAtomValue = useCallback((version2) => {
734 const atomState = store[READ_ATOM](atom, version2);
735 if ("e" in atomState) {
736 throw atomState.e;
737 }
738 if ("p" in atomState) {
739 throw atomState.p;
740 }
741 if ("v" in atomState) {
742 return atomState.v;
743 }
744 throw new Error("no atom value");
745 }, [store, atom]);
746 const [[version, value, atomFromUseReducer], rerenderIfChanged] = useReducer(useCallback((prev, nextVersion) => {
747 const nextValue = getAtomValue(nextVersion);
748 if (Object.is(prev[1], nextValue) && prev[2] === atom) {
749 return prev;
750 }
751 return [nextVersion, nextValue, atom];
752 }, [getAtomValue, atom]), void 0, () => {
753 const initialVersion = void 0;
754 const initialValue = getAtomValue(initialVersion);
755 return [initialVersion, initialValue, atom];
756 });
757 if (atomFromUseReducer !== atom) {
758 rerenderIfChanged(void 0);
759 }
760 useEffect(() => {
761 const unsubscribe = store[SUBSCRIBE_ATOM](atom, rerenderIfChanged);
762 rerenderIfChanged(void 0);
763 return unsubscribe;
764 }, [store, atom]);
765 useEffect(() => {
766 store[COMMIT_ATOM](atom, version);
767 });
768 useDebugValue(value);
769 return value;
770}
771
772function useSetAtom(atom, scope) {
773 const ScopeContext = getScopeContext(scope);
774 const { s: store, w: versionedWrite } = useContext(ScopeContext);
775 const setAtom = useCallback((update) => {
776 if ((import.meta.env && import.meta.env.MODE) !== "production" && !("write" in atom)) {
777 throw new Error("not writable atom");
778 }
779 const write = (version) => store[WRITE_ATOM](atom, update, version);
780 return versionedWrite ? versionedWrite(write) : write();
781 }, [store, versionedWrite, atom]);
782 return setAtom;
783}
784
785function useAtom(atom, scope) {
786 if ("scope" in atom) {
787 console.warn("atom.scope is deprecated. Please do useAtom(atom, scope) instead.");
788 scope = atom.scope;
789 }
790 return [
791 useAtomValue(atom, scope),
792 useSetAtom(atom, scope)
793 ];
794}
795
796export { Provider, getScopeContext as SECRET_INTERNAL_getScopeContext, atom, createStoreForExport as unstable_createStore, useAtom, useAtomValue, useSetAtom };