Skip to content

Commit

Permalink
enable all eslint rules and fix problems
Browse files Browse the repository at this point in the history
See discussion in tus#291
- had to disable no-use-before-define many places where onSuccess uses the upload object, maybe in the future onsuccess could provide upload as an argument to onSuccess
- also a lot of functions moved (as eslint doesn't allow function hoisting)
- disabled eslint for demos/cordova and demos/browser
  • Loading branch information
mifi committed Oct 29, 2021
1 parent 56739c4 commit d94abbe
Show file tree
Hide file tree
Showing 29 changed files with 774 additions and 746 deletions.
3 changes: 2 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
demos/*/node_modules
demos/cordova/platforms
demos/cordova/plugins
demos/cordova/www/js/tus.js
demos/cordova/www/js/index.js
demos/reactnative
demos/browser
lib.esm
lib.es5
dist
23 changes: 0 additions & 23 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,6 @@
// rules we had to turn off just to get a pass, but we'd
// like to turn on one by one with separate PRs
////////////////////////////////////////////////////////////
"consistent-return": ["warn"],
"eqeqeq": ["warn"],
"guard-for-in": ["warn"],
"import/no-extraneous-dependencies": ["warn"],
"import/no-unresolved": ["warn"],
"no-bitwise": ["warn"],
"no-mixed-operators": ["warn"],
"no-multi-assign": ["warn"],
"no-param-reassign": ["warn"],
"no-redeclare": ["warn"],
"no-restricted-globals": ["warn"],
"no-restricted-syntax": ["warn"],
"no-return-assign": ["warn"],
"no-shadow": ["warn"],
"no-unused-expressions": ["warn"],
"no-use-before-define": ["warn"],
"no-var": ["warn"],
"node/no-deprecated-api": ["warn"],
"prefer-destructuring": ["warn"],
"prefer-rest-params": ["warn"],
"react/destructuring-assignment": ["warn"],
"react/sort-comp": ["warn"],
"vars-on-top": ["warn"],

// Used so many places
"no-underscore-dangle": ["off"]
Expand Down
8 changes: 5 additions & 3 deletions bin/browserstack-jasmine.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint no-console: 0 */

// eslint-disable-next-line import/no-extraneous-dependencies
const browserstack = require('browserstack-runner')

const BS_USERNAME = process.env.BROWSERSTACK_USERNAME
Expand Down Expand Up @@ -46,7 +47,7 @@ const browsers = [
},
]

if (!BS_USERNAME || BS_USERNAME == '' || !BS_KEY || BS_KEY == '') {
if (!BS_USERNAME || BS_USERNAME === '' || !BS_KEY || BS_KEY === '') {
console.log('Please provide the BROWSERSTACK_USERNAME and BROWSERSTACK_KEY environment variables.')
process.exit(1)
}
Expand All @@ -61,7 +62,8 @@ function runTests (cb) {
browsers,
}, (err, reports) => {
if (err) {
return cb(err)
cb(err)
return
}

// Enable to see full report
Expand All @@ -87,7 +89,7 @@ function runTests (cb) {
console.log(`✓ ${report.browser}: Test suite passed`)
})

if (reports.length != browsers.length) {
if (reports.length !== browsers.length) {
console.log(`✘ Only received ${reports.length} reports but expected ${browsers.length}!`)
process.exitCode = 1
}
Expand Down
1 change: 1 addition & 0 deletions bin/puppeteer-jasmine.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* according to the result.
*/

// eslint-disable-next-line import/no-extraneous-dependencies
const puppeteer = require('puppeteer')
const path = require('path')

Expand Down
17 changes: 9 additions & 8 deletions demos/nodejs/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
/* eslint no-console: 0 */

var fs = require('fs')
var tus = require('../..')
const fs = require('fs')
const tus = require('../..')

var path = `${__dirname}/../../README.md`
var file = fs.createReadStream(path)
var size = fs.statSync(path).size
const path = `${__dirname}/../../README.md`
const file = fs.createReadStream(path)
const { size } = fs.statSync(path)

var options = {
const options = {
endpoint: 'https://tusd.tusdemo.net/files/',
metadata: {
filename: 'README.md',
Expand All @@ -18,13 +18,14 @@ var options = {
throw error
},
onProgress (bytesUploaded, bytesTotal) {
var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2)
console.log(bytesUploaded, bytesTotal, `${percentage}%`)
},
onSuccess () {
// eslint-disable-next-line no-use-before-define
console.log('Upload finished:', upload.url)
},
}

var upload = new tus.Upload(file, options)
const upload = new tus.Upload(file, options)
upload.start()
6 changes: 3 additions & 3 deletions lib/browser/fileReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import FileSource from './sources/FileSource'
import StreamSource from './sources/StreamSource'

export default class FileReader {
openFile (input, chunkSize) {
openFile (input, chunkSizeIn) {
// In React Native, when user selects a file, instead of a File or Blob,
// you usually get a file object {} with a uri property that contains
// a local path to the file. We use XMLHttpRequest to fetch
Expand All @@ -27,8 +27,8 @@ export default class FileReader {
}

if (typeof input.read === 'function') {
chunkSize = +chunkSize
if (!isFinite(chunkSize)) {
const chunkSize = +chunkSizeIn
if (!Number.isFinite(chunkSize)) {
return Promise.reject(new Error('cannot create source for stream without a finite value for the `chunkSize` option'))
}

Expand Down
52 changes: 27 additions & 25 deletions lib/browser/fingerprint.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,33 @@ import isReactNative from './isReactNative'

// TODO: Differenciate between input types

function hashCode (str) {
// from https://stackoverflow.com/a/8831937/151666
let hash = 0
if (str.length === 0) {
return hash
}
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i)
// eslint-disable-next-line no-bitwise
hash = ((hash << 5) - hash) + char
// eslint-disable-next-line no-bitwise
hash &= hash // Convert to 32bit integer
}
return hash
}

function reactNativeFingerprint (file, options) {
const exifHash = file.exif ? hashCode(JSON.stringify(file.exif)) : 'noexif'
return [
'tus-rn',
file.name || 'noname',
file.size || 'nosize',
exifHash,
options.endpoint,
].join('/')
}

/**
* Generate a fingerprint for a file which will be used the store the endpoint
*
Expand All @@ -23,28 +50,3 @@ export default function fingerprint (file, options) {
options.endpoint,
].join('-'))
}

function reactNativeFingerprint (file, options) {
const exifHash = file.exif ? hashCode(JSON.stringify(file.exif)) : 'noexif'
return [
'tus-rn',
file.name || 'noname',
file.size || 'nosize',
exifHash,
options.endpoint,
].join('/')
}

function hashCode (str) {
// from https://stackoverflow.com/a/8831937/151666
var hash = 0
if (str.length === 0) {
return hash
}
for (var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i)
hash = ((hash << 5) - hash) + char
hash &= hash // Convert to 32bit integer
}
return hash
}
45 changes: 23 additions & 22 deletions lib/browser/httpStack.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
/* eslint-disable max-classes-per-file */
export default class XHRHttpStack {
createRequest (method, url) {
return new Request(method, url)

class Response {
constructor (xhr) {
this._xhr = xhr
}

getName () {
return 'XHRHttpStack'
getStatus () {
return this._xhr.status
}

getHeader (header) {
return this._xhr.getResponseHeader(header)
}

getBody () {
return this._xhr.responseText
}

getUnderlyingObject () {
return this._xhr
}
}

Expand Down Expand Up @@ -75,24 +88,12 @@ class Request {
}
}

class Response {
constructor (xhr) {
this._xhr = xhr
}

getStatus () {
return this._xhr.status
}

getHeader (header) {
return this._xhr.getResponseHeader(header)
}

getBody () {
return this._xhr.responseText
export default class XHRHttpStack {
createRequest (method, url) {
return new Request(method, url)
}

getUnderlyingObject () {
return this._xhr
getName () {
return 'XHRHttpStack'
}
}
6 changes: 2 additions & 4 deletions lib/browser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,11 @@ const defaultOptions = {

class Upload extends BaseUpload {
constructor (file = null, options = {}) {
options = { ...defaultOptions, ...options }
super(file, options)
super(file, { ...defaultOptions, ...options })
}

static terminate (url, options, cb) {
options = { ...defaultOptions, ...options }
return BaseUpload.terminate(url, options, cb)
return BaseUpload.terminate(url, { ...defaultOptions, ...options }, cb)
}
}

Expand Down
6 changes: 3 additions & 3 deletions lib/browser/sources/StreamSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function concat (a, b) {
return new Blob([a, b], { type: a.type })
}
if (a.set) { // Is `a` a typed array?
var c = new a.constructor(a.length + b.length)
const c = new a.constructor(a.length + b.length)
c.set(a)
c.set(b, a.length)
return c
Expand Down Expand Up @@ -44,8 +44,8 @@ export default class StreamSource {
_readUntilEnoughDataOrDone (start, end) {
const hasEnoughData = end <= this._bufferOffset + len(this._buffer)
if (this._done || hasEnoughData) {
var value = this._getDataFromBuffer(start, end)
var done = value == null ? this._done : false
const value = this._getDataFromBuffer(start, end)
const done = value == null ? this._done : false
return Promise.resolve({ value, done })
}

Expand Down
8 changes: 4 additions & 4 deletions lib/browser/sources/isCordova.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const isCordova = () => typeof window != 'undefined' && (
typeof window.PhoneGap != 'undefined'
|| typeof window.Cordova != 'undefined'
|| typeof window.cordova != 'undefined')
const isCordova = () => typeof window !== 'undefined' && (
typeof window.PhoneGap !== 'undefined'
|| typeof window.Cordova !== 'undefined'
|| typeof window.cordova !== 'undefined')

export default isCordova
4 changes: 1 addition & 3 deletions lib/browser/urlStorage.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
/* global window, localStorage */

let hasStorage = false
try {
hasStorage = 'localStorage' in window

// Attempt to store and read entries from the local storage to detect Private
// Mode on Safari on iOS (see #49)
var key = 'tusSupport'
const key = 'tusSupport'
localStorage.setItem(key, localStorage.getItem(key))
} catch (e) {
// If we try to access localStorage inside a sandboxed iframe, a SecurityError
Expand Down
5 changes: 3 additions & 2 deletions lib/error.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
class DetailedError extends Error {
constructor (message, causingErr = null, req = null, res = null) {
super(message)
constructor (messageIn, causingErr = null, req = null, res = null) {
super(messageIn)

this.originalRequest = req
this.originalResponse = res
this.causingError = causingErr

let message = messageIn
if (causingErr != null) {
message += `, caused by ${causingErr.toString()}`
}
Expand Down
11 changes: 6 additions & 5 deletions lib/node/fingerprint.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,28 @@ export default function fingerprint (file, options) {
const blockSize = 64 * 1024 // 64kb
const content = file.slice(0, Math.min(blockSize, file.length))
const hash = createHash('md5').update(content).digest('hex')
const fingerprint = ['node-buffer', hash, file.length, options.endpoint].join('-')
return Promise.resolve(fingerprint)
const ret = ['node-buffer', hash, file.length, options.endpoint].join('-')
return Promise.resolve(ret)
}

if (file instanceof fs.ReadStream && file.path != null) {
return new Promise((resolve, reject) => {
const name = path.resolve(file.path)
fs.stat(file.path, (err, info) => {
if (err) {
return reject(err)
reject(err)
return
}

const fingerprint = [
const ret = [
'node-file',
name,
info.size,
info.mtime.getTime(),
options.endpoint,
].join('-')

resolve(fingerprint)
resolve(ret)
})
})
}
Expand Down

0 comments on commit d94abbe

Please sign in to comment.