mirror of
https://github.com/lancedikson/bowser
synced 2026-09-23 20:44:24 +00:00
Dual packaging, without breaking existing consumers (#628)
Co-authored-by: Yasumasa Ashida <ys.ashida@gmail.com>
This commit is contained in:
192
test/package/assertions.cjs
Normal file
192
test/package/assertions.cjs
Normal file
@@ -0,0 +1,192 @@
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* Runs *inside* a throwaway directory that has the packed bowser tarball
|
||||
* extracted into ./node_modules/bowser, so that bare specifiers resolve the way
|
||||
* they would for a real consumer.
|
||||
*
|
||||
* Deliberately written as ES5-compatible CommonJS: this file has to run on
|
||||
* every Node version bowser claims to support, down to 12.16.3. No optional
|
||||
* chaining, no nullish coalescing, no top-level await.
|
||||
*/
|
||||
var assert = require('assert');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var vm = require('vm');
|
||||
|
||||
var UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 '
|
||||
+ '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
||||
|
||||
var passed = 0;
|
||||
function check(name, fn) {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(' ok ' + name);
|
||||
}
|
||||
|
||||
/** Node version gate — ESM was unflagged in 12.17.0. */
|
||||
function nodeAtLeast(major, minor) {
|
||||
var parts = process.versions.node.split('.');
|
||||
var m = Number(parts[0]);
|
||||
var n = Number(parts[1]);
|
||||
return m > major || (m === major && n >= minor);
|
||||
}
|
||||
|
||||
console.log('bowser package smoke test on Node ' + process.versions.node);
|
||||
|
||||
// --- The CommonJS contract -------------------------------------------------
|
||||
// `require('bowser')` must be the Bowser class itself. If it ever becomes
|
||||
// `{ default, parse, getParser }`, every existing consumer breaks.
|
||||
|
||||
check('require("bowser") is the class, not a module namespace', function () {
|
||||
var Bowser = require('bowser');
|
||||
assert.strictEqual(typeof Bowser, 'function');
|
||||
assert.strictEqual(typeof Bowser.getParser, 'function');
|
||||
assert.strictEqual(typeof Bowser.parse, 'function');
|
||||
assert.strictEqual(
|
||||
Bowser.default,
|
||||
undefined,
|
||||
'require("bowser").default is set — the CJS interop unwrap was lost',
|
||||
);
|
||||
});
|
||||
|
||||
check('require("bowser") parses a user agent', function () {
|
||||
var Bowser = require('bowser');
|
||||
assert.strictEqual(Bowser.parse(UA).browser.name, 'Chrome');
|
||||
assert.strictEqual(Bowser.getParser(UA).getBrowserName(), 'Chrome');
|
||||
});
|
||||
|
||||
check('constant maps are exposed', function () {
|
||||
var Bowser = require('bowser');
|
||||
assert.strictEqual(typeof Bowser.BROWSER_MAP, 'object');
|
||||
assert.strictEqual(typeof Bowser.ENGINE_MAP, 'object');
|
||||
assert.strictEqual(typeof Bowser.OS_MAP, 'object');
|
||||
assert.strictEqual(typeof Bowser.PLATFORMS_MAP, 'object');
|
||||
});
|
||||
|
||||
// --- Legacy deep paths -----------------------------------------------------
|
||||
// These resolved before the exports map existed. Adding an exports map without
|
||||
// listing them turns them into ERR_PACKAGE_PATH_NOT_EXPORTED.
|
||||
|
||||
['bowser/es5.js', 'bowser/es5', 'bowser/bundled.js', 'bowser/bundled'].forEach(function (id) {
|
||||
check('require("' + id + '") works', function () {
|
||||
var B = require(id);
|
||||
assert.strictEqual(typeof B, 'function');
|
||||
assert.strictEqual(B.parse(UA).browser.name, 'Chrome');
|
||||
});
|
||||
});
|
||||
|
||||
// The src/*.js files are ES module sources, so they resolve but do not execute
|
||||
// under require(). Bundlers are the real consumer here. Assert resolution only.
|
||||
[
|
||||
'bowser.js', 'constants.js', 'parser.js', 'parser-browsers.js',
|
||||
'parser-engines.js', 'parser-os.js', 'parser-platforms.js', 'utils.js',
|
||||
].forEach(function (file) {
|
||||
var withExt = 'bowser/src/' + file;
|
||||
var withoutExt = withExt.replace(/\.js$/, '');
|
||||
check('resolves "' + withExt + '" and "' + withoutExt + '"', function () {
|
||||
assert.ok(fs.existsSync(require.resolve(withExt)));
|
||||
assert.ok(fs.existsSync(require.resolve(withoutExt)));
|
||||
});
|
||||
});
|
||||
|
||||
check('require.resolve("bowser/package.json") works', function () {
|
||||
assert.ok(fs.existsSync(require.resolve('bowser/package.json')));
|
||||
});
|
||||
|
||||
// --- The published manifest ------------------------------------------------
|
||||
|
||||
check('main/browser/module/types fields are unchanged', function () {
|
||||
var pkg = require('bowser/package.json');
|
||||
assert.strictEqual(pkg.main, 'es5.js');
|
||||
assert.strictEqual(pkg.browser, 'es5.js');
|
||||
assert.strictEqual(pkg.module, 'src/bowser.js');
|
||||
assert.strictEqual(pkg.types, 'index.d.ts');
|
||||
});
|
||||
|
||||
check('no "engines" field (would warn/fail installs on old Node)', function () {
|
||||
var pkg = require('bowser/package.json');
|
||||
assert.strictEqual(pkg.engines, undefined);
|
||||
});
|
||||
|
||||
check('no "type" field (would reclassify es5.js as ESM)', function () {
|
||||
var pkg = require('bowser/package.json');
|
||||
assert.strictEqual(pkg.type, undefined);
|
||||
});
|
||||
|
||||
check('published file list is exactly what we expect', function () {
|
||||
var root = path.dirname(require.resolve('bowser/package.json'));
|
||||
var actual = [];
|
||||
(function walk(dir, prefix) {
|
||||
fs.readdirSync(dir).forEach(function (name) {
|
||||
var full = path.join(dir, name);
|
||||
if (fs.statSync(full).isDirectory()) walk(full, prefix + name + '/');
|
||||
else actual.push(prefix + name);
|
||||
});
|
||||
}(root, ''));
|
||||
|
||||
var expected = [
|
||||
'LICENSE', 'README.md', 'bowser.mjs', 'bundled.js', 'es5.js',
|
||||
'index.d.mts', 'index.d.ts', 'package.json',
|
||||
'src/bowser.js', 'src/constants.js', 'src/parser-browsers.js',
|
||||
'src/parser-engines.js', 'src/parser-os.js', 'src/parser-platforms.js',
|
||||
'src/parser.js', 'src/utils.js',
|
||||
];
|
||||
assert.deepStrictEqual(actual.sort(), expected.sort());
|
||||
});
|
||||
|
||||
// --- The UMD / CDN contract ------------------------------------------------
|
||||
// Script-tag consumers get `window.bowser` (lowercase). Nothing else covers
|
||||
// this path, and a renamed global fails silently at runtime.
|
||||
|
||||
check('es5.js sets a lowercase `bowser` global when loaded as a script', function () {
|
||||
var file = require.resolve('bowser/es5.js');
|
||||
var sandbox = {};
|
||||
sandbox.self = sandbox;
|
||||
vm.runInNewContext(fs.readFileSync(file, 'utf8'), sandbox);
|
||||
assert.strictEqual(typeof sandbox.bowser, 'function', 'global `bowser` not set');
|
||||
assert.strictEqual(sandbox.bowser.parse(UA).browser.name, 'Chrome');
|
||||
assert.strictEqual(sandbox.Bowser, undefined, 'unexpected capitalised global');
|
||||
});
|
||||
|
||||
check('es5.js contains no ES6 template literals', function () {
|
||||
// rolldown's built-in (oxc) minifier rewrites every string literal as a
|
||||
// template literal, which is a syntax error in the old browsers this bundle
|
||||
// targets. Guards against the terser step being dropped from the build.
|
||||
var code = fs.readFileSync(require.resolve('bowser/es5.js'), 'utf8');
|
||||
assert.strictEqual(code.indexOf('`'), -1, 'es5.js contains a backtick');
|
||||
});
|
||||
|
||||
check('es5.js keeps the copyright banner', function () {
|
||||
var code = fs.readFileSync(require.resolve('bowser/es5.js'), 'utf8');
|
||||
assert.ok(code.indexOf('Bowser - a browser detector') !== -1);
|
||||
});
|
||||
|
||||
// --- The ESM contract ------------------------------------------------------
|
||||
|
||||
if (!nodeAtLeast(12, 17)) {
|
||||
console.log(' -- skipping ESM checks (Node ' + process.versions.node + ' < 12.17)');
|
||||
console.log('\n' + passed + ' checks passed');
|
||||
} else {
|
||||
// eslint-disable-next-line no-eval
|
||||
eval('import("bowser")')
|
||||
.then(function (mod) {
|
||||
check('import("bowser") has a working default export', function () {
|
||||
assert.strictEqual(typeof mod.default, 'function');
|
||||
assert.strictEqual(mod.default.parse(UA).browser.name, 'Chrome');
|
||||
});
|
||||
// This is issue #511: named imports must work, and must work unbound.
|
||||
check('import("bowser") has working named exports', function () {
|
||||
assert.strictEqual(typeof mod.parse, 'function');
|
||||
assert.strictEqual(typeof mod.getParser, 'function');
|
||||
var parse = mod.parse;
|
||||
var getParser = mod.getParser;
|
||||
assert.strictEqual(parse(UA).browser.name, 'Chrome');
|
||||
assert.strictEqual(getParser(UA).getBrowserName(), 'Chrome');
|
||||
});
|
||||
console.log('\n' + passed + ' checks passed');
|
||||
})
|
||||
.catch(function (err) {
|
||||
console.error('\nESM check failed: ' + err.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
100
test/package/smoke.cjs
Normal file
100
test/package/smoke.cjs
Normal file
@@ -0,0 +1,100 @@
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* Verifies the *packed* bowser package against the surface real consumers use.
|
||||
*
|
||||
* node test/package/smoke.cjs <path-to-bowser-x.y.z.tgz>
|
||||
*
|
||||
* The tarball is extracted into a throwaway directory as ./node_modules/bowser
|
||||
* and `assertions.cjs` is run next to it, so bare specifiers such as
|
||||
* `require('bowser')` and `require('bowser/es5.js')` resolve exactly as they
|
||||
* would after `npm install bowser`.
|
||||
*
|
||||
* Run this on every Node version bowser supports — that is the point of it.
|
||||
* See `.github/workflows/pull-request.yml`.
|
||||
*
|
||||
* Deliberately ES5-compatible CommonJS so it runs on Node 12.16.3.
|
||||
*/
|
||||
var cp = require('child_process');
|
||||
var fs = require('fs');
|
||||
var os = require('os');
|
||||
var path = require('path');
|
||||
var zlib = require('zlib');
|
||||
|
||||
var tarball = process.argv[2];
|
||||
|
||||
if (!tarball) {
|
||||
console.error('usage: node test/package/smoke.cjs <path-to-tarball.tgz>');
|
||||
console.error('');
|
||||
console.error('Create one with:');
|
||||
console.error(' npm version 0.0.0-ci --no-git-tag-version --allow-same-version');
|
||||
console.error(' npm pack');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
tarball = path.resolve(tarball);
|
||||
if (!fs.existsSync(tarball)) {
|
||||
console.error('no such tarball: ' + tarball);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bowser-smoke-'));
|
||||
var modules = path.join(tmp, 'node_modules');
|
||||
fs.mkdirSync(modules);
|
||||
|
||||
/**
|
||||
* Extracts an npm tarball using only Node built-ins, so the test needs no
|
||||
* external `tar`/`npm` process and runs identically on every OS and every
|
||||
* Node version in the support matrix.
|
||||
*
|
||||
* npm tarballs are gzipped ustar archives of regular files (npm rejects
|
||||
* anything else at publish time), which is the only shape handled here:
|
||||
* pax/global extended headers and directory entries are skipped, and parent
|
||||
* directories are created per file instead.
|
||||
*/
|
||||
function extractNpmTarball(tgz, dest) {
|
||||
var buf = zlib.gunzipSync(fs.readFileSync(tgz));
|
||||
var offset = 0;
|
||||
while (offset + 512 <= buf.length) {
|
||||
var header = buf.slice(offset, offset + 512);
|
||||
offset += 512;
|
||||
if (header[0] === 0) break; // zero block: end of archive
|
||||
var name = header.slice(0, 100).toString('utf8').replace(/\0[\s\S]*$/, '');
|
||||
var prefix = header.slice(345, 500).toString('utf8').replace(/\0[\s\S]*$/, '');
|
||||
if (prefix) name = prefix + '/' + name;
|
||||
var size = parseInt(header.slice(124, 136).toString('utf8'), 8) || 0;
|
||||
var type = header[156];
|
||||
if (type === 48 /* '0' */ || type === 0) {
|
||||
var target = path.join(dest, name);
|
||||
if (target.indexOf(dest + path.sep) !== 0) {
|
||||
throw new Error('tarball entry escapes destination: ' + name);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, buf.slice(offset, offset + size));
|
||||
}
|
||||
offset += Math.ceil(size / 512) * 512;
|
||||
}
|
||||
}
|
||||
|
||||
// npm tarballs always unpack to a single top-level `package/` directory.
|
||||
extractNpmTarball(tarball, modules);
|
||||
fs.renameSync(path.join(modules, 'package'), path.join(modules, 'bowser'));
|
||||
|
||||
var runner = path.join(tmp, 'assertions.cjs');
|
||||
fs.writeFileSync(runner, fs.readFileSync(path.join(__dirname, 'assertions.cjs')));
|
||||
|
||||
var result = cp.spawnSync(process.execPath, [runner], { cwd: tmp, stdio: 'inherit' });
|
||||
|
||||
try {
|
||||
// fs.rmSync landed in Node 14.14; recursive fs.rmdirSync (12.10+) covers the
|
||||
// bottom of the matrix. Both work on Windows, unlike shelling out to `rm`.
|
||||
if (fs.rmSync) {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
} else {
|
||||
fs.rmdirSync(tmp, { recursive: true });
|
||||
}
|
||||
} catch (e) { /* best effort */ }
|
||||
|
||||
if (result.status !== 0) {
|
||||
console.error('\npackage smoke test FAILED on Node ' + process.versions.node);
|
||||
process.exit(result.status || 1);
|
||||
}
|
||||
Reference in New Issue
Block a user