diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f754ead..72b39cf 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -80,14 +80,15 @@ updates: patterns: - "vitest" - "@vitest/*" - # publint and @arethetypeswrong/cli are pre-1.0, so breaking changes ship - # as minors; either can start failing `npm run check:package` against + # publint, @arethetypeswrong/cli and esbuild are pre-1.0, so breaking changes ship + # as minors; any of them can start failing `npm run check:package` against # unchanged package code. This group covers ALL update types, majors # included, so such a bump cannot block the grouped batch behind it. package-check: patterns: - "publint" - "@arethetypeswrong/*" + - "esbuild" npm-minor-patch: patterns: - "*" diff --git a/CLAUDE.md b/CLAUDE.md index d2d1dd4..e3aa605 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,6 +19,7 @@ - publint and attw each catch what the other misses. attw exits 0 on a tarball containing no declarations at all, so publint is what catches missing or unpublished files; publint passes a correctly-wired `exports` map whose declarations import chunks the build never emitted, so attw is what catches that. Dropping either silently loses a class of failure. - `scripts/assert-no-import-side-effects.js` guards `"sideEffects": false` in `check:package`, and nothing else verifies that claim. It fails a module-scope *read* of a browser global, not only a write, and fails any entry that imports a node builtin, since it cannot see what such code does at import; no entry needs one today. Detect the environment at call time, as every site in `src/` does; the script header gives the reasoning. - The flag saves a consumer bytes only when none of an entry's exports are used. `sideEffects` is module-granularity and `splitting: false` emits each entry as a single JS module, so there is no partial drop. Do not advertise it as a tree-shaking win. +- The exported defaults in `config/defaults.ts` are built by `@__PURE__` annotated factory calls, and `common/keys.ts` derives its key lists the same way, so a bundler can drop them: one imported function costs ~300 bytes rather than ~1,400 on esbuild. Inlining a factory or losing an annotation silently gives that back; see the comment above `createDefaultConfig` and `scripts/assert-bundle-budget.js`. ## Releases diff --git a/README.md b/README.md index 4e9d50b..5d15a48 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Three entry points: All three ship dual ESM/CJS builds with TypeScript declarations. The `/react` and `/server` subpaths need TypeScript `moduleResolution` set to `node16` or `nodenext` (TS 4.7+), or `bundler` (TS 5.0+); under the legacy `node`/`node10` setting only the root entry resolves types, though all three resolve at runtime in Node. -The root entry is a barrel, so for a browser bundle it matters how you import from it. A static `import { toSnakeCase }` prunes to roughly 1.4KB on esbuild, and to well under 1KB on Rollup and webpack. A `require()` of the same entry keeps all of it on esbuild, Rollup and Rolldown — roughly 28KB minified — because none of them tree-shake CommonJS; webpack 5 does prune CommonJS exports, so there the gap is about 640 bytes. `await import()` is not a dependable substitute: esbuild and Rolldown keep the whole namespace however you access it, and Rollup prunes it only when you destructure the result directly. Use a static `import` at the call site. The subpaths are far less exposed, because most of what they contain is used either way: `/server` differs by a few hundred bytes, and `/react` by about 2.7KB on esbuild and about 500 bytes on webpack, against the ~14KB the hook pulls in regardless. +The root entry is a barrel, so for a browser bundle it matters how you import from it. A static `import { toSnakeCase }` prunes to around 300 bytes on esbuild, Rollup, Rolldown and webpack alike. A `require()` of the same entry keeps all of it on esbuild, Rollup and Rolldown — roughly 28KB minified — because none of them tree-shake CommonJS; webpack 5 does prune CommonJS exports, so there the gap is about 200 bytes. `await import()` is not a dependable substitute: esbuild and Rolldown keep the whole namespace however you access it, and Rollup prunes it only when you destructure the result directly. Use a static `import` at the call site. The subpaths are far less exposed, because most of what they contain is used either way: `/server` differs by a few hundred bytes, and `/react` by about 3KB on esbuild and well under 1KB on webpack, against the ~14KB the hook pulls in regardless. ## Quick Start diff --git a/__tests__/common/keys.test.ts b/__tests__/common/keys.test.ts index af2199d..a46c5ef 100644 --- a/__tests__/common/keys.test.ts +++ b/__tests__/common/keys.test.ts @@ -12,6 +12,10 @@ import { detectKeyFormat, normalizeKey, toUrlKey, + SNAKE_TO_CAMEL, + CAMEL_TO_SNAKE, + STANDARD_SNAKE_KEYS, + STANDARD_CAMEL_KEYS, } from '../../src/common/keys' describe('toSnakeCase', () => { @@ -245,3 +249,17 @@ describe('isValidUtmParameters', () => { expect(isValidUtmParameters({ utmSource: 'test' })).toBe(true) }) }) + +/** + * These lists are derived from the maps above them. Pinning the relationship + * keeps a literal rewrite of either from drifting out of step. + */ +describe('standard key lists match the maps they come from', () => { + it('STANDARD_SNAKE_KEYS lists the keys of SNAKE_TO_CAMEL', () => { + expect(STANDARD_SNAKE_KEYS).toEqual(Object.keys(SNAKE_TO_CAMEL)) + }) + + it('STANDARD_CAMEL_KEYS lists the keys of CAMEL_TO_SNAKE', () => { + expect(STANDARD_CAMEL_KEYS).toEqual(Object.keys(CAMEL_TO_SNAKE)) + }) +}) diff --git a/__tests__/config/defaults.test.ts b/__tests__/config/defaults.test.ts new file mode 100644 index 0000000..953a8ac --- /dev/null +++ b/__tests__/config/defaults.test.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from 'vitest' +import { + DEFAULT_CONFIG, + DEFAULT_SANITIZE_CONFIG, + DEFAULT_PII_FILTER_CONFIG, + DEFAULT_PII_PATTERNS, + DEFAULT_ATTRIBUTION_CONFIG, + STANDARD_UTM_PARAMETERS, +} from '../../src/config/defaults' + +/** + * Every constant here is exported from the root entry, so one of them aliasing + * another would let a consumer mutating one default silently change a second. + */ +describe('exported defaults are independent of each other', () => { + it('DEFAULT_CONFIG holds copies of the sibling default objects', () => { + expect(DEFAULT_CONFIG.sanitize).not.toBe(DEFAULT_SANITIZE_CONFIG) + expect(DEFAULT_CONFIG.piiFiltering).not.toBe(DEFAULT_PII_FILTER_CONFIG) + expect(DEFAULT_CONFIG.attribution).not.toBe(DEFAULT_ATTRIBUTION_CONFIG) + expect(DEFAULT_CONFIG.allowedParameters).not.toBe(STANDARD_UTM_PARAMETERS) + expect(DEFAULT_CONFIG.piiFiltering.patterns).not.toBe(DEFAULT_PII_PATTERNS) + expect(DEFAULT_PII_FILTER_CONFIG.patterns).not.toBe(DEFAULT_PII_PATTERNS) + }) + + it('DEFAULT_CONFIG still equals the defaults it copies', () => { + expect(DEFAULT_CONFIG.sanitize).toEqual(DEFAULT_SANITIZE_CONFIG) + expect(DEFAULT_CONFIG.piiFiltering).toEqual(DEFAULT_PII_FILTER_CONFIG) + expect(DEFAULT_CONFIG.attribution).toEqual(DEFAULT_ATTRIBUTION_CONFIG) + expect(DEFAULT_CONFIG.allowedParameters).toEqual(STANDARD_UTM_PARAMETERS) + expect(DEFAULT_CONFIG.piiFiltering.patterns).toEqual(DEFAULT_PII_PATTERNS) + }) + + it('copies the patterns array without copying the patterns themselves', () => { + expect(DEFAULT_CONFIG.piiFiltering.patterns[0]).toBe(DEFAULT_PII_PATTERNS[0]) + }) +}) diff --git a/package-lock.json b/package-lock.json index 4d7e339..0679a66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "@testing-library/react": "^16.0.0", "@types/react": "^18.0.0", "@vitest/coverage-v8": "^5.0.0", + "esbuild": "^0.28.2", "jsdom": "^30.0.1", "oxlint": "^1.0.0", "prettier": "^3.0.0", diff --git a/package.json b/package.json index fc95c49..6b346fc 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "test:watch": "vitest", "coverage": "vitest run --coverage", "type-check": "tsc --noEmit", - "check:package": "npm run build && publint --strict && attw --pack . --profile node16 && node scripts/assert-no-import-side-effects.js", + "check:package": "npm run build && publint --strict && attw --pack . --profile node16 && node scripts/assert-no-import-side-effects.js && node scripts/assert-bundle-budget.js", "lint": "oxlint", "lint:fix": "oxlint --fix", "format": "prettier --write \"src/**/*.{ts,tsx}\" \"__tests__/**/*.{ts,tsx}\"", @@ -74,6 +74,7 @@ "@testing-library/react": "^16.0.0", "@types/react": "^18.0.0", "@vitest/coverage-v8": "^5.0.0", + "esbuild": "^0.28.2", "jsdom": "^30.0.1", "oxlint": "^1.0.0", "prettier": "^3.0.0", diff --git a/scripts/assert-bundle-budget.js b/scripts/assert-bundle-budget.js new file mode 100644 index 0000000..901a8d5 --- /dev/null +++ b/scripts/assert-bundle-budget.js @@ -0,0 +1,90 @@ +/** + * Fails if a consumer importing one small function from the root entry would + * ship more than BUDGET_BYTES, or if the pruned bundle does not work. + * + * What this protects is the two `@__PURE__` annotations in + * src/config/defaults.ts, on the factory calls that build + * DEFAULT_PII_FILTER_CONFIG and DEFAULT_CONFIG. The comment above + * createDefaultConfig says why they are written that way. Losing either retains + * the object and everything it reaches - ~670 or ~1,200 bytes against ~300 - + * with nothing any test can see. + * + * It does not cover the two annotations in src/common/keys.ts, worth 153 and 21 + * bytes to this import. Catching the 21 would need a ceiling with no headroom, + * so a breach here is most likely one of the defaults.ts pair. + * + * The bundle is executed as well as weighed, because an annotation on a call + * that is not in fact pure would license a bundler to drop something needed, + * and no other check prunes the entry and runs the result. + * + * Usage: npm run check:package (which builds first) + */ + +import { build } from 'esbuild' +import { existsSync } from 'fs' +import { fileURLToPath } from 'url' +import { dirname, join, resolve } from 'path' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const root = resolve(__dirname, '..') + +/** + * ~300 bytes with both defaults.ts annotations in place, ~670 or ~1,200 with + * either lost. The headroom absorbs ordinary growth in the function under test + * and patch-level minifier drift. + */ +const BUDGET_BYTES = 600 + +const ENTRY = 'dist/index.js' +const SYMBOL = 'toSnakeCase' + +async function main() { + if (!existsSync(join(root, ENTRY))) { + console.error(`${ENTRY} is missing. Run \`npm run build\` first.`) + process.exit(1) + } + + // Bundled straight from dist rather than from a packed tarball: the ESM root + // entry is the same file either way, and this keeps the check to a few ms. + const result = await build({ + stdin: { + contents: `import { ${SYMBOL} } from './${ENTRY}'\nglobalThis.__out = ${SYMBOL}(globalThis.__in)\n`, + resolveDir: root, + sourcefile: 'budget-entry.js', + loader: 'js', + }, + bundle: true, + minify: true, + format: 'esm', + platform: 'browser', + target: 'es2020', + external: ['react', 'react/jsx-runtime'], + write: false, + logLevel: 'silent', + }) + + const bytes = result.outputFiles[0].contents.byteLength + + if (bytes > BUDGET_BYTES) { + console.error( + `Importing { ${SYMBOL} } from the root entry now bundles to ${bytes} bytes, over the ${BUDGET_BYTES} budget.`, + ) + console.error('Most likely a factory call in src/config/defaults.ts lost its annotation.') + console.error('DEFAULT_PII_FILTER_CONFIG and DEFAULT_CONFIG each need one.') + process.exit(1) + } + + // Proves the pruning kept what the import actually needs. + globalThis.__in = 'utmTeamId' + const code = Buffer.from(result.outputFiles[0].contents).toString('utf-8') + await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`) + if (globalThis.__out !== 'utm_team_id') { + console.error(`The pruned bundle returned ${JSON.stringify(globalThis.__out)} for 'utmTeamId'.`) + console.error('An annotated call was not pure, so a needed value was dropped.') + process.exit(1) + } + + console.log(`Root entry bundles to ${bytes} bytes and still works (budget ${BUDGET_BYTES}).`) +} + +await main() diff --git a/src/common/keys.ts b/src/common/keys.ts index b7d164a..ac123fe 100644 --- a/src/common/keys.ts +++ b/src/common/keys.ts @@ -34,12 +34,12 @@ export const CAMEL_TO_SNAKE: Record = { /** * All standard snake_case UTM keys */ -export const STANDARD_SNAKE_KEYS = Object.keys(SNAKE_TO_CAMEL) +export const STANDARD_SNAKE_KEYS = /* @__PURE__ */ Object.keys(SNAKE_TO_CAMEL) /** * All standard camelCase UTM keys */ -export const STANDARD_CAMEL_KEYS = Object.keys(CAMEL_TO_SNAKE) +export const STANDARD_CAMEL_KEYS = /* @__PURE__ */ Object.keys(CAMEL_TO_SNAKE) /** * Convert a single key from snake_case to camelCase diff --git a/src/config/defaults.ts b/src/config/defaults.ts index 9b379ae..b2bf198 100644 --- a/src/config/defaults.ts +++ b/src/config/defaults.ts @@ -60,15 +60,20 @@ export const DEFAULT_PII_PATTERNS: PiiPattern[] = [ }, ] +/** Built in a function for the same reason as createDefaultConfig below. */ +function createPiiFilterConfig(): PiiFilterConfig { + return { + enabled: false, + mode: 'reject', + patterns: [...DEFAULT_PII_PATTERNS], + } +} + /** * Default PII filtering configuration * PII filtering is disabled by default but has sensible defaults when enabled */ -export const DEFAULT_PII_FILTER_CONFIG: PiiFilterConfig = { - enabled: false, - mode: 'reject', - patterns: [...DEFAULT_PII_PATTERNS], -} +export const DEFAULT_PII_FILTER_CONFIG: PiiFilterConfig = /* @__PURE__ */ createPiiFilterConfig() /** * Standard UTM parameters (snake_case format for URLs) @@ -83,53 +88,63 @@ export const STANDARD_UTM_PARAMETERS = [ ] as const /** - * Default configuration with all values set - * This is used as the base when merging with user-provided config + * Built in a function so the annotation on the export below has a call to attach + * to. esbuild and Rolldown cannot prove a spread pure, Rollup can, so without it + * this object is retained for an esbuild or Rolldown consumer at about a + * kilobyte. scripts/assert-bundle-budget.js fails if the annotation is lost. */ -export const DEFAULT_CONFIG: ResolvedUtmConfig = { - /** UTM tracking is enabled by default */ - enabled: true, +function createDefaultConfig(): ResolvedUtmConfig { + return { + /** UTM tracking is enabled by default */ + enabled: true, - /** Use snake_case format by default (matches URL query params) */ - keyFormat: 'snake_case', + /** Use snake_case format by default (matches URL query params) */ + keyFormat: 'snake_case', - /** Default storage key for browser storage */ - storageKey: 'utm_parameters', + /** Default storage key for browser storage */ + storageKey: 'utm_parameters', - /** Use sessionStorage by default (ephemeral, cleared on tab close) */ - storageType: 'session', + /** Use sessionStorage by default (ephemeral, cleared on tab close) */ + storageType: 'session', - /** Auto-capture UTM params when React hook mounts */ - captureOnMount: true, + /** Auto-capture UTM params when React hook mounts */ + captureOnMount: true, - /** Append UTM params to share URLs by default */ - appendToShares: true, + /** Append UTM params to share URLs by default */ + appendToShares: true, - /** Capture standard UTM parameters by default */ - allowedParameters: [...STANDARD_UTM_PARAMETERS], + /** Capture standard UTM parameters by default */ + allowedParameters: [...STANDARD_UTM_PARAMETERS], - /** Values are not folded to lowercase by default */ - lowercaseValues: false, + /** Values are not folded to lowercase by default */ + lowercaseValues: false, - /** No default parameters set */ - defaultParams: {}, + /** No default parameters set */ + defaultParams: {}, - /** No platform-specific share context by default */ - shareContextParams: {}, + /** No platform-specific share context by default */ + shareContextParams: {}, - /** No parameters excluded from shares by default */ - excludeFromShares: [], + /** No parameters excluded from shares by default */ + excludeFromShares: [], - /** Sanitization disabled by default */ - sanitize: { ...DEFAULT_SANITIZE_CONFIG }, + /** Sanitization disabled by default */ + sanitize: { ...DEFAULT_SANITIZE_CONFIG }, - /** PII filtering disabled by default (deep copy to prevent shared references) */ - piiFiltering: { ...DEFAULT_PII_FILTER_CONFIG, patterns: [...DEFAULT_PII_PATTERNS] }, + /** PII filtering disabled by default (deep copy to prevent shared references) */ + piiFiltering: { ...DEFAULT_PII_FILTER_CONFIG, patterns: [...DEFAULT_PII_PATTERNS] }, - /** Last-touch attribution by default */ - attribution: { ...DEFAULT_ATTRIBUTION_CONFIG }, + /** Last-touch attribution by default */ + attribution: { ...DEFAULT_ATTRIBUTION_CONFIG }, + } } +/** + * Default configuration with all values set + * This is used as the base when merging with user-provided config + */ +export const DEFAULT_CONFIG: ResolvedUtmConfig = /* @__PURE__ */ createDefaultConfig() + /** * Get a copy of the default configuration * Use this to avoid accidentally mutating the defaults