diff --git a/.github/scripts/install-public.cjs b/.github/scripts/install-public.cjs index d52ce61b..358bcf62 100644 --- a/.github/scripts/install-public.cjs +++ b/.github/scripts/install-public.cjs @@ -8,10 +8,9 @@ const path = require('node:path'); const os = require('node:os'); const { createHash } = require('node:crypto'); const { spawnSync } = require('node:child_process'); -const lockHash = '2b3cb29398b9d148aeb8dd321e6436629c16175b42436a46fe59a71e9850825d'; -const manifestHash = 'f77b805a5e292732f617c3814a24f4205ced9b326a5740e039acda6085737f34'; +const lockHash = 'fed4df803f8eddce823bca0310a8227166272531baccd41d850227aede1f4d03'; +const manifestHash = 'ad05ea374fd514879a01d79153b146aadc40dc5063224057e74bf4fe1eec95d1'; const approvedIntegrity = 'sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw=='; -const gitSource = 'git+ssh://git@github.com/ethanresnick/negotiator.git#e2fe4abc56271b9851132f3e508e7323415c8aea'; const patchFiles = { 'LICENSE': [1172, '23d466b1b134b415b66fa50c6526b4cf3e7b9258554da88d3abb371721e7ce68'], 'index.js': [2681, '9c6c900e7e85fb599c62d9b9e4dfd2ea2f61d119dce5ed69ac3a8da828819241'], @@ -28,7 +27,6 @@ const sha = data => createHash('sha256').update(data).digest('hex'); function verifyLock(lock) { let publicPackages = 0; - let gitPackages = 0; const parserPaths = []; for (const [name, value] of Object.entries(lock.packages)) { if (!name) continue; @@ -37,8 +35,7 @@ function verifyLock(lock) { assert.equal(value.integrity, approvedIntegrity); parserPaths.push(name); } - if (value.resolved === gitSource && name === 'node_modules/negotiator') gitPackages++; - else { + { const url = new URL(value.resolved); assert.equal(url.origin, 'https://registry.npmjs.org'); assert.equal(url.username + url.password + url.search + url.hash, ''); @@ -46,7 +43,6 @@ function verifyLock(lock) { } } assert.equal(publicPackages, 532); - assert.equal(gitPackages, 1); assert.deepEqual(parserPaths, ['node_modules/body-parser']); } @@ -108,12 +104,11 @@ function install() { PATH: process.env.PATH, HOME: temporary, npm_config_userconfig: path.join(temporary, 'npmrc'), npm_config_globalconfig: path.join(temporary, 'global-npmrc'), - npm_config_cache: path.join(temporary, 'cache'), - GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0', GIT_ALLOW_PROTOCOL: 'https', - // The unchanged public Git lock source does not require an SSH credential. - GIT_CONFIG_COUNT: '1', - GIT_CONFIG_KEY_0: 'url.https://github.com/ethanresnick/negotiator.git.insteadOf', - GIT_CONFIG_VALUE_0: 'ssh://git@github.com/ethanresnick/negotiator.git' + // Job-local public cache is reused only by the offline packed-consumer test. + // GitHub removes RUNNER_TEMP with the disposable job; nothing is uploaded. + npm_config_cache: process.env.RUNNER_TEMP + ? path.join(process.env.RUNNER_TEMP, 'json-api-public-cache') + : path.join(temporary, 'cache') }; const child = spawnSync(process.execPath, [path.join(npmRoot, 'bin/npm-cli.js'), 'ci'], { cwd: root, env, stdio: 'inherit', timeout: 240000 }); diff --git a/.github/scripts/install-public.test.cjs b/.github/scripts/install-public.test.cjs index 91c0b985..6eb71d0f 100644 --- a/.github/scripts/install-public.test.cjs +++ b/.github/scripts/install-public.test.cjs @@ -20,8 +20,8 @@ test('rejects private or authenticated registry destinations before npm runs', ( assert.throws(() => verifyLock(lock)); } }); -test('rejects changed Git source identity before npm runs', () => { - const lock = fresh(); lock.packages['node_modules/negotiator'].resolved += '0'; +test('rejects every external Git source before npm runs', () => { + const lock = fresh(); lock.packages['node_modules/body-parser'].resolved = 'git+https://github.com/ethanresnick/negotiator.git#e2fe4abc56271b9851132f3e508e7323415c8aea'; assert.throws(() => verifyLock(lock)); }); diff --git a/.github/scripts/qualify.sh b/.github/scripts/qualify.sh index 6c143b75..2c78859c 100644 --- a/.github/scripts/qualify.sh +++ b/.github/scripts/qualify.sh @@ -12,6 +12,7 @@ export npm_config_audit=false npm_config_fund=false npm_config_ignore_scripts=tr unset NODE_OPTIONS NODE_PATH timeout --kill-after=5s 180s npm run build +timeout --kill-after=5s 120s npm run test:vendor if [ "$1" = full ]; then timeout --kill-after=5s 120s npm run test:tooling else diff --git a/.github/workflows/qualification.yml b/.github/workflows/qualification.yml index 6c74b4b3..a0350804 100644 --- a/.github/workflows/qualification.yml +++ b/.github/workflows/qualification.yml @@ -41,6 +41,10 @@ jobs: run: node .github/scripts/install-public.cjs - name: Build, lint, tooling and both unit forms run: bash .github/scripts/qualify.sh full + - name: Verify isolated packed consumer offline + env: + JSON_API_PUBLIC_CACHE: ${{ runner.temp }}/json-api-public-cache + run: timeout --kill-after=5s 180s npm run test:package - name: Complete isolated database integration suite env: HOST: 127.0.0.1 @@ -78,3 +82,7 @@ jobs: package-manager-cache: false - name: Build, lint and runtime compatibility run: bash .github/scripts/qualify.sh compatibility + - name: Verify isolated packed consumer offline + env: + JSON_API_PUBLIC_CACHE: ${{ runner.temp }}/json-api-public-cache + run: timeout --kill-after=5s 180s npm run test:package diff --git a/docs/ci-qualification.md b/docs/ci-qualification.md index 9d2f0282..0d74ddd6 100644 --- a/docs/ci-qualification.md +++ b/docs/ci-qualification.md @@ -10,17 +10,32 @@ the emitted public entry, fixture installation, and the complete existing unit and integration selection. Node 18.20.8 runs lint/build, source and compiled units, the public entry, body-parser and lint controls. Dependencies are installed under the Node 24 distribution's npm 11.19.1 before switching the compatibility -job to Node 18. No runtime, package manifest, or dependency lock changes are made. +job to Node 18. The jobs do not rewrite runtime source, manifests or the lock. +Both runtimes also run the original 250 internal Negotiator tests, bounded parser +regressions, and an actual offline packed-package consumer installation. Installation uses an empty temporary credential route, disabled install scripts and audit requests, the public npm registry, and a seven-day release-age guard. The existing exact body-parser 1.20.9 exception is bounded by the frozen source hashes, exact version/integrity, and all ten installed tarball file hashes. -The unchanged public Negotiator commit uses an invocation-only HTTPS rewrite; -no SSH keys, global configuration, private grants, or private registries are used. +All 532 external lock nodes use the public registry. The custom Negotiator runtime +is now internal source under `vendor/negotiator`, with MIT/provenance retained and +the exact upstream language-parser fix. External Git dependencies and their +HTTPS rewrite exception are removed. No SSH keys, global configuration, private +grants or private registries are used. Dependency changes require a renewed source/age review and updated qualification hashes. A successful workflow is not a fresh vulnerability scan. +The install retains only its public npm cache in the disposable job's +`RUNNER_TEMP`; no cache is uploaded or shared between jobs. The package test uses +that cache offline, with lifecycle scripts disabled, and rejects dependency +versions outside the reviewed lock. It packs the real library using its existing +prepare build, installs it with lifecycle scripts disabled in a +temporary downstream project, verifies source/compiled internal runtime bytes, +exercises the public entry and real media/language behavior, and compiles a +declaration consumer. Checkout fallback is rejected. Its isolated consumer is +removed on completion; GitHub removes the job cache with the disposable job. + The integration job uses only its disposable official Mongo 7.0.45 Jammy service, pinned by digest and mapped to loopback port 27017. Existing tests hard-code `mongodb://localhost/integration-test`; IPv4 resolution and the HTTP test host diff --git a/package-lock.json b/package-lock.json index 1e17430a..00ddcd0b 100755 --- a/package-lock.json +++ b/package-lock.json @@ -26,7 +26,6 @@ "depd": "^1.1.2", "immutable": "^3.8.4", "lodash": "^4.18.1", - "negotiator": "git+https://github.com/ethanresnick/negotiator.git#e2fe4abc56271b9851132f3e508e7323415c8aea", "pluralize": "0.0.11", "pug": "^3.0.3", "qs": "^6.5.3", @@ -4063,15 +4062,6 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, - "node_modules/negotiator": { - "version": "0.6.0", - "resolved": "git+ssh://git@github.com/ethanresnick/negotiator.git#e2fe4abc56271b9851132f3e508e7323415c8aea", - "integrity": "sha512-rxRPqLO57odzcwOZuW7TC8hM41rmlK6TvAFnj9hvnwCQIZGIr1KJ8a6Km/5W05DXu/3CFWLfkDLTw0ONmUnhGw==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/nise": { "version": "5.1.9", "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.9.tgz", diff --git a/package.json b/package.json index 05cea6cf..ab10f6db 100755 --- a/package.json +++ b/package.json @@ -54,7 +54,6 @@ "depd": "^1.1.2", "immutable": "^3.8.4", "lodash": "^4.18.1", - "negotiator": "git+https://github.com/ethanresnick/negotiator.git#e2fe4abc56271b9851132f3e508e7323415c8aea", "pluralize": "0.0.11", "pug": "^3.0.3", "qs": "^6.5.3", @@ -113,7 +112,7 @@ "test:unit": "NODE_ENV=testing mocha --require ts-node/register --extension ts --recursive test/unit/ --full-trace --check-leaks", "test:tooling": "node --test test/tooling-security.cjs test/lint-compatibility.cjs test/body-parser-security.cjs", "test:debug": "npm run test -- --inspect-brk", - "build:lintfree": "npm run clean && cpr templates build/templates && echo Using TypeScript && tsc --version && tsc --pretty", + "build:lintfree": "npm run clean && cpr templates build/templates && cpr vendor build/vendor && echo Using TypeScript && tsc --version && tsc --pretty", "build": "npm run lint && npm run build:lintfree", "prepare": "npm run build", "prepublishOnly": "npm run test", @@ -121,7 +120,9 @@ "cover:view": "npm run cover && open coverage/index.html", "watch": "npm run build -- --watch", "watch:lintfree": "npm run build:lintfree -- --watch", - "watch:test": "npm run test -- --watch" + "watch:test": "npm run test -- --watch", + "test:vendor": "node --test --test-reporter=tap test/negotiator-security.cjs && mocha --reporter dot --check-leaks test/vendor-negotiator/", + "test:package": "node scripts/verify-packed-consumer.cjs" }, "bugs": { "url": "https://github.com/ethanresnick/json-api/issues" @@ -138,5 +139,12 @@ ], "engines": { "node": ">=18.20.8" - } + }, + "files": [ + "build", + "src", + "typings", + "templates", + "vendor" + ] } diff --git a/scripts/verify-packed-consumer.cjs b/scripts/verify-packed-consumer.cjs new file mode 100644 index 00000000..c3e54060 --- /dev/null +++ b/scripts/verify-packed-consumer.cjs @@ -0,0 +1,127 @@ +'use strict'; + +// Local/offline package delivery proof. The cache must contain only the reviewed +// public lock's packages; no credentials, registry requests or install scripts. +// Packing runs this repository's existing prepare build, as publication would. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const root = path.resolve(__dirname, '..'); +const cache = process.env.JSON_API_PUBLIC_CACHE; +assert(cache && path.isAbsolute(cache), 'Set JSON_API_PUBLIC_CACHE to the reviewed temporary public cache'); +const npm = path.resolve(path.dirname(fs.realpathSync(process.execPath)), '../lib/node_modules/npm/bin/npm-cli.js'); +const lock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'))); +const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'))); +const reviewed = new Set(Object.entries(lock.packages).filter(([location]) => location).map(([location, item]) => + (item.name || location.split('node_modules/').pop()) + '@' + item.version)); +const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'json-api-packed-consumer-')); +try { + const userconfig = path.join(temporary, 'npmrc'); + fs.writeFileSync(userconfig, 'registry=https://registry.npmjs.org\naudit=false\nfund=false\nignore-scripts=true\noffline=true\nmin-release-age=7\nmin-release-age-exclude[]=body-parser\n'); + const env = { PATH: process.env.PATH, HOME: temporary, npm_config_userconfig: userconfig, + npm_config_globalconfig: '/dev/null', npm_config_cache: cache }; + function run(args, cwd) { + const child = spawnSync(process.execPath, args, { cwd, env, encoding: 'utf8', timeout: 120000 }); + assert.ifError(child.error); + assert.equal(child.status, 0, (child.stdout + child.stderr).slice(-4000)); + return child.stdout; + } + const packed = JSON.parse(run([npm, 'pack', '--ignore-scripts=false', '--foreground-scripts=false', '--json', '--pack-destination', temporary], root))[0]; + const files = new Set(packed.files.map(file => file.path)); + for (const name of ['index.js', 'index.d.ts', 'lib/language.js', 'lib/mediaType.js', 'LICENSE']) { + assert(files.has('vendor/negotiator/' + name)); + assert(files.has('build/vendor/negotiator/' + name)); + } + assert(files.has('build/src/index.js') && files.has('build/src/index.d.ts')); + assert(files.has('src/steps/http/content-negotiation/negotiate-content-type.ts')); + assert(![...files].some(name => name.startsWith('node_modules/') || name.startsWith('.github/'))); + const consumer = path.join(temporary, 'consumer'); fs.mkdirSync(consumer); + const tarball = path.join(temporary, packed.filename); + const consumerManifest = { name: 'isolated-public-consumer', version: '1.0.0', private: true, + dependencies: { 'json-api': 'file:' + tarball, express: lock.packages['node_modules/express'].version, + mongoose: lock.packages['node_modules/mongoose'].version } }; + fs.writeFileSync(path.join(consumer, 'package.json'), JSON.stringify(consumerManifest)); + // A clean downstream install uses a lock, just as a real reproducible consumer + // should. Project only its reachable nodes from the reviewed library lock. + // npm ci's cache contains exact tarballs, not registry version-selection data. + const packages = { '': consumerManifest, 'node_modules/json-api': { + version: manifest.version, resolved: 'file:' + tarball, integrity: packed.integrity, + dependencies: manifest.dependencies, peerDependencies: manifest.peerDependencies, + engines: manifest.engines + } }; + function resolve(name, from) { + let current = from; + while (true) { + const location = (current ? current + '/' : '') + 'node_modules/' + name; + if (lock.packages[location]) return location; + if (!current) return undefined; + const parent = path.posix.dirname(current); + current = parent === '.' ? '' : parent; + } + } + const queue = Object.keys(manifest.dependencies).concat(['express', 'mongoose']).map(name => resolve(name, '')); + while (queue.length) { + const location = queue.shift(); assert(location, 'Missing reviewed dependency'); + if (packages[location]) continue; + const item = { ...lock.packages[location] }; delete item.dev; delete item.devOptional; + packages[location] = item; + for (const name of Object.keys({ ...item.dependencies, ...item.optionalDependencies, ...item.peerDependencies })) { + const next = resolve(name, location); + if (next) queue.push(next); + else assert(item.optionalDependencies?.[name] || item.peerDependenciesMeta?.[name]?.optional, 'Missing reviewed transitive dependency: ' + name); + } + } + fs.writeFileSync(path.join(consumer, 'package-lock.json'), JSON.stringify({ name: consumerManifest.name, + version: consumerManifest.version, lockfileVersion: 3, requires: true, packages })); + run([npm, 'ci', '--offline', '--ignore-scripts', '--legacy-peer-deps', '--no-audit', '--no-fund'], consumer); + const installed = JSON.parse(fs.readFileSync(path.join(consumer, 'package-lock.json'))); + for (const [location, item] of Object.entries(installed.packages)) { + if (!location || location === 'node_modules/json-api') continue; + const name = item.name || location.split('node_modules/').pop(); + assert(reviewed.has(name + '@' + item.version), 'Unreviewed downstream resolution: ' + name); + assert.equal(new URL(item.resolved).origin, 'https://registry.npmjs.org'); + if (name === 'body-parser') assert.equal(item.version, '1.20.9'); + } + const packageRoot = path.join(consumer, 'node_modules/json-api'); + assert(!JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'))).dependencies.negotiator); + for (const name of ['index.js', 'lib/charset.js', 'lib/encoding.js', 'lib/language.js', 'lib/mediaType.js']) { + const original = fs.readFileSync(path.join(root, 'vendor/negotiator', name)); + assert.deepEqual(fs.readFileSync(path.join(packageRoot, 'vendor/negotiator', name)), original); + assert.deepEqual(fs.readFileSync(path.join(packageRoot, 'build/vendor/negotiator', name)), original); + } + const smoke = ` + const assert=require('node:assert/strict'); + const api=require('json-api'); + const N=require('json-api/build/vendor/negotiator'); + const sourceN=require('json-api/vendor/negotiator'); + const negotiate=require('json-api/build/src/steps/http/content-negotiation/negotiate-content-type').default; + assert.equal(typeof api.APIController,'function'); + for(const Constructor of [N,sourceN]){ + assert.deepEqual(new Constructor({headers:{'accept-language':'en-US,en;q=0.8'}}).languages(),['en-US','en']); + const rows=new Constructor({headers:{accept:'application/vnd.api+json;ext=example,application/json;q=0.8'}}).mediaTypes(undefined,{detailed:true}); + assert.equal(rows[0].type,'application/vnd.api+json');assert.equal(rows[0].parameters.ext,'example'); + assert.equal(Object.getPrototypeOf(rows[0].parameters),null); + } + (async()=>{ + assert.equal(await negotiate('application/vnd.api+json',['application/vnd.api+json']),'application/vnd.api+json'); + await assert.rejects(negotiate('application/vnd.api+json;ext=x,application/json',['application/vnd.api+json']),e=>e.status==='406'); + assert.equal(await negotiate('application/vnd.api+json;ext=x,application/vnd.api+json',['application/vnd.api+json']),'application/vnd.api+json'); + const prefix=process.cwd()+require('node:path').sep+'node_modules'+require('node:path').sep; + assert(Object.keys(require.cache).every(file=>file.startsWith(prefix)),'Checkout fallback loaded'); + console.log('PACKED_PUBLIC_ENTRY_MEDIA_LANGUAGE_PASS'); + })().catch(e=>{console.error(e);process.exitCode=1;});`; + assert(run(['-e', smoke], consumer).includes('PACKED_PUBLIC_ENTRY_MEDIA_LANGUAGE_PASS')); + const child = spawnSync(process.execPath, ['-e', "const a=require('node:assert/strict'),N=require('json-api/build/vendor/negotiator');a.deepEqual(new N({headers:{'accept-language':'a-'.repeat(30000)+'x y'}}).languages(),[]);"], + { cwd: consumer, env, timeout: 1000, killSignal: 'SIGKILL' }); + assert.ifError(child.error); assert.equal(child.status, 0); + fs.writeFileSync(path.join(consumer, 'consumer.ts'), 'import N = require("json-api/build/vendor/negotiator");\nconst rows: N.DetailedMediaType[] = new N({headers:{accept:"application/json"}}).mediaTypes(undefined,{detailed:true});\nconst languages: string[] = new N({headers:{}}).languages();\nconsole.log(rows,languages);\n'); + run([path.join(root, 'node_modules/typescript/bin/tsc'), '--noEmit', '--strict', '--skipLibCheck', '--target', 'es2018', '--module', 'commonjs', '--moduleResolution', 'node', 'consumer.ts'], consumer); + console.log(JSON.stringify({ state: 'PACKED_ISOLATED_OFFLINE_CONSUMER_PASS', files: files.size, + packageIntegrity: packed.integrity, installedNodes: Object.keys(installed.packages).length - 1, + checkoutFallback: false, sourceAndCompiledVendorBytesMatch: true, declarationsPass: true, + libraryVersion: packed.version, dependencyVersionsRestrictedToReviewedLock: true })); +} finally { + fs.rmSync(temporary, { recursive: true, force: true }); +} diff --git a/src/controllers/Documentation.ts b/src/controllers/Documentation.ts index 76d22b8a..09f437d2 100755 --- a/src/controllers/Documentation.ts +++ b/src/controllers/Documentation.ts @@ -1,7 +1,7 @@ import _ = require("lodash"); import path = require("path"); import pug = require("pug"); -import Negotiator = require("negotiator"); +import Negotiator = require("../../vendor/negotiator"); import dasherize = require("dasherize"); import ResourceTypeRegistry, { ResourceTypeDescription, ResourceTypeInfo } from "../ResourceTypeRegistry"; diff --git a/src/steps/http/content-negotiation/negotiate-content-type.ts b/src/steps/http/content-negotiation/negotiate-content-type.ts index e0de305a..ff69439d 100755 --- a/src/steps/http/content-negotiation/negotiate-content-type.ts +++ b/src/steps/http/content-negotiation/negotiate-content-type.ts @@ -1,4 +1,4 @@ -import Negotiator = require("negotiator"); +import Negotiator = require("../../../../vendor/negotiator"); import * as Errors from "../../../util/errors"; import { objectIsEmpty } from "../../../util/misc"; diff --git a/test/negotiator-security.cjs b/test/negotiator-security.cjs new file mode 100644 index 00000000..ba1618f9 --- /dev/null +++ b/test/negotiator-security.cjs @@ -0,0 +1,37 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const Negotiator = require('../vendor/negotiator'); + +test('preserves regional language preference and quality exclusions', () => { + const n = new Negotiator({ headers: { 'accept-language': 'en-US,en;q=0.8,fr;q=0' } }); + assert.deepEqual(n.languages(), ['en-US', 'en']); + assert.equal(n.language(['fr', 'en']), 'en'); +}); + +test('rejects bounded adversarial language input without excessive backtracking', () => { + // An isolated process bounds both vulnerable-baseline work and regression failure. + // This is synthetic parser input, never a network request or application probe. + const child = spawnSync(process.execPath, ['-e', + "const assert=require('node:assert/strict');const language=require('./lib/language');" + + "assert.deepEqual(language('a-'.repeat(30000)+'x y'),[]);process.stdout.write('PASS');" + ], { + cwd: path.join(__dirname, '../vendor/negotiator'), timeout: 1000, killSignal: 'SIGKILL', + encoding: 'utf8', env: { PATH: process.env.PATH } + }); + assert.ifError(child.error); + assert.equal(child.status, 0); + assert.equal(child.stdout, 'PASS'); +}); + +test('retains custom detailed media types required by JSON API', () => { + const n = new Negotiator({ headers: { accept: 'application/vnd.api+json;ext=example;q=0.8,application/json' } }); + assert.deepEqual(n.mediaTypes(undefined, { detailed: true }), [ + { type: 'application/json', parameters: Object.create(null), q: 1 }, + { type: 'application/vnd.api+json', parameters: Object.assign(Object.create(null), { ext: 'example' }), q: 0.8 } + ]); + assert.equal(n.mediaType(['application/vnd.api+json', 'application/json']), 'application/json'); +}); diff --git a/test/vendor-negotiator/charset.js b/test/vendor-negotiator/charset.js new file mode 100644 index 00000000..50ed262f --- /dev/null +++ b/test/vendor-negotiator/charset.js @@ -0,0 +1,329 @@ + +var assert = require('assert') +var Negotiator = require('../../vendor/negotiator') + +describe('negotiator.charset()', function () { + whenAcceptCharset(undefined, function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.charset(), '*') + }) + }) + + whenAcceptCharset('*', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.charset(), '*') + }) + }) + + whenAcceptCharset('*, UTF-8', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.charset(), '*') + }) + }) + + whenAcceptCharset('*, UTF-8;q=0', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.charset(), '*') + }) + }) + + whenAcceptCharset('ISO-8859-1', function () { + it('should return ISO-8859-1', function () { + assert.strictEqual(this.negotiator.charset(), 'ISO-8859-1') + }) + }) + + whenAcceptCharset('UTF-8;q=0', function () { + it('should return undefined', function () { + assert.strictEqual(this.negotiator.charset(), undefined) + }) + }) + + whenAcceptCharset('UTF-8, ISO-8859-1', function () { + it('should return UTF-8', function () { + assert.strictEqual(this.negotiator.charset(), 'UTF-8') + }) + }) + + whenAcceptCharset('UTF-8;q=0.8, ISO-8859-1', function () { + it('should return ISO-8859-1', function () { + assert.strictEqual(this.negotiator.charset(), 'ISO-8859-1') + }) + }) + + whenAcceptCharset('UTF-8;q=0.9, ISO-8859-1;q=0.8, UTF-8;q=0.7', function () { + it('should return UTF-8', function () { + assert.strictEqual(this.negotiator.charset(), 'UTF-8') + }) + }) +}) + +describe('negotiator.charset(array)', function () { + whenAcceptCharset(undefined, function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.charset([]), undefined) + }) + + it('should return first type in list', function () { + assert.strictEqual(this.negotiator.charset(['UTF-8']), 'UTF-8') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'ISO-8859-1']), 'UTF-8') + }) + }) + + whenAcceptCharset('*', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.charset([]), undefined) + }) + + it('should return first type in list', function () { + assert.strictEqual(this.negotiator.charset(['UTF-8']), 'UTF-8') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'ISO-8859-1']), 'UTF-8') + }) + }) + + whenAcceptCharset('*, UTF-8', function () { + it('should return first type in list', function () { + assert.strictEqual(this.negotiator.charset(['UTF-8']), 'UTF-8') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'ISO-8859-1']), 'UTF-8') + }) + }) + + whenAcceptCharset('*, UTF-8;q=0', function () { + it('should return most client-preferred charset', function () { + assert.strictEqual(this.negotiator.charset(['UTF-8', 'ISO-8859-1']), 'ISO-8859-1') + }) + + it('should exclude UTF-8', function () { + assert.strictEqual(this.negotiator.charset(['UTF-8']), undefined) + }) + }) + + whenAcceptCharset('ISO-8859-1', function () { + it('should return matching charset', function () { + assert.strictEqual(this.negotiator.charset(['ISO-8859-1']), 'ISO-8859-1') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'ISO-8859-1']), 'ISO-8859-1') + }) + + it('should be case insensitive, returning provided casing', function () { + assert.strictEqual(this.negotiator.charset(['iso-8859-1']), 'iso-8859-1') + assert.strictEqual(this.negotiator.charset(['iso-8859-1', 'ISO-8859-1']), 'iso-8859-1') + assert.strictEqual(this.negotiator.charset(['ISO-8859-1', 'iso-8859-1']), 'ISO-8859-1') + }) + + it('should return undefined when no matching charsets', function () { + assert.strictEqual(this.negotiator.charset(['utf-8']), undefined) + }) + }) + + whenAcceptCharset('UTF-8;q=0', function () { + it('should always return undefined', function () { + assert.strictEqual(this.negotiator.charset(['ISO-8859-1']), undefined) + assert.strictEqual(this.negotiator.charset(['UTF-8', 'KOI8-R', 'ISO-8859-1']), undefined) + assert.strictEqual(this.negotiator.charset(['KOI8-R']), undefined) + }) + }) + + whenAcceptCharset('UTF-8, ISO-8859-1', function () { + it('should return first matching charset', function () { + assert.strictEqual(this.negotiator.charset(['ISO-8859-1']), 'ISO-8859-1') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'KOI8-R', 'ISO-8859-1']), 'UTF-8') + }) + + it('should return undefined when no matching charsets', function () { + assert.strictEqual(this.negotiator.charset(['KOI8-R']), undefined) + }) + }) + + whenAcceptCharset('UTF-8;q=0.8, ISO-8859-1', function () { + it('should return most client-preferred charset', function () { + assert.strictEqual(this.negotiator.charset(['ISO-8859-1']), 'ISO-8859-1') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'KOI8-R', 'ISO-8859-1']), 'ISO-8859-1') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'KOI8-R']), 'UTF-8') + }) + }) + + whenAcceptCharset('UTF-8;q=0.9, ISO-8859-1;q=0.8, UTF-8;q=0.7', function () { + it('should use highest perferred order on duplicate', function () { + assert.strictEqual(this.negotiator.charset(['ISO-8859-1']), 'ISO-8859-1') + assert.strictEqual(this.negotiator.charset(['UTF-8', 'ISO-8859-1']), 'UTF-8') + assert.strictEqual(this.negotiator.charset(['ISO-8859-1', 'UTF-8']), 'UTF-8') + }) + }) +}) + +describe('negotiator.charsets()', function () { + whenAcceptCharset(undefined, function () { + it('should return *', function () { + assert.deepEqual(this.negotiator.charsets(), ['*']) + }) + }) + + whenAcceptCharset('*', function () { + it('should return *', function () { + assert.deepEqual(this.negotiator.charsets(), ['*']) + }) + }) + + whenAcceptCharset('*, UTF-8', function () { + it('should return client-preferred charsets', function () { + assert.deepEqual(this.negotiator.charsets(), ['*', 'UTF-8']) + }) + }) + + whenAcceptCharset('*, UTF-8;q=0', function () { + it('should exclude UTF-8', function () { + assert.deepEqual(this.negotiator.charsets(), ['*']) + }) + }) + + whenAcceptCharset('UTF-8;q=0', function () { + it('should return empty list', function () { + assert.deepEqual(this.negotiator.charsets(), []) + }) + }) + + whenAcceptCharset('ISO-8859-1', function () { + it('should return client-preferred charsets', function () { + assert.deepEqual(this.negotiator.charsets(), ['ISO-8859-1']) + }) + }) + + whenAcceptCharset('UTF-8, ISO-8859-1', function () { + it('should return client-preferred charsets', function () { + assert.deepEqual(this.negotiator.charsets(), ['UTF-8', 'ISO-8859-1']) + }) + }) + + whenAcceptCharset('UTF-8;q=0.8, ISO-8859-1', function () { + it('should return client-preferred charsets', function () { + assert.deepEqual(this.negotiator.charsets(), ['ISO-8859-1', 'UTF-8']) + }) + }) + + whenAcceptCharset('UTF-8;q=0.9, ISO-8859-1;q=0.8, UTF-8;q=0.7', function () { + it.skip('should use highest perferred order on duplicate', function () { + assert.deepEqual(this.negotiator.charsets(), ['UTF-8', 'ISO-8859-1']) + }) + }) +}) + +describe('negotiator.charsets(array)', function () { + whenAcceptCharset(undefined, function () { + it('should return empty list for empty list', function () { + assert.deepEqual(this.negotiator.charsets([]), []) + }) + + it('should return original list', function () { + assert.deepEqual(this.negotiator.charsets(['UTF-8']), ['UTF-8']) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'ISO-8859-1']), ['UTF-8', 'ISO-8859-1']) + }) + }) + + whenAcceptCharset('*', function () { + it('should return empty list for empty list', function () { + assert.deepEqual(this.negotiator.charsets([]), []) + }) + + it('should return original list', function () { + assert.deepEqual(this.negotiator.charsets(['UTF-8']), ['UTF-8']) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'ISO-8859-1']), ['UTF-8', 'ISO-8859-1']) + }) + }) + + whenAcceptCharset('*, UTF-8', function () { + it('should return matching charsets', function () { + assert.deepEqual(this.negotiator.charsets(['UTF-8']), ['UTF-8']) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'ISO-8859-1']), ['UTF-8', 'ISO-8859-1']) + }) + }) + + whenAcceptCharset('*, UTF-8;q=0', function () { + it('should exclude UTF-8', function () { + assert.deepEqual(this.negotiator.charsets(['UTF-8']), []) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'ISO-8859-1']), ['ISO-8859-1']) + }) + }) + + whenAcceptCharset('UTF-8;q=0', function () { + it('should always return empty list', function () { + assert.deepEqual(this.negotiator.charsets(['ISO-8859-1']), []) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'KOI8-R', 'ISO-8859-1']), []) + assert.deepEqual(this.negotiator.charsets(['KOI8-R']), []) + }) + }) + + whenAcceptCharset('ISO-8859-1', function () { + it('should return matching charsets', function () { + assert.deepEqual(this.negotiator.charsets(['ISO-8859-1']), ['ISO-8859-1']) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'ISO-8859-1']), ['ISO-8859-1']) + }) + + it('should be case insensitive, returning provided casing', function () { + assert.deepEqual(this.negotiator.charsets(['iso-8859-1']), ['iso-8859-1']) + assert.deepEqual(this.negotiator.charsets(['iso-8859-1', 'ISO-8859-1']), ['iso-8859-1', 'ISO-8859-1']) + assert.deepEqual(this.negotiator.charsets(['ISO-8859-1', 'iso-8859-1']), ['ISO-8859-1', 'iso-8859-1']) + }) + + it('should return empty list when no matching charsets', function () { + assert.deepEqual(this.negotiator.charsets(['utf-8']), []) + }) + }) + + whenAcceptCharset('UTF-8, ISO-8859-1', function () { + it('should return matching charsets', function () { + assert.deepEqual(this.negotiator.charsets(['ISO-8859-1']), ['ISO-8859-1']) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'KOI8-R', 'ISO-8859-1']), ['UTF-8', 'ISO-8859-1']) + }) + + it('should return empty list when no matching charsets', function () { + assert.deepEqual(this.negotiator.charsets(['KOI8-R']), []) + }) + }) + + whenAcceptCharset('UTF-8;q=0.8, ISO-8859-1', function () { + it('should return matching charsets in client-preferred order', function () { + assert.deepEqual(this.negotiator.charsets(['ISO-8859-1']), ['ISO-8859-1']) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'KOI8-R', 'ISO-8859-1']), ['ISO-8859-1', 'UTF-8']) + }) + + it('should return empty list when no matching charsets', function () { + assert.deepEqual(this.negotiator.charsets(['KOI8-R']), []) + }) + }) + + whenAcceptCharset('UTF-8;q=0.9, ISO-8859-1;q=0.8, UTF-8;q=0.7', function () { + it('should use highest perferred order on duplicate', function () { + assert.deepEqual(this.negotiator.charsets(['ISO-8859-1']), ['ISO-8859-1']) + assert.deepEqual(this.negotiator.charsets(['UTF-8', 'ISO-8859-1']), ['UTF-8', 'ISO-8859-1']) + assert.deepEqual(this.negotiator.charsets(['ISO-8859-1', 'UTF-8']), ['UTF-8', 'ISO-8859-1']) + }) + }) +}) + +function createRequest(headers) { + var request = { + headers: {} + } + + if (headers) { + Object.keys(headers).forEach(function (key) { + request.headers[key.toLowerCase()] = headers[key] + }) + } + + return request +} + +function whenAcceptCharset(acceptCharset, func) { + var description = !acceptCharset + ? 'when no Accept-Charset' + : 'when Accept-Charset: ' + acceptCharset + + describe(description, function () { + before(function () { + this.negotiator = new Negotiator(createRequest({'Accept-Charset': acceptCharset})) + }) + + func() + }) +} diff --git a/test/vendor-negotiator/encoding.js b/test/vendor-negotiator/encoding.js new file mode 100644 index 00000000..3dde8ffa --- /dev/null +++ b/test/vendor-negotiator/encoding.js @@ -0,0 +1,442 @@ + +var assert = require('assert') +var Negotiator = require('../../vendor/negotiator') + +describe('negotiator.encoding()', function () { + whenAcceptEncoding(undefined, function () { + it('should return identity', function () { + assert.strictEqual(this.negotiator.encoding(), 'identity') + }) + }) + + whenAcceptEncoding('*', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.encoding(), '*') + }) + }) + + whenAcceptEncoding('*, gzip', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.encoding(), '*') + }) + }) + + whenAcceptEncoding('*, gzip;q=0', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.encoding(), '*') + }) + }) + + whenAcceptEncoding('*;q=0', function () { + it('should return undefined', function () { + assert.strictEqual(this.negotiator.encoding(), undefined) + }) + }) + + whenAcceptEncoding('*;q=0, identity;q=1', function () { + it('should return identity', function () { + assert.strictEqual(this.negotiator.encoding(), 'identity') + }) + }) + + whenAcceptEncoding('identity', function () { + it('should return identity', function () { + assert.strictEqual(this.negotiator.encoding(), 'identity') + }) + }) + + whenAcceptEncoding('identity;q=0', function () { + it('should return undefined', function () { + assert.strictEqual(this.negotiator.encoding(), undefined) + }) + }) + + whenAcceptEncoding('gzip', function () { + it('should return gzip', function () { + assert.strictEqual(this.negotiator.encoding(), 'gzip') + }) + }) + + whenAcceptEncoding('gzip, compress;q=0', function () { + it('should return gzip', function () { + assert.strictEqual(this.negotiator.encoding(), 'gzip') + }) + }) + + whenAcceptEncoding('gzip, deflate', function () { + it('should return gzip', function () { + assert.strictEqual(this.negotiator.encoding(), 'gzip') + }) + }) + + whenAcceptEncoding('gzip;q=0.8, deflate', function () { + it('should return deflate', function () { + assert.strictEqual(this.negotiator.encoding(), 'deflate') + }) + }) + + whenAcceptEncoding('gzip;q=0.8, identity;q=0.5, *;q=0.3', function () { + it('should return gzip', function () { + assert.strictEqual(this.negotiator.encoding(), 'gzip') + }) + }) +}) + +describe('negotiator.encoding(array)', function () { + whenAcceptEncoding(undefined, function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.encoding([]), undefined) + }) + + it('should only match identity', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), 'identity') + assert.strictEqual(this.negotiator.encoding(['gzip']), undefined) + }) + }) + + whenAcceptEncoding('*', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.encoding([]), undefined) + }) + + it('should return first item in list', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), 'identity') + assert.strictEqual(this.negotiator.encoding(['gzip']), 'gzip') + assert.strictEqual(this.negotiator.encoding(['gzip', 'identity']), 'gzip') + }) + }) + + whenAcceptEncoding('*, gzip', function () { + it('should prefer gzip', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), 'identity') + assert.strictEqual(this.negotiator.encoding(['gzip']), 'gzip') + assert.strictEqual(this.negotiator.encoding(['compress', 'gzip']), 'gzip') + }) + }) + + whenAcceptEncoding('*, gzip;q=0', function () { + it('should exclude gzip', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), 'identity') + assert.strictEqual(this.negotiator.encoding(['gzip']), undefined) + assert.strictEqual(this.negotiator.encoding(['gzip', 'compress']), 'compress') + }) + }) + + whenAcceptEncoding('*;q=0', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.encoding([]), undefined) + }) + + it('should match nothing', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), undefined) + assert.strictEqual(this.negotiator.encoding(['gzip']), undefined) + }) + }) + + whenAcceptEncoding('*;q=0, identity;q=1', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.encoding([]), undefined) + }) + + it('should still match identity', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), 'identity') + assert.strictEqual(this.negotiator.encoding(['gzip']), undefined) + }) + }) + + whenAcceptEncoding('identity', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.encoding([]), undefined) + }) + + it('should only match identity', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), 'identity') + assert.strictEqual(this.negotiator.encoding(['gzip']), undefined) + }) + }) + + whenAcceptEncoding('identity;q=0', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.encoding([]), undefined) + }) + + it('should match nothing', function () { + assert.strictEqual(this.negotiator.encoding(['identity']), undefined) + assert.strictEqual(this.negotiator.encoding(['gzip']), undefined) + }) + }) + + whenAcceptEncoding('gzip', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.encoding([]), undefined) + }) + + it('should return client-preferred encodings', function () { + assert.strictEqual(this.negotiator.encoding(['gzip']), 'gzip') + assert.strictEqual(this.negotiator.encoding(['identity', 'gzip']), 'gzip') + assert.strictEqual(this.negotiator.encoding(['identity']), 'identity') + }) + }) + + whenAcceptEncoding('gzip, compress;q=0', function () { + it('should not return compress', function () { + assert.strictEqual(this.negotiator.encoding(['compress']), undefined) + assert.strictEqual(this.negotiator.encoding(['deflate', 'compress']), undefined) + assert.strictEqual(this.negotiator.encoding(['gzip', 'compress']), 'gzip') + }) + }) + + whenAcceptEncoding('gzip, deflate', function () { + it('should return first client-preferred encoding', function () { + assert.strictEqual(this.negotiator.encoding(['deflate', 'compress']), 'deflate') + }) + }) + + whenAcceptEncoding('gzip;q=0.8, deflate', function () { + it('should return most client-preferred encoding', function () { + assert.strictEqual(this.negotiator.encoding(['gzip']), 'gzip') + assert.strictEqual(this.negotiator.encoding(['deflate']), 'deflate') + assert.strictEqual(this.negotiator.encoding(['deflate', 'gzip']), 'deflate') + }) + }) + + whenAcceptEncoding('gzip;q=0.8, identity;q=0.5, *;q=0.3', function () { + it('should return most client-preferred encoding', function () { + assert.strictEqual(this.negotiator.encoding(['gzip']), 'gzip') + assert.strictEqual(this.negotiator.encoding(['compress', 'identity']), 'identity') + }) + }) +}) + +describe('negotiator.encodings()', function () { + whenAcceptEncoding(undefined, function () { + it('should return identity', function () { + assert.deepEqual(this.negotiator.encodings(), ['identity']) + }) + }) + + whenAcceptEncoding('*', function () { + it('should return *', function () { + assert.deepEqual(this.negotiator.encodings(), ['*']) + }) + }) + + whenAcceptEncoding('*, gzip', function () { + it('should prefer gzip', function () { + assert.deepEqual(this.negotiator.encodings(), ['*', 'gzip']) + }) + }) + + whenAcceptEncoding('*, gzip;q=0', function () { + it('should return *', function () { + assert.deepEqual(this.negotiator.encodings(), ['*']) + }) + }) + + whenAcceptEncoding('*;q=0', function () { + it('should return an empty list', function () { + assert.deepEqual(this.negotiator.encodings(), []) + }) + }) + + whenAcceptEncoding('*;q=0, identity;q=1', function () { + it('should return identity', function () { + assert.deepEqual(this.negotiator.encodings(), ['identity']) + }) + }) + + whenAcceptEncoding('identity', function () { + it('should return identity', function () { + assert.deepEqual(this.negotiator.encodings(), ['identity']) + }) + }) + + whenAcceptEncoding('identity;q=0', function () { + it('should return an empty list', function () { + assert.deepEqual(this.negotiator.encodings(), []) + }) + }) + + whenAcceptEncoding('gzip', function () { + it('should return gzip, identity', function () { + assert.deepEqual(this.negotiator.encodings(), ['gzip', 'identity']) + }) + }) + + whenAcceptEncoding('gzip, compress;q=0', function () { + it('should not return compress', function () { + assert.deepEqual(this.negotiator.encodings(), ['gzip', 'identity']) + }) + }) + + whenAcceptEncoding('gzip, deflate', function () { + it('should return client-preferred encodings', function () { + assert.deepEqual(this.negotiator.encodings(), ['gzip', 'deflate', 'identity']) + }) + }) + + whenAcceptEncoding('gzip;q=0.8, deflate', function () { + it('should return client-preferred encodings', function () { + assert.deepEqual(this.negotiator.encodings(), ['deflate', 'gzip', 'identity']) + }) + }) + + whenAcceptEncoding('gzip;q=0.8, identity;q=0.5, *;q=0.3', function () { + it('should return client-preferred encodings', function () { + assert.deepEqual(this.negotiator.encodings(), ['gzip', 'identity', '*']) + }) + }) +}) + +describe('negotiator.encodings(array)', function () { + whenAcceptEncoding(undefined, function () { + it('should return empty list for empty list', function () { + assert.deepEqual(this.negotiator.encodings([]), []) + }) + + it('should only match identity', function () { + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + assert.deepEqual(this.negotiator.encodings(['gzip']), []) + }) + }) + + whenAcceptEncoding('*', function () { + it('should return empty list for empty list', function () { + assert.deepEqual(this.negotiator.encodings([]), []) + }) + + it('should return original list', function () { + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + assert.deepEqual(this.negotiator.encodings(['gzip']), ['gzip']) + assert.deepEqual(this.negotiator.encodings(['gzip', 'identity']), ['gzip', 'identity']) + }) + }) + + whenAcceptEncoding('*, gzip', function () { + it('should prefer gzip', function () { + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + assert.deepEqual(this.negotiator.encodings(['gzip']), ['gzip']) + assert.deepEqual(this.negotiator.encodings(['compress', 'gzip']), ['gzip', 'compress']) + }) + }) + + whenAcceptEncoding('*, gzip;q=0', function () { + it('should exclude gzip', function () { + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + assert.deepEqual(this.negotiator.encodings(['gzip']), []) + assert.deepEqual(this.negotiator.encodings(['gzip', 'compress']), ['compress']) + }) + }) + + whenAcceptEncoding('*;q=0', function () { + it('should always return empty list', function () { + assert.deepEqual(this.negotiator.encodings([]), []) + assert.deepEqual(this.negotiator.encodings(['identity']), []) + assert.deepEqual(this.negotiator.encodings(['gzip']), []) + }) + }) + + whenAcceptEncoding('*;q=0, identity;q=1', function () { + it('should still match identity', function () { + assert.deepEqual(this.negotiator.encodings([]), []) + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + assert.deepEqual(this.negotiator.encodings(['gzip']), []) + }) + }) + + whenAcceptEncoding('identity', function () { + it('should return empty list for empty list', function () { + assert.deepEqual(this.negotiator.encodings([]), []) + }) + + it('should only match identity', function () { + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + assert.deepEqual(this.negotiator.encodings(['gzip']), []) + }) + }) + + whenAcceptEncoding('identity;q=0', function () { + it('should always return empty list', function () { + assert.deepEqual(this.negotiator.encodings([]), []) + assert.deepEqual(this.negotiator.encodings(['identity']), []) + assert.deepEqual(this.negotiator.encodings(['gzip']), []) + }) + }) + + whenAcceptEncoding('gzip', function () { + it('should return empty list for empty list', function () { + assert.deepEqual(this.negotiator.encodings([]), []) + }) + + it('should be case insensitive, returning provided casing', function () { + assert.deepEqual(this.negotiator.encodings(['GZIP']), ['GZIP']) + assert.deepEqual(this.negotiator.encodings(['gzip', 'GZIP']), ['gzip', 'GZIP']) + assert.deepEqual(this.negotiator.encodings(['GZIP', 'gzip']), ['GZIP', 'gzip']) + }) + + it('should return client-preferred encodings', function () { + assert.deepEqual(this.negotiator.encodings(['gzip']), ['gzip']) + assert.deepEqual(this.negotiator.encodings(['gzip', 'identity']), ['gzip', 'identity']) + assert.deepEqual(this.negotiator.encodings(['identity', 'gzip']), ['gzip', 'identity']) + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + }) + }) + + whenAcceptEncoding('gzip, compress;q=0', function () { + it('should not return compress', function () { + assert.deepEqual(this.negotiator.encodings(['gzip', 'compress']), ['gzip']) + }) + }) + + whenAcceptEncoding('gzip, deflate', function () { + it('should return client-preferred encodings', function () { + assert.deepEqual(this.negotiator.encodings(['gzip']), ['gzip']) + assert.deepEqual(this.negotiator.encodings(['gzip', 'identity']), ['gzip', 'identity']) + assert.deepEqual(this.negotiator.encodings(['deflate', 'gzip']), ['gzip', 'deflate']) + assert.deepEqual(this.negotiator.encodings(['identity']), ['identity']) + }) + }) + + whenAcceptEncoding('gzip;q=0.8, deflate', function () { + it('should return client-preferred encodings', function () { + assert.deepEqual(this.negotiator.encodings(['gzip']), ['gzip']) + assert.deepEqual(this.negotiator.encodings(['deflate']), ['deflate']) + assert.deepEqual(this.negotiator.encodings(['deflate', 'gzip']), ['deflate', 'gzip']) + }) + }) + + whenAcceptEncoding('gzip;q=0.8, identity;q=0.5, *;q=0.3', function () { + it('should return client-preferred encodings', function () { + assert.deepEqual(this.negotiator.encodings(['gzip']), ['gzip']) + assert.deepEqual(this.negotiator.encodings(['identity', 'gzip', 'compress']), ['gzip', 'identity', 'compress']) + }) + }) +}) + +function createRequest(headers) { + var request = { + headers: {} + } + + if (headers) { + Object.keys(headers).forEach(function (key) { + request.headers[key.toLowerCase()] = headers[key] + }) + } + + return request +} + +function whenAcceptEncoding(acceptEncoding, func) { + var description = !acceptEncoding + ? 'when no Accept-Encoding' + : 'when Accept-Encoding: ' + acceptEncoding + + describe(description, function () { + before(function () { + this.negotiator = new Negotiator(createRequest({'Accept-Encoding': acceptEncoding})) + }) + + func() + }) +} diff --git a/test/vendor-negotiator/language.js b/test/vendor-negotiator/language.js new file mode 100644 index 00000000..b9cce4eb --- /dev/null +++ b/test/vendor-negotiator/language.js @@ -0,0 +1,425 @@ + +var assert = require('assert') +var Negotiator = require('../../vendor/negotiator') + +describe('negotiator.language()', function () { + whenAcceptLanguage(undefined, function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.language(), '*') + }) + }) + + whenAcceptLanguage('*', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.language(), '*') + }) + }) + + whenAcceptLanguage('*, en', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.language(), '*') + }) + }) + + whenAcceptLanguage('*, en;q=0', function () { + it('should return *', function () { + assert.strictEqual(this.negotiator.language(), '*') + }) + }) + + whenAcceptLanguage('*;q=0.8, en, es', function () { + it('should return en', function () { + assert.deepEqual(this.negotiator.language(), 'en') + }) + }) + + whenAcceptLanguage('en', function () { + it('should en', function () { + assert.strictEqual(this.negotiator.language(), 'en') + }) + }) + + whenAcceptLanguage('en;q=0', function () { + it('should return undefined', function () { + assert.strictEqual(this.negotiator.language(), undefined) + }) + }) + + whenAcceptLanguage('en;q=0.8, es', function () { + it('should return es', function () { + assert.strictEqual(this.negotiator.language(), 'es') + }) + }) + + whenAcceptLanguage('en;q=0.9, es;q=0.8, en;q=0.7', function () { + it('should return en', function () { + assert.strictEqual(this.negotiator.language(), 'en') + }) + }) + + whenAcceptLanguage('en-US, en;q=0.8', function () { + it('should return en-US', function () { + assert.strictEqual(this.negotiator.language(), 'en-US') + }) + }) + + whenAcceptLanguage('en-US, en-GB', function () { + it('should return en-US', function () { + assert.deepEqual(this.negotiator.language(), 'en-US') + }) + }) + + whenAcceptLanguage('en-US;q=0.8, es', function () { + it('should return es', function () { + assert.strictEqual(this.negotiator.language(), 'es') + }) + }) + + whenAcceptLanguage('nl;q=0.5, fr, de, en, it, es, pt, no, se, fi, ro', function () { + it('should return fr', function () { + assert.strictEqual(this.negotiator.language(), 'fr') + }) + }) +}) + +describe('negotiator.language(array)', function () { + whenAcceptLanguage(undefined, function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.language([]), undefined) + }) + + it('should return first language in list', function () { + assert.strictEqual(this.negotiator.language(['en']), 'en') + assert.strictEqual(this.negotiator.language(['es', 'en']), 'es') + }) + }) + + whenAcceptLanguage('*', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.language([]), undefined) + }) + + it('should return first language in list', function () { + assert.strictEqual(this.negotiator.language(['en']), 'en') + assert.strictEqual(this.negotiator.language(['es', 'en']), 'es') + }) + }) + + whenAcceptLanguage('*, en', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.language([]), undefined) + }) + + it('should return most preferred language', function () { + assert.strictEqual(this.negotiator.language(['en']), 'en') + assert.strictEqual(this.negotiator.language(['es', 'en']), 'en') + }) + }) + + whenAcceptLanguage('*, en;q=0', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.language([]), undefined) + }) + + it('should exclude en', function () { + assert.strictEqual(this.negotiator.language(['en']), undefined) + assert.strictEqual(this.negotiator.language(['es', 'en']), 'es') + }) + }) + + whenAcceptLanguage('*;q=0.8, en, es', function () { + it('should prefer en and es over everything', function () { + assert.deepEqual(this.negotiator.language(['en', 'nl']), 'en') + assert.deepEqual(this.negotiator.language(['ro', 'nl']), 'ro') + }) + }) + + whenAcceptLanguage('en', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.language([]), undefined) + }) + + it('should return preferred langauge', function () { + assert.strictEqual(this.negotiator.language(['en']), 'en') + assert.strictEqual(this.negotiator.language(['es', 'en']), 'en') + }) + + it('should accept en-US, preferring en over en-US', function () { + assert.strictEqual(this.negotiator.language(['en-US']), 'en-US') + assert.strictEqual(this.negotiator.language(['en-US', 'en']), 'en') + assert.strictEqual(this.negotiator.language(['en', 'en-US']), 'en') + }) + }) + + whenAcceptLanguage('en;q=0', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.language([]), undefined) + }) + + it('should return preferred langauge', function () { + assert.strictEqual(this.negotiator.language(['es', 'en']), undefined) + }) + }) + + whenAcceptLanguage('en;q=0.8, es', function () { + it('should return undefined for empty list', function () { + assert.strictEqual(this.negotiator.language([]), undefined) + }) + + it('should return preferred langauge', function () { + assert.strictEqual(this.negotiator.language(['en']), 'en') + assert.strictEqual(this.negotiator.language(['en', 'es']), 'es') + }) + }) + + whenAcceptLanguage('en;q=0.9, es;q=0.8, en;q=0.7', function () { + it('should use highest perferred order on duplicate', function () { + assert.strictEqual(this.negotiator.language(['es']), 'es') + assert.strictEqual(this.negotiator.language(['en', 'es']), 'en') + assert.strictEqual(this.negotiator.language(['es', 'en']), 'en') + }) + }) + + whenAcceptLanguage('en-US, en;q=0.8', function () { + it('should use prefer en-US over en', function () { + assert.strictEqual(this.negotiator.language(['en', 'en-US']), 'en-US') + assert.strictEqual(this.negotiator.language(['en-GB', 'en-US']), 'en-US') + assert.strictEqual(this.negotiator.language(['en-GB', 'es']), 'en-GB') + }) + }) + + whenAcceptLanguage('en-US, en-GB', function () { + it('should prefer en-US', function () { + assert.deepEqual(this.negotiator.language(['en-US', 'en-GB']), 'en-US') + assert.deepEqual(this.negotiator.language(['en-GB', 'en-US']), 'en-US') + }) + }) + + whenAcceptLanguage('en-US;q=0.8, es', function () { + it('should prefer es over en-US', function () { + assert.strictEqual(this.negotiator.language(['es', 'en-US']), 'es') + assert.strictEqual(this.negotiator.language(['en-US', 'es']), 'es') + assert.strictEqual(this.negotiator.language(['en-US', 'en']), 'en-US') + }) + }) + + whenAcceptLanguage('nl;q=0.5, fr, de, en, it, es, pt, no, se, fi, ro', function () { + it('should use prefer fr over nl', function () { + assert.strictEqual(this.negotiator.language(['nl', 'fr']), 'fr') + }) + }) +}) + +describe('negotiator.languages()', function () { + whenAcceptLanguage(undefined, function () { + it('should return *', function () { + assert.deepEqual(this.negotiator.languages(), ['*']) + }) + }) + + whenAcceptLanguage('*', function () { + it('should return *', function () { + assert.deepEqual(this.negotiator.languages(), ['*']) + }) + }) + + whenAcceptLanguage('*, en', function () { + it('should return *, en', function () { + assert.deepEqual(this.negotiator.languages(), ['*', 'en']) + }) + }) + + whenAcceptLanguage('*, en;q=0', function () { + it('should return *', function () { + assert.deepEqual(this.negotiator.languages(), ['*']) + }) + }) + + whenAcceptLanguage('*;q=0.8, en, es', function () { + it('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(), ['en', 'es', '*']) + }) + }) + + whenAcceptLanguage('en', function () { + it('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(), ['en']) + }) + }) + + whenAcceptLanguage('en;q=0', function () { + it('should return empty list', function () { + assert.deepEqual(this.negotiator.languages(), []) + }) + }) + + whenAcceptLanguage('en;q=0.8, es', function () { + it('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(), ['es', 'en']) + }) + }) + + whenAcceptLanguage('en;q=0.9, es;q=0.8, en;q=0.7', function () { + it.skip('should use highest perferred order on duplicate', function () { + assert.deepEqual(this.negotiator.languages(), ['en', 'es']) + }) + }) + + whenAcceptLanguage('en-US, en;q=0.8', function () { + it('should return en-US, en', function () { + assert.deepEqual(this.negotiator.languages(), ['en-US', 'en']) + }) + }) + + whenAcceptLanguage('en-US, en-GB', function () { + it('should return en-US, en-GB', function () { + assert.deepEqual(this.negotiator.languages(), ['en-US', 'en-GB']) + }) + }) + + whenAcceptLanguage('en-US;q=0.8, es', function () { + it('should return es, en-US', function () { + assert.deepEqual(this.negotiator.languages(), ['es', 'en-US']) + }) + }) + + whenAcceptLanguage('nl;q=0.5, fr, de, en, it, es, pt, no, se, fi, ro', function () { + it('should use prefer fr over nl', function () { + assert.deepEqual(this.negotiator.languages(), ['fr', 'de', 'en', 'it', 'es', 'pt', 'no', 'se', 'fi', 'ro', 'nl']) + }) + }) +}) + +describe('negotiator.languages(array)', function () { + whenAcceptLanguage(undefined, function () { + it('should return original list', function () { + assert.deepEqual(this.negotiator.languages(['en']), ['en']) + assert.deepEqual(this.negotiator.languages(['es', 'en']), ['es', 'en']) + }) + }) + + whenAcceptLanguage('*', function () { + it('should return original list', function () { + assert.deepEqual(this.negotiator.languages(['en']), ['en']) + assert.deepEqual(this.negotiator.languages(['es', 'en']), ['es', 'en']) + }) + }) + + whenAcceptLanguage('*, en', function () { + it('should return list in client-preferred order', function () { + assert.deepEqual(this.negotiator.languages(['en']), ['en']) + assert.deepEqual(this.negotiator.languages(['es', 'en']), ['en', 'es']) + }) + }) + + whenAcceptLanguage('*, en;q=0', function () { + it('should exclude en', function () { + assert.deepEqual(this.negotiator.languages(['en']), []) + assert.deepEqual(this.negotiator.languages(['es', 'en']), ['es']) + }) + }) + + whenAcceptLanguage('*;q=0.8, en, es', function () { + it('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(['fr', 'de', 'en', 'it', 'es', 'pt', 'no', 'se', 'fi', 'ro', 'nl']), + ['en', 'es', 'fr', 'de', 'it', 'pt', 'no', 'se', 'fi', 'ro', 'nl']) + }) + }) + + whenAcceptLanguage('en', function () { + it('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(['en']), ['en']) + assert.deepEqual(this.negotiator.languages(['en', 'es']), ['en']) + assert.deepEqual(this.negotiator.languages(['es', 'en']), ['en']) + }) + + it('should accept en-US, preferring en over en-US', function () { + assert.deepEqual(this.negotiator.languages(['en-US']), ['en-US']) + assert.deepEqual(this.negotiator.languages(['en-US', 'en']), ['en', 'en-US']) + assert.deepEqual(this.negotiator.languages(['en', 'en-US']), ['en', 'en-US']) + }) + }) + + whenAcceptLanguage('en;q=0', function () { + it('should return nothing', function () { + assert.deepEqual(this.negotiator.languages(['en']), []) + assert.deepEqual(this.negotiator.languages(['en', 'es']), []) + }) + }) + + whenAcceptLanguage('en;q=0.8, es', function () { + it('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(['en']), ['en']) + assert.deepEqual(this.negotiator.languages(['en', 'es']), ['es', 'en']) + assert.deepEqual(this.negotiator.languages(['es', 'en']), ['es', 'en']) + }) + }) + + whenAcceptLanguage('en;q=0.9, es;q=0.8, en;q=0.7', function () { + it.skip('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(['en']), ['en']) + assert.deepEqual(this.negotiator.languages(['en', 'es']), ['es', 'en']) + assert.deepEqual(this.negotiator.languages(['es', 'en']), ['es', 'en']) + }) + }) + + whenAcceptLanguage('en-US, en;q=0.8', function () { + it('should be case insensitive', function () { + assert.deepEqual(this.negotiator.languages(['en-us', 'EN']), ['en-us', 'EN']) + }) + + it('should prefer en-US over en', function () { + assert.deepEqual(this.negotiator.languages(['en-US', 'en']), ['en-US', 'en']) + assert.deepEqual(this.negotiator.languages(['en-GB', 'en-US', 'en']), ['en-US', 'en', 'en-GB']) + }) + }) + + whenAcceptLanguage('en-US, en-GB', function () { + it('should prefer en-US over en-GB', function () { + assert.deepEqual(this.negotiator.languages(['en-US', 'en-GB']), ['en-US', 'en-GB']) + assert.deepEqual(this.negotiator.languages(['en-GB', 'en-US']), ['en-US', 'en-GB']) + }) + }) + + whenAcceptLanguage('en-US;q=0.8, es', function () { + it('should prefer es over en-US', function () { + assert.deepEqual(this.negotiator.languages(['en', 'es']), ['es', 'en']) + assert.deepEqual(this.negotiator.languages(['en', 'es', 'en-US']), ['es', 'en-US', 'en']) + }) + }) + + whenAcceptLanguage('nl;q=0.5, fr, de, en, it, es, pt, no, se, fi, ro', function () { + it('should return preferred languages', function () { + assert.deepEqual(this.negotiator.languages(['fr', 'de', 'en', 'it', 'es', 'pt', 'no', 'se', 'fi', 'ro', 'nl']), + ['fr', 'de', 'en', 'it', 'es', 'pt', 'no', 'se', 'fi', 'ro', 'nl']) + }) + }) +}) + +function createRequest(headers) { + var request = { + headers: {} + } + + if (headers) { + Object.keys(headers).forEach(function (key) { + request.headers[key.toLowerCase()] = headers[key] + }) + } + + return request +} + +function whenAcceptLanguage(acceptLanguage, func) { + var description = !acceptLanguage + ? 'when no Accept-Language' + : 'when Accept-Language: ' + acceptLanguage + + describe(description, function () { + before(function () { + this.negotiator = new Negotiator(createRequest({'Accept-Language': acceptLanguage})) + }) + + func() + }) +} diff --git a/test/vendor-negotiator/mediaType.js b/test/vendor-negotiator/mediaType.js new file mode 100644 index 00000000..1c5c4f40 --- /dev/null +++ b/test/vendor-negotiator/mediaType.js @@ -0,0 +1,592 @@ + +var assert = require('assert') +var Negotiator = require('../../vendor/negotiator') + +describe('negotiator.mediaType()', function () { + whenAccept(undefined, function () { + it('should return */*', function () { + assert.strictEqual(this.negotiator.mediaType(), '*/*') + }) + }) + + whenAccept('*/*', function () { + it('should return */*', function () { + assert.strictEqual(this.negotiator.mediaType(), '*/*') + }) + }) + + whenAccept('application/json', function () { + it('should return application/json', function () { + assert.deepEqual(this.negotiator.mediaType(), 'application/json') + }) + }) + + whenAccept('application/json;q=0', function () { + it('should return undefined', function () { + assert.strictEqual(this.negotiator.mediaType(), undefined) + }) + }) + + whenAccept('application/json;q=0.2, text/html', function () { + it('should return text/html', function () { + assert.deepEqual(this.negotiator.mediaType(), 'text/html') + }) + }) + + whenAccept('text/*', function () { + it('should return text/*', function () { + assert.strictEqual(this.negotiator.mediaType(), 'text/*') + }) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, */*;q=0.1', function () { + it('should return text/plain', function () { + assert.strictEqual(this.negotiator.mediaType(), 'text/plain') + }) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, text/xml, text/yaml, text/javascript, text/csv, text/css, text/rtf, text/markdown, application/octet-stream;q=0.2, */*;q=0.1', function () { + it('should return text/plain', function () { + assert.strictEqual(this.negotiator.mediaType(), 'text/plain') + }) + }) +}) + +describe('negotiator.mediaType(undefined, {detailed: true})', function () { + whenAccept('text/*', function () { + it('should return a detailed spec object with text/*', function () { + assert.deepEqual( + this.negotiator.mediaType(undefined, {detailed: true}), + {"type": "text/*", parameters: {}, "q": 1} + ) + }) + }) + + whenAccept('text/plain;charset=utf-8;q=0.8, application/json;q=0.5, text/html;q=0.7, */*;q=0.1', function () { + it('should return a detailed object for text/plain', function () { + assert.deepEqual( + this.negotiator.mediaType(undefined, {detailed: true}), + {"type": "text/plain", parameters: {"charset": "utf-8"}, "q": .8} + ) + }) + }) +}) + +describe('negotiator.mediaType(array)', function () { + whenAccept(undefined, function () { + it('should return first item in list', function () { + assert.strictEqual(this.negotiator.mediaType(['text/html']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['text/html', 'application/json']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['application/json', 'text/html']), 'application/json') + }) + }) + + whenAccept('*/*', function () { + it('should return first item in list', function () { + assert.strictEqual(this.negotiator.mediaType(['text/html']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['text/html', 'application/json']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['application/json', 'text/html']), 'application/json') + }) + }) + + whenAccept('application/json', function () { + it('should be case insensitive', function () { + assert.strictEqual(this.negotiator.mediaType(['application/JSON']), 'application/JSON') + }) + + it('should only return application/json', function () { + assert.strictEqual(this.negotiator.mediaType(['text/html']), undefined) + assert.strictEqual(this.negotiator.mediaType(['text/html', 'application/json']), 'application/json') + }) + }) + + whenAccept('application/json;q=0', function () { + it('should return undefined', function () { + assert.strictEqual(this.negotiator.mediaType(), undefined) + }) + }) + + whenAccept('application/json;q=0.2, text/html', function () { + it('should prefer text/html over application/json', function () { + assert.strictEqual(this.negotiator.mediaType(['application/json']), 'application/json') + assert.strictEqual(this.negotiator.mediaType(['application/json', 'text/html']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['text/html', 'application/json']), 'text/html') + }) + }) + + whenAccept('text/*', function () { + it('should prefer text media types', function () { + assert.strictEqual(this.negotiator.mediaType(['application/json']), undefined) + assert.strictEqual(this.negotiator.mediaType(['application/json', 'text/html']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['text/html', 'application/json']), 'text/html') + }) + }) + + whenAccept('text/*, text/plain;q=0', function () { + it('should prefer text media types', function () { + assert.strictEqual(this.negotiator.mediaType(['application/json']), undefined) + assert.strictEqual(this.negotiator.mediaType(['application/json', 'text/html']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['text/html', 'application/json']), 'text/html') + }) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, */*;q=0.1', function () { + it('should return in preferred order', function () { + assert.strictEqual(this.negotiator.mediaType(['application/json', 'text/plain', 'text/html']), 'text/plain') + assert.strictEqual(this.negotiator.mediaType(['image/jpeg', 'text/html']), 'text/html') + assert.strictEqual(this.negotiator.mediaType(['image/jpeg', 'image/gif']), 'image/jpeg') + }) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, text/xml, text/yaml, text/javascript, text/csv, text/css, text/rtf, text/markdown, application/octet-stream;q=0.2, */*;q=0.1', function () { + it('should return the client-preferred order', function () { + assert.strictEqual(this.negotiator.mediaType(['text/plain', 'text/html', 'text/xml', 'text/yaml', 'text/javascript', 'text/csv', 'text/css', 'text/rtf', 'text/markdown', 'application/json', 'application/octet-stream']), + 'text/plain') + }) + }) +}) + +describe('negotiator.mediaType(array, {detailed: true})', function() { + whenAccept('text/*', function () { + it('should return a detailed spec object with text/html', function () { + assert.deepEqual( + this.negotiator.mediaType(["text/html"], {detailed: true}), + {"type": "text/html", parameters: {}, "q": 1} + ) + }) + }) + + whenAccept('text/html;LEVEL=1, application/json;q=0.5', function () { + it('should return parameters, but require an exact match', function () { + assert.deepEqual( + this.negotiator.mediaType(["text/html"], {detailed: true}), + undefined + ) + + assert.deepEqual( + this.negotiator.mediaType(["text/html; level=1"], {detailed: true}), + {"type": "text/html", "parameters": {"level": "1"}, "q": 1} + ) + }) + }) +}) + +describe('negotiator.mediaTypes()', function () { + whenAccept(undefined, function () { + it('should return */*', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['*/*']) + }) + }) + + whenAccept('*/*', function () { + it('should return */*', mediaTypesPreferred( + ['*/*'] + )) + }) + + whenAccept('application/json', function () { + it('should return application/json', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['application/json']) + }) + }) + + whenAccept('application/json;q=0', function () { + it('should return empty list', function () { + assert.deepEqual(this.negotiator.mediaTypes(), []) + }) + }) + + whenAccept('application/json;q=0.2, text/html', function () { + it('should return text/html, application/json', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['text/html', 'application/json']) + }) + }) + + whenAccept('text/*', function () { + it('should return text/*', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['text/*']) + }) + }) + + whenAccept('text/*, text/plain;q=0', function () { + it('should return text/*', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['text/*']) + }) + }) + + whenAccept('text/html;LEVEL=1', function () { + it('should return text/html;LEVEL=1', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['text/html']) + }) + }) + + whenAccept('text/html;foo="bar,text/css;";fizz="buzz,5", text/plain', function () { + it('should return text/html, text/plain', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['text/html', 'text/plain']) + }) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, */*;q=0.1', function () { + it('should return text/plain, text/html, application/json, */*', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['text/plain', 'text/html', 'application/json', '*/*']) + }) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, text/xml, text/yaml, text/javascript, text/csv, text/css, text/rtf, text/markdown, application/octet-stream;q=0.2, */*;q=0.1', function () { + it('should return the client-preferred order', function () { + assert.deepEqual(this.negotiator.mediaTypes(), ['text/plain', 'text/html', 'text/xml', 'text/yaml', 'text/javascript', 'text/csv', 'text/css', 'text/rtf', 'text/markdown', 'application/json', 'application/octet-stream', '*/*']) + }) + }) +}) + +describe('negotiator.mediaTypes(undefined, {detailed: true})', function() { + whenAccept('text/*', function () { + it('should return a detailed spec object with text/*', function () { + assert.deepEqual( + this.negotiator.mediaTypes(undefined, {detailed: true}), + [{"type": "text/*", parameters: {}, "q": 1}] + ) + }) + }) + + whenAccept('text/html;LEVEL=1, application/json;q=0.5', function () { + it('should return more-detailed spec objects', function () { + assert.deepEqual( + this.negotiator.mediaTypes(undefined, {detailed: true}), + [ + {"type": "text/html", "parameters": {"level": "1"}, "q": 1}, + {"type": "application/json", "parameters": {}, "q": 0.5} + ] + ) + }) + }) +}) + +describe('negotiator.mediaTypes(array)', function () { + whenAccept(undefined, function () { + it('should return return original list', mediaTypesNegotiated( + ['application/json', 'text/plain'], + ['application/json', 'text/plain'] + )) + }) + + whenAccept('*/*', function () { + it('should return return original list', mediaTypesNegotiated( + ['application/json', 'text/plain'], + ['application/json', 'text/plain'] + )) + }) + + whenAccept('*/*;q=0.8, text/*, image/*', function () { + it('should return return stable-sorted list', mediaTypesNegotiated( + ['application/json', 'text/html', 'text/plain', 'text/xml', 'application/xml', 'image/gif', 'image/jpeg', 'image/png', 'audio/mp3', 'application/javascript', 'text/javascript'], + ['text/html', 'text/plain', 'text/xml', 'text/javascript', 'image/gif', 'image/jpeg', 'image/png', 'application/json', 'application/xml', 'audio/mp3', 'application/javascript'] + )) + }) + + whenAccept('application/json', function () { + it('should accept application/json', mediaTypesNegotiated( + ['application/json'], + ['application/json'] + )) + + it('should be case insensitive', mediaTypesNegotiated( + ['application/JSON'], + ['application/JSON'] + )) + + it('should only return application/json', mediaTypesNegotiated( + ['text/html', 'application/json'], + ['application/json'] + )) + + it('should ignore invalid types', mediaTypesNegotiated( + ['boom', 'application/json'], + ['application/json'] + )) + }) + + whenAccept('application/json;q=0', function () { + it('should not accept application/json', mediaTypesNegotiated( + ['application/json'], + [] + )) + + it('should not accept other media types', mediaTypesNegotiated( + ['application/json', 'text/html', 'image/jpeg'], + [] + )) + }) + + whenAccept('application/json;q=0.2, text/html', function () { + it('should prefer text/html over application/json', mediaTypesNegotiated( + ['application/json', 'text/html'], + ['text/html', 'application/json'] + )) + }) + + whenAccept('application/json;q=0.9, text/html;q=0.8, application/json;q=0.7', function () { + it('should prefer application/json over text/html', mediaTypesNegotiated( + ['text/html', 'application/json'], + ['application/json', 'text/html'] + )) + }) + + whenAccept('application/json, */*;q=0.1', function () { + it('should prefer application/json over text/html', mediaTypesNegotiated( + ['text/html', 'application/json'], + ['application/json', 'text/html'] + )) + }) + + whenAccept('application/xhtml+xml;profile="http://www.wapforum.org/xhtml"', function () { + it('should accept application/xhtml+xml;profile="http://www.wapforum.org/xhtml"', mediaTypesNegotiated( + ['application/xhtml+xml;profile="http://www.wapforum.org/xhtml"'], + ['application/xhtml+xml;profile="http://www.wapforum.org/xhtml"'] + )) + }) + + whenAccept('text/*', function () { + it('should prefer text media types', mediaTypesNegotiated( + ['text/html', 'application/json', 'text/plain'], + ['text/html', 'text/plain'] + )) + }) + + whenAccept('text/*, text/html;level', function () { + it('should accept text/html', mediaTypesNegotiated( + ['text/html'], + ['text/html'] + )) + }) + + whenAccept('text/*, text/plain;q=0', function () { + it('should prefer text media types except text/plain', mediaTypesNegotiated( + ['text/html', 'text/plain'], + ['text/html'] + )) + }) + + whenAccept('text/*, text/plain;q=0.5', function () { + it('should prefer text/plain below other text types', mediaTypesNegotiated( + ['text/html', 'text/plain', 'text/xml'], + ['text/html', 'text/xml', 'text/plain'] + )) + }) + + whenAccept('text/html;level=1', function () { + it('should accept text/html;level=1', mediaTypesNegotiated( + ['text/html;level=1'], + ['text/html;level=1'] + )) + + it('should accept text/html;Level=1', mediaTypesNegotiated( + ['text/html;Level=1'], + ['text/html;Level=1'] + )) + + it('should not accept text/html;level=2', mediaTypesNegotiated( + ['text/html;level=2'], + [] + )) + + it('should not accept text/html', mediaTypesNegotiated( + ['text/html'], + [] + )) + + it('should accept text/html;level=1;foo=bar', mediaTypesNegotiated( + ['text/html;level=1;foo=bar'], + ['text/html;level=1;foo=bar'] + )) + }) + + whenAccept('text/html;level=1;foo=bar', function () { + it('should not accept text/html;level=1', mediaTypesNegotiated( + ['text/html;level=1'], + [] + )) + + it('should accept text/html;level=1;foo=bar', mediaTypesNegotiated( + ['text/html;level=1;foo=bar'], + ['text/html;level=1;foo=bar'] + )) + + it('should accept text/html;foo=bar;level=1', mediaTypesNegotiated( + ['text/html;foo=bar;level=1'], + ['text/html;foo=bar;level=1'] + )) + }) + + whenAccept('text/html;level=1;foo="bar"', function () { + it('should accept text/html;level=1;foo=bar', mediaTypesNegotiated( + ['text/html;level=1;foo=bar'], + ['text/html;level=1;foo=bar'] + )) + + it('should accept text/html;level=1;foo="bar"', mediaTypesNegotiated( + ['text/html;level=1;foo="bar"'], + ['text/html;level=1;foo="bar"'] + )) + }) + + whenAccept('text/html;foo=";level=2;"', function () { + it('should not accept text/html;level=2', mediaTypesNegotiated( + ['text/html;level=2'], + [] + )) + + it('should accept text/html;foo=";level=2;"', mediaTypesNegotiated( + ['text/html;foo=";level=2;"'], + ['text/html;foo=";level=2;"'] + )) + }) + + whenAccept('text/html;LEVEL=1', function () { + it('should accept text/html;level=1', mediaTypesNegotiated( + ['text/html;level=1'], + ['text/html;level=1'] + )) + + it('should accept text/html;Level=1', mediaTypesNegotiated( + ['text/html;Level=1'], + ['text/html;Level=1'] + )) + }) + + whenAccept('text/html;LEVEL=1;level=2', function () { + it('should accept text/html;level=2', mediaTypesNegotiated( + ['text/html;level=2'], + ['text/html;level=2'] + )) + + it('should not accept text/html;level=1', mediaTypesNegotiated( + ['text/html;level=1'], + [] + )) + }) + + whenAccept('text/html;level=2', function () { + it('should not accept text/html;level=1', mediaTypesNegotiated( + ['text/html;level=1'], + [] + )) + }) + + whenAccept('text/html;level=2, text/html', function () { + it('should prefer text/html;level=2 over text/html', mediaTypesNegotiated( + ['text/html', 'text/html;level=2'], + ['text/html;level=2', 'text/html'] + )) + }) + + whenAccept('text/html;level=2;q=0.1, text/html', function () { + it('should prefer text/html over text/html;level=2', mediaTypesNegotiated( + ['text/html;level=2', 'text/html'], + ['text/html', 'text/html;level=2'] + )) + }) + + whenAccept('text/html;level=2;q=0.1;level=1', function () { + it('should not accept text/html;level=1', mediaTypesNegotiated( + ['text/html;level=1'], + [] + )) + }) + + whenAccept('text/html;level=2;q=0.1, text/html;level=1, text/html;q=0.5', function () { + it('should prefer text/html;level=1, text/html, text/html;level=2', mediaTypesNegotiated( + ['text/html;level=1', 'text/html;level=2', 'text/html'], + ['text/html;level=1', 'text/html', 'text/html;level=2'] + )) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, */*;q=0.1', function () { + it('should prefer text/plain over text/html', mediaTypesNegotiated( + ['text/html', 'text/plain'], + ['text/plain', 'text/html'] + )) + + it('should prefer application/json after text', mediaTypesNegotiated( + ['application/json', 'text/html', 'text/plain'], + ['text/plain', 'text/html', 'application/json'] + )) + + it('should prefer image/jpeg after text', mediaTypesNegotiated( + ['image/jpeg', 'text/html', 'text/plain'], + ['text/plain', 'text/html', 'image/jpeg'] + )) + }) + + whenAccept('text/plain, application/json;q=0.5, text/html, text/xml, text/yaml, text/javascript, text/csv, text/css, text/rtf, text/markdown, application/octet-stream;q=0.2, */*;q=0.1', function () { + it('should return the client-preferred order', mediaTypesNegotiated( + ['text/plain', 'text/html', 'text/xml', 'text/yaml', 'text/javascript', 'text/csv', 'text/css', 'text/rtf', 'text/markdown', 'application/json', 'application/octet-stream'], + ['text/plain', 'text/html', 'text/xml', 'text/yaml', 'text/javascript', 'text/csv', 'text/css', 'text/rtf', 'text/markdown', 'application/json', 'application/octet-stream'] + )) + }) +}) + +describe('negotiator.mediaTypes(array, {detailed: true})', function() { + whenAccept('text/*', function () { + it('should return a detailed spect object with text/html', function () { + assert.deepEqual( + this.negotiator.mediaTypes(["text/html"], {detailed: true}), + [{"type": "text/html", parameters: {}, "q": 1}] + ) + }) + }) + + whenAccept('text/html;LEVEL=1, application/json;q=0.5', function () { + it('should return parameters, but require an exact match', function () { + assert.deepEqual( + this.negotiator.mediaTypes(["text/html"], {detailed: true}), + [] + ) + + assert.deepEqual( + this.negotiator.mediaTypes(["text/html; level=1"], {detailed: true}), + [{"type": "text/html", "parameters": {"level": "1"}, "q": 1}] + ) + }) + }) +}) + +function createRequest(headers) { + var request = { + headers: {} + } + + if (headers) { + Object.keys(headers).forEach(function (key) { + request.headers[key.toLowerCase()] = headers[key] + }) + } + + return request +} + +function mediaTypesNegotiated(serverTypes, preferredTypes) { + return function () { + assert.deepEqual(this.negotiator.mediaTypes(serverTypes), preferredTypes) + } +} + +function mediaTypesPreferred(preferredTypes) { + return function () { + assert.deepEqual(this.negotiator.mediaTypes(), preferredTypes) + } +} + +function whenAccept(accept, func) { + var description = !accept + ? 'when no Accept' + : 'when Accept: ' + accept + + describe(description, function () { + before(function () { + this.negotiator = Negotiator(createRequest({'Accept': accept})) + }) + + func() + }) +} diff --git a/vendor/negotiator/LICENSE b/vendor/negotiator/LICENSE new file mode 100644 index 00000000..ea6b9e2e --- /dev/null +++ b/vendor/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/negotiator/README.md b/vendor/negotiator/README.md new file mode 100644 index 00000000..23c4229d --- /dev/null +++ b/vendor/negotiator/README.md @@ -0,0 +1,28 @@ +This is an internal, MIT-licensed runtime, not a renamed registry package. +It preserves the detailed media-type extension required by this library and the +original charset, encoding and language APIs. The five JavaScript files come +from the exact custom fork `ethanresnick/negotiator` commit +`e2fe4abc56271b9851132f3e508e7323415c8aea`, with one runtime-line backport: + +- Advisory: https://github.com/advisories/GHSA-7mc5-chhp-fmc3 +- Official fix: https://github.com/jshttp/negotiator/commit/26a05ec15cf7d1fa56000d66ebe9c9a1a62cb75c +- Fixed upstream release: 0.6.1, commit `751c381c32707f238143cd65d78520e16f4ef9e5`. +- Local reviewed fork successor: `90952f6bb84ef3fe7130c996f9ab9e7a984acd31`. + +Only the language-parser regex differs from the pinned custom fork. LICENSE and +copyright notices are retained. This does not claim full upstream 0.6.1 identity +or comprehensive security clearance of the remaining source. + +Source callers import this directory directly. The existing build copies it to +`build/vendor/negotiator`, preserving the compiled callers' relative imports. +Both copies and their declarations are included in the package allowlist. +No install hook, external Git checkout or patch to a consumer's node_modules is +required. The library package version is unchanged pending release policy. + +`npm run test:vendor` retains the original 250 fork tests and adds a bounded +old-source-sensitive language regression. `npm run test:package` packs the real +library and installs it into an isolated consumer offline; set +`JSON_API_PUBLIC_CACHE` to a temporary public-only npm cache previously populated +by installation of the reviewed lock. It verifies compiled runtime and declaration +delivery without a checkout fallback. Local or hosted checks do not by themselves +publish this source or clear the current provider alert. diff --git a/vendor/negotiator/index.d.ts b/vendor/negotiator/index.d.ts new file mode 100644 index 00000000..deff06ef --- /dev/null +++ b/vendor/negotiator/index.d.ts @@ -0,0 +1,31 @@ +declare namespace Negotiator { + interface DetailedMediaType { + type: string; + parameters: { [name: string]: string }; + q: number; + } +} + +declare class Negotiator { + constructor(request: { headers: { [name: string]: string | undefined } }); + charset(available?: string[]): string | undefined; + charsets(available?: string[]): string[]; + encoding(available?: string[]): string | undefined; + encodings(available?: string[]): string[]; + language(available?: string[]): string | undefined; + languages(available?: string[]): string[]; + mediaType(available: string[] | undefined, options: { detailed: true }): Negotiator.DetailedMediaType | undefined; + mediaType(available?: string[], options?: { detailed?: false }): string | undefined; + mediaTypes(available: string[] | undefined, options: { detailed: true }): Negotiator.DetailedMediaType[]; + mediaTypes(available?: string[], options?: { detailed?: false }): string[]; + preferredCharset: Negotiator["charset"]; + preferredCharsets: Negotiator["charsets"]; + preferredEncoding: Negotiator["encoding"]; + preferredEncodings: Negotiator["encodings"]; + preferredLanguage: Negotiator["language"]; + preferredLanguages: Negotiator["languages"]; + preferredMediaType: Negotiator["mediaType"]; + preferredMediaTypes: Negotiator["mediaTypes"]; +} + +export = Negotiator; diff --git a/vendor/negotiator/index.js b/vendor/negotiator/index.js new file mode 100644 index 00000000..90101080 --- /dev/null +++ b/vendor/negotiator/index.js @@ -0,0 +1,124 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Cached loaded submodules. + * @private + */ + +var modules = Object.create(null); + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + var preferredCharsets = loadModule('charset').preferredCharsets; + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + var preferredEncodings = loadModule('encoding').preferredEncodings; + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + var preferredLanguages = loadModule('language').preferredLanguages; + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available, options) { + var set = this.mediaTypes(available, options); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available, options) { + var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes; + return preferredMediaTypes(this.request.headers.accept, available, options); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; + +/** + * Load the given module. + * @private + */ + +function loadModule(moduleName) { + var module = modules[moduleName]; + + if (module !== undefined) { + return module; + } + + // This uses a switch for static require analysis + switch (moduleName) { + case 'charset': + module = require('./lib/charset'); + break; + case 'encoding': + module = require('./lib/encoding'); + break; + case 'language': + module = require('./lib/language'); + break; + case 'mediaType': + module = require('./lib/mediaType'); + break; + default: + throw new Error('Cannot find module \'' + moduleName + '\''); + } + + // Store to prevent invoking require() + modules[moduleName] = module; + + return module; +} diff --git a/vendor/negotiator/lib/charset.js b/vendor/negotiator/lib/charset.js new file mode 100644 index 00000000..4bf0401a --- /dev/null +++ b/vendor/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*(\S+?)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/vendor/negotiator/lib/encoding.js b/vendor/negotiator/lib/encoding.js new file mode 100644 index 00000000..559e8597 --- /dev/null +++ b/vendor/negotiator/lib/encoding.js @@ -0,0 +1,184 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*(\S+?)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided) { + var accepts = parseAcceptEncoding(accept || ''); + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/vendor/negotiator/lib/language.js b/vendor/negotiator/lib/language.js new file mode 100644 index 00000000..1bd2d0e1 --- /dev/null +++ b/vendor/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var langauge = parseLanguage(accepts[i].trim(), i); + + if (langauge) { + accepts[j++] = langauge; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/vendor/negotiator/lib/mediaType.js b/vendor/negotiator/lib/mediaType.js new file mode 100644 index 00000000..007eec9b --- /dev/null +++ b/vendor/negotiator/lib/mediaType.js @@ -0,0 +1,310 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.substr(1, val.length - 2) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided, options) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + var detailed = options && options.detailed; + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(detailed ? getDetailedSpec : getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + var acceptables = priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); + + return detailed ? acceptables.map(parseMediaType).map(getDetailedSpec) : acceptables; +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Get detailed description object for this spec. + * @private + */ + +function getDetailedSpec(spec) { + return { + type: spec.type + '/' + spec.subtype, + parameters: spec.params, + q: spec.q + }; +}; + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.substr(0, index); + val = str.substr(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/vendor/negotiator/provenance.json b/vendor/negotiator/provenance.json new file mode 100644 index 00000000..7c01bb02 --- /dev/null +++ b/vendor/negotiator/provenance.json @@ -0,0 +1,19 @@ +{ + "origin": "ethanresnick/negotiator", + "upstreamBase": "e2fe4abc56271b9851132f3e508e7323415c8aea", + "localBackport": "90952f6bb84ef3fe7130c996f9ab9e7a984acd31", + "officialFix": "26a05ec15cf7d1fa56000d66ebe9c9a1a62cb75c", + "advisory": "GHSA-7mc5-chhp-fmc3", + "license": "MIT", + "runtimeChange": "Exact upstream language regex only; custom media type behavior and other runtime files unchanged", + "files": { + "index.js": "6a68089b85dce3342035d2c527e29320189f7df829f948fdc2a135a551fb6f2e", + "lib/charset.js": "42cdc1df0569a5af23f1b0736d52f138d02c2ea19317015b29296ca7b414cd49", + "lib/encoding.js": "0a0d0ab0d66928875b8595e24da314cddb6caa467203da0992ece379745f4227", + "lib/language.js": "d65b52869b713894013f58104f6aa60d2dc98cb5b0336d3e84fa373381cea9ec", + "lib/mediaType.js": "9592bef505ab15706a1518c05f9b702ec04dbf0bcce31bf752a84f5394ba47f5", + "LICENSE": "553d4d20029a24e315b428a1a54a9e109eaa340f2e958a4f50a92362c2c4070b" + }, + "externalPackageIdentity": false, + "clearance": "Specific parser backport; no comprehensive first-party or vendored-source advisory clearance" +}