From 75ea4dd2559bdb0b60a47a9d753c8358fd786f4c Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 24 Nov 2026 16:49:18 -0500 Subject: [PATCH 1/7] feat(core): Add experimental minification-independent function fingerprint Function fingerprints in SDK config reports hash the minified source, so a bundler renaming one helper changes them with no code change. This fingerprints a token stream instead, where renamed names, whitespace, comments, quote styles and number spellings don't matter. It isn't wired into the report yet. --- .../core/src/utils/fingerprintFunction.ts | 245 ++++++++++++++++++ .../lib/utils/fingerprintFunction.test.ts | 130 ++++++++++ 2 files changed, 375 insertions(+) create mode 100644 packages/core/src/utils/fingerprintFunction.ts create mode 100644 packages/core/test/lib/utils/fingerprintFunction.test.ts diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts new file mode 100644 index 000000000000..e9bfee62cb7d --- /dev/null +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -0,0 +1,245 @@ +import { fnv1a32 } from './hash'; + +/** + * Keywords minifiers never rename and that change what a function does, plus `undefined`, which they spell `void 0`. + * Contextual words (`async`, `of`, `get`, `set`, `static`) are left out on purpose: minifiers may use them as names. + * So are words an options callback is very unlikely to contain (`class`, `extends`, `super`, `yield`, `import`, `do`, + * `export`, `debugger`, `with`), to keep the list short. They are treated as ordinary names. + */ +const KEYWORDS = new Set( + 'break catch const continue default delete else finally for function if instanceof let new switch throw try var while await return typeof void in case this null true false undefined'.split( + ' ', + ), +); + +/** + * After these tokens a `{` opens an object literal rather than a block. + */ +const OBJECT_CONTEXT = new Set('( [ , = : ? ?? || && ! ... return typeof void in case'.split(' ')); + +/** + * After these keywords, as after any name or literal, a `/` is a division rather than the start of a regex literal. + */ +const VALUE_KEYWORDS = new Set('this null true false undefined'.split(' ')); + +/** + * Matches the longest punctuator at `lastIndex`, or else any one character. `a?.5:b` is a conditional, not optional + * chaining. A match is at most four characters long, so it cannot backtrack over the input. + */ +const PUNCTUATOR = /\.\.\.|=>|\?\.(?!\d)|\?\?=?|[=!]==?|\+\+|--|>>>=?|([*&|<>])\1?=?|[-+/%^]=|[^]/y; + +/** + * The last two are a no-break space and a byte order mark. + */ +const WHITESPACE = ' \n\t\r\u00a0\ufeff'; + +/** + * Fingerprints a function's behavior rather than its text: identifiers a minifier renames, whitespace, comments, + * quote styles, number spellings and common minifier rewrites don't change the result. + * + * Inlined helpers, reordered operands, closures over different values and engine-specific source text still do. + */ +export function fingerprintFunction(fn: (...args: never[]) => unknown): string { + let source: string; + try { + source = Function.prototype.toString.call(fn); + } catch { + return 'unknown'; + } + + return fnv1a32(tokenize(source).join(' ')); +} + +/** + * Splits source into tokens in their minification-independent form, in one linear pass. Unterminated strings, comments + * and regexes run to the end of the input. + */ +// oxlint-disable-next-line complexity +export function tokenize(src: string): string[] { + const tokens: string[] = []; + // What each open bracket belongs to: `true` for an object literal, `false` for a block, `(` or `[`, `null` for a + // template `${`. Only names directly inside an object literal can be its keys. + const braces: Array = []; + const length = src.length; + let i = 0; + // Whether a `/` here would be a division rather than the start of a regex literal. + let afterValue: boolean | undefined; + // The name of the previous token when it is an identifier that starts an object literal entry. + let key: string | undefined; + + const push = (token: string, endsValue?: boolean): void => { + tokens.push(token); + afterValue = endsValue; + key = ''; + }; + + while (i < length) { + const start = i; + const ch = src[i] as string; + const next = src[i + 1] as string; + const previous = tokens[tokens.length - 1]; + + if (WHITESPACE.includes(ch)) { + i++; + continue; + } + + if (ch === '/' && (next === '/' || next === '*')) { + const end = src.indexOf(next === '/' ? '\n' : '*/', i + 2); + i = end < 0 ? length : end + (next === '/' ? 1 : 2); + continue; + } + + if (ch === '"' || ch === "'") { + let value = ''; + for (i++; i < length && src[i] !== ch; i++) { + value += + src[i] !== '\\' + ? src[i] + : // An escaped quote means the same thing whichever quote style the minifier picked. + src[++i] === '"' || src[i] === "'" + ? src[i] + : src.slice(i - 1, i + 1); + } + i++; + push(JSON.stringify(value), true); + continue; + } + + // A template part runs from the opening backtick, or from the `}` that ends a substitution, up to the closing + // backtick or the next `${`. + if (ch === '`' || (ch === '}' && braces.pop() === null)) { + let text = ''; + i++; + while (i < length) { + const c = src[i++] as string; + text += c; + if (c === '\\') { + text += src.slice(i, ++i); + } else if (c === '`') { + break; + } else if (c === '$' && src[i] === '{') { + text += src[i++]; + braces.push(null); + break; + } + } + const isClosed = text.endsWith('`'); + // A template without substitutions is a plain string to a minifier. + push(ch === '`' && isClosed ? JSON.stringify(text.slice(0, -1)) : `\`${text}`, isClosed); + continue; + } + + if (isDigit(ch) || (ch === '.' && isDigit(next))) { + // Hex digits include `e`, so `0x1e+1` is an addition, not an exponent. + const isHex = ch === '0' && (next === 'x' || next === 'X'); + let c; + while ( + ++i < length && + (isIdentifierChar((c = src[i] as string)) || + c === '.' || + (!isHex && (c === '+' || c === '-') && (src[i - 1] === 'e' || src[i - 1] === 'E'))) + ); + let number = src.slice(start, i); + if (previous === 'void' && number === '0') { + // `void 0` is how minifiers spell `undefined`. + tokens.pop(); + number = 'undefined'; + } else if (previous === '!' && (number === '0' || number === '1')) { + // `!0` and `!1` are how minifiers spell `true` and `false`. + tokens.pop(); + number = number === '0' ? 'true' : 'false'; + } + push(canonicalNumber(number), true); + continue; + } + + if (isIdentifierStart(ch)) { + while (++i < length && isIdentifierChar(src[i] as string)); + const word = src.slice(start, i); + if (KEYWORDS.has(word)) { + push(word, VALUE_KEYWORDS.has(word)); + } else if (previous === '.' || previous === '?.' || previous === '#') { + // `a.b`, `a?.b` and `#b`: property names survive minification. + push(JSON.stringify(word), true); + } else { + // Without scope analysis a global can't be told from a local, so every other name is anonymous. + push('_', true); + if (braces[braces.length - 1] && (previous === '{' || previous === ',')) { + key = word; + } + } + continue; + } + + if (ch === '/' && !afterValue) { + let inClass = false; + let c; + for (i++; i < length && (c = src[i]) !== '\n' && (c !== '/' || inClass); i++) { + if (c === '\\') { + i++; + } else { + inClass = c === '[' || (c !== ']' && inClass); + } + } + // The closing slash, then the flags. + while (++i < length && isIdentifierChar(src[i] as string)); + push(src.slice(start, i), true); + continue; + } + + if (ch === '{') { + // Only a template part can end in `${`: strings are quoted and regexes end at a slash or a newline. + braces.push(!previous || OBJECT_CONTEXT.has(previous) || previous.endsWith('${')); + } else if (ch === '(' || ch === '[') { + braces.push(false); + } else if (ch === ')' || ch === ']') { + braces.pop(); + } + + PUNCTUATOR.lastIndex = i; + PUNCTUATOR.test(src); + i = PUNCTUATOR.lastIndex; + // Minifiers turn `===` and `!==` into `==` and `!=` where both sides are known to share a type. Those two are the + // only three-character punctuators with `=` in the middle. + const punctuator = src.slice(start, next === '=' && i - start > 2 ? i - 1 : i); + + if (key && ':(,}'.includes(punctuator)) { + // Object keys survive minification too. + tokens[tokens.length - 1] = JSON.stringify(key); + // Shorthand `{event}` becomes `{event:e}` once the binding is renamed. + if (',}'.includes(punctuator)) { + tokens.push(':', previous as string); + } + } + + push(punctuator, ')]}'.includes(ch)); + } + + return tokens; +} + +/** + * Spells a number the same way however the source wrote it, since minifiers rewrite `0.10` to `.1` and `1000` to `1e3`. + */ +function canonicalNumber(raw: string): string { + const digits = raw.replace(/_/g, ''); + if (digits.endsWith('n')) { + return digits; + } + const value = Number(digits); + + return Number.isNaN(value) ? raw : String(value); +} + +function isDigit(ch: string): boolean { + return ch >= '0' && ch <= '9'; +} + +function isIdentifierStart(ch: string): boolean { + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$' || ch > '\x7f'; +} + +function isIdentifierChar(ch: string): boolean { + return isIdentifierStart(ch) || isDigit(ch); +} diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts new file mode 100644 index 000000000000..a4bde4c9da77 --- /dev/null +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest'; +import { fingerprintFunction, tokenize } from '../../../src/utils/fingerprintFunction'; + +const norm = (src: string): string => tokenize(src).join(' '); + +describe('fingerprintFunction', () => { + describe('stays the same when only minification changes', () => { + it.each([ + ['renamed locals and imports', 'e=>n(e)?null:e', 't=>r(t)?null:t'], + ['spread of a renamed local', 'e=>({...e.tags})', 't=>({...t.tags})'], + ['whitespace', 'e => e', 'e=>e'], + ['comments', 'e=>e // keep all\n', 'e=>/* keep */e'], + ['quote style', `e=>e.type==="error"`, `e=>e.type==='error'`], + ['strict equality rewritten', `e=>e.type==="error"`, `e=>e.type=="error"`], + ['escaped quotes', `e=>"it's"`, `e=>'it\\'s'`], + ['template without substitutions', 'e=>`drop`', `e=>"drop"`], + ['number spelling', 'e=>e<0.1', 'e=>e<.1'], + ['exponent', 'e=>e>1000', 'e=>e>1e3'], + ['numeric separators', 'e=>e>1_000', 'e=>e>1000'], + ['void 0', 'e=>undefined', 'e=>void 0'], + ['!0 and !1', 'e=>[true,false]', 'e=>[!0,!1]'], + ['shorthand property', '({event})=>({event})', '({event:e})=>({event:e})'], + ['renamed call arguments inside an object', 'e=>({a:f(x,y,z)})', 't=>({a:g(p,q,r)})'], + ['renamed array items inside an object', 'e=>({a:[x,y,z]})', 't=>({a:[p,q,r]})'], + ['renamed arrow parameters inside an object', 'e=>({a:(x,y,z)=>x})', 't=>({a:(p,q,r)=>p})'], + ])('%s', (_label, a, b) => { + expect(norm(a)).toBe(norm(b)); + }); + }); + + describe('changes when behavior changes', () => { + it.each([ + ['always null vs passthrough', '()=>null', 'e=>e'], + ['return null vs return event', 'function(e){return null}', 'function(e){return e}'], + ['return undefined vs return event', 'function(e){return undefined}', 'function(e){return e}'], + ['property', 'e=>e.exception?e:null', 'e=>e.message?e:null'], + ['optional chaining property', 'e=>e?.exception?e:null', 'e=>e?.message?e:null'], + ['string literal', `e=>e.type==="transaction"?null:e`, `e=>e.type==="error"?null:e`], + ['bracket key', `e=>e["exception"]?e:null`, `e=>e["message"]?e:null`], + ['template literal', 'e=>`${e.level}:drop`', 'e=>`${e.level}:keep`'], + ['regex literal', 'e=>/foo/.test(e.message)?null:e', 'e=>/bar/.test(e.message)?null:e'], + ['regex flags', 'e=>/foo/i.test(e)', 'e=>/foo/g.test(e)'], + ['number', 'e=>Math.random()<0.1?e:null', 'e=>Math.random()<1?e:null'], + ['branches swapped', 'e=>n(e)?null:e', 'e=>n(e)?e:null'], + ['throw vs return', 'e=>{throw e}', 'e=>{return e}'], + ['object key', 'e=>({level:e})', 'e=>({type:e})'], + ['private field', 'e=>e.#a', 'e=>e.#b'], + ])('%s', (_label, a, b) => { + expect(norm(a)).not.toBe(norm(b)); + }); + }); + + describe('tokenizer', () => { + it('tells a regex from a division', () => { + expect(norm('e=>e/2/1')).toBe('_ => _ / 2 / 1'); + expect(norm('e=>/2/.test(e)')).toBe('_ => /2/ . "test" ( _ )'); + }); + + it('keeps regex character classes containing slashes intact', () => { + expect(norm('e=>/[/]a/.test(e)')).toBe('_ => /[/]a/ . "test" ( _ )'); + }); + + it('handles nested template literals and object literals in substitutions', () => { + expect(norm('e=>`a${`b${e}`}c${({k:e})}`')).toBe('_ => `a${ `b${ _ `` `c${ ( { "k" : _ } ) ``'); + }); + + it('treats a block body as a block, not an object', () => { + expect(norm('e=>{a:e}')).toBe('_ => { _ : _ }'); + }); + + it('survives unterminated input', () => { + expect(() => norm('e=>"abc')).not.toThrow(); + expect(() => norm('e=>`abc${')).not.toThrow(); + expect(() => norm('e=>/abc')).not.toThrow(); + expect(() => norm('e=>/* abc')).not.toThrow(); + expect(() => norm('}}}}')).not.toThrow(); + }); + + it('matches the longest punctuator', () => { + expect(norm('a>>>=b>>>c>>=d>>e>=f>g')).toBe('_ >>>= _ >>> _ >>= _ >> _ >= _ > _'); + expect(norm('a??=b??c?.d?e:f')).toBe('_ ??= _ ?? _ ?. "d" ? _ : _'); + expect(norm('a**=b**c*=d*e')).toBe('_ **= _ ** _ *= _ * _'); + expect(norm('a&&=b||=c&&d||e&f|g^=h')).toBe('_ &&= _ ||= _ && _ || _ & _ | _ ^= _'); + expect(norm('a=>b!==c===d!=e==f=!g')).toBe('_ => _ != _ == _ != _ == _ = ! _'); + expect(norm('a++ +b-- -c+=d-=e')).toBe('_ ++ + _ -- - _ += _ -= _'); + expect(norm('a++=b')).toBe('_ ++ = _'); + expect(norm('f(...a,..b)')).toBe('_ ( ... _ , . . "b" )'); + }); + + it('reads `?.` before a digit as a conditional', () => { + expect(norm('a?.5:b')).toBe('_ ? 0.5 : _'); + }); + + it('keeps an exponent sign in a number, except in hex', () => { + expect(norm('1e+3+0x1e+1')).toBe('1000 + 30 + 1'); + }); + + it('only rewrites `void 0`, `!0` and `!1`, and spells numbers canonically', () => { + expect(norm('[void 0x0,void 1,!2,!0n]')).toBe('[ void 0 , void 1 , ! 2 , ! 0n ]'); + expect(norm('1_000+0.10+.1+1_0n')).toBe('1000 + 0.1 + 0.1 + 10n'); + }); + + it('keeps object keys next to calls and arrays, and in objects nested inside them', () => { + expect(norm('({a:f(x,y),b:[y,{c}],d})')).toBe('( { "a" : _ ( _ , _ ) , "b" : [ _ , { "c" : _ } ] , "d" : _ } )'); + }); + + it('keeps object keys and method names', () => { + expect(norm('e=>({a:1,b(){},c,...d})')).toBe('_ => ( { "a" : 1 , "b" ( ) { } , "c" : _ , ... _ } )'); + }); + + it('keeps `undefined` but no other global', () => { + expect(norm('e=>Math.now()===undefined')).toBe('_ => _ . "now" ( ) == undefined'); + }); + + it('tells a regex from a division after keywords and closing brackets', () => { + expect(norm('return/a/g')).toBe('return /a/g'); + expect(norm('this/a/g')).toBe('this / _ / _'); + expect(norm('(a)/b/c')).toBe('( _ ) / _ / _'); + }); + + it('treats an escaped backtick at the end of an unterminated template like a closing one', () => { + expect(norm('`a\\`')).toBe('"a\\\\"'); + }); + }); + + it('fingerprints functions', () => { + expect(fingerprintFunction(e => e)).toBe(fingerprintFunction(t => t)); + expect(fingerprintFunction(() => null)).not.toBe(fingerprintFunction(e => e)); + }); +}); From f52cfde2a892465871d7c4935cea088d5f65a682 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 24 Nov 2026 17:19:21 -0500 Subject: [PATCH 2/7] feat(core): Use the token fingerprint for functions in SDK config reports --- .../core/src/integrations/reportSdkConfig.ts | 3 ++- .../lib/integrations/reportSdkConfig.test.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/core/src/integrations/reportSdkConfig.ts b/packages/core/src/integrations/reportSdkConfig.ts index 7b4160e887ba..286bcd1b1028 100644 --- a/packages/core/src/integrations/reportSdkConfig.ts +++ b/packages/core/src/integrations/reportSdkConfig.ts @@ -6,6 +6,7 @@ import { count } from '../metrics/public-api'; import { Scope } from '../scope'; import type { Integration, IntegrationFn } from '../types/integration'; import { debug } from '../utils/debug-logger'; +import { fingerprintFunction } from '../utils/fingerprintFunction'; import { fnv1a32 } from '../utils/hash'; import { isPlainObject } from '../utils/is'; import { isBrowser } from '../utils/isBrowser'; @@ -55,7 +56,7 @@ export const experimentalReportSdkConfigIntegration = defineIntegration(_experim // and unsupported values with fingerprints before hashing the config. function serialize(value: unknown, ancestors = new Set()): unknown { if (typeof value === 'function') { - return `[Function:${fnv1a32(Function.prototype.toString.call(value))}]`; + return `[Function:${fingerprintFunction(value as (...args: never[]) => unknown)}]`; } // JSON throws on bigints and omits symbols. diff --git a/packages/core/test/lib/integrations/reportSdkConfig.test.ts b/packages/core/test/lib/integrations/reportSdkConfig.test.ts index 009ef6aa9760..4e444314e3cd 100644 --- a/packages/core/test/lib/integrations/reportSdkConfig.test.ts +++ b/packages/core/test/lib/integrations/reportSdkConfig.test.ts @@ -226,6 +226,23 @@ describe('experimentalReportSdkConfigIntegration', () => { expect((payload.options as Record).initialScope).toMatch(/^\[Function:\w+\]$/); }); + it('reports callbacks that differ only in their local names as the same function', () => { + const report = (beforeSend: (event: unknown) => unknown): Record => + reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + ...captureOptionsSetByUser({ beforeSend, integrations: [experimentalReportSdkConfigIntegration()] }), + }), + ).options as Record; + + const original = report(event => event); + const renamed = report(e => e); + const dropsEverything = report(() => null); + + expect(renamed.beforeSend).toBe(original.beforeSend); + expect(dropsEverything.beforeSend).not.toBe(original.beforeSend); + }); + it('reports the names of the default integrations the user passed', () => { const userOptions = captureOptionsSetByUser({ defaultIntegrations: [experimentalReportSdkConfigIntegration()], From d6297ce0161493726b969e9e21f1dd4b052fe466 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 24 Nov 2026 17:20:03 -0500 Subject: [PATCH 3/7] fix(core): Keep shorthand keys with defaults in function fingerprints Minifiers expand a renamed destructuring default like `{level='error'}` to `{level:e='error'}`, so the key is now kept for `=` the same way it is for shorthand properties. --- packages/core/src/utils/fingerprintFunction.ts | 6 +++--- packages/core/test/lib/utils/fingerprintFunction.test.ts | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts index e9bfee62cb7d..cdac2e2caf68 100644 --- a/packages/core/src/utils/fingerprintFunction.ts +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -204,11 +204,11 @@ export function tokenize(src: string): string[] { // only three-character punctuators with `=` in the middle. const punctuator = src.slice(start, next === '=' && i - start > 2 ? i - 1 : i); - if (key && ':(,}'.includes(punctuator)) { + if (key && ':(,}='.includes(punctuator)) { // Object keys survive minification too. tokens[tokens.length - 1] = JSON.stringify(key); - // Shorthand `{event}` becomes `{event:e}` once the binding is renamed. - if (',}'.includes(punctuator)) { + // Shorthand `{event}` becomes `{event:e}` once the binding is renamed, and `{level=1}` becomes `{level:e=1}`. + if (',}='.includes(punctuator)) { tokens.push(':', previous as string); } } diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts index a4bde4c9da77..99a4ea8224ce 100644 --- a/packages/core/test/lib/utils/fingerprintFunction.test.ts +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -20,6 +20,7 @@ describe('fingerprintFunction', () => { ['void 0', 'e=>undefined', 'e=>void 0'], ['!0 and !1', 'e=>[true,false]', 'e=>[!0,!1]'], ['shorthand property', '({event})=>({event})', '({event:e})=>({event:e})'], + ['destructuring default', "({level='error'})=>level", "({level:e='error'})=>e"], ['renamed call arguments inside an object', 'e=>({a:f(x,y,z)})', 't=>({a:g(p,q,r)})'], ['renamed array items inside an object', 'e=>({a:[x,y,z]})', 't=>({a:[p,q,r]})'], ['renamed arrow parameters inside an object', 'e=>({a:(x,y,z)=>x})', 't=>({a:(p,q,r)=>p})'], From 5e7a197fb94fefa6b21e72b87acc432337101501 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 24 Nov 2026 18:32:09 -0500 Subject: [PATCH 4/7] fix(core): Read a slash after postfix increments as division in function fingerprints --- packages/core/src/utils/fingerprintFunction.ts | 3 ++- packages/core/test/lib/utils/fingerprintFunction.test.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts index cdac2e2caf68..6e5c966005f3 100644 --- a/packages/core/src/utils/fingerprintFunction.ts +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -213,7 +213,8 @@ export function tokenize(src: string): string[] { } } - push(punctuator, ')]}'.includes(ch)); + // A regex can't follow postfix `++` or `--`. + push(punctuator, ')]}'.includes(ch) || punctuator == '++' || punctuator == '--'); } return tokens; diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts index 99a4ea8224ce..2620f246eed0 100644 --- a/packages/core/test/lib/utils/fingerprintFunction.test.ts +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -117,6 +117,8 @@ describe('fingerprintFunction', () => { expect(norm('return/a/g')).toBe('return /a/g'); expect(norm('this/a/g')).toBe('this / _ / _'); expect(norm('(a)/b/c')).toBe('( _ ) / _ / _'); + expect(norm('e=>e++/2+n(e)')).toBe('_ => _ ++ / 2 + _ ( _ )'); + expect(norm('e=>e--/2')).toBe('_ => _ -- / 2'); }); it('treats an escaped backtick at the end of an unterminated template like a closing one', () => { From a049f41f83d52aa0de6fdb42718583c364ba2f35 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 24 Nov 2026 18:42:01 -0500 Subject: [PATCH 5/7] fix(core): Keep declaration and throw object keys, and regexes after blocks, in function fingerprints --- packages/core/src/utils/fingerprintFunction.ts | 11 +++++++---- .../core/test/lib/utils/fingerprintFunction.test.ts | 6 ++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts index 6e5c966005f3..d55853a52bb6 100644 --- a/packages/core/src/utils/fingerprintFunction.ts +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -15,7 +15,9 @@ const KEYWORDS = new Set( /** * After these tokens a `{` opens an object literal rather than a block. */ -const OBJECT_CONTEXT = new Set('( [ , = : ? ?? || && ! ... return typeof void in case'.split(' ')); +const OBJECT_CONTEXT = new Set( + '( [ , = : ? ?? || && ! ... return typeof void in case const let var throw await'.split(' '), +); /** * After these keywords, as after any name or literal, a `/` is a division rather than the start of a regex literal. @@ -106,9 +108,10 @@ export function tokenize(src: string): string[] { continue; } + const closes = ch === '}' ? braces.pop() : undefined; // A template part runs from the opening backtick, or from the `}` that ends a substitution, up to the closing // backtick or the next `${`. - if (ch === '`' || (ch === '}' && braces.pop() === null)) { + if (ch === '`' || closes === null) { let text = ''; i++; while (i < length) { @@ -213,8 +216,8 @@ export function tokenize(src: string): string[] { } } - // A regex can't follow postfix `++` or `--`. - push(punctuator, ')]}'.includes(ch) || punctuator == '++' || punctuator == '--'); + // A regex can follow a block's `}` but not an object's, nor postfix `++` or `--`. + push(punctuator, ')]'.includes(ch) || closes === true || punctuator == '++' || punctuator == '--'); } return tokens; diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts index 2620f246eed0..33c269772562 100644 --- a/packages/core/test/lib/utils/fingerprintFunction.test.ts +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -21,6 +21,7 @@ describe('fingerprintFunction', () => { ['!0 and !1', 'e=>[true,false]', 'e=>[!0,!1]'], ['shorthand property', '({event})=>({event})', '({event:e})=>({event:e})'], ['destructuring default', "({level='error'})=>level", "({level:e='error'})=>e"], + ['destructured declaration', 'e=>{const{event}=e;return event}', 'e=>{const{event:t}=e;return t}'], ['renamed call arguments inside an object', 'e=>({a:f(x,y,z)})', 't=>({a:g(p,q,r)})'], ['renamed array items inside an object', 'e=>({a:[x,y,z]})', 't=>({a:[p,q,r]})'], ['renamed arrow parameters inside an object', 'e=>({a:(x,y,z)=>x})', 't=>({a:(p,q,r)=>p})'], @@ -46,6 +47,9 @@ describe('fingerprintFunction', () => { ['throw vs return', 'e=>{throw e}', 'e=>{return e}'], ['object key', 'e=>({level:e})', 'e=>({type:e})'], ['private field', 'e=>e.#a', 'e=>e.#b'], + ['destructured key', 'e=>{const{exception:t}=e;return t}', 'e=>{const{message:t}=e;return t}'], + ['thrown object key', 'e=>{throw{level:e}}', 'e=>{throw{type:e}}'], + ['regex after a block', 'e=>{if(e){return e}/a/.test(e)}', 'e=>{if(e){return e}/b/.test(e)}'], ])('%s', (_label, a, b) => { expect(norm(a)).not.toBe(norm(b)); }); @@ -119,6 +123,8 @@ describe('fingerprintFunction', () => { expect(norm('(a)/b/c')).toBe('( _ ) / _ / _'); expect(norm('e=>e++/2+n(e)')).toBe('_ => _ ++ / 2 + _ ( _ )'); expect(norm('e=>e--/2')).toBe('_ => _ -- / 2'); + expect(norm('({}/2)')).toBe('( { } / 2 )'); + expect(norm('if(a){}/a/g')).toBe('if ( _ ) { } /a/g'); }); it('treats an escaped backtick at the end of an unterminated template like a closing one', () => { From d7e7bdb2a8c9adcea3c2cd9c90f21e1b9c6481eb Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Thu, 26 Nov 2026 12:21:40 -0500 Subject: [PATCH 6/7] ref(core): Replace the function fingerprint tokenizer with a smaller regex-driven scan The hand-written tokenizer cost about 1.3KB minified and gzipped. This one is about 0.7KB: a single regex does the lexing and a short loop tracks template substitutions and whether a slash is a division. It only aims to be stable across builds made with the same minifier, so it no longer treats different quote styles, number spellings, `void 0`, `!0`, `===` or shorthand keys as equal. Tests for those are removed and the exact-output tests are rewritten for the new token format. --- .../core/src/utils/fingerprintFunction.ts | 238 +++--------------- .../lib/utils/fingerprintFunction.test.ts | 81 +++--- 2 files changed, 72 insertions(+), 247 deletions(-) diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts index d55853a52bb6..4d625079c81a 100644 --- a/packages/core/src/utils/fingerprintFunction.ts +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -1,10 +1,8 @@ import { fnv1a32 } from './hash'; /** - * Keywords minifiers never rename and that change what a function does, plus `undefined`, which they spell `void 0`. + * Keywords minifiers never rename and that change what a function does. * Contextual words (`async`, `of`, `get`, `set`, `static`) are left out on purpose: minifiers may use them as names. - * So are words an options callback is very unlikely to contain (`class`, `extends`, `super`, `yield`, `import`, `do`, - * `export`, `debugger`, `with`), to keep the list short. They are treated as ordinary names. */ const KEYWORDS = new Set( 'break catch const continue default delete else finally for function if instanceof let new switch throw try var while await return typeof void in case this null true false undefined'.split( @@ -13,33 +11,30 @@ const KEYWORDS = new Set( ); /** - * After these tokens a `{` opens an object literal rather than a block. + * One alternative per kind of token: whitespace and comments, quoted string, backtick, spread, increment, a name (with + * an optional leading `.` or `?.` and a lookahead for a following `:`), regex literal, number, and any other character. */ -const OBJECT_CONTEXT = new Set( - '( [ , = : ? ?? || && ! ... return typeof void in case const let var throw await'.split(' '), -); - -/** - * After these keywords, as after any name or literal, a `/` is a division rather than the start of a regex literal. - */ -const VALUE_KEYWORDS = new Set('this null true false undefined'.split(' ')); +const TOKEN = + /(?:\s|\/\/.*|\/\*[^]*?(?:\*\/|$))+|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`|\.\.\.|\+\+|--|(\??\.#?|#)?([A-Za-z_$][\w$]*)(?=(\s*:)?)|\/(?:[^/\\\n[]|\\.|\[(?:[^\]\\\n]|\\.)*\])+\/\w*|\d[\w.]*|[^]/g; /** - * Matches the longest punctuator at `lastIndex`, or else any one character. `a?.5:b` is a conditional, not optional - * chaining. A match is at most four characters long, so it cannot backtrack over the input. + * The rest of a template part, up to the closing backtick or the next `${`. */ -const PUNCTUATOR = /\.\.\.|=>|\?\.(?!\d)|\?\?=?|[=!]==?|\+\+|--|>>>=?|([*&|<>])\1?=?|[-+/%^]=|[^]/y; +const TEMPLATE = /(?:[^`\\$]|\\.|\$(?!\{))*(?:`|\$\{|$)/y; /** - * The last two are a no-break space and a byte order mark. + * Tokens after which a `/` is a division rather than the start of a regex literal. */ -const WHITESPACE = ' \n\t\r\u00a0\ufeff'; +const ENDS_VALUE = /(?:[\w$"'`)\]]|\+\+|--)$/; /** - * Fingerprints a function's behavior rather than its text: identifiers a minifier renames, whitespace, comments, - * quote styles, number spellings and common minifier rewrites don't change the result. + * Fingerprints a function with every name a minifier can rename blanked out, so that a bundler renaming identifiers + * doesn't change the result. * - * Inlined helpers, reordered operands, closures over different values and engine-specific source text still do. + * This is a regex-driven scan rather than a parser, kept small for bundle size. It only aims to be stable across + * builds made with the same minifier: inlined helpers, reordered operands, different quote or number spellings, and + * shorthand keys written out in full still change the result. Method names and shorthand keys are blanked like any + * other name, and a label at the start of a block is kept like an object key. */ export function fingerprintFunction(fn: (...args: never[]) => unknown): string { let source: string; @@ -53,197 +48,46 @@ export function fingerprintFunction(fn: (...args: never[]) => unknown): string { } /** - * Splits source into tokens in their minification-independent form, in one linear pass. Unterminated strings, comments - * and regexes run to the end of the input. + * Splits source into tokens, replacing every name that is not a keyword, a property or an object key with `_`. */ -// oxlint-disable-next-line complexity export function tokenize(src: string): string[] { const tokens: string[] = []; - // What each open bracket belongs to: `true` for an object literal, `false` for a block, `(` or `[`, `null` for a - // template `${`. Only names directly inside an object literal can be its keys. - const braces: Array = []; - const length = src.length; - let i = 0; - // Whether a `/` here would be a division rather than the start of a regex literal. - let afterValue: boolean | undefined; - // The name of the previous token when it is an identifier that starts an object literal entry. - let key: string | undefined; - - const push = (token: string, endsValue?: boolean): void => { - tokens.push(token); - afterValue = endsValue; - key = ''; - }; - - while (i < length) { - const start = i; - const ch = src[i] as string; - const next = src[i + 1] as string; - const previous = tokens[tokens.length - 1]; + // `true` for each open `${`, `false` for each open `{`. + const braces: boolean[] = []; + let prev = ''; + let match; + TOKEN.lastIndex = 0; - if (WHITESPACE.includes(ch)) { - i++; - continue; - } - - if (ch === '/' && (next === '/' || next === '*')) { - const end = src.indexOf(next === '/' ? '\n' : '*/', i + 2); - i = end < 0 ? length : end + (next === '/' ? 1 : 2); - continue; - } - - if (ch === '"' || ch === "'") { - let value = ''; - for (i++; i < length && src[i] !== ch; i++) { - value += - src[i] !== '\\' - ? src[i] - : // An escaped quote means the same thing whichever quote style the minifier picked. - src[++i] === '"' || src[i] === "'" - ? src[i] - : src.slice(i - 1, i + 1); - } - i++; - push(JSON.stringify(value), true); - continue; - } - - const closes = ch === '}' ? braces.pop() : undefined; - // A template part runs from the opening backtick, or from the `}` that ends a substitution, up to the closing - // backtick or the next `${`. - if (ch === '`' || closes === null) { - let text = ''; - i++; - while (i < length) { - const c = src[i++] as string; - text += c; - if (c === '\\') { - text += src.slice(i, ++i); - } else if (c === '`') { - break; - } else if (c === '$' && src[i] === '{') { - text += src[i++]; - braces.push(null); - break; - } - } - const isClosed = text.endsWith('`'); - // A template without substitutions is a plain string to a minifier. - push(ch === '`' && isClosed ? JSON.stringify(text.slice(0, -1)) : `\`${text}`, isClosed); - continue; - } - - if (isDigit(ch) || (ch === '.' && isDigit(next))) { - // Hex digits include `e`, so `0x1e+1` is an addition, not an exponent. - const isHex = ch === '0' && (next === 'x' || next === 'X'); - let c; - while ( - ++i < length && - (isIdentifierChar((c = src[i] as string)) || - c === '.' || - (!isHex && (c === '+' || c === '-') && (src[i - 1] === 'e' || src[i - 1] === 'E'))) - ); - let number = src.slice(start, i); - if (previous === 'void' && number === '0') { - // `void 0` is how minifiers spell `undefined`. - tokens.pop(); - number = 'undefined'; - } else if (previous === '!' && (number === '0' || number === '1')) { - // `!0` and `!1` are how minifiers spell `true` and `false`. - tokens.pop(); - number = number === '0' ? 'true' : 'false'; - } - push(canonicalNumber(number), true); - continue; - } + while ((match = TOKEN.exec(src))) { + let token = match[0]; + const ch = token[0] as string; - if (isIdentifierStart(ch)) { - while (++i < length && isIdentifierChar(src[i] as string)); - const word = src.slice(start, i); - if (KEYWORDS.has(word)) { - push(word, VALUE_KEYWORDS.has(word)); - } else if (previous === '.' || previous === '?.' || previous === '#') { - // `a.b`, `a?.b` and `#b`: property names survive minification. - push(JSON.stringify(word), true); - } else { - // Without scope analysis a global can't be told from a local, so every other name is anonymous. - push('_', true); - if (braces[braces.length - 1] && (previous === '{' || previous === ',')) { - key = word; - } - } + if (ch <= ' ' || (ch === '/' && (token[1] === '/' || token[1] === '*'))) { continue; } - if (ch === '/' && !afterValue) { - let inClass = false; - let c; - for (i++; i < length && (c = src[i]) !== '\n' && (c !== '/' || inClass); i++) { - if (c === '\\') { - i++; - } else { - inClass = c === '[' || (c !== ']' && inClass); - } + if (ch === '`' || (ch === '}' && braces.pop())) { + TEMPLATE.lastIndex = TOKEN.lastIndex; + TEMPLATE.test(src); + token = src.slice(match.index, (TOKEN.lastIndex = TEMPLATE.lastIndex)); + if (token.endsWith('${')) { + braces.push(true); } - // The closing slash, then the flags. - while (++i < length && isIdentifierChar(src[i] as string)); - push(src.slice(start, i), true); - continue; - } - - if (ch === '{') { - // Only a template part can end in `${`: strings are quoted and regexes end at a slash or a newline. - braces.push(!previous || OBJECT_CONTEXT.has(previous) || previous.endsWith('${')); - } else if (ch === '(' || ch === '[') { + } else if (ch === '{') { braces.push(false); - } else if (ch === ')' || ch === ']') { - braces.pop(); - } - - PUNCTUATOR.lastIndex = i; - PUNCTUATOR.test(src); - i = PUNCTUATOR.lastIndex; - // Minifiers turn `===` and `!==` into `==` and `!=` where both sides are known to share a type. Those two are the - // only three-character punctuators with `=` in the middle. - const punctuator = src.slice(start, next === '=' && i - start > 2 ? i - 1 : i); - - if (key && ':(,}='.includes(punctuator)) { - // Object keys survive minification too. - tokens[tokens.length - 1] = JSON.stringify(key); - // Shorthand `{event}` becomes `{event:e}` once the binding is renamed, and `{level=1}` becomes `{level:e=1}`. - if (',}='.includes(punctuator)) { - tokens.push(':', previous as string); + } else if (match[2]) { + // Property names and object keys survive minification, every other name is anonymous. + if (!match[1] && !KEYWORDS.has(token) && !(match[3] && (prev === '{' || prev === ','))) { + token = '_'; } + } else if (ch === '/' && token[1] && ENDS_VALUE.test(prev) && (!KEYWORDS.has(prev) || prev === 'this')) { + // A division, not a regex literal: emit the slash alone and rescan what follows. + token = ch; + TOKEN.lastIndex = match.index + 1; } - // A regex can follow a block's `}` but not an object's, nor postfix `++` or `--`. - push(punctuator, ')]'.includes(ch) || closes === true || punctuator == '++' || punctuator == '--'); + tokens.push((prev = token)); } return tokens; } - -/** - * Spells a number the same way however the source wrote it, since minifiers rewrite `0.10` to `.1` and `1000` to `1e3`. - */ -function canonicalNumber(raw: string): string { - const digits = raw.replace(/_/g, ''); - if (digits.endsWith('n')) { - return digits; - } - const value = Number(digits); - - return Number.isNaN(value) ? raw : String(value); -} - -function isDigit(ch: string): boolean { - return ch >= '0' && ch <= '9'; -} - -function isIdentifierStart(ch: string): boolean { - return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$' || ch > '\x7f'; -} - -function isIdentifierChar(ch: string): boolean { - return isIdentifierStart(ch) || isDigit(ch); -} diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts index 33c269772562..310f1911c3c6 100644 --- a/packages/core/test/lib/utils/fingerprintFunction.test.ts +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -10,18 +10,11 @@ describe('fingerprintFunction', () => { ['spread of a renamed local', 'e=>({...e.tags})', 't=>({...t.tags})'], ['whitespace', 'e => e', 'e=>e'], ['comments', 'e=>e // keep all\n', 'e=>/* keep */e'], - ['quote style', `e=>e.type==="error"`, `e=>e.type==='error'`], - ['strict equality rewritten', `e=>e.type==="error"`, `e=>e.type=="error"`], - ['escaped quotes', `e=>"it's"`, `e=>'it\\'s'`], - ['template without substitutions', 'e=>`drop`', `e=>"drop"`], - ['number spelling', 'e=>e<0.1', 'e=>e<.1'], - ['exponent', 'e=>e>1000', 'e=>e>1e3'], - ['numeric separators', 'e=>e>1_000', 'e=>e>1000'], - ['void 0', 'e=>undefined', 'e=>void 0'], - ['!0 and !1', 'e=>[true,false]', 'e=>[!0,!1]'], - ['shorthand property', '({event})=>({event})', '({event:e})=>({event:e})'], - ['destructuring default', "({level='error'})=>level", "({level:e='error'})=>e"], - ['destructured declaration', 'e=>{const{event}=e;return event}', 'e=>{const{event:t}=e;return t}'], + ['renamed ternary branches', '(a,b)=>a?b:a', '(x,y)=>x?y:x'], + ['renamed destructuring targets', '({event:e})=>e', '({event:t})=>t'], + ['renamed names in template substitutions', "e=>`'${n(e)}' and '${e}'`", "t=>`'${r(t)}' and '${t}'`"], + ['renamed names after a regex containing quotes', `e=>/["']/.test(e)?n("x"):r`, `t=>/["']/.test(t)?a("x"):o`], + ['renamed operands of a division', 'e=>e/n/r', 't=>t/a/o'], ['renamed call arguments inside an object', 'e=>({a:f(x,y,z)})', 't=>({a:g(p,q,r)})'], ['renamed array items inside an object', 'e=>({a:[x,y,z]})', 't=>({a:[p,q,r]})'], ['renamed arrow parameters inside an object', 'e=>({a:(x,y,z)=>x})', 't=>({a:(p,q,r)=>p})'], @@ -57,20 +50,25 @@ describe('fingerprintFunction', () => { describe('tokenizer', () => { it('tells a regex from a division', () => { - expect(norm('e=>e/2/1')).toBe('_ => _ / 2 / 1'); - expect(norm('e=>/2/.test(e)')).toBe('_ => /2/ . "test" ( _ )'); + expect(norm('e=>e/2/1')).toBe('_ = > _ / 2 / 1'); + expect(norm('e=>/2/.test(e)')).toBe('_ = > /2/ .test ( _ )'); }); it('keeps regex character classes containing slashes intact', () => { - expect(norm('e=>/[/]a/.test(e)')).toBe('_ => /[/]a/ . "test" ( _ )'); + expect(norm('e=>/[/]a/.test(e)')).toBe('_ = > /[/]a/ .test ( _ )'); }); it('handles nested template literals and object literals in substitutions', () => { - expect(norm('e=>`a${`b${e}`}c${({k:e})}`')).toBe('_ => `a${ `b${ _ `` `c${ ( { "k" : _ } ) ``'); + expect(norm('e=>`a${`b${e}`}c${({k:e})}`')).toBe('_ = > `a${ `b${ _ }` }c${ ( { k : _ } ) }`'); }); - it('treats a block body as a block, not an object', () => { - expect(norm('e=>{a:e}')).toBe('_ => { _ : _ }'); + it('reads a regex inside a template substitution and a division after a template', () => { + expect(norm('e=>`${/a/.test(e)}`')).toBe('_ = > `${ /a/ .test ( _ ) }`'); + expect(norm('e=>`${e}`/2/e')).toBe('_ = > `${ _ }` / 2 / _'); + }); + + it('cannot tell a label at the start of a block from an object key', () => { + expect(norm('e=>{a:e}')).toBe('_ = > { a : _ }'); }); it('survives unterminated input', () => { @@ -79,56 +77,39 @@ describe('fingerprintFunction', () => { expect(() => norm('e=>/abc')).not.toThrow(); expect(() => norm('e=>/* abc')).not.toThrow(); expect(() => norm('}}}}')).not.toThrow(); + expect(() => norm('`a\\`')).not.toThrow(); }); - it('matches the longest punctuator', () => { - expect(norm('a>>>=b>>>c>>=d>>e>=f>g')).toBe('_ >>>= _ >>> _ >>= _ >> _ >= _ > _'); - expect(norm('a??=b??c?.d?e:f')).toBe('_ ??= _ ?? _ ?. "d" ? _ : _'); - expect(norm('a**=b**c*=d*e')).toBe('_ **= _ ** _ *= _ * _'); - expect(norm('a&&=b||=c&&d||e&f|g^=h')).toBe('_ &&= _ ||= _ && _ || _ & _ | _ ^= _'); - expect(norm('a=>b!==c===d!=e==f=!g')).toBe('_ => _ != _ == _ != _ == _ = ! _'); - expect(norm('a++ +b-- -c+=d-=e')).toBe('_ ++ + _ -- - _ += _ -= _'); - expect(norm('a++=b')).toBe('_ ++ = _'); - expect(norm('f(...a,..b)')).toBe('_ ( ... _ , . . "b" )'); - }); - - it('reads `?.` before a digit as a conditional', () => { - expect(norm('a?.5:b')).toBe('_ ? 0.5 : _'); - }); - - it('keeps an exponent sign in a number, except in hex', () => { - expect(norm('1e+3+0x1e+1')).toBe('1000 + 30 + 1'); + it('keeps spread and increments whole', () => { + expect(norm('a++ +b-- -c')).toBe('_ ++ + _ -- - _'); + expect(norm('f(...a,..b)')).toBe('_ ( ... _ , . .b )'); }); - it('only rewrites `void 0`, `!0` and `!1`, and spells numbers canonically', () => { - expect(norm('[void 0x0,void 1,!2,!0n]')).toBe('[ void 0 , void 1 , ! 2 , ! 0n ]'); - expect(norm('1_000+0.10+.1+1_0n')).toBe('1000 + 0.1 + 0.1 + 10n'); + it('keeps object keys next to calls and arrays, and in objects nested inside them', () => { + expect(norm('({a:f(x,y),b:[y,{c:z}]})')).toBe('( { a : _ ( _ , _ ) , b : [ _ , { c : _ } ] } )'); }); - it('keeps object keys next to calls and arrays, and in objects nested inside them', () => { - expect(norm('({a:f(x,y),b:[y,{c}],d})')).toBe('( { "a" : _ ( _ , _ ) , "b" : [ _ , { "c" : _ } ] , "d" : _ } )'); + it('does not mistake a ternary branch for an object key', () => { + expect(norm('f(x,a?b:c)')).toBe('_ ( _ , _ ? _ : _ )'); }); - it('keeps object keys and method names', () => { - expect(norm('e=>({a:1,b(){},c,...d})')).toBe('_ => ( { "a" : 1 , "b" ( ) { } , "c" : _ , ... _ } )'); + it('keeps object keys but not shorthand keys or method names', () => { + expect(norm('e=>({a:1,b(){},c,...d})')).toBe('_ = > ( { a : 1 , _ ( ) { } , _ , ... _ } )'); }); it('keeps `undefined` but no other global', () => { - expect(norm('e=>Math.now()===undefined')).toBe('_ => _ . "now" ( ) == undefined'); + expect(norm('e=>Math.now()===undefined')).toBe('_ = > _ .now ( ) = = = undefined'); }); - it('tells a regex from a division after keywords and closing brackets', () => { + it('tells a regex from a division after keywords, operators and closing brackets', () => { expect(norm('return/a/g')).toBe('return /a/g'); expect(norm('this/a/g')).toBe('this / _ / _'); expect(norm('(a)/b/c')).toBe('( _ ) / _ / _'); - expect(norm('e=>e++/2+n(e)')).toBe('_ => _ ++ / 2 + _ ( _ )'); - expect(norm('e=>e--/2')).toBe('_ => _ -- / 2'); + expect(norm('e=>e++/2+n(e)')).toBe('_ = > _ ++ / 2 + _ ( _ )'); + expect(norm('e=>e--/2')).toBe('_ = > _ -- / 2'); expect(norm('({}/2)')).toBe('( { } / 2 )'); expect(norm('if(a){}/a/g')).toBe('if ( _ ) { } /a/g'); - }); - - it('treats an escaped backtick at the end of an unterminated template like a closing one', () => { - expect(norm('`a\\`')).toBe('"a\\\\"'); + expect(norm('e=>e?/a/.test(e):e')).toBe('_ = > _ ? /a/ .test ( _ ) : _'); }); }); From b6d5905fe38f6d58f162d7a15ddb4aa8ce547813 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Thu, 26 Nov 2026 13:39:22 -0500 Subject: [PATCH 7/7] fix(core): Mark built-in and bound functions as native in function fingerprints Their source text is `{ [native code] }` with a header each engine spells differently, so the same bound callback fingerprinted differently per browser. --- packages/core/src/utils/fingerprintFunction.ts | 10 ++++++++++ .../core/test/lib/utils/fingerprintFunction.test.ts | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts index 4d625079c81a..9eefa7812713 100644 --- a/packages/core/src/utils/fingerprintFunction.ts +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -27,6 +27,12 @@ const TEMPLATE = /(?:[^`\\$]|\\.|\$(?!\{))*(?:`|\$\{|$)/y; */ const ENDS_VALUE = /(?:[\w$"'`)\]]|\+\+|--)$/; +/** + * Matches the source text engines report for built-in and bound functions, which has no real body and is spelled + * differently by each engine. + */ +const NATIVE = /\{\s*\[native code\]\s*\}\s*$/; + /** * Fingerprints a function with every name a minifier can rename blanked out, so that a bundler renaming identifiers * doesn't change the result. @@ -44,6 +50,10 @@ export function fingerprintFunction(fn: (...args: never[]) => unknown): string { return 'unknown'; } + if (NATIVE.test(source)) { + return 'native'; + } + return fnv1a32(tokenize(source).join(' ')); } diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts index 310f1911c3c6..90dad6fbd5c6 100644 --- a/packages/core/test/lib/utils/fingerprintFunction.test.ts +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -113,6 +113,16 @@ describe('fingerprintFunction', () => { }); }); + it('marks built-in and bound functions as native', () => { + const bound = function (this: unknown): unknown { + return this; + }.bind(null); + + expect(fingerprintFunction(bound)).toBe('native'); + expect(fingerprintFunction(Math.max)).toBe('native'); + expect(fingerprintFunction(() => '{ [native code] }'.length)).not.toBe('native'); + }); + it('fingerprints functions', () => { expect(fingerprintFunction(e => e)).toBe(fingerprintFunction(t => t)); expect(fingerprintFunction(() => null)).not.toBe(fingerprintFunction(e => e));