All files / src/snapshot json.ts

100% Statements 23/23
100% Branches 0/0
100% Functions 4/4
100% Lines 19/19

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 361x 1x 1x 1x 1x           1x 1x   1x 4x 4x     1x 1x 1x     1x 3x 3x     1x       1x 1x    
import { JsonEncoder } from '@jsonjoy.com/json-pack/lib/json/JsonEncoder';
import { JsonDecoder } from '@jsonjoy.com/json-pack/lib/json/JsonDecoder';
import { fromSnapshotSync, toSnapshotSync } from './sync';
import { fromSnapshot, toSnapshot } from './async';
import { writer } from './shared';
import type { AsyncSnapshotOptions, SnapshotNode, SnapshotOptions } from './types';
 
/** @todo Import this type from `json-joy` once it is available. */
export type JsonUint8Array<T> = Uint8Array & { __BRAND__: 'json'; __TYPE__: T };
 
const encoder = new JsonEncoder(writer);
const decoder = new JsonDecoder();
 
export const toJsonSnapshotSync = (options: SnapshotOptions): JsonUint8Array<SnapshotNode> => {
  const snapshot = toSnapshotSync(options);
  return encoder.encode(snapshot) as JsonUint8Array<SnapshotNode>;
};
 
export const fromJsonSnapshotSync = (uint8: JsonUint8Array<SnapshotNode>, options: SnapshotOptions): void => {
  const snapshot = decoder.read(uint8) as SnapshotNode;
  fromSnapshotSync(snapshot, options);
};
 
export const toJsonSnapshot = async (options: AsyncSnapshotOptions): Promise<JsonUint8Array<SnapshotNode>> => {
  const snapshot = await toSnapshot(options);
  return encoder.encode(snapshot) as JsonUint8Array<SnapshotNode>;
};
 
export const fromJsonSnapshot = async (
  uint8: JsonUint8Array<SnapshotNode>,
  options: AsyncSnapshotOptions,
): Promise<void> => {
  const snapshot = decoder.read(uint8) as SnapshotNode;
  await fromSnapshot(snapshot, options);
};