Uppy.ts 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  1. /* eslint-disable max-classes-per-file */
  2. /* global AggregateError */
  3. import Translator from '@uppy/utils/lib/Translator'
  4. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5. // @ts-ignore untyped
  6. import ee from 'namespace-emitter'
  7. import { nanoid } from 'nanoid/non-secure'
  8. import throttle from 'lodash/throttle.js'
  9. import DefaultStore from '@uppy/store-default'
  10. import getFileType from '@uppy/utils/lib/getFileType'
  11. import getFileNameAndExtension from '@uppy/utils/lib/getFileNameAndExtension'
  12. import { getSafeFileId } from '@uppy/utils/lib/generateFileID'
  13. import type {
  14. UppyFile,
  15. Meta,
  16. Body,
  17. MinimalRequiredUppyFile,
  18. } from '@uppy/utils/lib/UppyFile'
  19. import type { CompanionFile } from '@uppy/utils/lib/CompanionFile'
  20. import type {
  21. CompanionClientProvider,
  22. CompanionClientSearchProvider,
  23. } from '@uppy/utils/lib/CompanionClientProvider'
  24. import type {
  25. FileProgressNotStarted,
  26. FileProgressStarted,
  27. } from '@uppy/utils/lib/FileProgress'
  28. import type {
  29. Locale,
  30. I18n,
  31. OptionalPluralizeLocale,
  32. } from '@uppy/utils/lib/Translator'
  33. import supportsUploadProgress from './supportsUploadProgress.ts'
  34. import getFileName from './getFileName.ts'
  35. import { justErrorsLogger, debugLogger } from './loggers.ts'
  36. import {
  37. Restricter,
  38. defaultOptions as defaultRestrictionOptions,
  39. RestrictionError,
  40. } from './Restricter.ts'
  41. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  42. // @ts-ignore We don't want TS to generate types for the package.json
  43. import packageJson from '../package.json'
  44. import locale from './locale.ts'
  45. import type BasePlugin from './BasePlugin.ts'
  46. import type { Restrictions, ValidateableFile } from './Restricter.ts'
  47. type Processor = (
  48. fileIDs: string[],
  49. uploadID: string,
  50. ) => Promise<unknown> | void
  51. type FileRemoveReason = 'user' | 'cancel-all'
  52. type LogLevel = 'info' | 'warning' | 'error' | 'success'
  53. export type UnknownPlugin<
  54. M extends Meta,
  55. B extends Body,
  56. PluginState extends Record<string, unknown> = Record<string, unknown>,
  57. > = BasePlugin<any, M, B, PluginState>
  58. export type UnknownProviderPluginState = {
  59. authenticated: boolean | undefined
  60. breadcrumbs: {
  61. requestPath?: string
  62. name?: string
  63. id?: string
  64. }[]
  65. didFirstRender: boolean
  66. currentSelection: CompanionFile[]
  67. filterInput: string
  68. loading: boolean | string
  69. folders: CompanionFile[]
  70. files: CompanionFile[]
  71. isSearchVisible: boolean
  72. }
  73. /*
  74. * UnknownProviderPlugin can be any Companion plugin (such as Google Drive).
  75. * As the plugins are passed around throughout Uppy we need a generic type for this.
  76. * It may seems like duplication, but this type safe. Changing the type of `storage`
  77. * will error in the `Provider` class of @uppy/companion-client and vice versa.
  78. *
  79. * Note that this is the *plugin* class, not a version of the `Provider` class.
  80. * `Provider` does operate on Companion plugins with `uppy.getPlugin()`.
  81. */
  82. export type UnknownProviderPlugin<
  83. M extends Meta,
  84. B extends Body,
  85. > = UnknownPlugin<M, B, UnknownProviderPluginState> & {
  86. onFirstRender: () => void
  87. title: string
  88. files: UppyFile<M, B>[]
  89. icon: () => JSX.Element
  90. provider: CompanionClientProvider
  91. storage: {
  92. getItem: (key: string) => Promise<string | null>
  93. setItem: (key: string, value: string) => Promise<void>
  94. removeItem: (key: string) => Promise<void>
  95. }
  96. }
  97. /*
  98. * UnknownSearchProviderPlugin can be any search Companion plugin (such as Unsplash).
  99. * As the plugins are passed around throughout Uppy we need a generic type for this.
  100. * It may seems like duplication, but this type safe. Changing the type of `title`
  101. * will error in the `SearchProvider` class of @uppy/companion-client and vice versa.
  102. *
  103. * Note that this is the *plugin* class, not a version of the `SearchProvider` class.
  104. * `SearchProvider` does operate on Companion plugins with `uppy.getPlugin()`.
  105. */
  106. export type UnknownSearchProviderPluginState = {
  107. isInputMode?: boolean
  108. searchTerm?: string | null
  109. } & Pick<
  110. UnknownProviderPluginState,
  111. | 'loading'
  112. | 'files'
  113. | 'folders'
  114. | 'currentSelection'
  115. | 'filterInput'
  116. | 'didFirstRender'
  117. >
  118. export type UnknownSearchProviderPlugin<
  119. M extends Meta,
  120. B extends Body,
  121. > = UnknownPlugin<M, B, UnknownSearchProviderPluginState> & {
  122. onFirstRender: () => void
  123. title: string
  124. icon: () => JSX.Element
  125. provider: CompanionClientSearchProvider
  126. }
  127. export interface UploadResult<M extends Meta, B extends Body> {
  128. successful?: UppyFile<M, B>[]
  129. failed?: UppyFile<M, B>[]
  130. uploadID?: string
  131. [key: string]: unknown
  132. }
  133. interface CurrentUpload<M extends Meta, B extends Body> {
  134. fileIDs: string[]
  135. step: number
  136. result: UploadResult<M, B>
  137. }
  138. // TODO: can we use namespaces in other plugins to populate this?
  139. // eslint-disable-next-line @typescript-eslint/no-empty-interface
  140. interface Plugins extends Record<string, Record<string, unknown> | undefined> {}
  141. export interface State<M extends Meta, B extends Body>
  142. extends Record<string, unknown> {
  143. meta: M
  144. capabilities: {
  145. uploadProgress: boolean
  146. individualCancellation: boolean
  147. resumableUploads: boolean
  148. isMobileDevice?: boolean
  149. darkMode?: boolean
  150. }
  151. currentUploads: Record<string, CurrentUpload<M, B>>
  152. allowNewUpload: boolean
  153. recoveredState: null | Required<Pick<State<M, B>, 'files' | 'currentUploads'>>
  154. error: string | null
  155. files: {
  156. [key: string]: UppyFile<M, B>
  157. }
  158. info: Array<{
  159. isHidden?: boolean
  160. type: LogLevel
  161. message: string
  162. details?: string | Record<string, string> | null
  163. }>
  164. plugins: Plugins
  165. totalProgress: number
  166. companion?: Record<string, string>
  167. }
  168. export interface UppyOptions<M extends Meta, B extends Body> {
  169. id?: string
  170. autoProceed?: boolean
  171. /**
  172. * @deprecated Use allowMultipleUploadBatches
  173. */
  174. allowMultipleUploads?: boolean
  175. allowMultipleUploadBatches?: boolean
  176. logger?: typeof debugLogger
  177. debug?: boolean
  178. restrictions: Restrictions
  179. meta?: M
  180. onBeforeFileAdded?: (
  181. currentFile: UppyFile<M, B>,
  182. files: { [key: string]: UppyFile<M, B> },
  183. ) => UppyFile<M, B> | boolean | undefined
  184. onBeforeUpload?: (files: {
  185. [key: string]: UppyFile<M, B>
  186. }) => { [key: string]: UppyFile<M, B> } | boolean
  187. locale?: Locale
  188. store?: DefaultStore<State<M, B>>
  189. infoTimeout?: number
  190. }
  191. export interface UppyOptionsWithOptionalRestrictions<
  192. M extends Meta,
  193. B extends Body,
  194. > extends Omit<UppyOptions<M, B>, 'restrictions'> {
  195. restrictions?: Partial<Restrictions>
  196. }
  197. // The user facing type for UppyOptions used in uppy.setOptions()
  198. type MinimalRequiredOptions<M extends Meta, B extends Body> = Partial<
  199. Omit<UppyOptions<M, B>, 'locale' | 'meta' | 'restrictions'> & {
  200. locale: OptionalPluralizeLocale
  201. meta: Partial<M>
  202. restrictions: Partial<Restrictions>
  203. }
  204. >
  205. export type NonNullableUppyOptions<M extends Meta, B extends Body> = Required<
  206. UppyOptions<M, B>
  207. >
  208. type GenericEventCallback = () => void
  209. type FileAddedCallback<M extends Meta, B extends Body> = (
  210. file: UppyFile<M, B>,
  211. ) => void
  212. type FilesAddedCallback<M extends Meta, B extends Body> = (
  213. files: UppyFile<M, B>[],
  214. ) => void
  215. type FileRemovedCallback<M extends Meta, B extends Body> = (
  216. file: UppyFile<M, B>,
  217. reason?: FileRemoveReason,
  218. ) => void
  219. type UploadCallback = (data: { id: string; fileIDs: string[] }) => void
  220. type ProgressCallback = (progress: number) => void
  221. type PreProcessProgressCallback<M extends Meta, B extends Body> = (
  222. file: UppyFile<M, B> | undefined,
  223. progress: NonNullable<FileProgressStarted['preprocess']>,
  224. ) => void
  225. type PostProcessProgressCallback<M extends Meta, B extends Body> = (
  226. file: UppyFile<M, B> | undefined,
  227. progress: NonNullable<FileProgressStarted['postprocess']>,
  228. ) => void
  229. type ProcessCompleteCallback<M extends Meta, B extends Body> = (
  230. file: UppyFile<M, B> | undefined,
  231. progress?: NonNullable<FileProgressStarted['preprocess']>,
  232. ) => void
  233. type UploadPauseCallback<M extends Meta, B extends Body> = (
  234. fileID: UppyFile<M, B>['id'] | undefined,
  235. isPaused: boolean,
  236. ) => void
  237. type UploadStartCallback<M extends Meta, B extends Body> = (
  238. files: UppyFile<M, B>[],
  239. ) => void
  240. type UploadStartedCallback<M extends Meta, B extends Body> = (
  241. file: UppyFile<M, B>,
  242. ) => void
  243. type UploadProgressCallback<M extends Meta, B extends Body> = (
  244. file: UppyFile<M, B> | undefined,
  245. progress: FileProgressStarted,
  246. ) => void
  247. type UploadSuccessCallback<M extends Meta, B extends Body> = (
  248. file: UppyFile<M, B> | undefined,
  249. response: NonNullable<UppyFile<M, B>['response']>,
  250. ) => void
  251. type UploadCompleteCallback<M extends Meta, B extends Body> = (
  252. result: UploadResult<M, B>,
  253. ) => void
  254. type ErrorCallback<M extends Meta, B extends Body> = (
  255. error: { name: string; message: string; details?: string },
  256. file?: UppyFile<M, B>,
  257. response?: UppyFile<M, B>['response'],
  258. ) => void
  259. type UploadErrorCallback<M extends Meta, B extends Body> = (
  260. file: UppyFile<M, B> | undefined,
  261. error: { name: string; message: string; details?: string },
  262. response?:
  263. | Omit<NonNullable<UppyFile<M, B>['response']>, 'uploadURL'>
  264. | undefined,
  265. ) => void
  266. type UploadStalledCallback<M extends Meta, B extends Body> = (
  267. error: { message: string; details?: string },
  268. files: UppyFile<M, B>[],
  269. ) => void
  270. type UploadRetryCallback = (fileID: string) => void
  271. type RetryAllCallback = (fileIDs: string[]) => void
  272. type RestrictionFailedCallback<M extends Meta, B extends Body> = (
  273. file: UppyFile<M, B> | undefined,
  274. error: Error,
  275. ) => void
  276. type StateUpdateCallback<M extends Meta, B extends Body> = (
  277. prevState: State<M, B>,
  278. nextState: State<M, B>,
  279. patch?: Partial<State<M, B>>,
  280. ) => void
  281. type CancelAllCallback = (reason: { reason?: FileRemoveReason }) => void
  282. type PluginCallback = (plugin: UnknownPlugin<any, any>) => void
  283. export interface _UppyEventMap<M extends Meta, B extends Body> {
  284. 'back-online': GenericEventCallback
  285. 'cancel-all': CancelAllCallback
  286. complete: UploadCompleteCallback<M, B>
  287. error: ErrorCallback<M, B>
  288. 'file-added': FileAddedCallback<M, B>
  289. 'file-removed': FileRemovedCallback<M, B>
  290. 'files-added': FilesAddedCallback<M, B>
  291. 'info-hidden': GenericEventCallback
  292. 'info-visible': GenericEventCallback
  293. 'is-offline': GenericEventCallback
  294. 'is-online': GenericEventCallback
  295. 'pause-all': GenericEventCallback
  296. 'plugin-added': PluginCallback
  297. 'plugin-remove': PluginCallback
  298. 'postprocess-complete': ProcessCompleteCallback<M, B>
  299. 'postprocess-progress': PostProcessProgressCallback<M, B>
  300. 'preprocess-complete': ProcessCompleteCallback<M, B>
  301. 'preprocess-progress': PreProcessProgressCallback<M, B>
  302. progress: ProgressCallback
  303. 'reset-progress': GenericEventCallback
  304. restored: (pluginData: any) => void
  305. 'restore-confirmed': GenericEventCallback
  306. 'restore-canceled': GenericEventCallback
  307. 'restriction-failed': RestrictionFailedCallback<M, B>
  308. 'resume-all': GenericEventCallback
  309. 'retry-all': RetryAllCallback
  310. 'state-update': StateUpdateCallback<M, B>
  311. upload: UploadCallback
  312. 'upload-error': UploadErrorCallback<M, B>
  313. 'upload-pause': UploadPauseCallback<M, B>
  314. 'upload-progress': UploadProgressCallback<M, B>
  315. 'upload-retry': UploadRetryCallback
  316. 'upload-stalled': UploadStalledCallback<M, B>
  317. 'upload-success': UploadSuccessCallback<M, B>
  318. }
  319. /** @deprecated */
  320. export interface DeprecatedUppyEventMap<M extends Meta, B extends Body> {
  321. 'upload-start': UploadStartCallback<M, B>
  322. 'upload-started': UploadStartedCallback<M, B>
  323. }
  324. export interface UppyEventMap<M extends Meta, B extends Body>
  325. extends _UppyEventMap<M, B>,
  326. DeprecatedUppyEventMap<M, B> {}
  327. const defaultUploadState = {
  328. totalProgress: 0,
  329. allowNewUpload: true,
  330. error: null,
  331. recoveredState: null,
  332. }
  333. /**
  334. * Uppy Core module.
  335. * Manages plugins, state updates, acts as an event bus,
  336. * adds/removes files and metadata.
  337. */
  338. export class Uppy<M extends Meta, B extends Body> {
  339. static VERSION = packageJson.version
  340. #plugins: Record<string, UnknownPlugin<M, B>[]> = Object.create(null)
  341. #restricter
  342. #storeUnsubscribe
  343. #emitter = ee()
  344. #preProcessors: Set<Processor> = new Set()
  345. #uploaders: Set<Processor> = new Set()
  346. #postProcessors: Set<Processor> = new Set()
  347. defaultLocale: Locale
  348. locale: Locale
  349. // The user optionally passes in options, but we set defaults for missing options.
  350. // We consider all options present after the contructor has run.
  351. opts: NonNullableUppyOptions<M, B>
  352. store: NonNullableUppyOptions<M, B>['store']
  353. i18n: I18n
  354. i18nArray: Translator['translateArray']
  355. scheduledAutoProceed: ReturnType<typeof setTimeout> | null = null
  356. wasOffline = false
  357. /**
  358. * Instantiate Uppy
  359. */
  360. constructor(opts?: UppyOptionsWithOptionalRestrictions<M, B>) {
  361. this.defaultLocale = locale as any as Locale
  362. const defaultOptions: UppyOptions<Record<string, unknown>, B> = {
  363. id: 'uppy',
  364. autoProceed: false,
  365. allowMultipleUploadBatches: true,
  366. debug: false,
  367. restrictions: defaultRestrictionOptions,
  368. meta: {},
  369. onBeforeFileAdded: (file, files) => !Object.hasOwn(files, file.id),
  370. onBeforeUpload: (files) => files,
  371. store: new DefaultStore(),
  372. logger: justErrorsLogger,
  373. infoTimeout: 5000,
  374. }
  375. const merged = { ...defaultOptions, ...opts } as Omit<
  376. NonNullableUppyOptions<M, B>,
  377. 'restrictions'
  378. >
  379. // Merge default options with the ones set by user,
  380. // making sure to merge restrictions too
  381. this.opts = {
  382. ...merged,
  383. restrictions: {
  384. ...(defaultOptions.restrictions as Restrictions),
  385. ...(opts && opts.restrictions),
  386. },
  387. }
  388. // Support debug: true for backwards-compatability, unless logger is set in opts
  389. // opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
  390. if (opts && opts.logger && opts.debug) {
  391. this.log(
  392. 'You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.',
  393. 'warning',
  394. )
  395. } else if (opts && opts.debug) {
  396. this.opts.logger = debugLogger
  397. }
  398. this.log(`Using Core v${Uppy.VERSION}`)
  399. this.i18nInit()
  400. this.store = this.opts.store
  401. this.setState({
  402. ...defaultUploadState,
  403. plugins: {},
  404. files: {},
  405. currentUploads: {},
  406. capabilities: {
  407. uploadProgress: supportsUploadProgress(),
  408. individualCancellation: true,
  409. resumableUploads: false,
  410. },
  411. meta: { ...this.opts.meta },
  412. info: [],
  413. })
  414. this.#restricter = new Restricter<M, B>(() => this.opts, this.i18n)
  415. this.#storeUnsubscribe = this.store.subscribe(
  416. (prevState, nextState, patch) => {
  417. this.emit('state-update', prevState, nextState, patch)
  418. this.updateAll(nextState)
  419. },
  420. )
  421. // Exposing uppy object on window for debugging and testing
  422. if (this.opts.debug && typeof window !== 'undefined') {
  423. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  424. // @ts-ignore Mutating the global object for debug purposes
  425. window[this.opts.id] = this
  426. }
  427. this.#addListeners()
  428. }
  429. emit<T extends keyof UppyEventMap<M, B>>(
  430. event: T,
  431. ...args: Parameters<UppyEventMap<M, B>[T]>
  432. ): void {
  433. this.#emitter.emit(event, ...args)
  434. }
  435. on<K extends keyof UppyEventMap<M, B>>(
  436. event: K,
  437. callback: UppyEventMap<M, B>[K],
  438. ): this {
  439. this.#emitter.on(event, callback)
  440. return this
  441. }
  442. once<K extends keyof UppyEventMap<M, B>>(
  443. event: K,
  444. callback: UppyEventMap<M, B>[K],
  445. ): this {
  446. this.#emitter.once(event, callback)
  447. return this
  448. }
  449. off<K extends keyof UppyEventMap<M, B>>(
  450. event: K,
  451. callback: UppyEventMap<M, B>[K],
  452. ): this {
  453. this.#emitter.off(event, callback)
  454. return this
  455. }
  456. /**
  457. * Iterate on all plugins and run `update` on them.
  458. * Called each time state changes.
  459. *
  460. */
  461. updateAll(state: Partial<State<M, B>>): void {
  462. this.iteratePlugins((plugin: UnknownPlugin<M, B>) => {
  463. plugin.update(state)
  464. })
  465. }
  466. /**
  467. * Updates state with a patch
  468. */
  469. setState(patch?: Partial<State<M, B>>): void {
  470. this.store.setState(patch)
  471. }
  472. /**
  473. * Returns current state.
  474. */
  475. getState(): State<M, B> {
  476. return this.store.getState()
  477. }
  478. patchFilesState(filesWithNewState: {
  479. [id: string]: Partial<UppyFile<M, B>>
  480. }): void {
  481. const existingFilesState = this.getState().files
  482. this.setState({
  483. files: {
  484. ...existingFilesState,
  485. ...Object.fromEntries(
  486. Object.entries(filesWithNewState).map(([fileID, newFileState]) => [
  487. fileID,
  488. {
  489. ...existingFilesState[fileID],
  490. ...newFileState,
  491. },
  492. ]),
  493. ),
  494. },
  495. })
  496. }
  497. /**
  498. * Shorthand to set state for a specific file.
  499. */
  500. setFileState(fileID: string, state: Partial<UppyFile<M, B>>): void {
  501. if (!this.getState().files[fileID]) {
  502. throw new Error(
  503. `Can’t set state for ${fileID} (the file could have been removed)`,
  504. )
  505. }
  506. this.patchFilesState({ [fileID]: state })
  507. }
  508. i18nInit(): void {
  509. const onMissingKey = (key: string): void =>
  510. this.log(`Missing i18n string: ${key}`, 'error')
  511. const translator = new Translator([this.defaultLocale, this.opts.locale], {
  512. onMissingKey,
  513. })
  514. this.i18n = translator.translate.bind(translator)
  515. this.i18nArray = translator.translateArray.bind(translator)
  516. this.locale = translator.locale
  517. }
  518. setOptions(newOpts: MinimalRequiredOptions<M, B>): void {
  519. this.opts = {
  520. ...this.opts,
  521. ...(newOpts as UppyOptions<M, B>),
  522. restrictions: {
  523. ...this.opts.restrictions,
  524. ...(newOpts?.restrictions as Restrictions),
  525. },
  526. }
  527. if (newOpts.meta) {
  528. this.setMeta(newOpts.meta)
  529. }
  530. this.i18nInit()
  531. if (newOpts.locale) {
  532. this.iteratePlugins((plugin) => {
  533. plugin.setOptions(newOpts)
  534. })
  535. }
  536. // Note: this is not the preact `setState`, it's an internal function that has the same name.
  537. this.setState(undefined) // so that UI re-renders with new options
  538. }
  539. // todo next major: remove
  540. resetProgress(): void {
  541. const defaultProgress: Omit<FileProgressNotStarted, 'bytesTotal'> = {
  542. percentage: 0,
  543. bytesUploaded: 0,
  544. uploadComplete: false,
  545. uploadStarted: null,
  546. }
  547. const files = { ...this.getState().files }
  548. const updatedFiles: State<M, B>['files'] = {}
  549. Object.keys(files).forEach((fileID) => {
  550. updatedFiles[fileID] = {
  551. ...files[fileID],
  552. progress: {
  553. ...files[fileID].progress,
  554. ...defaultProgress,
  555. },
  556. }
  557. })
  558. this.setState({ files: updatedFiles, ...defaultUploadState })
  559. this.emit('reset-progress')
  560. }
  561. // @todo next major: rename to `clear()`, make it also cancel ongoing uploads
  562. // or throw and say you need to cancel manually
  563. clearUploadedFiles(): void {
  564. this.setState({ ...defaultUploadState, files: {} })
  565. }
  566. addPreProcessor(fn: Processor): void {
  567. this.#preProcessors.add(fn)
  568. }
  569. removePreProcessor(fn: Processor): boolean {
  570. return this.#preProcessors.delete(fn)
  571. }
  572. addPostProcessor(fn: Processor): void {
  573. this.#postProcessors.add(fn)
  574. }
  575. removePostProcessor(fn: Processor): boolean {
  576. return this.#postProcessors.delete(fn)
  577. }
  578. addUploader(fn: Processor): void {
  579. this.#uploaders.add(fn)
  580. }
  581. removeUploader(fn: Processor): boolean {
  582. return this.#uploaders.delete(fn)
  583. }
  584. setMeta(data: Partial<M>): void {
  585. const updatedMeta = { ...this.getState().meta, ...data }
  586. const updatedFiles = { ...this.getState().files }
  587. Object.keys(updatedFiles).forEach((fileID) => {
  588. updatedFiles[fileID] = {
  589. ...updatedFiles[fileID],
  590. meta: { ...updatedFiles[fileID].meta, ...data },
  591. }
  592. })
  593. this.log('Adding metadata:')
  594. this.log(data)
  595. this.setState({
  596. meta: updatedMeta,
  597. files: updatedFiles,
  598. })
  599. }
  600. setFileMeta(fileID: string, data: State<M, B>['meta']): void {
  601. const updatedFiles = { ...this.getState().files }
  602. if (!updatedFiles[fileID]) {
  603. this.log(
  604. 'Was trying to set metadata for a file that has been removed: ',
  605. fileID,
  606. )
  607. return
  608. }
  609. const newMeta = { ...updatedFiles[fileID].meta, ...data }
  610. updatedFiles[fileID] = { ...updatedFiles[fileID], meta: newMeta }
  611. this.setState({ files: updatedFiles })
  612. }
  613. /**
  614. * Get a file object.
  615. */
  616. getFile(fileID: string): UppyFile<M, B> {
  617. return this.getState().files[fileID]
  618. }
  619. /**
  620. * Get all files in an array.
  621. */
  622. getFiles(): UppyFile<M, B>[] {
  623. const { files } = this.getState()
  624. return Object.values(files)
  625. }
  626. getFilesByIds(ids: string[]): UppyFile<M, B>[] {
  627. return ids.map((id) => this.getFile(id))
  628. }
  629. // TODO: remove or refactor this method. It's very inefficient
  630. getObjectOfFilesPerState(): {
  631. newFiles: UppyFile<M, B>[]
  632. startedFiles: UppyFile<M, B>[]
  633. uploadStartedFiles: UppyFile<M, B>[]
  634. pausedFiles: UppyFile<M, B>[]
  635. completeFiles: UppyFile<M, B>[]
  636. erroredFiles: UppyFile<M, B>[]
  637. inProgressFiles: UppyFile<M, B>[]
  638. inProgressNotPausedFiles: UppyFile<M, B>[]
  639. processingFiles: UppyFile<M, B>[]
  640. isUploadStarted: boolean
  641. isAllComplete: boolean
  642. isAllErrored: boolean
  643. isAllPaused: boolean
  644. isUploadInProgress: boolean
  645. isSomeGhost: boolean
  646. } {
  647. const { files: filesObject, totalProgress, error } = this.getState()
  648. const files = Object.values(filesObject)
  649. const inProgressFiles = files.filter(
  650. ({ progress }) => !progress.uploadComplete && progress.uploadStarted,
  651. )
  652. const newFiles = files.filter((file) => !file.progress.uploadStarted)
  653. const startedFiles = files.filter(
  654. (file) =>
  655. file.progress.uploadStarted ||
  656. file.progress.preprocess ||
  657. file.progress.postprocess,
  658. )
  659. const uploadStartedFiles = files.filter(
  660. (file) => file.progress.uploadStarted,
  661. )
  662. const pausedFiles = files.filter((file) => file.isPaused)
  663. const completeFiles = files.filter((file) => file.progress.uploadComplete)
  664. const erroredFiles = files.filter((file) => file.error)
  665. const inProgressNotPausedFiles = inProgressFiles.filter(
  666. (file) => !file.isPaused,
  667. )
  668. const processingFiles = files.filter(
  669. (file) => file.progress.preprocess || file.progress.postprocess,
  670. )
  671. return {
  672. newFiles,
  673. startedFiles,
  674. uploadStartedFiles,
  675. pausedFiles,
  676. completeFiles,
  677. erroredFiles,
  678. inProgressFiles,
  679. inProgressNotPausedFiles,
  680. processingFiles,
  681. isUploadStarted: uploadStartedFiles.length > 0,
  682. isAllComplete:
  683. totalProgress === 100 &&
  684. completeFiles.length === files.length &&
  685. processingFiles.length === 0,
  686. isAllErrored: !!error && erroredFiles.length === files.length,
  687. isAllPaused:
  688. inProgressFiles.length !== 0 &&
  689. pausedFiles.length === inProgressFiles.length,
  690. isUploadInProgress: inProgressFiles.length > 0,
  691. isSomeGhost: files.some((file) => file.isGhost),
  692. }
  693. }
  694. #informAndEmit(
  695. errors: {
  696. name: string
  697. message: string
  698. isUserFacing?: boolean
  699. details?: string
  700. isRestriction?: boolean
  701. file?: UppyFile<M, B>
  702. }[],
  703. ): void {
  704. for (const error of errors) {
  705. if (error.isRestriction) {
  706. this.emit(
  707. 'restriction-failed',
  708. error.file,
  709. error as RestrictionError<M, B>,
  710. )
  711. } else {
  712. this.emit('error', error, error.file)
  713. }
  714. this.log(error, 'warning')
  715. }
  716. const userFacingErrors = errors.filter((error) => error.isUserFacing)
  717. // don't flood the user: only show the first 4 toasts
  718. const maxNumToShow = 4
  719. const firstErrors = userFacingErrors.slice(0, maxNumToShow)
  720. const additionalErrors = userFacingErrors.slice(maxNumToShow)
  721. firstErrors.forEach(({ message, details = '' }) => {
  722. this.info({ message, details }, 'error', this.opts.infoTimeout)
  723. })
  724. if (additionalErrors.length > 0) {
  725. this.info({
  726. message: this.i18n('additionalRestrictionsFailed', {
  727. count: additionalErrors.length,
  728. }),
  729. })
  730. }
  731. }
  732. validateRestrictions(
  733. file: ValidateableFile<M, B>,
  734. files: ValidateableFile<M, B>[] = this.getFiles(),
  735. ): RestrictionError<M, B> | null {
  736. try {
  737. this.#restricter.validate(files, [file])
  738. } catch (err) {
  739. return err
  740. }
  741. return null
  742. }
  743. #checkRequiredMetaFieldsOnFile(file: UppyFile<M, B>): boolean {
  744. const { missingFields, error } =
  745. this.#restricter.getMissingRequiredMetaFields(file)
  746. if (missingFields.length > 0) {
  747. this.setFileState(file.id, { missingRequiredMetaFields: missingFields })
  748. this.log(error.message)
  749. this.emit('restriction-failed', file, error)
  750. return false
  751. }
  752. return true
  753. }
  754. #checkRequiredMetaFields(files: State<M, B>['files']): boolean {
  755. let success = true
  756. for (const file of Object.values(files)) {
  757. if (!this.#checkRequiredMetaFieldsOnFile(file)) {
  758. success = false
  759. }
  760. }
  761. return success
  762. }
  763. #assertNewUploadAllowed(file?: UppyFile<M, B>): void {
  764. const { allowNewUpload } = this.getState()
  765. if (allowNewUpload === false) {
  766. const error = new RestrictionError<M, B>(
  767. this.i18n('noMoreFilesAllowed'),
  768. {
  769. file,
  770. },
  771. )
  772. this.#informAndEmit([error])
  773. throw error
  774. }
  775. }
  776. checkIfFileAlreadyExists(fileID: string): boolean {
  777. const { files } = this.getState()
  778. if (files[fileID] && !files[fileID].isGhost) {
  779. return true
  780. }
  781. return false
  782. }
  783. /**
  784. * Create a file state object based on user-provided `addFile()` options.
  785. */
  786. #transformFile(fileDescriptorOrFile: File | UppyFile<M, B>): UppyFile<M, B> {
  787. // Uppy expects files in { name, type, size, data } format.
  788. // If the actual File object is passed from input[type=file] or drag-drop,
  789. // we normalize it to match Uppy file object
  790. const file = (
  791. fileDescriptorOrFile instanceof File ?
  792. {
  793. name: fileDescriptorOrFile.name,
  794. type: fileDescriptorOrFile.type,
  795. size: fileDescriptorOrFile.size,
  796. data: fileDescriptorOrFile,
  797. }
  798. : fileDescriptorOrFile) as UppyFile<M, B>
  799. const fileType = getFileType(file)
  800. const fileName = getFileName(fileType, file)
  801. const fileExtension = getFileNameAndExtension(fileName).extension
  802. const id = getSafeFileId(file)
  803. const meta = file.meta || {}
  804. meta.name = fileName
  805. meta.type = fileType
  806. // `null` means the size is unknown.
  807. const size = Number.isFinite(file.data.size) ? file.data.size : null
  808. return {
  809. source: file.source || '',
  810. id,
  811. name: fileName,
  812. extension: fileExtension || '',
  813. meta: {
  814. ...this.getState().meta,
  815. ...meta,
  816. },
  817. type: fileType,
  818. data: file.data,
  819. progress: {
  820. percentage: 0,
  821. bytesUploaded: 0,
  822. bytesTotal: size,
  823. uploadComplete: false,
  824. uploadStarted: null,
  825. } satisfies FileProgressNotStarted,
  826. size,
  827. isGhost: false,
  828. isRemote: file.isRemote || false,
  829. // TODO: this should not be a string
  830. // @ts-expect-error wrong
  831. remote: file.remote || '',
  832. preview: file.preview,
  833. }
  834. }
  835. // Schedule an upload if `autoProceed` is enabled.
  836. #startIfAutoProceed(): void {
  837. if (this.opts.autoProceed && !this.scheduledAutoProceed) {
  838. this.scheduledAutoProceed = setTimeout(() => {
  839. this.scheduledAutoProceed = null
  840. this.upload().catch((err) => {
  841. if (!err.isRestriction) {
  842. this.log(err.stack || err.message || err)
  843. }
  844. })
  845. }, 4)
  846. }
  847. }
  848. #checkAndUpdateFileState(filesToAdd: UppyFile<M, B>[]): {
  849. nextFilesState: State<M, B>['files']
  850. validFilesToAdd: UppyFile<M, B>[]
  851. errors: RestrictionError<M, B>[]
  852. } {
  853. const { files: existingFiles } = this.getState()
  854. // create a copy of the files object only once
  855. const nextFilesState = { ...existingFiles }
  856. const validFilesToAdd: UppyFile<M, B>[] = []
  857. const errors: RestrictionError<M, B>[] = []
  858. for (const fileToAdd of filesToAdd) {
  859. try {
  860. let newFile = this.#transformFile(fileToAdd)
  861. // If a file has been recovered (Golden Retriever), but we were unable to recover its data (probably too large),
  862. // users are asked to re-select these half-recovered files and then this method will be called again.
  863. // In order to keep the progress, meta and everything else, we keep the existing file,
  864. // but we replace `data`, and we remove `isGhost`, because the file is no longer a ghost now
  865. const isGhost = existingFiles[newFile.id]?.isGhost
  866. if (isGhost) {
  867. const existingFileState = existingFiles[newFile.id]
  868. newFile = {
  869. ...existingFileState,
  870. isGhost: false,
  871. data: fileToAdd.data,
  872. }
  873. this.log(
  874. `Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`,
  875. )
  876. }
  877. const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(
  878. newFile,
  879. nextFilesState,
  880. )
  881. if (
  882. !onBeforeFileAddedResult &&
  883. this.checkIfFileAlreadyExists(newFile.id)
  884. ) {
  885. throw new RestrictionError(
  886. this.i18n('noDuplicates', { fileName: newFile.name }),
  887. { file: fileToAdd },
  888. )
  889. }
  890. // Pass through reselected files from Golden Retriever
  891. if (onBeforeFileAddedResult === false && !isGhost) {
  892. // Don’t show UI info for this error, as it should be done by the developer
  893. throw new RestrictionError(
  894. 'Cannot add the file because onBeforeFileAdded returned false.',
  895. { isUserFacing: false, file: fileToAdd },
  896. )
  897. } else if (
  898. typeof onBeforeFileAddedResult === 'object' &&
  899. onBeforeFileAddedResult !== null
  900. ) {
  901. newFile = onBeforeFileAddedResult
  902. }
  903. this.#restricter.validateSingleFile(newFile)
  904. // need to add it to the new local state immediately, so we can use the state to validate the next files too
  905. nextFilesState[newFile.id] = newFile
  906. validFilesToAdd.push(newFile)
  907. } catch (err) {
  908. errors.push(err)
  909. }
  910. }
  911. try {
  912. // need to run this separately because it's much more slow, so if we run it inside the for-loop it will be very slow
  913. // when many files are added
  914. this.#restricter.validateAggregateRestrictions(
  915. Object.values(existingFiles),
  916. validFilesToAdd,
  917. )
  918. } catch (err) {
  919. errors.push(err)
  920. // If we have any aggregate error, don't allow adding this batch
  921. return {
  922. nextFilesState: existingFiles,
  923. validFilesToAdd: [],
  924. errors,
  925. }
  926. }
  927. return {
  928. nextFilesState,
  929. validFilesToAdd,
  930. errors,
  931. }
  932. }
  933. /**
  934. * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
  935. * try to guess file type in a clever way, check file against restrictions,
  936. * and start an upload if `autoProceed === true`.
  937. */
  938. addFile(file: File | MinimalRequiredUppyFile<M, B>): UppyFile<M, B>['id'] {
  939. this.#assertNewUploadAllowed(file as UppyFile<M, B>)
  940. const { nextFilesState, validFilesToAdd, errors } =
  941. this.#checkAndUpdateFileState([file as UppyFile<M, B>])
  942. const restrictionErrors = errors.filter((error) => error.isRestriction)
  943. this.#informAndEmit(restrictionErrors)
  944. if (errors.length > 0) throw errors[0]
  945. this.setState({ files: nextFilesState })
  946. const [firstValidFileToAdd] = validFilesToAdd
  947. this.emit('file-added', firstValidFileToAdd)
  948. this.emit('files-added', validFilesToAdd)
  949. this.log(
  950. `Added file: ${firstValidFileToAdd.name}, ${firstValidFileToAdd.id}, mime type: ${firstValidFileToAdd.type}`,
  951. )
  952. this.#startIfAutoProceed()
  953. return firstValidFileToAdd.id
  954. }
  955. /**
  956. * Add multiple files to `state.files`. See the `addFile()` documentation.
  957. *
  958. * If an error occurs while adding a file, it is logged and the user is notified.
  959. * This is good for UI plugins, but not for programmatic use.
  960. * Programmatic users should usually still use `addFile()` on individual files.
  961. */
  962. addFiles(fileDescriptors: MinimalRequiredUppyFile<M, B>[]): void {
  963. this.#assertNewUploadAllowed()
  964. const { nextFilesState, validFilesToAdd, errors } =
  965. this.#checkAndUpdateFileState(fileDescriptors as UppyFile<M, B>[])
  966. const restrictionErrors = errors.filter((error) => error.isRestriction)
  967. this.#informAndEmit(restrictionErrors)
  968. const nonRestrictionErrors = errors.filter((error) => !error.isRestriction)
  969. if (nonRestrictionErrors.length > 0) {
  970. let message = 'Multiple errors occurred while adding files:\n'
  971. nonRestrictionErrors.forEach((subError) => {
  972. message += `\n * ${subError.message}`
  973. })
  974. this.info(
  975. {
  976. message: this.i18n('addBulkFilesFailed', {
  977. smart_count: nonRestrictionErrors.length,
  978. }),
  979. details: message,
  980. },
  981. 'error',
  982. this.opts.infoTimeout,
  983. )
  984. if (typeof AggregateError === 'function') {
  985. throw new AggregateError(nonRestrictionErrors, message)
  986. } else {
  987. const err = new Error(message)
  988. // @ts-expect-error fallback when AggregateError is not available
  989. err.errors = nonRestrictionErrors
  990. throw err
  991. }
  992. }
  993. // OK, we haven't thrown an error, we can start updating state and emitting events now:
  994. this.setState({ files: nextFilesState })
  995. validFilesToAdd.forEach((file) => {
  996. this.emit('file-added', file)
  997. })
  998. this.emit('files-added', validFilesToAdd)
  999. if (validFilesToAdd.length > 5) {
  1000. this.log(`Added batch of ${validFilesToAdd.length} files`)
  1001. } else {
  1002. Object.values(validFilesToAdd).forEach((file) => {
  1003. this.log(
  1004. `Added file: ${file.name}\n id: ${file.id}\n type: ${file.type}`,
  1005. )
  1006. })
  1007. }
  1008. if (validFilesToAdd.length > 0) {
  1009. this.#startIfAutoProceed()
  1010. }
  1011. }
  1012. removeFiles(fileIDs: string[], reason?: FileRemoveReason): void {
  1013. const { files, currentUploads } = this.getState()
  1014. const updatedFiles = { ...files }
  1015. const updatedUploads = { ...currentUploads }
  1016. const removedFiles = Object.create(null)
  1017. fileIDs.forEach((fileID) => {
  1018. if (files[fileID]) {
  1019. removedFiles[fileID] = files[fileID]
  1020. delete updatedFiles[fileID]
  1021. }
  1022. })
  1023. // Remove files from the `fileIDs` list in each upload.
  1024. function fileIsNotRemoved(uploadFileID: string): boolean {
  1025. return removedFiles[uploadFileID] === undefined
  1026. }
  1027. Object.keys(updatedUploads).forEach((uploadID) => {
  1028. const newFileIDs =
  1029. currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved)
  1030. // Remove the upload if no files are associated with it anymore.
  1031. if (newFileIDs.length === 0) {
  1032. delete updatedUploads[uploadID]
  1033. return
  1034. }
  1035. const { capabilities } = this.getState()
  1036. if (
  1037. newFileIDs.length !== currentUploads[uploadID].fileIDs.length &&
  1038. !capabilities.individualCancellation
  1039. ) {
  1040. throw new Error('individualCancellation is disabled')
  1041. }
  1042. updatedUploads[uploadID] = {
  1043. ...currentUploads[uploadID],
  1044. fileIDs: newFileIDs,
  1045. }
  1046. })
  1047. const stateUpdate: Partial<State<M, B>> = {
  1048. currentUploads: updatedUploads,
  1049. files: updatedFiles,
  1050. }
  1051. // If all files were removed - allow new uploads,
  1052. // and clear recoveredState
  1053. if (Object.keys(updatedFiles).length === 0) {
  1054. stateUpdate.allowNewUpload = true
  1055. stateUpdate.error = null
  1056. stateUpdate.recoveredState = null
  1057. }
  1058. this.setState(stateUpdate)
  1059. this.calculateTotalProgress()
  1060. const removedFileIDs = Object.keys(removedFiles)
  1061. removedFileIDs.forEach((fileID) => {
  1062. this.emit('file-removed', removedFiles[fileID], reason)
  1063. })
  1064. if (removedFileIDs.length > 5) {
  1065. this.log(`Removed ${removedFileIDs.length} files`)
  1066. } else {
  1067. this.log(`Removed files: ${removedFileIDs.join(', ')}`)
  1068. }
  1069. }
  1070. removeFile(fileID: string, reason?: FileRemoveReason): void {
  1071. this.removeFiles([fileID], reason)
  1072. }
  1073. pauseResume(fileID: string): boolean | undefined {
  1074. if (
  1075. !this.getState().capabilities.resumableUploads ||
  1076. this.getFile(fileID).progress.uploadComplete
  1077. ) {
  1078. return undefined
  1079. }
  1080. const wasPaused = this.getFile(fileID).isPaused || false
  1081. const isPaused = !wasPaused
  1082. this.setFileState(fileID, {
  1083. isPaused,
  1084. })
  1085. this.emit('upload-pause', fileID, isPaused)
  1086. return isPaused
  1087. }
  1088. pauseAll(): void {
  1089. const updatedFiles = { ...this.getState().files }
  1090. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  1091. return (
  1092. !updatedFiles[file].progress.uploadComplete &&
  1093. updatedFiles[file].progress.uploadStarted
  1094. )
  1095. })
  1096. inProgressUpdatedFiles.forEach((file) => {
  1097. const updatedFile = { ...updatedFiles[file], isPaused: true }
  1098. updatedFiles[file] = updatedFile
  1099. })
  1100. this.setState({ files: updatedFiles })
  1101. this.emit('pause-all')
  1102. }
  1103. resumeAll(): void {
  1104. const updatedFiles = { ...this.getState().files }
  1105. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  1106. return (
  1107. !updatedFiles[file].progress.uploadComplete &&
  1108. updatedFiles[file].progress.uploadStarted
  1109. )
  1110. })
  1111. inProgressUpdatedFiles.forEach((file) => {
  1112. const updatedFile = {
  1113. ...updatedFiles[file],
  1114. isPaused: false,
  1115. error: null,
  1116. }
  1117. updatedFiles[file] = updatedFile
  1118. })
  1119. this.setState({ files: updatedFiles })
  1120. this.emit('resume-all')
  1121. }
  1122. retryAll(): Promise<UploadResult<M, B> | undefined> {
  1123. const updatedFiles = { ...this.getState().files }
  1124. const filesToRetry = Object.keys(updatedFiles).filter((file) => {
  1125. return updatedFiles[file].error
  1126. })
  1127. filesToRetry.forEach((file) => {
  1128. const updatedFile = {
  1129. ...updatedFiles[file],
  1130. isPaused: false,
  1131. error: null,
  1132. }
  1133. updatedFiles[file] = updatedFile
  1134. })
  1135. this.setState({
  1136. files: updatedFiles,
  1137. error: null,
  1138. })
  1139. this.emit('retry-all', filesToRetry)
  1140. if (filesToRetry.length === 0) {
  1141. return Promise.resolve({
  1142. successful: [],
  1143. failed: [],
  1144. })
  1145. }
  1146. const uploadID = this.#createUpload(filesToRetry, {
  1147. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  1148. })
  1149. return this.#runUpload(uploadID)
  1150. }
  1151. cancelAll({ reason = 'user' }: { reason?: FileRemoveReason } = {}): void {
  1152. this.emit('cancel-all', { reason })
  1153. // Only remove existing uploads if user is canceling
  1154. if (reason === 'user') {
  1155. const { files } = this.getState()
  1156. const fileIDs = Object.keys(files)
  1157. if (fileIDs.length) {
  1158. this.removeFiles(fileIDs, 'cancel-all')
  1159. }
  1160. this.setState(defaultUploadState)
  1161. // todo should we call this.emit('reset-progress') like we do for resetProgress?
  1162. }
  1163. }
  1164. retryUpload(fileID: string): Promise<UploadResult<M, B> | undefined> {
  1165. this.setFileState(fileID, {
  1166. error: null,
  1167. isPaused: false,
  1168. })
  1169. this.emit('upload-retry', fileID)
  1170. const uploadID = this.#createUpload([fileID], {
  1171. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  1172. })
  1173. return this.#runUpload(uploadID)
  1174. }
  1175. logout(): void {
  1176. this.iteratePlugins((plugin) => {
  1177. ;(plugin as UnknownProviderPlugin<M, B>).provider?.logout?.()
  1178. })
  1179. }
  1180. // ___Why throttle at 500ms?
  1181. // - We must throttle at >250ms for superfocus in Dashboard to work well
  1182. // (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).
  1183. // [Practical Check]: if thottle is at 100ms, then if you are uploading a file,
  1184. // and click 'ADD MORE FILES', - focus won't activate in Firefox.
  1185. // - We must throttle at around >500ms to avoid performance lags.
  1186. // [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
  1187. // todo when uploading multiple files, this will cause problems because they share the same throttle,
  1188. // meaning some files might never get their progress reported (eaten up by progress events from other files)
  1189. calculateProgress = throttle(
  1190. (file, data) => {
  1191. const fileInState = this.getFile(file?.id)
  1192. if (file == null || !fileInState) {
  1193. this.log(
  1194. `Not setting progress for a file that has been removed: ${file?.id}`,
  1195. )
  1196. return
  1197. }
  1198. if (fileInState.progress.percentage === 100) {
  1199. this.log(
  1200. `Not setting progress for a file that has been already uploaded: ${file.id}`,
  1201. )
  1202. return
  1203. }
  1204. // bytesTotal may be null or zero; in that case we can't divide by it
  1205. const canHavePercentage =
  1206. Number.isFinite(data.bytesTotal) && data.bytesTotal > 0
  1207. this.setFileState(file.id, {
  1208. progress: {
  1209. ...fileInState.progress,
  1210. bytesUploaded: data.bytesUploaded,
  1211. bytesTotal: data.bytesTotal,
  1212. percentage:
  1213. canHavePercentage ?
  1214. Math.round((data.bytesUploaded / data.bytesTotal) * 100)
  1215. : 0,
  1216. },
  1217. })
  1218. this.calculateTotalProgress()
  1219. },
  1220. 500,
  1221. { leading: true, trailing: true },
  1222. )
  1223. calculateTotalProgress(): void {
  1224. // calculate total progress, using the number of files currently uploading,
  1225. // multiplied by 100 and the summ of individual progress of each file
  1226. const files = this.getFiles()
  1227. const inProgress = files.filter((file) => {
  1228. return (
  1229. file.progress.uploadStarted ||
  1230. file.progress.preprocess ||
  1231. file.progress.postprocess
  1232. )
  1233. })
  1234. if (inProgress.length === 0) {
  1235. this.emit('progress', 0)
  1236. this.setState({ totalProgress: 0 })
  1237. return
  1238. }
  1239. const sizedFiles = inProgress.filter(
  1240. (file) => file.progress.bytesTotal != null,
  1241. )
  1242. const unsizedFiles = inProgress.filter(
  1243. (file) => file.progress.bytesTotal == null,
  1244. )
  1245. if (sizedFiles.length === 0) {
  1246. const progressMax = inProgress.length * 100
  1247. const currentProgress = unsizedFiles.reduce((acc, file) => {
  1248. return acc + (file.progress.percentage as number)
  1249. }, 0)
  1250. const totalProgress = Math.round((currentProgress / progressMax) * 100)
  1251. this.setState({ totalProgress })
  1252. return
  1253. }
  1254. let totalSize = sizedFiles.reduce((acc, file) => {
  1255. return (acc + (file.progress.bytesTotal ?? 0)) as number
  1256. }, 0)
  1257. const averageSize = totalSize / sizedFiles.length
  1258. totalSize += averageSize * unsizedFiles.length
  1259. let uploadedSize = 0
  1260. sizedFiles.forEach((file) => {
  1261. uploadedSize += file.progress.bytesUploaded as number
  1262. })
  1263. unsizedFiles.forEach((file) => {
  1264. uploadedSize += (averageSize * (file.progress.percentage || 0)) / 100
  1265. })
  1266. let totalProgress =
  1267. totalSize === 0 ? 0 : Math.round((uploadedSize / totalSize) * 100)
  1268. // hot fix, because:
  1269. // uploadedSize ended up larger than totalSize, resulting in 1325% total
  1270. if (totalProgress > 100) {
  1271. totalProgress = 100
  1272. }
  1273. this.setState({ totalProgress })
  1274. this.emit('progress', totalProgress)
  1275. }
  1276. /**
  1277. * Registers listeners for all global actions, like:
  1278. * `error`, `file-removed`, `upload-progress`
  1279. */
  1280. #addListeners(): void {
  1281. // Type inference only works for inline functions so we have to type it again
  1282. const errorHandler: UppyEventMap<M, B>['error'] = (
  1283. error,
  1284. file,
  1285. response,
  1286. ) => {
  1287. let errorMsg = error.message || 'Unknown error'
  1288. if (error.details) {
  1289. errorMsg += ` ${error.details}`
  1290. }
  1291. this.setState({ error: errorMsg })
  1292. if (file != null && file.id in this.getState().files) {
  1293. this.setFileState(file.id, {
  1294. error: errorMsg,
  1295. response,
  1296. })
  1297. }
  1298. }
  1299. this.on('error', errorHandler)
  1300. this.on('upload-error', (file, error, response) => {
  1301. errorHandler(error, file, response)
  1302. if (typeof error === 'object' && error.message) {
  1303. this.log(error.message, 'error')
  1304. const newError = new Error(
  1305. this.i18n('failedToUpload', { file: file?.name ?? '' }),
  1306. ) as any // we may want a new custom error here
  1307. newError.isUserFacing = true // todo maybe don't do this with all errors?
  1308. newError.details = error.message
  1309. if (error.details) {
  1310. newError.details += ` ${error.details}`
  1311. }
  1312. this.#informAndEmit([newError])
  1313. } else {
  1314. this.#informAndEmit([error])
  1315. }
  1316. })
  1317. let uploadStalledWarningRecentlyEmitted: ReturnType<
  1318. typeof setTimeout
  1319. > | null = null
  1320. this.on('upload-stalled', (error, files) => {
  1321. const { message } = error
  1322. const details = files.map((file) => file.meta.name).join(', ')
  1323. if (!uploadStalledWarningRecentlyEmitted) {
  1324. this.info({ message, details }, 'warning', this.opts.infoTimeout)
  1325. uploadStalledWarningRecentlyEmitted = setTimeout(() => {
  1326. uploadStalledWarningRecentlyEmitted = null
  1327. }, this.opts.infoTimeout)
  1328. }
  1329. this.log(`${message} ${details}`.trim(), 'warning')
  1330. })
  1331. this.on('upload', () => {
  1332. this.setState({ error: null })
  1333. })
  1334. const onUploadStarted = (files: UppyFile<M, B>[]): void => {
  1335. const filesFiltered = files.filter((file) => {
  1336. const exists = file != null && this.getFile(file.id)
  1337. if (!exists)
  1338. this.log(
  1339. `Not setting progress for a file that has been removed: ${file?.id}`,
  1340. )
  1341. return exists
  1342. })
  1343. const filesState = Object.fromEntries(
  1344. filesFiltered.map((file) => [
  1345. file.id,
  1346. {
  1347. progress: {
  1348. uploadStarted: Date.now(),
  1349. uploadComplete: false,
  1350. percentage: 0,
  1351. bytesUploaded: 0,
  1352. bytesTotal: file.size,
  1353. } as FileProgressStarted,
  1354. },
  1355. ]),
  1356. )
  1357. this.patchFilesState(filesState)
  1358. }
  1359. this.on('upload-start', (files) => {
  1360. files.forEach((file: UppyFile<M, B>) => {
  1361. // todo backward compat, remove this event in a next major
  1362. this.emit('upload-started', file)
  1363. })
  1364. onUploadStarted(files)
  1365. })
  1366. this.on('upload-progress', this.calculateProgress)
  1367. this.on('upload-success', (file, uploadResp) => {
  1368. if (file == null || !this.getFile(file.id)) {
  1369. this.log(
  1370. `Not setting progress for a file that has been removed: ${file?.id}`,
  1371. )
  1372. return
  1373. }
  1374. const currentProgress = this.getFile(file.id).progress
  1375. this.setFileState(file.id, {
  1376. progress: {
  1377. ...currentProgress,
  1378. postprocess:
  1379. this.#postProcessors.size > 0 ?
  1380. {
  1381. mode: 'indeterminate',
  1382. }
  1383. : undefined,
  1384. uploadComplete: true,
  1385. percentage: 100,
  1386. bytesUploaded: currentProgress.bytesTotal,
  1387. } as FileProgressStarted,
  1388. response: uploadResp,
  1389. uploadURL: uploadResp.uploadURL,
  1390. isPaused: false,
  1391. })
  1392. // Remote providers sometimes don't tell us the file size,
  1393. // but we can know how many bytes we uploaded once the upload is complete.
  1394. if (file.size == null) {
  1395. this.setFileState(file.id, {
  1396. size: uploadResp.bytesUploaded || currentProgress.bytesTotal,
  1397. })
  1398. }
  1399. this.calculateTotalProgress()
  1400. })
  1401. this.on('preprocess-progress', (file, progress) => {
  1402. if (file == null || !this.getFile(file.id)) {
  1403. this.log(
  1404. `Not setting progress for a file that has been removed: ${file?.id}`,
  1405. )
  1406. return
  1407. }
  1408. this.setFileState(file.id, {
  1409. progress: { ...this.getFile(file.id).progress, preprocess: progress },
  1410. })
  1411. })
  1412. this.on('preprocess-complete', (file) => {
  1413. if (file == null || !this.getFile(file.id)) {
  1414. this.log(
  1415. `Not setting progress for a file that has been removed: ${file?.id}`,
  1416. )
  1417. return
  1418. }
  1419. const files = { ...this.getState().files }
  1420. files[file.id] = {
  1421. ...files[file.id],
  1422. progress: { ...files[file.id].progress },
  1423. }
  1424. delete files[file.id].progress.preprocess
  1425. this.setState({ files })
  1426. })
  1427. this.on('postprocess-progress', (file, progress) => {
  1428. if (file == null || !this.getFile(file.id)) {
  1429. this.log(
  1430. `Not setting progress for a file that has been removed: ${file?.id}`,
  1431. )
  1432. return
  1433. }
  1434. this.setFileState(file.id, {
  1435. progress: {
  1436. ...this.getState().files[file.id].progress,
  1437. postprocess: progress,
  1438. },
  1439. })
  1440. })
  1441. this.on('postprocess-complete', (file) => {
  1442. if (file == null || !this.getFile(file.id)) {
  1443. this.log(
  1444. `Not setting progress for a file that has been removed: ${file?.id}`,
  1445. )
  1446. return
  1447. }
  1448. const files = {
  1449. ...this.getState().files,
  1450. }
  1451. files[file.id] = {
  1452. ...files[file.id],
  1453. progress: {
  1454. ...files[file.id].progress,
  1455. },
  1456. }
  1457. delete files[file.id].progress.postprocess
  1458. this.setState({ files })
  1459. })
  1460. this.on('restored', () => {
  1461. // Files may have changed--ensure progress is still accurate.
  1462. this.calculateTotalProgress()
  1463. })
  1464. // @ts-expect-error should fix itself when dashboard it typed (also this doesn't belong here)
  1465. this.on('dashboard:file-edit-complete', (file) => {
  1466. if (file) {
  1467. this.#checkRequiredMetaFieldsOnFile(file)
  1468. }
  1469. })
  1470. // show informer if offline
  1471. if (typeof window !== 'undefined' && window.addEventListener) {
  1472. window.addEventListener('online', this.#updateOnlineStatus)
  1473. window.addEventListener('offline', this.#updateOnlineStatus)
  1474. setTimeout(this.#updateOnlineStatus, 3000)
  1475. }
  1476. }
  1477. updateOnlineStatus(): void {
  1478. const online = window.navigator.onLine ?? true
  1479. if (!online) {
  1480. this.emit('is-offline')
  1481. this.info(this.i18n('noInternetConnection'), 'error', 0)
  1482. this.wasOffline = true
  1483. } else {
  1484. this.emit('is-online')
  1485. if (this.wasOffline) {
  1486. this.emit('back-online')
  1487. this.info(this.i18n('connectedToInternet'), 'success', 3000)
  1488. this.wasOffline = false
  1489. }
  1490. }
  1491. }
  1492. #updateOnlineStatus = this.updateOnlineStatus.bind(this)
  1493. getID(): string {
  1494. return this.opts.id
  1495. }
  1496. /**
  1497. * Registers a plugin with Core.
  1498. */
  1499. use<T extends typeof BasePlugin<any, M, B>>(
  1500. Plugin: T,
  1501. opts?: ConstructorParameters<T>[1],
  1502. ): this {
  1503. if (typeof Plugin !== 'function') {
  1504. const msg =
  1505. `Expected a plugin class, but got ${
  1506. Plugin === null ? 'null' : typeof Plugin
  1507. }.` +
  1508. ' Please verify that the plugin was imported and spelled correctly.'
  1509. throw new TypeError(msg)
  1510. }
  1511. // Instantiate
  1512. const plugin = new Plugin(this, opts)
  1513. const pluginId = plugin.id
  1514. if (!pluginId) {
  1515. throw new Error('Your plugin must have an id')
  1516. }
  1517. if (!plugin.type) {
  1518. throw new Error('Your plugin must have a type')
  1519. }
  1520. const existsPluginAlready = this.getPlugin(pluginId)
  1521. if (existsPluginAlready) {
  1522. const msg =
  1523. `Already found a plugin named '${existsPluginAlready.id}'. ` +
  1524. `Tried to use: '${pluginId}'.\n` +
  1525. 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.'
  1526. throw new Error(msg)
  1527. }
  1528. // @ts-expect-error does exist
  1529. if (Plugin.VERSION) {
  1530. // @ts-expect-error does exist
  1531. this.log(`Using ${pluginId} v${Plugin.VERSION}`)
  1532. }
  1533. if (plugin.type in this.#plugins) {
  1534. this.#plugins[plugin.type].push(plugin)
  1535. } else {
  1536. this.#plugins[plugin.type] = [plugin]
  1537. }
  1538. plugin.install()
  1539. this.emit('plugin-added', plugin)
  1540. return this
  1541. }
  1542. /**
  1543. * Find one Plugin by name.
  1544. */
  1545. getPlugin(id: string): UnknownPlugin<M, B> | undefined {
  1546. for (const plugins of Object.values(this.#plugins)) {
  1547. const foundPlugin = plugins.find((plugin) => plugin.id === id)
  1548. if (foundPlugin != null) return foundPlugin
  1549. }
  1550. return undefined
  1551. }
  1552. private [Symbol.for('uppy test: getPlugins')](
  1553. type: string,
  1554. ): UnknownPlugin<M, B>[] {
  1555. return this.#plugins[type]
  1556. }
  1557. /**
  1558. * Iterate through all `use`d plugins.
  1559. *
  1560. */
  1561. iteratePlugins(method: (plugin: UnknownPlugin<M, B>) => void): void {
  1562. Object.values(this.#plugins).flat(1).forEach(method)
  1563. }
  1564. /**
  1565. * Uninstall and remove a plugin.
  1566. *
  1567. * @param {object} instance The plugin instance to remove.
  1568. */
  1569. removePlugin(instance: UnknownPlugin<M, B>): void {
  1570. this.log(`Removing plugin ${instance.id}`)
  1571. this.emit('plugin-remove', instance)
  1572. if (instance.uninstall) {
  1573. instance.uninstall()
  1574. }
  1575. const list = this.#plugins[instance.type]
  1576. // list.indexOf failed here, because Vue3 converted the plugin instance
  1577. // to a Proxy object, which failed the strict comparison test:
  1578. // obj !== objProxy
  1579. const index = list.findIndex((item) => item.id === instance.id)
  1580. if (index !== -1) {
  1581. list.splice(index, 1)
  1582. }
  1583. const state = this.getState()
  1584. const updatedState = {
  1585. plugins: {
  1586. ...state.plugins,
  1587. [instance.id]: undefined,
  1588. },
  1589. }
  1590. this.setState(updatedState)
  1591. }
  1592. /**
  1593. * Uninstall all plugins and close down this Uppy instance.
  1594. */
  1595. // @todo next major: rename to `destroy`.
  1596. // Cancel local uploads, cancel remote uploads, DON'T cancel assemblies
  1597. // document that if you do want to cancel assemblies, you need to call smth manually.
  1598. // Potentially remove reason, as it’s confusing, just come up with a default behaviour.
  1599. close({ reason }: { reason?: FileRemoveReason } | undefined = {}): void {
  1600. this.log(
  1601. `Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`,
  1602. )
  1603. this.cancelAll({ reason })
  1604. this.#storeUnsubscribe()
  1605. this.iteratePlugins((plugin) => {
  1606. this.removePlugin(plugin)
  1607. })
  1608. if (typeof window !== 'undefined' && window.removeEventListener) {
  1609. window.removeEventListener('online', this.#updateOnlineStatus)
  1610. window.removeEventListener('offline', this.#updateOnlineStatus)
  1611. }
  1612. }
  1613. hideInfo(): void {
  1614. const { info } = this.getState()
  1615. this.setState({ info: info.slice(1) })
  1616. this.emit('info-hidden')
  1617. }
  1618. /**
  1619. * Set info message in `state.info`, so that UI plugins like `Informer`
  1620. * can display the message.
  1621. */
  1622. info(
  1623. message:
  1624. | string
  1625. | { message: string; details?: string | Record<string, string> },
  1626. type: LogLevel = 'info',
  1627. duration = 3000,
  1628. ): void {
  1629. const isComplexMessage = typeof message === 'object'
  1630. this.setState({
  1631. info: [
  1632. ...this.getState().info,
  1633. {
  1634. type,
  1635. message: isComplexMessage ? message.message : message,
  1636. details: isComplexMessage ? message.details : null,
  1637. },
  1638. ],
  1639. })
  1640. setTimeout(() => this.hideInfo(), duration)
  1641. this.emit('info-visible')
  1642. }
  1643. /**
  1644. * Passes messages to a function, provided in `opts.logger`.
  1645. * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.
  1646. */
  1647. log(message: string | Record<any, any> | Error, type?: string): void {
  1648. const { logger } = this.opts
  1649. switch (type) {
  1650. case 'error':
  1651. logger.error(message)
  1652. break
  1653. case 'warning':
  1654. logger.warn(message)
  1655. break
  1656. default:
  1657. logger.debug(message)
  1658. break
  1659. }
  1660. }
  1661. // We need to store request clients by a unique ID, so we can share RequestClient instances across files
  1662. // this allows us to do rate limiting and synchronous operations like refreshing provider tokens
  1663. // example: refreshing tokens: if each file has their own requestclient,
  1664. // we don't have any way to synchronize all requests in order to
  1665. // - block all requests
  1666. // - refresh the token
  1667. // - unblock all requests and allow them to run with a the new access token
  1668. // back when we had a requestclient per file, once an access token expired,
  1669. // all 6 files would go ahead and refresh the token at the same time
  1670. // (calling /refresh-token up to 6 times), which will probably fail for some providers
  1671. #requestClientById = new Map<string, unknown>()
  1672. registerRequestClient(id: string, client: unknown): void {
  1673. this.#requestClientById.set(id, client)
  1674. }
  1675. /** @protected */
  1676. getRequestClientForFile<Client>(file: UppyFile<M, B>): Client {
  1677. if (!file.remote)
  1678. throw new Error(
  1679. `Tried to get RequestClient for a non-remote file ${file.id}`,
  1680. )
  1681. const requestClient = this.#requestClientById.get(
  1682. file.remote.requestClientId,
  1683. )
  1684. if (requestClient == null)
  1685. throw new Error(
  1686. `requestClientId "${file.remote.requestClientId}" not registered for file "${file.id}"`,
  1687. )
  1688. return requestClient as Client
  1689. }
  1690. /**
  1691. * Restore an upload by its ID.
  1692. */
  1693. restore(uploadID: string): Promise<UploadResult<M, B> | undefined> {
  1694. this.log(`Core: attempting to restore upload "${uploadID}"`)
  1695. if (!this.getState().currentUploads[uploadID]) {
  1696. this.#removeUpload(uploadID)
  1697. return Promise.reject(new Error('Nonexistent upload'))
  1698. }
  1699. return this.#runUpload(uploadID)
  1700. }
  1701. /**
  1702. * Create an upload for a bunch of files.
  1703. *
  1704. */
  1705. #createUpload(
  1706. fileIDs: string[],
  1707. opts: { forceAllowNewUpload?: boolean } = {},
  1708. ): string {
  1709. // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
  1710. const { forceAllowNewUpload = false } = opts
  1711. const { allowNewUpload, currentUploads } = this.getState()
  1712. if (!allowNewUpload && !forceAllowNewUpload) {
  1713. throw new Error('Cannot create a new upload: already uploading.')
  1714. }
  1715. const uploadID = nanoid()
  1716. this.emit('upload', {
  1717. id: uploadID,
  1718. fileIDs,
  1719. })
  1720. this.setState({
  1721. allowNewUpload:
  1722. this.opts.allowMultipleUploadBatches !== false &&
  1723. this.opts.allowMultipleUploads !== false,
  1724. currentUploads: {
  1725. ...currentUploads,
  1726. [uploadID]: {
  1727. fileIDs,
  1728. step: 0,
  1729. result: {},
  1730. },
  1731. },
  1732. })
  1733. return uploadID
  1734. }
  1735. private [Symbol.for('uppy test: createUpload')](...args: any[]): string {
  1736. // @ts-expect-error https://github.com/microsoft/TypeScript/issues/47595
  1737. return this.#createUpload(...args)
  1738. }
  1739. #getUpload(uploadID: string): CurrentUpload<M, B> {
  1740. const { currentUploads } = this.getState()
  1741. return currentUploads[uploadID]
  1742. }
  1743. /**
  1744. * Add data to an upload's result object.
  1745. */
  1746. addResultData(uploadID: string, data: CurrentUpload<M, B>['result']): void {
  1747. if (!this.#getUpload(uploadID)) {
  1748. this.log(
  1749. `Not setting result for an upload that has been removed: ${uploadID}`,
  1750. )
  1751. return
  1752. }
  1753. const { currentUploads } = this.getState()
  1754. const currentUpload = {
  1755. ...currentUploads[uploadID],
  1756. result: { ...currentUploads[uploadID].result, ...data },
  1757. }
  1758. this.setState({
  1759. currentUploads: { ...currentUploads, [uploadID]: currentUpload },
  1760. })
  1761. }
  1762. /**
  1763. * Remove an upload, eg. if it has been canceled or completed.
  1764. *
  1765. */
  1766. #removeUpload(uploadID: string): void {
  1767. const currentUploads = { ...this.getState().currentUploads }
  1768. delete currentUploads[uploadID]
  1769. this.setState({
  1770. currentUploads,
  1771. })
  1772. }
  1773. /**
  1774. * Run an upload. This picks up where it left off in case the upload is being restored.
  1775. */
  1776. async #runUpload(uploadID: string): Promise<UploadResult<M, B> | undefined> {
  1777. const getCurrentUpload = (): CurrentUpload<M, B> => {
  1778. const { currentUploads } = this.getState()
  1779. return currentUploads[uploadID]
  1780. }
  1781. let currentUpload = getCurrentUpload()
  1782. const steps = [
  1783. ...this.#preProcessors,
  1784. ...this.#uploaders,
  1785. ...this.#postProcessors,
  1786. ]
  1787. try {
  1788. for (let step = currentUpload.step || 0; step < steps.length; step++) {
  1789. if (!currentUpload) {
  1790. break
  1791. }
  1792. const fn = steps[step]
  1793. this.setState({
  1794. currentUploads: {
  1795. ...this.getState().currentUploads,
  1796. [uploadID]: {
  1797. ...currentUpload,
  1798. step,
  1799. },
  1800. },
  1801. })
  1802. const { fileIDs } = currentUpload
  1803. // TODO give this the `updatedUpload` object as its only parameter maybe?
  1804. // Otherwise when more metadata may be added to the upload this would keep getting more parameters
  1805. await fn(fileIDs, uploadID)
  1806. // Update currentUpload value in case it was modified asynchronously.
  1807. currentUpload = getCurrentUpload()
  1808. }
  1809. } catch (err) {
  1810. this.#removeUpload(uploadID)
  1811. throw err
  1812. }
  1813. // Set result data.
  1814. if (currentUpload) {
  1815. // Mark postprocessing step as complete if necessary; this addresses a case where we might get
  1816. // stuck in the postprocessing UI while the upload is fully complete.
  1817. // If the postprocessing steps do not do any work, they may not emit postprocessing events at
  1818. // all, and never mark the postprocessing as complete. This is fine on its own but we
  1819. // introduced code in the @uppy/core upload-success handler to prepare postprocessing progress
  1820. // state if any postprocessors are registered. That is to avoid a "flash of completed state"
  1821. // before the postprocessing plugins can emit events.
  1822. //
  1823. // So, just in case an upload with postprocessing plugins *has* completed *without* emitting
  1824. // postprocessing completion, we do it instead.
  1825. currentUpload.fileIDs.forEach((fileID) => {
  1826. const file = this.getFile(fileID)
  1827. if (file && file.progress.postprocess) {
  1828. this.emit('postprocess-complete', file)
  1829. }
  1830. })
  1831. const files = currentUpload.fileIDs.map((fileID) => this.getFile(fileID))
  1832. const successful = files.filter((file) => !file.error)
  1833. const failed = files.filter((file) => file.error)
  1834. this.addResultData(uploadID, { successful, failed, uploadID })
  1835. // Update currentUpload value in case it was modified asynchronously.
  1836. currentUpload = getCurrentUpload()
  1837. }
  1838. // Emit completion events.
  1839. // This is in a separate function so that the `currentUploads` variable
  1840. // always refers to the latest state. In the handler right above it refers
  1841. // to an outdated object without the `.result` property.
  1842. let result
  1843. if (currentUpload) {
  1844. result = currentUpload.result
  1845. this.emit('complete', result)
  1846. this.#removeUpload(uploadID)
  1847. }
  1848. if (result == null) {
  1849. this.log(
  1850. `Not setting result for an upload that has been removed: ${uploadID}`,
  1851. )
  1852. }
  1853. return result
  1854. }
  1855. /**
  1856. * Start an upload for all the files that are not currently being uploaded.
  1857. */
  1858. upload(): Promise<NonNullable<UploadResult<M, B>> | undefined> {
  1859. if (!this.#plugins.uploader?.length) {
  1860. this.log('No uploader type plugins are used', 'warning')
  1861. }
  1862. let { files } = this.getState()
  1863. const onBeforeUploadResult = this.opts.onBeforeUpload(files)
  1864. if (onBeforeUploadResult === false) {
  1865. return Promise.reject(
  1866. new Error(
  1867. 'Not starting the upload because onBeforeUpload returned false',
  1868. ),
  1869. )
  1870. }
  1871. if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
  1872. files = onBeforeUploadResult
  1873. // Updating files in state, because uploader plugins receive file IDs,
  1874. // and then fetch the actual file object from state
  1875. this.setState({
  1876. files,
  1877. })
  1878. }
  1879. return Promise.resolve()
  1880. .then(() => this.#restricter.validateMinNumberOfFiles(files))
  1881. .catch((err) => {
  1882. this.#informAndEmit([err])
  1883. throw err
  1884. })
  1885. .then(() => {
  1886. if (!this.#checkRequiredMetaFields(files)) {
  1887. throw new RestrictionError(this.i18n('missingRequiredMetaField'))
  1888. }
  1889. })
  1890. .catch((err) => {
  1891. // Doing this in a separate catch because we already emited and logged
  1892. // all the errors in `checkRequiredMetaFields` so we only throw a generic
  1893. // missing fields error here.
  1894. throw err
  1895. })
  1896. .then(() => {
  1897. const { currentUploads } = this.getState()
  1898. // get a list of files that are currently assigned to uploads
  1899. const currentlyUploadingFiles = Object.values(currentUploads).flatMap(
  1900. (curr) => curr.fileIDs,
  1901. )
  1902. const waitingFileIDs: string[] = []
  1903. Object.keys(files).forEach((fileID) => {
  1904. const file = this.getFile(fileID)
  1905. // if the file hasn't started uploading and hasn't already been assigned to an upload..
  1906. if (
  1907. !file.progress.uploadStarted &&
  1908. currentlyUploadingFiles.indexOf(fileID) === -1
  1909. ) {
  1910. waitingFileIDs.push(file.id)
  1911. }
  1912. })
  1913. const uploadID = this.#createUpload(waitingFileIDs)
  1914. return this.#runUpload(uploadID)
  1915. })
  1916. .catch((err) => {
  1917. this.emit('error', err)
  1918. this.log(err, 'error')
  1919. throw err
  1920. })
  1921. }
  1922. }
  1923. export default Uppy