All files / json-crdt-patch PatchBuilder.ts

95.58% Statements 173/181
79.06% Branches 34/43
96.66% Functions 29/30
98.73% Lines 156/158

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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441174x                                 174x 174x 174x 174x 174x 174x 174x   174x 126641x     14453x   112188x                 174x                 100448x 100448x                 426716x                   10888x 10888x 10888x                     64211x 64211x 64211x 64211x                 45261x 45261x 45261x 45261x                 24146x 24146x 24146x 24146x                 52536x 52536x 52536x 52536x                 6670x 6670x 6670x 6670x                     137114x 137114x 137114x 137114x                       7963x 7963x 7963x 7963x                 13168x 13168x 13168x 13168x                 72527x 72527x 72527x 72527x 72527x 72527x 72527x 72527x                 32092x 32092x 32092x 32092x 32092x 32092x 32092x 32092x                   12264x 12264x 12264x 12264x 12264x                 522812x 522812x 522812x 522812x 522812x 522812x 522812x 522812x                 17156x 17156x 17156x 17156x 17156x 17156x 17156x 17156x                 38341x 38341x 38341x 38341x 38341x 38341x 38341x                     144496x 144496x 144496x 144496x                     4257x 4257x 4257x 4257x                 41134x 41134x 41134x 38977x 38977x 92360x 92360x 92360x   38977x   41134x             26550x 26550x 16208x 24006x 16208x   26550x             36295x 36295x 36295x             1004x 1004x 1004x             3826x 3826x 3826x 3826x             10x 10x 10x 10x 26x 10x   10x             157843x 157831x 157825x 131275x 130271x 130261x 123316x 81254x   41638x   36295x     3321x                               34283x 34281x                                           1731585x 1731585x 1622630x 1622630x 2x 2x 2x        
import {
  NewConOp,
  NewObjOp,
  NewValOp,
  NewVecOp,
  NewStrOp,
  NewBinOp,
  NewArrOp,
  InsValOp,
  InsObjOp,
  InsVecOp,
  InsStrOp,
  InsBinOp,
  InsArrOp,
  DelOp,
  NopOp,
} from './operations';
import {type IClock, type ITimestampStruct, type ITimespanStruct, ts, Timestamp} from './clock';
import {isUint8Array} from '@jsonjoy.com/util/lib/buffers/isUint8Array';
import {Patch} from './Patch';
import {ORIGIN} from './constants';
import {VectorDelayedValue} from './builder/Tuple';
import {Konst} from './builder/Konst';
import {NodeBuilder} from './builder/DelayedValueBuilder';
 
const maybeConst = (x: unknown): boolean => {
  switch (typeof x) {
    case 'number':
    case 'boolean':
      return true;
    default:
      return x === null;
  }
};
 
/**
 * Utility class that helps in Patch construction.
 *
 * @category Patch
 */
export class PatchBuilder {
  /** The patch being constructed. */
  public patch: Patch;
 
  /**
   * Creates a new PatchBuilder instance.
   *
   * @param clock Clock to use for generating timestamps.
   */
  constructor(public clock: IClock) {
    this.patch = new Patch();
  }
 
  /**
   * Retrieve the sequence number of the next timestamp.
   *
   * @returns The next timestamp sequence number that will be used by the builder.
   */
  public nextTime(): number {
    return this.patch.nextTime() || this.clock.time;
  }
 
  /**
   * Returns the current {@link Patch} instance and resets the builder.
   *
   * @returns A new {@link Patch} instance containing all operations created
   *          using this builder.
   */
  public flush(): Patch {
    const patch = this.patch;
    this.patch = new Patch();
    return patch;
  }
 
  // --------------------------------------------------------- Basic operations
 
  /**
   * Create a new "obj" LWW-Map object.
   *
   * @returns ID of the new operation.
   */
  public obj(): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new NewObjOp(id));
    return id;
  }
 
  /**
   * Create a new "arr" RGA-Array object.
   *
   * @returns ID of the new operation.
   */
  public arr(): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new NewArrOp(id));
    return id;
  }
 
  /**
   * Create a new "vec" LWW-Array vector.
   *
   * @returns ID of the new operation.
   */
  public vec(): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new NewVecOp(id));
    return id;
  }
 
  /**
   * Create a new "str" RGA-String object.
   *
   * @returns ID of the new operation.
   */
  public str(): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new NewStrOp(id));
    return id;
  }
 
  /**
   * Create a new "bin" RGA-Binary object.
   *
   * @returns ID of the new operation.
   */
  public bin(): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new NewBinOp(id));
    return id;
  }
 
  /**
   * Create a new immutable constant JSON value. Can be anything, including
   * nested arrays and objects.
   *
   * @param value JSON value
   * @returns ID of the new operation.
   */
  public const(value: unknown): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new NewConOp(id, value));
    return id;
  }
 
  /**
   * Create a new "val" LWW-Register object. Can be anything, including
   * nested arrays and objects.
   *
   * @param val Reference to another object.
   * @returns ID of the new operation.
   * @todo Rename to `newVal`.
   */
  public val(): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new NewValOp(id));
    return id;
  }
 
  /**
   * Set value of document's root LWW-Register.
   *
   * @returns ID of the new operation.
   */
  public root(val: ITimestampStruct): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new InsValOp(id, ORIGIN, val));
    return id;
  }
 
  /**
   * Set fields of an "obj" object.
   *
   * @returns ID of the new operation.
   */
  public insObj(obj: ITimestampStruct, data: [key: string, value: ITimestampStruct][]): ITimestampStruct {
    this.pad();
    Iif (!data.length) throw new Error('EMPTY_TUPLES');
    const id = this.clock.tick(1);
    const op = new InsObjOp(id, obj, data);
    const span = op.span();
    Iif (span > 1) this.clock.tick(span - 1);
    this.patch.ops.push(op);
    return id;
  }
 
  /**
   * Set elements of a "vec" object.
   *
   * @returns ID of the new operation.
   */
  public insVec(obj: ITimestampStruct, data: [index: number, value: ITimestampStruct][]): ITimestampStruct {
    this.pad();
    Iif (!data.length) throw new Error('EMPTY_TUPLES');
    const id = this.clock.tick(1);
    const op = new InsVecOp(id, obj, data);
    const span = op.span();
    Iif (span > 1) this.clock.tick(span - 1);
    this.patch.ops.push(op);
    return id;
  }
 
  /**
   * Set value of a "val" object.
   *
   * @returns ID of the new operation.
   * @todo Rename to "insVal".
   */
  public setVal(obj: ITimestampStruct, val: ITimestampStruct): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    const op = new InsValOp(id, obj, val);
    this.patch.ops.push(op);
    return id;
  }
 
  /**
   * Insert a substring into a "str" object.
   *
   * @returns ID of the new operation.
   */
  public insStr(obj: ITimestampStruct, ref: ITimestampStruct, data: string): ITimestampStruct {
    this.pad();
    Iif (!data.length) throw new Error('EMPTY_STRING');
    const id = this.clock.tick(1);
    const op = new InsStrOp(id, obj, ref, data);
    const span = op.span();
    if (span > 1) this.clock.tick(span - 1);
    this.patch.ops.push(op);
    return id;
  }
 
  /**
   * Insert binary data into a "bin" object.
   *
   * @returns ID of the new operation.
   */
  public insBin(obj: ITimestampStruct, ref: ITimestampStruct, data: Uint8Array): ITimestampStruct {
    this.pad();
    Iif (!data.length) throw new Error('EMPTY_BINARY');
    const id = this.clock.tick(1);
    const op = new InsBinOp(id, obj, ref, data);
    const span = op.span();
    if (span > 1) this.clock.tick(span - 1);
    this.patch.ops.push(op);
    return id;
  }
 
  /**
   * Insert elements into an "arr" object.
   *
   * @returns ID of the new operation.
   */
  public insArr(arr: ITimestampStruct, ref: ITimestampStruct, data: ITimestampStruct[]): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    const op = new InsArrOp(id, arr, ref, data);
    const span = op.span();
    if (span > 1) this.clock.tick(span - 1);
    this.patch.ops.push(op);
    return id;
  }
 
  /**
   * Delete a span of operations.
   *
   * @param obj Object in which to delete something.
   * @param what List of time spans to delete.
   * @returns ID of the new operation.
   */
  public del(obj: ITimestampStruct, what: ITimespanStruct[]): ITimestampStruct {
    this.pad();
    const id = this.clock.tick(1);
    this.patch.ops.push(new DelOp(id, obj, what));
    return id;
  }
 
  /**
   * Operation that does nothing just skips IDs in the patch.
   *
   * @param span Length of the operation.
   * @returns ID of the new operation.
   *
   */
  public nop(span: number) {
    this.pad();
    const id = this.clock.tick(span);
    this.patch.ops.push(new NopOp(id, span));
    return id;
  }
 
  // --------------------------------------- JSON value construction operations
 
  /**
   * Run the necessary builder commands to create an arbitrary JSON object.
   */
  public jsonObj(obj: object): ITimestampStruct {
    const id = this.obj();
    const keys = Object.keys(obj);
    if (keys.length) {
      const tuples: [key: string, value: ITimestampStruct][] = [];
      for (const k of keys) {
        const value = (obj as any)[k];
        const valueId = value instanceof Timestamp ? value : maybeConst(value) ? this.const(value) : this.json(value);
        tuples.push([k, valueId]);
      }
      this.insObj(id, tuples);
    }
    return id;
  }
 
  /**
   * Run the necessary builder commands to create an arbitrary JSON array.
   */
  public jsonArr(arr: unknown[]): ITimestampStruct {
    const id = this.arr();
    if (arr.length) {
      const values: ITimestampStruct[] = [];
      for (const el of arr) values.push(this.json(el));
      this.insArr(id, id, values);
    }
    return id;
  }
 
  /**
   * Run builder commands to create a JSON string.
   */
  public jsonStr(str: string): ITimestampStruct {
    const id = this.str();
    if (str) this.insStr(id, id, str);
    return id;
  }
 
  /**
   * Run builder commands to create a binary data type.
   */
  public jsonBin(bin: Uint8Array): ITimestampStruct {
    const id = this.bin();
    if (bin.length) this.insBin(id, id, bin);
    return id;
  }
 
  /**
   * Run builder commands to create a JSON value.
   */
  public jsonVal(value: unknown): ITimestampStruct {
    const valId = this.val();
    const id = this.const(value);
    this.setVal(valId, id);
    return valId;
  }
 
  /**
   * Run builder commands to create a tuple.
   */
  public jsonVec(vector: unknown[]): ITimestampStruct {
    const id = this.vec();
    const length = vector.length;
    if (length) {
      const writes: [index: number, value: ITimestampStruct][] = [];
      for (let i = 0; i < length; i++) writes.push([i, this.constOrJson(vector[i])]);
      this.insVec(id, writes);
    }
    return id;
  }
 
  /**
   * Run the necessary builder commands to create any arbitrary JSON value.
   */
  public json(json: unknown): ITimestampStruct {
    if (json instanceof Timestamp) return json;
    if (json === undefined) return this.const(json);
    if (json instanceof Array) return this.jsonArr(json);
    if (isUint8Array(json)) return this.jsonBin(json);
    if (json instanceof VectorDelayedValue) return this.jsonVec(json.slots);
    if (json instanceof Konst) return this.const(json.val);
    if (json instanceof NodeBuilder) return json.build(this);
    switch (typeof json) {
      case 'object':
        return json === null ? this.jsonVal(json) : this.jsonObj(json!);
      case 'string':
        return this.jsonStr(json);
      case 'number':
      case 'boolean':
        return this.jsonVal(json);
    }
    throw new Error('INVALID_JSON');
  }
 
  /**
   * Given a JSON `value` creates the necessary builder commands to create
   * JSON CRDT Patch operations to construct the value. If the `value` is a
   * timestamp, it is returned as-is. If the `value` is a JSON primitive is
   * a number, boolean, or `null`, it is converted to a "con" data type. Otherwise,
   * the `value` is converted using the {@link PatchBuilder.json} method.
   *
   * @param value A JSON value for which to create JSON CRDT Patch construction operations.
   * @returns ID of the root constructed CRDT object.
   */
  public constOrJson(value: unknown): ITimestampStruct {
    if (value instanceof Timestamp) return value;
    return maybeConst(value) ? this.const(value) : this.json(value);
  }
 
  /**
   * Creates a "con" data type unless the value is already a timestamp, in which
   * case it is returned as-is.
   *
   * @param value Value to convert to a "con" data type.
   * @returns ID of the new "con" object.
   */
  public maybeConst(value: unknown | Timestamp): Timestamp {
    return value instanceof Timestamp ? value : this.const(value);
  }
 
  // ------------------------------------------------------------------ Private
 
  /**
   * Add padding "noop" operation if clock's time has jumped. This method checks
   * if clock has advanced past the ID of the last operation of the patch and,
   * if so, adds a "noop" operation to the patch to pad the gap.
   */
  public pad() {
    const nextTime = this.patch.nextTime();
    if (!nextTime) return;
    const drift = this.clock.time - nextTime;
    if (drift > 0) {
      const id = ts(this.clock.sid, nextTime);
      const padding = new NopOp(id, drift);
      this.patch.ops.push(padding);
    }
  }
}