repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/get-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/get-test.js | 'use strict'
const isBuffer = require('is-buffer')
const verifyNotFoundError = require('./util').verifyNotFoundError
const isTypedArray = require('./util').isTypedArray
let db
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.args = function (test, testCommon) {
testCommon.promises || test('test argument-less get() throws', function (t) {
t.throws(
db.get.bind(db),
/Error: get\(\) requires a callback argument/,
'no-arg get() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 1-arg, get() throws', function (t) {
t.throws(
db.get.bind(db, 'foo'),
/Error: get\(\) requires a callback argument/,
'callback-less, 1-arg get() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 3-arg, get() throws', function (t) {
t.throws(
db.get.bind(db, 'foo', {}),
/Error: get\(\) requires a callback argument/,
'callback-less, 2-arg get() throws'
)
t.end()
})
}
exports.get = function (test, testCommon) {
test('test simple get()', function (t) {
db.put('foo', 'bar', function (err) {
t.error(err)
db.get('foo', function (err, value) {
t.error(err)
let result
if (!testCommon.encodings) {
t.isNot(typeof value, 'string', 'should not be string by default')
if (isTypedArray(value)) {
result = String.fromCharCode.apply(null, new Uint16Array(value))
} else {
t.ok(isBuffer(value))
try {
result = value.toString()
} catch (e) {
t.error(e, 'should not throw when converting value to a string')
}
}
} else {
result = value
}
t.is(result, 'bar')
db.get('foo', {}, function (err, value) { // same but with {}
t.error(err)
let result
if (!testCommon.encodings) {
t.ok(typeof value !== 'string', 'should not be string by default')
if (isTypedArray(value)) {
result = String.fromCharCode.apply(null, new Uint16Array(value))
} else {
t.ok(isBuffer(value))
try {
result = value.toString()
} catch (e) {
t.error(e, 'should not throw when converting value to a string')
}
}
} else {
result = value
}
t.is(result, 'bar')
db.get('foo', { asBuffer: false }, function (err, value) {
t.error(err)
t.ok(typeof value === 'string', 'should be string if not buffer')
t.is(value, 'bar')
t.end()
})
})
})
})
})
test('test simultaneous get()', function (t) {
db.put('hello', 'world', function (err) {
t.error(err)
let completed = 0
const done = function () {
if (++completed === 20) t.end()
}
for (let i = 0; i < 10; ++i) {
db.get('hello', function (err, value) {
t.error(err)
t.is(value.toString(), 'world')
done()
})
}
for (let i = 0; i < 10; ++i) {
db.get('not found', function (err, value) {
t.ok(err, 'should error')
t.ok(verifyNotFoundError(err), 'should have correct error message')
t.ok(typeof value === 'undefined', 'value is undefined')
done()
})
}
})
})
test('test get() not found error is asynchronous', function (t) {
t.plan(4)
let async = false
db.get('not found', function (err, value) {
t.ok(err, 'should error')
t.ok(verifyNotFoundError(err), 'should have correct error message')
t.ok(typeof value === 'undefined', 'value is undefined')
t.ok(async, 'callback is asynchronous')
})
async = true
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.get(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-snapshot-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-snapshot-test.js | 'use strict'
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
}
exports.snapshot = function (test, testCommon) {
function make (run) {
return function (t) {
const db = testCommon.factory()
db.open(function (err) {
t.ifError(err, 'no open error')
db.put('z', 'from snapshot', function (err) {
t.ifError(err, 'no put error')
// For this test it is important that we don't read eagerly.
// NOTE: highWaterMark is not an abstract option atm, but
// it is supported by leveldown, rocksdb and others.
const it = db.iterator({ highWaterMark: 0 })
run(t, db, it, function end (err) {
t.ifError(err, 'no run error')
it.end(function (err) {
t.ifError(err, 'no iterator end error')
db.close(t.end.bind(t))
})
})
})
})
}
}
test('delete key after snapshotting', make(function (t, db, it, end) {
db.del('z', function (err) {
t.ifError(err, 'no del error')
it.next(function (err, key, value) {
t.ifError(err, 'no next error')
t.ok(key, 'got a key')
t.is(key.toString(), 'z', 'correct key')
t.is(value.toString(), 'from snapshot', 'correct value')
end()
})
})
}))
test('overwrite key after snapshotting', make(function (t, db, it, end) {
db.put('z', 'not from snapshot', function (err) {
t.ifError(err, 'no put error')
it.next(function (err, key, value) {
t.ifError(err, 'no next error')
t.ok(key, 'got a key')
t.is(key.toString(), 'z', 'correct key')
t.is(value.toString(), 'from snapshot', 'correct value')
end()
})
})
}))
test('add key after snapshotting that sorts first', make(function (t, db, it, end) {
db.put('a', 'not from snapshot', function (err) {
t.ifError(err, 'no put error')
it.next(function (err, key, value) {
t.ifError(err, 'no next error')
t.ok(key, 'got a key')
t.is(key.toString(), 'z', 'correct key')
t.is(value.toString(), 'from snapshot', 'correct value')
end()
})
})
}))
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.snapshot(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-test.js | 'use strict'
let db
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.args = function (test, testCommon) {
test('test iterator has db reference', function (t) {
const iterator = db.iterator()
// For levelup & deferred-leveldown compat: may return iterator of an underlying db, that's okay.
t.ok(iterator.db === db || iterator.db === (db.db || db._db || db))
iterator.end(t.end.bind(t))
})
test('test iterator#next returns this in callback mode', function (t) {
const iterator = db.iterator()
const self = iterator.next(function () {})
t.ok(iterator === self)
iterator.end(t.end.bind(t))
})
}
exports.sequence = function (test, testCommon) {
test('test twice iterator#end() callback with error', function (t) {
const iterator = db.iterator()
iterator.end(function (err) {
t.error(err)
let async = false
iterator.end(function (err2) {
t.ok(err2, 'returned error')
t.is(err2.name, 'Error', 'correct error')
t.is(err2.message, 'end() already called on iterator')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
})
test('test iterator#next after iterator#end() callback with error', function (t) {
const iterator = db.iterator()
iterator.end(function (err) {
t.error(err)
let async = false
iterator.next(function (err2) {
t.ok(err2, 'returned error')
t.is(err2.name, 'Error', 'correct error')
t.is(err2.message, 'cannot call next() after end()', 'correct message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
})
test('test twice iterator#next() throws', function (t) {
const iterator = db.iterator()
iterator.next(function (err) {
t.error(err)
iterator.end(function (err) {
t.error(err)
t.end()
})
})
let async = false
iterator.next(function (err) {
t.ok(err, 'returned error')
t.is(err.name, 'Error', 'correct error')
t.is(err.message, 'cannot call next() before previous next() has completed')
t.ok(async, 'callback is asynchronous')
})
async = true
})
}
exports.iterator = function (test, testCommon) {
test('test simple iterator()', function (t) {
const data = [
{ type: 'put', key: 'foobatch1', value: 'bar1' },
{ type: 'put', key: 'foobatch2', value: 'bar2' },
{ type: 'put', key: 'foobatch3', value: 'bar3' }
]
let idx = 0
db.batch(data, function (err) {
t.error(err)
const iterator = db.iterator()
const fn = function (err, key, value) {
t.error(err)
if (key && value) {
if (testCommon.encodings) {
t.is(typeof key, 'string', 'key argument is a string')
t.is(typeof value, 'string', 'value argument is a string')
} else {
t.ok(Buffer.isBuffer(key), 'key argument is a Buffer')
t.ok(Buffer.isBuffer(value), 'value argument is a Buffer')
}
t.is(key.toString(), data[idx].key, 'correct key')
t.is(value.toString(), data[idx].value, 'correct value')
db._nextTick(next)
idx++
} else { // end
t.ok(err == null, 'err argument is nullish')
t.ok(typeof key === 'undefined', 'key argument is undefined')
t.ok(typeof value === 'undefined', 'value argument is undefined')
t.is(idx, data.length, 'correct number of entries')
iterator.end(function () {
t.end()
})
}
}
const next = function () {
iterator.next(fn)
}
next()
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.sequence(test, testCommon)
exports.iterator(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-seek-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-seek-test.js | 'use strict'
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.sequence(test, testCommon)
exports.seek(test, testCommon)
exports.tearDown(test, testCommon)
}
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
}
exports.sequence = function (test, testCommon) {
function make (name, testFn) {
test(name, function (t) {
const db = testCommon.factory()
const done = function (err) {
t.error(err, 'no error from done()')
db.close(function (err) {
t.error(err, 'no error from close()')
t.end()
})
}
db.open(function (err) {
t.error(err, 'no error from open()')
testFn(db, t, done)
})
})
}
make('iterator#seek() throws if next() has not completed', function (db, t, done) {
const ite = db.iterator()
let error
let async = false
ite.next(function (err, key, value) {
t.error(err, 'no error from next()')
t.ok(async, 'next is asynchronous')
ite.end(done)
})
async = true
try {
ite.seek('two')
} catch (err) {
error = err.message
}
t.is(error, 'cannot call seek() before next() has completed', 'got error')
})
make('iterator#seek() throws after end()', function (db, t, done) {
const ite = db.iterator()
// TODO: why call next? Can't we end immediately?
ite.next(function (err, key, value) {
t.error(err, 'no error from next()')
ite.end(function (err) {
t.error(err, 'no error from end()')
let error
try {
ite.seek('two')
} catch (err) {
error = err.message
}
t.is(error, 'cannot call seek() after end()', 'got error')
done()
})
})
})
}
exports.seek = function (test, testCommon) {
function make (name, testFn) {
test(name, function (t) {
const db = testCommon.factory()
const done = function (err) {
t.error(err, 'no error from done()')
db.close(function (err) {
t.error(err, 'no error from close()')
t.end()
})
}
db.open(function (err) {
t.error(err, 'no error from open()')
db.batch([
{ type: 'put', key: 'one', value: '1' },
{ type: 'put', key: 'two', value: '2' },
{ type: 'put', key: 'three', value: '3' }
], function (err) {
t.error(err, 'no error from batch()')
testFn(db, t, done)
})
})
})
}
make('iterator#seek() to string target', function (db, t, done) {
const ite = db.iterator()
ite.seek('two')
ite.next(function (err, key, value) {
t.error(err, 'no error')
t.same(key.toString(), 'two', 'key matches')
t.same(value.toString(), '2', 'value matches')
ite.next(function (err, key, value) {
t.error(err, 'no error')
t.same(key, undefined, 'end of iterator')
t.same(value, undefined, 'end of iterator')
ite.end(done)
})
})
})
if (testCommon.bufferKeys) {
make('iterator#seek() to buffer target', function (db, t, done) {
const ite = db.iterator()
ite.seek(Buffer.from('two'))
ite.next(function (err, key, value) {
t.error(err, 'no error from next()')
t.equal(key.toString(), 'two', 'key matches')
t.equal(value.toString(), '2', 'value matches')
ite.next(function (err, key, value) {
t.error(err, 'no error from next()')
t.equal(key, undefined, 'end of iterator')
t.equal(value, undefined, 'end of iterator')
ite.end(done)
})
})
})
}
make('iterator#seek() on reverse iterator', function (db, t, done) {
const ite = db.iterator({ reverse: true, limit: 1 })
ite.seek('three!')
ite.next(function (err, key, value) {
t.error(err, 'no error')
t.same(key.toString(), 'three', 'key matches')
t.same(value.toString(), '3', 'value matches')
ite.end(done)
})
})
make('iterator#seek() to out of range target', function (db, t, done) {
const ite = db.iterator()
ite.seek('zzz')
ite.next(function (err, key, value) {
t.error(err, 'no error')
t.same(key, undefined, 'end of iterator')
t.same(value, undefined, 'end of iterator')
ite.end(done)
})
})
make('iterator#seek() on reverse iterator to out of range target', function (db, t, done) {
const ite = db.iterator({ reverse: true })
ite.seek('zzz')
ite.next(function (err, key, value) {
t.error(err, 'no error')
t.same(key.toString(), 'two')
t.same(value.toString(), '2')
ite.end(done)
})
})
test('iterator#seek() respects range', function (t) {
const db = testCommon.factory()
db.open(function (err) {
t.error(err, 'no error from open()')
// Can't use Array.fill() because IE
const ops = []
for (let i = 0; i < 10; i++) {
ops.push({ type: 'put', key: String(i), value: String(i) })
}
db.batch(ops, function (err) {
t.error(err, 'no error from batch()')
let pending = 0
expect({ gt: '5' }, '4', undefined)
expect({ gt: '5' }, '5', undefined)
expect({ gt: '5' }, '6', '6')
expect({ gte: '5' }, '4', undefined)
expect({ gte: '5' }, '5', '5')
expect({ gte: '5' }, '6', '6')
expect({ lt: '5' }, '4', '4')
expect({ lt: '5' }, '5', undefined)
expect({ lt: '5' }, '6', undefined)
expect({ lte: '5' }, '4', '4')
expect({ lte: '5' }, '5', '5')
expect({ lte: '5' }, '6', undefined)
expect({ lt: '5', reverse: true }, '4', '4')
expect({ lt: '5', reverse: true }, '5', undefined)
expect({ lt: '5', reverse: true }, '6', undefined)
expect({ lte: '5', reverse: true }, '4', '4')
expect({ lte: '5', reverse: true }, '5', '5')
expect({ lte: '5', reverse: true }, '6', undefined)
expect({ gt: '5', reverse: true }, '4', undefined)
expect({ gt: '5', reverse: true }, '5', undefined)
expect({ gt: '5', reverse: true }, '6', '6')
expect({ gte: '5', reverse: true }, '4', undefined)
expect({ gte: '5', reverse: true }, '5', '5')
expect({ gte: '5', reverse: true }, '6', '6')
expect({ gt: '7', lt: '8' }, '7', undefined)
expect({ gte: '7', lt: '8' }, '7', '7')
expect({ gte: '7', lt: '8' }, '8', undefined)
expect({ gt: '7', lte: '8' }, '8', '8')
function expect (range, target, expected) {
pending++
const ite = db.iterator(range)
ite.seek(target)
ite.next(function (err, key, value) {
t.error(err, 'no error from next()')
const json = JSON.stringify(range)
const msg = 'seek(' + target + ') on ' + json + ' yields ' + expected
if (expected === undefined) {
t.equal(value, undefined, msg)
} else {
t.equal(value.toString(), expected, msg)
}
ite.end(function (err) {
t.error(err, 'no error from end()')
if (!--pending) done()
})
})
}
function done () {
db.close(function (err) {
t.error(err, 'no error from close()')
t.end()
})
}
})
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/close-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/close-test.js | 'use strict'
let db
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.close = function (test, testCommon) {
test('test close()', function (t) {
testCommon.promises || t.throws(
db.close.bind(db),
/Error: close\(\) requires a callback argument/,
'no-arg close() throws'
)
testCommon.promises || t.throws(
db.close.bind(db, 'foo'),
/Error: close\(\) requires a callback argument/,
'non-callback close() throws'
)
db.close(function (err) {
t.error(err)
t.end()
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.close(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/open-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/open-test.js | 'use strict'
exports.setUp = function (test, testCommon) {
test('setUp', testCommon.setUp)
}
exports.args = function (test, testCommon) {
testCommon.promises || test('test database open no-arg throws', function (t) {
const db = testCommon.factory()
t.throws(
db.open.bind(db),
/Error: open\(\) requires a callback argument/,
'no-arg open() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 1-arg, open() throws', function (t) {
const db = testCommon.factory()
t.throws(
db.open.bind(db, {}),
/Error: open\(\) requires a callback argument/,
'callback-less, 1-arg open() throws'
)
t.end()
})
}
exports.open = function (test, testCommon) {
test('test database open, no options', function (t) {
const db = testCommon.factory()
// default createIfMissing=true, errorIfExists=false
db.open(function (err) {
t.error(err)
db.close(function () {
t.end()
})
})
})
test('test database open, options and callback', function (t) {
const db = testCommon.factory()
// default createIfMissing=true, errorIfExists=false
db.open({}, function (err) {
t.error(err)
db.close(function () {
t.end()
})
})
})
test('test database open, close and open', function (t) {
const db = testCommon.factory()
db.open(function (err) {
t.error(err)
db.close(function (err) {
t.error(err)
db.open(function (err) {
t.error(err)
db.close(function () {
t.end()
})
})
})
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.open(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/open-create-if-missing-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/open-create-if-missing-test.js | 'use strict'
exports.setUp = function (test, testCommon) {
test('setUp', testCommon.setUp)
}
exports.createIfMissing = function (test, testCommon) {
test('test database open createIfMissing:false', function (t) {
const db = testCommon.factory()
let async = false
db.open({ createIfMissing: false }, function (err) {
t.ok(err, 'error')
t.ok(/does not exist/.test(err.message), 'error is about dir not existing')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.createIfMissing(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/index.js | aws/lti-middleware/node_modules/abstract-leveldown/test/index.js | 'use strict'
const common = require('./common')
function suite (options) {
const testCommon = common(options)
const test = testCommon.test
require('./factory-test')(test, testCommon)
require('./manifest-test')(test, testCommon)
require('./leveldown-test')(test, testCommon)
require('./open-test').all(test, testCommon)
require('./close-test').all(test, testCommon)
if (testCommon.createIfMissing) {
require('./open-create-if-missing-test').all(test, testCommon)
}
if (testCommon.errorIfExists) {
require('./open-error-if-exists-test').all(test, testCommon)
}
require('./put-test').all(test, testCommon)
require('./get-test').all(test, testCommon)
require('./del-test').all(test, testCommon)
require('./put-get-del-test').all(test, testCommon)
if (testCommon.getMany) {
require('./get-many-test').all(test, testCommon)
}
require('./batch-test').all(test, testCommon)
require('./chained-batch-test').all(test, testCommon)
require('./iterator-test').all(test, testCommon)
require('./iterator-range-test').all(test, testCommon)
require('./async-iterator-test').all(test, testCommon)
if (testCommon.seek) {
require('./iterator-seek-test').all(test, testCommon)
}
if (testCommon.snapshots) {
require('./iterator-snapshot-test').all(test, testCommon)
} else {
require('./iterator-no-snapshot-test').all(test, testCommon)
}
if (testCommon.clear) {
require('./clear-test').all(test, testCommon)
require('./clear-range-test').all(test, testCommon)
}
}
suite.common = common
module.exports = suite
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/chained-batch-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/chained-batch-test.js | 'use strict'
const collectEntries = require('level-concat-iterator')
let db
function collectBatchOps (batch) {
const _put = batch._put
const _del = batch._del
const _operations = []
if (typeof _put !== 'function' || typeof _del !== 'function') {
return batch._operations
}
batch._put = function (key, value) {
_operations.push({ type: 'put', key, value })
return _put.apply(this, arguments)
}
batch._del = function (key) {
_operations.push({ type: 'del', key })
return _del.apply(this, arguments)
}
return _operations
}
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.args = function (test, testCommon) {
test('test batch has db reference', function (t) {
t.ok(db.batch().db === db)
t.end()
})
test('test batch#put() with missing `value`', function (t) {
t.plan(1)
try {
db.batch().put('foo1')
} catch (err) {
t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message')
}
})
test('test batch#put() with missing `key`', function (t) {
try {
db.batch().put(undefined, 'foo1')
} catch (err) {
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#put() with null `key`', function (t) {
try {
db.batch().put(null, 'foo1')
} catch (err) {
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#put() with missing `key` and `value`', function (t) {
try {
db.batch().put()
} catch (err) {
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#put() with null or undefined `value`', function (t) {
const illegalValues = [null, undefined]
t.plan(illegalValues.length)
illegalValues.forEach(function (value) {
try {
db.batch().put('key', value)
} catch (err) {
t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message')
}
})
})
test('test batch#del() with missing `key`', function (t) {
try {
db.batch().del()
} catch (err) {
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#del() with null or undefined `key`', function (t) {
const illegalKeys = [null, undefined]
t.plan(illegalKeys.length)
illegalKeys.forEach(function (key) {
try {
db.batch().del(key)
} catch (err) {
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
}
})
})
test('test batch#clear() doesn\'t throw', function (t) {
db.batch().clear()
t.end()
})
testCommon.promises || test('test batch#write() with no callback', function (t) {
try {
db.batch().write()
} catch (err) {
t.equal(err.message, 'write() requires a callback argument', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#put() after write()', function (t) {
const batch = db.batch().put('foo', 'bar')
batch.write(function () {})
try {
batch.put('boom', 'bang')
} catch (err) {
t.equal(err.message, 'write() already called on this batch', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#del() after write()', function (t) {
const batch = db.batch().put('foo', 'bar')
batch.write(function () {})
try {
batch.del('foo')
} catch (err) {
t.equal(err.message, 'write() already called on this batch', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#clear() after write()', function (t) {
const batch = db.batch().put('foo', 'bar')
batch.write(function () {})
try {
batch.clear()
} catch (err) {
t.equal(err.message, 'write() already called on this batch', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
test('test batch#write() after write()', function (t) {
const batch = db.batch().put('foo', 'bar')
batch.write(function () {})
try {
batch.write(function () {})
} catch (err) {
t.equal(err.message, 'write() already called on this batch', 'correct error message')
return t.end()
}
t.fail('should have thrown')
t.end()
})
testCommon.serialize && test('test serialize object', function (t) {
const batch = db.batch()
const ops = collectBatchOps(batch)
batch
.put({ foo: 'bar' }, { beep: 'boop' })
.del({ bar: 'baz' })
ops.forEach(function (op) {
t.ok(op.key, '.key is set for .put and .del operations')
if (op.type === 'put') {
t.ok(op.value, '.value is set for .put operation')
}
})
t.end()
})
testCommon.serialize && test('test custom _serialize*', function (t) {
t.plan(4)
const _db = Object.create(db)
const batch = _db.batch()
const ops = collectBatchOps(batch)
_db._serializeKey = function (key) {
t.same(key, { foo: 'bar' })
return 'key1'
}
_db._serializeValue = function (value) {
t.same(value, { beep: 'boop' })
return 'value1'
}
batch.put({ foo: 'bar' }, { beep: 'boop' })
_db._serializeKey = function (key) {
t.same(key, { bar: 'baz' })
return 'key2'
}
batch.del({ bar: 'baz' })
t.deepEqual(ops, [
{ type: 'put', key: 'key1', value: 'value1' },
{ type: 'del', key: 'key2' }
])
})
test('test batch#write() with no operations', function (t) {
let async = false
db.batch().write(function (err) {
t.ifError(err, 'no error from write()')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
}
exports.batch = function (test, testCommon) {
test('test basic batch', function (t) {
db.batch([
{ type: 'put', key: 'one', value: '1' },
{ type: 'put', key: 'two', value: '2' },
{ type: 'put', key: 'three', value: '3' }
], function (err) {
t.error(err)
db.batch()
.put('1', 'one')
.del('2', 'two')
.put('3', 'three')
.clear()
.put('one', 'I')
.put('two', 'II')
.del('three')
.put('foo', 'bar')
.write(function (err) {
t.error(err)
collectEntries(
db.iterator({ keyAsBuffer: false, valueAsBuffer: false }), function (err, data) {
t.error(err)
t.equal(data.length, 3, 'correct number of entries')
const expected = [
{ key: 'foo', value: 'bar' },
{ key: 'one', value: 'I' },
{ key: 'two', value: 'II' }
]
t.deepEqual(data, expected)
t.end()
}
)
})
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.batch(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/common.js | aws/lti-middleware/node_modules/abstract-leveldown/test/common.js | 'use strict'
function testCommon (options) {
const factory = options.factory
const test = options.test
if (typeof factory !== 'function') {
throw new TypeError('factory must be a function')
}
if (typeof test !== 'function') {
throw new TypeError('test must be a function')
}
if (options.legacyRange != null) {
throw new Error('The legacyRange option has been removed')
}
return {
test: test,
factory: factory,
// TODO (next major): remove
setUp: options.setUp || noopTest(),
tearDown: options.tearDown || noopTest(),
// TODO (next major): use db.supports instead
bufferKeys: options.bufferKeys !== false,
createIfMissing: options.createIfMissing !== false,
errorIfExists: options.errorIfExists !== false,
snapshots: options.snapshots !== false,
seek: options.seek !== false,
clear: !!options.clear,
getMany: !!options.getMany,
// Support running test suite on a levelup db. All options below this line
// are undocumented and should not be used by abstract-leveldown db's (yet).
promises: !!options.promises,
status: options.status !== false,
serialize: options.serialize !== false,
// If true, the test suite assumes a default encoding of utf8 (like levelup)
// and that operations return strings rather than buffers by default.
encodings: !!options.encodings,
deferredOpen: !!options.deferredOpen,
streams: !!options.streams
}
}
function noopTest () {
return function (t) {
t.end()
}
}
module.exports = testCommon
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/put-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/put-test.js | 'use strict'
const isTypedArray = require('./util').isTypedArray
let db
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.args = function (test, testCommon) {
testCommon.promises || test('test argument-less put() throws', function (t) {
t.throws(
db.put.bind(db),
/Error: put\(\) requires a callback argument/,
'no-arg put() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 1-arg, put() throws', function (t) {
t.throws(
db.put.bind(db, 'foo'),
/Error: put\(\) requires a callback argument/,
'callback-less, 1-arg put() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 2-arg, put() throws', function (t) {
t.throws(
db.put.bind(db, 'foo', 'bar'),
/Error: put\(\) requires a callback argument/,
'callback-less, 2-arg put() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 3-arg, put() throws', function (t) {
t.throws(
db.put.bind(db, 'foo', 'bar', {}),
/Error: put\(\) requires a callback argument/,
'callback-less, 3-arg put() throws'
)
t.end()
})
}
exports.put = function (test, testCommon) {
test('test simple put()', function (t) {
db.put('foo', 'bar', function (err) {
t.error(err)
db.get('foo', function (err, value) {
t.error(err)
let result = value.toString()
if (isTypedArray(value)) {
result = String.fromCharCode.apply(null, new Uint16Array(value))
}
t.equal(result, 'bar')
t.end()
})
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.put(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/manifest-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/manifest-test.js | 'use strict'
const suite = require('level-supports/test')
module.exports = function (test, testCommon) {
test('setUp common', testCommon.setUp)
suite(test, testCommon)
testCommon.status && test('manifest has status', function (t) {
const db = testCommon.factory()
t.is(db.supports.status, true)
// The semantics of not opening or closing a new db are unclear
// atm, so let's open it before closing, like every other test.
db.open(function (err) {
t.ifError(err, 'no open error')
db.close(t.end.bind(t))
})
})
test('tearDown', testCommon.tearDown)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/clear-range-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/clear-range-test.js | 'use strict'
const concat = require('level-concat-iterator')
const data = (function () {
const d = []
let i = 0
let k
for (; i < 100; i++) {
k = (i < 10 ? '0' : '') + i
d.push({
key: k,
value: String(Math.random())
})
}
return d
}())
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
}
exports.range = function (test, testCommon) {
function rangeTest (name, opts, expected) {
test('db#clear() with ' + name, function (t) {
prepare(t, function (db) {
db.clear(opts, function (err) {
t.ifError(err, 'no clear error')
verify(t, db, expected)
})
})
})
}
function prepare (t, callback) {
const db = testCommon.factory()
db.open(function (err) {
t.ifError(err, 'no open error')
db.batch(data.map(function (d) {
return {
type: 'put',
key: d.key,
value: d.value
}
}), function (err) {
t.ifError(err, 'no batch error')
callback(db)
})
})
}
function verify (t, db, expected) {
const it = db.iterator({ keyAsBuffer: false, valueAsBuffer: false })
concat(it, function (err, result) {
t.ifError(err, 'no concat error')
t.is(result.length, expected.length, 'correct number of entries')
t.same(result, expected)
db.close(t.end.bind(t))
})
}
function exclude (data, start, end, expectedLength) {
data = data.slice()
const removed = data.splice(start, end - start + 1) // Inclusive
if (expectedLength != null) checkLength(removed, expectedLength)
return data
}
// For sanity checks on test arguments
function checkLength (arr, length) {
if (arr.length !== length) {
throw new RangeError('Expected ' + length + ' elements, got ' + arr.length)
}
return arr
}
rangeTest('full range', {}, [])
// Reversing has no effect without limit
rangeTest('reverse=true', {
reverse: true
}, [])
rangeTest('gte=00', {
gte: '00'
}, [])
rangeTest('gte=50', {
gte: '50'
}, data.slice(0, 50))
rangeTest('lte=50 and reverse=true', {
lte: '50',
reverse: true
}, data.slice(51))
rangeTest('gte=49.5 (midway)', {
gte: '49.5'
}, data.slice(0, 50))
rangeTest('gte=49999 (midway)', {
gte: '49999'
}, data.slice(0, 50))
rangeTest('lte=49.5 (midway) and reverse=true', {
lte: '49.5',
reverse: true
}, data.slice(50))
rangeTest('lt=49.5 (midway) and reverse=true', {
lt: '49.5',
reverse: true
}, data.slice(50))
rangeTest('lt=50 and reverse=true', {
lt: '50',
reverse: true
}, data.slice(50))
rangeTest('lte=50', {
lte: '50'
}, data.slice(51))
rangeTest('lte=50.5 (midway)', {
lte: '50.5'
}, data.slice(51))
rangeTest('lte=50555 (midway)', {
lte: '50555'
}, data.slice(51))
rangeTest('lt=50555 (midway)', {
lt: '50555'
}, data.slice(51))
rangeTest('gte=50.5 (midway) and reverse=true', {
gte: '50.5',
reverse: true
}, data.slice(0, 51))
rangeTest('gt=50.5 (midway) and reverse=true', {
gt: '50.5',
reverse: true
}, data.slice(0, 51))
rangeTest('gt=50 and reverse=true', {
gt: '50',
reverse: true
}, data.slice(0, 51))
// First key is actually '00' so it should avoid it
rangeTest('lte=0', {
lte: '0'
}, data)
// First key is actually '00' so it should avoid it
rangeTest('lt=0', {
lt: '0'
}, data)
rangeTest('gte=30 and lte=70', {
gte: '30',
lte: '70'
}, exclude(data, 30, 70))
rangeTest('gt=29 and lt=71', {
gt: '29',
lt: '71'
}, exclude(data, 30, 70))
rangeTest('gte=30 and lte=70 and reverse=true', {
lte: '70',
gte: '30',
reverse: true
}, exclude(data, 30, 70))
rangeTest('gt=29 and lt=71 and reverse=true', {
lt: '71',
gt: '29',
reverse: true
}, exclude(data, 30, 70))
rangeTest('limit=20', {
limit: 20
}, data.slice(20))
rangeTest('limit=20 and gte=20', {
limit: 20,
gte: '20'
}, exclude(data, 20, 39, 20))
rangeTest('limit=20 and reverse=true', {
limit: 20,
reverse: true
}, data.slice(0, -20))
rangeTest('limit=20 and lte=79 and reverse=true', {
limit: 20,
lte: '79',
reverse: true
}, exclude(data, 60, 79, 20))
rangeTest('limit=-1 should clear whole database', {
limit: -1
}, [])
rangeTest('limit=0 should not clear anything', {
limit: 0
}, data)
rangeTest('lte after limit', {
limit: 20,
lte: '50'
}, data.slice(20))
rangeTest('lte before limit', {
limit: 50,
lte: '19'
}, data.slice(20))
rangeTest('gte after database end', {
gte: '9a'
}, data)
rangeTest('gt after database end', {
gt: '9a'
}, data)
rangeTest('lte after database end and reverse=true', {
lte: '9a',
reverse: true
}, [])
rangeTest('lte and gte after database and reverse=true', {
lte: '9b',
gte: '9a',
reverse: true
}, data)
rangeTest('lt and gt after database and reverse=true', {
lt: '9b',
gt: '9a',
reverse: true
}, data)
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.range(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-no-snapshot-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-no-snapshot-test.js | 'use strict'
const collectEntries = require('level-concat-iterator')
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
}
exports.noSnapshot = function (test, testCommon) {
function make (run) {
return function (t) {
const db = testCommon.factory()
const operations = [
{ type: 'put', key: 'a', value: 'a' },
{ type: 'put', key: 'b', value: 'b' },
{ type: 'put', key: 'c', value: 'c' }
]
db.open(function (err) {
t.ifError(err, 'no open error')
db.batch(operations, function (err) {
t.ifError(err, 'no batch error')
// For this test it is important that we don't read eagerly.
// NOTE: highWaterMark is not an abstract option atm, but
// it is supported by leveldown, rocksdb and others.
const it = db.iterator({ highWaterMark: 0 })
run(db, function (err) {
t.ifError(err, 'no run error')
verify(t, it, db)
})
})
})
}
}
function verify (t, it, db) {
collectEntries(it, function (err, entries) {
t.ifError(err, 'no iterator error')
const kv = entries.map(function (entry) {
return entry.key.toString() + entry.value.toString()
})
if (kv.length === 3) {
t.same(kv, ['aa', 'bb', 'cc'], 'maybe supports snapshots')
} else {
t.same(kv, ['aa', 'cc'], 'ignores keys that have been deleted in the mean time')
}
db.close(t.end.bind(t))
})
}
test('delete key after creating iterator', make(function (db, done) {
db.del('b', done)
}))
test('batch delete key after creating iterator', make(function (db, done) {
db.batch([{ type: 'del', key: 'b' }], done)
}))
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.noSnapshot(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/clear-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/clear-test.js | 'use strict'
const concat = require('level-concat-iterator')
let db
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.args = function (test, testCommon) {
testCommon.promises || test('test argument-less clear() throws', function (t) {
t.throws(
db.clear.bind(db),
/Error: clear\(\) requires a callback argument/,
'no-arg clear() throws'
)
t.end()
})
}
exports.clear = function (test, testCommon) {
makeTest('string', ['a', 'b'])
if (testCommon.bufferKeys) {
makeTest('buffer', [Buffer.from('a'), Buffer.from('b')])
makeTest('mixed', [Buffer.from('a'), 'b'])
// These keys would be equal when compared as utf8 strings
makeTest('non-utf8 buffer', [Buffer.from('80', 'hex'), Buffer.from('c0', 'hex')])
}
function makeTest (type, keys) {
test('test simple clear() on ' + type + ' keys', function (t) {
t.plan(8)
const db = testCommon.factory()
const ops = keys.map(function (key) {
return { type: 'put', key: key, value: 'foo' }
})
db.open(function (err) {
t.ifError(err, 'no open error')
db.batch(ops, function (err) {
t.ifError(err, 'no batch error')
concat(db.iterator(), function (err, entries) {
t.ifError(err, 'no concat error')
t.is(entries.length, keys.length, 'has entries')
db.clear(function (err) {
t.ifError(err, 'no clear error')
concat(db.iterator(), function (err, entries) {
t.ifError(err, 'no concat error')
t.is(entries.length, 0, 'has no entries')
db.close(function (err) {
t.ifError(err, 'no close error')
})
})
})
})
})
})
})
}
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.clear(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/async-iterator-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/async-iterator-test.js | 'use strict'
const input = [{ key: '1', value: '1' }, { key: '2', value: '2' }]
let db
exports.setup = function (test, testCommon) {
test('setup', function (t) {
t.plan(2)
db = testCommon.factory()
db.open(function (err) {
t.ifError(err, 'no open() error')
db.batch(input.map(entry => ({ ...entry, type: 'put' })), function (err) {
t.ifError(err, 'no batch() error')
})
})
})
}
exports.asyncIterator = function (test, testCommon) {
test('for await...of db.iterator()', async function (t) {
t.plan(2)
const it = db.iterator({ keyAsBuffer: false, valueAsBuffer: false })
const output = []
for await (const [key, value] of it) {
output.push({ key, value })
}
t.ok(it._ended, 'ended')
t.same(output, input)
})
test('for await...of db.iterator() does not permit reuse', async function (t) {
t.plan(3)
const it = db.iterator()
// eslint-disable-next-line no-unused-vars
for await (const [key, value] of it) {
t.pass('nexted')
}
try {
// eslint-disable-next-line no-unused-vars
for await (const [key, value] of it) {
t.fail('should not be called')
}
} catch (err) {
t.is(err.message, 'cannot call next() after end()')
}
})
test('for await...of db.iterator() ends on user error', async function (t) {
t.plan(2)
const it = db.iterator()
try {
// eslint-disable-next-line no-unused-vars, no-unreachable-loop
for await (const kv of it) {
throw new Error('user error')
}
} catch (err) {
t.is(err.message, 'user error')
t.ok(it._ended, 'ended')
}
})
test('for await...of db.iterator() with user error and end() error', async function (t) {
t.plan(3)
const it = db.iterator()
const end = it._end
it._end = function (callback) {
end.call(this, function (err) {
t.ifError(err, 'no real error from end()')
callback(new Error('end error'))
})
}
try {
// eslint-disable-next-line no-unused-vars, no-unreachable-loop
for await (const kv of it) {
throw new Error('user error')
}
} catch (err) {
// TODO: ideally, this would be a combined aka aggregate error
t.is(err.message, 'user error')
t.ok(it._ended, 'ended')
}
})
test('for await...of db.iterator() ends on iterator error', async function (t) {
t.plan(3)
const it = db.iterator()
it._next = function (callback) {
t.pass('nexted')
this._nextTick(callback, new Error('iterator error'))
}
try {
// eslint-disable-next-line no-unused-vars
for await (const kv of it) {
t.fail('should not yield results')
}
} catch (err) {
t.is(err.message, 'iterator error')
t.ok(it._ended, 'ended')
}
})
test('for await...of db.iterator() with iterator error and end() error', async function (t) {
t.plan(4)
const it = db.iterator()
const end = it._end
it._next = function (callback) {
t.pass('nexted')
this._nextTick(callback, new Error('iterator error'))
}
it._end = function (callback) {
end.call(this, function (err) {
t.ifError(err, 'no real error from end()')
callback(new Error('end error'))
})
}
try {
// eslint-disable-next-line no-unused-vars
for await (const kv of it) {
t.fail('should not yield results')
}
} catch (err) {
// TODO: ideally, this would be a combined aka aggregate error
t.is(err.message, 'end error')
t.ok(it._ended, 'ended')
}
})
test('for await...of db.iterator() ends on user break', async function (t) {
t.plan(2)
const it = db.iterator()
// eslint-disable-next-line no-unused-vars, no-unreachable-loop
for await (const kv of it) {
t.pass('got a chance to break')
break
}
t.ok(it._ended, 'ended')
})
test('for await...of db.iterator() with user break and end() error', async function (t) {
t.plan(4)
const it = db.iterator()
const end = it._end
it._end = function (callback) {
end.call(this, function (err) {
t.ifError(err, 'no real error from end()')
callback(new Error('end error'))
})
}
try {
// eslint-disable-next-line no-unused-vars, no-unreachable-loop
for await (const kv of it) {
t.pass('got a chance to break')
break
}
} catch (err) {
t.is(err.message, 'end error')
t.ok(it._ended, 'ended')
}
})
}
exports.teardown = function (test, testCommon) {
test('teardown', function (t) {
t.plan(1)
db.close(function (err) {
t.ifError(err, 'no close() error')
})
})
}
exports.all = function (test, testCommon) {
exports.setup(test, testCommon)
exports.asyncIterator(test, testCommon)
exports.teardown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-range-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/iterator-range-test.js | 'use strict'
const collectEntries = require('level-concat-iterator')
let db
const data = (function () {
const d = []
let i = 0
let k
for (; i < 100; i++) {
k = (i < 10 ? '0' : '') + i
d.push({
key: k,
value: String(Math.random())
})
}
return d
}())
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(function () {
db.batch(data.map(function (d) {
return {
type: 'put',
key: d.key,
value: d.value
}
}), t.end.bind(t))
})
})
}
exports.range = function (test, testCommon) {
function rangeTest (name, opts, expected) {
opts.keyAsBuffer = false
opts.valueAsBuffer = false
test(name, function (t) {
collectEntries(db.iterator(opts), function (err, result) {
t.error(err)
t.is(result.length, expected.length, 'correct number of entries')
t.same(result, expected)
t.end()
})
})
// Test the documented promise that in reverse mode,
// "the returned entries are the same, but in reverse".
if (!opts.reverse && !('limit' in opts)) {
const reverseOpts = Object.assign({}, opts, { reverse: true })
rangeTest(
name + ' (flipped)',
reverseOpts,
expected.slice().reverse()
)
}
}
rangeTest('test full data collection', {}, data)
rangeTest('test iterator with reverse=true', {
reverse: true
}, data.slice().reverse())
rangeTest('test iterator with gte=00', {
gte: '00'
}, data)
rangeTest('test iterator with gte=50', {
gte: '50'
}, data.slice(50))
rangeTest('test iterator with lte=50 and reverse=true', {
lte: '50',
reverse: true
}, data.slice().reverse().slice(49))
rangeTest('test iterator with gte=49.5 (midway)', {
gte: '49.5'
}, data.slice(50))
rangeTest('test iterator with gte=49999 (midway)', {
gte: '49999'
}, data.slice(50))
rangeTest('test iterator with lte=49.5 (midway) and reverse=true', {
lte: '49.5',
reverse: true
}, data.slice().reverse().slice(50))
rangeTest('test iterator with lt=49.5 (midway) and reverse=true', {
lt: '49.5',
reverse: true
}, data.slice().reverse().slice(50))
rangeTest('test iterator with lt=50 and reverse=true', {
lt: '50',
reverse: true
}, data.slice().reverse().slice(50))
rangeTest('test iterator with lte=50', {
lte: '50'
}, data.slice(0, 51))
rangeTest('test iterator with lte=50.5 (midway)', {
lte: '50.5'
}, data.slice(0, 51))
rangeTest('test iterator with lte=50555 (midway)', {
lte: '50555'
}, data.slice(0, 51))
rangeTest('test iterator with lt=50555 (midway)', {
lt: '50555'
}, data.slice(0, 51))
rangeTest('test iterator with gte=50.5 (midway) and reverse=true', {
gte: '50.5',
reverse: true
}, data.slice().reverse().slice(0, 49))
rangeTest('test iterator with gt=50.5 (midway) and reverse=true', {
gt: '50.5',
reverse: true
}, data.slice().reverse().slice(0, 49))
rangeTest('test iterator with gt=50 and reverse=true', {
gt: '50',
reverse: true
}, data.slice().reverse().slice(0, 49))
// first key is actually '00' so it should avoid it
rangeTest('test iterator with lte=0', {
lte: '0'
}, [])
// first key is actually '00' so it should avoid it
rangeTest('test iterator with lt=0', {
lt: '0'
}, [])
rangeTest('test iterator with gte=30 and lte=70', {
gte: '30',
lte: '70'
}, data.slice(30, 71))
rangeTest('test iterator with gt=29 and lt=71', {
gt: '29',
lt: '71'
}, data.slice(30, 71))
rangeTest('test iterator with gte=30 and lte=70 and reverse=true', {
lte: '70',
gte: '30',
reverse: true
}, data.slice().reverse().slice(29, 70))
rangeTest('test iterator with gt=29 and lt=71 and reverse=true', {
lt: '71',
gt: '29',
reverse: true
}, data.slice().reverse().slice(29, 70))
rangeTest('test iterator with limit=20', {
limit: 20
}, data.slice(0, 20))
rangeTest('test iterator with limit=20 and gte=20', {
limit: 20,
gte: '20'
}, data.slice(20, 40))
rangeTest('test iterator with limit=20 and reverse=true', {
limit: 20,
reverse: true
}, data.slice().reverse().slice(0, 20))
rangeTest('test iterator with limit=20 and lte=79 and reverse=true', {
limit: 20,
lte: '79',
reverse: true
}, data.slice().reverse().slice(20, 40))
// the default limit value from levelup is -1
rangeTest('test iterator with limit=-1 should iterate over whole database', {
limit: -1
}, data)
rangeTest('test iterator with limit=0 should not iterate over anything', {
limit: 0
}, [])
rangeTest('test iterator with lte after limit', {
limit: 20,
lte: '50'
}, data.slice(0, 20))
rangeTest('test iterator with lte before limit', {
limit: 50,
lte: '19'
}, data.slice(0, 20))
rangeTest('test iterator with gte after database end', {
gte: '9a'
}, [])
rangeTest('test iterator with gt after database end', {
gt: '9a'
}, [])
rangeTest('test iterator with lte after database end and reverse=true', {
lte: '9a',
reverse: true
}, data.slice().reverse())
rangeTest('test iterator with lt after database end', {
lt: 'a'
}, data.slice())
rangeTest('test iterator with lt at database end', {
lt: data[data.length - 1].key
}, data.slice(0, -1))
rangeTest('test iterator with lte at database end', {
lte: data[data.length - 1].key
}, data.slice())
rangeTest('test iterator with lt before database end', {
lt: data[data.length - 2].key
}, data.slice(0, -2))
rangeTest('test iterator with lte before database end', {
lte: data[data.length - 2].key
}, data.slice(0, -1))
rangeTest('test iterator with lte and gte after database and reverse=true', {
lte: '9b',
gte: '9a',
reverse: true
}, [])
rangeTest('test iterator with lt and gt after database and reverse=true', {
lt: '9b',
gt: '9a',
reverse: true
}, [])
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.range(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/factory-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/factory-test.js | 'use strict'
const concat = require('level-concat-iterator')
module.exports = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('testCommon.factory() returns a unique database', function (t) {
const db1 = testCommon.factory()
const db2 = testCommon.factory()
function close () {
db1.close(function (err) {
t.error(err, 'no error while closing db1')
db2.close(function (err) {
t.error(err, 'no error while closing db2')
t.end()
})
})
}
db1.open(function (err) {
t.error(err, 'no error while opening db1')
db2.open(function (err) {
t.error(err, 'no error while opening db2')
db1.put('key', 'value', function (err) {
t.error(err, 'put key in db1')
concat(db2.iterator(), function (err, entries) {
t.error(err, 'got items from db2')
t.same(entries, [], 'db2 should be empty')
close()
})
})
})
})
})
test('tearDown', testCommon.tearDown)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/del-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/del-test.js | 'use strict'
const verifyNotFoundError = require('./util').verifyNotFoundError
let db
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.args = function (test, testCommon) {
testCommon.promises || test('test argument-less del() throws', function (t) {
t.throws(
db.del.bind(db),
/Error: del\(\) requires a callback argument/,
'no-arg del() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 1-arg, del() throws', function (t) {
t.throws(
db.del.bind(db, 'foo'),
/Error: del\(\) requires a callback argument/,
'callback-less, 1-arg del() throws'
)
t.end()
})
testCommon.promises || test('test callback-less, 3-arg, del() throws', function (t) {
t.throws(
db.del.bind(db, 'foo', {}),
/Error: del\(\) requires a callback argument/,
'callback-less, 2-arg del() throws'
)
t.end()
})
}
exports.del = function (test, testCommon) {
test('test simple del()', function (t) {
db.put('foo', 'bar', function (err) {
t.error(err)
db.del('foo', function (err) {
t.error(err)
db.get('foo', function (err, value) {
t.ok(err, 'entry properly deleted')
t.ok(typeof value === 'undefined', 'value is undefined')
t.ok(verifyNotFoundError(err), 'NotFound error')
t.end()
})
})
})
})
test('test del on non-existent key', function (t) {
db.del('blargh', function (err) {
t.error(err)
t.end()
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.del(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/self.js | aws/lti-middleware/node_modules/abstract-leveldown/test/self.js | 'use strict'
const test = require('tape')
const sinon = require('sinon')
const inherits = require('util').inherits
const AbstractLevelDOWN = require('../').AbstractLevelDOWN
const AbstractIterator = require('../').AbstractIterator
const AbstractChainedBatch = require('../').AbstractChainedBatch
const testCommon = require('./common')({
test: test,
clear: true,
factory: function () {
return new AbstractLevelDOWN()
}
})
const rangeOptions = ['gt', 'gte', 'lt', 'lte']
// Test the suite itself as well as the default implementation,
// excluding noop operations that can't pass the test suite.
require('./leveldown-test')(test, testCommon)
require('./manifest-test')(test, testCommon)
require('./open-test').all(test, testCommon)
require('./open-create-if-missing-test').setUp(test, testCommon)
require('./open-create-if-missing-test').tearDown(test, testCommon)
require('./open-error-if-exists-test').setUp(test, testCommon)
require('./open-error-if-exists-test').tearDown(test, testCommon)
require('./del-test').setUp(test, testCommon)
require('./del-test').args(test, testCommon)
require('./get-test').setUp(test, testCommon)
require('./get-test').args(test, testCommon)
require('./get-many-test').setUp(test, testCommon)
require('./get-many-test').args(test, testCommon)
require('./put-test').setUp(test, testCommon)
require('./put-test').args(test, testCommon)
require('./put-get-del-test').setUp(test, testCommon)
require('./put-get-del-test').errorKeys(test, testCommon)
require('./put-get-del-test').tearDown(test, testCommon)
require('./batch-test').setUp(test, testCommon)
require('./batch-test').args(test, testCommon)
require('./chained-batch-test').setUp(test, testCommon)
require('./chained-batch-test').args(test, testCommon)
require('./chained-batch-test').tearDown(test, testCommon)
require('./close-test').all(test, testCommon)
require('./iterator-test').setUp(test, testCommon)
require('./iterator-test').args(test, testCommon)
require('./iterator-test').sequence(test, testCommon)
require('./iterator-test').tearDown(test, testCommon)
require('./iterator-range-test').setUp(test, testCommon)
require('./iterator-range-test').tearDown(test, testCommon)
require('./async-iterator-test').setup(test, testCommon)
require('./async-iterator-test').teardown(test, testCommon)
require('./iterator-snapshot-test').setUp(test, testCommon)
require('./iterator-snapshot-test').tearDown(test, testCommon)
require('./iterator-no-snapshot-test').setUp(test, testCommon)
require('./iterator-no-snapshot-test').tearDown(test, testCommon)
require('./iterator-seek-test').setUp(test, testCommon)
require('./iterator-seek-test').sequence(test, testCommon)
require('./iterator-seek-test').tearDown(test, testCommon)
require('./clear-test').setUp(test, testCommon)
require('./clear-test').args(test, testCommon)
require('./clear-test').tearDown(test, testCommon)
require('./clear-range-test').setUp(test, testCommon)
require('./clear-range-test').tearDown(test, testCommon)
function implement (ctor, methods) {
function Test () {
ctor.apply(this, arguments)
}
inherits(Test, ctor)
for (const k in methods) {
Test.prototype[k] = methods[k]
}
return Test
}
// Temporary test for browsers
// Not supported on Safari < 12 and Safari iOS < 12
test('async generator', async function (t) {
let ended = false
const end = async () => {
await new Promise((resolve) => setTimeout(resolve, 100))
ended = true
}
async function * generator () {
try {
yield 1
yield 2
yield 3
yield 4
} finally {
// Test that we're always able to cleanup resources
await end()
}
}
const res = []
for await (const x of generator()) {
res.push(x)
if (x === 2) break
}
t.same(res, [1, 2])
t.is(ended, true)
ended = false
try {
for await (const x of generator()) {
res.push(x)
if (x === 2) throw new Error('userland error')
}
} catch (err) {
t.is(err.message, 'userland error')
}
t.same(res, [1, 2, 1, 2])
t.is(ended, true)
})
/**
* Extensibility
*/
test('test core extensibility', function (t) {
const Test = implement(AbstractLevelDOWN)
const test = new Test()
t.equal(test.status, 'new', 'status is new')
t.end()
})
test('test key/value serialization', function (t) {
const Test = implement(AbstractLevelDOWN)
const test = new Test()
;['', {}, null, undefined, Buffer.alloc(0)].forEach(function (v) {
t.ok(test._serializeKey(v) === v, '_serializeKey is an identity function')
t.ok(test._serializeValue(v) === v, '_serializeValue is an identity function')
})
t.end()
})
test('test open() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const expectedOptions = { createIfMissing: true, errorIfExists: false }
const Test = implement(AbstractLevelDOWN, { _open: spy })
const test = new Test('foobar')
test.open(expectedCb)
t.equal(spy.callCount, 1, 'got _open() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _open() was correct')
t.equal(spy.getCall(0).args.length, 2, 'got two arguments')
t.deepEqual(spy.getCall(0).args[0], expectedOptions, 'got default options argument')
test.open({ options: 1 }, expectedCb)
expectedOptions.options = 1
t.equal(spy.callCount, 2, 'got _open() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _open() was correct')
t.equal(spy.getCall(1).args.length, 2, 'got two arguments')
t.deepEqual(spy.getCall(1).args[0], expectedOptions, 'got expected options argument')
t.end()
})
test('test close() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const Test = implement(AbstractLevelDOWN, { _close: spy })
const test = new Test('foobar')
test.close(expectedCb)
t.equal(spy.callCount, 1, 'got _close() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _close() was correct')
t.equal(spy.getCall(0).args.length, 1, 'got one arguments')
t.end()
})
test('test get() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const expectedOptions = { asBuffer: true }
const expectedKey = 'a key'
const Test = implement(AbstractLevelDOWN, { _get: spy })
const test = new Test('foobar')
test.get(expectedKey, expectedCb)
t.equal(spy.callCount, 1, 'got _get() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _get() was correct')
t.equal(spy.getCall(0).args.length, 3, 'got three arguments')
t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument')
t.deepEqual(spy.getCall(0).args[1], expectedOptions, 'got default options argument')
t.equal(spy.getCall(0).args[2], expectedCb, 'got expected cb argument')
test.get(expectedKey, { options: 1 }, expectedCb)
expectedOptions.options = 1
t.equal(spy.callCount, 2, 'got _get() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _get() was correct')
t.equal(spy.getCall(1).args.length, 3, 'got three arguments')
t.equal(spy.getCall(1).args[0], expectedKey, 'got expected key argument')
t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument')
t.equal(spy.getCall(1).args[2], expectedCb, 'got expected cb argument')
t.end()
})
test('test getMany() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const expectedOptions = { asBuffer: true }
const expectedKey = 'a key'
const Test = implement(AbstractLevelDOWN, { _getMany: spy })
const test = new Test('foobar')
test.status = 'open'
test.getMany([expectedKey], expectedCb)
t.equal(spy.callCount, 1, 'got _getMany() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _getMany() was correct')
t.equal(spy.getCall(0).args.length, 3, 'got three arguments')
t.deepEqual(spy.getCall(0).args[0], [expectedKey], 'got expected keys argument')
t.deepEqual(spy.getCall(0).args[1], expectedOptions, 'got default options argument')
t.equal(spy.getCall(0).args[2], expectedCb, 'got expected cb argument')
test.getMany([expectedKey], { options: 1 }, expectedCb)
expectedOptions.options = 1
t.equal(spy.callCount, 2, 'got _getMany() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _getMany() was correct')
t.equal(spy.getCall(1).args.length, 3, 'got three arguments')
t.deepEqual(spy.getCall(1).args[0], [expectedKey], 'got expected key argument')
t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument')
t.equal(spy.getCall(1).args[2], expectedCb, 'got expected cb argument')
t.end()
})
test('test del() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const expectedOptions = { options: 1 }
const expectedKey = 'a key'
const Test = implement(AbstractLevelDOWN, { _del: spy })
const test = new Test('foobar')
test.del(expectedKey, expectedCb)
t.equal(spy.callCount, 1, 'got _del() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _del() was correct')
t.equal(spy.getCall(0).args.length, 3, 'got three arguments')
t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument')
t.deepEqual(spy.getCall(0).args[1], {}, 'got blank options argument')
t.equal(spy.getCall(0).args[2], expectedCb, 'got expected cb argument')
test.del(expectedKey, expectedOptions, expectedCb)
t.equal(spy.callCount, 2, 'got _del() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _del() was correct')
t.equal(spy.getCall(1).args.length, 3, 'got three arguments')
t.equal(spy.getCall(1).args[0], expectedKey, 'got expected key argument')
t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument')
t.equal(spy.getCall(1).args[2], expectedCb, 'got expected cb argument')
t.end()
})
test('test put() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const expectedOptions = { options: 1 }
const expectedKey = 'a key'
const expectedValue = 'a value'
const Test = implement(AbstractLevelDOWN, { _put: spy })
const test = new Test('foobar')
test.put(expectedKey, expectedValue, expectedCb)
t.equal(spy.callCount, 1, 'got _put() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _put() was correct')
t.equal(spy.getCall(0).args.length, 4, 'got four arguments')
t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument')
t.equal(spy.getCall(0).args[1], expectedValue, 'got expected value argument')
t.deepEqual(spy.getCall(0).args[2], {}, 'got blank options argument')
t.equal(spy.getCall(0).args[3], expectedCb, 'got expected cb argument')
test.put(expectedKey, expectedValue, expectedOptions, expectedCb)
t.equal(spy.callCount, 2, 'got _put() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _put() was correct')
t.equal(spy.getCall(1).args.length, 4, 'got four arguments')
t.equal(spy.getCall(1).args[0], expectedKey, 'got expected key argument')
t.equal(spy.getCall(1).args[1], expectedValue, 'got expected value argument')
t.deepEqual(spy.getCall(1).args[2], expectedOptions, 'got blank options argument')
t.equal(spy.getCall(1).args[3], expectedCb, 'got expected cb argument')
t.end()
})
test('test batch([]) (array-form) extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const expectedOptions = { options: 1 }
const expectedArray = [
{ type: 'put', key: '1', value: '1' },
{ type: 'del', key: '2' }
]
const Test = implement(AbstractLevelDOWN, { _batch: spy })
const test = new Test('foobar')
test.batch(expectedArray, expectedCb)
t.equal(spy.callCount, 1, 'got _batch() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _batch() was correct')
t.equal(spy.getCall(0).args.length, 3, 'got three arguments')
t.deepEqual(spy.getCall(0).args[0], expectedArray, 'got expected array argument')
t.deepEqual(spy.getCall(0).args[1], {}, 'got expected options argument')
t.equal(spy.getCall(0).args[2], expectedCb, 'got expected callback argument')
test.batch(expectedArray, expectedOptions, expectedCb)
t.equal(spy.callCount, 2, 'got _batch() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _batch() was correct')
t.equal(spy.getCall(1).args.length, 3, 'got three arguments')
t.deepEqual(spy.getCall(1).args[0], expectedArray, 'got expected array argument')
t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument')
t.equal(spy.getCall(1).args[2], expectedCb, 'got expected callback argument')
test.batch(expectedArray, null, expectedCb)
t.equal(spy.callCount, 3, 'got _batch() call')
t.equal(spy.getCall(2).thisValue, test, '`this` on _batch() was correct')
t.equal(spy.getCall(2).args.length, 3, 'got three arguments')
t.deepEqual(spy.getCall(2).args[0], expectedArray, 'got expected array argument')
t.ok(spy.getCall(2).args[1], 'options should not be null')
t.equal(spy.getCall(2).args[2], expectedCb, 'got expected callback argument')
t.end()
})
test('test batch([]) (array-form) with empty array is asynchronous', function (t) {
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, { _batch: spy })
const test = new Test()
let async = false
test.batch([], function (err) {
t.ifError(err, 'no error')
t.ok(async, 'callback is asynchronous')
// Assert that asynchronicity is provided by batch() rather than _batch()
t.is(spy.callCount, 0, '_batch() call was bypassed')
t.end()
})
async = true
})
test('test chained batch() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const expectedOptions = { options: 1 }
const Test = implement(AbstractLevelDOWN, { _batch: spy })
const test = new Test('foobar')
test.batch().put('foo', 'bar').del('bang').write(expectedCb)
t.equal(spy.callCount, 1, 'got _batch() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _batch() was correct')
t.equal(spy.getCall(0).args.length, 3, 'got three arguments')
t.equal(spy.getCall(0).args[0].length, 2, 'got expected array argument')
t.deepEqual(spy.getCall(0).args[0][0], { type: 'put', key: 'foo', value: 'bar' }, 'got expected array argument[0]')
t.deepEqual(spy.getCall(0).args[0][1], { type: 'del', key: 'bang' }, 'got expected array argument[1]')
t.deepEqual(spy.getCall(0).args[1], {}, 'got expected options argument')
t.equal(spy.getCall(0).args[2], expectedCb, 'got expected callback argument')
test.batch().put('foo', 'bar', expectedOptions).del('bang', expectedOptions).write(expectedOptions, expectedCb)
t.equal(spy.callCount, 2, 'got _batch() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _batch() was correct')
t.equal(spy.getCall(1).args.length, 3, 'got three arguments')
t.equal(spy.getCall(1).args[0].length, 2, 'got expected array argument')
t.deepEqual(spy.getCall(1).args[0][0], { type: 'put', key: 'foo', value: 'bar', options: 1 }, 'got expected array argument[0]')
t.deepEqual(spy.getCall(1).args[0][1], { type: 'del', key: 'bang', options: 1 }, 'got expected array argument[1]')
t.deepEqual(spy.getCall(1).args[1], expectedOptions, 'got expected options argument')
t.equal(spy.getCall(1).args[2], expectedCb, 'got expected callback argument')
t.end()
})
test('test chained batch() with no operations is asynchronous', function (t) {
const Test = implement(AbstractLevelDOWN, {})
const test = new Test()
let async = false
test.batch().write(function (err) {
t.ifError(err, 'no error')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test chained batch() (custom _chainedBatch) extensibility', function (t) {
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, { _chainedBatch: spy })
const test = new Test('foobar')
test.batch()
t.equal(spy.callCount, 1, 'got _chainedBatch() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _chainedBatch() was correct')
test.batch()
t.equal(spy.callCount, 2, 'got _chainedBatch() call')
t.equal(spy.getCall(1).thisValue, test, '`this` on _chainedBatch() was correct')
t.end()
})
test('test AbstractChainedBatch extensibility', function (t) {
const Test = implement(AbstractChainedBatch)
const db = {}
const test = new Test(db)
t.ok(test.db === db, 'instance has db reference')
t.end()
})
test('test AbstractChainedBatch expects a db', function (t) {
t.plan(1)
const Test = implement(AbstractChainedBatch)
try {
Test()
} catch (err) {
t.is(err.message, 'First argument must be an abstract-leveldown compliant store')
}
})
test('test AbstractChainedBatch#write() extensibility', function (t) {
const spy = sinon.spy()
const spycb = sinon.spy()
const Test = implement(AbstractChainedBatch, { _write: spy })
const test = new Test({ test: true })
test.write(spycb)
t.equal(spy.callCount, 1, 'got _write() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _write() was correct')
t.equal(spy.getCall(0).args.length, 2, 'got two arguments')
t.same(spy.getCall(0).args[0], {}, 'got options')
// awkward here cause of nextTick & an internal wrapped cb
t.equal(typeof spy.getCall(0).args[1], 'function', 'got a callback function')
t.equal(spycb.callCount, 0, 'spycb not called')
spy.getCall(0).args[1]()
t.equal(spycb.callCount, 1, 'spycb called, i.e. was our cb argument')
t.end()
})
test('test AbstractChainedBatch#write() extensibility with null options', function (t) {
const spy = sinon.spy()
const Test = implement(AbstractChainedBatch, { _write: spy })
const test = new Test({ test: true })
test.write(null, function () {})
t.equal(spy.callCount, 1, 'got _write() call')
t.same(spy.getCall(0).args[0], {}, 'got options')
t.end()
})
test('test AbstractChainedBatch#write() extensibility with options', function (t) {
const spy = sinon.spy()
const Test = implement(AbstractChainedBatch, { _write: spy })
const test = new Test({ test: true })
test.write({ test: true }, function () {})
t.equal(spy.callCount, 1, 'got _write() call')
t.same(spy.getCall(0).args[0], { test: true }, 'got options')
t.end()
})
test('test AbstractChainedBatch#put() extensibility', function (t) {
const spy = sinon.spy()
const expectedKey = 'key'
const expectedValue = 'value'
const Test = implement(AbstractChainedBatch, { _put: spy })
const test = new Test(testCommon.factory())
const returnValue = test.put(expectedKey, expectedValue)
t.equal(spy.callCount, 1, 'got _put call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _put() was correct')
t.equal(spy.getCall(0).args.length, 3, 'got 3 arguments')
t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument')
t.equal(spy.getCall(0).args[1], expectedValue, 'got expected value argument')
t.same(spy.getCall(0).args[2], {}, 'got expected options argument')
t.equal(returnValue, test, 'get expected return value')
t.end()
})
test('test AbstractChainedBatch#del() extensibility', function (t) {
const spy = sinon.spy()
const expectedKey = 'key'
const Test = implement(AbstractChainedBatch, { _del: spy })
const test = new Test(testCommon.factory())
const returnValue = test.del(expectedKey)
t.equal(spy.callCount, 1, 'got _del call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _del() was correct')
t.equal(spy.getCall(0).args.length, 2, 'got 2 arguments')
t.equal(spy.getCall(0).args[0], expectedKey, 'got expected key argument')
t.same(spy.getCall(0).args[1], {}, 'got expected options argument')
t.equal(returnValue, test, 'get expected return value')
t.end()
})
test('test AbstractChainedBatch#clear() extensibility', function (t) {
const spy = sinon.spy()
const Test = implement(AbstractChainedBatch, { _clear: spy })
const test = new Test(testCommon.factory())
const returnValue = test.clear()
t.equal(spy.callCount, 1, 'got _clear call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _clear() was correct')
t.equal(spy.getCall(0).args.length, 0, 'got zero arguments')
t.equal(returnValue, test, 'get expected return value')
t.end()
})
test('test iterator() extensibility', function (t) {
const spy = sinon.spy()
const expectedOptions = {
options: 1,
reverse: false,
keys: true,
values: true,
limit: -1,
keyAsBuffer: true,
valueAsBuffer: true
}
const Test = implement(AbstractLevelDOWN, { _iterator: spy })
const test = new Test('foobar')
test.iterator({ options: 1 })
t.equal(spy.callCount, 1, 'got _iterator() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _iterator() was correct')
t.equal(spy.getCall(0).args.length, 1, 'got one arguments')
t.deepEqual(spy.getCall(0).args[0], expectedOptions, 'got expected options argument')
t.end()
})
test('test AbstractIterator extensibility', function (t) {
const Test = implement(AbstractIterator)
const db = {}
const test = new Test(db)
t.ok(test.db === db, 'instance has db reference')
t.end()
})
test('test AbstractIterator#next() extensibility', function (t) {
const spy = sinon.spy()
const spycb = sinon.spy()
const Test = implement(AbstractIterator, { _next: spy })
const test = new Test({})
test.next(spycb)
t.equal(spy.callCount, 1, 'got _next() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _next() was correct')
t.equal(spy.getCall(0).args.length, 1, 'got one arguments')
// awkward here cause of nextTick & an internal wrapped cb
t.equal(typeof spy.getCall(0).args[0], 'function', 'got a callback function')
t.equal(spycb.callCount, 0, 'spycb not called')
spy.getCall(0).args[0]()
t.equal(spycb.callCount, 1, 'spycb called, i.e. was our cb argument')
t.end()
})
test('test AbstractIterator#end() extensibility', function (t) {
const spy = sinon.spy()
const expectedCb = function () {}
const Test = implement(AbstractIterator, { _end: spy })
const test = new Test({})
test.end(expectedCb)
t.equal(spy.callCount, 1, 'got _end() call')
t.equal(spy.getCall(0).thisValue, test, '`this` on _end() was correct')
t.equal(spy.getCall(0).args.length, 1, 'got one arguments')
t.equal(spy.getCall(0).args[0], expectedCb, 'got expected cb argument')
t.end()
})
test('test clear() extensibility', function (t) {
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, { _clear: spy })
const db = new Test()
const callback = function () {}
call([callback], { reverse: false, limit: -1 })
call([null, callback], { reverse: false, limit: -1 })
call([undefined, callback], { reverse: false, limit: -1 })
call([{ custom: 1 }, callback], { custom: 1, reverse: false, limit: -1 })
call([{ reverse: true, limit: 0 }, callback], { reverse: true, limit: 0 })
call([{ reverse: 1 }, callback], { reverse: true, limit: -1 })
call([{ reverse: null }, callback], { reverse: false, limit: -1 })
function call (args, expectedOptions) {
db.clear.apply(db, args)
t.is(spy.callCount, 1, 'got _clear() call')
t.is(spy.getCall(0).thisValue, db, '`this` on _clear() was correct')
t.is(spy.getCall(0).args.length, 2, 'got two arguments')
t.same(spy.getCall(0).args[0], expectedOptions, 'got expected options argument')
t.is(spy.getCall(0).args[1], callback, 'got expected callback argument')
spy.resetHistory()
}
t.end()
})
test('test serialization extensibility (get)', function (t) {
t.plan(2)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_get: spy,
_serializeKey: function (key) {
return key.toUpperCase()
}
})
const test = new Test()
test.get('foo', function () {})
t.is(spy.callCount, 1, 'got _get() call')
t.is(spy.getCall(0).args[0], 'FOO', 'got expected key argument')
})
test('test serialization extensibility (getMany)', function (t) {
t.plan(2)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_getMany: spy,
_serializeKey: function (key) {
return key.toUpperCase()
}
})
const test = new Test()
test.status = 'open'
test.getMany(['foo', 'bar'], function () {})
t.is(spy.callCount, 1, 'got _getMany() call')
t.same(spy.getCall(0).args[0], ['FOO', 'BAR'], 'got expected keys argument')
})
test('test serialization extensibility (put)', function (t) {
t.plan(5)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_put: spy,
_serializeKey: function (key) {
t.equal(key, 'no')
return 'foo'
},
_serializeValue: function (value) {
t.equal(value, 'nope')
return 'bar'
}
})
const test = new Test('foobar')
test.put('no', 'nope', function () {})
t.equal(spy.callCount, 1, 'got _put() call')
t.equal(spy.getCall(0).args[0], 'foo', 'got expected key argument')
t.equal(spy.getCall(0).args[1], 'bar', 'got expected value argument')
})
test('test serialization extensibility (del)', function (t) {
t.plan(3)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_del: spy,
_serializeKey: function (key) {
t.equal(key, 'no')
return 'foo'
},
_serializeValue: function (value) {
t.fail('should not be called')
}
})
const test = new Test('foobar')
test.del('no', function () {})
t.equal(spy.callCount, 1, 'got _del() call')
t.equal(spy.getCall(0).args[0], 'foo', 'got expected key argument')
t.end()
})
test('test serialization extensibility (batch array put)', function (t) {
t.plan(5)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_batch: spy,
_serializeKey: function (key) {
t.equal(key, 'no')
return 'foo'
},
_serializeValue: function (value) {
t.equal(value, 'nope')
return 'bar'
}
})
const test = new Test('foobar')
test.batch([{ type: 'put', key: 'no', value: 'nope' }], function () {})
t.equal(spy.callCount, 1, 'got _batch() call')
t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key')
t.equal(spy.getCall(0).args[0][0].value, 'bar', 'got expected value')
})
test('test serialization extensibility (batch chain put)', function (t) {
t.plan(5)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_batch: spy,
_serializeKey: function (key) {
t.equal(key, 'no')
return 'foo'
},
_serializeValue: function (value) {
t.equal(value, 'nope')
return 'bar'
}
})
const test = new Test('foobar')
test.batch().put('no', 'nope').write(function () {})
t.equal(spy.callCount, 1, 'got _batch() call')
t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key')
t.equal(spy.getCall(0).args[0][0].value, 'bar', 'got expected value')
})
test('test serialization extensibility (batch array del)', function (t) {
t.plan(3)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_batch: spy,
_serializeKey: function (key) {
t.equal(key, 'no')
return 'foo'
},
_serializeValue: function (value) {
t.fail('should not be called')
}
})
const test = new Test('foobar')
test.batch([{ type: 'del', key: 'no' }], function () {})
t.equal(spy.callCount, 1, 'got _batch() call')
t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key')
})
test('test serialization extensibility (batch chain del)', function (t) {
t.plan(3)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_batch: spy,
_serializeKey: function (key) {
t.equal(key, 'no')
return 'foo'
},
_serializeValue: function (value) {
t.fail('should not be called')
}
})
const test = new Test('foobar')
test.batch().del('no').write(function () {})
t.equal(spy.callCount, 1, 'got _batch() call')
t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key')
})
test('test serialization extensibility (batch array is not mutated)', function (t) {
t.plan(7)
const spy = sinon.spy()
const Test = implement(AbstractLevelDOWN, {
_batch: spy,
_serializeKey: function (key) {
t.equal(key, 'no')
return 'foo'
},
_serializeValue: function (value) {
t.equal(value, 'nope')
return 'bar'
}
})
const test = new Test('foobar')
const op = { type: 'put', key: 'no', value: 'nope' }
test.batch([op], function () {})
t.equal(spy.callCount, 1, 'got _batch() call')
t.equal(spy.getCall(0).args[0][0].key, 'foo', 'got expected key')
t.equal(spy.getCall(0).args[0][0].value, 'bar', 'got expected value')
t.equal(op.key, 'no', 'did not mutate input key')
t.equal(op.value, 'nope', 'did not mutate input value')
})
test('test serialization extensibility (iterator range options)', function (t) {
t.plan(2)
function Test () {
AbstractLevelDOWN.call(this)
}
inherits(Test, AbstractLevelDOWN)
Test.prototype._serializeKey = function (key) {
t.is(key, 'input')
return 'output'
}
Test.prototype._iterator = function (options) {
return new Iterator(this, options)
}
function Iterator (db, options) {
AbstractIterator.call(this, db)
t.is(options.gt, 'output')
}
inherits(Iterator, AbstractIterator)
const test = new Test()
test.iterator({ gt: 'input' })
})
test('test serialization extensibility (iterator seek)', function (t) {
t.plan(3)
const spy = sinon.spy()
const TestIterator = implement(AbstractIterator, { _seek: spy })
const Test = implement(AbstractLevelDOWN, {
_iterator: function () {
return new TestIterator(this)
},
_serializeKey: function (key) {
t.equal(key, 'target')
return 'serialized'
}
})
const test = new Test('foobar')
const it = test.iterator()
it.seek('target')
t.equal(spy.callCount, 1, 'got _seek() call')
t.equal(spy.getCall(0).args[0], 'serialized', 'got expected target argument')
})
test('test serialization extensibility (clear range options)', function (t) {
t.plan(rangeOptions.length * 2)
rangeOptions.forEach(function (key) {
const Test = implement(AbstractLevelDOWN, {
_serializeKey: function (key) {
t.is(key, 'input')
return 'output'
},
_clear: function (options, callback) {
t.is(options[key], 'output')
}
})
const db = new Test()
const options = {}
options[key] = 'input'
db.clear(options, function () {})
})
})
test('clear() does not delete empty or nullish range options', function (t) {
const rangeValues = [Buffer.alloc(0), '', null, undefined]
t.plan(rangeOptions.length * rangeValues.length)
rangeValues.forEach(function (value) {
const Test = implement(AbstractLevelDOWN, {
_clear: function (options, callback) {
rangeOptions.forEach(function (key) {
t.ok(key in options, key + ' option should not be deleted')
})
}
})
const db = new Test()
const options = {}
rangeOptions.forEach(function (key) {
options[key] = value
})
db.clear(options, function () {})
})
})
test('.status', function (t) {
t.plan(5)
t.test('empty prototype', function (t) {
const Test = implement(AbstractLevelDOWN)
const test = new Test('foobar')
t.equal(test.status, 'new')
test.open(function (err) {
t.error(err)
t.equal(test.status, 'open')
test.close(function (err) {
t.error(err)
t.equal(test.status, 'closed')
t.end()
})
})
t.equal(test.status, 'opening')
})
t.test('open error', function (t) {
const Test = implement(AbstractLevelDOWN, {
_open: function (options, cb) {
cb(new Error())
}
})
const test = new Test('foobar')
test.open(function (err) {
t.ok(err)
t.equal(test.status, 'new')
t.end()
})
})
t.test('close error', function (t) {
const Test = implement(AbstractLevelDOWN, {
_close: function (cb) {
cb(new Error())
}
})
const test = new Test('foobar')
test.open(function () {
test.close(function (err) {
t.ok(err)
t.equal(test.status, 'open')
t.end()
})
})
})
t.test('open', function (t) {
const Test = implement(AbstractLevelDOWN, {
_open: function (options, cb) {
this._nextTick(cb)
}
})
const test = new Test('foobar')
test.open(function (err) {
t.error(err)
t.equal(test.status, 'open')
t.end()
})
t.equal(test.status, 'opening')
})
t.test('close', function (t) {
const Test = implement(AbstractLevelDOWN, {
_close: function (cb) {
this._nextTick(cb)
}
})
const test = new Test('foobar')
test.open(function (err) {
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | true |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/open-error-if-exists-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/open-error-if-exists-test.js | 'use strict'
exports.setUp = function (test, testCommon) {
test('setUp', testCommon.setUp)
}
exports.errorIfExists = function (test, testCommon) {
test('test database open errorIfExists:true', function (t) {
const db = testCommon.factory()
db.open({}, function (err) {
t.error(err)
db.close(function (err) {
t.error(err)
let async = false
db.open({ createIfMissing: false, errorIfExists: true }, function (err) {
t.ok(err, 'error')
t.ok(/exists/.test(err.message), 'error is about already existing')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
})
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', testCommon.tearDown)
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.errorIfExists(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/put-get-del-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/put-get-del-test.js | 'use strict'
const verifyNotFoundError = require('./util').verifyNotFoundError
const assertAsync = require('./util').assertAsync
const testBuffer = Buffer.from('testbuffer')
let db
function makeGetDelErrorTests (test, testCommon, type, key, expectedError) {
test('test get() with ' + type + ' causes error', function (t) {
let async = false
db.get(key, function (err) {
t.ok(err, 'has error')
t.ok(err instanceof Error)
t.ok(err.message.match(expectedError), 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test del() with ' + type + ' causes error', function (t) {
let async = false
db.del(key, function (err) {
t.ok(err, 'has error')
t.ok(err instanceof Error)
t.ok(err.message.match(expectedError), 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
testCommon.getMany && test('test getMany() with ' + type + ' causes error', assertAsync.ctx(function (t) {
// Add 1 assertion for every assertAsync()
t.plan(2 * 4)
db.getMany([key], assertAsync(function (err) {
t.ok(err, 'has error')
t.ok(err instanceof Error)
t.ok(err.message.match(expectedError), 'correct error message')
}))
db.getMany(['valid', key], assertAsync(function (err) {
t.ok(err, 'has error')
t.ok(err instanceof Error)
t.ok(err.message.match(expectedError), 'correct error message')
}))
}))
}
function makePutErrorTest (test, type, key, value, expectedError) {
test('test put() with ' + type + ' causes error', function (t) {
let async = false
db.put(key, value, function (err) {
t.ok(err, 'has error')
t.ok(err instanceof Error)
t.ok(err.message.match(expectedError), 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
}
function makePutGetDelSuccessfulTest (test, testCommon, type, key, value, expectedResult) {
const hasExpectedResult = arguments.length === 6
test('test put()/get()/del() with ' + type, function (t) {
db.put(key, value, function (err) {
t.error(err)
db.get(key, function (err, _value) {
t.error(err, 'no error, has key/value for `' + type + '`')
let result
if (!testCommon.encodings) {
t.ok(Buffer.isBuffer(_value), 'is a Buffer')
result = _value
} else {
t.is(typeof _value, 'string', 'is a string')
result = _value
}
if (hasExpectedResult) {
t.equal(result.toString(), expectedResult)
} else {
if (result != null) { result = _value.toString() }
if (value != null) { value = value.toString() }
t.equals(result, value)
}
db.del(key, function (err) {
t.error(err, 'no error, deleted key/value for `' + type + '`')
let async = false
db.get(key, function (err, value) {
t.ok(err, 'entry properly deleted')
t.ok(verifyNotFoundError(err), 'should have correct error message')
t.equal(typeof value, 'undefined', 'value is undefined')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
})
})
})
}
function makeErrorKeyTest (test, testCommon, type, key, expectedError) {
makeGetDelErrorTests(test, testCommon, type, key, expectedError)
makePutErrorTest(test, type, key, 'foo', expectedError)
}
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.errorKeys = function (test, testCommon) {
makeErrorKeyTest(test, testCommon, 'null key', null, /key cannot be `null` or `undefined`/)
makeErrorKeyTest(test, testCommon, 'undefined key', undefined, /key cannot be `null` or `undefined`/)
makeErrorKeyTest(test, testCommon, 'empty String key', '', /key cannot be an empty String/)
makeErrorKeyTest(test, testCommon, 'empty Buffer key', Buffer.alloc(0), /key cannot be an empty \w*Buffer/)
makeErrorKeyTest(test, testCommon, 'empty Array key', [], /key cannot be an empty Array/)
}
exports.errorValues = function (test, testCommon) {
makePutErrorTest(test, 'null value', 'key', null, /value cannot be `null` or `undefined`/)
makePutErrorTest(test, 'undefined value', 'key', undefined, /value cannot be `null` or `undefined`/)
}
exports.nonErrorKeys = function (test, testCommon) {
// valid falsey keys
makePutGetDelSuccessfulTest(test, testCommon, '`0` key', 0, 'foo 0')
// standard String key
makePutGetDelSuccessfulTest(
test
, testCommon
, 'long String key'
, 'some long string that I\'m using as a key for this unit test, cross your fingers human, we\'re going in!'
, 'foo'
)
if (testCommon.bufferKeys) {
makePutGetDelSuccessfulTest(test, testCommon, 'Buffer key', testBuffer, 'foo')
}
// non-empty Array as a value
makePutGetDelSuccessfulTest(test, testCommon, 'Array value', 'foo', [1, 2, 3, 4])
}
exports.nonErrorValues = function (test, testCommon) {
// valid falsey values
makePutGetDelSuccessfulTest(test, testCommon, '`false` value', 'foo false', false)
makePutGetDelSuccessfulTest(test, testCommon, '`0` value', 'foo 0', 0)
makePutGetDelSuccessfulTest(test, testCommon, '`NaN` value', 'foo NaN', NaN)
// all of the following result in an empty-string value:
makePutGetDelSuccessfulTest(test, testCommon, 'empty String value', 'foo', '', '')
makePutGetDelSuccessfulTest(test, testCommon, 'empty Buffer value', 'foo', Buffer.alloc(0), '')
// note that an implementation may return the value as an array
makePutGetDelSuccessfulTest(test, testCommon, 'empty Array value', 'foo', [], '')
// standard String value
makePutGetDelSuccessfulTest(
test
, testCommon
, 'long String value'
, 'foo'
, 'some long string that I\'m using as a key for this unit test, cross your fingers human, we\'re going in!'
)
// standard Buffer value
makePutGetDelSuccessfulTest(test, testCommon, 'Buffer value', 'foo', testBuffer)
// non-empty Array as a key
makePutGetDelSuccessfulTest(test, testCommon, 'Array key', [1, 2, 3, 4], 'foo')
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.errorKeys(test, testCommon)
exports.errorValues(test, testCommon)
exports.nonErrorKeys(test, testCommon)
exports.nonErrorValues(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/batch-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/batch-test.js | 'use strict'
const verifyNotFoundError = require('./util').verifyNotFoundError
const isTypedArray = require('./util').isTypedArray
let db
exports.setUp = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
exports.args = function (test, testCommon) {
testCommon.promises || test('test callback-less, 2-arg, batch() throws', function (t) {
t.throws(
db.batch.bind(db, 'foo', {}),
/Error: batch\(array\) requires a callback argument/,
'callback-less, 2-arg batch() throws'
)
t.end()
})
test('test batch() with missing `value`', function (t) {
db.batch([{ type: 'put', key: 'foo1' }], function (err) {
t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message')
t.end()
})
})
test('test batch() with null or undefined `value`', function (t) {
const illegalValues = [null, undefined]
t.plan(illegalValues.length)
illegalValues.forEach(function (value) {
db.batch([{ type: 'put', key: 'foo1', value: value }], function (err) {
t.is(err.message, 'value cannot be `null` or `undefined`', 'correct error message')
})
})
})
test('test batch() with missing `key`', function (t) {
let async = false
db.batch([{ type: 'put', value: 'foo1' }], function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test batch() with null or undefined `key`', function (t) {
const illegalKeys = [null, undefined]
t.plan(illegalKeys.length * 3)
illegalKeys.forEach(function (key) {
let async = false
db.batch([{ type: 'put', key: key, value: 'foo1' }], function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
t.ok(async, 'callback is asynchronous')
})
async = true
})
})
test('test batch() with empty `key`', function (t) {
const illegalKeys = [
{ type: 'String', key: '' },
{ type: 'Buffer', key: Buffer.alloc(0) },
{ type: 'Array', key: [] }
]
t.plan(illegalKeys.length * 3)
illegalKeys.forEach(function (item) {
let async = false
db.batch([{ type: 'put', key: item.key, value: 'foo1' }], function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'key cannot be an empty ' + item.type, 'correct error message')
t.ok(async, 'callback is asynchronous')
})
async = true
})
})
test('test batch() with missing `key` and `value`', function (t) {
let async = false
db.batch([{ type: 'put' }], function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'key cannot be `null` or `undefined`', 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test batch() with missing `type`', function (t) {
let async = false
db.batch([{ key: 'key', value: 'value' }], function (err) {
t.ok(err, 'got error')
t.equal(err.message, "`type` must be 'put' or 'del'", 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test batch() with wrong `type`', function (t) {
let async = false
db.batch([{ key: 'key', value: 'value', type: 'foo' }], function (err) {
t.ok(err, 'got error')
t.equal(err.message, "`type` must be 'put' or 'del'", 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test batch() with missing array', function (t) {
let async = false
db.batch(function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'batch(array) requires an array argument', 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test batch() with undefined array', function (t) {
let async = false
db.batch(undefined, function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'batch(array) requires an array argument', 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test batch() with null array', function (t) {
let async = false
db.batch(null, function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'batch(array) requires an array argument', 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
test('test batch() with null options', function (t) {
db.batch([], null, function (err) {
t.error(err)
t.end()
})
})
;[null, undefined, 1, true].forEach(function (element) {
const type = element === null ? 'null' : typeof element
test('test batch() with ' + type + ' element', function (t) {
let async = false
db.batch([element], function (err) {
t.ok(err, 'got error')
t.equal(err.message, 'batch(array) element must be an object and not `null`', 'correct error message')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
})
test('test batch() with empty array', function (t) {
let async = false
db.batch([], function (err) {
t.error(err, 'no error from batch()')
t.ok(async, 'callback is asynchronous')
t.end()
})
async = true
})
}
exports.batch = function (test, testCommon) {
test('test simple batch()', function (t) {
db.batch([{ type: 'put', key: 'foo', value: 'bar' }], function (err) {
t.error(err)
db.get('foo', function (err, value) {
t.error(err)
let result
if (testCommon.encodings) {
t.is(typeof value, 'string')
result = value
} else if (isTypedArray(value)) {
result = String.fromCharCode.apply(null, new Uint16Array(value))
} else {
t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer)
result = value.toString()
}
t.equal(result, 'bar')
t.end()
})
})
})
test('test multiple batch()', function (t) {
db.batch([
{ type: 'put', key: 'foobatch1', value: 'bar1' },
{ type: 'put', key: 'foobatch2', value: 'bar2' },
{ type: 'put', key: 'foobatch3', value: 'bar3' },
{ type: 'del', key: 'foobatch2' }
], function (err) {
t.error(err)
let r = 0
const done = function () {
if (++r === 3) { t.end() }
}
db.get('foobatch1', function (err, value) {
t.error(err)
let result
if (testCommon.encodings) {
t.is(typeof value, 'string')
result = value
} else if (isTypedArray(value)) {
result = String.fromCharCode.apply(null, new Uint16Array(value))
} else {
t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer)
result = value.toString()
}
t.equal(result, 'bar1')
done()
})
db.get('foobatch2', function (err, value) {
t.ok(err, 'entry not found')
t.ok(typeof value === 'undefined', 'value is undefined')
t.ok(verifyNotFoundError(err), 'NotFound error')
done()
})
db.get('foobatch3', function (err, value) {
t.error(err)
let result
if (testCommon.encodings) {
t.is(typeof value, 'string')
result = value
} else if (isTypedArray(value)) {
result = String.fromCharCode.apply(null, new Uint16Array(value))
} else {
t.ok(typeof Buffer !== 'undefined' && value instanceof Buffer)
result = value.toString()
}
t.equal(result, 'bar3')
done()
})
})
})
}
exports.atomic = function (test, testCommon) {
test('test multiple batch()', function (t) {
t.plan(4)
let async = false
db.batch([
{ type: 'put', key: 'foobah1', value: 'bar1' },
{ type: 'put', value: 'bar2' },
{ type: 'put', key: 'foobah3', value: 'bar3' }
], function (err) {
t.ok(err, 'should error')
t.ok(async, 'callback is asynchronous')
db.get('foobah1', function (err) {
t.ok(err, 'should not be found')
})
db.get('foobah3', function (err) {
t.ok(err, 'should not be found')
})
})
async = true
})
}
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
})
}
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.batch(test, testCommon)
exports.atomic(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/util.js | aws/lti-middleware/node_modules/abstract-leveldown/test/util.js | 'use strict'
const nfre = /NotFound/i
const spies = []
exports.verifyNotFoundError = function verifyNotFoundError (err) {
return nfre.test(err.message) || nfre.test(err.name)
}
exports.isTypedArray = function isTypedArray (value) {
return (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) ||
(typeof Uint8Array !== 'undefined' && value instanceof Uint8Array)
}
/**
* Wrap a callback to check that it's called asynchronously. Must be
* combined with a `ctx()`, `with()` or `end()` call.
*
* @param {function} cb Callback to check.
* @param {string} name Optional callback name to use in assertion messages.
* @returns {function} Wrapped callback.
*/
exports.assertAsync = function (cb, name) {
const spy = {
called: false,
name: name || cb.name || 'anonymous'
}
spies.push(spy)
return function (...args) {
spy.called = true
return cb.apply(this, args)
}
}
/**
* Verify that callbacks wrapped with `assertAsync()` were not yet called.
* @param {import('tape').Test} t Tape test object.
*/
exports.assertAsync.end = function (t) {
for (const { called, name } of spies.splice(0, spies.length)) {
t.is(called, false, `callback (${name}) is asynchronous`)
}
}
/**
* Wrap a test function to verify `assertAsync()` spies at the end.
* @param {import('tape').TestCase} test Test function to be passed to `tape()`.
* @returns {import('tape').TestCase} Wrapped test function.
*/
exports.assertAsync.ctx = function (test) {
return function (...args) {
const ret = test.call(this, ...args)
exports.assertAsync.end(args[0])
return ret
}
}
/**
* Wrap an arbitrary callback to verify `assertAsync()` spies at the end.
* @param {import('tape').Test} t Tape test object.
* @param {function} cb Callback to wrap.
* @returns {function} Wrapped callback.
*/
exports.assertAsync.with = function (t, cb) {
return function (...args) {
const ret = cb.call(this, ...args)
exports.assertAsync.end(t)
return ret
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/leveldown-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/leveldown-test.js | 'use strict'
module.exports = function (test, testCommon) {
test('setUp common', testCommon.setUp)
test('test database open method exists', function (t) {
const db = testCommon.factory()
t.ok(db, 'database object returned')
t.ok(typeof db.open === 'function', 'open() function exists')
t.end()
})
test('tearDown', testCommon.tearDown)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/test/get-many-test.js | aws/lti-middleware/node_modules/abstract-leveldown/test/get-many-test.js | 'use strict'
const isBuffer = require('is-buffer')
const isTypedArray = require('./util').isTypedArray
const assertAsync = require('./util').assertAsync
let db
/**
* @param {import('tape')} test
*/
exports.setUp = function (test, testCommon) {
test('setUp db', function (t) {
db = testCommon.factory()
db.open(t.end.bind(t))
})
}
/**
* @param {import('tape')} test
*/
exports.args = function (test, testCommon) {
test('test getMany() requires an array argument (callback)', assertAsync.ctx(function (t) {
// Add 1 assertion for every assertAsync()
t.plan(4)
db.getMany('foo', assertAsync(function (err) {
t.is(err && err.message, 'getMany() requires an array argument')
}))
db.getMany('foo', {}, assertAsync(function (err) {
t.is(err && err.message, 'getMany() requires an array argument')
}))
}))
test('test getMany() requires an array argument (promise)', function (t) {
t.plan(3)
db.getMany().catch(function (err) {
t.is(err && err.message, 'getMany() requires an array argument')
})
db.getMany('foo').catch(function (err) {
t.is(err && err.message, 'getMany() requires an array argument')
})
db.getMany('foo', {}).catch(function (err) {
t.is(err && err.message, 'getMany() requires an array argument')
})
})
}
/**
* @param {import('tape')} test
*/
exports.getMany = function (test, testCommon) {
test('test getMany() support is reflected in manifest', function (t) {
t.is(db.supports && db.supports.getMany, true)
t.end()
})
test('test simple getMany()', function (t) {
db.put('foo', 'bar', function (err) {
t.error(err)
function verify (err, values) {
t.error(err)
t.ok(Array.isArray(values), 'got an array')
t.is(values.length, 1, 'array has 1 element')
const value = values[0]
let result
if (!testCommon.encodings) {
t.isNot(typeof value, 'string', 'should not be string by default')
if (isTypedArray(value)) {
result = String.fromCharCode.apply(null, new Uint16Array(value))
} else {
t.ok(isBuffer(value))
try {
result = value.toString()
} catch (e) {
t.error(e, 'should not throw when converting value to a string')
}
}
} else {
result = value
}
t.is(result, 'bar')
}
db.getMany(['foo'], function (err, values) {
verify(err, values)
db.getMany(['foo'], {}, function (err, values) {
verify(err, values)
db.getMany(['foo'], { asBuffer: false }, function (err, values) {
t.error(err)
t.is(values && typeof values[0], 'string', 'should be string if not buffer')
t.same(values, ['bar'])
t.end()
})
})
})
})
})
test('test getMany() with multiple keys', function (t) {
t.plan(5)
db.put('beep', 'boop', function (err) {
t.ifError(err)
db.getMany(['foo', 'beep'], { asBuffer: false }, function (err, values) {
t.ifError(err)
t.same(values, ['bar', 'boop'])
})
db.getMany(['beep', 'foo'], { asBuffer: false }, function (err, values) {
t.ifError(err)
t.same(values, ['boop', 'bar'], 'maintains order of input keys')
})
})
})
test('test empty getMany()', assertAsync.ctx(function (t) {
t.plan(2 * 3)
for (const asBuffer in [true, false]) {
db.getMany([], { asBuffer }, assertAsync(function (err, values) {
t.ifError(err)
t.same(values, [])
}))
}
}))
test('test not-found getMany()', assertAsync.ctx(function (t) {
t.plan(2 * 3)
for (const asBuffer in [true, false]) {
db.getMany(['nope', 'another'], { asBuffer }, assertAsync(function (err, values) {
t.ifError(err)
t.same(values, [undefined, undefined])
}))
}
}))
test('test getMany() with promise', async function (t) {
t.same(await db.getMany(['foo'], { asBuffer: false }), ['bar'])
t.same(await db.getMany(['beep'], { asBuffer: false }), ['boop'])
t.same(await db.getMany(['foo', 'beep'], { asBuffer: false }), ['bar', 'boop'])
t.same(await db.getMany(['beep', 'foo'], { asBuffer: false }), ['boop', 'bar'])
t.same(await db.getMany(['beep', 'foo', 'nope'], { asBuffer: false }), ['boop', 'bar', undefined])
t.same(await db.getMany([], { asBuffer: false }), [])
})
test('test simultaneous getMany()', function (t) {
db.put('hello', 'world', function (err) {
t.error(err)
let completed = 0
const done = function () {
if (++completed === 20) t.end()
}
for (let i = 0; i < 10; ++i) {
db.getMany(['hello'], function (err, values) {
t.error(err)
t.is(values.length, 1)
t.is(values[0] && values[0].toString(), 'world')
done()
})
}
for (let i = 0; i < 10; ++i) {
db.getMany(['not found'], function (err, values) {
t.error(err)
t.same(values, [undefined])
done()
})
}
})
})
test('test getMany() on new db', assertAsync.ctx(function (t) {
t.plan(2 * 2 * 5)
// Also test empty array because it has a fast-path
for (const keys of [['foo'], []]) {
// Opening should make no difference, because we call it after getMany()
for (const open of [true, false]) {
const db = testCommon.factory()
if (testCommon.status) {
t.is(db.status, testCommon.deferredOpen ? 'opening' : 'new')
} else {
t.pass('no status')
}
// Must be true if db supports deferredOpen
const operational = testCommon.deferredOpen || db.isOperational()
db.getMany(keys, assertAsync(function (err, values) {
if (operational) {
t.ifError(err, 'no error')
t.same(values, keys.map(_ => undefined))
} else {
t.is(err && err.message, 'Database is not open')
t.is(values, undefined)
}
}))
if (open) {
db.open(t.error.bind(t))
} else {
t.pass()
}
}
}
}))
test('test getMany() on opening db', assertAsync.ctx(function (t) {
t.plan(2 * 5)
// Also test empty array because it has a fast-path
for (const keys of [['foo'], []]) {
const db = testCommon.factory()
// Is a noop if db supports deferredOpen
db.open(assertAsync(t.error.bind(t), 'open'))
// Must be true if db supports deferredOpen
const operational = testCommon.deferredOpen || db.isOperational()
db.getMany(keys, assertAsync(function (err, values) {
if (operational) {
t.ifError(err, 'no error')
t.same(values, keys.map(_ => undefined))
} else {
t.is(err && err.message, 'Database is not open')
t.is(values, undefined)
}
}))
}
}))
test('test getMany() on closed db', function (t) {
t.plan(2 * 6)
// Also test empty array because it has a fast-path
for (const keys of [['foo'], []]) {
const db = testCommon.factory()
db.open(function (err) {
t.ifError(err)
t.is(db.isOperational(), true)
db.close(assertAsync.with(t, function (err) {
t.ifError(err)
t.is(db.isOperational(), false)
db.getMany(keys, assertAsync(function (err) {
t.is(err && err.message, 'Database is not open')
}))
}))
})
}
})
test('test getMany() on closing db', function (t) {
t.plan(2 * 4)
// Also test empty array because it has a fast-path
for (const keys of [['foo'], []]) {
const db = testCommon.factory()
db.open(assertAsync.with(t, function (err) {
t.ifError(err)
db.close(function (err) {
t.ifError(err)
})
db.getMany(keys, assertAsync(function (err) {
t.is(err && err.message, 'Database is not open')
}))
}))
}
})
}
/**
* @param {import('tape')} test
*/
exports.tearDown = function (test, testCommon) {
test('tearDown', function (t) {
db.close(t.end.bind(t))
})
}
/**
* @param {import('tape')} test
*/
exports.all = function (test, testCommon) {
exports.setUp(test, testCommon)
exports.args(test, testCommon)
exports.getMany(test, testCommon)
exports.tearDown(test, testCommon)
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abstract-leveldown/lib/common.js | aws/lti-middleware/node_modules/abstract-leveldown/lib/common.js | 'use strict'
exports.getCallback = function (options, callback) {
return typeof options === 'function' ? options : callback
}
exports.getOptions = function (options) {
return typeof options === 'object' && options !== null ? options : {}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abort-controller/browser.js | aws/lti-middleware/node_modules/abort-controller/browser.js | /*globals self, window */
"use strict"
/*eslint-disable @mysticatea/prettier */
const { AbortController, AbortSignal } =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
module.exports = AbortController
module.exports.AbortSignal = AbortSignal
module.exports.default = AbortController
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abort-controller/polyfill.js | aws/lti-middleware/node_modules/abort-controller/polyfill.js | /*globals require, self, window */
"use strict"
const ac = require("./dist/abort-controller")
/*eslint-disable @mysticatea/prettier */
const g =
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
/* otherwise */ undefined
/*eslint-enable @mysticatea/prettier */
if (g) {
if (typeof g.AbortController === "undefined") {
g.AbortController = ac.AbortController
}
if (typeof g.AbortSignal === "undefined") {
g.AbortSignal = ac.AbortSignal
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abort-controller/dist/abort-controller.js | aws/lti-middleware/node_modules/abort-controller/dist/abort-controller.js | /**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var eventTargetShim = require('event-target-shim');
/**
* The signal class.
* @see https://dom.spec.whatwg.org/#abortsignal
*/
class AbortSignal extends eventTargetShim.EventTarget {
/**
* AbortSignal cannot be constructed directly.
*/
constructor() {
super();
throw new TypeError("AbortSignal cannot be constructed directly");
}
/**
* Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
*/
get aborted() {
const aborted = abortedFlags.get(this);
if (typeof aborted !== "boolean") {
throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
}
return aborted;
}
}
eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort");
/**
* Create an AbortSignal object.
*/
function createAbortSignal() {
const signal = Object.create(AbortSignal.prototype);
eventTargetShim.EventTarget.call(signal);
abortedFlags.set(signal, false);
return signal;
}
/**
* Abort a given signal.
*/
function abortSignal(signal) {
if (abortedFlags.get(signal) !== false) {
return;
}
abortedFlags.set(signal, true);
signal.dispatchEvent({ type: "abort" });
}
/**
* Aborted flag for each instances.
*/
const abortedFlags = new WeakMap();
// Properties should be enumerable.
Object.defineProperties(AbortSignal.prototype, {
aborted: { enumerable: true },
});
// `toString()` should return `"[object AbortSignal]"`
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortSignal",
});
}
/**
* The AbortController.
* @see https://dom.spec.whatwg.org/#abortcontroller
*/
class AbortController {
/**
* Initialize this controller.
*/
constructor() {
signals.set(this, createAbortSignal());
}
/**
* Returns the `AbortSignal` object associated with this object.
*/
get signal() {
return getSignal(this);
}
/**
* Abort and signal to any observers that the associated activity is to be aborted.
*/
abort() {
abortSignal(getSignal(this));
}
}
/**
* Associated signals.
*/
const signals = new WeakMap();
/**
* Get the associated signal of a given controller.
*/
function getSignal(controller) {
const signal = signals.get(controller);
if (signal == null) {
throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
}
return signal;
}
// Properties should be enumerable.
Object.defineProperties(AbortController.prototype, {
signal: { enumerable: true },
abort: { enumerable: true },
});
if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
configurable: true,
value: "AbortController",
});
}
exports.AbortController = AbortController;
exports.AbortSignal = AbortSignal;
exports.default = AbortController;
module.exports = AbortController
module.exports.AbortController = module.exports["default"] = AbortController
module.exports.AbortSignal = AbortSignal
//# sourceMappingURL=abort-controller.js.map
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/abort-controller/dist/abort-controller.umd.js | aws/lti-middleware/node_modules/abort-controller/dist/abort-controller.umd.js | /**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/(function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):(a=a||self,b(a.AbortControllerShim={}))})(this,function(a){'use strict';function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function d(a,b){for(var c,d=0;d<b.length;d++)c=b[d],c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(a,c.key,c)}function e(a,b,c){return b&&d(a.prototype,b),c&&d(a,c),a}function f(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function");a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),b&&h(a,b)}function g(a){return g=Object.setPrototypeOf?Object.getPrototypeOf:function(a){return a.__proto__||Object.getPrototypeOf(a)},g(a)}function h(a,b){return h=Object.setPrototypeOf||function(a,b){return a.__proto__=b,a},h(a,b)}function i(a){if(void 0===a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return a}function j(a,b){return b&&("object"==typeof b||"function"==typeof b)?b:i(a)}function k(a){var b=F.get(a);return console.assert(null!=b,"'this' is expected an Event object, but got",a),b}function l(a){return null==a.passiveListener?void(!a.event.cancelable||(a.canceled=!0,"function"==typeof a.event.preventDefault&&a.event.preventDefault())):void("undefined"!=typeof console&&"function"==typeof console.error&&console.error("Unable to preventDefault inside passive event listener invocation.",a.passiveListener))}function m(a,b){F.set(this,{eventTarget:a,event:b,eventPhase:2,currentTarget:a,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:b.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});for(var c,d=Object.keys(b),e=0;e<d.length;++e)c=d[e],c in this||Object.defineProperty(this,c,n(c))}function n(a){return{get:function(){return k(this).event[a]},set:function(b){k(this).event[a]=b},configurable:!0,enumerable:!0}}function o(a){return{value:function(){var b=k(this).event;return b[a].apply(b,arguments)},configurable:!0,enumerable:!0}}function p(a,b){function c(b,c){a.call(this,b,c)}var d=Object.keys(b);if(0===d.length)return a;c.prototype=Object.create(a.prototype,{constructor:{value:c,configurable:!0,writable:!0}});for(var e,f=0;f<d.length;++f)if(e=d[f],!(e in a.prototype)){var g=Object.getOwnPropertyDescriptor(b,e),h="function"==typeof g.value;Object.defineProperty(c.prototype,e,h?o(e):n(e))}return c}function q(a){if(null==a||a===Object.prototype)return m;var b=G.get(a);return null==b&&(b=p(q(Object.getPrototypeOf(a)),a),G.set(a,b)),b}function r(a,b){var c=q(Object.getPrototypeOf(b));return new c(a,b)}function s(a){return k(a).immediateStopped}function t(a,b){k(a).eventPhase=b}function u(a,b){k(a).currentTarget=b}function v(a,b){k(a).passiveListener=b}function w(a){return null!==a&&"object"===b(a)}function x(a){var b=H.get(a);if(null==b)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return b}function y(a){return{get:function(){for(var b=x(this),c=b.get(a);null!=c;){if(3===c.listenerType)return c.listener;c=c.next}return null},set:function(b){"function"==typeof b||w(b)||(b=null);for(var c=x(this),d=null,e=c.get(a);null!=e;)3===e.listenerType?null===d?null===e.next?c.delete(a):c.set(a,e.next):d.next=e.next:d=e,e=e.next;if(null!==b){var f={listener:b,listenerType:3,passive:!1,once:!1,next:null};null===d?c.set(a,f):d.next=f}},configurable:!0,enumerable:!0}}function z(a,b){Object.defineProperty(a,"on".concat(b),y(b))}function A(a){function b(){B.call(this)}b.prototype=Object.create(B.prototype,{constructor:{value:b,configurable:!0,writable:!0}});for(var c=0;c<a.length;++c)z(b.prototype,a[c]);return b}function B(){if(this instanceof B)return void H.set(this,new Map);if(1===arguments.length&&Array.isArray(arguments[0]))return A(arguments[0]);if(0<arguments.length){for(var a=Array(arguments.length),b=0;b<arguments.length;++b)a[b]=arguments[b];return A(a)}throw new TypeError("Cannot call a class as a function")}function C(){var a=Object.create(K.prototype);return B.call(a),L.set(a,!1),a}function D(a){!1!==L.get(a)||(L.set(a,!0),a.dispatchEvent({type:"abort"}))}function E(a){var c=N.get(a);if(null==c)throw new TypeError("Expected 'this' to be an 'AbortController' object, but got ".concat(null===a?"null":b(a)));return c}var F=new WeakMap,G=new WeakMap;m.prototype={get type(){return k(this).event.type},get target(){return k(this).eventTarget},get currentTarget(){return k(this).currentTarget},composedPath:function(){var a=k(this).currentTarget;return null==a?[]:[a]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return k(this).eventPhase},stopPropagation:function(){var a=k(this);a.stopped=!0,"function"==typeof a.event.stopPropagation&&a.event.stopPropagation()},stopImmediatePropagation:function(){var a=k(this);a.stopped=!0,a.immediateStopped=!0,"function"==typeof a.event.stopImmediatePropagation&&a.event.stopImmediatePropagation()},get bubbles(){return!!k(this).event.bubbles},get cancelable(){return!!k(this).event.cancelable},preventDefault:function(){l(k(this))},get defaultPrevented(){return k(this).canceled},get composed(){return!!k(this).event.composed},get timeStamp(){return k(this).timeStamp},get srcElement(){return k(this).eventTarget},get cancelBubble(){return k(this).stopped},set cancelBubble(a){if(a){var b=k(this);b.stopped=!0,"boolean"==typeof b.event.cancelBubble&&(b.event.cancelBubble=!0)}},get returnValue(){return!k(this).canceled},set returnValue(a){a||l(k(this))},initEvent:function(){}},Object.defineProperty(m.prototype,"constructor",{value:m,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.Event&&(Object.setPrototypeOf(m.prototype,window.Event.prototype),G.set(window.Event.prototype,m));var H=new WeakMap,I=1,J=2;B.prototype={addEventListener:function(a,b,c){if(null!=b){if("function"!=typeof b&&!w(b))throw new TypeError("'listener' should be a function or an object.");var d=x(this),e=w(c),f=e?!!c.capture:!!c,g=f?I:J,h={listener:b,listenerType:g,passive:e&&!!c.passive,once:e&&!!c.once,next:null},i=d.get(a);if(void 0===i)return void d.set(a,h);for(var j=null;null!=i;){if(i.listener===b&&i.listenerType===g)return;j=i,i=i.next}j.next=h}},removeEventListener:function(a,b,c){if(null!=b)for(var d=x(this),e=w(c)?!!c.capture:!!c,f=e?I:J,g=null,h=d.get(a);null!=h;){if(h.listener===b&&h.listenerType===f)return void(null===g?null===h.next?d.delete(a):d.set(a,h.next):g.next=h.next);g=h,h=h.next}},dispatchEvent:function(a){if(null==a||"string"!=typeof a.type)throw new TypeError("\"event.type\" should be a string.");var b=x(this),c=a.type,d=b.get(c);if(null==d)return!0;for(var e=r(this,a),f=null;null!=d;){if(d.once?null===f?null===d.next?b.delete(c):b.set(c,d.next):f.next=d.next:f=d,v(e,d.passive?d.listener:null),"function"==typeof d.listener)try{d.listener.call(this,e)}catch(a){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(a)}else d.listenerType!==3&&"function"==typeof d.listener.handleEvent&&d.listener.handleEvent(e);if(s(e))break;d=d.next}return v(e,null),t(e,0),u(e,null),!e.defaultPrevented}},Object.defineProperty(B.prototype,"constructor",{value:B,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.EventTarget&&Object.setPrototypeOf(B.prototype,window.EventTarget.prototype);var K=function(a){function d(){var a;throw c(this,d),a=j(this,g(d).call(this)),new TypeError("AbortSignal cannot be constructed directly")}return f(d,a),e(d,[{key:"aborted",get:function(){var a=L.get(this);if("boolean"!=typeof a)throw new TypeError("Expected 'this' to be an 'AbortSignal' object, but got ".concat(null===this?"null":b(this)));return a}}]),d}(B);z(K.prototype,"abort");var L=new WeakMap;Object.defineProperties(K.prototype,{aborted:{enumerable:!0}}),"function"==typeof Symbol&&"symbol"===b(Symbol.toStringTag)&&Object.defineProperty(K.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});var M=function(){function a(){c(this,a),N.set(this,C())}return e(a,[{key:"abort",value:function(){D(E(this))}},{key:"signal",get:function(){return E(this)}}]),a}(),N=new WeakMap;if(Object.defineProperties(M.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),"function"==typeof Symbol&&"symbol"===b(Symbol.toStringTag)&&Object.defineProperty(M.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"}),a.AbortController=M,a.AbortSignal=K,a.default=M,Object.defineProperty(a,"__esModule",{value:!0}),"undefined"==typeof module&&"undefined"==typeof define){var O=Function("return this")();"undefined"==typeof O.AbortController&&(O.AbortController=M,O.AbortSignal=K)}});
//# sourceMappingURL=abort-controller.umd.js.map
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@vendia/serverless-express/index.js | aws/lti-middleware/node_modules/@vendia/serverless-express/index.js | 'use strict'
module.exports = require('./src/index')
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@vendia/serverless-express/middleware.js | aws/lti-middleware/node_modules/@vendia/serverless-express/middleware.js | 'use strict'
module.exports = require('./src/middleware')
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@vendia/serverless-express/src/index.js | aws/lti-middleware/node_modules/@vendia/serverless-express/src/index.js | const codeGenieServerlessExpress = require('@codegenie/serverless-express')
exports.createServer = codeGenieServerlessExpress.createServer
exports.proxy = codeGenieServerlessExpress.proxy
/* istanbul ignore else */
if (process.env.NODE_ENV === 'test') {
exports.getPathWithQueryStringParams = codeGenieServerlessExpress.getPathWithQueryStringParams
exports.mapApiGatewayEventToHttpRequest = codeGenieServerlessExpress.mapApiGatewayEventToHttpRequest
exports.forwardResponseToApiGateway = codeGenieServerlessExpress.forwardResponseToApiGateway
exports.forwardConnectionErrorResponseToApiGateway = codeGenieServerlessExpress.forwardConnectionErrorResponseToApiGateway
exports.forwardLibraryErrorResponseToApiGateway = codeGenieServerlessExpress.forwardLibraryErrorResponseToApiGateway
exports.forwardRequestToNodeServer = codeGenieServerlessExpress.forwardRequestToNodeServer
exports.startServer = codeGenieServerlessExpress.startServer
exports.getSocketPath = codeGenieServerlessExpress.getSocketPath
exports.makeResolver = codeGenieServerlessExpress.makeResolver
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@vendia/serverless-express/src/middleware.js | aws/lti-middleware/node_modules/@vendia/serverless-express/src/middleware.js | const codeGenieServerlessExpress = require('@codegenie/serverless-express/middleware')
module.exports.eventContext = codeGenieServerlessExpress.eventContext
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/utf16.js | aws/lti-middleware/node_modules/iconv-lite/encodings/utf16.js | "use strict";
var Buffer = require("safer-buffer").Buffer;
// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js
// == UTF16-BE codec. ==========================================================
exports.utf16be = Utf16BECodec;
function Utf16BECodec() {
}
Utf16BECodec.prototype.encoder = Utf16BEEncoder;
Utf16BECodec.prototype.decoder = Utf16BEDecoder;
Utf16BECodec.prototype.bomAware = true;
// -- Encoding
function Utf16BEEncoder() {
}
Utf16BEEncoder.prototype.write = function(str) {
var buf = Buffer.from(str, 'ucs2');
for (var i = 0; i < buf.length; i += 2) {
var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
}
return buf;
}
Utf16BEEncoder.prototype.end = function() {
}
// -- Decoding
function Utf16BEDecoder() {
this.overflowByte = -1;
}
Utf16BEDecoder.prototype.write = function(buf) {
if (buf.length == 0)
return '';
var buf2 = Buffer.alloc(buf.length + 1),
i = 0, j = 0;
if (this.overflowByte !== -1) {
buf2[0] = buf[0];
buf2[1] = this.overflowByte;
i = 1; j = 2;
}
for (; i < buf.length-1; i += 2, j+= 2) {
buf2[j] = buf[i+1];
buf2[j+1] = buf[i];
}
this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;
return buf2.slice(0, j).toString('ucs2');
}
Utf16BEDecoder.prototype.end = function() {
}
// == UTF-16 codec =============================================================
// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
// Defaults to UTF-16LE, as it's prevalent and default in Node.
// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});
// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).
exports.utf16 = Utf16Codec;
function Utf16Codec(codecOptions, iconv) {
this.iconv = iconv;
}
Utf16Codec.prototype.encoder = Utf16Encoder;
Utf16Codec.prototype.decoder = Utf16Decoder;
// -- Encoding (pass-through)
function Utf16Encoder(options, codec) {
options = options || {};
if (options.addBOM === undefined)
options.addBOM = true;
this.encoder = codec.iconv.getEncoder('utf-16le', options);
}
Utf16Encoder.prototype.write = function(str) {
return this.encoder.write(str);
}
Utf16Encoder.prototype.end = function() {
return this.encoder.end();
}
// -- Decoding
function Utf16Decoder(options, codec) {
this.decoder = null;
this.initialBytes = [];
this.initialBytesLen = 0;
this.options = options || {};
this.iconv = codec.iconv;
}
Utf16Decoder.prototype.write = function(buf) {
if (!this.decoder) {
// Codec is not chosen yet. Accumulate initial bytes.
this.initialBytes.push(buf);
this.initialBytesLen += buf.length;
if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below)
return '';
// We have enough bytes -> detect endianness.
var buf = Buffer.concat(this.initialBytes),
encoding = detectEncoding(buf, this.options.defaultEncoding);
this.decoder = this.iconv.getDecoder(encoding, this.options);
this.initialBytes.length = this.initialBytesLen = 0;
}
return this.decoder.write(buf);
}
Utf16Decoder.prototype.end = function() {
if (!this.decoder) {
var buf = Buffer.concat(this.initialBytes),
encoding = detectEncoding(buf, this.options.defaultEncoding);
this.decoder = this.iconv.getDecoder(encoding, this.options);
var res = this.decoder.write(buf),
trail = this.decoder.end();
return trail ? (res + trail) : res;
}
return this.decoder.end();
}
function detectEncoding(buf, defaultEncoding) {
var enc = defaultEncoding || 'utf-16le';
if (buf.length >= 2) {
// Check BOM.
if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM
enc = 'utf-16be';
else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM
enc = 'utf-16le';
else {
// No BOM found. Try to deduce encoding from initial content.
// Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
// So, we count ASCII as if it was LE or BE, and decide from that.
var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions
_len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even.
for (var i = 0; i < _len; i += 2) {
if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++;
if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++;
}
if (asciiCharsBE > asciiCharsLE)
enc = 'utf-16be';
else if (asciiCharsBE < asciiCharsLE)
enc = 'utf-16le';
}
}
return enc;
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/index.js | aws/lti-middleware/node_modules/iconv-lite/encodings/index.js | "use strict";
// Update this array if you add/rename/remove files in this directory.
// We support Browserify by skipping automatic module discovery and requiring modules directly.
var modules = [
require("./internal"),
require("./utf16"),
require("./utf7"),
require("./sbcs-codec"),
require("./sbcs-data"),
require("./sbcs-data-generated"),
require("./dbcs-codec"),
require("./dbcs-data"),
];
// Put all encoding/alias/codec definitions to single object and export it.
for (var i = 0; i < modules.length; i++) {
var module = modules[i];
for (var enc in module)
if (Object.prototype.hasOwnProperty.call(module, enc))
exports[enc] = module[enc];
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/dbcs-codec.js | aws/lti-middleware/node_modules/iconv-lite/encodings/dbcs-codec.js | "use strict";
var Buffer = require("safer-buffer").Buffer;
// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
// To save memory and loading time, we read table files only when requested.
exports._dbcs = DBCSCodec;
var UNASSIGNED = -1,
GB18030_CODE = -2,
SEQ_START = -10,
NODE_START = -1000,
UNASSIGNED_NODE = new Array(0x100),
DEF_CHAR = -1;
for (var i = 0; i < 0x100; i++)
UNASSIGNED_NODE[i] = UNASSIGNED;
// Class DBCSCodec reads and initializes mapping tables.
function DBCSCodec(codecOptions, iconv) {
this.encodingName = codecOptions.encodingName;
if (!codecOptions)
throw new Error("DBCS codec is called without the data.")
if (!codecOptions.table)
throw new Error("Encoding '" + this.encodingName + "' has no data.");
// Load tables.
var mappingTable = codecOptions.table();
// Decode tables: MBCS -> Unicode.
// decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
// Trie root is decodeTables[0].
// Values: >= 0 -> unicode character code. can be > 0xFFFF
// == UNASSIGNED -> unknown/unassigned sequence.
// == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
// <= NODE_START -> index of the next node in our trie to process next byte.
// <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.
this.decodeTables = [];
this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
// Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.
this.decodeTableSeq = [];
// Actual mapping tables consist of chunks. Use them to fill up decode tables.
for (var i = 0; i < mappingTable.length; i++)
this._addDecodeChunk(mappingTable[i]);
this.defaultCharUnicode = iconv.defaultCharUnicode;
// Encode tables: Unicode -> DBCS.
// `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
// Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
// Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
// == UNASSIGNED -> no conversion found. Output a default char.
// <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.
this.encodeTable = [];
// `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
// objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
// means end of sequence (needed when one sequence is a strict subsequence of another).
// Objects are kept separately from encodeTable to increase performance.
this.encodeTableSeq = [];
// Some chars can be decoded, but need not be encoded.
var skipEncodeChars = {};
if (codecOptions.encodeSkipVals)
for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
var val = codecOptions.encodeSkipVals[i];
if (typeof val === 'number')
skipEncodeChars[val] = true;
else
for (var j = val.from; j <= val.to; j++)
skipEncodeChars[j] = true;
}
// Use decode trie to recursively fill out encode tables.
this._fillEncodeTable(0, 0, skipEncodeChars);
// Add more encoding pairs when needed.
if (codecOptions.encodeAdd) {
for (var uChar in codecOptions.encodeAdd)
if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
}
this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
// Load & create GB18030 tables when needed.
if (typeof codecOptions.gb18030 === 'function') {
this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
// Add GB18030 decode tables.
var thirdByteNodeIdx = this.decodeTables.length;
var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);
var fourthByteNodeIdx = this.decodeTables.length;
var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);
for (var i = 0x81; i <= 0xFE; i++) {
var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];
var secondByteNode = this.decodeTables[secondByteNodeIdx];
for (var j = 0x30; j <= 0x39; j++)
secondByteNode[j] = NODE_START - thirdByteNodeIdx;
}
for (var i = 0x81; i <= 0xFE; i++)
thirdByteNode[i] = NODE_START - fourthByteNodeIdx;
for (var i = 0x30; i <= 0x39; i++)
fourthByteNode[i] = GB18030_CODE
}
}
DBCSCodec.prototype.encoder = DBCSEncoder;
DBCSCodec.prototype.decoder = DBCSDecoder;
// Decoder helpers
DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
var bytes = [];
for (; addr > 0; addr >>= 8)
bytes.push(addr & 0xFF);
if (bytes.length == 0)
bytes.push(0);
var node = this.decodeTables[0];
for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
var val = node[bytes[i]];
if (val == UNASSIGNED) { // Create new node.
node[bytes[i]] = NODE_START - this.decodeTables.length;
this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
}
else if (val <= NODE_START) { // Existing node.
node = this.decodeTables[NODE_START - val];
}
else
throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
}
return node;
}
DBCSCodec.prototype._addDecodeChunk = function(chunk) {
// First element of chunk is the hex mbcs code where we start.
var curAddr = parseInt(chunk[0], 16);
// Choose the decoding node where we'll write our chars.
var writeTable = this._getDecodeTrieNode(curAddr);
curAddr = curAddr & 0xFF;
// Write all other elements of the chunk to the table.
for (var k = 1; k < chunk.length; k++) {
var part = chunk[k];
if (typeof part === "string") { // String, write as-is.
for (var l = 0; l < part.length;) {
var code = part.charCodeAt(l++);
if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
var codeTrail = part.charCodeAt(l++);
if (0xDC00 <= codeTrail && codeTrail < 0xE000)
writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
else
throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]);
}
else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
var len = 0xFFF - code + 2;
var seq = [];
for (var m = 0; m < len; m++)
seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
this.decodeTableSeq.push(seq);
}
else
writeTable[curAddr++] = code; // Basic char
}
}
else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
var charCode = writeTable[curAddr - 1] + 1;
for (var l = 0; l < part; l++)
writeTable[curAddr++] = charCode++;
}
else
throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]);
}
if (curAddr > 0xFF)
throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
}
// Encoder helpers
DBCSCodec.prototype._getEncodeBucket = function(uCode) {
var high = uCode >> 8; // This could be > 0xFF because of astral characters.
if (this.encodeTable[high] === undefined)
this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
return this.encodeTable[high];
}
DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
var bucket = this._getEncodeBucket(uCode);
var low = uCode & 0xFF;
if (bucket[low] <= SEQ_START)
this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
else if (bucket[low] == UNASSIGNED)
bucket[low] = dbcsCode;
}
DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
// Get the root of character tree according to first character of the sequence.
var uCode = seq[0];
var bucket = this._getEncodeBucket(uCode);
var low = uCode & 0xFF;
var node;
if (bucket[low] <= SEQ_START) {
// There's already a sequence with - use it.
node = this.encodeTableSeq[SEQ_START-bucket[low]];
}
else {
// There was no sequence object - allocate a new one.
node = {};
if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
bucket[low] = SEQ_START - this.encodeTableSeq.length;
this.encodeTableSeq.push(node);
}
// Traverse the character tree, allocating new nodes as needed.
for (var j = 1; j < seq.length-1; j++) {
var oldVal = node[uCode];
if (typeof oldVal === 'object')
node = oldVal;
else {
node = node[uCode] = {}
if (oldVal !== undefined)
node[DEF_CHAR] = oldVal
}
}
// Set the leaf to given dbcsCode.
uCode = seq[seq.length-1];
node[uCode] = dbcsCode;
}
DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
var node = this.decodeTables[nodeIdx];
for (var i = 0; i < 0x100; i++) {
var uCode = node[i];
var mbCode = prefix + i;
if (skipEncodeChars[mbCode])
continue;
if (uCode >= 0)
this._setEncodeChar(uCode, mbCode);
else if (uCode <= NODE_START)
this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);
else if (uCode <= SEQ_START)
this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
}
}
// == Encoder ==================================================================
function DBCSEncoder(options, codec) {
// Encoder state
this.leadSurrogate = -1;
this.seqObj = undefined;
// Static data
this.encodeTable = codec.encodeTable;
this.encodeTableSeq = codec.encodeTableSeq;
this.defaultCharSingleByte = codec.defCharSB;
this.gb18030 = codec.gb18030;
}
DBCSEncoder.prototype.write = function(str) {
var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
leadSurrogate = this.leadSurrogate,
seqObj = this.seqObj, nextChar = -1,
i = 0, j = 0;
while (true) {
// 0. Get next character.
if (nextChar === -1) {
if (i == str.length) break;
var uCode = str.charCodeAt(i++);
}
else {
var uCode = nextChar;
nextChar = -1;
}
// 1. Handle surrogates.
if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
if (uCode < 0xDC00) { // We've got lead surrogate.
if (leadSurrogate === -1) {
leadSurrogate = uCode;
continue;
} else {
leadSurrogate = uCode;
// Double lead surrogate found.
uCode = UNASSIGNED;
}
} else { // We've got trail surrogate.
if (leadSurrogate !== -1) {
uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
leadSurrogate = -1;
} else {
// Incomplete surrogate pair - only trail surrogate found.
uCode = UNASSIGNED;
}
}
}
else if (leadSurrogate !== -1) {
// Incomplete surrogate pair - only lead surrogate found.
nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
leadSurrogate = -1;
}
// 2. Convert uCode character.
var dbcsCode = UNASSIGNED;
if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
var resCode = seqObj[uCode];
if (typeof resCode === 'object') { // Sequence continues.
seqObj = resCode;
continue;
} else if (typeof resCode == 'number') { // Sequence finished. Write it.
dbcsCode = resCode;
} else if (resCode == undefined) { // Current character is not part of the sequence.
// Try default character for this sequence
resCode = seqObj[DEF_CHAR];
if (resCode !== undefined) {
dbcsCode = resCode; // Found. Write it.
nextChar = uCode; // Current character will be written too in the next iteration.
} else {
// TODO: What if we have no default? (resCode == undefined)
// Then, we should write first char of the sequence as-is and try the rest recursively.
// Didn't do it for now because no encoding has this situation yet.
// Currently, just skip the sequence and write current char.
}
}
seqObj = undefined;
}
else if (uCode >= 0) { // Regular character
var subtable = this.encodeTable[uCode >> 8];
if (subtable !== undefined)
dbcsCode = subtable[uCode & 0xFF];
if (dbcsCode <= SEQ_START) { // Sequence start
seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
continue;
}
if (dbcsCode == UNASSIGNED && this.gb18030) {
// Use GB18030 algorithm to find character(s) to write.
var idx = findIdx(this.gb18030.uChars, uCode);
if (idx != -1) {
var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
newBuf[j++] = 0x30 + dbcsCode;
continue;
}
}
}
// 3. Write dbcsCode character.
if (dbcsCode === UNASSIGNED)
dbcsCode = this.defaultCharSingleByte;
if (dbcsCode < 0x100) {
newBuf[j++] = dbcsCode;
}
else if (dbcsCode < 0x10000) {
newBuf[j++] = dbcsCode >> 8; // high byte
newBuf[j++] = dbcsCode & 0xFF; // low byte
}
else {
newBuf[j++] = dbcsCode >> 16;
newBuf[j++] = (dbcsCode >> 8) & 0xFF;
newBuf[j++] = dbcsCode & 0xFF;
}
}
this.seqObj = seqObj;
this.leadSurrogate = leadSurrogate;
return newBuf.slice(0, j);
}
DBCSEncoder.prototype.end = function() {
if (this.leadSurrogate === -1 && this.seqObj === undefined)
return; // All clean. Most often case.
var newBuf = Buffer.alloc(10), j = 0;
if (this.seqObj) { // We're in the sequence.
var dbcsCode = this.seqObj[DEF_CHAR];
if (dbcsCode !== undefined) { // Write beginning of the sequence.
if (dbcsCode < 0x100) {
newBuf[j++] = dbcsCode;
}
else {
newBuf[j++] = dbcsCode >> 8; // high byte
newBuf[j++] = dbcsCode & 0xFF; // low byte
}
} else {
// See todo above.
}
this.seqObj = undefined;
}
if (this.leadSurrogate !== -1) {
// Incomplete surrogate pair - only lead surrogate found.
newBuf[j++] = this.defaultCharSingleByte;
this.leadSurrogate = -1;
}
return newBuf.slice(0, j);
}
// Export for testing
DBCSEncoder.prototype.findIdx = findIdx;
// == Decoder ==================================================================
function DBCSDecoder(options, codec) {
// Decoder state
this.nodeIdx = 0;
this.prevBuf = Buffer.alloc(0);
// Static data
this.decodeTables = codec.decodeTables;
this.decodeTableSeq = codec.decodeTableSeq;
this.defaultCharUnicode = codec.defaultCharUnicode;
this.gb18030 = codec.gb18030;
}
DBCSDecoder.prototype.write = function(buf) {
var newBuf = Buffer.alloc(buf.length*2),
nodeIdx = this.nodeIdx,
prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length,
seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence.
uCode;
if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later.
prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]);
for (var i = 0, j = 0; i < buf.length; i++) {
var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];
// Lookup in current trie node.
var uCode = this.decodeTables[nodeIdx][curByte];
if (uCode >= 0) {
// Normal character, just use it.
}
else if (uCode === UNASSIGNED) { // Unknown char.
// TODO: Callback with seq.
//var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle).
uCode = this.defaultCharUnicode.charCodeAt(0);
}
else if (uCode === GB18030_CODE) {
var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30);
var idx = findIdx(this.gb18030.gbChars, ptr);
uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
}
else if (uCode <= NODE_START) { // Go to next trie node.
nodeIdx = NODE_START - uCode;
continue;
}
else if (uCode <= SEQ_START) { // Output a sequence of chars.
var seq = this.decodeTableSeq[SEQ_START - uCode];
for (var k = 0; k < seq.length - 1; k++) {
uCode = seq[k];
newBuf[j++] = uCode & 0xFF;
newBuf[j++] = uCode >> 8;
}
uCode = seq[seq.length-1];
}
else
throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
// Write the character to buffer, handling higher planes using surrogate pair.
if (uCode > 0xFFFF) {
uCode -= 0x10000;
var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);
newBuf[j++] = uCodeLead & 0xFF;
newBuf[j++] = uCodeLead >> 8;
uCode = 0xDC00 + uCode % 0x400;
}
newBuf[j++] = uCode & 0xFF;
newBuf[j++] = uCode >> 8;
// Reset trie node.
nodeIdx = 0; seqStart = i+1;
}
this.nodeIdx = nodeIdx;
this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
return newBuf.slice(0, j).toString('ucs2');
}
DBCSDecoder.prototype.end = function() {
var ret = '';
// Try to parse all remaining chars.
while (this.prevBuf.length > 0) {
// Skip 1 character in the buffer.
ret += this.defaultCharUnicode;
var buf = this.prevBuf.slice(1);
// Parse remaining as usual.
this.prevBuf = Buffer.alloc(0);
this.nodeIdx = 0;
if (buf.length > 0)
ret += this.write(buf);
}
this.nodeIdx = 0;
return ret;
}
// Binary search for GB18030. Returns largest i such that table[i] <= val.
function findIdx(table, val) {
if (table[0] > val)
return -1;
var l = 0, r = table.length;
while (l < r-1) { // always table[l] <= val < table[r]
var mid = l + Math.floor((r-l+1)/2);
if (table[mid] <= val)
l = mid;
else
r = mid;
}
return l;
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/sbcs-data.js | aws/lti-middleware/node_modules/iconv-lite/encodings/sbcs-data.js | "use strict";
// Manually added data to be used by sbcs codec in addition to generated one.
module.exports = {
// Not supported by iconv, not sure why.
"10029": "maccenteuro",
"maccenteuro": {
"type": "_sbcs",
"chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
},
"808": "cp808",
"ibm808": "cp808",
"cp808": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
},
"mik": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
// Aliases of generated encodings.
"ascii8bit": "ascii",
"usascii": "ascii",
"ansix34": "ascii",
"ansix341968": "ascii",
"ansix341986": "ascii",
"csascii": "ascii",
"cp367": "ascii",
"ibm367": "ascii",
"isoir6": "ascii",
"iso646us": "ascii",
"iso646irv": "ascii",
"us": "ascii",
"latin1": "iso88591",
"latin2": "iso88592",
"latin3": "iso88593",
"latin4": "iso88594",
"latin5": "iso88599",
"latin6": "iso885910",
"latin7": "iso885913",
"latin8": "iso885914",
"latin9": "iso885915",
"latin10": "iso885916",
"csisolatin1": "iso88591",
"csisolatin2": "iso88592",
"csisolatin3": "iso88593",
"csisolatin4": "iso88594",
"csisolatincyrillic": "iso88595",
"csisolatinarabic": "iso88596",
"csisolatingreek" : "iso88597",
"csisolatinhebrew": "iso88598",
"csisolatin5": "iso88599",
"csisolatin6": "iso885910",
"l1": "iso88591",
"l2": "iso88592",
"l3": "iso88593",
"l4": "iso88594",
"l5": "iso88599",
"l6": "iso885910",
"l7": "iso885913",
"l8": "iso885914",
"l9": "iso885915",
"l10": "iso885916",
"isoir14": "iso646jp",
"isoir57": "iso646cn",
"isoir100": "iso88591",
"isoir101": "iso88592",
"isoir109": "iso88593",
"isoir110": "iso88594",
"isoir144": "iso88595",
"isoir127": "iso88596",
"isoir126": "iso88597",
"isoir138": "iso88598",
"isoir148": "iso88599",
"isoir157": "iso885910",
"isoir166": "tis620",
"isoir179": "iso885913",
"isoir199": "iso885914",
"isoir203": "iso885915",
"isoir226": "iso885916",
"cp819": "iso88591",
"ibm819": "iso88591",
"cyrillic": "iso88595",
"arabic": "iso88596",
"arabic8": "iso88596",
"ecma114": "iso88596",
"asmo708": "iso88596",
"greek" : "iso88597",
"greek8" : "iso88597",
"ecma118" : "iso88597",
"elot928" : "iso88597",
"hebrew": "iso88598",
"hebrew8": "iso88598",
"turkish": "iso88599",
"turkish8": "iso88599",
"thai": "iso885911",
"thai8": "iso885911",
"celtic": "iso885914",
"celtic8": "iso885914",
"isoceltic": "iso885914",
"tis6200": "tis620",
"tis62025291": "tis620",
"tis62025330": "tis620",
"10000": "macroman",
"10006": "macgreek",
"10007": "maccyrillic",
"10079": "maciceland",
"10081": "macturkish",
"cspc8codepage437": "cp437",
"cspc775baltic": "cp775",
"cspc850multilingual": "cp850",
"cspcp852": "cp852",
"cspc862latinhebrew": "cp862",
"cpgr": "cp869",
"msee": "cp1250",
"mscyrl": "cp1251",
"msansi": "cp1252",
"msgreek": "cp1253",
"msturk": "cp1254",
"mshebr": "cp1255",
"msarab": "cp1256",
"winbaltrim": "cp1257",
"cp20866": "koi8r",
"20866": "koi8r",
"ibm878": "koi8r",
"cskoi8r": "koi8r",
"cp21866": "koi8u",
"21866": "koi8u",
"ibm1168": "koi8u",
"strk10482002": "rk1048",
"tcvn5712": "tcvn",
"tcvn57121": "tcvn",
"gb198880": "iso646cn",
"cn": "iso646cn",
"csiso14jisc6220ro": "iso646jp",
"jisc62201969ro": "iso646jp",
"jp": "iso646jp",
"cshproman8": "hproman8",
"r8": "hproman8",
"roman8": "hproman8",
"xroman8": "hproman8",
"ibm1051": "hproman8",
"mac": "macintosh",
"csmacintosh": "macintosh",
};
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/sbcs-codec.js | aws/lti-middleware/node_modules/iconv-lite/encodings/sbcs-codec.js | "use strict";
var Buffer = require("safer-buffer").Buffer;
// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
// correspond to encoded bytes (if 128 - then lower half is ASCII).
exports._sbcs = SBCSCodec;
function SBCSCodec(codecOptions, iconv) {
if (!codecOptions)
throw new Error("SBCS codec is called without the data.")
// Prepare char buffer for decoding.
if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
if (codecOptions.chars.length === 128) {
var asciiString = "";
for (var i = 0; i < 128; i++)
asciiString += String.fromCharCode(i);
codecOptions.chars = asciiString + codecOptions.chars;
}
this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
// Encoding buffer.
var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
for (var i = 0; i < codecOptions.chars.length; i++)
encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
this.encodeBuf = encodeBuf;
}
SBCSCodec.prototype.encoder = SBCSEncoder;
SBCSCodec.prototype.decoder = SBCSDecoder;
function SBCSEncoder(options, codec) {
this.encodeBuf = codec.encodeBuf;
}
SBCSEncoder.prototype.write = function(str) {
var buf = Buffer.alloc(str.length);
for (var i = 0; i < str.length; i++)
buf[i] = this.encodeBuf[str.charCodeAt(i)];
return buf;
}
SBCSEncoder.prototype.end = function() {
}
function SBCSDecoder(options, codec) {
this.decodeBuf = codec.decodeBuf;
}
SBCSDecoder.prototype.write = function(buf) {
// Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
var decodeBuf = this.decodeBuf;
var newBuf = Buffer.alloc(buf.length*2);
var idx1 = 0, idx2 = 0;
for (var i = 0; i < buf.length; i++) {
idx1 = buf[i]*2; idx2 = i*2;
newBuf[idx2] = decodeBuf[idx1];
newBuf[idx2+1] = decodeBuf[idx1+1];
}
return newBuf.toString('ucs2');
}
SBCSDecoder.prototype.end = function() {
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/sbcs-data-generated.js | aws/lti-middleware/node_modules/iconv-lite/encodings/sbcs-data-generated.js | "use strict";
// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
module.exports = {
"437": "cp437",
"737": "cp737",
"775": "cp775",
"850": "cp850",
"852": "cp852",
"855": "cp855",
"856": "cp856",
"857": "cp857",
"858": "cp858",
"860": "cp860",
"861": "cp861",
"862": "cp862",
"863": "cp863",
"864": "cp864",
"865": "cp865",
"866": "cp866",
"869": "cp869",
"874": "windows874",
"922": "cp922",
"1046": "cp1046",
"1124": "cp1124",
"1125": "cp1125",
"1129": "cp1129",
"1133": "cp1133",
"1161": "cp1161",
"1162": "cp1162",
"1163": "cp1163",
"1250": "windows1250",
"1251": "windows1251",
"1252": "windows1252",
"1253": "windows1253",
"1254": "windows1254",
"1255": "windows1255",
"1256": "windows1256",
"1257": "windows1257",
"1258": "windows1258",
"28591": "iso88591",
"28592": "iso88592",
"28593": "iso88593",
"28594": "iso88594",
"28595": "iso88595",
"28596": "iso88596",
"28597": "iso88597",
"28598": "iso88598",
"28599": "iso88599",
"28600": "iso885910",
"28601": "iso885911",
"28603": "iso885913",
"28604": "iso885914",
"28605": "iso885915",
"28606": "iso885916",
"windows874": {
"type": "_sbcs",
"chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
},
"win874": "windows874",
"cp874": "windows874",
"windows1250": {
"type": "_sbcs",
"chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
},
"win1250": "windows1250",
"cp1250": "windows1250",
"windows1251": {
"type": "_sbcs",
"chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
},
"win1251": "windows1251",
"cp1251": "windows1251",
"windows1252": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"win1252": "windows1252",
"cp1252": "windows1252",
"windows1253": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
},
"win1253": "windows1253",
"cp1253": "windows1253",
"windows1254": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
},
"win1254": "windows1254",
"cp1254": "windows1254",
"windows1255": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת���"
},
"win1255": "windows1255",
"cp1255": "windows1255",
"windows1256": {
"type": "_sbcs",
"chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œں ،¢£¤¥¦§¨©ھ«¬®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûüے"
},
"win1256": "windows1256",
"cp1256": "windows1256",
"windows1257": {
"type": "_sbcs",
"chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
},
"win1257": "windows1257",
"cp1257": "windows1257",
"windows1258": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
},
"win1258": "windows1258",
"cp1258": "windows1258",
"iso88591": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"cp28591": "iso88591",
"iso88592": {
"type": "_sbcs",
"chars": "
Ą˘Ł¤ĽŚ§¨ŠŞŤŹŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
},
"cp28592": "iso88592",
"iso88593": {
"type": "_sbcs",
"chars": "
Ħ˘£¤�Ĥ§¨İŞĞĴ�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
},
"cp28593": "iso88593",
"iso88594": {
"type": "_sbcs",
"chars": "
ĄĸŖ¤Ĩϧ¨ŠĒĢŦޝ°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
},
"cp28594": "iso88594",
"iso88595": {
"type": "_sbcs",
"chars": "
ЁЂЃЄЅІЇЈЉЊЋЌЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
},
"cp28595": "iso88595",
"iso88596": {
"type": "_sbcs",
"chars": "
���¤�������،�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
},
"cp28596": "iso88596",
"iso88597": {
"type": "_sbcs",
"chars": "
‘’£€₯¦§¨©ͺ«¬�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
},
"cp28597": "iso88597",
"iso88598": {
"type": "_sbcs",
"chars": "
�¢£¤¥¦§¨©×«¬®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת���"
},
"cp28598": "iso88598",
"iso88599": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
},
"cp28599": "iso88599",
"iso885910": {
"type": "_sbcs",
"chars": "
ĄĒĢĪĨͧĻĐŠŦŽŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
},
"cp28600": "iso885910",
"iso885911": {
"type": "_sbcs",
"chars": "
กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
},
"cp28601": "iso885911",
"iso885913": {
"type": "_sbcs",
"chars": "
”¢£¤„¦§Ø©Ŗ«¬®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
},
"cp28603": "iso885913",
"iso885914": {
"type": "_sbcs",
"chars": "
Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
},
"cp28604": "iso885914",
"iso885915": {
"type": "_sbcs",
"chars": "
¡¢£€¥Š§š©ª«¬®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"cp28605": "iso885915",
"iso885916": {
"type": "_sbcs",
"chars": "
ĄąŁ€„Чš©Ș«ŹźŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
},
"cp28606": "iso885916",
"cp437": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm437": "cp437",
"csibm437": "cp437",
"cp737": {
"type": "_sbcs",
"chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
},
"ibm737": "cp737",
"csibm737": "cp737",
"cp775": {
"type": "_sbcs",
"chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’±“¾¶§÷„°∙·¹³²■ "
},
"ibm775": "cp775",
"csibm775": "cp775",
"cp850": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´±‗¾¶§÷¸°¨·¹³²■ "
},
"ibm850": "cp850",
"csibm850": "cp850",
"cp852": {
"type": "_sbcs",
"chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´˝˛ˇ˘§÷¸°¨˙űŘř■ "
},
"ibm852": "cp852",
"csibm852": "cp852",
"cp855": {
"type": "_sbcs",
"chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№ыЫзЗшШэЭщЩчЧ§■ "
},
"ibm855": "cp855",
"csibm855": "cp855",
"cp856": {
"type": "_sbcs",
"chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´±‗¾¶§÷¸°¨·¹³²■ "
},
"ibm856": "cp856",
"csibm856": "cp856",
"cp857": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´±�¾¶§÷¸°¨·¹³²■ "
},
"ibm857": "cp857",
"csibm857": "cp857",
"cp858": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´±‗¾¶§÷¸°¨·¹³²■ "
},
"ibm858": "cp858",
"csibm858": "cp858",
"cp860": {
"type": "_sbcs",
"chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm860": "cp860",
"csibm860": "cp860",
"cp861": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm861": "cp861",
"csibm861": "cp861",
"cp862": {
"type": "_sbcs",
"chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm862": "cp862",
"csibm862": "cp862",
"cp863": {
"type": "_sbcs",
"chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm863": "cp863",
"csibm863": "cp863",
"cp864": {
"type": "_sbcs",
"chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
},
"ibm864": "cp864",
"csibm864": "cp864",
"cp865": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm865": "cp865",
"csibm865": "cp865",
"cp866": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
},
"ibm866": "cp866",
"csibm866": "cp866",
"cp869": {
"type": "_sbcs",
"chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄±υφχ§ψ΅°¨ωϋΰώ■ "
},
"ibm869": "cp869",
"csibm869": "cp869",
"cp922": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§¨©ª«¬®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
},
"ibm922": "cp922",
"csibm922": "cp922",
"cp1046": {
"type": "_sbcs",
"chars": "ﺈ×÷ﹱ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
},
"ibm1046": "cp1046",
"csibm1046": "cp1046",
"cp1124": {
"type": "_sbcs",
"chars": "
ЁЂҐЄЅІЇЈЉЊЋЌЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
},
"ibm1124": "cp1124",
"csibm1124": "cp1124",
"cp1125": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
},
"ibm1125": "cp1125",
"csibm1125": "cp1125",
"cp1129": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§œ©ª«¬®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
},
"ibm1129": "cp1129",
"csibm1129": "cp1129",
"cp1133": {
"type": "_sbcs",
"chars": "
ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
},
"ibm1133": "cp1133",
"csibm1133": "cp1133",
"cp1161": {
"type": "_sbcs",
"chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
},
"ibm1161": "cp1161",
"csibm1161": "cp1161",
"cp1162": {
"type": "_sbcs",
"chars": "€…‘’“”•–— กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
},
"ibm1162": "cp1162",
"csibm1162": "cp1162",
"cp1163": {
"type": "_sbcs",
"chars": "
¡¢£€¥¦§œ©ª«¬®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
},
"ibm1163": "cp1163",
"csibm1163": "cp1163",
"maccroatian": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
},
"maccyrillic": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
},
"macgreek": {
"type": "_sbcs",
"chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
},
"maciceland": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"macroman": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"macromania": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"macthai": {
"type": "_sbcs",
"chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
},
"macturkish": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
},
"macukraine": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
},
"koi8r": {
"type": "_sbcs",
"chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"koi8u": {
"type": "_sbcs",
"chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"koi8ru": {
"type": "_sbcs",
"chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"koi8t": {
"type": "_sbcs",
"chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"armscii8": {
"type": "_sbcs",
"chars": "
�և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
},
"rk1048": {
"type": "_sbcs",
"chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
},
"tcvn": {
"type": "_sbcs",
"chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
},
"georgianacademy": {
"type": "_sbcs",
"chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"georgianps": {
"type": "_sbcs",
"chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"pt154": {
"type": "_sbcs",
"chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
},
"viscii": {
"type": "_sbcs",
"chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
},
"iso646cn": {
"type": "_sbcs",
"chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
},
"iso646jp": {
"type": "_sbcs",
"chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
},
"hproman8": {
"type": "_sbcs",
"chars": "
ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
},
"macintosh": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"ascii": {
"type": "_sbcs",
"chars": "��������������������������������������������������������������������������������������������������������������������������������"
},
"tis620": {
"type": "_sbcs",
"chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/internal.js | aws/lti-middleware/node_modules/iconv-lite/encodings/internal.js | "use strict";
var Buffer = require("safer-buffer").Buffer;
// Export Node.js internal encodings.
module.exports = {
// Encodings
utf8: { type: "_internal", bomAware: true},
cesu8: { type: "_internal", bomAware: true},
unicode11utf8: "utf8",
ucs2: { type: "_internal", bomAware: true},
utf16le: "ucs2",
binary: { type: "_internal" },
base64: { type: "_internal" },
hex: { type: "_internal" },
// Codec.
_internal: InternalCodec,
};
//------------------------------------------------------------------------------
function InternalCodec(codecOptions, iconv) {
this.enc = codecOptions.encodingName;
this.bomAware = codecOptions.bomAware;
if (this.enc === "base64")
this.encoder = InternalEncoderBase64;
else if (this.enc === "cesu8") {
this.enc = "utf8"; // Use utf8 for decoding.
this.encoder = InternalEncoderCesu8;
// Add decoder for versions of Node not supporting CESU-8
if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
this.decoder = InternalDecoderCesu8;
this.defaultCharUnicode = iconv.defaultCharUnicode;
}
}
}
InternalCodec.prototype.encoder = InternalEncoder;
InternalCodec.prototype.decoder = InternalDecoder;
//------------------------------------------------------------------------------
// We use node.js internal decoder. Its signature is the same as ours.
var StringDecoder = require('string_decoder').StringDecoder;
if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
StringDecoder.prototype.end = function() {};
function InternalDecoder(options, codec) {
StringDecoder.call(this, codec.enc);
}
InternalDecoder.prototype = StringDecoder.prototype;
//------------------------------------------------------------------------------
// Encoder is mostly trivial
function InternalEncoder(options, codec) {
this.enc = codec.enc;
}
InternalEncoder.prototype.write = function(str) {
return Buffer.from(str, this.enc);
}
InternalEncoder.prototype.end = function() {
}
//------------------------------------------------------------------------------
// Except base64 encoder, which must keep its state.
function InternalEncoderBase64(options, codec) {
this.prevStr = '';
}
InternalEncoderBase64.prototype.write = function(str) {
str = this.prevStr + str;
var completeQuads = str.length - (str.length % 4);
this.prevStr = str.slice(completeQuads);
str = str.slice(0, completeQuads);
return Buffer.from(str, "base64");
}
InternalEncoderBase64.prototype.end = function() {
return Buffer.from(this.prevStr, "base64");
}
//------------------------------------------------------------------------------
// CESU-8 encoder is also special.
function InternalEncoderCesu8(options, codec) {
}
InternalEncoderCesu8.prototype.write = function(str) {
var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
// Naive implementation, but it works because CESU-8 is especially easy
// to convert from UTF-16 (which all JS strings are encoded in).
if (charCode < 0x80)
buf[bufIdx++] = charCode;
else if (charCode < 0x800) {
buf[bufIdx++] = 0xC0 + (charCode >>> 6);
buf[bufIdx++] = 0x80 + (charCode & 0x3f);
}
else { // charCode will always be < 0x10000 in javascript.
buf[bufIdx++] = 0xE0 + (charCode >>> 12);
buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
buf[bufIdx++] = 0x80 + (charCode & 0x3f);
}
}
return buf.slice(0, bufIdx);
}
InternalEncoderCesu8.prototype.end = function() {
}
//------------------------------------------------------------------------------
// CESU-8 decoder is not implemented in Node v4.0+
function InternalDecoderCesu8(options, codec) {
this.acc = 0;
this.contBytes = 0;
this.accBytes = 0;
this.defaultCharUnicode = codec.defaultCharUnicode;
}
InternalDecoderCesu8.prototype.write = function(buf) {
var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes,
res = '';
for (var i = 0; i < buf.length; i++) {
var curByte = buf[i];
if ((curByte & 0xC0) !== 0x80) { // Leading byte
if (contBytes > 0) { // Previous code is invalid
res += this.defaultCharUnicode;
contBytes = 0;
}
if (curByte < 0x80) { // Single-byte code
res += String.fromCharCode(curByte);
} else if (curByte < 0xE0) { // Two-byte code
acc = curByte & 0x1F;
contBytes = 1; accBytes = 1;
} else if (curByte < 0xF0) { // Three-byte code
acc = curByte & 0x0F;
contBytes = 2; accBytes = 1;
} else { // Four or more are not supported for CESU-8.
res += this.defaultCharUnicode;
}
} else { // Continuation byte
if (contBytes > 0) { // We're waiting for it.
acc = (acc << 6) | (curByte & 0x3f);
contBytes--; accBytes++;
if (contBytes === 0) {
// Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
if (accBytes === 2 && acc < 0x80 && acc > 0)
res += this.defaultCharUnicode;
else if (accBytes === 3 && acc < 0x800)
res += this.defaultCharUnicode;
else
// Actually add character.
res += String.fromCharCode(acc);
}
} else { // Unexpected continuation byte
res += this.defaultCharUnicode;
}
}
}
this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
return res;
}
InternalDecoderCesu8.prototype.end = function() {
var res = 0;
if (this.contBytes > 0)
res += this.defaultCharUnicode;
return res;
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/dbcs-data.js | aws/lti-middleware/node_modules/iconv-lite/encodings/dbcs-data.js | "use strict";
// Description of supported double byte encodings and aliases.
// Tables are not require()-d until they are needed to speed up library load.
// require()-s are direct to support Browserify.
module.exports = {
// == Japanese/ShiftJIS ====================================================
// All japanese encodings are based on JIS X set of standards:
// JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
// JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes.
// Has several variations in 1978, 1983, 1990 and 1997.
// JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
// JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
// 2 planes, first is superset of 0208, second - revised 0212.
// Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
// Byte encodings are:
// * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
// encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
// Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
// * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes.
// 0x00-0x7F - lower part of 0201
// 0x8E, 0xA1-0xDF - upper part of 0201
// (0xA1-0xFE)x2 - 0208 plane (94x94).
// 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
// * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
// Used as-is in ISO2022 family.
// * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII,
// 0201-1976 Roman, 0208-1978, 0208-1983.
// * ISO2022-JP-1: Adds esc seq for 0212-1990.
// * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
// * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
// * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
//
// After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
//
// Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
'shiftjis': {
type: '_dbcs',
table: function() { return require('./tables/shiftjis.json') },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
encodeSkipVals: [{from: 0xED40, to: 0xF940}],
},
'csshiftjis': 'shiftjis',
'mskanji': 'shiftjis',
'sjis': 'shiftjis',
'windows31j': 'shiftjis',
'ms31j': 'shiftjis',
'xsjis': 'shiftjis',
'windows932': 'shiftjis',
'ms932': 'shiftjis',
'932': 'shiftjis',
'cp932': 'shiftjis',
'eucjp': {
type: '_dbcs',
table: function() { return require('./tables/eucjp.json') },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
},
// TODO: KDDI extension to Shift_JIS
// TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
// TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
// == Chinese/GBK ==========================================================
// http://en.wikipedia.org/wiki/GBK
// We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
// Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
'gb2312': 'cp936',
'gb231280': 'cp936',
'gb23121980': 'cp936',
'csgb2312': 'cp936',
'csiso58gb231280': 'cp936',
'euccn': 'cp936',
// Microsoft's CP936 is a subset and approximation of GBK.
'windows936': 'cp936',
'ms936': 'cp936',
'936': 'cp936',
'cp936': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json') },
},
// GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
'gbk': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
},
'xgbk': 'gbk',
'isoir58': 'gbk',
// GB18030 is an algorithmic extension of GBK.
// Main source: https://www.w3.org/TR/encoding/#gbk-encoder
// http://icu-project.org/docs/papers/gb18030.html
// http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
// http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
'gb18030': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
gb18030: function() { return require('./tables/gb18030-ranges.json') },
encodeSkipVals: [0x80],
encodeAdd: {'€': 0xA2E3},
},
'chinese': 'gb18030',
// == Korean ===============================================================
// EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
'windows949': 'cp949',
'ms949': 'cp949',
'949': 'cp949',
'cp949': {
type: '_dbcs',
table: function() { return require('./tables/cp949.json') },
},
'cseuckr': 'cp949',
'csksc56011987': 'cp949',
'euckr': 'cp949',
'isoir149': 'cp949',
'korean': 'cp949',
'ksc56011987': 'cp949',
'ksc56011989': 'cp949',
'ksc5601': 'cp949',
// == Big5/Taiwan/Hong Kong ================================================
// There are lots of tables for Big5 and cp950. Please see the following links for history:
// http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
// Variations, in roughly number of defined chars:
// * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
// * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
// * Big5-2003 (Taiwan standard) almost superset of cp950.
// * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
// * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard.
// many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
// Plus, it has 4 combining sequences.
// Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
// because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
// Implementations are not consistent within browsers; sometimes labeled as just big5.
// MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
// Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
// In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
// Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
// http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
//
// Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
// Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
'windows950': 'cp950',
'ms950': 'cp950',
'950': 'cp950',
'cp950': {
type: '_dbcs',
table: function() { return require('./tables/cp950.json') },
},
// Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
'big5': 'big5hkscs',
'big5hkscs': {
type: '_dbcs',
table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) },
encodeSkipVals: [0xa2cc],
},
'cnbig5': 'big5hkscs',
'csbig5': 'big5hkscs',
'xxbig5': 'big5hkscs',
};
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/encodings/utf7.js | aws/lti-middleware/node_modules/iconv-lite/encodings/utf7.js | "use strict";
var Buffer = require("safer-buffer").Buffer;
// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3
exports.utf7 = Utf7Codec;
exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
function Utf7Codec(codecOptions, iconv) {
this.iconv = iconv;
};
Utf7Codec.prototype.encoder = Utf7Encoder;
Utf7Codec.prototype.decoder = Utf7Decoder;
Utf7Codec.prototype.bomAware = true;
// -- Encoding
var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
function Utf7Encoder(options, codec) {
this.iconv = codec.iconv;
}
Utf7Encoder.prototype.write = function(str) {
// Naive implementation.
// Non-direct chars are encoded as "+<base64>-"; single "+" char is encoded as "+-".
return Buffer.from(str.replace(nonDirectChars, function(chunk) {
return "+" + (chunk === '+' ? '' :
this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, ''))
+ "-";
}.bind(this)));
}
Utf7Encoder.prototype.end = function() {
}
// -- Decoding
function Utf7Decoder(options, codec) {
this.iconv = codec.iconv;
this.inBase64 = false;
this.base64Accum = '';
}
var base64Regex = /[A-Za-z0-9\/+]/;
var base64Chars = [];
for (var i = 0; i < 256; i++)
base64Chars[i] = base64Regex.test(String.fromCharCode(i));
var plusChar = '+'.charCodeAt(0),
minusChar = '-'.charCodeAt(0),
andChar = '&'.charCodeAt(0);
Utf7Decoder.prototype.write = function(buf) {
var res = "", lastI = 0,
inBase64 = this.inBase64,
base64Accum = this.base64Accum;
// The decoder is more involved as we must handle chunks in stream.
for (var i = 0; i < buf.length; i++) {
if (!inBase64) { // We're in direct mode.
// Write direct chars until '+'
if (buf[i] == plusChar) {
res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
lastI = i+1;
inBase64 = true;
}
} else { // We decode base64.
if (!base64Chars[buf[i]]) { // Base64 ended.
if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
res += "+";
} else {
var b64str = base64Accum + buf.slice(lastI, i).toString();
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
if (buf[i] != minusChar) // Minus is absorbed after base64.
i--;
lastI = i+1;
inBase64 = false;
base64Accum = '';
}
}
}
if (!inBase64) {
res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
} else {
var b64str = base64Accum + buf.slice(lastI).toString();
var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
b64str = b64str.slice(0, canBeDecoded);
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
this.inBase64 = inBase64;
this.base64Accum = base64Accum;
return res;
}
Utf7Decoder.prototype.end = function() {
var res = "";
if (this.inBase64 && this.base64Accum.length > 0)
res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
this.inBase64 = false;
this.base64Accum = '';
return res;
}
// UTF-7-IMAP codec.
// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
// Differences:
// * Base64 part is started by "&" instead of "+"
// * Direct characters are 0x20-0x7E, except "&" (0x26)
// * In Base64, "," is used instead of "/"
// * Base64 must not be used to represent direct characters.
// * No implicit shift back from Base64 (should always end with '-')
// * String must end in non-shifted position.
// * "-&" while in base64 is not allowed.
exports.utf7imap = Utf7IMAPCodec;
function Utf7IMAPCodec(codecOptions, iconv) {
this.iconv = iconv;
};
Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
Utf7IMAPCodec.prototype.bomAware = true;
// -- Encoding
function Utf7IMAPEncoder(options, codec) {
this.iconv = codec.iconv;
this.inBase64 = false;
this.base64Accum = Buffer.alloc(6);
this.base64AccumIdx = 0;
}
Utf7IMAPEncoder.prototype.write = function(str) {
var inBase64 = this.inBase64,
base64Accum = this.base64Accum,
base64AccumIdx = this.base64AccumIdx,
buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;
for (var i = 0; i < str.length; i++) {
var uChar = str.charCodeAt(i);
if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
if (inBase64) {
if (base64AccumIdx > 0) {
bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
base64AccumIdx = 0;
}
buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
inBase64 = false;
}
if (!inBase64) {
buf[bufIdx++] = uChar; // Write direct character
if (uChar === andChar) // Ampersand -> '&-'
buf[bufIdx++] = minusChar;
}
} else { // Non-direct character
if (!inBase64) {
buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
inBase64 = true;
}
if (inBase64) {
base64Accum[base64AccumIdx++] = uChar >> 8;
base64Accum[base64AccumIdx++] = uChar & 0xFF;
if (base64AccumIdx == base64Accum.length) {
bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
base64AccumIdx = 0;
}
}
}
}
this.inBase64 = inBase64;
this.base64AccumIdx = base64AccumIdx;
return buf.slice(0, bufIdx);
}
Utf7IMAPEncoder.prototype.end = function() {
var buf = Buffer.alloc(10), bufIdx = 0;
if (this.inBase64) {
if (this.base64AccumIdx > 0) {
bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
this.base64AccumIdx = 0;
}
buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
this.inBase64 = false;
}
return buf.slice(0, bufIdx);
}
// -- Decoding
function Utf7IMAPDecoder(options, codec) {
this.iconv = codec.iconv;
this.inBase64 = false;
this.base64Accum = '';
}
var base64IMAPChars = base64Chars.slice();
base64IMAPChars[','.charCodeAt(0)] = true;
Utf7IMAPDecoder.prototype.write = function(buf) {
var res = "", lastI = 0,
inBase64 = this.inBase64,
base64Accum = this.base64Accum;
// The decoder is more involved as we must handle chunks in stream.
// It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).
for (var i = 0; i < buf.length; i++) {
if (!inBase64) { // We're in direct mode.
// Write direct chars until '&'
if (buf[i] == andChar) {
res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
lastI = i+1;
inBase64 = true;
}
} else { // We decode base64.
if (!base64IMAPChars[buf[i]]) { // Base64 ended.
if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
res += "&";
} else {
var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/');
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
if (buf[i] != minusChar) // Minus may be absorbed after base64.
i--;
lastI = i+1;
inBase64 = false;
base64Accum = '';
}
}
}
if (!inBase64) {
res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
} else {
var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/');
var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
b64str = b64str.slice(0, canBeDecoded);
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
this.inBase64 = inBase64;
this.base64Accum = base64Accum;
return res;
}
Utf7IMAPDecoder.prototype.end = function() {
var res = "";
if (this.inBase64 && this.base64Accum.length > 0)
res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
this.inBase64 = false;
this.base64Accum = '';
return res;
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/lib/index.js | aws/lti-middleware/node_modules/iconv-lite/lib/index.js | "use strict";
// Some environments don't have global Buffer (e.g. React Native).
// Solution would be installing npm modules "buffer" and "stream" explicitly.
var Buffer = require("safer-buffer").Buffer;
var bomHandling = require("./bom-handling"),
iconv = module.exports;
// All codecs and aliases are kept here, keyed by encoding name/alias.
// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
iconv.encodings = null;
// Characters emitted in case of error.
iconv.defaultCharUnicode = '�';
iconv.defaultCharSingleByte = '?';
// Public API.
iconv.encode = function encode(str, encoding, options) {
str = "" + (str || ""); // Ensure string.
var encoder = iconv.getEncoder(encoding, options);
var res = encoder.write(str);
var trail = encoder.end();
return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
}
iconv.decode = function decode(buf, encoding, options) {
if (typeof buf === 'string') {
if (!iconv.skipDecodeWarning) {
console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
iconv.skipDecodeWarning = true;
}
buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
}
var decoder = iconv.getDecoder(encoding, options);
var res = decoder.write(buf);
var trail = decoder.end();
return trail ? (res + trail) : res;
}
iconv.encodingExists = function encodingExists(enc) {
try {
iconv.getCodec(enc);
return true;
} catch (e) {
return false;
}
}
// Legacy aliases to convert functions
iconv.toEncoding = iconv.encode;
iconv.fromEncoding = iconv.decode;
// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
iconv._codecDataCache = {};
iconv.getCodec = function getCodec(encoding) {
if (!iconv.encodings)
iconv.encodings = require("../encodings"); // Lazy load all encoding definitions.
// Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
var enc = iconv._canonicalizeEncoding(encoding);
// Traverse iconv.encodings to find actual codec.
var codecOptions = {};
while (true) {
var codec = iconv._codecDataCache[enc];
if (codec)
return codec;
var codecDef = iconv.encodings[enc];
switch (typeof codecDef) {
case "string": // Direct alias to other encoding.
enc = codecDef;
break;
case "object": // Alias with options. Can be layered.
for (var key in codecDef)
codecOptions[key] = codecDef[key];
if (!codecOptions.encodingName)
codecOptions.encodingName = enc;
enc = codecDef.type;
break;
case "function": // Codec itself.
if (!codecOptions.encodingName)
codecOptions.encodingName = enc;
// The codec function must load all tables and return object with .encoder and .decoder methods.
// It'll be called only once (for each different options object).
codec = new codecDef(codecOptions, iconv);
iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
return codec;
default:
throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
}
}
}
iconv._canonicalizeEncoding = function(encoding) {
// Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
}
iconv.getEncoder = function getEncoder(encoding, options) {
var codec = iconv.getCodec(encoding),
encoder = new codec.encoder(options, codec);
if (codec.bomAware && options && options.addBOM)
encoder = new bomHandling.PrependBOM(encoder, options);
return encoder;
}
iconv.getDecoder = function getDecoder(encoding, options) {
var codec = iconv.getCodec(encoding),
decoder = new codec.decoder(options, codec);
if (codec.bomAware && !(options && options.stripBOM === false))
decoder = new bomHandling.StripBOM(decoder, options);
return decoder;
}
// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json.
var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node;
if (nodeVer) {
// Load streaming support in Node v0.10+
var nodeVerArr = nodeVer.split(".").map(Number);
if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) {
require("./streams")(iconv);
}
// Load Node primitive extensions.
require("./extend-node")(iconv);
}
if ("Ā" != "\u0100") {
console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.");
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/lib/bom-handling.js | aws/lti-middleware/node_modules/iconv-lite/lib/bom-handling.js | "use strict";
var BOMChar = '\uFEFF';
exports.PrependBOM = PrependBOMWrapper
function PrependBOMWrapper(encoder, options) {
this.encoder = encoder;
this.addBOM = true;
}
PrependBOMWrapper.prototype.write = function(str) {
if (this.addBOM) {
str = BOMChar + str;
this.addBOM = false;
}
return this.encoder.write(str);
}
PrependBOMWrapper.prototype.end = function() {
return this.encoder.end();
}
//------------------------------------------------------------------------------
exports.StripBOM = StripBOMWrapper;
function StripBOMWrapper(decoder, options) {
this.decoder = decoder;
this.pass = false;
this.options = options || {};
}
StripBOMWrapper.prototype.write = function(buf) {
var res = this.decoder.write(buf);
if (this.pass || !res)
return res;
if (res[0] === BOMChar) {
res = res.slice(1);
if (typeof this.options.stripBOM === 'function')
this.options.stripBOM();
}
this.pass = true;
return res;
}
StripBOMWrapper.prototype.end = function() {
return this.decoder.end();
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/lib/extend-node.js | aws/lti-middleware/node_modules/iconv-lite/lib/extend-node.js | "use strict";
var Buffer = require("buffer").Buffer;
// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer
// == Extend Node primitives to use iconv-lite =================================
module.exports = function (iconv) {
var original = undefined; // Place to keep original methods.
// Node authors rewrote Buffer internals to make it compatible with
// Uint8Array and we cannot patch key functions since then.
// Note: this does use older Buffer API on a purpose
iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array);
iconv.extendNodeEncodings = function extendNodeEncodings() {
if (original) return;
original = {};
if (!iconv.supportsNodeEncodingsExtension) {
console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node");
console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility");
return;
}
var nodeNativeEncodings = {
'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true,
'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true,
};
Buffer.isNativeEncoding = function(enc) {
return enc && nodeNativeEncodings[enc.toLowerCase()];
}
// -- SlowBuffer -----------------------------------------------------------
var SlowBuffer = require('buffer').SlowBuffer;
original.SlowBufferToString = SlowBuffer.prototype.toString;
SlowBuffer.prototype.toString = function(encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
// Use native conversion when possible
if (Buffer.isNativeEncoding(encoding))
return original.SlowBufferToString.call(this, encoding, start, end);
// Otherwise, use our decoding method.
if (typeof start == 'undefined') start = 0;
if (typeof end == 'undefined') end = this.length;
return iconv.decode(this.slice(start, end), encoding);
}
original.SlowBufferWrite = SlowBuffer.prototype.write;
SlowBuffer.prototype.write = function(string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length;
length = undefined;
}
} else { // legacy
var swap = encoding;
encoding = offset;
offset = length;
length = swap;
}
offset = +offset || 0;
var remaining = this.length - offset;
if (!length) {
length = remaining;
} else {
length = +length;
if (length > remaining) {
length = remaining;
}
}
encoding = String(encoding || 'utf8').toLowerCase();
// Use native conversion when possible
if (Buffer.isNativeEncoding(encoding))
return original.SlowBufferWrite.call(this, string, offset, length, encoding);
if (string.length > 0 && (length < 0 || offset < 0))
throw new RangeError('attempt to write beyond buffer bounds');
// Otherwise, use our encoding method.
var buf = iconv.encode(string, encoding);
if (buf.length < length) length = buf.length;
buf.copy(this, offset, 0, length);
return length;
}
// -- Buffer ---------------------------------------------------------------
original.BufferIsEncoding = Buffer.isEncoding;
Buffer.isEncoding = function(encoding) {
return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding);
}
original.BufferByteLength = Buffer.byteLength;
Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) {
encoding = String(encoding || 'utf8').toLowerCase();
// Use native conversion when possible
if (Buffer.isNativeEncoding(encoding))
return original.BufferByteLength.call(this, str, encoding);
// Slow, I know, but we don't have a better way yet.
return iconv.encode(str, encoding).length;
}
original.BufferToString = Buffer.prototype.toString;
Buffer.prototype.toString = function(encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
// Use native conversion when possible
if (Buffer.isNativeEncoding(encoding))
return original.BufferToString.call(this, encoding, start, end);
// Otherwise, use our decoding method.
if (typeof start == 'undefined') start = 0;
if (typeof end == 'undefined') end = this.length;
return iconv.decode(this.slice(start, end), encoding);
}
original.BufferWrite = Buffer.prototype.write;
Buffer.prototype.write = function(string, offset, length, encoding) {
var _offset = offset, _length = length, _encoding = encoding;
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length;
length = undefined;
}
} else { // legacy
var swap = encoding;
encoding = offset;
offset = length;
length = swap;
}
encoding = String(encoding || 'utf8').toLowerCase();
// Use native conversion when possible
if (Buffer.isNativeEncoding(encoding))
return original.BufferWrite.call(this, string, _offset, _length, _encoding);
offset = +offset || 0;
var remaining = this.length - offset;
if (!length) {
length = remaining;
} else {
length = +length;
if (length > remaining) {
length = remaining;
}
}
if (string.length > 0 && (length < 0 || offset < 0))
throw new RangeError('attempt to write beyond buffer bounds');
// Otherwise, use our encoding method.
var buf = iconv.encode(string, encoding);
if (buf.length < length) length = buf.length;
buf.copy(this, offset, 0, length);
return length;
// TODO: Set _charsWritten.
}
// -- Readable -------------------------------------------------------------
if (iconv.supportsStreams) {
var Readable = require('stream').Readable;
original.ReadableSetEncoding = Readable.prototype.setEncoding;
Readable.prototype.setEncoding = function setEncoding(enc, options) {
// Use our own decoder, it has the same interface.
// We cannot use original function as it doesn't handle BOM-s.
this._readableState.decoder = iconv.getDecoder(enc, options);
this._readableState.encoding = enc;
}
Readable.prototype.collect = iconv._collect;
}
}
// Remove iconv-lite Node primitive extensions.
iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() {
if (!iconv.supportsNodeEncodingsExtension)
return;
if (!original)
throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.")
delete Buffer.isNativeEncoding;
var SlowBuffer = require('buffer').SlowBuffer;
SlowBuffer.prototype.toString = original.SlowBufferToString;
SlowBuffer.prototype.write = original.SlowBufferWrite;
Buffer.isEncoding = original.BufferIsEncoding;
Buffer.byteLength = original.BufferByteLength;
Buffer.prototype.toString = original.BufferToString;
Buffer.prototype.write = original.BufferWrite;
if (iconv.supportsStreams) {
var Readable = require('stream').Readable;
Readable.prototype.setEncoding = original.ReadableSetEncoding;
delete Readable.prototype.collect;
}
original = undefined;
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/iconv-lite/lib/streams.js | aws/lti-middleware/node_modules/iconv-lite/lib/streams.js | "use strict";
var Buffer = require("buffer").Buffer,
Transform = require("stream").Transform;
// == Exports ==================================================================
module.exports = function(iconv) {
// Additional Public API.
iconv.encodeStream = function encodeStream(encoding, options) {
return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
}
iconv.decodeStream = function decodeStream(encoding, options) {
return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
}
iconv.supportsStreams = true;
// Not published yet.
iconv.IconvLiteEncoderStream = IconvLiteEncoderStream;
iconv.IconvLiteDecoderStream = IconvLiteDecoderStream;
iconv._collect = IconvLiteDecoderStream.prototype.collect;
};
// == Encoder stream =======================================================
function IconvLiteEncoderStream(conv, options) {
this.conv = conv;
options = options || {};
options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
Transform.call(this, options);
}
IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
constructor: { value: IconvLiteEncoderStream }
});
IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
if (typeof chunk != 'string')
return done(new Error("Iconv encoding stream needs strings as its input."));
try {
var res = this.conv.write(chunk);
if (res && res.length) this.push(res);
done();
}
catch (e) {
done(e);
}
}
IconvLiteEncoderStream.prototype._flush = function(done) {
try {
var res = this.conv.end();
if (res && res.length) this.push(res);
done();
}
catch (e) {
done(e);
}
}
IconvLiteEncoderStream.prototype.collect = function(cb) {
var chunks = [];
this.on('error', cb);
this.on('data', function(chunk) { chunks.push(chunk); });
this.on('end', function() {
cb(null, Buffer.concat(chunks));
});
return this;
}
// == Decoder stream =======================================================
function IconvLiteDecoderStream(conv, options) {
this.conv = conv;
options = options || {};
options.encoding = this.encoding = 'utf8'; // We output strings.
Transform.call(this, options);
}
IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
constructor: { value: IconvLiteDecoderStream }
});
IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
if (!Buffer.isBuffer(chunk))
return done(new Error("Iconv decoding stream needs buffers as its input."));
try {
var res = this.conv.write(chunk);
if (res && res.length) this.push(res, this.encoding);
done();
}
catch (e) {
done(e);
}
}
IconvLiteDecoderStream.prototype._flush = function(done) {
try {
var res = this.conv.end();
if (res && res.length) this.push(res, this.encoding);
done();
}
catch (e) {
done(e);
}
}
IconvLiteDecoderStream.prototype.collect = function(cb) {
var res = '';
this.on('error', cb);
this.on('data', function(chunk) { res += chunk; });
this.on('end', function() {
cb(null, res);
});
return this;
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/string-width/index.js | aws/lti-middleware/node_modules/string-width/index.js | 'use strict';
const stripAnsi = require('strip-ansi');
const isFullwidthCodePoint = require('is-fullwidth-code-point');
const emojiRegex = require('emoji-regex');
const stringWidth = string => {
if (typeof string !== 'string' || string.length === 0) {
return 0;
}
string = stripAnsi(string);
if (string.length === 0) {
return 0;
}
string = string.replace(emojiRegex(), ' ');
let width = 0;
for (let i = 0; i < string.length; i++) {
const code = string.codePointAt(i);
// Ignore control characters
if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
continue;
}
// Ignore combining characters
if (code >= 0x300 && code <= 0x36F) {
continue;
}
// Surrogates
if (code > 0xFFFF) {
i++;
}
width += isFullwidthCodePoint(code) ? 2 : 1;
}
return width;
};
module.exports = stringWidth;
// TODO: remove this in the next major version
module.exports.default = stringWidth;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/index.js | aws/lti-middleware/node_modules/express/index.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
module.exports = require('./lib/express');
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/express.js | aws/lti-middleware/node_modules/express/lib/express.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var bodyParser = require('body-parser')
var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./application');
var Route = require('./router/route');
var Router = require('./router');
var req = require('./request');
var res = require('./response');
/**
* Expose `createApplication()`.
*/
exports = module.exports = createApplication;
/**
* Create an express application.
*
* @return {Function}
* @api public
*/
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
// expose the prototype that will get set on responses
app.response = Object.create(res, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
app.init();
return app;
}
/**
* Expose the prototypes.
*/
exports.application = proto;
exports.request = req;
exports.response = res;
/**
* Expose constructors.
*/
exports.Route = Route;
exports.Router = Router;
/**
* Expose middleware
*/
exports.json = bodyParser.json
exports.query = require('./middleware/query');
exports.raw = bodyParser.raw
exports.static = require('serve-static');
exports.text = bodyParser.text
exports.urlencoded = bodyParser.urlencoded
/**
* Replace removed middleware with an appropriate error message.
*/
var removedMiddlewares = [
'bodyParser',
'compress',
'cookieSession',
'session',
'logger',
'cookieParser',
'favicon',
'responseTime',
'errorHandler',
'timeout',
'methodOverride',
'vhost',
'csrf',
'directory',
'limit',
'multipart',
'staticCache'
]
removedMiddlewares.forEach(function (name) {
Object.defineProperty(exports, name, {
get: function () {
throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.');
},
configurable: true
});
});
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/application.js | aws/lti-middleware/node_modules/express/lib/application.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var finalhandler = require('finalhandler');
var Router = require('./router');
var methods = require('methods');
var middleware = require('./middleware/init');
var query = require('./middleware/query');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var merge = require('utils-merge');
var resolve = require('path').resolve;
var setPrototypeOf = require('setprototypeof')
var slice = Array.prototype.slice;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Variable for trust proxy inheritance back-compat
* @private
*/
var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @private
*/
app.init = function init() {
this.cache = {};
this.engines = {};
this.settings = {};
this.defaultConfiguration();
};
/**
* Initialize application configuration.
* @private
*/
app.defaultConfiguration = function defaultConfiguration() {
var env = process.env.NODE_ENV || 'development';
// default settings
this.enable('x-powered-by');
this.set('etag', 'weak');
this.set('env', env);
this.set('query parser', 'extended');
this.set('subdomain offset', 2);
this.set('trust proxy', false);
// trust proxy inherit back-compat
Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
configurable: true,
value: true
});
debug('booting in %s mode', env);
this.on('mount', function onmount(parent) {
// inherit trust proxy
if (this.settings[trustProxyDefaultSymbol] === true
&& typeof parent.settings['trust proxy fn'] === 'function') {
delete this.settings['trust proxy'];
delete this.settings['trust proxy fn'];
}
// inherit protos
setPrototypeOf(this.request, parent.request)
setPrototypeOf(this.response, parent.response)
setPrototypeOf(this.engines, parent.engines)
setPrototypeOf(this.settings, parent.settings)
});
// setup locals
this.locals = Object.create(null);
// top-most app is mounted at /
this.mountpath = '/';
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('view', View);
this.set('views', resolve('views'));
this.set('jsonp callback name', 'callback');
if (env === 'production') {
this.enable('view cache');
}
Object.defineProperty(this, 'router', {
get: function() {
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
}
});
};
/**
* lazily adds the base router if it has not yet been added.
*
* We cannot add the base router in the defaultConfiguration because
* it reads app settings which might be set after that has run.
*
* @private
*/
app.lazyrouter = function lazyrouter() {
if (!this._router) {
this._router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));
}
};
/**
* Dispatch a req, res pair into the application. Starts pipeline processing.
*
* If no callback is provided, then default error handlers will respond
* in the event of an error bubbling through the stack.
*
* @private
*/
app.handle = function handle(req, res, callback) {
var router = this._router;
// final handler
var done = callback || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// no routes
if (!router) {
debug('no routes defined on app');
done();
return;
}
router.handle(req, res, done);
};
/**
* Proxy `Router#use()` to add middleware to the app router.
* See Router#use() documentation for details.
*
* If the _fn_ parameter is an express app, then it will be
* mounted at the _route_ specified.
*
* @public
*/
app.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate app.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var fns = flatten(slice.call(arguments, offset));
if (fns.length === 0) {
throw new TypeError('app.use() requires a middleware function')
}
// setup router
this.lazyrouter();
var router = this._router;
fns.forEach(function (fn) {
// non-express app
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
debug('.use app under %s', path);
fn.mountpath = path;
fn.parent = this;
// restore .app property on req and res
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
setPrototypeOf(req, orig.request)
setPrototypeOf(res, orig.response)
next(err);
});
});
// mounted an app
fn.emit('mount', this);
}, this);
return this;
};
/**
* Proxy to the app `Router#route()`
* Returns a new `Route` instance for the _path_.
*
* Routes are isolated middleware stacks for specific paths.
* See the Route api docs for details.
*
* @public
*/
app.route = function route(path) {
this.lazyrouter();
return this._router.route(path);
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.ejs" file Express will invoke the following internally:
*
* app.engine('ejs', require('ejs').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you don't need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @public
*/
app.engine = function engine(ext, fn) {
if (typeof fn !== 'function') {
throw new Error('callback function required');
}
// get file extension
var extension = ext[0] !== '.'
? '.' + ext
: ext;
// store engine
this.engines[extension] = fn;
return this;
};
/**
* Proxy to `Router#param()` with one added api feature. The _name_ parameter
* can be an array of names.
*
* See the Router#param() docs for more details.
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @public
*/
app.param = function param(name, fn) {
this.lazyrouter();
if (Array.isArray(name)) {
for (var i = 0; i < name.length; i++) {
this.param(name[i], fn);
}
return this;
}
this._router.param(name, fn);
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.set('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {*} [val]
* @return {Server} for chaining
* @public
*/
app.set = function set(setting, val) {
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
debug('set "%s" to %o', setting, val);
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
this.set('etag fn', compileETag(val));
break;
case 'query parser':
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
this.set('trust proxy fn', compileTrust(val));
// trust proxy inherit back-compat
Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
configurable: true,
value: false
});
break;
}
return this;
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @private
*/
app.path = function path() {
return this.parent
? this.parent.path() + this.mountpath
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @public
*/
app.enabled = function enabled(setting) {
return Boolean(this.set(setting));
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @public
*/
app.disabled = function disabled(setting) {
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @public
*/
app.enable = function enable(setting) {
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @public
*/
app.disable = function disable(setting) {
return this.set(setting, false);
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if (method === 'get' && arguments.length === 1) {
// app.get(setting)
return this.set(path);
}
this.lazyrouter();
var route = this._router.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @public
*/
app.all = function all(path) {
this.lazyrouter();
var route = this._router.route(path);
var args = slice.call(arguments, 1);
for (var i = 0; i < methods.length; i++) {
route[methods[i]].apply(route, args);
}
return this;
};
// del -> delete alias
app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
/**
* Render the given view `name` name with `options`
* and a callback accepting an error and the
* rendered template string.
*
* Example:
*
* app.render('email', { name: 'Tobi' }, function(err, html){
* // ...
* })
*
* @param {String} name
* @param {Object|Function} options or fn
* @param {Function} callback
* @public
*/
app.render = function render(name, options, callback) {
var cache = this.cache;
var done = callback;
var engines = this.engines;
var opts = options;
var renderOptions = {};
var view;
// support callback function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
// merge app.locals
merge(renderOptions, this.locals);
// merge options._locals
if (opts._locals) {
merge(renderOptions, opts._locals);
}
// merge options
merge(renderOptions, opts);
// set .cache unless explicitly provided
if (renderOptions.cache == null) {
renderOptions.cache = this.enabled('view cache');
}
// primed cache
if (renderOptions.cache) {
view = cache[name];
}
// view
if (!view) {
var View = this.get('view');
view = new View(name, {
defaultEngine: this.get('view engine'),
root: this.get('views'),
engines: engines
});
if (!view.path) {
var dirs = Array.isArray(view.root) && view.root.length > 1
? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
: 'directory "' + view.root + '"'
var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
err.view = view;
return done(err);
}
// prime the cache
if (renderOptions.cache) {
cache[name] = view;
}
}
// render
tryRender(view, renderOptions, done);
};
/**
* Listen for connections.
*
* A node `http.Server` is returned, with this
* application (which is a `Function`) as its
* callback. If you wish to create both an HTTP
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('http')
* , https = require('https')
* , express = require('express')
* , app = express();
*
* http.createServer(app).listen(80);
* https.createServer({ ... }, app).listen(443);
*
* @return {http.Server}
* @public
*/
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
/**
* Log error using console.error.
*
* @param {Error} err
* @private
*/
function logerror(err) {
/* istanbul ignore next */
if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
/**
* Try rendering a view.
* @private
*/
function tryRender(view, options, callback) {
try {
view.render(options, callback);
} catch (err) {
callback(err);
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/view.js | aws/lti-middleware/node_modules/express/lib/view.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var debug = require('debug')('express:view');
var path = require('path');
var fs = require('fs');
/**
* Module variables.
* @private
*/
var dirname = path.dirname;
var basename = path.basename;
var extname = path.extname;
var join = path.join;
var resolve = path.resolve;
/**
* Module exports.
* @public
*/
module.exports = View;
/**
* Initialize a new `View` with the given `name`.
*
* Options:
*
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
* @param {string} name
* @param {object} options
* @public
*/
function View(name, options) {
var opts = options || {};
this.defaultEngine = opts.defaultEngine;
this.ext = extname(name);
this.name = name;
this.root = opts.root;
if (!this.ext && !this.defaultEngine) {
throw new Error('No default engine was specified and no extension was provided.');
}
var fileName = name;
if (!this.ext) {
// get extension from default engine name
this.ext = this.defaultEngine[0] !== '.'
? '.' + this.defaultEngine
: this.defaultEngine;
fileName += this.ext;
}
if (!opts.engines[this.ext]) {
// load engine
var mod = this.ext.substr(1)
debug('require "%s"', mod)
// default engine export
var fn = require(mod).__express
if (typeof fn !== 'function') {
throw new Error('Module "' + mod + '" does not provide a view engine.')
}
opts.engines[this.ext] = fn
}
// store loaded engine
this.engine = opts.engines[this.ext];
// lookup path
this.path = this.lookup(fileName);
}
/**
* Lookup view by the given `name`
*
* @param {string} name
* @private
*/
View.prototype.lookup = function lookup(name) {
var path;
var roots = [].concat(this.root);
debug('lookup "%s"', name);
for (var i = 0; i < roots.length && !path; i++) {
var root = roots[i];
// resolve the path
var loc = resolve(root, name);
var dir = dirname(loc);
var file = basename(loc);
// resolve the file
path = this.resolve(dir, file);
}
return path;
};
/**
* Render with the given options.
*
* @param {object} options
* @param {function} callback
* @private
*/
View.prototype.render = function render(options, callback) {
debug('render "%s"', this.path);
this.engine(this.path, options, callback);
};
/**
* Resolve the file within the given directory.
*
* @param {string} dir
* @param {string} file
* @private
*/
View.prototype.resolve = function resolve(dir, file) {
var ext = this.ext;
// <path>.<ext>
var path = join(dir, file);
var stat = tryStat(path);
if (stat && stat.isFile()) {
return path;
}
// <path>/index.<ext>
path = join(dir, basename(file, ext), 'index' + ext);
stat = tryStat(path);
if (stat && stat.isFile()) {
return path;
}
};
/**
* Return a stat, maybe.
*
* @param {string} path
* @return {fs.Stats}
* @private
*/
function tryStat(path) {
debug('stat "%s"', path);
try {
return fs.statSync(path);
} catch (e) {
return undefined;
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/request.js | aws/lti-middleware/node_modules/express/lib/request.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var accepts = require('accepts');
var deprecate = require('depd')('express');
var isIP = require('net').isIP;
var typeis = require('type-is');
var http = require('http');
var fresh = require('fresh');
var parseRange = require('range-parser');
var parse = require('parseurl');
var proxyaddr = require('proxy-addr');
/**
* Request prototype.
* @public
*/
var req = Object.create(http.IncomingMessage.prototype)
/**
* Module exports.
* @public
*/
module.exports = req
/**
* Return request header.
*
* The `Referrer` header field is special-cased,
* both `Referrer` and `Referer` are interchangeable.
*
* Examples:
*
* req.get('Content-Type');
* // => "text/plain"
*
* req.get('content-type');
* // => "text/plain"
*
* req.get('Something');
* // => undefined
*
* Aliased as `req.header()`.
*
* @param {String} name
* @return {String}
* @public
*/
req.get =
req.header = function header(name) {
if (!name) {
throw new TypeError('name argument is required to req.get');
}
if (typeof name !== 'string') {
throw new TypeError('name must be a string to req.get');
}
var lc = name.toLowerCase();
switch (lc) {
case 'referer':
case 'referrer':
return this.headers.referrer
|| this.headers.referer;
default:
return this.headers[lc];
}
};
/**
* To do: update docs.
*
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single MIME type string
* such as "application/json", an extension name
* such as "json", a comma-delimited list such as "json, html, text/plain",
* an argument list such as `"json", "html", "text/plain"`,
* or an array `["json", "html", "text/plain"]`. When a list
* or array is given, the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* req.accepts('html');
* // => "html"
*
* // Accept: text/*, application/json
* req.accepts('html');
* // => "html"
* req.accepts('text/html');
* // => "text/html"
* req.accepts('json, text');
* // => "json"
* req.accepts('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* req.accepts('image/png');
* req.accepts('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* req.accepts(['html', 'json']);
* req.accepts('html', 'json');
* req.accepts('html, json');
* // => "json"
*
* @param {String|Array} type(s)
* @return {String|Array|Boolean}
* @public
*/
req.accepts = function(){
var accept = accepts(this);
return accept.types.apply(accept, arguments);
};
/**
* Check if the given `encoding`s are accepted.
*
* @param {String} ...encoding
* @return {String|Array}
* @public
*/
req.acceptsEncodings = function(){
var accept = accepts(this);
return accept.encodings.apply(accept, arguments);
};
req.acceptsEncoding = deprecate.function(req.acceptsEncodings,
'req.acceptsEncoding: Use acceptsEncodings instead');
/**
* Check if the given `charset`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {String} ...charset
* @return {String|Array}
* @public
*/
req.acceptsCharsets = function(){
var accept = accepts(this);
return accept.charsets.apply(accept, arguments);
};
req.acceptsCharset = deprecate.function(req.acceptsCharsets,
'req.acceptsCharset: Use acceptsCharsets instead');
/**
* Check if the given `lang`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {String} ...lang
* @return {String|Array}
* @public
*/
req.acceptsLanguages = function(){
var accept = accepts(this);
return accept.languages.apply(accept, arguments);
};
req.acceptsLanguage = deprecate.function(req.acceptsLanguages,
'req.acceptsLanguage: Use acceptsLanguages instead');
/**
* Parse Range header field, capping to the given `size`.
*
* Unspecified ranges such as "0-" require knowledge of your resource length. In
* the case of a byte range this is of course the total number of bytes. If the
* Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
* and `-2` when syntactically invalid.
*
* When ranges are returned, the array has a "type" property which is the type of
* range that is required (most commonly, "bytes"). Each array element is an object
* with a "start" and "end" property for the portion of the range.
*
* The "combine" option can be set to `true` and overlapping & adjacent ranges
* will be combined into a single range.
*
* NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
* should respond with 4 users when available, not 3.
*
* @param {number} size
* @param {object} [options]
* @param {boolean} [options.combine=false]
* @return {number|array}
* @public
*/
req.range = function range(size, options) {
var range = this.get('Range');
if (!range) return;
return parseRange(size, range, options);
};
/**
* Return the value of param `name` when present or `defaultValue`.
*
* - Checks route placeholders, ex: _/user/:id_
* - Checks body params, ex: id=12, {"id":12}
* - Checks query string params, ex: ?id=12
*
* To utilize request bodies, `req.body`
* should be an object. This can be done by using
* the `bodyParser()` middleware.
*
* @param {String} name
* @param {Mixed} [defaultValue]
* @return {String}
* @public
*/
req.param = function param(name, defaultValue) {
var params = this.params || {};
var body = this.body || {};
var query = this.query || {};
var args = arguments.length === 1
? 'name'
: 'name, default';
deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');
if (null != params[name] && params.hasOwnProperty(name)) return params[name];
if (null != body[name]) return body[name];
if (null != query[name]) return query[name];
return defaultValue;
};
/**
* Check if the incoming request contains the "Content-Type"
* header field, and it contains the given mime `type`.
*
* Examples:
*
* // With Content-Type: text/html; charset=utf-8
* req.is('html');
* req.is('text/html');
* req.is('text/*');
* // => true
*
* // When Content-Type is application/json
* req.is('json');
* req.is('application/json');
* req.is('application/*');
* // => true
*
* req.is('html');
* // => false
*
* @param {String|Array} types...
* @return {String|false|null}
* @public
*/
req.is = function is(types) {
var arr = types;
// support flattened arguments
if (!Array.isArray(types)) {
arr = new Array(arguments.length);
for (var i = 0; i < arr.length; i++) {
arr[i] = arguments[i];
}
}
return typeis(this, arr);
};
/**
* Return the protocol string "http" or "https"
* when requested with TLS. When the "trust proxy"
* setting trusts the socket address, the
* "X-Forwarded-Proto" header field will be trusted
* and used if present.
*
* If you're running behind a reverse proxy that
* supplies https for you this may be enabled.
*
* @return {String}
* @public
*/
defineGetter(req, 'protocol', function protocol(){
var proto = this.connection.encrypted
? 'https'
: 'http';
var trust = this.app.get('trust proxy fn');
if (!trust(this.connection.remoteAddress, 0)) {
return proto;
}
// Note: X-Forwarded-Proto is normally only ever a
// single value, but this is to be safe.
var header = this.get('X-Forwarded-Proto') || proto
var index = header.indexOf(',')
return index !== -1
? header.substring(0, index).trim()
: header.trim()
});
/**
* Short-hand for:
*
* req.protocol === 'https'
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'secure', function secure(){
return this.protocol === 'https';
});
/**
* Return the remote address from the trusted proxy.
*
* The is the remote address on the socket unless
* "trust proxy" is set.
*
* @return {String}
* @public
*/
defineGetter(req, 'ip', function ip(){
var trust = this.app.get('trust proxy fn');
return proxyaddr(this, trust);
});
/**
* When "trust proxy" is set, trusted proxy addresses + client.
*
* For example if the value were "client, proxy1, proxy2"
* you would receive the array `["client", "proxy1", "proxy2"]`
* where "proxy2" is the furthest down-stream and "proxy1" and
* "proxy2" were trusted.
*
* @return {Array}
* @public
*/
defineGetter(req, 'ips', function ips() {
var trust = this.app.get('trust proxy fn');
var addrs = proxyaddr.all(this, trust);
// reverse the order (to farthest -> closest)
// and remove socket address
addrs.reverse().pop()
return addrs
});
/**
* Return subdomains as an array.
*
* Subdomains are the dot-separated parts of the host before the main domain of
* the app. By default, the domain of the app is assumed to be the last two
* parts of the host. This can be changed by setting "subdomain offset".
*
* For example, if the domain is "tobi.ferrets.example.com":
* If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
* If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
*
* @return {Array}
* @public
*/
defineGetter(req, 'subdomains', function subdomains() {
var hostname = this.hostname;
if (!hostname) return [];
var offset = this.app.get('subdomain offset');
var subdomains = !isIP(hostname)
? hostname.split('.').reverse()
: [hostname];
return subdomains.slice(offset);
});
/**
* Short-hand for `url.parse(req.url).pathname`.
*
* @return {String}
* @public
*/
defineGetter(req, 'path', function path() {
return parse(this).pathname;
});
/**
* Parse the "Host" header field to a hostname.
*
* When the "trust proxy" setting trusts the socket
* address, the "X-Forwarded-Host" header field will
* be trusted.
*
* @return {String}
* @public
*/
defineGetter(req, 'hostname', function hostname(){
var trust = this.app.get('trust proxy fn');
var host = this.get('X-Forwarded-Host');
if (!host || !trust(this.connection.remoteAddress, 0)) {
host = this.get('Host');
} else if (host.indexOf(',') !== -1) {
// Note: X-Forwarded-Host is normally only ever a
// single value, but this is to be safe.
host = host.substring(0, host.indexOf(',')).trimRight()
}
if (!host) return;
// IPv6 literal support
var offset = host[0] === '['
? host.indexOf(']') + 1
: 0;
var index = host.indexOf(':', offset);
return index !== -1
? host.substring(0, index)
: host;
});
// TODO: change req.host to return host in next major
defineGetter(req, 'host', deprecate.function(function host(){
return this.hostname;
}, 'req.host: Use req.hostname instead'));
/**
* Check if the request is fresh, aka
* Last-Modified and/or the ETag
* still match.
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'fresh', function(){
var method = this.method;
var res = this.res
var status = res.statusCode
// GET or HEAD for weak freshness validation only
if ('GET' !== method && 'HEAD' !== method) return false;
// 2xx or 304 as per rfc2616 14.26
if ((status >= 200 && status < 300) || 304 === status) {
return fresh(this.headers, {
'etag': res.get('ETag'),
'last-modified': res.get('Last-Modified')
})
}
return false;
});
/**
* Check if the request is stale, aka
* "Last-Modified" and / or the "ETag" for the
* resource has changed.
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'stale', function stale(){
return !this.fresh;
});
/**
* Check if the request was an _XMLHttpRequest_.
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'xhr', function xhr(){
var val = this.get('X-Requested-With') || '';
return val.toLowerCase() === 'xmlhttprequest';
});
/**
* Helper function for creating a getter on an object.
*
* @param {Object} obj
* @param {String} name
* @param {Function} getter
* @private
*/
function defineGetter(obj, name, getter) {
Object.defineProperty(obj, name, {
configurable: true,
enumerable: true,
get: getter
});
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/utils.js | aws/lti-middleware/node_modules/express/lib/utils.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @api private
*/
var Buffer = require('safe-buffer').Buffer
var contentDisposition = require('content-disposition');
var contentType = require('content-type');
var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var mime = require('send').mime;
var etag = require('etag');
var proxyaddr = require('proxy-addr');
var qs = require('qs');
var querystring = require('querystring');
/**
* Return strong ETag for `body`.
*
* @param {String|Buffer} body
* @param {String} [encoding]
* @return {String}
* @api private
*/
exports.etag = createETagGenerator({ weak: false })
/**
* Return weak ETag for `body`.
*
* @param {String|Buffer} body
* @param {String} [encoding]
* @return {String}
* @api private
*/
exports.wetag = createETagGenerator({ weak: true })
/**
* Check if `path` looks absolute.
*
* @param {String} path
* @return {Boolean}
* @api private
*/
exports.isAbsolute = function(path){
if ('/' === path[0]) return true;
if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path
if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path
};
/**
* Flatten the given `arr`.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
exports.flatten = deprecate.function(flatten,
'utils.flatten: use array-flatten npm module instead');
/**
* Normalize the given `type`, for example "html" becomes "text/html".
*
* @param {String} type
* @return {Object}
* @api private
*/
exports.normalizeType = function(type){
return ~type.indexOf('/')
? acceptParams(type)
: { value: mime.lookup(type), params: {} };
};
/**
* Normalize `types`, for example "html" becomes "text/html".
*
* @param {Array} types
* @return {Array}
* @api private
*/
exports.normalizeTypes = function(types){
var ret = [];
for (var i = 0; i < types.length; ++i) {
ret.push(exports.normalizeType(types[i]));
}
return ret;
};
/**
* Generate Content-Disposition header appropriate for the filename.
* non-ascii filenames are urlencoded and a filename* parameter is added
*
* @param {String} filename
* @return {String}
* @api private
*/
exports.contentDisposition = deprecate.function(contentDisposition,
'utils.contentDisposition: use content-disposition npm module instead');
/**
* Parse accept params `str` returning an
* object with `.value`, `.quality` and `.params`.
* also includes `.originalIndex` for stable sorting
*
* @param {String} str
* @return {Object}
* @api private
*/
function acceptParams(str, index) {
var parts = str.split(/ *; */);
var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };
for (var i = 1; i < parts.length; ++i) {
var pms = parts[i].split(/ *= */);
if ('q' === pms[0]) {
ret.quality = parseFloat(pms[1]);
} else {
ret.params[pms[0]] = pms[1];
}
}
return ret;
}
/**
* Compile "etag" value to function.
*
* @param {Boolean|String|Function} val
* @return {Function}
* @api private
*/
exports.compileETag = function(val) {
var fn;
if (typeof val === 'function') {
return val;
}
switch (val) {
case true:
case 'weak':
fn = exports.wetag;
break;
case false:
break;
case 'strong':
fn = exports.etag;
break;
default:
throw new TypeError('unknown value for etag function: ' + val);
}
return fn;
}
/**
* Compile "query parser" value to function.
*
* @param {String|Function} val
* @return {Function}
* @api private
*/
exports.compileQueryParser = function compileQueryParser(val) {
var fn;
if (typeof val === 'function') {
return val;
}
switch (val) {
case true:
case 'simple':
fn = querystring.parse;
break;
case false:
fn = newObject;
break;
case 'extended':
fn = parseExtendedQueryString;
break;
default:
throw new TypeError('unknown value for query parser function: ' + val);
}
return fn;
}
/**
* Compile "proxy trust" value to function.
*
* @param {Boolean|String|Number|Array|Function} val
* @return {Function}
* @api private
*/
exports.compileTrust = function(val) {
if (typeof val === 'function') return val;
if (val === true) {
// Support plain true/false
return function(){ return true };
}
if (typeof val === 'number') {
// Support trusting hop count
return function(a, i){ return i < val };
}
if (typeof val === 'string') {
// Support comma-separated values
val = val.split(',')
.map(function (v) { return v.trim() })
}
return proxyaddr.compile(val || []);
}
/**
* Set the charset in a given Content-Type string.
*
* @param {String} type
* @param {String} charset
* @return {String}
* @api private
*/
exports.setCharset = function setCharset(type, charset) {
if (!type || !charset) {
return type;
}
// parse type
var parsed = contentType.parse(type);
// set charset
parsed.parameters.charset = charset;
// format type
return contentType.format(parsed);
};
/**
* Create an ETag generator function, generating ETags with
* the given options.
*
* @param {object} options
* @return {function}
* @private
*/
function createETagGenerator (options) {
return function generateETag (body, encoding) {
var buf = !Buffer.isBuffer(body)
? Buffer.from(body, encoding)
: body
return etag(buf, options)
}
}
/**
* Parse an extended query string with qs.
*
* @return {Object}
* @private
*/
function parseExtendedQueryString(str) {
return qs.parse(str, {
allowPrototypes: true
});
}
/**
* Return new empty object.
*
* @return {Object}
* @api private
*/
function newObject() {
return {};
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/response.js | aws/lti-middleware/node_modules/express/lib/response.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var Buffer = require('safe-buffer').Buffer
var contentDisposition = require('content-disposition');
var deprecate = require('depd')('express');
var encodeUrl = require('encodeurl');
var escapeHtml = require('escape-html');
var http = require('http');
var isAbsolute = require('./utils').isAbsolute;
var onFinished = require('on-finished');
var path = require('path');
var statuses = require('statuses')
var merge = require('utils-merge');
var sign = require('cookie-signature').sign;
var normalizeType = require('./utils').normalizeType;
var normalizeTypes = require('./utils').normalizeTypes;
var setCharset = require('./utils').setCharset;
var cookie = require('cookie');
var send = require('send');
var extname = path.extname;
var mime = send.mime;
var resolve = path.resolve;
var vary = require('vary');
/**
* Response prototype.
* @public
*/
var res = Object.create(http.ServerResponse.prototype)
/**
* Module exports.
* @public
*/
module.exports = res
/**
* Module variables.
* @private
*/
var charsetRegExp = /;\s*charset\s*=/;
/**
* Set status `code`.
*
* @param {Number} code
* @return {ServerResponse}
* @public
*/
res.status = function status(code) {
this.statusCode = code;
return this;
};
/**
* Set Link header field with the given `links`.
*
* Examples:
*
* res.links({
* next: 'http://api.example.com/users?page=2',
* last: 'http://api.example.com/users?page=5'
* });
*
* @param {Object} links
* @return {ServerResponse}
* @public
*/
res.links = function(links){
var link = this.get('Link') || '';
if (link) link += ', ';
return this.set('Link', link + Object.keys(links).map(function(rel){
return '<' + links[rel] + '>; rel="' + rel + '"';
}).join(', '));
};
/**
* Send a response.
*
* Examples:
*
* res.send(Buffer.from('wahoo'));
* res.send({ some: 'json' });
* res.send('<p>some html</p>');
*
* @param {string|number|boolean|object|Buffer} body
* @public
*/
res.send = function send(body) {
var chunk = body;
var encoding;
var req = this.req;
var type;
// settings
var app = this.app;
// allow status / body
if (arguments.length === 2) {
// res.send(body, status) backwards compat
if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {
deprecate('res.send(body, status): Use res.status(status).send(body) instead');
this.statusCode = arguments[1];
} else {
deprecate('res.send(status, body): Use res.status(status).send(body) instead');
this.statusCode = arguments[0];
chunk = arguments[1];
}
}
// disambiguate res.send(status) and res.send(status, num)
if (typeof chunk === 'number' && arguments.length === 1) {
// res.send(status) will set status message as text string
if (!this.get('Content-Type')) {
this.type('txt');
}
deprecate('res.send(status): Use res.sendStatus(status) instead');
this.statusCode = chunk;
chunk = statuses[chunk]
}
switch (typeof chunk) {
// string defaulting to html
case 'string':
if (!this.get('Content-Type')) {
this.type('html');
}
break;
case 'boolean':
case 'number':
case 'object':
if (chunk === null) {
chunk = '';
} else if (Buffer.isBuffer(chunk)) {
if (!this.get('Content-Type')) {
this.type('bin');
}
} else {
return this.json(chunk);
}
break;
}
// write strings in utf-8
if (typeof chunk === 'string') {
encoding = 'utf8';
type = this.get('Content-Type');
// reflect this in content-type
if (typeof type === 'string') {
this.set('Content-Type', setCharset(type, 'utf-8'));
}
}
// determine if ETag should be generated
var etagFn = app.get('etag fn')
var generateETag = !this.get('ETag') && typeof etagFn === 'function'
// populate Content-Length
var len
if (chunk !== undefined) {
if (Buffer.isBuffer(chunk)) {
// get length of Buffer
len = chunk.length
} else if (!generateETag && chunk.length < 1000) {
// just calculate length when no ETag + small chunk
len = Buffer.byteLength(chunk, encoding)
} else {
// convert chunk to Buffer and calculate
chunk = Buffer.from(chunk, encoding)
encoding = undefined;
len = chunk.length
}
this.set('Content-Length', len);
}
// populate ETag
var etag;
if (generateETag && len !== undefined) {
if ((etag = etagFn(chunk, encoding))) {
this.set('ETag', etag);
}
}
// freshness
if (req.fresh) this.statusCode = 304;
// strip irrelevant headers
if (204 === this.statusCode || 304 === this.statusCode) {
this.removeHeader('Content-Type');
this.removeHeader('Content-Length');
this.removeHeader('Transfer-Encoding');
chunk = '';
}
if (req.method === 'HEAD') {
// skip body for HEAD
this.end();
} else {
// respond
this.end(chunk, encoding);
}
return this;
};
/**
* Send JSON response.
*
* Examples:
*
* res.json(null);
* res.json({ user: 'tj' });
*
* @param {string|number|boolean|object} obj
* @public
*/
res.json = function json(obj) {
var val = obj;
// allow status / body
if (arguments.length === 2) {
// res.json(body, status) backwards compat
if (typeof arguments[1] === 'number') {
deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');
this.statusCode = arguments[1];
} else {
deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
this.statusCode = arguments[0];
val = arguments[1];
}
}
// settings
var app = this.app;
var escape = app.get('json escape')
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = stringify(val, replacer, spaces, escape)
// content-type
if (!this.get('Content-Type')) {
this.set('Content-Type', 'application/json');
}
return this.send(body);
};
/**
* Send JSON response with JSONP callback support.
*
* Examples:
*
* res.jsonp(null);
* res.jsonp({ user: 'tj' });
*
* @param {string|number|boolean|object} obj
* @public
*/
res.jsonp = function jsonp(obj) {
var val = obj;
// allow status / body
if (arguments.length === 2) {
// res.jsonp(body, status) backwards compat
if (typeof arguments[1] === 'number') {
deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead');
this.statusCode = arguments[1];
} else {
deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');
this.statusCode = arguments[0];
val = arguments[1];
}
}
// settings
var app = this.app;
var escape = app.get('json escape')
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = stringify(val, replacer, spaces, escape)
var callback = this.req.query[app.get('jsonp callback name')];
// content-type
if (!this.get('Content-Type')) {
this.set('X-Content-Type-Options', 'nosniff');
this.set('Content-Type', 'application/json');
}
// fixup callback
if (Array.isArray(callback)) {
callback = callback[0];
}
// jsonp
if (typeof callback === 'string' && callback.length !== 0) {
this.set('X-Content-Type-Options', 'nosniff');
this.set('Content-Type', 'text/javascript');
// restrict callback charset
callback = callback.replace(/[^\[\]\w$.]/g, '');
if (body === undefined) {
// empty argument
body = ''
} else if (typeof body === 'string') {
// replace chars not allowed in JavaScript that are in JSON
body = body
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
// the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
// the typeof check is just to reduce client error noise
body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
}
return this.send(body);
};
/**
* Send given HTTP status code.
*
* Sets the response status to `statusCode` and the body of the
* response to the standard description from node's http.STATUS_CODES
* or the statusCode number if no description.
*
* Examples:
*
* res.sendStatus(200);
*
* @param {number} statusCode
* @public
*/
res.sendStatus = function sendStatus(statusCode) {
var body = statuses[statusCode] || String(statusCode)
this.statusCode = statusCode;
this.type('txt');
return this.send(body);
};
/**
* Transfer the file at the given `path`.
*
* Automatically sets the _Content-Type_ response header field.
* The callback `callback(err)` is invoked when the transfer is complete
* or when an error occurs. Be sure to check `res.headersSent`
* if you wish to attempt responding, as the header and some data
* may have already been transferred.
*
* Options:
*
* - `maxAge` defaulting to 0 (can be string converted by `ms`)
* - `root` root directory for relative filenames
* - `headers` object of headers to serve with file
* - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
*
* Other options are passed along to `send`.
*
* Examples:
*
* The following example illustrates how `res.sendFile()` may
* be used as an alternative for the `static()` middleware for
* dynamic situations. The code backing `res.sendFile()` is actually
* the same code, so HTTP cache support etc is identical.
*
* app.get('/user/:uid/photos/:file', function(req, res){
* var uid = req.params.uid
* , file = req.params.file;
*
* req.user.mayViewFilesFrom(uid, function(yes){
* if (yes) {
* res.sendFile('/uploads/' + uid + '/' + file);
* } else {
* res.send(403, 'Sorry! you cant see that.');
* }
* });
* });
*
* @public
*/
res.sendFile = function sendFile(path, options, callback) {
var done = callback;
var req = this.req;
var res = this;
var next = req.next;
var opts = options || {};
if (!path) {
throw new TypeError('path argument is required to res.sendFile');
}
if (typeof path !== 'string') {
throw new TypeError('path must be a string to res.sendFile')
}
// support function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
if (!opts.root && !isAbsolute(path)) {
throw new TypeError('path must be absolute or specify root to res.sendFile');
}
// create file stream
var pathname = encodeURI(path);
var file = send(req, pathname, opts);
// transfer
sendfile(res, file, opts, function (err) {
if (done) return done(err);
if (err && err.code === 'EISDIR') return next();
// next() all but write errors
if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
next(err);
}
});
};
/**
* Transfer the file at the given `path`.
*
* Automatically sets the _Content-Type_ response header field.
* The callback `callback(err)` is invoked when the transfer is complete
* or when an error occurs. Be sure to check `res.headersSent`
* if you wish to attempt responding, as the header and some data
* may have already been transferred.
*
* Options:
*
* - `maxAge` defaulting to 0 (can be string converted by `ms`)
* - `root` root directory for relative filenames
* - `headers` object of headers to serve with file
* - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
*
* Other options are passed along to `send`.
*
* Examples:
*
* The following example illustrates how `res.sendfile()` may
* be used as an alternative for the `static()` middleware for
* dynamic situations. The code backing `res.sendfile()` is actually
* the same code, so HTTP cache support etc is identical.
*
* app.get('/user/:uid/photos/:file', function(req, res){
* var uid = req.params.uid
* , file = req.params.file;
*
* req.user.mayViewFilesFrom(uid, function(yes){
* if (yes) {
* res.sendfile('/uploads/' + uid + '/' + file);
* } else {
* res.send(403, 'Sorry! you cant see that.');
* }
* });
* });
*
* @public
*/
res.sendfile = function (path, options, callback) {
var done = callback;
var req = this.req;
var res = this;
var next = req.next;
var opts = options || {};
// support function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
// create file stream
var file = send(req, path, opts);
// transfer
sendfile(res, file, opts, function (err) {
if (done) return done(err);
if (err && err.code === 'EISDIR') return next();
// next() all but write errors
if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
next(err);
}
});
};
res.sendfile = deprecate.function(res.sendfile,
'res.sendfile: Use res.sendFile instead');
/**
* Transfer the file at the given `path` as an attachment.
*
* Optionally providing an alternate attachment `filename`,
* and optional callback `callback(err)`. The callback is invoked
* when the data transfer is complete, or when an error has
* occurred. Be sure to check `res.headersSent` if you plan to respond.
*
* Optionally providing an `options` object to use with `res.sendFile()`.
* This function will set the `Content-Disposition` header, overriding
* any `Content-Disposition` header passed as header options in order
* to set the attachment and filename.
*
* This method uses `res.sendFile()`.
*
* @public
*/
res.download = function download (path, filename, options, callback) {
var done = callback;
var name = filename;
var opts = options || null
// support function as second or third arg
if (typeof filename === 'function') {
done = filename;
name = null;
opts = null
} else if (typeof options === 'function') {
done = options
opts = null
}
// set Content-Disposition when file is sent
var headers = {
'Content-Disposition': contentDisposition(name || path)
};
// merge user-provided headers
if (opts && opts.headers) {
var keys = Object.keys(opts.headers)
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
if (key.toLowerCase() !== 'content-disposition') {
headers[key] = opts.headers[key]
}
}
}
// merge user-provided options
opts = Object.create(opts)
opts.headers = headers
// Resolve the full path for sendFile
var fullPath = resolve(path);
// send file
return this.sendFile(fullPath, opts, done)
};
/**
* Set _Content-Type_ response header with `type` through `mime.lookup()`
* when it does not contain "/", or set the Content-Type to `type` otherwise.
*
* Examples:
*
* res.type('.html');
* res.type('html');
* res.type('json');
* res.type('application/json');
* res.type('png');
*
* @param {String} type
* @return {ServerResponse} for chaining
* @public
*/
res.contentType =
res.type = function contentType(type) {
var ct = type.indexOf('/') === -1
? mime.lookup(type)
: type;
return this.set('Content-Type', ct);
};
/**
* Respond to the Acceptable formats using an `obj`
* of mime-type callbacks.
*
* This method uses `req.accepted`, an array of
* acceptable types ordered by their quality values.
* When "Accept" is not present the _first_ callback
* is invoked, otherwise the first match is used. When
* no match is performed the server responds with
* 406 "Not Acceptable".
*
* Content-Type is set for you, however if you choose
* you may alter this within the callback using `res.type()`
* or `res.set('Content-Type', ...)`.
*
* res.format({
* 'text/plain': function(){
* res.send('hey');
* },
*
* 'text/html': function(){
* res.send('<p>hey</p>');
* },
*
* 'application/json': function () {
* res.send({ message: 'hey' });
* }
* });
*
* In addition to canonicalized MIME types you may
* also use extnames mapped to these types:
*
* res.format({
* text: function(){
* res.send('hey');
* },
*
* html: function(){
* res.send('<p>hey</p>');
* },
*
* json: function(){
* res.send({ message: 'hey' });
* }
* });
*
* By default Express passes an `Error`
* with a `.status` of 406 to `next(err)`
* if a match is not made. If you provide
* a `.default` callback it will be invoked
* instead.
*
* @param {Object} obj
* @return {ServerResponse} for chaining
* @public
*/
res.format = function(obj){
var req = this.req;
var next = req.next;
var fn = obj.default;
if (fn) delete obj.default;
var keys = Object.keys(obj);
var key = keys.length > 0
? req.accepts(keys)
: false;
this.vary("Accept");
if (key) {
this.set('Content-Type', normalizeType(key).value);
obj[key](req, this, next);
} else if (fn) {
fn();
} else {
var err = new Error('Not Acceptable');
err.status = err.statusCode = 406;
err.types = normalizeTypes(keys).map(function(o){ return o.value });
next(err);
}
return this;
};
/**
* Set _Content-Disposition_ header to _attachment_ with optional `filename`.
*
* @param {String} filename
* @return {ServerResponse}
* @public
*/
res.attachment = function attachment(filename) {
if (filename) {
this.type(extname(filename));
}
this.set('Content-Disposition', contentDisposition(filename));
return this;
};
/**
* Append additional header `field` with value `val`.
*
* Example:
*
* res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
* res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
* res.append('Warning', '199 Miscellaneous warning');
*
* @param {String} field
* @param {String|Array} val
* @return {ServerResponse} for chaining
* @public
*/
res.append = function append(field, val) {
var prev = this.get(field);
var value = val;
if (prev) {
// concat the new and prev vals
value = Array.isArray(prev) ? prev.concat(val)
: Array.isArray(val) ? [prev].concat(val)
: [prev, val]
}
return this.set(field, value);
};
/**
* Set header `field` to `val`, or pass
* an object of header fields.
*
* Examples:
*
* res.set('Foo', ['bar', 'baz']);
* res.set('Accept', 'application/json');
* res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
*
* Aliased as `res.header()`.
*
* @param {String|Object} field
* @param {String|Array} val
* @return {ServerResponse} for chaining
* @public
*/
res.set =
res.header = function header(field, val) {
if (arguments.length === 2) {
var value = Array.isArray(val)
? val.map(String)
: String(val);
// add charset to content-type
if (field.toLowerCase() === 'content-type') {
if (Array.isArray(value)) {
throw new TypeError('Content-Type cannot be set to an Array');
}
if (!charsetRegExp.test(value)) {
var charset = mime.charsets.lookup(value.split(';')[0]);
if (charset) value += '; charset=' + charset.toLowerCase();
}
}
this.setHeader(field, value);
} else {
for (var key in field) {
this.set(key, field[key]);
}
}
return this;
};
/**
* Get value for header `field`.
*
* @param {String} field
* @return {String}
* @public
*/
res.get = function(field){
return this.getHeader(field);
};
/**
* Clear cookie `name`.
*
* @param {String} name
* @param {Object} [options]
* @return {ServerResponse} for chaining
* @public
*/
res.clearCookie = function clearCookie(name, options) {
var opts = merge({ expires: new Date(1), path: '/' }, options);
return this.cookie(name, '', opts);
};
/**
* Set cookie `name` to `value`, with the given `options`.
*
* Options:
*
* - `maxAge` max-age in milliseconds, converted to `expires`
* - `signed` sign the cookie
* - `path` defaults to "/"
*
* Examples:
*
* // "Remember Me" for 15 minutes
* res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
*
* // same as above
* res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
*
* @param {String} name
* @param {String|Object} value
* @param {Object} [options]
* @return {ServerResponse} for chaining
* @public
*/
res.cookie = function (name, value, options) {
var opts = merge({}, options);
var secret = this.req.secret;
var signed = opts.signed;
if (signed && !secret) {
throw new Error('cookieParser("secret") required for signed cookies');
}
var val = typeof value === 'object'
? 'j:' + JSON.stringify(value)
: String(value);
if (signed) {
val = 's:' + sign(val, secret);
}
if ('maxAge' in opts) {
opts.expires = new Date(Date.now() + opts.maxAge);
opts.maxAge /= 1000;
}
if (opts.path == null) {
opts.path = '/';
}
this.append('Set-Cookie', cookie.serialize(name, String(val), opts));
return this;
};
/**
* Set the location header to `url`.
*
* The given `url` can also be "back", which redirects
* to the _Referrer_ or _Referer_ headers or "/".
*
* Examples:
*
* res.location('/foo/bar').;
* res.location('http://example.com');
* res.location('../login');
*
* @param {String} url
* @return {ServerResponse} for chaining
* @public
*/
res.location = function location(url) {
var loc = url;
// "back" is an alias for the referrer
if (url === 'back') {
loc = this.req.get('Referrer') || '/';
}
// set location
return this.set('Location', encodeUrl(loc));
};
/**
* Redirect to the given `url` with optional response `status`
* defaulting to 302.
*
* The resulting `url` is determined by `res.location()`, so
* it will play nicely with mounted apps, relative paths,
* `"back"` etc.
*
* Examples:
*
* res.redirect('/foo/bar');
* res.redirect('http://example.com');
* res.redirect(301, 'http://example.com');
* res.redirect('../login'); // /blog/post/1 -> /blog/login
*
* @public
*/
res.redirect = function redirect(url) {
var address = url;
var body;
var status = 302;
// allow status / url
if (arguments.length === 2) {
if (typeof arguments[0] === 'number') {
status = arguments[0];
address = arguments[1];
} else {
deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');
status = arguments[1];
}
}
// Set location header
address = this.location(address).get('Location');
// Support text/{plain,html} by default
this.format({
text: function(){
body = statuses[status] + '. Redirecting to ' + address
},
html: function(){
var u = escapeHtml(address);
body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'
},
default: function(){
body = '';
}
});
// Respond
this.statusCode = status;
this.set('Content-Length', Buffer.byteLength(body));
if (this.req.method === 'HEAD') {
this.end();
} else {
this.end(body);
}
};
/**
* Add `field` to Vary. If already present in the Vary set, then
* this call is simply ignored.
*
* @param {Array|String} field
* @return {ServerResponse} for chaining
* @public
*/
res.vary = function(field){
// checks for back-compat
if (!field || (Array.isArray(field) && !field.length)) {
deprecate('res.vary(): Provide a field name');
return this;
}
vary(this, field);
return this;
};
/**
* Render `view` with the given `options` and optional callback `fn`.
* When a callback function is given a response will _not_ be made
* automatically, otherwise a response of _200_ and _text/html_ is given.
*
* Options:
*
* - `cache` boolean hinting to the engine it should cache
* - `filename` filename of the view being rendered
*
* @public
*/
res.render = function render(view, options, callback) {
var app = this.req.app;
var done = callback;
var opts = options || {};
var req = this.req;
var self = this;
// support callback function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
// merge res.locals
opts._locals = self.locals;
// default callback to respond
done = done || function (err, str) {
if (err) return req.next(err);
self.send(str);
};
// render
app.render(view, opts, done);
};
// pipe the send file stream
function sendfile(res, file, options, callback) {
var done = false;
var streaming;
// request aborted
function onaborted() {
if (done) return;
done = true;
var err = new Error('Request aborted');
err.code = 'ECONNABORTED';
callback(err);
}
// directory
function ondirectory() {
if (done) return;
done = true;
var err = new Error('EISDIR, read');
err.code = 'EISDIR';
callback(err);
}
// errors
function onerror(err) {
if (done) return;
done = true;
callback(err);
}
// ended
function onend() {
if (done) return;
done = true;
callback();
}
// file
function onfile() {
streaming = false;
}
// finished
function onfinish(err) {
if (err && err.code === 'ECONNRESET') return onaborted();
if (err) return onerror(err);
if (done) return;
setImmediate(function () {
if (streaming !== false && !done) {
onaborted();
return;
}
if (done) return;
done = true;
callback();
});
}
// streaming
function onstream() {
streaming = true;
}
file.on('directory', ondirectory);
file.on('end', onend);
file.on('error', onerror);
file.on('file', onfile);
file.on('stream', onstream);
onFinished(res, onfinish);
if (options.headers) {
// set headers on successful transfer
file.on('headers', function headers(res) {
var obj = options.headers;
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
res.setHeader(k, obj[k]);
}
});
}
// pipe
file.pipe(res);
}
/**
* Stringify JSON, like JSON.stringify, but v8 optimized, with the
* ability to escape characters that can trigger HTML sniffing.
*
* @param {*} value
* @param {function} replaces
* @param {number} spaces
* @param {boolean} escape
* @returns {string}
* @private
*/
function stringify (value, replacer, spaces, escape) {
// v8 checks arguments.length for optimizing simple call
// https://bugs.chromium.org/p/v8/issues/detail?id=4730
var json = replacer || spaces
? JSON.stringify(value, replacer, spaces)
: JSON.stringify(value);
if (escape && typeof json === 'string') {
json = json.replace(/[<>&]/g, function (c) {
switch (c.charCodeAt(0)) {
case 0x3c:
return '\\u003c'
case 0x3e:
return '\\u003e'
case 0x26:
return '\\u0026'
/* istanbul ignore next: unreachable default */
default:
return c
}
})
}
return json
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/middleware/query.js | aws/lti-middleware/node_modules/express/lib/middleware/query.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var merge = require('utils-merge')
var parseUrl = require('parseurl');
var qs = require('qs');
/**
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function query(options) {
var opts = merge({}, options)
var queryparse = qs.parse;
if (typeof options === 'function') {
queryparse = options;
opts = undefined;
}
if (opts !== undefined && opts.allowPrototypes === undefined) {
// back-compat for qs module
opts.allowPrototypes = true;
}
return function query(req, res, next){
if (!req.query) {
var val = parseUrl(req).query;
req.query = queryparse(val, opts);
}
next();
};
};
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/middleware/init.js | aws/lti-middleware/node_modules/express/lib/middleware/init.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var setPrototypeOf = require('setprototypeof')
/**
* Initialization middleware, exposing the
* request and response to each other, as well
* as defaulting the X-Powered-By header field.
*
* @param {Function} app
* @return {Function}
* @api private
*/
exports.init = function(app){
return function expressInit(req, res, next){
if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express');
req.res = res;
res.req = req;
req.next = next;
setPrototypeOf(req, app.request)
setPrototypeOf(res, app.response)
res.locals = res.locals || Object.create(null);
next();
};
};
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/router/route.js | aws/lti-middleware/node_modules/express/lib/router/route.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var debug = require('debug')('express:router:route');
var flatten = require('array-flatten');
var Layer = require('./layer');
var methods = require('methods');
/**
* Module variables.
* @private
*/
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
/**
* Module exports.
* @public
*/
module.exports = Route;
/**
* Initialize `Route` with the given `path`,
*
* @param {String} path
* @public
*/
function Route(path) {
this.path = path;
this.stack = [];
debug('new %o', path)
// route handlers for various http methods
this.methods = {};
}
/**
* Determine if the route handles a given method.
* @private
*/
Route.prototype._handles_method = function _handles_method(method) {
if (this.methods._all) {
return true;
}
var name = method.toLowerCase();
if (name === 'head' && !this.methods['head']) {
name = 'get';
}
return Boolean(this.methods[name]);
};
/**
* @return {Array} supported HTTP methods
* @private
*/
Route.prototype._options = function _options() {
var methods = Object.keys(this.methods);
// append automatic head
if (this.methods.get && !this.methods.head) {
methods.push('head');
}
for (var i = 0; i < methods.length; i++) {
// make upper case
methods[i] = methods[i].toUpperCase();
}
return methods;
};
/**
* dispatch req, res into this route
* @private
*/
Route.prototype.dispatch = function dispatch(req, res, done) {
var idx = 0;
var stack = this.stack;
if (stack.length === 0) {
return done();
}
var method = req.method.toLowerCase();
if (method === 'head' && !this.methods['head']) {
method = 'get';
}
req.route = this;
next();
function next(err) {
// signal to exit route
if (err && err === 'route') {
return done();
}
// signal to exit router
if (err && err === 'router') {
return done(err)
}
var layer = stack[idx++];
if (!layer) {
return done(err);
}
if (layer.method && layer.method !== method) {
return next(err);
}
if (err) {
layer.handle_error(err, req, res, next);
} else {
layer.handle_request(req, res, next);
}
}
};
/**
* Add a handler for all HTTP verbs to this route.
*
* Behaves just like middleware and can respond or call `next`
* to continue processing.
*
* You can use multiple `.all` call to add multiple handlers.
*
* function check_something(req, res, next){
* next();
* };
*
* function validate_user(req, res, next){
* next();
* };
*
* route
* .all(validate_user)
* .all(check_something)
* .get(function(req, res, next){
* res.send('hello world');
* });
*
* @param {function} handler
* @return {Route} for chaining
* @api public
*/
Route.prototype.all = function all() {
var handles = flatten(slice.call(arguments));
for (var i = 0; i < handles.length; i++) {
var handle = handles[i];
if (typeof handle !== 'function') {
var type = toString.call(handle);
var msg = 'Route.all() requires a callback function but got a ' + type
throw new TypeError(msg);
}
var layer = Layer('/', {}, handle);
layer.method = undefined;
this.methods._all = true;
this.stack.push(layer);
}
return this;
};
methods.forEach(function(method){
Route.prototype[method] = function(){
var handles = flatten(slice.call(arguments));
for (var i = 0; i < handles.length; i++) {
var handle = handles[i];
if (typeof handle !== 'function') {
var type = toString.call(handle);
var msg = 'Route.' + method + '() requires a callback function but got a ' + type
throw new Error(msg);
}
debug('%s %o', method, this.path)
var layer = Layer('/', {}, handle);
layer.method = method;
this.methods[method] = true;
this.stack.push(layer);
}
return this;
};
});
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/router/index.js | aws/lti-middleware/node_modules/express/lib/router/index.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var Route = require('./route');
var Layer = require('./layer');
var methods = require('methods');
var mixin = require('utils-merge');
var debug = require('debug')('express:router');
var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var parseUrl = require('parseurl');
var setPrototypeOf = require('setprototypeof')
/**
* Module variables.
* @private
*/
var objectRegExp = /^\[object (\S+)\]$/;
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
/**
* Initialize a new `Router` with the given `options`.
*
* @param {Object} [options]
* @return {Router} which is an callable function
* @public
*/
var proto = module.exports = function(options) {
var opts = options || {};
function router(req, res, next) {
router.handle(req, res, next);
}
// mixin Router class functions
setPrototypeOf(router, proto)
router.params = {};
router._params = [];
router.caseSensitive = opts.caseSensitive;
router.mergeParams = opts.mergeParams;
router.strict = opts.strict;
router.stack = [];
return router;
};
/**
* Map the given param placeholder `name`(s) to the given callback.
*
* Parameter mapping is used to provide pre-conditions to routes
* which use normalized placeholders. For example a _:user_id_ parameter
* could automatically load a user's information from the database without
* any additional code,
*
* The callback uses the same signature as middleware, the only difference
* being that the value of the placeholder is passed, in this case the _id_
* of the user. Once the `next()` function is invoked, just like middleware
* it will continue on to execute the route, or subsequent parameter functions.
*
* Just like in middleware, you must either respond to the request or call next
* to avoid stalling the request.
*
* app.param('user_id', function(req, res, next, id){
* User.find(id, function(err, user){
* if (err) {
* return next(err);
* } else if (!user) {
* return next(new Error('failed to load user'));
* }
* req.user = user;
* next();
* });
* });
*
* @param {String} name
* @param {Function} fn
* @return {app} for chaining
* @public
*/
proto.param = function param(name, fn) {
// param logic
if (typeof name === 'function') {
deprecate('router.param(fn): Refactor to use path params');
this._params.push(name);
return;
}
// apply param functions
var params = this._params;
var len = params.length;
var ret;
if (name[0] === ':') {
deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead');
name = name.substr(1);
}
for (var i = 0; i < len; ++i) {
if (ret = params[i](name, fn)) {
fn = ret;
}
}
// ensure we end up with a
// middleware function
if ('function' !== typeof fn) {
throw new Error('invalid param() call for ' + name + ', got ' + fn);
}
(this.params[name] = this.params[name] || []).push(fn);
return this;
};
/**
* Dispatch a req, res into the router.
* @private
*/
proto.handle = function handle(req, res, out) {
var self = this;
debug('dispatching %s %s', req.method, req.url);
var idx = 0;
var protohost = getProtohost(req.url) || ''
var removed = '';
var slashAdded = false;
var paramcalled = {};
// store options for OPTIONS request
// only used if OPTIONS request
var options = [];
// middleware and routes
var stack = self.stack;
// manage inter-router variables
var parentParams = req.params;
var parentUrl = req.baseUrl || '';
var done = restore(out, req, 'baseUrl', 'next', 'params');
// setup next layer
req.next = next;
// for options requests, respond with a default if nothing else responds
if (req.method === 'OPTIONS') {
done = wrap(done, function(old, err) {
if (err || options.length === 0) return old(err);
sendOptionsResponse(res, options, old);
});
}
// setup basic req values
req.baseUrl = parentUrl;
req.originalUrl = req.originalUrl || req.url;
next();
function next(err) {
var layerError = err === 'route'
? null
: err;
// remove added slash
if (slashAdded) {
req.url = req.url.substr(1);
slashAdded = false;
}
// restore altered req.url
if (removed.length !== 0) {
req.baseUrl = parentUrl;
req.url = protohost + removed + req.url.substr(protohost.length);
removed = '';
}
// signal to exit router
if (layerError === 'router') {
setImmediate(done, null)
return
}
// no more matching layers
if (idx >= stack.length) {
setImmediate(done, layerError);
return;
}
// get pathname of request
var path = getPathname(req);
if (path == null) {
return done(layerError);
}
// find next matching layer
var layer;
var match;
var route;
while (match !== true && idx < stack.length) {
layer = stack[idx++];
match = matchLayer(layer, path);
route = layer.route;
if (typeof match !== 'boolean') {
// hold on to layerError
layerError = layerError || match;
}
if (match !== true) {
continue;
}
if (!route) {
// process non-route handlers normally
continue;
}
if (layerError) {
// routes do not match with a pending error
match = false;
continue;
}
var method = req.method;
var has_method = route._handles_method(method);
// build up automatic options response
if (!has_method && method === 'OPTIONS') {
appendMethods(options, route._options());
}
// don't even bother matching route
if (!has_method && method !== 'HEAD') {
match = false;
continue;
}
}
// no match
if (match !== true) {
return done(layerError);
}
// store route for dispatch on change
if (route) {
req.route = route;
}
// Capture one-time layer values
req.params = self.mergeParams
? mergeParams(layer.params, parentParams)
: layer.params;
var layerPath = layer.path;
// this should be done for the layer
self.process_params(layer, paramcalled, req, res, function (err) {
if (err) {
return next(layerError || err);
}
if (route) {
return layer.handle_request(req, res, next);
}
trim_prefix(layer, layerError, layerPath, path);
});
}
function trim_prefix(layer, layerError, layerPath, path) {
if (layerPath.length !== 0) {
// Validate path is a prefix match
if (layerPath !== path.substr(0, layerPath.length)) {
next(layerError)
return
}
// Validate path breaks on a path separator
var c = path[layerPath.length]
if (c && c !== '/' && c !== '.') return next(layerError)
// Trim off the part of the url that matches the route
// middleware (.use stuff) needs to have the path stripped
debug('trim prefix (%s) from url %s', layerPath, req.url);
removed = layerPath;
req.url = protohost + req.url.substr(protohost.length + removed.length);
// Ensure leading slash
if (!protohost && req.url[0] !== '/') {
req.url = '/' + req.url;
slashAdded = true;
}
// Setup base URL (no trailing slash)
req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'
? removed.substring(0, removed.length - 1)
: removed);
}
debug('%s %s : %s', layer.name, layerPath, req.originalUrl);
if (layerError) {
layer.handle_error(layerError, req, res, next);
} else {
layer.handle_request(req, res, next);
}
}
};
/**
* Process any parameters for the layer.
* @private
*/
proto.process_params = function process_params(layer, called, req, res, done) {
var params = this.params;
// captured parameters from the layer, keys and values
var keys = layer.keys;
// fast track
if (!keys || keys.length === 0) {
return done();
}
var i = 0;
var name;
var paramIndex = 0;
var key;
var paramVal;
var paramCallbacks;
var paramCalled;
// process params in order
// param callbacks can be async
function param(err) {
if (err) {
return done(err);
}
if (i >= keys.length ) {
return done();
}
paramIndex = 0;
key = keys[i++];
name = key.name;
paramVal = req.params[name];
paramCallbacks = params[name];
paramCalled = called[name];
if (paramVal === undefined || !paramCallbacks) {
return param();
}
// param previously called with same value or error occurred
if (paramCalled && (paramCalled.match === paramVal
|| (paramCalled.error && paramCalled.error !== 'route'))) {
// restore value
req.params[name] = paramCalled.value;
// next param
return param(paramCalled.error);
}
called[name] = paramCalled = {
error: null,
match: paramVal,
value: paramVal
};
paramCallback();
}
// single param callbacks
function paramCallback(err) {
var fn = paramCallbacks[paramIndex++];
// store updated value
paramCalled.value = req.params[key.name];
if (err) {
// store error
paramCalled.error = err;
param(err);
return;
}
if (!fn) return param();
try {
fn(req, res, paramCallback, paramVal, key.name);
} catch (e) {
paramCallback(e);
}
}
param();
};
/**
* Use the given middleware function, with optional path, defaulting to "/".
*
* Use (like `.all`) will run for any http METHOD, but it will not add
* handlers for those methods so OPTIONS requests will not consider `.use`
* functions even if they could respond.
*
* The other difference is that _route_ path is stripped and not visible
* to the handler function. The main effect of this feature is that mounted
* handlers can operate without any code changes regardless of the "prefix"
* pathname.
*
* @public
*/
proto.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate router.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var callbacks = flatten(slice.call(arguments, offset));
if (callbacks.length === 0) {
throw new TypeError('Router.use() requires a middleware function')
}
for (var i = 0; i < callbacks.length; i++) {
var fn = callbacks[i];
if (typeof fn !== 'function') {
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
}
// add the middleware
debug('use %o %s', path, fn.name || '<anonymous>')
var layer = new Layer(path, {
sensitive: this.caseSensitive,
strict: false,
end: false
}, fn);
layer.route = undefined;
this.stack.push(layer);
}
return this;
};
/**
* Create a new Route for the given path.
*
* Each route contains a separate middleware stack and VERB handlers.
*
* See the Route api documentation for details on adding handlers
* and middleware to routes.
*
* @param {String} path
* @return {Route}
* @public
*/
proto.route = function route(path) {
var route = new Route(path);
var layer = new Layer(path, {
sensitive: this.caseSensitive,
strict: this.strict,
end: true
}, route.dispatch.bind(route));
layer.route = route;
this.stack.push(layer);
return route;
};
// create Router#VERB functions
methods.concat('all').forEach(function(method){
proto[method] = function(path){
var route = this.route(path)
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
// append methods to a list of methods
function appendMethods(list, addition) {
for (var i = 0; i < addition.length; i++) {
var method = addition[i];
if (list.indexOf(method) === -1) {
list.push(method);
}
}
}
// get pathname of request
function getPathname(req) {
try {
return parseUrl(req).pathname;
} catch (err) {
return undefined;
}
}
// Get get protocol + host for a URL
function getProtohost(url) {
if (typeof url !== 'string' || url.length === 0 || url[0] === '/') {
return undefined
}
var searchIndex = url.indexOf('?')
var pathLength = searchIndex !== -1
? searchIndex
: url.length
var fqdnIndex = url.substr(0, pathLength).indexOf('://')
return fqdnIndex !== -1
? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
: undefined
}
// get type for error message
function gettype(obj) {
var type = typeof obj;
if (type !== 'object') {
return type;
}
// inspect [[Class]] for objects
return toString.call(obj)
.replace(objectRegExp, '$1');
}
/**
* Match path to a layer.
*
* @param {Layer} layer
* @param {string} path
* @private
*/
function matchLayer(layer, path) {
try {
return layer.match(path);
} catch (err) {
return err;
}
}
// merge params with parent params
function mergeParams(params, parent) {
if (typeof parent !== 'object' || !parent) {
return params;
}
// make copy of parent for base
var obj = mixin({}, parent);
// simple non-numeric merging
if (!(0 in params) || !(0 in parent)) {
return mixin(obj, params);
}
var i = 0;
var o = 0;
// determine numeric gaps
while (i in params) {
i++;
}
while (o in parent) {
o++;
}
// offset numeric indices in params before merge
for (i--; i >= 0; i--) {
params[i + o] = params[i];
// create holes for the merge when necessary
if (i < o) {
delete params[i];
}
}
return mixin(obj, params);
}
// restore obj props after function
function restore(fn, obj) {
var props = new Array(arguments.length - 2);
var vals = new Array(arguments.length - 2);
for (var i = 0; i < props.length; i++) {
props[i] = arguments[i + 2];
vals[i] = obj[props[i]];
}
return function () {
// restore vals
for (var i = 0; i < props.length; i++) {
obj[props[i]] = vals[i];
}
return fn.apply(this, arguments);
};
}
// send an OPTIONS response
function sendOptionsResponse(res, options, next) {
try {
var body = options.join(',');
res.set('Allow', body);
res.send(body);
} catch (err) {
next(err);
}
}
// wrap a function
function wrap(old, fn) {
return function proxy() {
var args = new Array(arguments.length + 1);
args[0] = old;
for (var i = 0, len = arguments.length; i < len; i++) {
args[i + 1] = arguments[i];
}
fn.apply(this, args);
};
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/express/lib/router/layer.js | aws/lti-middleware/node_modules/express/lib/router/layer.js | /*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var pathRegexp = require('path-to-regexp');
var debug = require('debug')('express:router:layer');
/**
* Module variables.
* @private
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Module exports.
* @public
*/
module.exports = Layer;
function Layer(path, options, fn) {
if (!(this instanceof Layer)) {
return new Layer(path, options, fn);
}
debug('new %o', path)
var opts = options || {};
this.handle = fn;
this.name = fn.name || '<anonymous>';
this.params = undefined;
this.path = undefined;
this.regexp = pathRegexp(path, this.keys = [], opts);
// set fast path flags
this.regexp.fast_star = path === '*'
this.regexp.fast_slash = path === '/' && opts.end === false
}
/**
* Handle the error for the layer.
*
* @param {Error} error
* @param {Request} req
* @param {Response} res
* @param {function} next
* @api private
*/
Layer.prototype.handle_error = function handle_error(error, req, res, next) {
var fn = this.handle;
if (fn.length !== 4) {
// not a standard error handler
return next(error);
}
try {
fn(error, req, res, next);
} catch (err) {
next(err);
}
};
/**
* Handle the request for the layer.
*
* @param {Request} req
* @param {Response} res
* @param {function} next
* @api private
*/
Layer.prototype.handle_request = function handle(req, res, next) {
var fn = this.handle;
if (fn.length > 3) {
// not a standard request handler
return next();
}
try {
fn(req, res, next);
} catch (err) {
next(err);
}
};
/**
* Check if this route matches `path`, if so
* populate `.params`.
*
* @param {String} path
* @return {Boolean}
* @api private
*/
Layer.prototype.match = function match(path) {
var match
if (path != null) {
// fast path non-ending match for / (any path matches)
if (this.regexp.fast_slash) {
this.params = {}
this.path = ''
return true
}
// fast path for * (everything matched in a param)
if (this.regexp.fast_star) {
this.params = {'0': decode_param(path)}
this.path = path
return true
}
// match the path
match = this.regexp.exec(path)
}
if (!match) {
this.params = undefined;
this.path = undefined;
return false;
}
// store values
this.params = {};
this.path = match[0]
var keys = this.keys;
var params = this.params;
for (var i = 1; i < match.length; i++) {
var key = keys[i - 1];
var prop = key.name;
var val = decode_param(match[i])
if (val !== undefined || !(hasOwnProperty.call(params, prop))) {
params[prop] = val;
}
}
return true;
};
/**
* Decode param value.
*
* @param {string} val
* @return {string}
* @private
*/
function decode_param(val) {
if (typeof val !== 'string' || val.length === 0) {
return val;
}
try {
return decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
err.message = 'Failed to decode param \'' + val + '\'';
err.status = err.statusCode = 400;
}
throw err;
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/bytes/index.js | aws/lti-middleware/node_modules/bytes/index.js | /*!
* bytes
* Copyright(c) 2012-2014 TJ Holowaychuk
* Copyright(c) 2015 Jed Watson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
* @public
*/
module.exports = bytes;
module.exports.format = format;
module.exports.parse = parse;
/**
* Module variables.
* @private
*/
var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
var map = {
b: 1,
kb: 1 << 10,
mb: 1 << 20,
gb: 1 << 30,
tb: Math.pow(1024, 4),
pb: Math.pow(1024, 5),
};
var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
/**
* Convert the given value in bytes into a string or parse to string to an integer in bytes.
*
* @param {string|number} value
* @param {{
* case: [string],
* decimalPlaces: [number]
* fixedDecimals: [boolean]
* thousandsSeparator: [string]
* unitSeparator: [string]
* }} [options] bytes options.
*
* @returns {string|number|null}
*/
function bytes(value, options) {
if (typeof value === 'string') {
return parse(value);
}
if (typeof value === 'number') {
return format(value, options);
}
return null;
}
/**
* Format the given value in bytes into a string.
*
* If the value is negative, it is kept as such. If it is a float,
* it is rounded.
*
* @param {number} value
* @param {object} [options]
* @param {number} [options.decimalPlaces=2]
* @param {number} [options.fixedDecimals=false]
* @param {string} [options.thousandsSeparator=]
* @param {string} [options.unit=]
* @param {string} [options.unitSeparator=]
*
* @returns {string|null}
* @public
*/
function format(value, options) {
if (!Number.isFinite(value)) {
return null;
}
var mag = Math.abs(value);
var thousandsSeparator = (options && options.thousandsSeparator) || '';
var unitSeparator = (options && options.unitSeparator) || '';
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
var fixedDecimals = Boolean(options && options.fixedDecimals);
var unit = (options && options.unit) || '';
if (!unit || !map[unit.toLowerCase()]) {
if (mag >= map.pb) {
unit = 'PB';
} else if (mag >= map.tb) {
unit = 'TB';
} else if (mag >= map.gb) {
unit = 'GB';
} else if (mag >= map.mb) {
unit = 'MB';
} else if (mag >= map.kb) {
unit = 'KB';
} else {
unit = 'B';
}
}
var val = value / map[unit.toLowerCase()];
var str = val.toFixed(decimalPlaces);
if (!fixedDecimals) {
str = str.replace(formatDecimalsRegExp, '$1');
}
if (thousandsSeparator) {
str = str.split('.').map(function (s, i) {
return i === 0
? s.replace(formatThousandsRegExp, thousandsSeparator)
: s
}).join('.');
}
return str + unitSeparator + unit;
}
/**
* Parse the string value into an integer in bytes.
*
* If no unit is given, it is assumed the value is in bytes.
*
* @param {number|string} val
*
* @returns {number|null}
* @public
*/
function parse(val) {
if (typeof val === 'number' && !isNaN(val)) {
return val;
}
if (typeof val !== 'string') {
return null;
}
// Test if the string passed is valid
var results = parseRegExp.exec(val);
var floatValue;
var unit = 'b';
if (!results) {
// Nothing could be extracted from the given string
floatValue = parseInt(val, 10);
unit = 'b'
} else {
// Retrieve the value and the unit
floatValue = parseFloat(results[1]);
unit = results[4].toLowerCase();
}
if (isNaN(floatValue)) {
return null;
}
return Math.floor(map[unit] * floatValue);
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/long/index.js | aws/lti-middleware/node_modules/long/index.js | module.exports = require("./src/long");
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/long/src/long.js | aws/lti-middleware/node_modules/long/src/long.js | module.exports = Long;
/**
* wasm optimizations, to do native i64 multiplication and divide
*/
var wasm = null;
try {
wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11
])), {}).exports;
} catch (e) {
// no wasm support :(
}
/**
* Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
* See the from* functions below for more convenient ways of constructing Longs.
* @exports Long
* @class A Long class for representing a 64 bit two's-complement integer value.
* @param {number} low The low (signed) 32 bits of the long
* @param {number} high The high (signed) 32 bits of the long
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @constructor
*/
function Long(low, high, unsigned) {
/**
* The low 32 bits as a signed value.
* @type {number}
*/
this.low = low | 0;
/**
* The high 32 bits as a signed value.
* @type {number}
*/
this.high = high | 0;
/**
* Whether unsigned or not.
* @type {boolean}
*/
this.unsigned = !!unsigned;
}
// The internal representation of a long is the two given signed, 32-bit values.
// We use 32-bit pieces because these are the size of integers on which
// Javascript performs bit-operations. For operations like addition and
// multiplication, we split each number into 16 bit pieces, which can easily be
// multiplied within Javascript's floating-point representation without overflow
// or change in sign.
//
// In the algorithms below, we frequently reduce the negative case to the
// positive case by negating the input(s) and then post-processing the result.
// Note that we must ALWAYS check specially whether those values are MIN_VALUE
// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
// a positive number, it overflows back into a negative). Not handling this
// case would often result in infinite recursion.
//
// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
// methods on which they depend.
/**
* An indicator used to reliably determine if an object is a Long or not.
* @type {boolean}
* @const
* @private
*/
Long.prototype.__isLong__;
Object.defineProperty(Long.prototype, "__isLong__", { value: true });
/**
* @function
* @param {*} obj Object
* @returns {boolean}
* @inner
*/
function isLong(obj) {
return (obj && obj["__isLong__"]) === true;
}
/**
* Tests if the specified object is a Long.
* @function
* @param {*} obj Object
* @returns {boolean}
*/
Long.isLong = isLong;
/**
* A cache of the Long representations of small integer values.
* @type {!Object}
* @inner
*/
var INT_CACHE = {};
/**
* A cache of the Long representations of small unsigned integer values.
* @type {!Object}
* @inner
*/
var UINT_CACHE = {};
/**
* @param {number} value
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromInt(value, unsigned) {
var obj, cachedObj, cache;
if (unsigned) {
value >>>= 0;
if (cache = (0 <= value && value < 256)) {
cachedObj = UINT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
if (cache)
UINT_CACHE[value] = obj;
return obj;
} else {
value |= 0;
if (cache = (-128 <= value && value < 128)) {
cachedObj = INT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = fromBits(value, value < 0 ? -1 : 0, false);
if (cache)
INT_CACHE[value] = obj;
return obj;
}
}
/**
* Returns a Long representing the given 32 bit integer value.
* @function
* @param {number} value The 32 bit integer in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromInt = fromInt;
/**
* @param {number} value
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromNumber(value, unsigned) {
if (isNaN(value))
return unsigned ? UZERO : ZERO;
if (unsigned) {
if (value < 0)
return UZERO;
if (value >= TWO_PWR_64_DBL)
return MAX_UNSIGNED_VALUE;
} else {
if (value <= -TWO_PWR_63_DBL)
return MIN_VALUE;
if (value + 1 >= TWO_PWR_63_DBL)
return MAX_VALUE;
}
if (value < 0)
return fromNumber(-value, unsigned).neg();
return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
}
/**
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
* @function
* @param {number} value The number in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromNumber = fromNumber;
/**
* @param {number} lowBits
* @param {number} highBits
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromBits(lowBits, highBits, unsigned) {
return new Long(lowBits, highBits, unsigned);
}
/**
* Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
* assumed to use 32 bits.
* @function
* @param {number} lowBits The low 32 bits
* @param {number} highBits The high 32 bits
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromBits = fromBits;
/**
* @function
* @param {number} base
* @param {number} exponent
* @returns {number}
* @inner
*/
var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
/**
* @param {string} str
* @param {(boolean|number)=} unsigned
* @param {number=} radix
* @returns {!Long}
* @inner
*/
function fromString(str, unsigned, radix) {
if (str.length === 0)
throw Error('empty string');
if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
return ZERO;
if (typeof unsigned === 'number') {
// For goog.math.long compatibility
radix = unsigned,
unsigned = false;
} else {
unsigned = !! unsigned;
}
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw RangeError('radix');
var p;
if ((p = str.indexOf('-')) > 0)
throw Error('interior hyphen');
else if (p === 0) {
return fromString(str.substring(1), unsigned, radix).neg();
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = fromNumber(pow_dbl(radix, 8));
var result = ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i),
value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = fromNumber(pow_dbl(radix, size));
result = result.mul(power).add(fromNumber(value));
} else {
result = result.mul(radixToPower);
result = result.add(fromNumber(value));
}
}
result.unsigned = unsigned;
return result;
}
/**
* Returns a Long representation of the given string, written using the specified radix.
* @function
* @param {string} str The textual representation of the Long
* @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed
* @param {number=} radix The radix in which the text is written (2-36), defaults to 10
* @returns {!Long} The corresponding Long value
*/
Long.fromString = fromString;
/**
* @function
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromValue(val, unsigned) {
if (typeof val === 'number')
return fromNumber(val, unsigned);
if (typeof val === 'string')
return fromString(val, unsigned);
// Throws for non-objects, converts non-instanceof Long:
return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
}
/**
* Converts the specified value to a Long using the appropriate from* function for its type.
* @function
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long}
*/
Long.fromValue = fromValue;
// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
// no runtime penalty for these.
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_16_DBL = 1 << 16;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_24_DBL = 1 << 24;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
/**
* @type {!Long}
* @const
* @inner
*/
var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
/**
* @type {!Long}
* @inner
*/
var ZERO = fromInt(0);
/**
* Signed zero.
* @type {!Long}
*/
Long.ZERO = ZERO;
/**
* @type {!Long}
* @inner
*/
var UZERO = fromInt(0, true);
/**
* Unsigned zero.
* @type {!Long}
*/
Long.UZERO = UZERO;
/**
* @type {!Long}
* @inner
*/
var ONE = fromInt(1);
/**
* Signed one.
* @type {!Long}
*/
Long.ONE = ONE;
/**
* @type {!Long}
* @inner
*/
var UONE = fromInt(1, true);
/**
* Unsigned one.
* @type {!Long}
*/
Long.UONE = UONE;
/**
* @type {!Long}
* @inner
*/
var NEG_ONE = fromInt(-1);
/**
* Signed negative one.
* @type {!Long}
*/
Long.NEG_ONE = NEG_ONE;
/**
* @type {!Long}
* @inner
*/
var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
/**
* Maximum signed value.
* @type {!Long}
*/
Long.MAX_VALUE = MAX_VALUE;
/**
* @type {!Long}
* @inner
*/
var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
/**
* Maximum unsigned value.
* @type {!Long}
*/
Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
/**
* @type {!Long}
* @inner
*/
var MIN_VALUE = fromBits(0, 0x80000000|0, false);
/**
* Minimum signed value.
* @type {!Long}
*/
Long.MIN_VALUE = MIN_VALUE;
/**
* @alias Long.prototype
* @inner
*/
var LongPrototype = Long.prototype;
/**
* Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
* @returns {number}
*/
LongPrototype.toInt = function toInt() {
return this.unsigned ? this.low >>> 0 : this.low;
};
/**
* Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
* @returns {number}
*/
LongPrototype.toNumber = function toNumber() {
if (this.unsigned)
return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
};
/**
* Converts the Long to a string written in the specified radix.
* @param {number=} radix Radix (2-36), defaults to 10
* @returns {string}
* @override
* @throws {RangeError} If `radix` is out of range
*/
LongPrototype.toString = function toString(radix) {
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw RangeError('radix');
if (this.isZero())
return '0';
if (this.isNegative()) { // Unsigned Longs are never negative
if (this.eq(MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = fromNumber(radix),
div = this.div(radixLong),
rem1 = div.mul(radixLong).sub(this);
return div.toString(radix) + rem1.toInt().toString(radix);
} else
return '-' + this.neg().toString(radix);
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
rem = this;
var result = '';
while (true) {
var remDiv = rem.div(radixToPower),
intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero())
return digits + result;
else {
while (digits.length < 6)
digits = '0' + digits;
result = '' + digits + result;
}
}
};
/**
* Gets the high 32 bits as a signed integer.
* @returns {number} Signed high bits
*/
LongPrototype.getHighBits = function getHighBits() {
return this.high;
};
/**
* Gets the high 32 bits as an unsigned integer.
* @returns {number} Unsigned high bits
*/
LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
return this.high >>> 0;
};
/**
* Gets the low 32 bits as a signed integer.
* @returns {number} Signed low bits
*/
LongPrototype.getLowBits = function getLowBits() {
return this.low;
};
/**
* Gets the low 32 bits as an unsigned integer.
* @returns {number} Unsigned low bits
*/
LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
return this.low >>> 0;
};
/**
* Gets the number of bits needed to represent the absolute value of this Long.
* @returns {number}
*/
LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
if (this.isNegative()) // Unsigned Longs are never negative
return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
var val = this.high != 0 ? this.high : this.low;
for (var bit = 31; bit > 0; bit--)
if ((val & (1 << bit)) != 0)
break;
return this.high != 0 ? bit + 33 : bit + 1;
};
/**
* Tests if this Long's value equals zero.
* @returns {boolean}
*/
LongPrototype.isZero = function isZero() {
return this.high === 0 && this.low === 0;
};
/**
* Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.
* @returns {boolean}
*/
LongPrototype.eqz = LongPrototype.isZero;
/**
* Tests if this Long's value is negative.
* @returns {boolean}
*/
LongPrototype.isNegative = function isNegative() {
return !this.unsigned && this.high < 0;
};
/**
* Tests if this Long's value is positive.
* @returns {boolean}
*/
LongPrototype.isPositive = function isPositive() {
return this.unsigned || this.high >= 0;
};
/**
* Tests if this Long's value is odd.
* @returns {boolean}
*/
LongPrototype.isOdd = function isOdd() {
return (this.low & 1) === 1;
};
/**
* Tests if this Long's value is even.
* @returns {boolean}
*/
LongPrototype.isEven = function isEven() {
return (this.low & 1) === 0;
};
/**
* Tests if this Long's value equals the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.equals = function equals(other) {
if (!isLong(other))
other = fromValue(other);
if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
return false;
return this.high === other.high && this.low === other.low;
};
/**
* Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.eq = LongPrototype.equals;
/**
* Tests if this Long's value differs from the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.notEquals = function notEquals(other) {
return !this.eq(/* validates */ other);
};
/**
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.neq = LongPrototype.notEquals;
/**
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.ne = LongPrototype.notEquals;
/**
* Tests if this Long's value is less than the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lessThan = function lessThan(other) {
return this.comp(/* validates */ other) < 0;
};
/**
* Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lt = LongPrototype.lessThan;
/**
* Tests if this Long's value is less than or equal the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
return this.comp(/* validates */ other) <= 0;
};
/**
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lte = LongPrototype.lessThanOrEqual;
/**
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.le = LongPrototype.lessThanOrEqual;
/**
* Tests if this Long's value is greater than the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.greaterThan = function greaterThan(other) {
return this.comp(/* validates */ other) > 0;
};
/**
* Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.gt = LongPrototype.greaterThan;
/**
* Tests if this Long's value is greater than or equal the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
return this.comp(/* validates */ other) >= 0;
};
/**
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.gte = LongPrototype.greaterThanOrEqual;
/**
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.ge = LongPrototype.greaterThanOrEqual;
/**
* Compares this Long's value with the specified's.
* @param {!Long|number|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
*/
LongPrototype.compare = function compare(other) {
if (!isLong(other))
other = fromValue(other);
if (this.eq(other))
return 0;
var thisNeg = this.isNegative(),
otherNeg = other.isNegative();
if (thisNeg && !otherNeg)
return -1;
if (!thisNeg && otherNeg)
return 1;
// At this point the sign bits are the same
if (!this.unsigned)
return this.sub(other).isNegative() ? -1 : 1;
// Both are positive if at least one is unsigned
return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
};
/**
* Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
* @function
* @param {!Long|number|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
*/
LongPrototype.comp = LongPrototype.compare;
/**
* Negates this Long's value.
* @returns {!Long} Negated Long
*/
LongPrototype.negate = function negate() {
if (!this.unsigned && this.eq(MIN_VALUE))
return MIN_VALUE;
return this.not().add(ONE);
};
/**
* Negates this Long's value. This is an alias of {@link Long#negate}.
* @function
* @returns {!Long} Negated Long
*/
LongPrototype.neg = LongPrototype.negate;
/**
* Returns the sum of this and the specified Long.
* @param {!Long|number|string} addend Addend
* @returns {!Long} Sum
*/
LongPrototype.add = function add(addend) {
if (!isLong(addend))
addend = fromValue(addend);
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high >>> 16;
var a32 = this.high & 0xFFFF;
var a16 = this.low >>> 16;
var a00 = this.low & 0xFFFF;
var b48 = addend.high >>> 16;
var b32 = addend.high & 0xFFFF;
var b16 = addend.low >>> 16;
var b00 = addend.low & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 + b48;
c48 &= 0xFFFF;
return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the difference of this and the specified Long.
* @param {!Long|number|string} subtrahend Subtrahend
* @returns {!Long} Difference
*/
LongPrototype.subtract = function subtract(subtrahend) {
if (!isLong(subtrahend))
subtrahend = fromValue(subtrahend);
return this.add(subtrahend.neg());
};
/**
* Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
* @function
* @param {!Long|number|string} subtrahend Subtrahend
* @returns {!Long} Difference
*/
LongPrototype.sub = LongPrototype.subtract;
/**
* Returns the product of this and the specified Long.
* @param {!Long|number|string} multiplier Multiplier
* @returns {!Long} Product
*/
LongPrototype.multiply = function multiply(multiplier) {
if (this.isZero())
return ZERO;
if (!isLong(multiplier))
multiplier = fromValue(multiplier);
// use wasm support if present
if (wasm) {
var low = wasm.mul(this.low,
this.high,
multiplier.low,
multiplier.high);
return fromBits(low, wasm.get_high(), this.unsigned);
}
if (multiplier.isZero())
return ZERO;
if (this.eq(MIN_VALUE))
return multiplier.isOdd() ? MIN_VALUE : ZERO;
if (multiplier.eq(MIN_VALUE))
return this.isOdd() ? MIN_VALUE : ZERO;
if (this.isNegative()) {
if (multiplier.isNegative())
return this.neg().mul(multiplier.neg());
else
return this.neg().mul(multiplier).neg();
} else if (multiplier.isNegative())
return this.mul(multiplier.neg()).neg();
// If both longs are small, use float multiplication
if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high >>> 16;
var a32 = this.high & 0xFFFF;
var a16 = this.low >>> 16;
var a00 = this.low & 0xFFFF;
var b48 = multiplier.high >>> 16;
var b32 = multiplier.high & 0xFFFF;
var b16 = multiplier.low >>> 16;
var b00 = multiplier.low & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xFFFF;
return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
* @function
* @param {!Long|number|string} multiplier Multiplier
* @returns {!Long} Product
*/
LongPrototype.mul = LongPrototype.multiply;
/**
* Returns this Long divided by the specified. The result is signed if this Long is signed or
* unsigned if this Long is unsigned.
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Quotient
*/
LongPrototype.divide = function divide(divisor) {
if (!isLong(divisor))
divisor = fromValue(divisor);
if (divisor.isZero())
throw Error('division by zero');
// use wasm support if present
if (wasm) {
// guard against signed division overflow: the largest
// negative number / -1 would be 1 larger than the largest
// positive number, due to two's complement.
if (!this.unsigned &&
this.high === -0x80000000 &&
divisor.low === -1 && divisor.high === -1) {
// be consistent with non-wasm code path
return this;
}
var low = (this.unsigned ? wasm.div_u : wasm.div_s)(
this.low,
this.high,
divisor.low,
divisor.high
);
return fromBits(low, wasm.get_high(), this.unsigned);
}
if (this.isZero())
return this.unsigned ? UZERO : ZERO;
var approx, rem, res;
if (!this.unsigned) {
// This section is only relevant for signed longs and is derived from the
// closure library as a whole.
if (this.eq(MIN_VALUE)) {
if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
else if (divisor.eq(MIN_VALUE))
return ONE;
else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shr(1);
approx = halfThis.div(divisor).shl(1);
if (approx.eq(ZERO)) {
return divisor.isNegative() ? ONE : NEG_ONE;
} else {
rem = this.sub(divisor.mul(approx));
res = approx.add(rem.div(divisor));
return res;
}
}
} else if (divisor.eq(MIN_VALUE))
return this.unsigned ? UZERO : ZERO;
if (this.isNegative()) {
if (divisor.isNegative())
return this.neg().div(divisor.neg());
return this.neg().div(divisor).neg();
} else if (divisor.isNegative())
return this.div(divisor.neg()).neg();
res = ZERO;
} else {
// The algorithm below has not been made for unsigned longs. It's therefore
// required to take special care of the MSB prior to running it.
if (!divisor.unsigned)
divisor = divisor.toUnsigned();
if (divisor.gt(this))
return UZERO;
if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
return UONE;
res = UZERO;
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
rem = this;
while (rem.gte(divisor)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2),
delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
approxRes = fromNumber(approx),
approxRem = approxRes.mul(divisor);
while (approxRem.isNegative() || approxRem.gt(rem)) {
approx -= delta;
approxRes = fromNumber(approx, this.unsigned);
approxRem = approxRes.mul(divisor);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero())
approxRes = ONE;
res = res.add(approxRes);
rem = rem.sub(approxRem);
}
return res;
};
/**
* Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Quotient
*/
LongPrototype.div = LongPrototype.divide;
/**
* Returns this Long modulo the specified.
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.modulo = function modulo(divisor) {
if (!isLong(divisor))
divisor = fromValue(divisor);
// use wasm support if present
if (wasm) {
var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(
this.low,
this.high,
divisor.low,
divisor.high
);
return fromBits(low, wasm.get_high(), this.unsigned);
}
return this.sub(this.div(divisor).mul(divisor));
};
/**
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.mod = LongPrototype.modulo;
/**
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.rem = LongPrototype.modulo;
/**
* Returns the bitwise NOT of this Long.
* @returns {!Long}
*/
LongPrototype.not = function not() {
return fromBits(~this.low, ~this.high, this.unsigned);
};
/**
* Returns the bitwise AND of this Long and the specified.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
*/
LongPrototype.and = function and(other) {
if (!isLong(other))
other = fromValue(other);
return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
};
/**
* Returns the bitwise OR of this Long and the specified.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
*/
LongPrototype.or = function or(other) {
if (!isLong(other))
other = fromValue(other);
return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
};
/**
* Returns the bitwise XOR of this Long and the given one.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
*/
LongPrototype.xor = function xor(other) {
if (!isLong(other))
other = fromValue(other);
return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
};
/**
* Returns this Long with bits shifted to the left by the given amount.
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shiftLeft = function shiftLeft(numBits) {
if (isLong(numBits))
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | true |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/long/dist/long.js | aws/lti-middleware/node_modules/long/dist/long.js | !function(t,i){"object"==typeof exports&&"object"==typeof module?module.exports=i():"function"==typeof define&&define.amd?define([],i):"object"==typeof exports?exports.Long=i():t.Long=i()}("undefined"!=typeof self?self:this,function(){return function(t){function i(e){if(n[e])return n[e].exports;var r=n[e]={i:e,l:!1,exports:{}};return t[e].call(r.exports,r,r.exports,i),r.l=!0,r.exports}var n={};return i.m=t,i.c=n,i.d=function(t,n,e){i.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:e})},i.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(n,"a",n),n},i.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},i.p="",i(i.s=0)}([function(t,i){function n(t,i,n){this.low=0|t,this.high=0|i,this.unsigned=!!n}function e(t){return!0===(t&&t.__isLong__)}function r(t,i){var n,e,r;return i?(t>>>=0,(r=0<=t&&t<256)&&(e=l[t])?e:(n=h(t,(0|t)<0?-1:0,!0),r&&(l[t]=n),n)):(t|=0,(r=-128<=t&&t<128)&&(e=f[t])?e:(n=h(t,t<0?-1:0,!1),r&&(f[t]=n),n))}function s(t,i){if(isNaN(t))return i?p:m;if(i){if(t<0)return p;if(t>=c)return q}else{if(t<=-v)return _;if(t+1>=v)return E}return t<0?s(-t,i).neg():h(t%d|0,t/d|0,i)}function h(t,i,e){return new n(t,i,e)}function u(t,i,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return m;if("number"==typeof i?(n=i,i=!1):i=!!i,(n=n||10)<2||36<n)throw RangeError("radix");var e;if((e=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===e)return u(t.substring(1),i,n).neg();for(var r=s(a(n,8)),h=m,o=0;o<t.length;o+=8){var g=Math.min(8,t.length-o),f=parseInt(t.substring(o,o+g),n);if(g<8){var l=s(a(n,g));h=h.mul(l).add(s(f))}else h=h.mul(r),h=h.add(s(f))}return h.unsigned=i,h}function o(t,i){return"number"==typeof t?s(t,i):"string"==typeof t?u(t,i):h(t.low,t.high,"boolean"==typeof i?i:t.unsigned)}t.exports=n;var g=null;try{g=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=e;var f={},l={};n.fromInt=r,n.fromNumber=s,n.fromBits=h;var a=Math.pow;n.fromString=u,n.fromValue=o;var d=4294967296,c=d*d,v=c/2,w=r(1<<24),m=r(0);n.ZERO=m;var p=r(0,!0);n.UZERO=p;var y=r(1);n.ONE=y;var b=r(1,!0);n.UONE=b;var N=r(-1);n.NEG_ONE=N;var E=h(-1,2147483647,!1);n.MAX_VALUE=E;var q=h(-1,-1,!0);n.MAX_UNSIGNED_VALUE=q;var _=h(0,-2147483648,!1);n.MIN_VALUE=_;var B=n.prototype;B.toInt=function(){return this.unsigned?this.low>>>0:this.low},B.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},B.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(_)){var i=s(t),n=this.div(i),e=n.mul(i).sub(this);return n.toString(t)+e.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var r=s(a(t,6),this.unsigned),h=this,u="";;){var o=h.div(r),g=h.sub(o.mul(r)).toInt()>>>0,f=g.toString(t);if(h=o,h.isZero())return f+u;for(;f.length<6;)f="0"+f;u=""+f+u}},B.getHighBits=function(){return this.high},B.getHighBitsUnsigned=function(){return this.high>>>0},B.getLowBits=function(){return this.low},B.getLowBitsUnsigned=function(){return this.low>>>0},B.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,i=31;i>0&&0==(t&1<<i);i--);return 0!=this.high?i+33:i+1},B.isZero=function(){return 0===this.high&&0===this.low},B.eqz=B.isZero,B.isNegative=function(){return!this.unsigned&&this.high<0},B.isPositive=function(){return this.unsigned||this.high>=0},B.isOdd=function(){return 1==(1&this.low)},B.isEven=function(){return 0==(1&this.low)},B.equals=function(t){return e(t)||(t=o(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&(this.high===t.high&&this.low===t.low)},B.eq=B.equals,B.notEquals=function(t){return!this.eq(t)},B.neq=B.notEquals,B.ne=B.notEquals,B.lessThan=function(t){return this.comp(t)<0},B.lt=B.lessThan,B.lessThanOrEqual=function(t){return this.comp(t)<=0},B.lte=B.lessThanOrEqual,B.le=B.lessThanOrEqual,B.greaterThan=function(t){return this.comp(t)>0},B.gt=B.greaterThan,B.greaterThanOrEqual=function(t){return this.comp(t)>=0},B.gte=B.greaterThanOrEqual,B.ge=B.greaterThanOrEqual,B.compare=function(t){if(e(t)||(t=o(t)),this.eq(t))return 0;var i=this.isNegative(),n=t.isNegative();return i&&!n?-1:!i&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},B.comp=B.compare,B.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(y)},B.neg=B.negate,B.add=function(t){e(t)||(t=o(t));var i=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,u=t.high>>>16,g=65535&t.high,f=t.low>>>16,l=65535&t.low,a=0,d=0,c=0,v=0;return v+=s+l,c+=v>>>16,v&=65535,c+=r+f,d+=c>>>16,c&=65535,d+=n+g,a+=d>>>16,d&=65535,a+=i+u,a&=65535,h(c<<16|v,a<<16|d,this.unsigned)},B.subtract=function(t){return e(t)||(t=o(t)),this.add(t.neg())},B.sub=B.subtract,B.multiply=function(t){if(this.isZero())return m;if(e(t)||(t=o(t)),g){return h(g.mul(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(t.isZero())return m;if(this.eq(_))return t.isOdd()?_:m;if(t.eq(_))return this.isOdd()?_:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(w)&&t.lt(w))return s(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,n=65535&this.high,r=this.low>>>16,u=65535&this.low,f=t.high>>>16,l=65535&t.high,a=t.low>>>16,d=65535&t.low,c=0,v=0,p=0,y=0;return y+=u*d,p+=y>>>16,y&=65535,p+=r*d,v+=p>>>16,p&=65535,p+=u*a,v+=p>>>16,p&=65535,v+=n*d,c+=v>>>16,v&=65535,v+=r*a,c+=v>>>16,v&=65535,v+=u*l,c+=v>>>16,v&=65535,c+=i*d+n*a+r*l+u*f,c&=65535,h(p<<16|y,c<<16|v,this.unsigned)},B.mul=B.multiply,B.divide=function(t){if(e(t)||(t=o(t)),t.isZero())throw Error("division by zero");if(g){if(!this.unsigned&&-2147483648===this.high&&-1===t.low&&-1===t.high)return this;return h((this.unsigned?g.div_u:g.div_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p:m;var i,n,r;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return p;if(t.gt(this.shru(1)))return b;r=p}else{if(this.eq(_)){if(t.eq(y)||t.eq(N))return _;if(t.eq(_))return y;return i=this.shr(1).div(t).shl(1),i.eq(m)?t.isNegative()?y:N:(n=this.sub(t.mul(i)),r=i.add(n.div(t)))}if(t.eq(_))return this.unsigned?p:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();r=m}for(n=this;n.gte(t);){i=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var u=Math.ceil(Math.log(i)/Math.LN2),f=u<=48?1:a(2,u-48),l=s(i),d=l.mul(t);d.isNegative()||d.gt(n);)i-=f,l=s(i,this.unsigned),d=l.mul(t);l.isZero()&&(l=y),r=r.add(l),n=n.sub(d)}return r},B.div=B.divide,B.modulo=function(t){if(e(t)||(t=o(t)),g){return h((this.unsigned?g.rem_u:g.rem_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},B.mod=B.modulo,B.rem=B.modulo,B.not=function(){return h(~this.low,~this.high,this.unsigned)},B.and=function(t){return e(t)||(t=o(t)),h(this.low&t.low,this.high&t.high,this.unsigned)},B.or=function(t){return e(t)||(t=o(t)),h(this.low|t.low,this.high|t.high,this.unsigned)},B.xor=function(t){return e(t)||(t=o(t)),h(this.low^t.low,this.high^t.high,this.unsigned)},B.shiftLeft=function(t){return e(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?h(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):h(0,this.low<<t-32,this.unsigned)},B.shl=B.shiftLeft,B.shiftRight=function(t){return e(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?h(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):h(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},B.shr=B.shiftRight,B.shiftRightUnsigned=function(t){if(e(t)&&(t=t.toInt()),0===(t&=63))return this;var i=this.high;if(t<32){return h(this.low>>>t|i<<32-t,i>>>t,this.unsigned)}return 32===t?h(i,0,this.unsigned):h(i>>>t-32,0,this.unsigned)},B.shru=B.shiftRightUnsigned,B.shr_u=B.shiftRightUnsigned,B.toSigned=function(){return this.unsigned?h(this.low,this.high,!1):this},B.toUnsigned=function(){return this.unsigned?this:h(this.low,this.high,!0)},B.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},B.toBytesLE=function(){var t=this.high,i=this.low;return[255&i,i>>>8&255,i>>>16&255,i>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},B.toBytesBE=function(){var t=this.high,i=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,i>>>24,i>>>16&255,i>>>8&255,255&i]},n.fromBytes=function(t,i,e){return e?n.fromBytesLE(t,i):n.fromBytesBE(t,i)},n.fromBytesLE=function(t,i){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,i)},n.fromBytesBE=function(t,i){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],i)}}])});
//# sourceMappingURL=long.js.map | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@tootallnate/once/dist/overloaded-parameters.js | aws/lti-middleware/node_modules/@tootallnate/once/dist/overloaded-parameters.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=overloaded-parameters.js.map | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@tootallnate/once/dist/types.js | aws/lti-middleware/node_modules/@tootallnate/once/dist/types.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/@tootallnate/once/dist/index.js | aws/lti-middleware/node_modules/@tootallnate/once/dist/index.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function once(emitter, name, { signal } = {}) {
return new Promise((resolve, reject) => {
function cleanup() {
signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', cleanup);
emitter.removeListener(name, onEvent);
emitter.removeListener('error', onError);
}
function onEvent(...args) {
cleanup();
resolve(args);
}
function onError(err) {
cleanup();
reject(err);
}
signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', cleanup);
emitter.on(name, onEvent);
emitter.on('error', onError);
});
}
exports.default = once;
//# sourceMappingURL=index.js.map | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/functional-red-black-tree/rbtree.js | aws/lti-middleware/node_modules/functional-red-black-tree/rbtree.js | "use strict"
module.exports = createRBTree
var RED = 0
var BLACK = 1
function RBNode(color, key, value, left, right, count) {
this._color = color
this.key = key
this.value = value
this.left = left
this.right = right
this._count = count
}
function cloneNode(node) {
return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
}
function repaint(color, node) {
return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
}
function recount(node) {
node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
}
function RedBlackTree(compare, root) {
this._compare = compare
this.root = root
}
var proto = RedBlackTree.prototype
Object.defineProperty(proto, "keys", {
get: function() {
var result = []
this.forEach(function(k,v) {
result.push(k)
})
return result
}
})
Object.defineProperty(proto, "values", {
get: function() {
var result = []
this.forEach(function(k,v) {
result.push(v)
})
return result
}
})
//Returns the number of nodes in the tree
Object.defineProperty(proto, "length", {
get: function() {
if(this.root) {
return this.root._count
}
return 0
}
})
//Insert a new item into the tree
proto.insert = function(key, value) {
var cmp = this._compare
//Find point to insert new node at
var n = this.root
var n_stack = []
var d_stack = []
while(n) {
var d = cmp(key, n.key)
n_stack.push(n)
d_stack.push(d)
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
//Rebuild path to leaf node
n_stack.push(new RBNode(RED, key, value, null, null, 1))
for(var s=n_stack.length-2; s>=0; --s) {
var n = n_stack[s]
if(d_stack[s] <= 0) {
n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
} else {
n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
}
}
//Rebalance tree using rotations
//console.log("start insert", key, d_stack)
for(var s=n_stack.length-1; s>1; --s) {
var p = n_stack[s-1]
var n = n_stack[s]
if(p._color === BLACK || n._color === BLACK) {
break
}
var pp = n_stack[s-2]
if(pp.left === p) {
if(p.left === n) {
var y = pp.right
if(y && y._color === RED) {
//console.log("LLr")
p._color = BLACK
pp.right = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("LLb")
pp._color = RED
pp.left = p.right
p._color = BLACK
p.right = pp
n_stack[s-2] = p
n_stack[s-1] = n
recount(pp)
recount(p)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.left === pp) {
ppp.left = p
} else {
ppp.right = p
}
}
break
}
} else {
var y = pp.right
if(y && y._color === RED) {
//console.log("LRr")
p._color = BLACK
pp.right = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("LRb")
p.right = n.left
pp._color = RED
pp.left = n.right
n._color = BLACK
n.left = p
n.right = pp
n_stack[s-2] = n
n_stack[s-1] = p
recount(pp)
recount(p)
recount(n)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.left === pp) {
ppp.left = n
} else {
ppp.right = n
}
}
break
}
}
} else {
if(p.right === n) {
var y = pp.left
if(y && y._color === RED) {
//console.log("RRr", y.key)
p._color = BLACK
pp.left = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("RRb")
pp._color = RED
pp.right = p.left
p._color = BLACK
p.left = pp
n_stack[s-2] = p
n_stack[s-1] = n
recount(pp)
recount(p)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.right === pp) {
ppp.right = p
} else {
ppp.left = p
}
}
break
}
} else {
var y = pp.left
if(y && y._color === RED) {
//console.log("RLr")
p._color = BLACK
pp.left = repaint(BLACK, y)
pp._color = RED
s -= 1
} else {
//console.log("RLb")
p.left = n.right
pp._color = RED
pp.right = n.left
n._color = BLACK
n.right = p
n.left = pp
n_stack[s-2] = n
n_stack[s-1] = p
recount(pp)
recount(p)
recount(n)
if(s >= 3) {
var ppp = n_stack[s-3]
if(ppp.right === pp) {
ppp.right = n
} else {
ppp.left = n
}
}
break
}
}
}
}
//Return new tree
n_stack[0]._color = BLACK
return new RedBlackTree(cmp, n_stack[0])
}
//Visit all nodes inorder
function doVisitFull(visit, node) {
if(node.left) {
var v = doVisitFull(visit, node.left)
if(v) { return v }
}
var v = visit(node.key, node.value)
if(v) { return v }
if(node.right) {
return doVisitFull(visit, node.right)
}
}
//Visit half nodes in order
function doVisitHalf(lo, compare, visit, node) {
var l = compare(lo, node.key)
if(l <= 0) {
if(node.left) {
var v = doVisitHalf(lo, compare, visit, node.left)
if(v) { return v }
}
var v = visit(node.key, node.value)
if(v) { return v }
}
if(node.right) {
return doVisitHalf(lo, compare, visit, node.right)
}
}
//Visit all nodes within a range
function doVisit(lo, hi, compare, visit, node) {
var l = compare(lo, node.key)
var h = compare(hi, node.key)
var v
if(l <= 0) {
if(node.left) {
v = doVisit(lo, hi, compare, visit, node.left)
if(v) { return v }
}
if(h > 0) {
v = visit(node.key, node.value)
if(v) { return v }
}
}
if(h > 0 && node.right) {
return doVisit(lo, hi, compare, visit, node.right)
}
}
proto.forEach = function rbTreeForEach(visit, lo, hi) {
if(!this.root) {
return
}
switch(arguments.length) {
case 1:
return doVisitFull(visit, this.root)
break
case 2:
return doVisitHalf(lo, this._compare, visit, this.root)
break
case 3:
if(this._compare(lo, hi) >= 0) {
return
}
return doVisit(lo, hi, this._compare, visit, this.root)
break
}
}
//First item in list
Object.defineProperty(proto, "begin", {
get: function() {
var stack = []
var n = this.root
while(n) {
stack.push(n)
n = n.left
}
return new RedBlackTreeIterator(this, stack)
}
})
//Last item in list
Object.defineProperty(proto, "end", {
get: function() {
var stack = []
var n = this.root
while(n) {
stack.push(n)
n = n.right
}
return new RedBlackTreeIterator(this, stack)
}
})
//Find the ith item in the tree
proto.at = function(idx) {
if(idx < 0) {
return new RedBlackTreeIterator(this, [])
}
var n = this.root
var stack = []
while(true) {
stack.push(n)
if(n.left) {
if(idx < n.left._count) {
n = n.left
continue
}
idx -= n.left._count
}
if(!idx) {
return new RedBlackTreeIterator(this, stack)
}
idx -= 1
if(n.right) {
if(idx >= n.right._count) {
break
}
n = n.right
} else {
break
}
}
return new RedBlackTreeIterator(this, [])
}
proto.ge = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d <= 0) {
last_ptr = stack.length
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
proto.gt = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d < 0) {
last_ptr = stack.length
}
if(d < 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
proto.lt = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d > 0) {
last_ptr = stack.length
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
proto.le = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
var last_ptr = 0
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d >= 0) {
last_ptr = stack.length
}
if(d < 0) {
n = n.left
} else {
n = n.right
}
}
stack.length = last_ptr
return new RedBlackTreeIterator(this, stack)
}
//Finds the item with key if it exists
proto.find = function(key) {
var cmp = this._compare
var n = this.root
var stack = []
while(n) {
var d = cmp(key, n.key)
stack.push(n)
if(d === 0) {
return new RedBlackTreeIterator(this, stack)
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
return new RedBlackTreeIterator(this, [])
}
//Removes item with key from tree
proto.remove = function(key) {
var iter = this.find(key)
if(iter) {
return iter.remove()
}
return this
}
//Returns the item at `key`
proto.get = function(key) {
var cmp = this._compare
var n = this.root
while(n) {
var d = cmp(key, n.key)
if(d === 0) {
return n.value
}
if(d <= 0) {
n = n.left
} else {
n = n.right
}
}
return
}
//Iterator for red black tree
function RedBlackTreeIterator(tree, stack) {
this.tree = tree
this._stack = stack
}
var iproto = RedBlackTreeIterator.prototype
//Test if iterator is valid
Object.defineProperty(iproto, "valid", {
get: function() {
return this._stack.length > 0
}
})
//Node of the iterator
Object.defineProperty(iproto, "node", {
get: function() {
if(this._stack.length > 0) {
return this._stack[this._stack.length-1]
}
return null
},
enumerable: true
})
//Makes a copy of an iterator
iproto.clone = function() {
return new RedBlackTreeIterator(this.tree, this._stack.slice())
}
//Swaps two nodes
function swapNode(n, v) {
n.key = v.key
n.value = v.value
n.left = v.left
n.right = v.right
n._color = v._color
n._count = v._count
}
//Fix up a double black node in a tree
function fixDoubleBlack(stack) {
var n, p, s, z
for(var i=stack.length-1; i>=0; --i) {
n = stack[i]
if(i === 0) {
n._color = BLACK
return
}
//console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
p = stack[i-1]
if(p.left === n) {
//console.log("left child")
s = p.right
if(s.right && s.right._color === RED) {
//console.log("case 1: right sibling child red")
s = p.right = cloneNode(s)
z = s.right = cloneNode(s.right)
p.right = s.left
s.left = p
s.right = z
s._color = p._color
n._color = BLACK
p._color = BLACK
z._color = BLACK
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.left === p) {
pp.left = s
} else {
pp.right = s
}
}
stack[i-1] = s
return
} else if(s.left && s.left._color === RED) {
//console.log("case 1: left sibling child red")
s = p.right = cloneNode(s)
z = s.left = cloneNode(s.left)
p.right = z.left
s.left = z.right
z.left = p
z.right = s
z._color = p._color
p._color = BLACK
s._color = BLACK
n._color = BLACK
recount(p)
recount(s)
recount(z)
if(i > 1) {
var pp = stack[i-2]
if(pp.left === p) {
pp.left = z
} else {
pp.right = z
}
}
stack[i-1] = z
return
}
if(s._color === BLACK) {
if(p._color === RED) {
//console.log("case 2: black sibling, red parent", p.right.value)
p._color = BLACK
p.right = repaint(RED, s)
return
} else {
//console.log("case 2: black sibling, black parent", p.right.value)
p.right = repaint(RED, s)
continue
}
} else {
//console.log("case 3: red sibling")
s = cloneNode(s)
p.right = s.left
s.left = p
s._color = p._color
p._color = RED
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.left === p) {
pp.left = s
} else {
pp.right = s
}
}
stack[i-1] = s
stack[i] = p
if(i+1 < stack.length) {
stack[i+1] = n
} else {
stack.push(n)
}
i = i+2
}
} else {
//console.log("right child")
s = p.left
if(s.left && s.left._color === RED) {
//console.log("case 1: left sibling child red", p.value, p._color)
s = p.left = cloneNode(s)
z = s.left = cloneNode(s.left)
p.left = s.right
s.right = p
s.left = z
s._color = p._color
n._color = BLACK
p._color = BLACK
z._color = BLACK
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.right === p) {
pp.right = s
} else {
pp.left = s
}
}
stack[i-1] = s
return
} else if(s.right && s.right._color === RED) {
//console.log("case 1: right sibling child red")
s = p.left = cloneNode(s)
z = s.right = cloneNode(s.right)
p.left = z.right
s.right = z.left
z.right = p
z.left = s
z._color = p._color
p._color = BLACK
s._color = BLACK
n._color = BLACK
recount(p)
recount(s)
recount(z)
if(i > 1) {
var pp = stack[i-2]
if(pp.right === p) {
pp.right = z
} else {
pp.left = z
}
}
stack[i-1] = z
return
}
if(s._color === BLACK) {
if(p._color === RED) {
//console.log("case 2: black sibling, red parent")
p._color = BLACK
p.left = repaint(RED, s)
return
} else {
//console.log("case 2: black sibling, black parent")
p.left = repaint(RED, s)
continue
}
} else {
//console.log("case 3: red sibling")
s = cloneNode(s)
p.left = s.right
s.right = p
s._color = p._color
p._color = RED
recount(p)
recount(s)
if(i > 1) {
var pp = stack[i-2]
if(pp.right === p) {
pp.right = s
} else {
pp.left = s
}
}
stack[i-1] = s
stack[i] = p
if(i+1 < stack.length) {
stack[i+1] = n
} else {
stack.push(n)
}
i = i+2
}
}
}
}
//Removes item at iterator from tree
iproto.remove = function() {
var stack = this._stack
if(stack.length === 0) {
return this.tree
}
//First copy path to node
var cstack = new Array(stack.length)
var n = stack[stack.length-1]
cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
for(var i=stack.length-2; i>=0; --i) {
var n = stack[i]
if(n.left === stack[i+1]) {
cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
} else {
cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
}
}
//Get node
n = cstack[cstack.length-1]
//console.log("start remove: ", n.value)
//If not leaf, then swap with previous node
if(n.left && n.right) {
//console.log("moving to leaf")
//First walk to previous leaf
var split = cstack.length
n = n.left
while(n.right) {
cstack.push(n)
n = n.right
}
//Copy path to leaf
var v = cstack[split-1]
cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
cstack[split-1].key = n.key
cstack[split-1].value = n.value
//Fix up stack
for(var i=cstack.length-2; i>=split; --i) {
n = cstack[i]
cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
}
cstack[split-1].left = cstack[split]
}
//console.log("stack=", cstack.map(function(v) { return v.value }))
//Remove leaf node
n = cstack[cstack.length-1]
if(n._color === RED) {
//Easy case: removing red leaf
//console.log("RED leaf")
var p = cstack[cstack.length-2]
if(p.left === n) {
p.left = null
} else if(p.right === n) {
p.right = null
}
cstack.pop()
for(var i=0; i<cstack.length; ++i) {
cstack[i]._count--
}
return new RedBlackTree(this.tree._compare, cstack[0])
} else {
if(n.left || n.right) {
//Second easy case: Single child black parent
//console.log("BLACK single child")
if(n.left) {
swapNode(n, n.left)
} else if(n.right) {
swapNode(n, n.right)
}
//Child must be red, so repaint it black to balance color
n._color = BLACK
for(var i=0; i<cstack.length-1; ++i) {
cstack[i]._count--
}
return new RedBlackTree(this.tree._compare, cstack[0])
} else if(cstack.length === 1) {
//Third easy case: root
//console.log("ROOT")
return new RedBlackTree(this.tree._compare, null)
} else {
//Hard case: Repaint n, and then do some nasty stuff
//console.log("BLACK leaf no children")
for(var i=0; i<cstack.length; ++i) {
cstack[i]._count--
}
var parent = cstack[cstack.length-2]
fixDoubleBlack(cstack)
//Fix up links
if(parent.left === n) {
parent.left = null
} else {
parent.right = null
}
}
}
return new RedBlackTree(this.tree._compare, cstack[0])
}
//Returns key
Object.defineProperty(iproto, "key", {
get: function() {
if(this._stack.length > 0) {
return this._stack[this._stack.length-1].key
}
return
},
enumerable: true
})
//Returns value
Object.defineProperty(iproto, "value", {
get: function() {
if(this._stack.length > 0) {
return this._stack[this._stack.length-1].value
}
return
},
enumerable: true
})
//Returns the position of this iterator in the sorted list
Object.defineProperty(iproto, "index", {
get: function() {
var idx = 0
var stack = this._stack
if(stack.length === 0) {
var r = this.tree.root
if(r) {
return r._count
}
return 0
} else if(stack[stack.length-1].left) {
idx = stack[stack.length-1].left._count
}
for(var s=stack.length-2; s>=0; --s) {
if(stack[s+1] === stack[s].right) {
++idx
if(stack[s].left) {
idx += stack[s].left._count
}
}
}
return idx
},
enumerable: true
})
//Advances iterator to next element in list
iproto.next = function() {
var stack = this._stack
if(stack.length === 0) {
return
}
var n = stack[stack.length-1]
if(n.right) {
n = n.right
while(n) {
stack.push(n)
n = n.left
}
} else {
stack.pop()
while(stack.length > 0 && stack[stack.length-1].right === n) {
n = stack[stack.length-1]
stack.pop()
}
}
}
//Checks if iterator is at end of tree
Object.defineProperty(iproto, "hasNext", {
get: function() {
var stack = this._stack
if(stack.length === 0) {
return false
}
if(stack[stack.length-1].right) {
return true
}
for(var s=stack.length-1; s>0; --s) {
if(stack[s-1].left === stack[s]) {
return true
}
}
return false
}
})
//Update value
iproto.update = function(value) {
var stack = this._stack
if(stack.length === 0) {
throw new Error("Can't update empty node!")
}
var cstack = new Array(stack.length)
var n = stack[stack.length-1]
cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
for(var i=stack.length-2; i>=0; --i) {
n = stack[i]
if(n.left === stack[i+1]) {
cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
} else {
cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
}
}
return new RedBlackTree(this.tree._compare, cstack[0])
}
//Moves iterator backward one element
iproto.prev = function() {
var stack = this._stack
if(stack.length === 0) {
return
}
var n = stack[stack.length-1]
if(n.left) {
n = n.left
while(n) {
stack.push(n)
n = n.right
}
} else {
stack.pop()
while(stack.length > 0 && stack[stack.length-1].left === n) {
n = stack[stack.length-1]
stack.pop()
}
}
}
//Checks if iterator is at start of tree
Object.defineProperty(iproto, "hasPrev", {
get: function() {
var stack = this._stack
if(stack.length === 0) {
return false
}
if(stack[stack.length-1].left) {
return true
}
for(var s=stack.length-1; s>0; --s) {
if(stack[s-1].right === stack[s]) {
return true
}
}
return false
}
})
//Default comparison function
function defaultCompare(a, b) {
if(a < b) {
return -1
}
if(a > b) {
return 1
}
return 0
}
//Build a tree
function createRBTree(compare) {
return new RedBlackTree(compare || defaultCompare, null)
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/functional-red-black-tree/bench/test.js | aws/lti-middleware/node_modules/functional-red-black-tree/bench/test.js | "use strict"
var createTree = require("../rbtree.js")
var t = createTree()
var s = Date.now()
for(var i=0; i<100000; ++i) {
t = t.insert(Math.random(), Math.random())
}
console.log(Date.now() - s) | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/functional-red-black-tree/test/test.js | aws/lti-middleware/node_modules/functional-red-black-tree/test/test.js | "use strict"
var makeTree = require("../rbtree.js")
var tape = require("tape")
var util = require("util")
var iota = require("iota-array")
var COLORS = [ "r", "b", "bb" ]
function printTree(tree) {
if(!tree) {
return []
}
return [ COLORS[tree._color], tree.key, printTree(tree.left), printTree(tree.right) ]
}
function print(t) {
console.log(util.inspect(printTree(t.root), {depth:12}))
}
//Ensures the red black axioms are satisfied by tree
function checkTree(tree, t) {
if(!tree.root) {
return
}
t.equals(tree.root._color, 1, "root is black")
function checkNode(node) {
if(!node) {
return [1, 0]
}
if(node._color === 0) {
t.assert(!node.left || node.left._color === 1, "children of red node must be black")
t.assert(!node.right || node.right._color === 1, "children of red node must be black")
} else {
t.equals(node._color, 1, "node color must be red or black")
}
if(node.left) {
t.assert(tree._compare(node.left.key, node.key) <= 0, "left tree order invariant")
}
if(node.right) {
t.assert(tree._compare(node.right.key, node.key) >= 0, "right tree order invariant")
}
var cl = checkNode(node.left)
var cr = checkNode(node.right)
t.equals(cl[0], cr[0], "number of black nodes along all paths to root must be constant")
t.equals(cl[1] + cr[1] + 1, node._count, "item count consistency")
return [cl[0] + node._color, cl[1] + cr[1] + 1]
}
var r = checkNode(tree.root)
t.equals(r[1], tree.length, "tree length")
}
tape("insert()", function(t) {
var t1 = makeTree()
var u = t1
var arr = []
for(var i=20; i>=0; --i) {
var x = i
var next = u.insert(x, true)
checkTree(u, t)
checkTree(next, t)
t.equals(u.length, arr.length)
arr.push(x)
u = next
}
for(var i=-20; i<0; ++i) {
var x = i
var next = u.insert(x, true)
checkTree(u, t)
checkTree(next, t)
arr.sort(function(a,b) { return a-b })
var ptr = 0
u.forEach(function(k,v) {
t.equals(k, arr[ptr++])
})
t.equals(ptr, arr.length)
arr.push(x)
u = next
}
var start = u.begin
for(var i=-20, j=0; j<=40; ++i, ++j) {
t.equals(u.at(j).key, i, "checking at()")
t.equals(start.key, i, "checking iter")
t.equals(start.index, j, "checking index")
t.assert(start.valid, "checking valid")
if(j < 40) {
t.assert(start.hasNext, "hasNext()")
} else {
t.assert(!start.hasNext, "eof hasNext()")
}
start.next()
}
t.assert(!start.valid, "invalid eof iterator")
t.assert(!start.hasNext, "hasNext() at eof fail")
t.equals(start.index, 41, "eof index")
t.end()
})
tape("foreach", function(t) {
var u = iota(31).reduce(function(u, k, v) {
return u.insert(k, v)
}, makeTree())
//Check basic foreach
var visit_keys = []
var visit_vals = []
u.forEach(function(k,v) {
visit_keys.push(k)
visit_vals.push(v)
})
t.same(visit_keys, u.keys)
t.same(visit_vals, u.values)
//Check foreach with termination
visit_keys = []
visit_vals = []
t.equals(u.forEach(function(k,v) {
if(k === 5) {
return 1000
}
visit_keys.push(k)
visit_vals.push(v)
}), 1000)
t.same(visit_keys, u.keys.slice(0, 5))
t.same(visit_vals, u.values.slice(0, 5))
//Check half interval foreach
visit_keys = []
visit_vals = []
u.forEach(function(k,v) {
visit_keys.push(k)
visit_vals.push(v)
}, 3)
t.same(visit_keys, u.keys.slice(3))
t.same(visit_vals, u.values.slice(3))
//Check half interval foreach with termination
visit_keys = []
visit_vals = []
t.equals(u.forEach(function(k,v) {
if(k === 12) {
return 1000
}
visit_keys.push(k)
visit_vals.push(v)
}, 3), 1000)
t.same(visit_keys, u.keys.slice(3, 12))
t.same(visit_vals, u.values.slice(3, 12))
//Check interval foreach
visit_keys = []
visit_vals = []
u.forEach(function(k,v) {
visit_keys.push(k)
visit_vals.push(v)
}, 3, 15)
t.same(visit_keys, u.keys.slice(3, 15))
t.same(visit_vals, u.values.slice(3, 15))
//Check interval foreach with termination
visit_keys = []
visit_vals = []
t.equals(u.forEach(function(k,v) {
if(k === 12) {
return 1000
}
visit_keys.push(k)
visit_vals.push(v)
}, 3, 15), 1000)
t.same(visit_keys, u.keys.slice(3, 12))
t.same(visit_vals, u.values.slice(3, 12))
t.end()
})
function compareIterators(a, b, t) {
t.equals(a.tree, b.tree, "iter trees")
t.equals(a.valid, b.valid, "iter validity")
if(!b.valid) {
return
}
t.equals(a.node, b.node, "iter node")
t.equals(a.key, b.key, "iter key")
t.equals(a.value, b.value, "iter value")
t.equals(a.index, b.index, "iter index")
}
tape("iterators", function(t) {
var u = iota(20).reduce(function(u, k, v) {
return u.insert(k, v)
}, makeTree())
//Try walking forward
var iter = u.begin
var c = iter.clone()
t.ok(iter.hasNext, "must have next at beginneing")
t.ok(!iter.hasPrev, "must not have predecessor")
for(var i=0; i<20; ++i) {
var v = u.at(i)
compareIterators(iter, v, t)
t.equals(iter.index, i)
iter.next()
}
t.ok(!iter.valid, "must be eof iterator")
//Check if the clone worked
compareIterators(c, u.begin, t)
//Try walking backward
var iter = u.end
t.ok(!iter.hasNext, "must not have next")
t.ok(iter.hasPrev, "must have predecessor")
for(var i=19; i>=0; --i) {
var v = u.at(i)
compareIterators(iter, v, t)
t.equals(iter.index, i)
iter.prev()
}
t.ok(!iter.valid, "must be eof iterator")
t.end()
})
tape("remove()", function(t) {
var sz = [1, 2, 10, 20, 23, 31, 32, 33]
for(var n=0; n<sz.length; ++n) {
var c = sz[n]
var u = iota(c).reduce(function(u, k, v) {
return u.insert(k, v)
}, makeTree())
for(var i=0; i<c; ++i) {
checkTree(u.remove(i), t)
}
}
t.end()
})
tape("update()", function(t) {
var arr = [0, 1, 2, 3, 4, 5, 6 ]
var u = arr.reduce(function(u, k, v) {
return u.insert(k, v)
}, makeTree())
for(var iter=u.begin; iter.hasNext; iter.next()) {
var p = iter.value
var updated = iter.update(1000)
t.equals(iter.value, iter.key, "ensure no mutation")
t.equals(updated.find(iter.key).value, 1000, "ensure update applied")
checkTree(updated, t)
checkTree(u, t)
}
t.end()
})
tape("keys and values", function(t) {
var original_keys = [ "potato", "sock", "foot", "apple", "newspaper", "gameboy" ]
var original_values = [ 42, 10, false, "!!!", {}, null ]
var u = makeTree()
for(var i=0; i<original_keys.length; ++i) {
u = u.insert(original_keys[i], original_values[i])
}
var zipped = iota(6).map(function(i) {
return [ original_keys[i], original_values[i] ]
})
zipped.sort(function(a,b) {
if(a[0] < b[0]) { return -1 }
if(a[0] > b[0]) { return 1 }
return 0
})
var keys = zipped.map(function(v) { return v[0] })
var values = zipped.map(function(v) { return v[1] })
t.same(u.keys, keys)
t.same(u.values, values)
t.end()
})
tape("searching", function(t) {
var arr = [0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 6 ]
var u = arr.reduce(function(u, k, v) {
return u.insert(k, v)
}, makeTree())
for(var i=0; i<arr.length; ++i) {
if(arr[i] !== arr[i-1] && arr[i] !== arr[i+1]) {
t.equals(u.get(arr[i]), i, "get " + arr[i])
}
}
t.equals(u.get(-1), undefined, "get missing")
t.equals(u.ge(3).index, 6, "ge simple")
t.equals(u.ge(0.9).index, 1, "ge run start")
t.equals(u.ge(1).index, 1, "ge run mid")
t.equals(u.ge(1.1).index, 5, "ge run end")
t.equals(u.ge(0).index, 0, "ge first")
t.equals(u.ge(6).index, 9, "ge last")
t.equals(u.ge(100).valid, false, "ge big")
t.equals(u.ge(-1).index, 0, "ge small")
t.equals(u.gt(3).index, 7, "gt simple")
t.equals(u.gt(0.9).index, 1, "gt run start")
t.equals(u.gt(1).index, 5, "gt run mid")
t.equals(u.gt(1.1).index, 5, "gt run end")
t.equals(u.gt(0).index, 1, "gt first")
t.equals(u.gt(6).valid, false, "gt last")
t.equals(u.gt(100).valid, false, "gt big")
t.equals(u.gt(-1).index, 0, "ge small")
t.equals(u.le(3).index, 6, "le simple")
t.equals(u.le(0.9).index, 0, "le run start")
t.equals(u.le(1).index, 4, "le run mid")
t.equals(u.le(1.1).index, 4, "le run end")
t.equals(u.le(0).index, 0, "le first")
t.equals(u.le(6).index, 10, "le last")
t.equals(u.le(100).index, 10, "le big")
t.equals(u.le(-1).valid, false, "le small")
t.equals(u.lt(3).index, 5, "lt simple")
t.equals(u.lt(0.9).index, 0, "lt run start")
t.equals(u.lt(1).index, 0, "lt run mid")
t.equals(u.lt(1.1).index, 4, "lt run end")
t.equals(u.lt(0).valid, false, "lt first")
t.equals(u.lt(6).index, 8, "lt last")
t.equals(u.lt(100).index, 10, "lt big")
t.equals(u.lt(-1).valid, false, "lt small")
t.equals(u.find(-1).valid, false, "find missing small")
t.equals(u.find(10000).valid, false, "find missing big")
t.equals(u.find(3).index, 6, "find simple")
t.ok(u.find(1).index > 0, "find repeat")
t.ok(u.find(1).index < 5, "find repeat")
for(var i=0; i<arr.length; ++i) {
t.equals(u.find(arr[i]).key, arr[i], "find " + i)
}
for(var i=0; i<arr.length; ++i) {
t.equals(u.at(i).key, arr[i], "at " + i)
}
t.equals(u.at(-1).valid, false, "at missing small")
t.equals(u.at(1000).valid, false, "at missing big")
t.end()
})
tape("slab-sequence", function(t) {
var tree = makeTree()
tree=tree.insert(0, 0)
checkTree(tree, t)
t.same(tree.values, [0])
tree=tree.insert(1, 1)
checkTree(tree, t)
t.same(tree.values, [0,1])
tree=tree.insert(0.5, 2)
checkTree(tree, t)
t.same(tree.values, [0,2,1])
tree=tree.insert(0.25, 3)
checkTree(tree, t)
t.same(tree.values, [0,3,2,1])
tree=tree.remove(0)
checkTree(tree, t)
t.same(tree.values, [3,2,1])
tree=tree.insert(0.375, 4)
checkTree(tree, t)
t.same(tree.values, [3, 4, 2, 1])
tree=tree.remove(1)
checkTree(tree, t)
t.same(tree.values, [3,4,2])
tree=tree.remove(0.5)
checkTree(tree, t)
t.same(tree.values, [3,4])
tree=tree.remove(0.375)
checkTree(tree, t)
t.same(tree.values, [3])
tree=tree.remove(0.25)
checkTree(tree, t)
t.same(tree.values, [])
t.end()
})
tape("slab-sequence-2", function(t) {
var u = makeTree()
u=u.insert( 12 , 22 )
u=u.insert( 11 , 3 )
u=u.insert( 10 , 28 )
u=u.insert( 13 , 16 )
u=u.insert( 9 , 9 )
u=u.insert( 14 , 10 )
u=u.insert( 8 , 15 )
u=u.insert( 15 , 29 )
u=u.insert( 16 , 4 )
u=u.insert( 7 , 21 )
u=u.insert( 17 , 23 )
u=u.insert( 6 , 2 )
u=u.insert( 5 , 27 )
u=u.insert( 18 , 17 )
u=u.insert( 4 , 8 )
u=u.insert( 31 , 11 )
u=u.insert( 30 , 30 )
u=u.insert( 29 , 5 )
u=u.insert( 28 , 24 )
u=u.insert( 27 , 18 )
u=u.insert( 26 , 12 )
u=u.insert( 25 , 31 )
u=u.insert( 24 , 6 )
u=u.insert( 23 , 25 )
u=u.insert( 19 , 7 )
u=u.insert( 20 , 13 )
u=u.insert( 1 , 20 )
u=u.insert( 0 , 14 )
u=u.insert( 22 , 0 )
u=u.insert( 2 , 1 )
u=u.insert( 3 , 26 )
u=u.insert( 21 , 19 )
u=u.remove( 18 , 17 )
u=u.remove( 17 , 23 )
u=u.remove( 16 , 4 )
u=u.remove( 15 , 29 )
u=u.remove( 14 , 10 )
u=u.remove( 13 , 16 )
u=u.remove( 12 , 22 )
u=u.remove( 6 , 2 )
u=u.remove( 7 , 21 )
u=u.remove( 8 , 15 )
u=u.remove( 11 , 3 )
u=u.remove( 4 , 8 )
u=u.remove( 9 , 9 )
u=u.remove( 10 , 28 )
u=u.remove( 5 , 27 )
u=u.remove( 31 , 11 )
u=u.remove( 0 , 14 )
u=u.remove( 30 , 30 )
u=u.remove( 29 , 5 )
u=u.remove( 1 , 20 )
u=u.remove( 28 , 24 )
u=u.remove( 2 , 1 )
u=u.remove( 3 , 26 )
u=u.remove( 27 , 18 )
u=u.remove( 19 , 7 )
u=u.remove( 26 , 12 )
u=u.remove( 20 , 13 )
u=u.remove( 25 , 31 )
u=u.remove( 24 , 6 )
u=u.remove( 21 , 19 )
u=u.remove( 23 , 25 )
u=u.remove( 22 , 0 )
t.end()
})
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/extend/index.js | aws/lti-middleware/node_modules/extend/index.js | 'use strict';
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var defineProperty = Object.defineProperty;
var gOPD = Object.getOwnPropertyDescriptor;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
return Array.isArray(arr);
}
return toStr.call(arr) === '[object Array]';
};
var isPlainObject = function isPlainObject(obj) {
if (!obj || toStr.call(obj) !== '[object Object]') {
return false;
}
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) { /**/ }
return typeof key === 'undefined' || hasOwn.call(obj, key);
};
// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
var setProperty = function setProperty(target, options) {
if (defineProperty && options.name === '__proto__') {
defineProperty(target, options.name, {
enumerable: true,
configurable: true,
value: options.newValue,
writable: true
});
} else {
target[options.name] = options.newValue;
}
};
// Return undefined instead of __proto__ if '__proto__' is not an own property
var getProperty = function getProperty(obj, name) {
if (name === '__proto__') {
if (!hasOwn.call(obj, name)) {
return void 0;
} else if (gOPD) {
// In early versions of node, obj['__proto__'] is buggy when obj has
// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
return gOPD(obj, name).value;
}
}
return obj[name];
};
module.exports = function extend() {
var options, name, src, copy, copyIsArray, clone;
var target = arguments[0];
var i = 1;
var length = arguments.length;
var deep = false;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
target = {};
}
for (; i < length; ++i) {
options = arguments[i];
// Only deal with non-null/undefined values
if (options != null) {
// Extend the base object
for (name in options) {
src = getProperty(target, name);
copy = getProperty(options, name);
// Prevent never-ending loop
if (target !== copy) {
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
// Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
setProperty(target, { name: name, newValue: copy });
}
}
}
}
}
// Return the modified object
return target;
};
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/encodings.js | aws/lti-middleware/node_modules/text-decoding/src/encodings.js | /**
* Encodings table: https://encoding.spec.whatwg.org/encodings.json
*/
const encodings = [
{
encodings: [
{
labels: [
"unicode-1-1-utf-8",
"utf-8",
"utf8",
],
name: "UTF-8",
},
],
heading: "The Encoding",
},
{
encodings: [
{
labels: [
"866",
"cp866",
"csibm866",
"ibm866",
],
name: "IBM866",
},
{
labels: [
"csisolatin2",
"iso-8859-2",
"iso-ir-101",
"iso8859-2",
"iso88592",
"iso_8859-2",
"iso_8859-2:1987",
"l2",
"latin2",
],
name: "ISO-8859-2",
},
{
labels: [
"csisolatin3",
"iso-8859-3",
"iso-ir-109",
"iso8859-3",
"iso88593",
"iso_8859-3",
"iso_8859-3:1988",
"l3",
"latin3",
],
name: "ISO-8859-3",
},
{
labels: [
"csisolatin4",
"iso-8859-4",
"iso-ir-110",
"iso8859-4",
"iso88594",
"iso_8859-4",
"iso_8859-4:1988",
"l4",
"latin4",
],
name: "ISO-8859-4",
},
{
labels: [
"csisolatincyrillic",
"cyrillic",
"iso-8859-5",
"iso-ir-144",
"iso8859-5",
"iso88595",
"iso_8859-5",
"iso_8859-5:1988",
],
name: "ISO-8859-5",
},
{
labels: [
"arabic",
"asmo-708",
"csiso88596e",
"csiso88596i",
"csisolatinarabic",
"ecma-114",
"iso-8859-6",
"iso-8859-6-e",
"iso-8859-6-i",
"iso-ir-127",
"iso8859-6",
"iso88596",
"iso_8859-6",
"iso_8859-6:1987",
],
name: "ISO-8859-6",
},
{
labels: [
"csisolatingreek",
"ecma-118",
"elot_928",
"greek",
"greek8",
"iso-8859-7",
"iso-ir-126",
"iso8859-7",
"iso88597",
"iso_8859-7",
"iso_8859-7:1987",
"sun_eu_greek",
],
name: "ISO-8859-7",
},
{
labels: [
"csiso88598e",
"csisolatinhebrew",
"hebrew",
"iso-8859-8",
"iso-8859-8-e",
"iso-ir-138",
"iso8859-8",
"iso88598",
"iso_8859-8",
"iso_8859-8:1988",
"visual",
],
name: "ISO-8859-8",
},
{
labels: [
"csiso88598i",
"iso-8859-8-i",
"logical",
],
name: "ISO-8859-8-I",
},
{
labels: [
"csisolatin6",
"iso-8859-10",
"iso-ir-157",
"iso8859-10",
"iso885910",
"l6",
"latin6",
],
name: "ISO-8859-10",
},
{
labels: [
"iso-8859-13",
"iso8859-13",
"iso885913",
],
name: "ISO-8859-13",
},
{
labels: [
"iso-8859-14",
"iso8859-14",
"iso885914",
],
name: "ISO-8859-14",
},
{
labels: [
"csisolatin9",
"iso-8859-15",
"iso8859-15",
"iso885915",
"iso_8859-15",
"l9",
],
name: "ISO-8859-15",
},
{
labels: [
"iso-8859-16",
],
name: "ISO-8859-16",
},
{
labels: [
"cskoi8r",
"koi",
"koi8",
"koi8-r",
"koi8_r",
],
name: "KOI8-R",
},
{
labels: [
"koi8-ru",
"koi8-u",
],
name: "KOI8-U",
},
{
labels: [
"csmacintosh",
"mac",
"macintosh",
"x-mac-roman",
],
name: "macintosh",
},
{
labels: [
"dos-874",
"iso-8859-11",
"iso8859-11",
"iso885911",
"tis-620",
"windows-874",
],
name: "windows-874",
},
{
labels: [
"cp1250",
"windows-1250",
"x-cp1250",
],
name: "windows-1250",
},
{
labels: [
"cp1251",
"windows-1251",
"x-cp1251",
],
name: "windows-1251",
},
{
labels: [
"ansi_x3.4-1968",
"ascii",
"cp1252",
"cp819",
"csisolatin1",
"ibm819",
"iso-8859-1",
"iso-ir-100",
"iso8859-1",
"iso88591",
"iso_8859-1",
"iso_8859-1:1987",
"l1",
"latin1",
"us-ascii",
"windows-1252",
"x-cp1252",
],
name: "windows-1252",
},
{
labels: [
"cp1253",
"windows-1253",
"x-cp1253",
],
name: "windows-1253",
},
{
labels: [
"cp1254",
"csisolatin5",
"iso-8859-9",
"iso-ir-148",
"iso8859-9",
"iso88599",
"iso_8859-9",
"iso_8859-9:1989",
"l5",
"latin5",
"windows-1254",
"x-cp1254",
],
name: "windows-1254",
},
{
labels: [
"cp1255",
"windows-1255",
"x-cp1255",
],
name: "windows-1255",
},
{
labels: [
"cp1256",
"windows-1256",
"x-cp1256",
],
name: "windows-1256",
},
{
labels: [
"cp1257",
"windows-1257",
"x-cp1257",
],
name: "windows-1257",
},
{
labels: [
"cp1258",
"windows-1258",
"x-cp1258",
],
name: "windows-1258",
},
{
labels: [
"x-mac-cyrillic",
"x-mac-ukrainian",
],
name: "x-mac-cyrillic",
},
],
heading: "Legacy single-byte encodings",
},
{
encodings: [
{
labels: [
"chinese",
"csgb2312",
"csiso58gb231280",
"gb2312",
"gb_2312",
"gb_2312-80",
"gbk",
"iso-ir-58",
"x-gbk",
],
name: "GBK",
},
{
labels: [
"gb18030",
],
name: "gb18030",
},
],
heading: "Legacy multi-byte Chinese (simplified) encodings",
},
{
encodings: [
{
labels: [
"big5",
"big5-hkscs",
"cn-big5",
"csbig5",
"x-x-big5",
],
name: "Big5",
},
],
heading: "Legacy multi-byte Chinese (traditional) encodings",
},
{
encodings: [
{
labels: [
"cseucpkdfmtjapanese",
"euc-jp",
"x-euc-jp",
],
name: "EUC-JP",
},
{
labels: [
"csiso2022jp",
"iso-2022-jp",
],
name: "ISO-2022-JP",
},
{
labels: [
"csshiftjis",
"ms932",
"ms_kanji",
"shift-jis",
"shift_jis",
"sjis",
"windows-31j",
"x-sjis",
],
name: "Shift_JIS",
},
],
heading: "Legacy multi-byte Japanese encodings",
},
{
encodings: [
{
labels: [
"cseuckr",
"csksc56011987",
"euc-kr",
"iso-ir-149",
"korean",
"ks_c_5601-1987",
"ks_c_5601-1989",
"ksc5601",
"ksc_5601",
"windows-949",
],
name: "EUC-KR",
},
],
heading: "Legacy multi-byte Korean encodings",
},
{
encodings: [
{
labels: [
"csiso2022kr",
"hz-gb-2312",
"iso-2022-cn",
"iso-2022-cn-ext",
"iso-2022-kr",
],
name: "replacement",
},
{
labels: [
"utf-16be",
],
name: "UTF-16BE",
},
{
labels: [
"utf-16",
"utf-16le",
],
name: "UTF-16LE",
},
{
labels: [
"x-user-defined",
],
name: "x-user-defined",
},
],
heading: "Legacy miscellaneous encodings",
},
]
export default encodings | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/index.js | aws/lti-middleware/node_modules/text-decoding/src/index.js | import TextEncoder from './lib/TextEncoder'
import TextDecoder from './lib/TextDecoder'
import EncodingIndexes from './encoding-indexes'
import { getEncoding } from './lib'
//
// Implementation of Encoding specification
// https://encoding.spec.whatwg.org/
//
export { TextEncoder, TextDecoder, EncodingIndexes, getEncoding } | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/table.js | aws/lti-middleware/node_modules/text-decoding/src/table.js | import Encodings from './encodings'
import { UTF8Decoder, UTF8Encoder } from './implementations/utf8'
import { UTF16Decoder, UTF16Encoder } from './implementations/utf16'
import { GB18030Decoder, GB18030Encoder } from './implementations/gb18030'
import { Big5Decoder, Big5Encoder } from './implementations/big5'
import { EUCJPDecoder, EUCJPEncoder } from './implementations/euc-jp'
import { EUCKRDecoder, EUCKREncoder } from './implementations/euc-kr'
import { ISO2022JPDecoder, ISO2022JPEncoder } from './implementations/iso-2022-jp'
import { XUserDefinedDecoder, XUserDefinedEncoder } from './implementations/x-user-defined'
import { ShiftJISDecoder, ShiftJISEncoder } from './implementations/shift-jis'
import { SingleByteDecoder, SingleByteEncoder } from './implementations/single-byte'
import index from './indexes';
// 5.2 Names and labels
// TODO: Define @typedef for Encoding: {name:string,labels:Array.<string>}
// https://github.com/google/closure-compiler/issues/247
// Label to encoding registry.
/** @type {Object.<string,{name:string,labels:Array.<string>}>} */
export const label_to_encoding = {}
Encodings.forEach(({ encodings }) => {
encodings.forEach((encoding) => {
encoding.labels.forEach((label) => {
label_to_encoding[label] = encoding
})
})
})
// Registry of of encoder/decoder factories, by encoding name.
export const encoders = {
'UTF-8'() { // 9.1 utf-8
return new UTF8Encoder()
},
'GBK'(options) { // 11.1.2 gbk encoder;
// gbk's encoder is gb18030's encoder with its gbk flag set.
return new GB18030Encoder(options, true)
},
'gb18030'() {
return new GB18030Encoder()
},
'Big5'() {
return new Big5Encoder()
},
'EUC-JP'() {
return new EUCJPEncoder()
},
'EUC-KR'() {
return new EUCKREncoder()
},
'ISO-2022-JP'() {
return new ISO2022JPEncoder()
},
'UTF-16BE'() { // 15.3 utf-16be
return new UTF16Encoder(true)
},
'UTF-16LE'() { // 15.4 utf-16le
return new UTF16Encoder()
},
'x-user-defined'() {
return new XUserDefinedEncoder()
},
'Shift_JIS'() {
return new ShiftJISEncoder()
},
}
/** @type {Object.<string, function({fatal:boolean}): Decoder>} */
export const decoders = {
'UTF-8'(options) { // 9.1.1 utf-8 decoder
return new UTF8Decoder(options)
},
'GBK'(options) { // 11.1.1 gbk decoder; gbk's decoder is gb18030's decoder.
return new GB18030Decoder(options)
},
'gb18030'(options) {
return new GB18030Decoder(options)
},
'Big5'(options) {
return new Big5Decoder(options)
},
'EUC-JP'(options) {
return new EUCJPDecoder(options)
},
'EUC-KR'(options) {
return new EUCKRDecoder(options)
},
'ISO-2022-JP'(options) {
return new ISO2022JPDecoder(options)
},
'UTF-16BE'(options) { // 15.3.1 utf-16be decoder
return new UTF16Decoder(true, options)
},
'UTF-16LE'(options) { // 15.4.1 utf-16le decoder
return new UTF16Decoder(false, options)
},
'x-user-defined'() {
return new XUserDefinedDecoder()
},
'Shift_JIS'(options) {
return new ShiftJISDecoder(options)
},
}
Encodings.forEach(({ heading, encodings }) => {
if (heading != 'Legacy single-byte encodings')
return
encodings.forEach((encoding) => {
const name = encoding.name
const idx = index(name.toLowerCase())
decoders[name] = (options) => {
return new SingleByteDecoder(idx, options)
}
encoders[name] = (options) => {
return new SingleByteEncoder(idx, options)
}
})
}) | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/encoding-indexes.js | aws/lti-middleware/node_modules/text-decoding/src/encoding-indexes.js | const Indexes = {
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | true |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/indexes.js | aws/lti-middleware/node_modules/text-decoding/src/indexes.js | import { inRange } from './utils'
import Indexes from './encoding-indexes'
//
// 6. Indexes
//
/**
* @param {number} pointer The |pointer| to search for.
* @param {(!Array.<?number>|undefined)} index The |index| to search within.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in |index|.
*/
export function indexCodePointFor(pointer, i) {
if (!i) return null
return i[pointer] || null
}
/**
* @param {number} code_point The |code point| to search for.
* @param {!Array.<?number>} i The |index| to search within.
* @return {?number} The first pointer corresponding to |code point| in
* |index|, or null if |code point| is not in |index|.
*/
export function indexPointerFor(code_point, i) {
var pointer = i.indexOf(code_point)
return pointer === -1 ? null : pointer
}
/**
* @param {string} name Name of the index.
*/
export default function index(name) {
return Indexes[name]
}
/**
* @param {number} pointer The |pointer| to search for in the gb18030 index.
* @return The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in the gb18030 index.
*/
export function indexGB18030RangesCodePointFor(pointer) {
// 1. If pointer is greater than 39419 and less than 189000, or
// pointer is greater than 1237575, return null.
if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575))
return null
// 2. If pointer is 7457, return code point U+E7C7.
if (pointer === 7457) return 0xE7C7
// 3. Let offset be the last pointer in index gb18030 ranges that
// is equal to or less than pointer and let code point offset be
// its corresponding code point.
var offset = 0
var code_point_offset = 0
var idx = index('gb18030-ranges')
var i
for (i = 0; i < idx.length; ++i) {
/** @type {!Array.<number>} */
var entry = idx[i]
if (entry[0] <= pointer) {
offset = entry[0]
code_point_offset = entry[1]
} else {
break
}
}
// 4. Return a code point whose value is code point offset +
// pointer − offset.
return code_point_offset + pointer - offset
}
/**
* @param {number} code_point The |code point| to locate in the gb18030 index.
* @return {number} The first pointer corresponding to |code point| in the
* gb18030 index.
*/
export function indexGB18030RangesPointerFor(code_point) {
// 1. If code point is U+E7C7, return pointer 7457.
if (code_point === 0xE7C7) return 7457
// 2. Let offset be the last code point in index gb18030 ranges
// that is equal to or less than code point and let pointer offset
// be its corresponding pointer.
var offset = 0
var pointer_offset = 0
var idx = index('gb18030-ranges')
var i
for (i = 0; i < idx.length; ++i) {
/** @type {!Array.<number>} */
var entry = idx[i]
if (entry[1] <= code_point) {
offset = entry[1]
pointer_offset = entry[0]
} else {
break
}
}
// 3. Return a pointer whose value is pointer offset + code point
// − offset.
return pointer_offset + code_point - offset
}
/**
* @param {number} code_point The |code_point| to search for in the Shift_JIS
* index.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in the Shift_JIS index.
*/
export function indexShiftJISPointerFor(code_point) {
// 1. Let index be index jis0208 excluding all entries whose
// pointer is in the range 8272 to 8835, inclusive.
shift_jis_index = shift_jis_index ||
index('jis0208').map((cp, pointer) => {
return inRange(pointer, 8272, 8835) ? null : cp
})
const index_ = shift_jis_index
// 2. Return the index pointer for code point in index.
return index_.indexOf(code_point)
}
var shift_jis_index
/**
* @param {number} code_point The |code_point| to search for in the big5
* index.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in the big5 index.
*/
export function indexBig5PointerFor(code_point) {
// 1. Let index be index Big5 excluding all entries whose pointer
big5_index_no_hkscs = big5_index_no_hkscs ||
index('big5').map((cp, pointer) => {
return (pointer < (0xA1 - 0x81) * 157) ? null : cp
})
var index_ = big5_index_no_hkscs
// 2. If code point is U+2550, U+255E, U+2561, U+256A, U+5341, or
// U+5345, return the last pointer corresponding to code point in
// index.
if (code_point === 0x2550 || code_point === 0x255E ||
code_point === 0x2561 || code_point === 0x256A ||
code_point === 0x5341 || code_point === 0x5345) {
return index_.lastIndexOf(code_point)
}
// 3. Return the index pointer for code point in index.
return indexPointerFor(code_point, index_)
}
var big5_index_no_hkscs | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/utils.js | aws/lti-middleware/node_modules/text-decoding/src/utils.js | //
// Utilities
//
/**
* @param {number} a The number to test.
* @param {number} min The minimum value in the range, inclusive.
* @param {number} max The maximum value in the range, inclusive.
* @return {boolean} True if a >= min and a <= max.
*/
export function inRange(a, min, max) {
return min <= a && a <= max
}
export const floor = Math.floor
/**
* @param {string} string Input string of UTF-16 code units.
* @return {!Array.<number>} Code points.
*/
export function stringToCodePoints(string) {
// https://heycam.github.io/webidl/#dfn-obtain-unicode
// 1. Let S be the DOMString value.
var s = String(string)
// 2. Let n be the length of S.
var n = s.length
// 3. Initialize i to 0.
var i = 0
// 4. Initialize U to be an empty sequence of Unicode characters.
var u = []
// 5. While i < n:
while (i < n) {
// 1. Let c be the code unit in S at index i.
var c = s.charCodeAt(i)
// 2. Depending on the value of c:
// c < 0xD800 or c > 0xDFFF
if (c < 0xD800 || c > 0xDFFF) {
// Append to U the Unicode character with code point c.
u.push(c)
}
// 0xDC00 ≤ c ≤ 0xDFFF
else if (0xDC00 <= c && c <= 0xDFFF) {
// Append to U a U+FFFD REPLACEMENT CHARACTER.
u.push(0xFFFD)
}
// 0xD800 ≤ c ≤ 0xDBFF
else if (0xD800 <= c && c <= 0xDBFF) {
// 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
// CHARACTER.
if (i === n - 1) {
u.push(0xFFFD)
}
// 2. Otherwise, i < n−1:
else {
// 1. Let d be the code unit in S at index i+1.
var d = s.charCodeAt(i + 1)
// 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
if (0xDC00 <= d && d <= 0xDFFF) {
// 1. Let a be c & 0x3FF.
var a = c & 0x3FF
// 2. Let b be d & 0x3FF.
var b = d & 0x3FF
// 3. Append to U the Unicode character with code point
// 2^16+2^10*a+b.
u.push(0x10000 + (a << 10) + b)
// 4. Set i to i+1.
i += 1
}
// 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a
// U+FFFD REPLACEMENT CHARACTER.
else {
u.push(0xFFFD)
}
}
}
// 3. Set i to i+1.
i += 1
}
// 6. Return U.
return u
}
/**
* @param {!Array.<number>} code_points Array of code points.
* @return {string} string String of UTF-16 code units.
*/
export function codePointsToString(code_points) {
var s = ''
for (var i = 0; i < code_points.length; ++i) {
var cp = code_points[i]
if (cp <= 0xFFFF) {
s += String.fromCharCode(cp)
} else {
cp -= 0x10000
s += String.fromCharCode((cp >> 10) + 0xD800,
(cp & 0x3FF) + 0xDC00)
}
}
return s
}
/**
* @param {boolean} fatal If true, decoding errors raise an exception.
* @param {number=} opt_code_point Override the standard fallback code point.
* @return The code point to insert on a decoding error.
*/
export function decoderError(fatal, opt_code_point) {
if (fatal)
throw TypeError('Decoder error')
return opt_code_point || 0xFFFD
}
/**
* @param {number} code_point The code point that could not be encoded.
* @return {number} Always throws, no value is actually returned.
*/
export function encoderError(code_point) {
throw TypeError('The code point ' + code_point + ' could not be encoded.')
}
/**
* @param {number} code_unit
* @param {boolean} utf16be
*/
export function convertCodeUnitToBytes(code_unit, utf16be) {
// 1. Let byte1 be code unit >> 8.
const byte1 = code_unit >> 8
// 2. Let byte2 be code unit & 0x00FF.
const byte2 = code_unit & 0x00FF
// 3. Then return the bytes in order:
// utf-16be flag is set: byte1, then byte2.
if (utf16be)
return [byte1, byte2]
// utf-16be flag is unset: byte2, then byte1.
return [byte2, byte1]
}
//
// 4. Terminology
//
/**
* An ASCII byte is a byte in the range 0x00 to 0x7F, inclusive.
* @param {number} a The number to test.
* @return {boolean} True if a is in the range 0x00 to 0x7F, inclusive.
*/
export function isASCIIByte(a) {
return 0x00 <= a && a <= 0x7F
}
/**
* An ASCII code point is a code point in the range U+0000 to
* U+007F, inclusive.
*/
export const isASCIICodePoint = isASCIIByte
/**
* End-of-stream is a special token that signifies no more tokens are in the stream.
*/
export const end_of_stream = -1
export const finished = -1 | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/lib/TextDecoder.js | aws/lti-middleware/node_modules/text-decoding/src/lib/TextDecoder.js | import Stream, { DEFAULT_ENCODING, getEncoding } from './'
import { end_of_stream, finished, codePointsToString } from '../utils'
import { decoders } from '../table'
// 8.1 Interface TextDecoder
export default class TextDecoder {
/**
* @param {string=} label The label of the encoding; defaults to 'utf-8'.
* @param {Object=} options
*/
constructor(label = DEFAULT_ENCODING, options = {}) {
// A TextDecoder object has an associated encoding, decoder,
// stream, ignore BOM flag (initially unset), BOM seen flag
// (initially unset), error mode (initially replacement), and do
// not flush flag (initially unset).
/** @private */
this._encoding = null
/** @private @type {?Decoder} */
this._decoder = null
/** @private @type {boolean} */
this._ignoreBOM = false
/** @private @type {boolean} */
this._BOMseen = false
/** @private @type {string} */
this._error_mode = 'replacement'
/** @private @type {boolean} */
this._do_not_flush = false
// 1. Let encoding be the result of getting an encoding from
// label.
const encoding = getEncoding(label)
// 2. If encoding is failure or replacement, throw a RangeError.
if (encoding === null || encoding.name == 'replacement')
throw RangeError('Unknown encoding: ' + label)
if (!decoders[encoding.name]) {
throw Error('Decoder not present.' +
' Did you forget to include encoding-indexes.js first?')
}
// 4. Set dec's encoding to encoding.
this._encoding = encoding
// 5. If options's fatal member is true, set dec's error mode to
// fatal.
if (options['fatal'])
this._error_mode = 'fatal'
// 6. If options's ignoreBOM member is true, set dec's ignore BOM
// flag.
if (options['ignoreBOM'])
this._ignoreBOM = true
}
get encoding() {
return this._encoding.name.toLowerCase()
}
get fatal() {
return this._error_mode === 'fatal'
}
get ignoreBOM() {
return this._ignoreBOM
}
/**
* @param {BufferSource=} input The buffer of bytes to decode.
* @param {Object=} options
* @return The decoded string.
*/
decode(input, options = {}) {
let bytes
if (typeof input === 'object' && input instanceof ArrayBuffer) {
bytes = new Uint8Array(input)
} else if (typeof input === 'object' && 'buffer' in input &&
input.buffer instanceof ArrayBuffer) {
bytes = new Uint8Array(input.buffer,
input.byteOffset,
input.byteLength)
} else {
bytes = new Uint8Array(0)
}
// 1. If the do not flush flag is unset, set decoder to a new
// encoding's decoder, set stream to a new stream, and unset the
// BOM seen flag.
if (!this._do_not_flush) {
this._decoder = decoders[this._encoding.name]({
fatal: this._error_mode === 'fatal' })
this._BOMseen = false
}
// 2. If options's stream is true, set the do not flush flag, and
// unset the do not flush flag otherwise.
this._do_not_flush = Boolean(options['stream'])
// 3. If input is given, push a copy of input to stream.
// TODO: Align with spec algorithm - maintain stream on instance.
const input_stream = new Stream(bytes)
// 4. Let output be a new stream.
const output = []
/** @type {?(number|!Array.<number>)} */
let result
// 5. While true:
while (true) {
// 1. Let token be the result of reading from stream.
const token = input_stream.read()
// 2. If token is end-of-stream and the do not flush flag is
// set, return output, serialized.
// TODO: Align with spec algorithm.
if (token === end_of_stream)
break
// 3. Otherwise, run these subsubsteps:
// 1. Let result be the result of processing token for decoder,
// stream, output, and error mode.
result = this._decoder.handler(input_stream, token)
// 2. If result is finished, return output, serialized.
if (result === finished)
break
if (result !== null) {
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
}
// 3. Otherwise, if result is error, throw a TypeError.
// (Thrown in handler)
// 4. Otherwise, do nothing.
}
// TODO: Align with spec algorithm.
if (!this._do_not_flush) {
do {
result = this._decoder.handler(input_stream, input_stream.read())
if (result === finished)
break
if (result === null)
continue
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
} while (!input_stream.endOfStream())
this._decoder = null
}
return this.serializeStream(output)
}
// A TextDecoder object also has an associated serialize stream
// algorithm...
/**
* @param {!Array.<number>} stream
*/
serializeStream(stream) {
// 1. Let token be the result of reading from stream.
// (Done in-place on array, rather than as a stream)
// 2. If encoding is UTF-8, UTF-16BE, or UTF-16LE, and ignore
// BOM flag and BOM seen flag are unset, run these subsubsteps:
if (['UTF-8', 'UTF-16LE', 'UTF-16BE'].includes(this._encoding.name) &&
!this._ignoreBOM && !this._BOMseen) {
if (stream.length > 0 && stream[0] === 0xFEFF) {
// 1. If token is U+FEFF, set BOM seen flag.
this._BOMseen = true
stream.shift()
} else if (stream.length > 0) {
// 2. Otherwise, if token is not end-of-stream, set BOM seen
// flag and append token to stream.
this._BOMseen = true
} else {
// 3. Otherwise, if token is not end-of-stream, append token
// to output.
// (no-op)
}
}
// 4. Otherwise, return output.
return codePointsToString(stream)
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/lib/index.js | aws/lti-middleware/node_modules/text-decoding/src/lib/index.js | import { end_of_stream } from '../utils'
import { label_to_encoding } from '../table'
export default class Stream {
/**
* A stream represents an ordered sequence of tokens.
* @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide
* the stream.
*/
constructor(tokens) {
this.tokens = [...tokens]
// Reversed as push/pop is more efficient than shift/unshift.
this.tokens.reverse()
}
/**
* @returns True if end-of-stream has been hit.
*/
endOfStream() {
return !this.tokens.length
}
/**
* When a token is read from a stream, the first token in the
* stream must be returned and subsequently removed, and
* end-of-stream must be returned otherwise.
*
* @return Get the next token from the stream, or end_of_stream.
*/
read() {
if (!this.tokens.length)
return end_of_stream
return this.tokens.pop()
}
/**
* When one or more tokens are prepended to a stream, those tokens
* must be inserted, in given order, before the first token in the
* stream.
*
* @param {(number|!Array.<number>)} token The token(s) to prepend to the
* stream.
*/
prepend(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token)
while (tokens.length)
this.tokens.push(tokens.pop())
} else {
this.tokens.push(token)
}
}
/**
* When one or more tokens are pushed to a stream, those tokens
* must be inserted, in given order, after the last token in the
* stream.
*
* @param {(number|!Array.<number>)} token The tokens(s) to push to the
* stream.
*/
push(token) {
if (Array.isArray(token)) {
const tokens = /**@type {!Array.<number>}*/(token)
while (tokens.length)
this.tokens.unshift(tokens.shift())
} else {
this.tokens.unshift(token)
}
}
}
export const DEFAULT_ENCODING = 'utf-8'
/**
* Returns the encoding for the label.
* @param {string} label The encoding label.
*/
export function getEncoding(label) {
// 1. Remove any leading and trailing ASCII whitespace from label.
label = String(label).trim().toLowerCase()
// 2. If label is an ASCII case-insensitive match for any of the
// labels listed in the table below, return the corresponding
// encoding, and failure otherwise.
if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) {
return label_to_encoding[label]
}
return null
}
//
// 5. Encodings
//
// 5.1 Encoders and decoders
// /** @interface */
// function Decoder() {}
// Decoder.prototype = {
// /**
// * @param {Stream} stream The stream of bytes being decoded.
// * @param {number} bite The next byte read from the stream.
// * @return {?(number|!Array.<number>)} The next code point(s)
// * decoded, or null if not enough data exists in the input
// * stream to decode a complete code point, or |finished|.
// */
// handler: function(stream, bite) {},
// }
// /** @interface */
// function Encoder() {}
// Encoder.prototype = {
// /**
// * @param {Stream} stream The stream of code points being encoded.
// * @param {number} code_point Next code point read from the stream.
// * @return {(number|!Array.<number>)} Byte(s) to emit, or |finished|.
// */
// handler: function(stream, code_point) {},
// } | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/lib/TextEncoder.js | aws/lti-middleware/node_modules/text-decoding/src/lib/TextEncoder.js | import Stream, { DEFAULT_ENCODING, getEncoding } from './'
import { end_of_stream, finished, stringToCodePoints } from '../utils'
import { encoders } from '../table'
// 8.2 Interface TextEncoder
export default class TextEncoder {
/**
* @param {string=} label The label of the encoding. NONSTANDARD.
* @param {Object=} [options] NONSTANDARD.
*/
constructor(label, options = {}) {
// A TextEncoder object has an associated encoding and encoder.
/** @private */
this._encoding = null
/** @private @type {?Encoder} */
this._encoder = null
// Non-standard
/** @private @type {boolean} */
this._do_not_flush = false
/** @private @type {string} */
this._fatal = options['fatal'] ? 'fatal' : 'replacement'
// 2. Set enc's encoding to UTF-8's encoder.
if (options['NONSTANDARD_allowLegacyEncoding']) {
// NONSTANDARD behavior.
label = label !== undefined ? String(label) : DEFAULT_ENCODING
var encoding = getEncoding(label)
if (encoding === null || encoding.name === 'replacement')
throw RangeError('Unknown encoding: ' + label)
if (!encoders[encoding.name]) {
throw Error('Encoder not present.' +
' Did you forget to include encoding-indexes.js first?')
}
this._encoding = encoding
} else {
// Standard behavior.
this._encoding = getEncoding('utf-8')
if (label !== undefined && 'console' in global) {
console.warn('TextEncoder constructor called with encoding label, '
+ 'which is ignored.')
}
}
}
get encoding() {
return this._encoding.name.toLowerCase()
}
/**
* @param {string=} opt_string The string to encode.
* @param {Object=} options
*/
encode(opt_string = '', options = {}) {
// NOTE: This option is nonstandard. None of the encodings
// permitted for encoding (i.e. UTF-8, UTF-16) are stateful when
// the input is a USVString so streaming is not necessary.
if (!this._do_not_flush)
this._encoder = encoders[this._encoding.name]({
fatal: this._fatal === 'fatal' })
this._do_not_flush = Boolean(options['stream'])
// 1. Convert input to a stream.
const input = new Stream(stringToCodePoints(opt_string))
// 2. Let output be a new stream
const output = []
/** @type {?(number|!Array.<number>)} */
var result
// 3. While true, run these substeps:
while (true) {
// 1. Let token be the result of reading from input.
var token = input.read()
if (token === end_of_stream)
break
// 2. Let result be the result of processing token for encoder,
// input, output.
result = this._encoder.handler(input, token)
if (result === finished)
break
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
}
// TODO: Align with spec algorithm.
if (!this._do_not_flush) {
while (true) {
result = this._encoder.handler(input, input.read())
if (result === finished)
break
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
}
this._encoder = null
}
// 3. If result is finished, convert output into a byte sequence,
// and then return a Uint8Array object wrapping an ArrayBuffer
// containing output.
return new Uint8Array(output)
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/utf16.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/utf16.js | import { inRange, decoderError, end_of_stream, finished, convertCodeUnitToBytes } from '../utils'
// 15.2.1 shared utf-16 decoder
/**
* @implements {Decoder}
*/
export class UTF16Decoder {
/**
* @param {boolean} utf16_be True if big-endian, false if little-endian.
* @param {{fatal: boolean}} options
*/
constructor(utf16_be, options) {
const { fatal } = options
this.utf16_be = utf16_be
this.fatal = fatal
this.utf16_lead_byte = null
this.utf16_lead_surrogate = null
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream and either utf-16 lead byte or
// utf-16 lead surrogate is not null, set utf-16 lead byte and
// utf-16 lead surrogate to null, and return error.
if (bite === end_of_stream && (this.utf16_lead_byte !== null ||
this.utf16_lead_surrogate !== null)) {
return decoderError(this.fatal)
}
// 2. If byte is end-of-stream and utf-16 lead byte and utf-16
// lead surrogate are null, return finished.
if (bite === end_of_stream && this.utf16_lead_byte === null &&
this.utf16_lead_surrogate === null) {
return finished
}
// 3. If utf-16 lead byte is null, set utf-16 lead byte to byte
// and return continue.
if (this.utf16_lead_byte === null) {
this.utf16_lead_byte = bite
return null
}
// 4. Let code unit be the result of:
let code_unit
if (this.utf16_be) {
// utf-16be decoder flag is set
// (utf-16 lead byte << 8) + byte.
code_unit = (this.utf16_lead_byte << 8) + bite
} else {
// utf-16be decoder flag is unset
// (byte << 8) + utf-16 lead byte.
code_unit = (bite << 8) + this.utf16_lead_byte
}
// Then set utf-16 lead byte to null.
this.utf16_lead_byte = null
// 5. If utf-16 lead surrogate is not null, let lead surrogate
// be utf-16 lead surrogate, set utf-16 lead surrogate to null,
// and then run these substeps:
if (this.utf16_lead_surrogate !== null) {
const lead_surrogate = this.utf16_lead_surrogate
this.utf16_lead_surrogate = null
// 1. If code unit is in the range U+DC00 to U+DFFF,
// inclusive, return a code point whose value is 0x10000 +
// ((lead surrogate − 0xD800) << 10) + (code unit − 0xDC00).
if (inRange(code_unit, 0xDC00, 0xDFFF)) {
return 0x10000 + (lead_surrogate - 0xD800) * 0x400 +
(code_unit - 0xDC00)
}
// 2. Prepend the sequence resulting of converting code unit
// to bytes using utf-16be decoder flag to stream and return
// error.
stream.prepend(convertCodeUnitToBytes(code_unit, this.utf16_be))
return decoderError(this.fatal)
}
// 6. If code unit is in the range U+D800 to U+DBFF, inclusive,
// set utf-16 lead surrogate to code unit and return continue.
if (inRange(code_unit, 0xD800, 0xDBFF)) {
this.utf16_lead_surrogate = code_unit
return null
}
// 7. If code unit is in the range U+DC00 to U+DFFF, inclusive,
// return error.
if (inRange(code_unit, 0xDC00, 0xDFFF))
return decoderError(this.fatal)
// 8. Return code point code unit.
return code_unit
}
}
// 15.2.2 shared utf-16 encoder
/**
* @implements {Encoder}
*/
export class UTF16Encoder {
/**
* @param {boolean} [utf16_be] True if big-endian, false if little-endian.
*/
constructor(utf16_be = false) {
this.utf16_be = utf16_be
}
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
*/
handler(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is in the range U+0000 to U+FFFF, inclusive,
// return the sequence resulting of converting code point to
// bytes using utf-16be encoder flag.
if (inRange(code_point, 0x0000, 0xFFFF))
return convertCodeUnitToBytes(code_point, this.utf16_be)
// 3. Let lead be ((code point − 0x10000) >> 10) + 0xD800,
// converted to bytes using utf-16be encoder flag.
const lead = convertCodeUnitToBytes(
((code_point - 0x10000) >> 10) + 0xD800, this.utf16_be)
// 4. Let trail be ((code point − 0x10000) & 0x3FF) + 0xDC00,
// converted to bytes using utf-16be encoder flag.
const trail = convertCodeUnitToBytes(
((code_point - 0x10000) & 0x3FF) + 0xDC00, this.utf16_be)
// 5. Return a byte sequence of lead followed by trail.
return lead.concat(trail)
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/single-byte.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/single-byte.js | import { end_of_stream, finished, isASCIIByte, decoderError, encoderError, isASCIICodePoint } from '../utils'
import { indexPointerFor } from '../indexes'
//
// 10. Legacy single-byte encodings
//
// 10.1 single-byte decoder
/**
* @implements {Decoder}
*/
export class SingleByteDecoder {
/**
* @param {!Array.<number>} index The encoding index.
* @param {{fatal: boolean}} options
*/
constructor(index, options) {
const { fatal } = options
this.fatal = fatal
this.index = index
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished
// 2. If byte is an ASCII byte, return a code point whose value
// is byte.
if (isASCIIByte(bite))
return bite
// 3. Let code point be the index code point for byte − 0x80 in
// index single-byte.
var code_point = this.index[bite - 0x80]
// 4. If code point is null, return error.
if (code_point === null)
return decoderError(this.fatal)
// 5. Return a code point whose value is code point.
return code_point
}
}
// 10.2 single-byte encoder
/**
* @implements {Encoder}
*/
export class SingleByteEncoder {
/**
* @param {!Array.<?number>} index The encoding index.
*/
constructor(index) {
this.index = index
}
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
handler(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 3. Let pointer be the index pointer for code point in index
// single-byte.
const pointer = indexPointerFor(code_point, this.index)
// 4. If pointer is null, return error with code point.
if (pointer === null)
encoderError(code_point)
// 5. Return a byte whose value is pointer + 0x80.
return pointer + 0x80
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/utf8.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/utf8.js | import { inRange, decoderError, isASCIICodePoint,
end_of_stream, finished } from '../utils'
/**
* @implements {Decoder}
*/
export class UTF8Decoder {
/**
* @param {{fatal: boolean}} options
*/
constructor(options) {
const { fatal } = options
// utf-8's decoder's has an associated utf-8 code point, utf-8
// bytes seen, and utf-8 bytes needed (all initially 0), a utf-8
// lower boundary (initially 0x80), and a utf-8 upper boundary
// (initially 0xBF).
let /** @type {number} */ utf8_code_point = 0,
/** @type {number} */ utf8_bytes_seen = 0,
/** @type {number} */ utf8_bytes_needed = 0,
/** @type {number} */ utf8_lower_boundary = 0x80,
/** @type {number} */ utf8_upper_boundary = 0xBF
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
* @return {?(number|!Array.<number>)} The next code point(s)
* decoded, or null if not enough data exists in the input
* stream to decode a complete code point.
*/
this.handler = function(stream, bite) {
// 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
// set utf-8 bytes needed to 0 and return error.
if (bite === end_of_stream && utf8_bytes_needed !== 0) {
utf8_bytes_needed = 0
return decoderError(fatal)
}
// 2. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished
// 3. If utf-8 bytes needed is 0, based on byte:
if (utf8_bytes_needed === 0) {
// 0x00 to 0x7F
if (inRange(bite, 0x00, 0x7F)) {
// Return a code point whose value is byte.
return bite
}
// 0xC2 to 0xDF
else if (inRange(bite, 0xC2, 0xDF)) {
// 1. Set utf-8 bytes needed to 1.
utf8_bytes_needed = 1
// 2. Set UTF-8 code point to byte & 0x1F.
utf8_code_point = bite & 0x1F
}
// 0xE0 to 0xEF
else if (inRange(bite, 0xE0, 0xEF)) {
// 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
if (bite === 0xE0)
utf8_lower_boundary = 0xA0
// 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
if (bite === 0xED)
utf8_upper_boundary = 0x9F
// 3. Set utf-8 bytes needed to 2.
utf8_bytes_needed = 2
// 4. Set UTF-8 code point to byte & 0xF.
utf8_code_point = bite & 0xF
}
// 0xF0 to 0xF4
else if (inRange(bite, 0xF0, 0xF4)) {
// 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
if (bite === 0xF0)
utf8_lower_boundary = 0x90
// 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
if (bite === 0xF4)
utf8_upper_boundary = 0x8F
// 3. Set utf-8 bytes needed to 3.
utf8_bytes_needed = 3
// 4. Set UTF-8 code point to byte & 0x7.
utf8_code_point = bite & 0x7
}
// Otherwise
else {
// Return error.
return decoderError(fatal)
}
// Return continue.
return null
}
// 4. If byte is not in the range utf-8 lower boundary to utf-8
// upper boundary, inclusive, run these substeps:
if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {
// 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
// bytes seen to 0, set utf-8 lower boundary to 0x80, and set
// utf-8 upper boundary to 0xBF.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0
utf8_lower_boundary = 0x80
utf8_upper_boundary = 0xBF
// 2. Prepend byte to stream.
stream.prepend(bite)
// 3. Return error.
return decoderError(fatal)
}
// 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
// to 0xBF.
utf8_lower_boundary = 0x80
utf8_upper_boundary = 0xBF
// 6. Set UTF-8 code point to (UTF-8 code point << 6) | (byte &
// 0x3F)
utf8_code_point = (utf8_code_point << 6) | (bite & 0x3F)
// 7. Increase utf-8 bytes seen by one.
utf8_bytes_seen += 1
// 8. If utf-8 bytes seen is not equal to utf-8 bytes needed,
// continue.
if (utf8_bytes_seen !== utf8_bytes_needed)
return null
// 9. Let code point be utf-8 code point.
var code_point = utf8_code_point
// 10. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
// seen to 0.
utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0
// 11. Return a code point whose value is code point.
return code_point
}
}
}
// 9.1.2 utf-8 encoder
/**
* @implements {Encoder}
*/
export class UTF8Encoder {
constructor() {
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 3. Set count and offset based on the range code point is in:
var count, offset
// U+0080 to U+07FF, inclusive:
if (inRange(code_point, 0x0080, 0x07FF)) {
// 1 and 0xC0
count = 1
offset = 0xC0
}
// U+0800 to U+FFFF, inclusive:
else if (inRange(code_point, 0x0800, 0xFFFF)) {
// 2 and 0xE0
count = 2
offset = 0xE0
}
// U+10000 to U+10FFFF, inclusive:
else if (inRange(code_point, 0x10000, 0x10FFFF)) {
// 3 and 0xF0
count = 3
offset = 0xF0
}
// 4. Let bytes be a byte sequence whose first byte is (code
// point >> (6 × count)) + offset.
var bytes = [(code_point >> (6 * count)) + offset]
// 5. Run these substeps while count is greater than 0:
while (count > 0) {
// 1. Set temp to code point >> (6 × (count − 1)).
var temp = code_point >> (6 * (count - 1))
// 2. Append to bytes 0x80 | (temp & 0x3F).
bytes.push(0x80 | (temp & 0x3F))
// 3. Decrease count by one.
count -= 1
}
// 6. Return bytes bytes, in order.
return bytes
}
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/iso-2022-jp.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/iso-2022-jp.js | import { inRange, decoderError, encoderError, isASCIICodePoint,
end_of_stream, finished, floor } from '../utils'
import index, { indexCodePointFor, indexPointerFor } from '../indexes'
// 13.2 iso-2022-jp
// 13.2.1 iso-2022-jp decoder
/**
* @implements {Decoder}
*/
export class ISO2022JPDecoder {
constructor(options) {
const { fatal } = options
this.fatal = fatal
/** @enum */
this.states = {
ASCII: 0,
Roman: 1,
Katakana: 2,
LeadByte: 3,
TrailByte: 4,
EscapeStart: 5,
Escape: 6,
}
// iso-2022-jp's decoder has an associated iso-2022-jp decoder
// state (initially ASCII), iso-2022-jp decoder output state
// (initially ASCII), iso-2022-jp lead (initially 0x00), and
// iso-2022-jp output flag (initially unset).
this.iso2022jp_decoder_state = this.states.ASCII
this.iso2022jp_decoder_output_state = this.states.ASCII,
this.iso2022jp_lead = 0x00
this.iso2022jp_output_flag = false
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// switching on iso-2022-jp decoder state:
switch (this.iso2022jp_decoder_state) {
default:
case this.states.ASCII:
// ASCII
// Based on byte:
// 0x1B
if (bite === 0x1B) {
// Set iso-2022-jp decoder state to escape start and return
// continue.
this.iso2022jp_decoder_state = this.states.EscapeStart
return null
}
// 0x00 to 0x7F, excluding 0x0E, 0x0F, and 0x1B
if (inRange(bite, 0x00, 0x7F) && bite !== 0x0E
&& bite !== 0x0F && bite !== 0x1B) {
// Unset the iso-2022-jp output flag and return a code point
// whose value is byte.
this.iso2022jp_output_flag = false
return bite
}
// end-of-stream
if (bite === end_of_stream) {
// Return finished.
return finished
}
// Otherwise
// Unset the iso-2022-jp output flag and return error.
this.iso2022jp_output_flag = false
return decoderError(this.fatal)
case this.states.Roman:
// Roman
// Based on byte:
// 0x1B
if (bite === 0x1B) {
// Set iso-2022-jp decoder state to escape start and return
// continue.
this.iso2022jp_decoder_state = this.states.EscapeStart
return null
}
// 0x5C
if (bite === 0x5C) {
// Unset the iso-2022-jp output flag and return code point
// U+00A5.
this.iso2022jp_output_flag = false
return 0x00A5
}
// 0x7E
if (bite === 0x7E) {
// Unset the iso-2022-jp output flag and return code point
// U+203E.
this.iso2022jp_output_flag = false
return 0x203E
}
// 0x00 to 0x7F, excluding 0x0E, 0x0F, 0x1B, 0x5C, and 0x7E
if (inRange(bite, 0x00, 0x7F) && bite !== 0x0E && bite !== 0x0F
&& bite !== 0x1B && bite !== 0x5C && bite !== 0x7E) {
// Unset the iso-2022-jp output flag and return a code point
// whose value is byte.
this.iso2022jp_output_flag = false
return bite
}
// end-of-stream
if (bite === end_of_stream) {
// Return finished.
return finished
}
// Otherwise
// Unset the iso-2022-jp output flag and return error.
this.iso2022jp_output_flag = false
return decoderError(this.fatal)
case this.states.Katakana:
// Katakana
// Based on byte:
// 0x1B
if (bite === 0x1B) {
// Set iso-2022-jp decoder state to escape start and return
// continue.
this.iso2022jp_decoder_state = this.states.EscapeStart
return null
}
// 0x21 to 0x5F
if (inRange(bite, 0x21, 0x5F)) {
// Unset the iso-2022-jp output flag and return a code point
// whose value is 0xFF61 − 0x21 + byte.
this.iso2022jp_output_flag = false
return 0xFF61 - 0x21 + bite
}
// end-of-stream
if (bite === end_of_stream) {
// Return finished.
return finished
}
// Otherwise
// Unset the iso-2022-jp output flag and return error.
this.iso2022jp_output_flag = false
return decoderError(this.fatal)
case this.states.LeadByte:
// Lead byte
// Based on byte:
// 0x1B
if (bite === 0x1B) {
// Set iso-2022-jp decoder state to escape start and return
// continue.
this.iso2022jp_decoder_state = this.states.EscapeStart
return null
}
// 0x21 to 0x7E
if (inRange(bite, 0x21, 0x7E)) {
// Unset the iso-2022-jp output flag, set iso-2022-jp lead
// to byte, iso-2022-jp decoder state to trail byte, and
// return continue.
this.iso2022jp_output_flag = false
this.iso2022jp_lead = bite
this.iso2022jp_decoder_state = this.states.TrailByte
return null
}
// end-of-stream
if (bite === end_of_stream) {
// Return finished.
return finished
}
// Otherwise
// Unset the iso-2022-jp output flag and return error.
this.iso2022jp_output_flag = false
return decoderError(this.fatal)
case this.states.TrailByte:
// Trail byte
// Based on byte:
// 0x1B
if (bite === 0x1B) {
// Set iso-2022-jp decoder state to escape start and return
// continue.
this.iso2022jp_decoder_state = this.states.EscapeStart
return decoderError(this.fatal)
}
// 0x21 to 0x7E
if (inRange(bite, 0x21, 0x7E)) {
// 1. Set the iso-2022-jp decoder state to lead byte.
this.iso2022jp_decoder_state = this.states.LeadByte
// 2. Let pointer be (iso-2022-jp lead − 0x21) × 94 + byte − 0x21.
const pointer = (this.iso2022jp_lead - 0x21) * 94 + bite - 0x21
// 3. Let code point be the index code point for pointer in
// index jis0208.
const code_point = indexCodePointFor(pointer, index('jis0208'))
// 4. If code point is null, return error.
if (code_point === null)
return decoderError(this.fatal)
// 5. Return a code point whose value is code point.
return code_point
}
// end-of-stream
if (bite === end_of_stream) {
// Set the iso-2022-jp decoder state to lead byte, prepend
// byte to stream, and return error.
this.iso2022jp_decoder_state = this.states.LeadByte
stream.prepend(bite)
return decoderError(this.fatal)
}
// Otherwise
// Set iso-2022-jp decoder state to lead byte and return
// error.
this.iso2022jp_decoder_state = this.states.LeadByte
return decoderError(this.fatal)
case this.states.EscapeStart:
// Escape start
// 1. If byte is either 0x24 or 0x28, set iso-2022-jp lead to
// byte, iso-2022-jp decoder state to escape, and return
// continue.
if (bite === 0x24 || bite === 0x28) {
this.iso2022jp_lead = bite
this.iso2022jp_decoder_state = this.states.Escape
return null
}
// 2. Prepend byte to stream.
stream.prepend(bite)
// 3. Unset the iso-2022-jp output flag, set iso-2022-jp
// decoder state to iso-2022-jp decoder output state, and
// return error.
this.iso2022jp_output_flag = false
this.iso2022jp_decoder_state = this.iso2022jp_decoder_output_state
return decoderError(this.fatal)
case this.states.Escape: {
// Escape
// 1. Let lead be iso-2022-jp lead and set iso-2022-jp lead to
// 0x00.
const lead = this.iso2022jp_lead
this.iso2022jp_lead = 0x00
// 2. Let state be null.
let state = null
// 3. If lead is 0x28 and byte is 0x42, set state to ASCII.
if (lead === 0x28 && bite === 0x42)
state = this.states.ASCII
// 4. If lead is 0x28 and byte is 0x4A, set state to Roman.
if (lead === 0x28 && bite === 0x4A)
state = this.states.Roman
// 5. If lead is 0x28 and byte is 0x49, set state to Katakana.
if (lead === 0x28 && bite === 0x49)
state = this.states.Katakana
// 6. If lead is 0x24 and byte is either 0x40 or 0x42, set
// state to lead byte.
if (lead === 0x24 && (bite === 0x40 || bite === 0x42))
state = this.states.LeadByte
// 7. If state is non-null, run these substeps:
if (state !== null) {
// 1. Set iso-2022-jp decoder state and iso-2022-jp decoder
// output state to this.states.
this.iso2022jp_decoder_state = this.iso2022jp_decoder_state = state
// 2. Let output flag be the iso-2022-jp output flag.
const output_flag = this.iso2022jp_output_flag
// 3. Set the iso-2022-jp output flag.
this.iso2022jp_output_flag = true
// 4. Return continue, if output flag is unset, and error
// otherwise.
return !output_flag ? null : decoderError(this.fatal)
}
// 8. Prepend lead and byte to stream.
stream.prepend([lead, bite])
// 9. Unset the iso-2022-jp output flag, set iso-2022-jp
// decoder state to iso-2022-jp decoder output state and
// return error.
this.iso2022jp_output_flag = false
this.iso2022jp_decoder_state = this.iso2022jp_decoder_output_state
return decoderError(this.fatal)
}
}
}
}
// 13.2.2 iso-2022-jp encoder
/**
* @implements {Encoder}
*/
export class ISO2022JPEncoder {
constructor() {
// iso-2022-jp's encoder has an associated iso-2022-jp encoder
// state which is one of ASCII, Roman, and jis0208 (initially
// ASCII).
/** @enum */
this.states = {
ASCII: 0,
Roman: 1,
jis0208: 2,
}
this.iso2022jp_state = this.states.ASCII
}
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
*/
handler(stream, code_point) {
// 1. If code point is end-of-stream and iso-2022-jp encoder
// state is not ASCII, prepend code point to stream, set
// iso-2022-jp encoder state to ASCII, and return three bytes
// 0x1B 0x28 0x42.
if (code_point === end_of_stream &&
this.iso2022jp_state !== this.states.ASCII) {
stream.prepend(code_point)
this.iso2022jp_state = this.states.ASCII
return [0x1B, 0x28, 0x42]
}
// 2. If code point is end-of-stream and iso-2022-jp encoder
// state is ASCII, return finished.
if (code_point === end_of_stream && this.iso2022jp_state === this.states.ASCII)
return finished
// 3. If ISO-2022-JP encoder state is ASCII or Roman, and code
// point is U+000E, U+000F, or U+001B, return error with U+FFFD.
if ((this.iso2022jp_state === this.states.ASCII ||
this.iso2022jp_state === this.states.Roman) &&
(code_point === 0x000E || code_point === 0x000F ||
code_point === 0x001B)) {
return encoderError(0xFFFD)
}
// 4. If iso-2022-jp encoder state is ASCII and code point is an
// ASCII code point, return a byte whose value is code point.
if (this.iso2022jp_state === this.states.ASCII &&
isASCIICodePoint(code_point))
return code_point
// 5. If iso-2022-jp encoder state is Roman and code point is an
// ASCII code point, excluding U+005C and U+007E, or is U+00A5
// or U+203E, run these substeps:
if (this.iso2022jp_state === this.states.Roman &&
((isASCIICodePoint(code_point) &&
code_point !== 0x005C && code_point !== 0x007E) ||
(code_point == 0x00A5 || code_point == 0x203E))) {
// 1. If code point is an ASCII code point, return a byte
// whose value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 2. If code point is U+00A5, return byte 0x5C.
if (code_point === 0x00A5)
return 0x5C
// 3. If code point is U+203E, return byte 0x7E.
if (code_point === 0x203E)
return 0x7E
}
// 6. If code point is an ASCII code point, and iso-2022-jp
// encoder state is not ASCII, prepend code point to stream, set
// iso-2022-jp encoder state to ASCII, and return three bytes
// 0x1B 0x28 0x42.
if (isASCIICodePoint(code_point) &&
this.iso2022jp_state !== this.states.ASCII) {
stream.prepend(code_point)
this.iso2022jp_state = this.states.ASCII
return [0x1B, 0x28, 0x42]
}
// 7. If code point is either U+00A5 or U+203E, and iso-2022-jp
// encoder state is not Roman, prepend code point to stream, set
// iso-2022-jp encoder state to Roman, and return three bytes
// 0x1B 0x28 0x4A.
if ((code_point === 0x00A5 || code_point === 0x203E) &&
this.iso2022jp_state !== this.states.Roman) {
stream.prepend(code_point)
this.iso2022jp_state = this.states.Roman
return [0x1B, 0x28, 0x4A]
}
// 8. If code point is U+2212, set it to U+FF0D.
if (code_point === 0x2212)
code_point = 0xFF0D
// 9. Let pointer be the index pointer for code point in index
// jis0208.
const pointer = indexPointerFor(code_point, index('jis0208'))
// 10. If pointer is null, return error with code point.
if (pointer === null)
return encoderError(code_point)
// 11. If iso-2022-jp encoder state is not jis0208, prepend code
// point to stream, set iso-2022-jp encoder state to jis0208,
// and return three bytes 0x1B 0x24 0x42.
if (this.iso2022jp_state !== this.states.jis0208) {
stream.prepend(code_point)
this.iso2022jp_state = this.states.jis0208
return [0x1B, 0x24, 0x42]
}
// 12. Let lead be floor(pointer / 94) + 0x21.
const lead = floor(pointer / 94) + 0x21
// 13. Let trail be pointer % 94 + 0x21.
const trail = pointer % 94 + 0x21
// 14. Return two bytes whose values are lead and trail.
return [lead, trail]
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/euc-kr.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/euc-kr.js | import { inRange, decoderError, encoderError, isASCIICodePoint,
end_of_stream, finished, isASCIIByte, floor } from '../utils'
import index, { indexCodePointFor, indexPointerFor } from '../indexes'
//
// 14. Legacy multi-byte Korean encodings
//
// 14.1 euc-kr
// 14.1.1 euc-kr decoder
/**
* @implements {Decoder}
*/
export class EUCKRDecoder {
constructor(options) {
const { fatal } = options
this.fatal = fatal
// euc-kr's decoder has an associated euc-kr lead (initially 0x00).
this.euckr_lead = 0x00
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream and euc-kr lead is not 0x00, set
// euc-kr lead to 0x00 and return error.
if (bite === end_of_stream && this.euckr_lead !== 0) {
this.euckr_lead = 0x00
return decoderError(this.fatal)
}
// 2. If byte is end-of-stream and euc-kr lead is 0x00, return
// finished.
if (bite === end_of_stream && this.euckr_lead === 0)
return finished
// 3. If euc-kr lead is not 0x00, let lead be euc-kr lead, let
// pointer be null, set euc-kr lead to 0x00, and then run these
// substeps:
if (this.euckr_lead !== 0x00) {
const lead = this.euckr_lead
let pointer = null
this.euckr_lead = 0x00
// 1. If byte is in the range 0x41 to 0xFE, inclusive, set
// pointer to (lead − 0x81) × 190 + (byte − 0x41).
if (inRange(bite, 0x41, 0xFE))
pointer = (lead - 0x81) * 190 + (bite - 0x41)
// 2. Let code point be null, if pointer is null, and the
// index code point for pointer in index euc-kr otherwise.
const code_point = (pointer === null)
? null : indexCodePointFor(pointer, index('euc-kr'))
// 3. If code point is null and byte is an ASCII byte, prepend
// byte to stream.
if (pointer === null && isASCIIByte(bite))
stream.prepend(bite)
// 4. If code point is null, return error.
if (code_point === null)
return decoderError(this.fatal)
// 5. Return a code point whose value is code point.
return code_point
}
// 4. If byte is an ASCII byte, return a code point whose value
// is byte.
if (isASCIIByte(bite))
return bite
// 5. If byte is in the range 0x81 to 0xFE, inclusive, set
// euc-kr lead to byte and return continue.
if (inRange(bite, 0x81, 0xFE)) {
this.euckr_lead = bite
return null
}
// 6. Return error.
return decoderError(this.fatal)
}
}
// 14.1.2 euc-kr encoder
/**
* @implements {Encoder}
*/
export class EUCKREncoder {
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit.
*/
handler(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 3. Let pointer be the index pointer for code point in index
// euc-kr.
const pointer = indexPointerFor(code_point, index('euc-kr'))
// 4. If pointer is null, return error with code point.
if (pointer === null)
return encoderError(code_point)
// 5. Let lead be floor(pointer / 190) + 0x81.
const lead = floor(pointer / 190) + 0x81
// 6. Let trail be pointer % 190 + 0x41.
const trail = (pointer % 190) + 0x41
// 7. Return two bytes whose values are lead and trail.
return [lead, trail]
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/big5.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/big5.js | import { inRange, decoderError, encoderError, isASCIICodePoint,
end_of_stream, finished, isASCIIByte, floor } from '../utils'
import index, { indexBig5PointerFor, indexCodePointFor } from '../indexes'
//
// 12. Legacy multi-byte Chinese (traditional) encodings
//
// 12.1 Big5
// 12.1.1 Big5 decoder
/**
* @implements {Decoder}
*/
export class Big5Decoder {
constructor(options) {
const { fatal } = options
this.fatal = fatal
// Big5's decoder has an associated Big5 lead (initially 0x00).
this.Big5_lead = 0x00
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream and Big5 lead is not 0x00, set
// Big5 lead to 0x00 and return error.
if (bite === end_of_stream && this.Big5_lead !== 0x00) {
this.Big5_lead = 0x00
return decoderError(this.fatal)
}
// 2. If byte is end-of-stream and Big5 lead is 0x00, return
// finished.
if (bite === end_of_stream && this.Big5_lead === 0x00)
return finished
// 3. If Big5 lead is not 0x00, let lead be Big5 lead, let
// pointer be null, set Big5 lead to 0x00, and then run these
// substeps:
if (this.Big5_lead !== 0x00) {
const lead = this.Big5_lead
let pointer = null
this.Big5_lead = 0x00
// 1. Let offset be 0x40 if byte is less than 0x7F and 0x62
// otherwise.
const offset = bite < 0x7F ? 0x40 : 0x62
// 2. If byte is in the range 0x40 to 0x7E, inclusive, or 0xA1
// to 0xFE, inclusive, set pointer to (lead − 0x81) × 157 +
// (byte − offset).
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE))
pointer = (lead - 0x81) * 157 + (bite - offset)
// 3. If there is a row in the table below whose first column
// is pointer, return the two code points listed in its second
// column
// Pointer | Code points
// --------+--------------
// 1133 | U+00CA U+0304
// 1135 | U+00CA U+030C
// 1164 | U+00EA U+0304
// 1166 | U+00EA U+030C
switch (pointer) {
case 1133: return [0x00CA, 0x0304]
case 1135: return [0x00CA, 0x030C]
case 1164: return [0x00EA, 0x0304]
case 1166: return [0x00EA, 0x030C]
}
// 4. Let code point be null if pointer is null and the index
// code point for pointer in index Big5 otherwise.
const code_point = (pointer === null) ? null :
indexCodePointFor(pointer, index('big5'))
// 5. If code point is null and byte is an ASCII byte, prepend
// byte to stream.
if (code_point === null && isASCIIByte(bite))
stream.prepend(bite)
// 6. If code point is null, return error.
if (code_point === null)
return decoderError(this.fatal)
// 7. Return a code point whose value is code point.
return code_point
}
// 4. If byte is an ASCII byte, return a code point whose value
// is byte.
if (isASCIIByte(bite))
return bite
// 5. If byte is in the range 0x81 to 0xFE, inclusive, set Big5
// lead to byte and return continue.
if (inRange(bite, 0x81, 0xFE)) {
this.Big5_lead = bite
return null
}
// 6. Return error.
return decoderError(this.fatal)
}
}
// 12.1.2 Big5 encoder
/**
* @implements {Encoder}
*/
export class Big5Encoder {
constructor() {
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
*/
this.handler = function(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 3. Let pointer be the index Big5 pointer for code point.
const pointer = indexBig5PointerFor(code_point)
// 4. If pointer is null, return error with code point.
if (pointer === null)
return encoderError(code_point)
// 5. Let lead be floor(pointer / 157) + 0x81.
const lead = floor(pointer / 157) + 0x81
// 6. If lead is less than 0xA1, return error with code point.
if (lead < 0xA1)
return encoderError(code_point)
// 7. Let trail be pointer % 157.
const trail = pointer % 157
// 8. Let offset be 0x40 if trail is less than 0x3F and 0x62
// otherwise.
const offset = trail < 0x3F ? 0x40 : 0x62
// Return two bytes whose values are lead and trail + offset.
return [lead, trail + offset]
}
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/euc-jp.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/euc-jp.js | import { inRange, decoderError, encoderError, isASCIICodePoint,
end_of_stream, finished, isASCIIByte, floor } from '../utils'
import index, { indexCodePointFor, indexPointerFor } from '../indexes'
//
// 13. Legacy multi-byte Japanese encodings
//
// 13.1 euc-jp
// 13.1.1 euc-jp decoder
/**
* @implements {Decoder}
*/
export class EUCJPDecoder {
constructor(options) {
const { fatal } = options
this.fatal = fatal
// euc-jp's decoder has an associated euc-jp jis0212 flag
// (initially unset) and euc-jp lead (initially 0x00).
this.eucjp_jis0212_flag = false
this.eucjp_lead = 0x00
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream and euc-jp lead is not 0x00, set
// euc-jp lead to 0x00, and return error.
if (bite === end_of_stream && this.eucjp_lead !== 0x00) {
this.eucjp_lead = 0x00
return decoderError(this.fatal)
}
// 2. If byte is end-of-stream and euc-jp lead is 0x00, return
// finished.
if (bite === end_of_stream && this.eucjp_lead === 0x00)
return finished
// 3. If euc-jp lead is 0x8E and byte is in the range 0xA1 to
// 0xDF, inclusive, set euc-jp lead to 0x00 and return a code
// point whose value is 0xFF61 − 0xA1 + byte.
if (this.eucjp_lead === 0x8E && inRange(bite, 0xA1, 0xDF)) {
this.eucjp_lead = 0x00
return 0xFF61 - 0xA1 + bite
}
// 4. If euc-jp lead is 0x8F and byte is in the range 0xA1 to
// 0xFE, inclusive, set the euc-jp jis0212 flag, set euc-jp lead
// to byte, and return continue.
if (this.eucjp_lead === 0x8F && inRange(bite, 0xA1, 0xFE)) {
this.eucjp_jis0212_flag = true
this.eucjp_lead = bite
return null
}
// 5. If euc-jp lead is not 0x00, let lead be euc-jp lead, set
// euc-jp lead to 0x00, and run these substeps:
if (this.eucjp_lead !== 0x00) {
const lead = this.eucjp_lead
this.eucjp_lead = 0x00
// 1. Let code point be null.
let code_point = null
// 2. If lead and byte are both in the range 0xA1 to 0xFE,
// inclusive, set code point to the index code point for (lead
// − 0xA1) × 94 + byte − 0xA1 in index jis0208 if the euc-jp
// jis0212 flag is unset and in index jis0212 otherwise.
if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) {
code_point = indexCodePointFor(
(lead - 0xA1) * 94 + (bite - 0xA1),
index(!this.eucjp_jis0212_flag ? 'jis0208' : 'jis0212'))
}
// 3. Unset the euc-jp jis0212 flag.
this.eucjp_jis0212_flag = false
// 4. If byte is not in the range 0xA1 to 0xFE, inclusive,
// prepend byte to stream.
if (!inRange(bite, 0xA1, 0xFE))
stream.prepend(bite)
// 5. If code point is null, return error.
if (code_point === null)
return decoderError(this.fatal)
// 6. Return a code point whose value is code point.
return code_point
}
// 6. If byte is an ASCII byte, return a code point whose value
// is byte.
if (isASCIIByte(bite))
return bite
// 7. If byte is 0x8E, 0x8F, or in the range 0xA1 to 0xFE,
// inclusive, set euc-jp lead to byte and return continue.
if (bite === 0x8E || bite === 0x8F || inRange(bite, 0xA1, 0xFE)) {
this.eucjp_lead = bite
return null
}
// 8. Return error.
return decoderError(this.fatal)
}
}
// 13.1.2 euc-jp encoder
/**
* @implements {Encoder}
*/
export class EUCJPEncoder {
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
*/
handler(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 3. If code point is U+00A5, return byte 0x5C.
if (code_point === 0x00A5)
return 0x5C
// 4. If code point is U+203E, return byte 0x7E.
if (code_point === 0x203E)
return 0x7E
// 5. If code point is in the range U+FF61 to U+FF9F, inclusive,
// return two bytes whose values are 0x8E and code point −
// 0xFF61 + 0xA1.
if (inRange(code_point, 0xFF61, 0xFF9F))
return [0x8E, code_point - 0xFF61 + 0xA1]
// 6. If code point is U+2212, set it to U+FF0D.
if (code_point === 0x2212)
code_point = 0xFF0D
// 7. Let pointer be the index pointer for code point in index
// jis0208.
const pointer = indexPointerFor(code_point, index('jis0208'))
// 8. If pointer is null, return error with code point.
if (pointer === null)
return encoderError(code_point)
// 9. Let lead be floor(pointer / 94) + 0xA1.
const lead = floor(pointer / 94) + 0xA1
// 10. Let trail be pointer % 94 + 0xA1.
const trail = pointer % 94 + 0xA1
// 11. Return two bytes whose values are lead and trail.
return [lead, trail]
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/shift-jis.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/shift-jis.js | import { inRange, decoderError, encoderError, floor, isASCIICodePoint, isASCIIByte,
end_of_stream, finished } from '../utils'
import index, { indexCodePointFor, indexShiftJISPointerFor } from '../indexes'
// 13.3 Shift_JIS
// 13.3.1 Shift_JIS decoder
/**
* @constructor
* @implements {Decoder}
* @param {{fatal: boolean}} options
*/
export class ShiftJISDecoder {
constructor(options) {
const { fatal } = options
this.fatal = fatal
// Shift_JIS's decoder has an associated Shift_JIS lead (initially
// 0x00).
this.Shift_JIS_lead = 0x00
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream and Shift_JIS lead is not 0x00,
// set Shift_JIS lead to 0x00 and return error.
if (bite === end_of_stream && this.Shift_JIS_lead !== 0x00) {
this.Shift_JIS_lead = 0x00
return decoderError(this.fatal)
}
// 2. If byte is end-of-stream and Shift_JIS lead is 0x00,
// return finished.
if (bite === end_of_stream && this.Shift_JIS_lead === 0x00)
return finished
// 3. If Shift_JIS lead is not 0x00, let lead be Shift_JIS lead,
// let pointer be null, set Shift_JIS lead to 0x00, and then run
// these substeps:
if (this.Shift_JIS_lead !== 0x00) {
var lead = this.Shift_JIS_lead
var pointer = null
this.Shift_JIS_lead = 0x00
// 1. Let offset be 0x40, if byte is less than 0x7F, and 0x41
// otherwise.
var offset = (bite < 0x7F) ? 0x40 : 0x41
// 2. Let lead offset be 0x81, if lead is less than 0xA0, and
// 0xC1 otherwise.
var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1
// 3. If byte is in the range 0x40 to 0x7E, inclusive, or 0x80
// to 0xFC, inclusive, set pointer to (lead − lead offset) ×
// 188 + byte − offset.
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC))
pointer = (lead - lead_offset) * 188 + bite - offset
// 4. If pointer is in the range 8836 to 10715, inclusive,
// return a code point whose value is 0xE000 − 8836 + pointer.
if (inRange(pointer, 8836, 10715))
return 0xE000 - 8836 + pointer
// 5. Let code point be null, if pointer is null, and the
// index code point for pointer in index jis0208 otherwise.
var code_point = (pointer === null) ? null :
indexCodePointFor(pointer, index('jis0208'))
// 6. If code point is null and byte is an ASCII byte, prepend
// byte to stream.
if (code_point === null && isASCIIByte(bite))
stream.prepend(bite)
// 7. If code point is null, return error.
if (code_point === null)
return decoderError(this.fatal)
// 8. Return a code point whose value is code point.
return code_point
}
// 4. If byte is an ASCII byte or 0x80, return a code point
// whose value is byte.
if (isASCIIByte(bite) || bite === 0x80)
return bite
// 5. If byte is in the range 0xA1 to 0xDF, inclusive, return a
// code point whose value is 0xFF61 − 0xA1 + byte.
if (inRange(bite, 0xA1, 0xDF))
return 0xFF61 - 0xA1 + bite
// 6. If byte is in the range 0x81 to 0x9F, inclusive, or 0xE0
// to 0xFC, inclusive, set Shift_JIS lead to byte and return
// continue.
if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) {
this.Shift_JIS_lead = bite
return null
}
// 7. Return error.
return decoderError(this.fatal)
}
}
// 13.3.2 Shift_JIS encoder
/**
* @constructor
* @implements {Encoder}
* @param {{fatal: boolean}} options
*/
export class ShiftJISEncoder {
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
*/
handler(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point or U+0080, return a
// byte whose value is code point.
if (isASCIICodePoint(code_point) || code_point === 0x0080)
return code_point
// 3. If code point is U+00A5, return byte 0x5C.
if (code_point === 0x00A5)
return 0x5C
// 4. If code point is U+203E, return byte 0x7E.
if (code_point === 0x203E)
return 0x7E
// 5. If code point is in the range U+FF61 to U+FF9F, inclusive,
// return a byte whose value is code point − 0xFF61 + 0xA1.
if (inRange(code_point, 0xFF61, 0xFF9F))
return code_point - 0xFF61 + 0xA1
// 6. If code point is U+2212, set it to U+FF0D.
if (code_point === 0x2212)
code_point = 0xFF0D
// 7. Let pointer be the index Shift_JIS pointer for code point.
var pointer = indexShiftJISPointerFor(code_point)
// 8. If pointer is null, return error with code point.
if (pointer === null)
return encoderError(code_point)
// 9. Let lead be floor(pointer / 188).
var lead = floor(pointer / 188)
// 10. Let lead offset be 0x81, if lead is less than 0x1F, and
// 0xC1 otherwise.
var lead_offset = (lead < 0x1F) ? 0x81 : 0xC1
// 11. Let trail be pointer % 188.
var trail = pointer % 188
// 12. Let offset be 0x40, if trail is less than 0x3F, and 0x41
// otherwise.
var offset = (trail < 0x3F) ? 0x40 : 0x41
// 13. Return two bytes whose values are lead + lead offset and
// trail + offset.
return [lead + lead_offset, trail + offset]
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/x-user-defined.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/x-user-defined.js | import { inRange, encoderError, end_of_stream, finished, isASCIIByte, isASCIICodePoint } from '../utils'
// 15.5 x-user-defined
// 15.5.1 x-user-defined decoder
/**
* @implements {Decoder}
*/
export class XUserDefinedDecoder {
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream, return finished.
if (bite === end_of_stream)
return finished
// 2. If byte is an ASCII byte, return a code point whose value
// is byte.
if (isASCIIByte(bite))
return bite
// 3. Return a code point whose value is 0xF780 + byte − 0x80.
return 0xF780 + bite - 0x80
}
}
// 15.5.2 x-user-defined encoder
/**
* @implements {Encoder}
*/
export class XUserDefinedEncoder {
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
*/
handler(stream, code_point) {
// 1.If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 3. If code point is in the range U+F780 to U+F7FF, inclusive,
// return a byte whose value is code point − 0xF780 + 0x80.
if (inRange(code_point, 0xF780, 0xF7FF))
return code_point - 0xF780 + 0x80
// 4. Return error with code point.
return encoderError(code_point)
}
} | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/src/implementations/gb18030.js | aws/lti-middleware/node_modules/text-decoding/src/implementations/gb18030.js | import { inRange, decoderError, encoderError, isASCIICodePoint,
end_of_stream, finished, isASCIIByte, floor } from '../utils'
import index, {
indexGB18030RangesCodePointFor, indexGB18030RangesPointerFor,
indexCodePointFor, indexPointerFor } from '../indexes'
// 11.2 gb18030
// 11.2.1 gb18030 decoder
/**
* @constructor
* @implements {Decoder}
* @param {{fatal: boolean}} options
*/
export class GB18030Decoder {
constructor(options) {
const { fatal } = options
this.fatal = fatal
// gb18030's decoder has an associated gb18030 first, gb18030
// second, and gb18030 third (all initially 0x00).
this.gb18030_first = 0x00
this.gb18030_second = 0x00,
this.gb18030_third = 0x00
}
/**
* @param {Stream} stream The stream of bytes being decoded.
* @param {number} bite The next byte read from the stream.
* @return The next code point(s) decoded, or null if not enough data exists in the input stream to decode a complete code point.
*/
handler(stream, bite) {
// 1. If byte is end-of-stream and gb18030 first, gb18030
// second, and gb18030 third are 0x00, return finished.
if (bite === end_of_stream && this.gb18030_first === 0x00 &&
this.gb18030_second === 0x00 && this.gb18030_third === 0x00) {
return finished
}
// 2. If byte is end-of-stream, and gb18030 first, gb18030
// second, or gb18030 third is not 0x00, set gb18030 first,
// gb18030 second, and gb18030 third to 0x00, and return error.
if (bite === end_of_stream &&
(this.gb18030_first !== 0x00 || this.gb18030_second !== 0x00 ||
this.gb18030_third !== 0x00)) {
this.gb18030_first = 0x00
this.gb18030_second = 0x00
this.gb18030_third = 0x00
decoderError(this.fatal)
}
var code_point
// 3. If gb18030 third is not 0x00, run these substeps:
if (this.gb18030_third !== 0x00) {
// 1. Let code point be null.
code_point = null
// 2. If byte is in the range 0x30 to 0x39, inclusive, set
// code point to the index gb18030 ranges code point for
// (((gb18030 first − 0x81) × 10 + gb18030 second − 0x30) ×
// 126 + gb18030 third − 0x81) × 10 + byte − 0x30.
if (inRange(bite, 0x30, 0x39)) {
code_point = indexGB18030RangesCodePointFor(
(((this.gb18030_first - 0x81) * 10 + this.gb18030_second - 0x30) * 126 +
this.gb18030_third - 0x81) * 10 + bite - 0x30)
}
// 3. Let buffer be a byte sequence consisting of gb18030
// second, gb18030 third, and byte, in order.
var buffer = [this.gb18030_second, this.gb18030_third, bite]
// 4. Set gb18030 first, gb18030 second, and gb18030 third to
// 0x00.
this.gb18030_first = 0x00
this.gb18030_second = 0x00
this.gb18030_third = 0x00
// 5. If code point is null, prepend buffer to stream and
// return error.
if (code_point === null) {
stream.prepend(buffer)
return decoderError(this.fatal)
}
// 6. Return a code point whose value is code point.
return code_point
}
// 4. If gb18030 second is not 0x00, run these substeps:
if (this.gb18030_second !== 0x00) {
// 1. If byte is in the range 0x81 to 0xFE, inclusive, set
// gb18030 third to byte and return continue.
if (inRange(bite, 0x81, 0xFE)) {
this.gb18030_third = bite
return null
}
// 2. Prepend gb18030 second followed by byte to stream, set
// gb18030 first and gb18030 second to 0x00, and return error.
stream.prepend([this.gb18030_second, bite])
this.gb18030_first = 0x00
this.gb18030_second = 0x00
return decoderError(this.fatal)
}
// 5. If gb18030 first is not 0x00, run these substeps:
if (this.gb18030_first !== 0x00) {
// 1. If byte is in the range 0x30 to 0x39, inclusive, set
// gb18030 second to byte and return continue.
if (inRange(bite, 0x30, 0x39)) {
this.gb18030_second = bite
return null
}
// 2. Let lead be gb18030 first, let pointer be null, and set
// gb18030 first to 0x00.
var lead = this.gb18030_first
var pointer = null
this.gb18030_first = 0x00
// 3. Let offset be 0x40 if byte is less than 0x7F and 0x41
// otherwise.
var offset = bite < 0x7F ? 0x40 : 0x41
// 4. If byte is in the range 0x40 to 0x7E, inclusive, or 0x80
// to 0xFE, inclusive, set pointer to (lead − 0x81) × 190 +
// (byte − offset).
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE))
pointer = (lead - 0x81) * 190 + (bite - offset)
// 5. Let code point be null if pointer is null and the index
// code point for pointer in index gb18030 otherwise.
code_point = pointer === null ? null :
indexCodePointFor(pointer, index('gb18030'))
// 6. If code point is null and byte is an ASCII byte, prepend
// byte to stream.
if (code_point === null && isASCIIByte(bite))
stream.prepend(bite)
// 7. If code point is null, return error.
if (code_point === null)
return decoderError(this.fatal)
// 8. Return a code point whose value is code point.
return code_point
}
// 6. If byte is an ASCII byte, return a code point whose value
// is byte.
if (isASCIIByte(bite))
return bite
// 7. If byte is 0x80, return code point U+20AC.
if (bite === 0x80)
return 0x20AC
// 8. If byte is in the range 0x81 to 0xFE, inclusive, set
// gb18030 first to byte and return continue.
if (inRange(bite, 0x81, 0xFE)) {
this.gb18030_first = bite
return null
}
// 9. Return error.
return decoderError(this.fatal)
}
}
// 11.2.2 gb18030 encoder
/**
* @implements {Encoder}
*/
export class GB18030Encoder {
/**
* @param {Stream} stream Input stream.
* @param {number} code_point Next code point read from the stream.
* @return Byte(s) to emit.
*/
handler(stream, code_point) {
// 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream)
return finished
// 2. If code point is an ASCII code point, return a byte whose
// value is code point.
if (isASCIICodePoint(code_point))
return code_point
// 3. If code point is U+E5E5, return error with code point.
if (code_point === 0xE5E5)
return encoderError(code_point)
// 4. If the gbk flag is set and code point is U+20AC, return
// byte 0x80.
if (this.gbk_flag && code_point === 0x20AC)
return 0x80
// 5. Let pointer be the index pointer for code point in index
// gb18030.
var pointer = indexPointerFor(code_point, index('gb18030'))
// 6. If pointer is not null, run these substeps:
if (pointer !== null) {
// 1. Let lead be floor(pointer / 190) + 0x81.
var lead = floor(pointer / 190) + 0x81
// 2. Let trail be pointer % 190.
var trail = pointer % 190
// 3. Let offset be 0x40 if trail is less than 0x3F and 0x41 otherwise.
var offset = trail < 0x3F ? 0x40 : 0x41
// 4. Return two bytes whose values are lead and trail + offset.
return [lead, trail + offset]
}
// 7. If gbk flag is set, return error with code point.
if (this.gbk_flag)
return encoderError(code_point)
// 8. Set pointer to the index gb18030 ranges pointer for code
// point.
pointer = indexGB18030RangesPointerFor(code_point)
// 9. Let byte1 be floor(pointer / 10 / 126 / 10).
var byte1 = floor(pointer / 10 / 126 / 10)
// 10. Set pointer to pointer − byte1 × 10 × 126 × 10.
pointer = pointer - byte1 * 10 * 126 * 10
// 11. Let byte2 be floor(pointer / 10 / 126).
var byte2 = floor(pointer / 10 / 126)
// 12. Set pointer to pointer − byte2 × 10 × 126.
pointer = pointer - byte2 * 10 * 126
// 13. Let byte3 be floor(pointer / 10).
var byte3 = floor(pointer / 10)
// 14. Let byte4 be pointer − byte3 × 10.
var byte4 = pointer - byte3 * 10
// 15. Return four bytes whose values are byte1 + 0x81, byte2 +
// 0x30, byte3 + 0x81, byte4 + 0x30.
return [byte1 + 0x81,
byte2 + 0x30,
byte3 + 0x81,
byte4 + 0x30]
}
constructor(options = {}, gbk_flag = false) {
// gb18030's decoder has an associated gbk flag (initially unset).
this.gbk_flag = gbk_flag
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/encodings.js | aws/lti-middleware/node_modules/text-decoding/build/encodings.js | /**
* Encodings table: https://encoding.spec.whatwg.org/encodings.json
*/
const encodings = [
{
encodings: [
{
labels: [
"unicode-1-1-utf-8",
"utf-8",
"utf8",
],
name: "UTF-8",
},
],
heading: "The Encoding",
},
{
encodings: [
{
labels: [
"866",
"cp866",
"csibm866",
"ibm866",
],
name: "IBM866",
},
{
labels: [
"csisolatin2",
"iso-8859-2",
"iso-ir-101",
"iso8859-2",
"iso88592",
"iso_8859-2",
"iso_8859-2:1987",
"l2",
"latin2",
],
name: "ISO-8859-2",
},
{
labels: [
"csisolatin3",
"iso-8859-3",
"iso-ir-109",
"iso8859-3",
"iso88593",
"iso_8859-3",
"iso_8859-3:1988",
"l3",
"latin3",
],
name: "ISO-8859-3",
},
{
labels: [
"csisolatin4",
"iso-8859-4",
"iso-ir-110",
"iso8859-4",
"iso88594",
"iso_8859-4",
"iso_8859-4:1988",
"l4",
"latin4",
],
name: "ISO-8859-4",
},
{
labels: [
"csisolatincyrillic",
"cyrillic",
"iso-8859-5",
"iso-ir-144",
"iso8859-5",
"iso88595",
"iso_8859-5",
"iso_8859-5:1988",
],
name: "ISO-8859-5",
},
{
labels: [
"arabic",
"asmo-708",
"csiso88596e",
"csiso88596i",
"csisolatinarabic",
"ecma-114",
"iso-8859-6",
"iso-8859-6-e",
"iso-8859-6-i",
"iso-ir-127",
"iso8859-6",
"iso88596",
"iso_8859-6",
"iso_8859-6:1987",
],
name: "ISO-8859-6",
},
{
labels: [
"csisolatingreek",
"ecma-118",
"elot_928",
"greek",
"greek8",
"iso-8859-7",
"iso-ir-126",
"iso8859-7",
"iso88597",
"iso_8859-7",
"iso_8859-7:1987",
"sun_eu_greek",
],
name: "ISO-8859-7",
},
{
labels: [
"csiso88598e",
"csisolatinhebrew",
"hebrew",
"iso-8859-8",
"iso-8859-8-e",
"iso-ir-138",
"iso8859-8",
"iso88598",
"iso_8859-8",
"iso_8859-8:1988",
"visual",
],
name: "ISO-8859-8",
},
{
labels: [
"csiso88598i",
"iso-8859-8-i",
"logical",
],
name: "ISO-8859-8-I",
},
{
labels: [
"csisolatin6",
"iso-8859-10",
"iso-ir-157",
"iso8859-10",
"iso885910",
"l6",
"latin6",
],
name: "ISO-8859-10",
},
{
labels: [
"iso-8859-13",
"iso8859-13",
"iso885913",
],
name: "ISO-8859-13",
},
{
labels: [
"iso-8859-14",
"iso8859-14",
"iso885914",
],
name: "ISO-8859-14",
},
{
labels: [
"csisolatin9",
"iso-8859-15",
"iso8859-15",
"iso885915",
"iso_8859-15",
"l9",
],
name: "ISO-8859-15",
},
{
labels: [
"iso-8859-16",
],
name: "ISO-8859-16",
},
{
labels: [
"cskoi8r",
"koi",
"koi8",
"koi8-r",
"koi8_r",
],
name: "KOI8-R",
},
{
labels: [
"koi8-ru",
"koi8-u",
],
name: "KOI8-U",
},
{
labels: [
"csmacintosh",
"mac",
"macintosh",
"x-mac-roman",
],
name: "macintosh",
},
{
labels: [
"dos-874",
"iso-8859-11",
"iso8859-11",
"iso885911",
"tis-620",
"windows-874",
],
name: "windows-874",
},
{
labels: [
"cp1250",
"windows-1250",
"x-cp1250",
],
name: "windows-1250",
},
{
labels: [
"cp1251",
"windows-1251",
"x-cp1251",
],
name: "windows-1251",
},
{
labels: [
"ansi_x3.4-1968",
"ascii",
"cp1252",
"cp819",
"csisolatin1",
"ibm819",
"iso-8859-1",
"iso-ir-100",
"iso8859-1",
"iso88591",
"iso_8859-1",
"iso_8859-1:1987",
"l1",
"latin1",
"us-ascii",
"windows-1252",
"x-cp1252",
],
name: "windows-1252",
},
{
labels: [
"cp1253",
"windows-1253",
"x-cp1253",
],
name: "windows-1253",
},
{
labels: [
"cp1254",
"csisolatin5",
"iso-8859-9",
"iso-ir-148",
"iso8859-9",
"iso88599",
"iso_8859-9",
"iso_8859-9:1989",
"l5",
"latin5",
"windows-1254",
"x-cp1254",
],
name: "windows-1254",
},
{
labels: [
"cp1255",
"windows-1255",
"x-cp1255",
],
name: "windows-1255",
},
{
labels: [
"cp1256",
"windows-1256",
"x-cp1256",
],
name: "windows-1256",
},
{
labels: [
"cp1257",
"windows-1257",
"x-cp1257",
],
name: "windows-1257",
},
{
labels: [
"cp1258",
"windows-1258",
"x-cp1258",
],
name: "windows-1258",
},
{
labels: [
"x-mac-cyrillic",
"x-mac-ukrainian",
],
name: "x-mac-cyrillic",
},
],
heading: "Legacy single-byte encodings",
},
{
encodings: [
{
labels: [
"chinese",
"csgb2312",
"csiso58gb231280",
"gb2312",
"gb_2312",
"gb_2312-80",
"gbk",
"iso-ir-58",
"x-gbk",
],
name: "GBK",
},
{
labels: [
"gb18030",
],
name: "gb18030",
},
],
heading: "Legacy multi-byte Chinese (simplified) encodings",
},
{
encodings: [
{
labels: [
"big5",
"big5-hkscs",
"cn-big5",
"csbig5",
"x-x-big5",
],
name: "Big5",
},
],
heading: "Legacy multi-byte Chinese (traditional) encodings",
},
{
encodings: [
{
labels: [
"cseucpkdfmtjapanese",
"euc-jp",
"x-euc-jp",
],
name: "EUC-JP",
},
{
labels: [
"csiso2022jp",
"iso-2022-jp",
],
name: "ISO-2022-JP",
},
{
labels: [
"csshiftjis",
"ms932",
"ms_kanji",
"shift-jis",
"shift_jis",
"sjis",
"windows-31j",
"x-sjis",
],
name: "Shift_JIS",
},
],
heading: "Legacy multi-byte Japanese encodings",
},
{
encodings: [
{
labels: [
"cseuckr",
"csksc56011987",
"euc-kr",
"iso-ir-149",
"korean",
"ks_c_5601-1987",
"ks_c_5601-1989",
"ksc5601",
"ksc_5601",
"windows-949",
],
name: "EUC-KR",
},
],
heading: "Legacy multi-byte Korean encodings",
},
{
encodings: [
{
labels: [
"csiso2022kr",
"hz-gb-2312",
"iso-2022-cn",
"iso-2022-cn-ext",
"iso-2022-kr",
],
name: "replacement",
},
{
labels: [
"utf-16be",
],
name: "UTF-16BE",
},
{
labels: [
"utf-16",
"utf-16le",
],
name: "UTF-16LE",
},
{
labels: [
"x-user-defined",
],
name: "x-user-defined",
},
],
heading: "Legacy miscellaneous encodings",
},
]
module.exports=encodings | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/index.js | aws/lti-middleware/node_modules/text-decoding/build/index.js | const TextEncoder = require('./lib/TextEncoder');
const TextDecoder = require('./lib/TextDecoder');
const EncodingIndexes = require('./encoding-indexes');
const { getEncoding } = require('./lib');
//
// Implementation of Encoding specification
// https://encoding.spec.whatwg.org/
//
module.exports.TextEncoder = TextEncoder
module.exports.TextDecoder = TextDecoder
module.exports.EncodingIndexes = EncodingIndexes
module.exports.getEncoding = getEncoding | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/table.js | aws/lti-middleware/node_modules/text-decoding/build/table.js | const Encodings = require('./encodings');
const { UTF8Decoder, UTF8Encoder } = require('./implementations/utf8');
const { UTF16Decoder, UTF16Encoder } = require('./implementations/utf16');
const { GB18030Decoder, GB18030Encoder } = require('./implementations/gb18030');
const { Big5Decoder, Big5Encoder } = require('./implementations/big5');
const { EUCJPDecoder, EUCJPEncoder } = require('./implementations/euc-jp');
const { EUCKRDecoder, EUCKREncoder } = require('./implementations/euc-kr');
const { ISO2022JPDecoder, ISO2022JPEncoder } = require('./implementations/iso-2022-jp');
const { XUserDefinedDecoder, XUserDefinedEncoder } = require('./implementations/x-user-defined');
const { ShiftJISDecoder, ShiftJISEncoder } = require('./implementations/shift-jis');
const { SingleByteDecoder, SingleByteEncoder } = require('./implementations/single-byte');
const index = require('./indexes');;
// 5.2 Names and labels
// TODO: Define @typedef for Encoding: {name:string,labels:Array.<string>}
// https://github.com/google/closure-compiler/issues/247
// Label to encoding registry.
/** @type {Object.<string,{name:string,labels:Array.<string>}>} */
const label_to_encoding = {}
Encodings.forEach(({ encodings }) => {
encodings.forEach((encoding) => {
encoding.labels.forEach((label) => {
label_to_encoding[label] = encoding
})
})
})
// Registry of of encoder/decoder factories, by encoding name.
const encoders = {
'UTF-8'() { // 9.1 utf-8
return new UTF8Encoder()
},
'GBK'(options) { // 11.1.2 gbk encoder;
// gbk's encoder is gb18030's encoder with its gbk flag set.
return new GB18030Encoder(options, true)
},
'gb18030'() {
return new GB18030Encoder()
},
'Big5'() {
return new Big5Encoder()
},
'EUC-JP'() {
return new EUCJPEncoder()
},
'EUC-KR'() {
return new EUCKREncoder()
},
'ISO-2022-JP'() {
return new ISO2022JPEncoder()
},
'UTF-16BE'() { // 15.3 utf-16be
return new UTF16Encoder(true)
},
'UTF-16LE'() { // 15.4 utf-16le
return new UTF16Encoder()
},
'x-user-defined'() {
return new XUserDefinedEncoder()
},
'Shift_JIS'() {
return new ShiftJISEncoder()
},
}
/** @type {Object.<string, function({fatal:boolean}): Decoder>} */
const decoders = {
'UTF-8'(options) { // 9.1.1 utf-8 decoder
return new UTF8Decoder(options)
},
'GBK'(options) { // 11.1.1 gbk decoder; gbk's decoder is gb18030's decoder.
return new GB18030Decoder(options)
},
'gb18030'(options) {
return new GB18030Decoder(options)
},
'Big5'(options) {
return new Big5Decoder(options)
},
'EUC-JP'(options) {
return new EUCJPDecoder(options)
},
'EUC-KR'(options) {
return new EUCKRDecoder(options)
},
'ISO-2022-JP'(options) {
return new ISO2022JPDecoder(options)
},
'UTF-16BE'(options) { // 15.3.1 utf-16be decoder
return new UTF16Decoder(true, options)
},
'UTF-16LE'(options) { // 15.4.1 utf-16le decoder
return new UTF16Decoder(false, options)
},
'x-user-defined'() {
return new XUserDefinedDecoder()
},
'Shift_JIS'(options) {
return new ShiftJISDecoder(options)
},
}
Encodings.forEach(({ heading, encodings }) => {
if (heading != 'Legacy single-byte encodings')
return
encodings.forEach((encoding) => {
const name = encoding.name
const idx = index(name.toLowerCase())
decoders[name] = (options) => {
return new SingleByteDecoder(idx, options)
}
encoders[name] = (options) => {
return new SingleByteEncoder(idx, options)
}
})
})
module.exports.label_to_encoding = label_to_encoding
module.exports.encoders = encoders
module.exports.decoders = decoders | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/encoding-indexes.js | aws/lti-middleware/node_modules/text-decoding/build/encoding-indexes.js | const Indexes = {
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | true |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/indexes.js | aws/lti-middleware/node_modules/text-decoding/build/indexes.js | const { inRange } = require('./utils');
const Indexes = require('./encoding-indexes');
//
// 6. Indexes
//
/**
* @param {number} pointer The |pointer| to search for.
* @param {(!Array.<?number>|undefined)} index The |index| to search within.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in |index|.
*/
function indexCodePointFor(pointer, i) {
if (!i) return null
return i[pointer] || null
}
/**
* @param {number} code_point The |code point| to search for.
* @param {!Array.<?number>} i The |index| to search within.
* @return {?number} The first pointer corresponding to |code point| in
* |index|, or null if |code point| is not in |index|.
*/
function indexPointerFor(code_point, i) {
var pointer = i.indexOf(code_point)
return pointer === -1 ? null : pointer
}
/**
* @param {string} name Name of the index.
*/
function index(name) {
return Indexes[name]
}
/**
* @param {number} pointer The |pointer| to search for in the gb18030 index.
* @return The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in the gb18030 index.
*/
function indexGB18030RangesCodePointFor(pointer) {
// 1. If pointer is greater than 39419 and less than 189000, or
// pointer is greater than 1237575, return null.
if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575))
return null
// 2. If pointer is 7457, return code point U+E7C7.
if (pointer === 7457) return 0xE7C7
// 3. Let offset be the last pointer in index gb18030 ranges that
// is equal to or less than pointer and let code point offset be
// its corresponding code point.
var offset = 0
var code_point_offset = 0
var idx = index('gb18030-ranges')
var i
for (i = 0; i < idx.length; ++i) {
/** @type {!Array.<number>} */
var entry = idx[i]
if (entry[0] <= pointer) {
offset = entry[0]
code_point_offset = entry[1]
} else {
break
}
}
// 4. Return a code point whose value is code point offset +
// pointer − offset.
return code_point_offset + pointer - offset
}
/**
* @param {number} code_point The |code point| to locate in the gb18030 index.
* @return {number} The first pointer corresponding to |code point| in the
* gb18030 index.
*/
function indexGB18030RangesPointerFor(code_point) {
// 1. If code point is U+E7C7, return pointer 7457.
if (code_point === 0xE7C7) return 7457
// 2. Let offset be the last code point in index gb18030 ranges
// that is equal to or less than code point and let pointer offset
// be its corresponding pointer.
var offset = 0
var pointer_offset = 0
var idx = index('gb18030-ranges')
var i
for (i = 0; i < idx.length; ++i) {
/** @type {!Array.<number>} */
var entry = idx[i]
if (entry[1] <= code_point) {
offset = entry[1]
pointer_offset = entry[0]
} else {
break
}
}
// 3. Return a pointer whose value is pointer offset + code point
// − offset.
return pointer_offset + code_point - offset
}
/**
* @param {number} code_point The |code_point| to search for in the Shift_JIS
* index.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in the Shift_JIS index.
*/
function indexShiftJISPointerFor(code_point) {
// 1. Let index be index jis0208 excluding all entries whose
// pointer is in the range 8272 to 8835, inclusive.
shift_jis_index = shift_jis_index ||
index('jis0208').map((cp, pointer) => {
return inRange(pointer, 8272, 8835) ? null : cp
})
const index_ = shift_jis_index
// 2. Return the index pointer for code point in index.
return index_.indexOf(code_point)
}
var shift_jis_index
/**
* @param {number} code_point The |code_point| to search for in the big5
* index.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in the big5 index.
*/
function indexBig5PointerFor(code_point) {
// 1. Let index be index Big5 excluding all entries whose pointer
big5_index_no_hkscs = big5_index_no_hkscs ||
index('big5').map((cp, pointer) => {
return (pointer < (0xA1 - 0x81) * 157) ? null : cp
})
var index_ = big5_index_no_hkscs
// 2. If code point is U+2550, U+255E, U+2561, U+256A, U+5341, or
// U+5345, return the last pointer corresponding to code point in
// index.
if (code_point === 0x2550 || code_point === 0x255E ||
code_point === 0x2561 || code_point === 0x256A ||
code_point === 0x5341 || code_point === 0x5345) {
return index_.lastIndexOf(code_point)
}
// 3. Return the index pointer for code point in index.
return indexPointerFor(code_point, index_)
}
var big5_index_no_hkscs
module.exports = index
module.exports.indexCodePointFor = indexCodePointFor
module.exports.indexPointerFor = indexPointerFor
module.exports.indexGB18030RangesCodePointFor = indexGB18030RangesCodePointFor
module.exports.indexGB18030RangesPointerFor = indexGB18030RangesPointerFor
module.exports.indexShiftJISPointerFor = indexShiftJISPointerFor
module.exports.indexBig5PointerFor = indexBig5PointerFor | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/utils.js | aws/lti-middleware/node_modules/text-decoding/build/utils.js | //
// Utilities
//
/**
* @param {number} a The number to test.
* @param {number} min The minimum value in the range, inclusive.
* @param {number} max The maximum value in the range, inclusive.
* @return {boolean} True if a >= min and a <= max.
*/
function inRange(a, min, max) {
return min <= a && a <= max
}
const floor = Math.floor
/**
* @param {string} string Input string of UTF-16 code units.
* @return {!Array.<number>} Code points.
*/
function stringToCodePoints(string) {
// https://heycam.github.io/webidl/#dfn-obtain-unicode
// 1. Let S be the DOMString value.
var s = String(string)
// 2. Let n be the length of S.
var n = s.length
// 3. Initialize i to 0.
var i = 0
// 4. Initialize U to be an empty sequence of Unicode characters.
var u = []
// 5. While i < n:
while (i < n) {
// 1. Let c be the code unit in S at index i.
var c = s.charCodeAt(i)
// 2. Depending on the value of c:
// c < 0xD800 or c > 0xDFFF
if (c < 0xD800 || c > 0xDFFF) {
// Append to U the Unicode character with code point c.
u.push(c)
}
// 0xDC00 ≤ c ≤ 0xDFFF
else if (0xDC00 <= c && c <= 0xDFFF) {
// Append to U a U+FFFD REPLACEMENT CHARACTER.
u.push(0xFFFD)
}
// 0xD800 ≤ c ≤ 0xDBFF
else if (0xD800 <= c && c <= 0xDBFF) {
// 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
// CHARACTER.
if (i === n - 1) {
u.push(0xFFFD)
}
// 2. Otherwise, i < n−1:
else {
// 1. Let d be the code unit in S at index i+1.
var d = s.charCodeAt(i + 1)
// 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
if (0xDC00 <= d && d <= 0xDFFF) {
// 1. Let a be c & 0x3FF.
var a = c & 0x3FF
// 2. Let b be d & 0x3FF.
var b = d & 0x3FF
// 3. Append to U the Unicode character with code point
// 2^16+2^10*a+b.
u.push(0x10000 + (a << 10) + b)
// 4. Set i to i+1.
i += 1
}
// 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a
// U+FFFD REPLACEMENT CHARACTER.
else {
u.push(0xFFFD)
}
}
}
// 3. Set i to i+1.
i += 1
}
// 6. Return U.
return u
}
/**
* @param {!Array.<number>} code_points Array of code points.
* @return {string} string String of UTF-16 code units.
*/
function codePointsToString(code_points) {
var s = ''
for (var i = 0; i < code_points.length; ++i) {
var cp = code_points[i]
if (cp <= 0xFFFF) {
s += String.fromCharCode(cp)
} else {
cp -= 0x10000
s += String.fromCharCode((cp >> 10) + 0xD800,
(cp & 0x3FF) + 0xDC00)
}
}
return s
}
/**
* @param {boolean} fatal If true, decoding errors raise an exception.
* @param {number=} opt_code_point Override the standard fallback code point.
* @return The code point to insert on a decoding error.
*/
function decoderError(fatal, opt_code_point) {
if (fatal)
throw TypeError('Decoder error')
return opt_code_point || 0xFFFD
}
/**
* @param {number} code_point The code point that could not be encoded.
* @return {number} Always throws, no value is actually returned.
*/
function encoderError(code_point) {
throw TypeError('The code point ' + code_point + ' could not be encoded.')
}
/**
* @param {number} code_unit
* @param {boolean} utf16be
*/
function convertCodeUnitToBytes(code_unit, utf16be) {
// 1. Let byte1 be code unit >> 8.
const byte1 = code_unit >> 8
// 2. Let byte2 be code unit & 0x00FF.
const byte2 = code_unit & 0x00FF
// 3. Then return the bytes in order:
// utf-16be flag is set: byte1, then byte2.
if (utf16be)
return [byte1, byte2]
// utf-16be flag is unset: byte2, then byte1.
return [byte2, byte1]
}
//
// 4. Terminology
//
/**
* An ASCII byte is a byte in the range 0x00 to 0x7F, inclusive.
* @param {number} a The number to test.
* @return {boolean} True if a is in the range 0x00 to 0x7F, inclusive.
*/
function isASCIIByte(a) {
return 0x00 <= a && a <= 0x7F
}
/**
* An ASCII code point is a code point in the range U+0000 to
* U+007F, inclusive.
*/
const isASCIICodePoint = isASCIIByte
/**
* End-of-stream is a special token that signifies no more tokens are in the stream.
*/
const end_of_stream = -1
const finished = -1
module.exports.inRange = inRange
module.exports.floor = floor
module.exports.stringToCodePoints = stringToCodePoints
module.exports.codePointsToString = codePointsToString
module.exports.decoderError = decoderError
module.exports.encoderError = encoderError
module.exports.convertCodeUnitToBytes = convertCodeUnitToBytes
module.exports.isASCIIByte = isASCIIByte
module.exports.isASCIICodePoint = isASCIICodePoint
module.exports.end_of_stream = end_of_stream
module.exports.finished = finished | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/lib/TextDecoder.js | aws/lti-middleware/node_modules/text-decoding/build/lib/TextDecoder.js | const Stream = require('./'); const { DEFAULT_ENCODING, getEncoding } = Stream;
const { end_of_stream, finished, codePointsToString } = require('../utils');
const { decoders } = require('../table');
// 8.1 Interface TextDecoder
class TextDecoder {
/**
* @param {string=} label The label of the encoding; defaults to 'utf-8'.
* @param {Object=} options
*/
constructor(label = DEFAULT_ENCODING, options = {}) {
// A TextDecoder object has an associated encoding, decoder,
// stream, ignore BOM flag (initially unset), BOM seen flag
// (initially unset), error mode (initially replacement), and do
// not flush flag (initially unset).
/** @private */
this._encoding = null
/** @private @type {?Decoder} */
this._decoder = null
/** @private @type {boolean} */
this._ignoreBOM = false
/** @private @type {boolean} */
this._BOMseen = false
/** @private @type {string} */
this._error_mode = 'replacement'
/** @private @type {boolean} */
this._do_not_flush = false
// 1. Let encoding be the result of getting an encoding from
// label.
const encoding = getEncoding(label)
// 2. If encoding is failure or replacement, throw a RangeError.
if (encoding === null || encoding.name == 'replacement')
throw RangeError('Unknown encoding: ' + label)
if (!decoders[encoding.name]) {
throw Error('Decoder not present.' +
' Did you forget to include encoding-indexes.js first?')
}
// 4. Set dec's encoding to encoding.
this._encoding = encoding
// 5. If options's fatal member is true, set dec's error mode to
// fatal.
if (options['fatal'])
this._error_mode = 'fatal'
// 6. If options's ignoreBOM member is true, set dec's ignore BOM
// flag.
if (options['ignoreBOM'])
this._ignoreBOM = true
}
get encoding() {
return this._encoding.name.toLowerCase()
}
get fatal() {
return this._error_mode === 'fatal'
}
get ignoreBOM() {
return this._ignoreBOM
}
/**
* @param {BufferSource=} input The buffer of bytes to decode.
* @param {Object=} options
* @return The decoded string.
*/
decode(input, options = {}) {
let bytes
if (typeof input === 'object' && input instanceof ArrayBuffer) {
bytes = new Uint8Array(input)
} else if (typeof input === 'object' && 'buffer' in input &&
input.buffer instanceof ArrayBuffer) {
bytes = new Uint8Array(input.buffer,
input.byteOffset,
input.byteLength)
} else {
bytes = new Uint8Array(0)
}
// 1. If the do not flush flag is unset, set decoder to a new
// encoding's decoder, set stream to a new stream, and unset the
// BOM seen flag.
if (!this._do_not_flush) {
this._decoder = decoders[this._encoding.name]({
fatal: this._error_mode === 'fatal' })
this._BOMseen = false
}
// 2. If options's stream is true, set the do not flush flag, and
// unset the do not flush flag otherwise.
this._do_not_flush = Boolean(options['stream'])
// 3. If input is given, push a copy of input to stream.
// TODO: Align with spec algorithm - maintain stream on instance.
const input_stream = new Stream(bytes)
// 4. Let output be a new stream.
const output = []
/** @type {?(number|!Array.<number>)} */
let result
// 5. While true:
while (true) {
// 1. Let token be the result of reading from stream.
const token = input_stream.read()
// 2. If token is end-of-stream and the do not flush flag is
// set, return output, serialized.
// TODO: Align with spec algorithm.
if (token === end_of_stream)
break
// 3. Otherwise, run these subsubsteps:
// 1. Let result be the result of processing token for decoder,
// stream, output, and error mode.
result = this._decoder.handler(input_stream, token)
// 2. If result is finished, return output, serialized.
if (result === finished)
break
if (result !== null) {
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
}
// 3. Otherwise, if result is error, throw a TypeError.
// (Thrown in handler)
// 4. Otherwise, do nothing.
}
// TODO: Align with spec algorithm.
if (!this._do_not_flush) {
do {
result = this._decoder.handler(input_stream, input_stream.read())
if (result === finished)
break
if (result === null)
continue
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
} while (!input_stream.endOfStream())
this._decoder = null
}
return this.serializeStream(output)
}
// A TextDecoder object also has an associated serialize stream
// algorithm...
/**
* @param {!Array.<number>} stream
*/
serializeStream(stream) {
// 1. Let token be the result of reading from stream.
// (Done in-place on array, rather than as a stream)
// 2. If encoding is UTF-8, UTF-16BE, or UTF-16LE, and ignore
// BOM flag and BOM seen flag are unset, run these subsubsteps:
if (['UTF-8', 'UTF-16LE', 'UTF-16BE'].includes(this._encoding.name) &&
!this._ignoreBOM && !this._BOMseen) {
if (stream.length > 0 && stream[0] === 0xFEFF) {
// 1. If token is U+FEFF, set BOM seen flag.
this._BOMseen = true
stream.shift()
} else if (stream.length > 0) {
// 2. Otherwise, if token is not end-of-stream, set BOM seen
// flag and append token to stream.
this._BOMseen = true
} else {
// 3. Otherwise, if token is not end-of-stream, append token
// to output.
// (no-op)
}
}
// 4. Otherwise, return output.
return codePointsToString(stream)
}
}
module.exports = TextDecoder | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/lib/index.js | aws/lti-middleware/node_modules/text-decoding/build/lib/index.js | const { end_of_stream } = require('../utils');
const { label_to_encoding } = require('../table');
class Stream {
/**
* A stream represents an ordered sequence of tokens.
* @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide
* the stream.
*/
constructor(tokens) {
this.tokens = [...tokens]
// Reversed as push/pop is more efficient than shift/unshift.
this.tokens.reverse()
}
/**
* @returns True if end-of-stream has been hit.
*/
endOfStream() {
return !this.tokens.length
}
/**
* When a token is read from a stream, the first token in the
* stream must be returned and subsequently removed, and
* end-of-stream must be returned otherwise.
*
* @return Get the next token from the stream, or end_of_stream.
*/
read() {
if (!this.tokens.length)
return end_of_stream
return this.tokens.pop()
}
/**
* When one or more tokens are prepended to a stream, those tokens
* must be inserted, in given order, before the first token in the
* stream.
*
* @param {(number|!Array.<number>)} token The token(s) to prepend to the
* stream.
*/
prepend(token) {
if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token)
while (tokens.length)
this.tokens.push(tokens.pop())
} else {
this.tokens.push(token)
}
}
/**
* When one or more tokens are pushed to a stream, those tokens
* must be inserted, in given order, after the last token in the
* stream.
*
* @param {(number|!Array.<number>)} token The tokens(s) to push to the
* stream.
*/
push(token) {
if (Array.isArray(token)) {
const tokens = /**@type {!Array.<number>}*/(token)
while (tokens.length)
this.tokens.unshift(tokens.shift())
} else {
this.tokens.unshift(token)
}
}
}
const DEFAULT_ENCODING = 'utf-8'
/**
* Returns the encoding for the label.
* @param {string} label The encoding label.
*/
function getEncoding(label) {
// 1. Remove any leading and trailing ASCII whitespace from label.
label = String(label).trim().toLowerCase()
// 2. If label is an ASCII case-insensitive match for any of the
// labels listed in the table below, return the corresponding
// encoding, and failure otherwise.
if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) {
return label_to_encoding[label]
}
return null
}
//
// 5. Encodings
//
// 5.1 Encoders and decoders
// /** @interface */
// function Decoder() {}
// Decoder.prototype = {
// /**
// * @param {Stream} stream The stream of bytes being decoded.
// * @param {number} bite The next byte read from the stream.
// * @return {?(number|!Array.<number>)} The next code point(s)
// * decoded, or null if not enough data exists in the input
// * stream to decode a complete code point, or |finished|.
// */
// handler: function(stream, bite) {},
// }
// /** @interface */
// function Encoder() {}
// Encoder.prototype = {
// /**
// * @param {Stream} stream The stream of code points being encoded.
// * @param {number} code_point Next code point read from the stream.
// * @return {(number|!Array.<number>)} Byte(s) to emit, or |finished|.
// */
// handler: function(stream, code_point) {},
// }
module.exports = Stream
module.exports.DEFAULT_ENCODING = DEFAULT_ENCODING
module.exports.getEncoding = getEncoding | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/aws/lti-middleware/node_modules/text-decoding/build/lib/TextEncoder.js | aws/lti-middleware/node_modules/text-decoding/build/lib/TextEncoder.js | const Stream = require('./'); const { DEFAULT_ENCODING, getEncoding } = Stream;
const { end_of_stream, finished, stringToCodePoints } = require('../utils');
const { encoders } = require('../table');
// 8.2 Interface TextEncoder
class TextEncoder {
/**
* @param {string=} label The label of the encoding. NONSTANDARD.
* @param {Object=} [options] NONSTANDARD.
*/
constructor(label, options = {}) {
// A TextEncoder object has an associated encoding and encoder.
/** @private */
this._encoding = null
/** @private @type {?Encoder} */
this._encoder = null
// Non-standard
/** @private @type {boolean} */
this._do_not_flush = false
/** @private @type {string} */
this._fatal = options['fatal'] ? 'fatal' : 'replacement'
// 2. Set enc's encoding to UTF-8's encoder.
if (options['NONSTANDARD_allowLegacyEncoding']) {
// NONSTANDARD behavior.
label = label !== undefined ? String(label) : DEFAULT_ENCODING
var encoding = getEncoding(label)
if (encoding === null || encoding.name === 'replacement')
throw RangeError('Unknown encoding: ' + label)
if (!encoders[encoding.name]) {
throw Error('Encoder not present.' +
' Did you forget to include encoding-indexes.js first?')
}
this._encoding = encoding
} else {
// Standard behavior.
this._encoding = getEncoding('utf-8')
if (label !== undefined && 'console' in global) {
console.warn('TextEncoder constructor called with encoding label, '
+ 'which is ignored.')
}
}
}
get encoding() {
return this._encoding.name.toLowerCase()
}
/**
* @param {string=} opt_string The string to encode.
* @param {Object=} options
*/
encode(opt_string = '', options = {}) {
// NOTE: This option is nonstandard. None of the encodings
// permitted for encoding (i.e. UTF-8, UTF-16) are stateful when
// the input is a USVString so streaming is not necessary.
if (!this._do_not_flush)
this._encoder = encoders[this._encoding.name]({
fatal: this._fatal === 'fatal' })
this._do_not_flush = Boolean(options['stream'])
// 1. Convert input to a stream.
const input = new Stream(stringToCodePoints(opt_string))
// 2. Let output be a new stream
const output = []
/** @type {?(number|!Array.<number>)} */
var result
// 3. While true, run these substeps:
while (true) {
// 1. Let token be the result of reading from input.
var token = input.read()
if (token === end_of_stream)
break
// 2. Let result be the result of processing token for encoder,
// input, output.
result = this._encoder.handler(input, token)
if (result === finished)
break
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
}
// TODO: Align with spec algorithm.
if (!this._do_not_flush) {
while (true) {
result = this._encoder.handler(input, input.read())
if (result === finished)
break
if (Array.isArray(result))
output.push.apply(output, /**@type {!Array.<number>}*/(result))
else
output.push(result)
}
this._encoder = null
}
// 3. If result is finished, convert output into a byte sequence,
// and then return a Uint8Array object wrapping an ArrayBuffer
// containing output.
return new Uint8Array(output)
}
}
module.exports = TextEncoder | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.