Skip to content

Commit

Permalink
Make bundle headers fully deterministic
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperisager committed Jan 23, 2025
1 parent 6438e3f commit 4833414
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 10 deletions.
25 changes: 15 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,13 +254,13 @@ module.exports = exports = class Bundle {
const { indent = 0 } = opts

const header = {
version: this.version,
id: this.id,
main: this.main,
imports: this.imports,
resolutions: this.resolutions,
addons: this.addons.sort(),
assets: this.assets.sort(),
version: Bundle.version,
id: this._id,
main: this._main,
imports: cloneImportsMap(this._imports),
resolutions: cloneResolutionsMap(this._resolutions),
addons: cloneFilesList(this._addons, 'Addons'),
assets: cloneFilesList(this._assets, 'Assets'),
files: {}
}

Expand Down Expand Up @@ -301,6 +301,7 @@ module.exports = exports = class Bundle {
return {
__proto__: { constructor: Bundle },

version: this.version,
id: this.id,
main: this.main,
imports: this.imports,
Expand Down Expand Up @@ -387,11 +388,15 @@ function isDecimal(c) {
return c >= 0x30 && c <= 0x39
}

function compareKeys([a], [b]) {
return a > b ? 1 : a < b ? -1 : 0
}

function cloneImportsMap(value) {
if (typeof value === 'object' && value !== null) {
const imports = {}

for (const entry of Object.entries(value)) {
for (const entry of Object.entries(value).sort(compareKeys)) {
imports[entry[0]] = cloneImportsMapEntry(entry[1])
}

Expand Down Expand Up @@ -425,7 +430,7 @@ function cloneResolutionsMap(value) {
if (typeof value === 'object' && value !== null) {
const resolutions = {}

for (const entry of Object.entries(value)) {
for (const entry of Object.entries(value).sort(compareKeys)) {
resolutions[entry[0]] = cloneImportsMap(entry[1])
}

Expand All @@ -451,7 +456,7 @@ function cloneFilesList(value, name) {
files.push(entry)
}

return files
return files.sort()
}

throw new TypeError(
Expand Down
26 changes: 26 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,35 @@ test('hashbang', (t) => {
test('reproducible buffers', (t) => {
const a = new Bundle()
a.write('/foo.js', 'foo').write('/bar.js', 'bar')
a.resolutions = {
'/foo.js': {
a: {
f: '/f',
e: '/e'
},
b: '/b'
},
'/bar.js': {
c: '/c',
d: '/d'
}
}

const b = new Bundle()
b.write('/bar.js', 'bar').write('/foo.js', 'foo')
b.resolutions = {
'/bar.js': {
d: '/d',
c: '/c'
},
'/foo.js': {
b: '/b',
a: {
f: '/f',
e: '/e'
}
}
}

t.alike(a.toBuffer(), b.toBuffer())
})

0 comments on commit 4833414

Please sign in to comment.