Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@uppy/tus: migrate to TS #4899

Merged
merged 5 commits into from
Feb 5, 2024
Merged

@uppy/tus: migrate to TS #4899

merged 5 commits into from
Feb 5, 2024

Conversation

Murderlon
Copy link
Member

No description provided.

@Murderlon Murderlon requested review from mifi and aduh95 January 31, 2024 10:59
@Murderlon Murderlon self-assigned this Jan 31, 2024
Copy link
Contributor

github-actions bot commented Jan 31, 2024

Diff output files
diff --git a/packages/@uppy/tus/lib/getFingerprint.js b/packages/@uppy/tus/lib/getFingerprint.js
index fc6c75b..78133d6 100644
--- a/packages/@uppy/tus/lib/getFingerprint.js
+++ b/packages/@uppy/tus/lib/getFingerprint.js
@@ -8,12 +8,12 @@ function isReactNative() {
   return typeof navigator !== "undefined" && typeof navigator.product === "string"
     && navigator.product.toLowerCase() === "reactnative";
 }
-export default function getFingerprint(uppyFileObj) {
+export default function getFingerprint(uppyFile) {
   return (file, options) => {
     if (isCordova() || isReactNative()) {
       return tus.defaultOptions.fingerprint(file, options);
     }
-    const uppyFingerprint = ["tus", uppyFileObj.id, options.endpoint].join("-");
+    const uppyFingerprint = ["tus", uppyFile.id, options.endpoint].join("-");
     return Promise.resolve(uppyFingerprint);
   };
 }
diff --git a/packages/@uppy/tus/lib/index.js b/packages/@uppy/tus/lib/index.js
index 322ac3f..c20af75 100644
--- a/packages/@uppy/tus/lib/index.js
+++ b/packages/@uppy/tus/lib/index.js
@@ -9,7 +9,7 @@ function _classPrivateFieldLooseKey(name) {
   return "__private_" + id++ + "_" + name;
 }
 import BasePlugin from "@uppy/core/lib/BasePlugin.js";
-import EventManager from "@uppy/utils/lib/EventManager";
+import EventManager from "@uppy/core/lib/EventManager.js";
 import { filterFilesToEmitUploadStarted, filterNonFailedFiles } from "@uppy/utils/lib/fileFilters";
 import hasProperty from "@uppy/utils/lib/hasProperty";
 import isNetworkError from "@uppy/utils/lib/isNetworkError";
@@ -39,6 +39,11 @@ const tusDefaultOptions = {
   uploadLengthDeferred: false,
   uploadDataDuringCreation: false,
 };
+const defaultOptions = {
+  limit: 20,
+  retryDelays: tusDefaultOptions.retryDelays,
+  withCredentials: false,
+};
 var _retryDelayIterator = _classPrivateFieldLooseKey("retryDelayIterator");
 var _uploadLocalFile = _classPrivateFieldLooseKey("uploadLocalFile");
 var _getCompanionClientArgs = _classPrivateFieldLooseKey("getCompanionClientArgs");
@@ -47,7 +52,10 @@ var _handleUpload = _classPrivateFieldLooseKey("handleUpload");
 export default class Tus extends BasePlugin {
   constructor(uppy, _opts) {
     var _this$opts$rateLimite, _this$opts$retryDelay;
-    super(uppy, _opts);
+    super(uppy, {
+      ...defaultOptions,
+      ..._opts,
+    });
     Object.defineProperty(this, _uploadFiles, {
       value: _uploadFiles2,
     });
@@ -81,16 +89,6 @@ export default class Tus extends BasePlugin {
     });
     this.type = "uploader";
     this.id = this.opts.id || "Tus";
-    this.title = "Tus";
-    const defaultOptions = {
-      limit: 20,
-      retryDelays: tusDefaultOptions.retryDelays,
-      withCredentials: false,
-    };
-    this.opts = {
-      ...defaultOptions,
-      ..._opts,
-    };
     if ((_opts == null ? void 0 : _opts.allowedMetaFields) === undefined && "metaFields" in this.opts) {
       throw new Error("The `metaFields` option has been renamed to `allowedMetaFields`.");
     }
@@ -111,7 +109,11 @@ export default class Tus extends BasePlugin {
       ...this.uppy.getState().files,
     };
     Object.keys(files).forEach(fileID => {
-      if (files[fileID].tus && files[fileID].tus.uploadUrl) {
+      var _files$fileID;
+      if (
+        (_files$fileID = files[fileID]) != null && (_files$fileID = _files$fileID.tus) != null
+        && _files$fileID.uploadUrl
+      ) {
         const tusState = {
           ...files[fileID].tus,
         };
@@ -127,13 +129,10 @@ export default class Tus extends BasePlugin {
     });
   }
   resetUploaderReferences(fileID, opts) {
-    if (opts === void 0) {
-      opts = {};
-    }
     if (this.uploaders[fileID]) {
       const uploader = this.uploaders[fileID];
       uploader.abort();
-      if (opts.abort) {
+      if (opts != null && opts.abort) {
         uploader.abort(true);
       }
       this.uploaders[fileID] = null;
@@ -190,17 +189,22 @@ function _uploadLocalFile2(file) {
     if (typeof opts.headers === "function") {
       opts.headers = opts.headers(file);
     }
+    const {
+      onShouldRetry,
+      onBeforeRequest,
+      ...commonOpts
+    } = opts;
     const uploadOptions = {
       ...tusDefaultOptions,
-      ...opts,
+      ...commonOpts,
     };
     uploadOptions.fingerprint = getFingerprint(file);
-    uploadOptions.onBeforeRequest = req => {
+    uploadOptions.onBeforeRequest = async req => {
       const xhr = req.getUnderlyingObject();
       xhr.withCredentials = !!opts.withCredentials;
       let userProvidedPromise;
-      if (typeof opts.onBeforeRequest === "function") {
-        userProvidedPromise = opts.onBeforeRequest(req, file);
+      if (typeof onBeforeRequest === "function") {
+        userProvidedPromise = onBeforeRequest(req, file);
       }
       if (hasProperty(queuedRequest, "shouldBeRequeued")) {
         if (!queuedRequest.shouldBeRequeued) return Promise.reject();
@@ -215,14 +219,15 @@ function _uploadLocalFile2(file) {
           done();
           return () => {};
         });
-        return Promise.all([p, userProvidedPromise]);
+        await Promise.all([p, userProvidedPromise]);
+        return undefined;
       }
       return userProvidedPromise;
     };
     uploadOptions.onError = err => {
       var _queuedRequest;
       this.uppy.log(err);
-      const xhr = err.originalRequest ? err.originalRequest.getUnderlyingObject() : null;
+      const xhr = err.originalRequest != null ? err.originalRequest.getUnderlyingObject() : null;
       if (isNetworkError(xhr)) {
         err = new NetworkError(err, xhr);
       }
@@ -246,14 +251,20 @@ function _uploadLocalFile2(file) {
       });
     };
     uploadOptions.onSuccess = () => {
+      var _upload$url;
       const uploadResp = {
-        uploadURL: upload.url,
+        uploadURL: (_upload$url = upload.url) != null ? _upload$url : undefined,
+        status: 200,
+        body: {},
       };
       this.resetUploaderReferences(file.id);
       queuedRequest.done();
       this.uppy.emit("upload-success", file, uploadResp);
       if (upload.url) {
-        this.uppy.log(`Download ${upload.file.name} from ${upload.url}`);
+        const {
+          name,
+        } = upload.file;
+        this.uppy.log(`Download ${name} from ${upload.url}`);
       }
       if (typeof opts.onSuccess === "function") {
         opts.onSuccess();
@@ -278,7 +289,7 @@ function _uploadLocalFile2(file) {
           }
           this.requests.rateLimit(next.value);
         }
-      } else if (status > 400 && status < 500 && status !== 409 && status !== 423) {
+      } else if (status != null && status > 400 && status < 500 && status !== 409 && status !== 423) {
         return false;
       } else if (typeof navigator !== "undefined" && navigator.onLine === false) {
         if (!this.requests.isPaused) {
@@ -305,13 +316,9 @@ function _uploadLocalFile2(file) {
       };
       return true;
     };
-    if (opts.onShouldRetry != null) {
-      uploadOptions.onShouldRetry = function() {
-        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
-          args[_key] = arguments[_key];
-        }
-        return opts.onShouldRetry(...args, defaultOnShouldRetry);
-      };
+    if (onShouldRetry != null) {
+      uploadOptions.onShouldRetry = (error, retryAttempt) =>
+        onShouldRetry(error, retryAttempt, opts, defaultOnShouldRetry);
     } else {
       uploadOptions.onShouldRetry = defaultOnShouldRetry;
     }
@@ -323,7 +330,7 @@ function _uploadLocalFile2(file) {
     const meta = {};
     const allowedMetaFields = Array.isArray(opts.allowedMetaFields) ? opts.allowedMetaFields : Object.keys(file.meta);
     allowedMetaFields.forEach(item => {
-      meta[item] = file.meta[item];
+      meta[item] = String(file.meta[item]);
     });
     copyProp(meta, "type", "filetype");
     copyProp(meta, "name", "filename");
@@ -390,6 +397,7 @@ function _uploadLocalFile2(file) {
   });
 }
 function _getCompanionClientArgs2(file) {
+  var _file$remote;
   const opts = {
     ...this.opts,
   };
@@ -397,7 +405,7 @@ function _getCompanionClientArgs2(file) {
     Object.assign(opts, file.tus);
   }
   return {
-    ...file.remote.body,
+    ...((_file$remote = file.remote) == null ? void 0 : _file$remote.body),
     endpoint: opts.endpoint,
     uploadUrl: opts.uploadUrl,
     protocol: "tus",
@@ -410,9 +418,7 @@ async function _uploadFiles2(files) {
   const filesFiltered = filterNonFailedFiles(files);
   const filesToEmit = filterFilesToEmitUploadStarted(filesFiltered);
   this.uppy.emit("upload-start", filesToEmit);
-  await Promise.allSettled(filesFiltered.map((file, i) => {
-    const current = i + 1;
-    const total = files.length;
+  await Promise.allSettled(filesFiltered.map(file => {
     if (file.isRemote) {
       const getQueue = () => this.requests;
       const controller = new AbortController();
@@ -435,7 +441,7 @@ async function _uploadFiles2(files) {
       })();
       return uploadPromise;
     }
-    return _classPrivateFieldLooseBase(this, _uploadLocalFile)[_uploadLocalFile](file, current, total);
+    return _classPrivateFieldLooseBase(this, _uploadLocalFile)[_uploadLocalFile](file);
   }));
 }
 Tus.VERSION = packageJson.version;

packages/@uppy/tus/src/index.ts Show resolved Hide resolved
packages/@uppy/tus/src/index.ts Show resolved Hide resolved
packages/@uppy/tus/src/index.ts Show resolved Hide resolved
packages/@uppy/tus/src/index.ts Outdated Show resolved Hide resolved
packages/@uppy/tus/src/index.ts Outdated Show resolved Hide resolved
packages/@uppy/tus/src/index.ts Outdated Show resolved Hide resolved
@mifi
Copy link
Contributor

mifi commented Feb 5, 2024

created a suggestion here #4910

* implement type improvements

* fix type check
@@ -55,6 +55,7 @@ export interface TusOpts<M extends Meta, B extends Body>
retryDelays?: number[]
withCredentials?: boolean
allowedMetaFields?: string[]
rateLimitedQueue?: RateLimitedQueue
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i wonder why this wasn't needed in #4910 and when running build:ts locally 🤔

@mifi
Copy link
Contributor

mifi commented Feb 5, 2024

this is strange... github actions is still failing but i'm not getting any ts errors locally with build:ts or in vscode

even when running

yarn build:clean
yarn build:lib
yarn build:ts

@Murderlon
Copy link
Member Author

Murderlon commented Feb 5, 2024

Yes it's odd but it makes sense, we were accessing opts.rateLimitedQueue and it wasn't typed. CI successful now.

@Murderlon Murderlon merged commit 4d03bba into main Feb 5, 2024
16 checks passed
@Murderlon Murderlon deleted the tus-ts branch February 5, 2024 14:37
Murderlon added a commit that referenced this pull request Feb 14, 2024
* main:
  Image editor: make compressor work after the image editor, too (#4918)
  meta: exclude `tsconfig` files from npm bundles (#4916)
  @uppy/compressor: migrate to TS (#4907)
  Update uppy-ProviderBrowser-viewType--list.scss (#4913)
  @uppy/tus: migrate to TS (#4899)
@github-actions github-actions bot mentioned this pull request Feb 19, 2024
github-actions bot added a commit that referenced this pull request Feb 19, 2024
| Package                   | Version | Package                   | Version |
| ------------------------- | ------- | ------------------------- | ------- |
| @uppy/audio               |   1.1.5 | @uppy/remote-sources      |   1.1.1 |
| @uppy/aws-s3              |   3.6.1 | @uppy/status-bar          |   3.2.6 |
| @uppy/aws-s3-multipart    |  3.10.1 | @uppy/store-default       |   3.2.1 |
| @uppy/companion           |  4.12.1 | @uppy/store-redux         |   3.0.6 |
| @uppy/companion-client    |   3.7.1 | @uppy/svelte              |   3.1.2 |
| @uppy/compressor          |   1.1.0 | @uppy/thumbnail-generator |   3.0.7 |
| @uppy/core                |   3.9.0 | @uppy/transloadit         |   3.5.0 |
| @uppy/dashboard           |   3.7.2 | @uppy/tus                 |   3.5.1 |
| @uppy/drop-target         |   2.0.3 | @uppy/utils               |   5.7.1 |
| @uppy/form                |   3.1.0 | @uppy/vue                 |   1.1.1 |
| @uppy/golden-retriever    |   3.1.2 | @uppy/webcam              |   3.3.5 |
| @uppy/image-editor        |   2.4.1 | @uppy/xhr-upload          |   3.6.1 |
| @uppy/locales             |   3.5.1 | uppy                      |  3.22.0 |
| @uppy/provider-views      |   3.9.0 |                           |         |

-  @uppy/aws-s3-multipart,@uppy/aws-s3,@uppy/companion-client,@uppy/tus,@uppy/xhr-upload: update `uppyfile` objects before emitting events (antoine du hamel / #4928)
- @uppy/transloadit: add `clientname` option (marius / #4920)
- @uppy/thumbnail-generator: fix broken previews after cropping (evgenia karunus / #4926)
- @uppy/compressor: upgrade compressorjs (merlijn vos / #4924)
- @uppy/companion: fix companion dns and allow redirects from http->https again (mikael finstad / #4895)
- @uppy/dashboard: autoopenfileeditor - rename "edit file" to "edit image" (evgenia karunus / #4925)
- meta: resolve jsx to preact in shared tsconfig (merlijn vos / #4923)
- @uppy/image-editor: image editor: make compressor work after the image editor, too (evgenia karunus / #4918)
- meta: exclude `tsconfig` files from npm bundles (antoine du hamel / #4916)
- @uppy/compressor: migrate to ts (mikael finstad / #4907)
- @uppy/provider-views: update uppy-providerbrowser-viewtype--list.scss (aditya patadia / #4913)
- @uppy/tus: migrate to ts (merlijn vos / #4899)
- meta: bump yarn version (antoine du hamel / #4906)
- meta: validate `defaultoptions` for stricter option types (antoine du hamel / #4901)
- @uppy/dashboard: Uncouple native camera and video buttons from the `disableLocalFiles` option (jake mcallister / #4894)
- meta: put experimental ternaries in .prettierrc.js (merlijn vos / #4900)
- @uppy/xhr-upload: migrate to ts (merlijn vos / #4892)
- @uppy/drop-target: refactor to typescript (artur paikin / #4863)
- meta: fix missing line return in js2ts script (antoine du hamel)
- meta: disable `@typescript-eslint/no-empty-function` lint rule (antoine du hamel / #4891)
- @uppy/companion-client: fix tests and linter (antoine du hamel / #4890)
- @uppy/companion-client: migrate to ts (merlijn vos / #4864)
- meta: prettier 3.0.3 -> 3.2.4 (antoine du hamel / #4889)
- @uppy/image-editor: migrate to ts (merlijn vos / #4880)
- meta: fix race condition in `e2e.yml` (antoine du hamel)
- @uppy/core: add utility type to help define plugin option types (antoine du hamel / #4885)
- meta: merge `output-watcher` and `e2e` workflows (antoine du hamel / #4886)
- @uppy/status-bar: fix `statusbaroptions` type (antoine du hamel / #4883)
- @uppy/core: improve types of .use() (merlijn vos / #4882)
- @uppy/audio: fix `audiooptions` (antoine du hamel / #4884)
- meta: upgrade vite and vitest (antoine du hamel / #4881)
- meta: fix `yarn build:clean` (antoine du hamel)
- @uppy/audio: refactor to typescript (antoine du hamel / #4860)
- @uppy/status-bar: refactor to typescript (antoine du hamel / #4839)
- @uppy/core: add `plugintarget` type and mark options as optional (antoine du hamel / #4874)
- meta: improve output watcher diff (antoine du hamel / #4876)
- meta: minify the output watcher diff further (antoine du hamel)
- meta: remove comments from output watcher (mikael finstad / #4875)
- @uppy/utils: improve types for `finddomelement` (antoine du hamel / #4873)
- @uppy/code: allow plugins to type `pluginstate` (antoine du hamel / #4872)
- meta: build(deps): bump follow-redirects from 1.15.1 to 1.15.4 (dependabot[bot] / #4862)
- meta: add `output-watcher` gha to help check output diff (antoine du hamel / #4868)
- meta: generate locale pack from output file (antoine du hamel / #4867)
- meta: comment on what we want to do about close, resetprogress, clearuploadedfiles, etc in the next major (artur paikin / #4865)
- meta: fix `yarn build:clean` (antoine du hamel / #4866)
- meta: use `explicit-module-boundary-types` lint rule (antoine du hamel / #4858)
- @uppy/form: use requestsubmit (merlijn vos / #4852)
- @uppy/provider-views: add referrerpolicy to images (merlijn vos / #4853)
- @uppy/core: add `debuglogger` as export in manual types (antoine du hamel / #4831)
- meta: fix `js2ts` script (antoine du hamel / #4846)
- @uppy/xhr-upload: show remove button (merlijn vos / #4851)
- meta: upgrade `@transloadit/prettier-bytes` (antoine du hamel / #4850)
- @uppy/core: add missing requiredmetafields key in restrictions (darthf1 / #4819)
- @uppy/companion,@uppy/tus: bump `tus-js-client` version range (merlijn vos / #4848)
- meta: build(deps): bump aws/aws-sdk-php from 3.272.1 to 3.288.1 in /examples/aws-php (dependabot[bot] / #4838)
- @uppy/dashboard: fix `typeerror` when `file.remote` is nullish (antoine du hamel / #4825)
- meta: fix `js2ts` script (antoine du hamel / #4844)
- @uppy/locales: fix "save" button translation in hr_hr.ts (žan žlender / #4830)
- meta: fix linting of `.tsx` files (antoine du hamel / #4843)
- @uppy/core: fix types (antoine du hamel / #4842)
- @uppy/utils: improve `preprocess` and `postprocess` types (antoine du hamel / #4841)
- meta: fix `yarn build:clean` (mikael finstad / #4840)
- meta: dev: remove extensions from vite aliases (antoine du hamel)
- meta: fix `"e2e"` script (antoine du hamel)
- @uppy/core: refactor to ts (murderlon)
- meta: fix typescript ci (antoine du hamel)
- meta: fix clean script (mikael finstad / #4820)
- @uppy/companion-client: fix `typeerror` (antoine du hamel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants