From 7056ba76040b9369d86c57838ef938c9d9ef73d8 Mon Sep 17 00:00:00 2001
From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com>
Date: Tue, 17 Dec 2024 12:54:59 -0700
Subject: [PATCH] fix: correctly escape field paths with multiple backslashes
 or backticks (#2259) (#2261)

Co-authored-by: Albert Nisbet <4309984+albertnis@users.noreply.github.com>
---
 dev/src/path.ts  |  2 +-
 dev/test/path.ts | 20 +++++++++++++++++---
 2 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/dev/src/path.ts b/dev/src/path.ts
index 73a57d0b7..bb16e122d 100644
--- a/dev/src/path.ts
+++ b/dev/src/path.ts
@@ -672,7 +672,7 @@ export class FieldPath extends Path<FieldPath> implements firestore.FieldPath {
       .map(str => {
         return UNESCAPED_FIELD_NAME_RE.test(str)
           ? str
-          : '`' + str.replace('\\', '\\\\').replace('`', '\\`') + '`';
+          : '`' + str.replace(/\\/g, '\\\\').replace(/`/g, '\\`') + '`';
       })
       .join('.');
   }
diff --git a/dev/test/path.ts b/dev/test/path.ts
index 805c50b6e..aa7627dcb 100644
--- a/dev/test/path.ts
+++ b/dev/test/path.ts
@@ -68,9 +68,23 @@ describe('ResourcePath', () => {
 
 describe('FieldPath', () => {
   it('encodes field names', () => {
-    const components = [['foo'], ['foo', 'bar'], ['.', '`'], ['\\']];
-
-    const results = ['foo', 'foo.bar', '`.`.`\\``', '`\\\\`'];
+    const components = [
+      ['foo'],
+      ['foo', 'bar'],
+      ['.', '`'],
+      ['\\'],
+      ['\\\\'],
+      ['``'],
+    ];
+
+    const results = [
+      'foo',
+      'foo.bar',
+      '`.`.`\\``',
+      '`\\\\`',
+      '`\\\\\\\\`',
+      '`\\`\\``',
+    ];
 
     for (let i = 0; i < components.length; ++i) {
       expect(new FieldPath(...components[i]).toString()).to.equal(results[i]);