Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 33 additions & 20 deletions core/projectify/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import {Stream} from 'stream';
// See the License for the specific language governing permissions and
// limitations under the License.

const PROJECT_ID_TOKEN = '{{projectId}}';
const PROJECT_ID_TOKEN_REGEX = /{{projectId}}/g;

/**
* Populate the `{{projectId}}` placeholder.
*
Expand All @@ -25,33 +28,43 @@ import {Stream} from 'stream';
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function replaceProjectIdToken(value: any, projectId: string): any {
if (Array.isArray(value)) {
value = (value as string[]).map(v => replaceProjectIdToken(v, projectId));
if (typeof value === 'string') {
if (value.includes(PROJECT_ID_TOKEN)) {
if (!projectId || projectId === PROJECT_ID_TOKEN) {
throw new MissingProjectIdError();
}
return value.replace(PROJECT_ID_TOKEN_REGEX, projectId);
}
return value;
}

if (value === null || typeof value !== 'object') {
return value;
}

if (
value !== null &&
typeof value === 'object' &&
!(value instanceof Buffer) &&
!(value instanceof Stream) &&
typeof value.hasOwnProperty === 'function'
) {
for (const opt in value) {
// eslint-disable-next-line no-prototype-builtins
if (value.hasOwnProperty(opt)) {
value[opt] = replaceProjectIdToken(value[opt], projectId);
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
const original = value[i];
const processed = replaceProjectIdToken(original, projectId);
if (processed !== original) {
value[i] = processed;
}
}
return value;
}
Comment thread
surbhigarg92 marked this conversation as resolved.
Comment on lines +45 to 54
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Mutating the input array in-place is a breaking change compared to the original implementation, which used .map() to return a new array. If a caller passes an array and expects it to remain unmodified, this in-place mutation will introduce unexpected side effects. Furthermore, if a frozen array contains a placeholder, attempting to mutate it in-place will throw a TypeError at runtime.

To preserve the performance benefits of avoiding allocations when no placeholders are present, while maintaining safety and backward compatibility, we can use a Copy-on-Write approach. We only clone the array if we actually detect a modified element.

Suggested change
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
const original = value[i];
const processed = replaceProjectIdToken(original, projectId);
if (processed !== original) {
value[i] = processed;
}
}
return value;
}
if (Array.isArray(value)) {
let cloned: any[] | null = null;
for (let i = 0; i < value.length; i++) {
const original = value[i];
const processed = replaceProjectIdToken(original, projectId);
if (processed !== original) {
if (!cloned) {
cloned = [...value];
}
cloned[i] = processed;
}
}
return cloned || value;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original implementation was already mutating values in-place for all nested objects

// Original implementation mutated objects in-place:
for (const opt in value) {
  if (value.hasOwnProperty(opt)) {
    value[opt] = replaceProjectIdToken(value[opt], projectId);
  }
}

To address the concern about frozen arrays/objects without triggering new allocations, we implemented a Selective-Write strategy.

const original = value[i];
const processed = replaceProjectIdToken(original, projectId);
if (processed !== original) {
  value[i] = processed; // Only writes if a placeholder was actually found & changed!
}


if (
typeof value === 'string' &&
(value as string).indexOf('{{projectId}}') > -1
) {
if (!projectId || projectId === '{{projectId}}') {
throw new MissingProjectIdError();
if (value instanceof Buffer || value instanceof Stream) {
return value;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we combine this check for Buffer and Stream with the other checks above for null and non-object primitives?

// Early return for null, primitives (i.e. booleans, numbers), Buffers, and Streams. These are non-traversable leaf nodes.
// Note this must come after the string check.
if (
    value === null ||
    typeof value !== 'object' ||
    value instanceof Buffer ||
    value instanceof Stream
) {
    return value;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont mind doing this change, but I was simply trying to micro-optimize here.

Chances of value having null, object or array is really high compared to Buffer or Stream. So I was trying to avoid this check value instanceof Buffer || value instanceof Stream for little later.

}

for (const key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
const original = value[key];
const processed = replaceProjectIdToken(original, projectId);
if (processed !== original) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this could be simplified using more modern syntax:

for (const key of Object.keys(value)) {
    value[key] = replaceProjectIdToken(value[key], projectId);
}

I don't think we need the additional if (processed !== original) because this function has already been modified to return the references in place?

Copy link
Copy Markdown
Contributor Author

@surbhigarg92 surbhigarg92 May 29, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Object.keys(value) allocates a brand new array of strings , this triggers garbage collection and degrades speed compared to for...in.

  2. if (processed !== original): selective-write check! - Without this check, the code will unconditionally attempt to write to value[key]. That means if a frozen object is passed (even one with no placeholders to replace), it will immediately crash with a TypeError. This check was intentionally added,

Earlier, this method was indirectly safe when receiving frozen arrays because the original implementation used .map(), which safely cloned the reference. Since we migrated off .map() to achieve better performance speedup via in-place mutation, we engineered the if (original !== processed) check to preserve that exact historical frozen-structure compatibility. Without it, the unconditional assignment in the Object.keys() snippet would trigger an immediate TypeError in strict mode on frozen structures, even when no replacements are made.

value[key] = processed;
}
}
value = (value as string).replace(/{{projectId}}/g, projectId);
}
Comment thread
surbhigarg92 marked this conversation as resolved.

return value;
Expand Down
38 changes: 38 additions & 0 deletions core/projectify/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ describe('projectId placeholder', () => {
],
},
],
simpleArray: ['A {{projectId}} Z'],
},
PROJECT_ID,
),
Expand Down Expand Up @@ -74,6 +75,7 @@ describe('projectId placeholder', () => {
],
},
],
simpleArray: ['A ' + PROJECT_ID + ' Z'],
},
);
});
Expand Down Expand Up @@ -116,6 +118,42 @@ describe('projectId placeholder', () => {
);
});

it('should not modify primitives without placeholder', () => {
assert.strictEqual(
replaceProjectIdToken('no-placeholder', PROJECT_ID),
'no-placeholder',
);
assert.strictEqual(replaceProjectIdToken(123, PROJECT_ID), 123);
assert.strictEqual(replaceProjectIdToken(true, PROJECT_ID), true);
assert.strictEqual(replaceProjectIdToken(null, PROJECT_ID), null);
assert.strictEqual(replaceProjectIdToken(undefined, PROJECT_ID), undefined);
});

it('should not modify arrays without placeholder', () => {
const array = [1, 2, 3];
assert.strictEqual(replaceProjectIdToken(array, PROJECT_ID), array);
});

it('should not modify objects without placeholder', () => {
const object = {a: 1, b: 2};
assert.strictEqual(replaceProjectIdToken(object, PROJECT_ID), object);
});

it('should traverse frozen arrays without placeholder safely', () => {
const frozenArray = Object.freeze(['no-placeholder', 123, true]);
const replacedArray = replaceProjectIdToken(frozenArray, PROJECT_ID);
assert.strictEqual(frozenArray, replacedArray);
});

it('should traverse frozen objects without placeholder safely', () => {
const frozenObject = Object.freeze({
prop: 'no-placeholder',
other: 123,
});
const replacedObject = replaceProjectIdToken(frozenObject, PROJECT_ID);
assert.strictEqual(frozenObject, replacedObject);
});

it('should not inject projectId into stream', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const transform = new stream.Transform() as any;
Expand Down
Loading