All files / src readable.ts

100% Statements 201/201
100% Branches 81/81
100% Functions 23/23
100% Lines 201/201

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 4072x                       2x       2x     2x 16x 20x 20x 16x                                                                             2x       365x         365x         365x         365x   365x   365x         365x   365x 1295x 1295x 1295x   365x 144x 144x   365x 136x 136x         365x         365x         365x         365x         365x         365x         365x         365x         365x   365x 365x 365x 365x 365x 365x 365x 365x 365x 365x 365x     365x 322x 105x 105x 105x 322x   365x 283x   267x   283x 103x 103x   267x 283x   365x 11x 11x 6x 11x 3x 3x 9x 9x 11x 3x 3x 3x 3x 3x 3x 3x 3x 11x 2x 2x 11x   365x 2057x   622x 622x 622x 102x 111x 99x 99x 99x 111x 102x 622x 619x 619x 619x 619x 582x 582x 582x 582x 4x 4x 582x 619x 21x 21x 21x 21x 619x 622x 2057x 2x 2x 2034x 2023x 5x 5x 2023x 2029x 2057x         365x 335x 2x 2x 1x 1x 2x   335x   335x   335x   335x 121x 133x 133x 121x 121x 133x 121x   335x 335x     365x 235x   216x 216x 235x 235x   365x 105x 105x 105x   365x 139x 139x 139x 139x 139x   365x 40x 40x 40x 40x                     365x 7x 7x 7x                     365x 1x 1x   365x 91x 91x   365x 4x 4x 365x   2x 238x 238x 238x 238x   238x   238x   238x 234x 214x 214x 214x 234x   238x 238x                         2x 234x 234x 234x                                                       2x 234x 234x 234x  
import { batchFlush, batchStart, type BatchTask, tasks } from "./batch";
import {
  type OwnedReadable,
  type OwnedWritable,
  type Config,
  type Disposer,
  type Readable,
  type SetValue,
  type Subscriber,
  type Version,
  type Writable,
} from "./typings";
import { BRAND, invokeEach, strictEqual, UNIQUE_VALUE } from "./utils";
 
export type Deps = Map<ReadableImpl, Version>;
 
const registry = /* @__PURE__ */ new FinalizationRegistry<{
  d: Deps;
  r: WeakRef<ReadableImpl>;
}>(({ d, r }) => {
  for (const dep of d.keys()) {
    dep.dependents_?.delete(r);
  }
});
 
export interface CreateReadable {
  /**
   * Creates a Readonly with the given value.
   *
   * @returns A tuple with the Readonly and a function to set the value.
   */
  <TValue = any>(): [OwnedReadable<NoInfer<TValue> | undefined>, SetValue<NoInfer<TValue> | undefined>];
  /**
   * Creates a Readonly with the given value.
   *
   * @param value
   * @param config Optional custom config.
   * @returns A tuple with the Readonly and a function to set the value.
   */
  (value: [], config?: Config<any[]>): [OwnedReadable<any[]>, SetValue<any[]>];
  /**
   * Creates a Readonly with the given value.
   *
   * @param value
   * @param config Optional custom config.
   * @returns A tuple with the Readonly and a function to set the value.
   */
  <TValue = any>(value: TValue, config?: Config<TValue>): [OwnedReadable<NoInfer<TValue>>, SetValue<NoInfer<TValue>>];
  /**
   * Creates a Readonly with the given value.
   *
   * @param value
   * @param config Optional custom config.
   * @returns A tuple with the Readonly and a function to set the value.
   */
  <TValue = any>(
    value?: TValue,
    config?: Config<TValue>,
  ): [OwnedReadable<NoInfer<TValue | undefined>>, SetValue<NoInfer<TValue | undefined>>];
}
 
/** @internal */
export class ReadableImpl<TValue = any> implements BatchTask {
  /**
   * @internal
   */
  public readonly [BRAND]: BRAND = BRAND;
 
  /**
   * @internal
   */
  public dependents_?: Set<WeakRef<ReadableImpl>>;
 
  /**
   * @internal
   */
  public deps_?: Map<ReadableImpl, Version>;
 
  /**
   * @internal
   */
  public equal_?: (newValue: TValue, oldValue: TValue) => boolean;
 
  public name?: string;
 
  public set?: (value: TValue) => void;
 
  /**
   * @internal
   */
  private _subs_?: Set<Subscriber<TValue>>;
 
  public get $version(): Version {
    this.get();
    return this._version_;
  }
 
  public get value(): TValue {
    return this.get();
  }
 
  public set value(value: TValue) {
    this.set?.(value);
  }
 
  /**
   * @internal
   */
  private _lastSubInvokeVersion_: Version = -1;
 
  /**
   * @internal
   */
  private _disposed_?: Error | true;
 
  /**
   * @internal
   */
  private _resolveValue_: (self: ReadableImpl<TValue>) => TValue;
 
  /**
   * @internal
   */
  private _resolveValueError_: any;
 
  /**
   * @internal
   */
  private _value_: TValue = UNIQUE_VALUE as TValue;
 
  /**
   * @internal
   */
  private _valueMaybeDirty_ = true;
 
  /**
   * @internal
   */
  private _version_: Version = -1;
 
  /**
   * @internal
   */
  private _weakRefSelf_?: WeakRef<ReadableImpl<TValue>>;
 
  /**
   * @internal
   */
  private _onDisposeValue_?: (oldValue: TValue) => void;
 
  public constructor(
    resolveValue: (self: ReadableImpl<TValue>) => TValue,
    config?: Config<TValue>,
    deps?: Map<ReadableImpl, Version>,
  ) {
    this._resolveValue_ = resolveValue;
    this.equal_ = (config?.equal ?? strictEqual) || undefined;
    this.name = config?.name;
    this.deps_ = deps;
    this._onDisposeValue_ = config?.onDisposeValue;
  }
 
  /** @internal */
  public task_(): void {
    if (this._subs_?.size && this._lastSubInvokeVersion_ !== this.$version) {
      this._lastSubInvokeVersion_ = this.$version;
      invokeEach(this._subs_, this.get());
    }
  }
 
  public addDep_(dep: ReadableImpl): void {
    if (strictEqual(this.deps_?.get(dep), dep.$version)) return;
 
    (this.deps_ ??= new Map()).set(dep, dep.$version);
 
    if (!this._weakRefSelf_) {
      registry.register(this, { d: this.deps_, r: (this._weakRefSelf_ = new WeakRef(this)) }, this.deps_);
    }
 
    (dep.dependents_ ??= new Set()).add(this._weakRefSelf_);
  }
 
  public dispose(): void {
    if (this._disposed_) return;
    if (process.env.NODE_ENV !== "production") {
      this._disposed_ = new Error("[embra] Readable disposed at:");
    } else {
      this._disposed_ = true;
    }
    tasks.delete(this);
    this.dependents_ = undefined;
    if (this.deps_) {
      registry.unregister(this.deps_);
      if (this._weakRefSelf_) {
        for (const dep of this.deps_.keys()) {
          dep.dependents_?.delete(this._weakRefSelf_);
        }
      }
      this.deps_.clear();
    }
    if (this._onDisposeValue_ && !strictEqual(this._value_, UNIQUE_VALUE)) {
      this._onDisposeValue_(this._value_);
    }
  }
 
  public get(): TValue {
    if (this._valueMaybeDirty_) {
      // reset state immediately so that recursive notify_ calls can mark this as dirty again
      this._valueMaybeDirty_ = false;
      let changed = !this.deps_;
      if (this.deps_) {
        for (const [dep, version] of this.deps_) {
          if (!strictEqual(dep.$version, version)) {
            changed = true;
            break;
          }
        }
      }
      if (changed) {
        this._resolveValueError_ = UNIQUE_VALUE;
        try {
          const value = this._resolveValue_(this);
          if (!this.equal_?.(value, this._value_)) {
            const oldValue = this._value_;
            this._value_ = value;
            this._version_ = (this._version_ + 1) | 0;
            if (this._onDisposeValue_ && !strictEqual(oldValue, UNIQUE_VALUE) && !strictEqual(oldValue, value)) {
              this._onDisposeValue_(oldValue);
            }
          }
        } catch (e) {
          this._valueMaybeDirty_ = true;
          this._resolveValueError_ = e;
          throw e;
        }
      }
    }
    if (!strictEqual(this._resolveValueError_, UNIQUE_VALUE)) {
      throw this._resolveValueError_;
    }
    if (process.env.NODE_ENV !== "production") {
      if (strictEqual(UNIQUE_VALUE, this._value_)) {
        throw new Error("Cycle detected");
      }
    }
    return this._value_;
  }
 
  /**
   * @internal
   */
  public notify_(): void {
    if (this._disposed_) {
      console.error(new Error("disposed"));
      if (process.env.NODE_ENV !== "production") {
        console.error(this._disposed_);
      }
    }
 
    this._valueMaybeDirty_ = true;
 
    const isFirst = batchStart();
 
    tasks.add(this);
 
    if (this.dependents_) {
      for (const ref of this.dependents_) {
        const dependent = ref.deref();
        if (dependent && !tasks.has(dependent)) {
          dependent.notify_();
        }
      }
    }
 
    isFirst && batchFlush();
  }
 
  /** @internal */
  public onReaction_(subscriber: Subscriber<TValue>): void {
    if (!this._subs_?.size) {
      // start tracking last first on first subscription
      this._lastSubInvokeVersion_ = this.$version;
    }
    (this._subs_ ??= new Set()).add(subscriber);
  }
 
  public reaction(subscriber: Subscriber<TValue>): Disposer {
    this.onReaction_(subscriber);
    return () => this.unsubscribe(subscriber);
  }
 
  public removeDep_(dep: ReadableImpl): void {
    this.deps_?.delete(dep);
    if (this._weakRefSelf_) {
      dep.dependents_?.delete(this._weakRefSelf_);
    }
  }
 
  public subscribe(subscriber: Subscriber<TValue>): Disposer {
    const disposer = this.reaction(subscriber);
    subscriber(this.get());
    return disposer;
  }
 
  /**
   * @returns the JSON representation of `this.value`.
   *
   * @example
   * ```js
   * const v$ = writable(writable(writable({ a: 1 })));
   * JSON.stringify(v$); // '{"a":1}'
   * ```
   */
  public toJSON(key?: string): unknown {
    const value = this.get() as null | undefined | { toJSON?: (key?: string) => unknown };
    return value?.toJSON ? value.toJSON(key) : value;
  }
 
  /**
   * @returns the string representation of `this.value`.
   *
   * @example
   * ```js
   * const v$ = writable(writable(writable(1)));
   * console.log(`${v$}`); // "1"
   * ```
   */
  public toString(): string {
    return "" + this.toJSON();
  }
 
  public unsubscribe(subscriber?: (...args: any[]) => any): void {
    subscriber ? this._subs_?.delete(subscriber) : this._subs_?.clear();
  }
 
  public valueOf(): TValue {
    return this.get();
  }
}
 
export const readable: CreateReadable = <TValue = any>(
  value?: TValue,
  config?: Config<TValue | undefined>,
): [OwnedReadable<NoInfer<TValue> | undefined>, SetValue<NoInfer<TValue> | undefined>] => {
  let currentValue = value;
 
  const get = () => currentValue;
 
  const v = new ReadableImpl(get, config);
 
  const set = (value: TValue | undefined): void => {
    if (!v.equal_?.(value, currentValue)) {
      currentValue = value;
      v.notify_();
    }
  };
 
  return [v, set];
};
 
export interface ToWritable {
  <TValue>($: OwnedReadable<TValue>, set: (this: void, value: TValue) => void): OwnedWritable<TValue>;
  <TValue>($: Readable<TValue>, set: (this: void, value: TValue) => void): Writable<TValue>;
}
 
/**
 * Converts a Readable to a Writable By adding a setter function.
 * @param $
 * @param set a function that sets the value of Readable.
 * @returns The same Readable with the new setter.
 */
export const toWritable: ToWritable = <TValue>(
  $: Readable<TValue>,
  set: (this: void, value: TValue) => void,
): OwnedWritable<TValue> => ((($ as OwnedWritable<TValue>).set = set), $ as OwnedWritable<TValue>);
 
export interface CreateWritable {
  /**
   * Creates a Writable.
   * @returns A Writable with undefined value.
   */
  <TValue = any>(): OwnedWritable<TValue | undefined>;
  /**
   * Creates a Writable.
   * @param value Initial value.
   * @param config Optional custom config.
   */
  (value: [], config?: Config<any[]>): OwnedWritable<any[]>;
  /**
   * Creates a Writable.
   * @param value Initial value.
   * @param config Optional custom config.
   */
  <TValue = any>(value: TValue, config?: Config<TValue>): OwnedWritable<TValue>;
  /**
   * Creates a Writable.
   * @param value Initial value.
   * @param config Optional custom config.
   */
  <TValue = any>(value?: TValue, config?: Config<TValue | undefined>): OwnedWritable<TValue>;
}
 
export const writable: CreateWritable = <TValue = any>(
  value?: TValue,
  config?: Config<TValue>,
): OwnedWritable<NoInfer<TValue | undefined>> => toWritable(...readable(value, config));