All files / core/util Path.ts

94.93% Statements 131/138
80.36% Branches 45/56
96% Functions 24/25
94.57% Lines 122/129
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                                16x 16x             16x                 16x 8258x                 46861x 17309x     17309x 17309x 23707x 10201x 10201x     17309x   17309x   29552x 29552x       16x 44312x   34209x           16x 11908x           16x 22994x 22994x 22993x   22994x           16x 874x 874x         16x 4943x 4943x 5121x     4943x     16x 98x 98x 129x 129x     98x                 2354x 1177x           16x 298x   260x 260x 177x   260x             16x 6298x 6298x 4421x   6298x 2352x         912x     3946x 3946x 3991x       6298x           16x 37139x               16x 4366x 4366x 4366x 2018x 2348x 2348x                                   16x 28x 28x 28x 29x 29x   8x 4x               16x 305x 25x     280x         644x 2x       278x               16x 5584x 5584x 5584x 827x   4757x 6967x 3816x   3151x 3151x   941x   16x                       16x                   767x   767x   767x   767x 1117x   767x       16x 2088x       16x 2088x       16x   1321x 1321x   1321x 1321x 1321x     16x 1321x 1321x   1321x 1321x       16x 2088x                   2088x                               16x           16x  
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { nameCompare } from './util';
import { stringLength } from '@firebase/util';
/**
 * An immutable object representing a parsed path.  It's immutable so that you
 * can pass them around to other functions without worrying about them changing
 * it.
 */
 
export class Path {
  private pieces_: string[];
  private pieceNum_: number;
 
  /**
   * Singleton to represent an empty path
   *
   * @const
   */
  static get Empty() {
    return new Path('');
  }
 
  /**
   * @param {string|Array.<string>} pathOrString Path string to parse,
   *      or another path, or the raw tokens array
   * @param {number=} pieceNum
   */
  constructor(pathOrString: string | string[], pieceNum?: number) {
    if (pieceNum === void 0) {
      this.pieces_ = (pathOrString as string).split('/');
 
      // Remove empty pieces.
      let copyTo = 0;
      for (let i = 0; i < this.pieces_.length; i++) {
        if (this.pieces_[i].length > 0) {
          this.pieces_[copyTo] = this.pieces_[i];
          copyTo++;
        }
      }
      this.pieces_.length = copyTo;
 
      this.pieceNum_ = 0;
    } else {
      this.pieces_ = pathOrString as string[];
      this.pieceNum_ = pieceNum;
    }
  }
 
  getFront(): string | null {
    if (this.pieceNum_ >= this.pieces_.length) return null;
 
    return this.pieces_[this.pieceNum_];
  }
 
  /**
   * @return {number} The number of segments in this path
   */
  getLength(): number {
    return this.pieces_.length - this.pieceNum_;
  }
 
  /**
   * @return {!Path}
   */
  popFront(): Path {
    let pieceNum = this.pieceNum_;
    if (pieceNum < this.pieces_.length) {
      pieceNum++;
    }
    return new Path(this.pieces_, pieceNum);
  }
 
  /**
   * @return {?string}
   */
  getBack(): string | null {
    Eif (this.pieceNum_ < this.pieces_.length)
      return this.pieces_[this.pieces_.length - 1];
 
    return null;
  }
 
  toString(): string {
    let pathString = '';
    for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
      Eif (this.pieces_[i] !== '') pathString += '/' + this.pieces_[i];
    }
 
    return pathString || '/';
  }
 
  toUrlEncodedString(): string {
    let pathString = '';
    for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
      Eif (this.pieces_[i] !== '')
        pathString += '/' + encodeURIComponent(String(this.pieces_[i]));
    }
 
    return pathString || '/';
  }
 
  /**
   * Shallow copy of the parts of the path.
   *
   * @param {number=} begin
   * @return {!Array<string>}
   */
  slice(Ebegin: number = 0): string[] {
    return this.pieces_.slice(this.pieceNum_ + begin);
  }
 
  /**
   * @return {?Path}
   */
  parent(): Path | null {
    if (this.pieceNum_ >= this.pieces_.length) return null;
 
    const pieces = [];
    for (let i = this.pieceNum_; i < this.pieces_.length - 1; i++)
      pieces.push(this.pieces_[i]);
 
    return new Path(pieces, 0);
  }
 
  /**
   * @param {string|!Path} childPathObj
   * @return {!Path}
   */
  child(childPathObj: string | Path): Path {
    const pieces = [];
    for (let i = this.pieceNum_; i < this.pieces_.length; i++)
      pieces.push(this.pieces_[i]);
 
    if (childPathObj instanceof Path) {
      for (
        let i = childPathObj.pieceNum_;
        i < childPathObj.pieces_.length;
        i++
      ) {
        pieces.push(childPathObj.pieces_[i]);
      }
    } else {
      const childPieces = childPathObj.split('/');
      for (let i = 0; i < childPieces.length; i++) {
        if (childPieces[i].length > 0) pieces.push(childPieces[i]);
      }
    }
 
    return new Path(pieces, 0);
  }
 
  /**
   * @return {boolean} True if there are no segments in this path
   */
  isEmpty(): boolean {
    return this.pieceNum_ >= this.pieces_.length;
  }
 
  /**
   * @param {!Path} outerPath
   * @param {!Path} innerPath
   * @return {!Path} The path from outerPath to innerPath
   */
  static relativePath(outerPath: Path, innerPath: Path): Path {
    const outer = outerPath.getFront(),
      inner = innerPath.getFront();
    if (outer === null) {
      return innerPath;
    } else Eif (outer === inner) {
      return Path.relativePath(outerPath.popFront(), innerPath.popFront());
    } else {
      throw new Error(
        'INTERNAL ERROR: innerPath (' +
          innerPath +
          ') is not within ' +
          'outerPath (' +
          outerPath +
          ')'
      );
    }
  }
 
  /**
   * @param {!Path} left
   * @param {!Path} right
   * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.
   */
  static comparePaths(left: Path, right: Path): number {
    const leftKeys = left.slice();
    const rightKeys = right.slice();
    for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
      const cmp = nameCompare(leftKeys[i], rightKeys[i]);
      if (cmp !== 0) return cmp;
    }
    if (leftKeys.length === rightKeys.length) return 0;
    return leftKeys.length < rightKeys.length ? -1 : 1;
  }
 
  /**
   *
   * @param {Path} other
   * @return {boolean} true if paths are the same.
   */
  equals(other: Path): boolean {
    if (this.getLength() !== other.getLength()) {
      return false;
    }
 
    for (
      let i = this.pieceNum_, j = other.pieceNum_;
      i <= this.pieces_.length;
      i++, j++
    ) {
      if (this.pieces_[i] !== other.pieces_[j]) {
        return false;
      }
    }
 
    return true;
  }
 
  /**
   *
   * @param {!Path} other
   * @return {boolean} True if this path is a parent (or the same as) other
   */
  contains(other: Path): boolean {
    let i = this.pieceNum_;
    let j = other.pieceNum_;
    if (this.getLength() > other.getLength()) {
      return false;
    }
    while (i < this.pieces_.length) {
      if (this.pieces_[i] !== other.pieces_[j]) {
        return false;
      }
      ++i;
      ++j;
    }
    return true;
  }
} // end Path
 
/**
 * Dynamic (mutable) path used to count path lengths.
 *
 * This class is used to efficiently check paths for valid
 * length (in UTF8 bytes) and depth (used in path validation).
 *
 * Throws Error exception if path is ever invalid.
 *
 * The definition of a path always begins with '/'.
 */
export class ValidationPath {
  /** @type {!Array<string>} */
  private parts_: string[];
  /** @type {number} Initialize to number of '/' chars needed in path. */
  private byteLength_: number;
 
  /**
   * @param {!Path} path Initial Path.
   * @param {string} errorPrefix_ Prefix for any error messages.
   */
  constructor(path: Path, private errorPrefix_: string) {
    /** @type {!Array<string>} */
    this.parts_ = path.slice();
    /** @type {number} Initialize to number of '/' chars needed in path. */
    this.byteLength_ = Math.max(1, this.parts_.length);
 
    for (let i = 0; i < this.parts_.length; i++) {
      this.byteLength_ += stringLength(this.parts_[i]);
    }
    this.checkValid_();
  }
 
  /** @const {number} Maximum key depth. */
  static get MAX_PATH_DEPTH() {
    return 32;
  }
 
  /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */
  static get MAX_PATH_LENGTH_BYTES() {
    return 768;
  }
 
  /** @param {string} child */
  push(child: string) {
    // Count the needed '/'
    Eif (this.parts_.length > 0) {
      this.byteLength_ += 1;
    }
    this.parts_.push(child);
    this.byteLength_ += stringLength(child);
    this.checkValid_();
  }
 
  pop() {
    const last = this.parts_.pop();
    this.byteLength_ -= stringLength(last);
    // Un-count the previous '/'
    Eif (this.parts_.length > 0) {
      this.byteLength_ -= 1;
    }
  }
 
  private checkValid_() {
    Iif (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {
      throw new Error(
        this.errorPrefix_ +
          'has a key path longer than ' +
          ValidationPath.MAX_PATH_LENGTH_BYTES +
          ' bytes (' +
          this.byteLength_ +
          ').'
      );
    }
    Iif (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {
      throw new Error(
        this.errorPrefix_ +
          'path specified exceeds the maximum depth that can be written (' +
          ValidationPath.MAX_PATH_DEPTH +
          ') or object contains a cycle ' +
          this.toErrorString()
      );
    }
  }
 
  /**
   * String for use in error messages - uses '.' notation for path.
   *
   * @return {string}
   */
  toErrorString(): string {
    if (this.parts_.length == 0) {
      return '';
    }
    return "in property '" + this.parts_.join('.') + "'";
  }
}