payload-video-streaming 0.2.0-beta.0 → 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +174 -543
  2. package/dist/access.d.ts +35 -0
  3. package/dist/access.js +53 -0
  4. package/dist/access.js.map +1 -0
  5. package/dist/bin/args.d.ts +13 -0
  6. package/dist/bin/args.js +61 -0
  7. package/dist/bin/args.js.map +1 -1
  8. package/dist/bin/cli.js +9 -1
  9. package/dist/bin/cli.js.map +1 -1
  10. package/dist/bin/webhooks.d.ts +15 -0
  11. package/dist/bin/webhooks.js +149 -0
  12. package/dist/bin/webhooks.js.map +1 -0
  13. package/dist/collection.js +148 -1
  14. package/dist/collection.js.map +1 -1
  15. package/dist/components/BulkUploader.d.ts +16 -0
  16. package/dist/components/BulkUploader.js +226 -0
  17. package/dist/components/BulkUploader.js.map +1 -0
  18. package/dist/components/ListUploader.js +22 -0
  19. package/dist/components/ListUploader.js.map +1 -1
  20. package/dist/components/Uploader.d.ts +5 -0
  21. package/dist/components/Uploader.js +13 -4
  22. package/dist/components/Uploader.js.map +1 -1
  23. package/dist/components/VideoField.js +9 -5
  24. package/dist/components/VideoField.js.map +1 -1
  25. package/dist/components/VideoRelationshipField.d.ts +16 -0
  26. package/dist/components/VideoRelationshipField.js +106 -0
  27. package/dist/components/VideoRelationshipField.js.map +1 -0
  28. package/dist/components/WebhookStatusPanel.d.ts +6 -0
  29. package/dist/components/WebhookStatusPanel.js +143 -0
  30. package/dist/components/WebhookStatusPanel.js.map +1 -0
  31. package/dist/components/api.d.ts +7 -1
  32. package/dist/components/api.js +2 -0
  33. package/dist/components/api.js.map +1 -1
  34. package/dist/components/uploadFile.d.ts +30 -0
  35. package/dist/components/uploadFile.js +140 -0
  36. package/dist/components/uploadFile.js.map +1 -0
  37. package/dist/components/usePluginApi.d.ts +5 -0
  38. package/dist/components/useUploadQueue.d.ts +35 -0
  39. package/dist/components/useUploadQueue.js +135 -0
  40. package/dist/components/useUploadQueue.js.map +1 -0
  41. package/dist/components/useVideoUpload.d.ts +3 -7
  42. package/dist/components/useVideoUpload.js +29 -123
  43. package/dist/components/useVideoUpload.js.map +1 -1
  44. package/dist/core/provider.d.ts +16 -0
  45. package/dist/core/provider.js.map +1 -1
  46. package/dist/endpoints/index.js +38 -2
  47. package/dist/endpoints/index.js.map +1 -1
  48. package/dist/exports/client.d.ts +9 -0
  49. package/dist/exports/client.js +5 -0
  50. package/dist/exports/client.js.map +1 -1
  51. package/dist/exports/react.d.ts +12 -0
  52. package/dist/exports/react.js +7 -0
  53. package/dist/exports/react.js.map +1 -1
  54. package/dist/fields.d.ts +11 -2
  55. package/dist/fields.js +62 -2
  56. package/dist/fields.js.map +1 -1
  57. package/dist/frontend/VideoUploader.d.ts +65 -0
  58. package/dist/frontend/VideoUploader.js +260 -0
  59. package/dist/frontend/VideoUploader.js.map +1 -0
  60. package/dist/frontend/useVideoStatus.d.ts +26 -0
  61. package/dist/frontend/useVideoStatus.js +68 -0
  62. package/dist/frontend/useVideoStatus.js.map +1 -0
  63. package/dist/index.d.ts +5 -4
  64. package/dist/index.js +3 -2
  65. package/dist/index.js.map +1 -1
  66. package/dist/options.d.ts +7 -2
  67. package/dist/options.js +65 -2
  68. package/dist/options.js.map +1 -1
  69. package/dist/plugin.js +80 -1
  70. package/dist/plugin.js.map +1 -1
  71. package/dist/providers/bunny/provider.d.ts +2 -1
  72. package/dist/providers/bunny/provider.js +8 -0
  73. package/dist/providers/bunny/provider.js.map +1 -1
  74. package/dist/providers/cloudflare/provider.d.ts +2 -1
  75. package/dist/providers/cloudflare/provider.js +11 -0
  76. package/dist/providers/cloudflare/provider.js.map +1 -1
  77. package/dist/providers/mux/provider.d.ts +2 -1
  78. package/dist/providers/mux/provider.js +9 -0
  79. package/dist/providers/mux/provider.js.map +1 -1
  80. package/dist/service.d.ts +28 -1
  81. package/dist/service.js +114 -4
  82. package/dist/service.js.map +1 -1
  83. package/dist/types.d.ts +155 -1
  84. package/dist/types.js +1 -1
  85. package/dist/types.js.map +1 -1
  86. package/package.json +2 -1
@@ -0,0 +1,30 @@
1
+ import type { CreateUploadResult } from '../types.js';
2
+ import type { PluginApi } from './api.js';
3
+ export type VideoUploadOptions = {
4
+ /** Replace the video of this document instead of creating one. */
5
+ id?: number | string;
6
+ /** Provider id for a new document. Default: the plugin's default provider. */
7
+ provider?: string;
8
+ title?: string;
9
+ };
10
+ export type VideoUploadCallbacks = {
11
+ /** The document and provider upload exist; the file starts sending. */
12
+ onCreated?: (result: CreateUploadResult) => void;
13
+ onProgress?: (loaded: number, total: number) => void;
14
+ };
15
+ export type VideoUploadController = {
16
+ /** Stops the upload for good; `done` rejects with "Upload cancelled". */
17
+ cancel(): void;
18
+ /** Whether `pause()` works for this upload's protocol (all but one-shot `post`). Known once created. */
19
+ readonly canPause: boolean;
20
+ /** Resolves when the file has reached the provider (processing continues there). */
21
+ readonly done: Promise<CreateUploadResult>;
22
+ pause(): void;
23
+ resume(): void;
24
+ };
25
+ /**
26
+ * Uploads a file from the browser straight to the video provider, without React: creates the document
27
+ * through `POST /upload`, then sends the file with whichever protocol the provider chose (a multipart
28
+ * `post`, resumable `tus` or `put-chunked`). `tus-js-client` is loaded only when a tus upload starts.
29
+ */
30
+ export declare const uploadVideoFile: (api: PluginApi, file: File, options?: VideoUploadOptions, callbacks?: VideoUploadCallbacks) => VideoUploadController;
@@ -0,0 +1,140 @@
1
+ 'use client';
2
+ import { ChunkedUpload } from './chunkedUpload.js';
3
+ const cancelled = ()=>new Error('Upload cancelled');
4
+ /**
5
+ * Uploads a file from the browser straight to the video provider, without React: creates the document
6
+ * through `POST /upload`, then sends the file with whichever protocol the provider chose (a multipart
7
+ * `post`, resumable `tus` or `put-chunked`). `tus-js-client` is loaded only when a tus upload starts.
8
+ */ export const uploadVideoFile = (api, file, options = {}, callbacks = {})=>{
9
+ let pausable = null;
10
+ let abort = null;
11
+ let isCancelled = false;
12
+ let paused = false;
13
+ let canPause = false;
14
+ const run = async ()=>{
15
+ const result = await api.createUpload({
16
+ filename: file.name,
17
+ id: options.id,
18
+ provider: options.provider,
19
+ size: file.size,
20
+ title: options.title,
21
+ type: file.type || undefined
22
+ });
23
+ if (isCancelled) {
24
+ throw cancelled();
25
+ }
26
+ callbacks.onCreated?.(result);
27
+ const onProgress = (loaded, total)=>callbacks.onProgress?.(loaded, total);
28
+ const upload = result.upload;
29
+ if (upload.protocol === 'tus') {
30
+ const { Upload } = await import('tus-js-client');
31
+ await new Promise((resolve, reject)=>{
32
+ const tus = new Upload(file, {
33
+ // tus-js-client casts the option with Number(), so an explicit undefined would become NaN
34
+ // (empty PATCH requests forever). Leave it out to keep the default: one request.
35
+ ...upload.chunkSize ? {
36
+ chunkSize: upload.chunkSize
37
+ } : {},
38
+ endpoint: upload.endpoint,
39
+ headers: upload.headers,
40
+ metadata: {
41
+ filename: file.name,
42
+ filetype: file.type,
43
+ ...upload.metadata
44
+ },
45
+ onError: reject,
46
+ onProgress,
47
+ onSuccess: ()=>resolve(),
48
+ retryDelays: [
49
+ 0,
50
+ 1000,
51
+ 3000,
52
+ 5000,
53
+ 10000
54
+ ],
55
+ uploadSize: file.size,
56
+ uploadUrl: upload.uploadUrl
57
+ });
58
+ pausable = {
59
+ pause: ()=>void tus.abort(),
60
+ resume: ()=>tus.start()
61
+ };
62
+ abort = ()=>{
63
+ // Ask the server to discard the partial upload; not every tus server supports termination.
64
+ tus.abort(true).catch(()=>undefined);
65
+ reject(cancelled());
66
+ };
67
+ canPause = true;
68
+ if (!paused) {
69
+ tus.start();
70
+ }
71
+ });
72
+ } else if (upload.protocol === 'put-chunked') {
73
+ const chunked = new ChunkedUpload({
74
+ chunkSize: upload.chunkSize,
75
+ file,
76
+ headers: upload.headers,
77
+ onProgress,
78
+ url: upload.url
79
+ });
80
+ await new Promise((resolve, reject)=>{
81
+ const start = ()=>chunked.start().then(resolve, (err)=>{
82
+ // A pause aborts the request in flight; only real failures (or a cancel) end the upload.
83
+ if (isCancelled || err.name !== 'AbortError') {
84
+ reject(isCancelled ? cancelled() : err);
85
+ }
86
+ });
87
+ pausable = {
88
+ pause: ()=>chunked.pause(),
89
+ resume: ()=>void start()
90
+ };
91
+ abort = ()=>{
92
+ chunked.pause();
93
+ reject(cancelled());
94
+ };
95
+ canPause = true;
96
+ if (!paused) {
97
+ void start();
98
+ }
99
+ });
100
+ } else {
101
+ await new Promise((resolve, reject)=>{
102
+ const xhr = new XMLHttpRequest();
103
+ abort = ()=>xhr.abort();
104
+ xhr.upload.onprogress = (e)=>e.lengthComputable && onProgress(e.loaded, e.total);
105
+ xhr.onload = ()=>xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (HTTP ${xhr.status})`));
106
+ xhr.onerror = ()=>reject(new Error('Network error during upload'));
107
+ xhr.onabort = ()=>reject(cancelled());
108
+ const form = new FormData();
109
+ form.append(upload.fieldName ?? 'file', file, file.name);
110
+ xhr.open('POST', upload.url);
111
+ xhr.send(form);
112
+ });
113
+ }
114
+ return result;
115
+ };
116
+ const done = run().finally(()=>{
117
+ pausable = null;
118
+ abort = null;
119
+ });
120
+ return {
121
+ cancel () {
122
+ isCancelled = true;
123
+ abort?.();
124
+ },
125
+ get canPause () {
126
+ return canPause;
127
+ },
128
+ done,
129
+ pause () {
130
+ paused = true;
131
+ pausable?.pause();
132
+ },
133
+ resume () {
134
+ paused = false;
135
+ pausable?.resume();
136
+ }
137
+ };
138
+ };
139
+
140
+ //# sourceMappingURL=uploadFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/components/uploadFile.ts"],"sourcesContent":["'use client'\n\nimport type { Upload as TusUpload } from 'tus-js-client'\n\nimport type { CreateUploadResult } from '../types.js'\nimport type { PluginApi } from './api.js'\n\nimport { ChunkedUpload } from './chunkedUpload.js'\n\nexport type VideoUploadOptions = {\n /** Replace the video of this document instead of creating one. */\n id?: number | string\n /** Provider id for a new document. Default: the plugin's default provider. */\n provider?: string\n title?: string\n}\n\nexport type VideoUploadCallbacks = {\n /** The document and provider upload exist; the file starts sending. */\n onCreated?: (result: CreateUploadResult) => void\n onProgress?: (loaded: number, total: number) => void\n}\n\nexport type VideoUploadController = {\n /** Stops the upload for good; `done` rejects with \"Upload cancelled\". */\n cancel(): void\n /** Whether `pause()` works for this upload's protocol (all but one-shot `post`). Known once created. */\n readonly canPause: boolean\n /** Resolves when the file has reached the provider (processing continues there). */\n readonly done: Promise<CreateUploadResult>\n pause(): void\n resume(): void\n}\n\nconst cancelled = () => new Error('Upload cancelled')\n\n/**\n * Uploads a file from the browser straight to the video provider, without React: creates the document\n * through `POST /upload`, then sends the file with whichever protocol the provider chose (a multipart\n * `post`, resumable `tus` or `put-chunked`). `tus-js-client` is loaded only when a tus upload starts.\n */\nexport const uploadVideoFile = (\n api: PluginApi,\n file: File,\n options: VideoUploadOptions = {},\n callbacks: VideoUploadCallbacks = {},\n): VideoUploadController => {\n let pausable: null | { pause(): void; resume(): void } = null\n let abort: null | (() => void) = null\n let isCancelled = false\n let paused = false\n let canPause = false\n\n const run = async (): Promise<CreateUploadResult> => {\n const result = await api.createUpload({\n filename: file.name,\n id: options.id,\n provider: options.provider,\n size: file.size,\n title: options.title,\n type: file.type || undefined,\n })\n if (isCancelled) {\n throw cancelled()\n }\n callbacks.onCreated?.(result)\n const onProgress = (loaded: number, total: number) => callbacks.onProgress?.(loaded, total)\n const upload = result.upload\n\n if (upload.protocol === 'tus') {\n const { Upload } = await import('tus-js-client')\n await new Promise<void>((resolve, reject) => {\n const tus: TusUpload = new Upload(file, {\n // tus-js-client casts the option with Number(), so an explicit undefined would become NaN\n // (empty PATCH requests forever). Leave it out to keep the default: one request.\n ...(upload.chunkSize ? { chunkSize: upload.chunkSize } : {}),\n endpoint: upload.endpoint,\n headers: upload.headers,\n metadata: { filename: file.name, filetype: file.type, ...upload.metadata },\n onError: reject,\n onProgress,\n onSuccess: () => resolve(),\n retryDelays: [0, 1000, 3000, 5000, 10000],\n uploadSize: file.size,\n uploadUrl: upload.uploadUrl,\n })\n pausable = { pause: () => void tus.abort(), resume: () => tus.start() }\n abort = () => {\n // Ask the server to discard the partial upload; not every tus server supports termination.\n tus.abort(true).catch(() => undefined)\n reject(cancelled())\n }\n canPause = true\n if (!paused) {\n tus.start()\n }\n })\n } else if (upload.protocol === 'put-chunked') {\n const chunked = new ChunkedUpload({ chunkSize: upload.chunkSize, file, headers: upload.headers, onProgress, url: upload.url })\n await new Promise<void>((resolve, reject) => {\n const start = () =>\n chunked.start().then(resolve, (err: Error) => {\n // A pause aborts the request in flight; only real failures (or a cancel) end the upload.\n if (isCancelled || err.name !== 'AbortError') {\n reject(isCancelled ? cancelled() : err)\n }\n })\n pausable = { pause: () => chunked.pause(), resume: () => void start() }\n abort = () => {\n chunked.pause()\n reject(cancelled())\n }\n canPause = true\n if (!paused) {\n void start()\n }\n })\n } else {\n await new Promise<void>((resolve, reject) => {\n const xhr = new XMLHttpRequest()\n abort = () => xhr.abort()\n xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(e.loaded, e.total)\n xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (HTTP ${xhr.status})`)))\n xhr.onerror = () => reject(new Error('Network error during upload'))\n xhr.onabort = () => reject(cancelled())\n const form = new FormData()\n form.append(upload.fieldName ?? 'file', file, file.name)\n xhr.open('POST', upload.url)\n xhr.send(form)\n })\n }\n return result\n }\n\n const done = run().finally(() => {\n pausable = null\n abort = null\n })\n\n return {\n cancel() {\n isCancelled = true\n abort?.()\n },\n get canPause() {\n return canPause\n },\n done,\n pause() {\n paused = true\n pausable?.pause()\n },\n resume() {\n paused = false\n pausable?.resume()\n },\n }\n}\n"],"names":["ChunkedUpload","cancelled","Error","uploadVideoFile","api","file","options","callbacks","pausable","abort","isCancelled","paused","canPause","run","result","createUpload","filename","name","id","provider","size","title","type","undefined","onCreated","onProgress","loaded","total","upload","protocol","Upload","Promise","resolve","reject","tus","chunkSize","endpoint","headers","metadata","filetype","onError","onSuccess","retryDelays","uploadSize","uploadUrl","pause","resume","start","catch","chunked","url","then","err","xhr","XMLHttpRequest","onprogress","e","lengthComputable","onload","status","onerror","onabort","form","FormData","append","fieldName","open","send","done","finally","cancel"],"mappings":"AAAA;AAOA,SAASA,aAAa,QAAQ,qBAAoB;AA2BlD,MAAMC,YAAY,IAAM,IAAIC,MAAM;AAElC;;;;CAIC,GACD,OAAO,MAAMC,kBAAkB,CAC7BC,KACAC,MACAC,UAA8B,CAAC,CAAC,EAChCC,YAAkC,CAAC,CAAC;IAEpC,IAAIC,WAAqD;IACzD,IAAIC,QAA6B;IACjC,IAAIC,cAAc;IAClB,IAAIC,SAAS;IACb,IAAIC,WAAW;IAEf,MAAMC,MAAM;QACV,MAAMC,SAAS,MAAMV,IAAIW,YAAY,CAAC;YACpCC,UAAUX,KAAKY,IAAI;YACnBC,IAAIZ,QAAQY,EAAE;YACdC,UAAUb,QAAQa,QAAQ;YAC1BC,MAAMf,KAAKe,IAAI;YACfC,OAAOf,QAAQe,KAAK;YACpBC,MAAMjB,KAAKiB,IAAI,IAAIC;QACrB;QACA,IAAIb,aAAa;YACf,MAAMT;QACR;QACAM,UAAUiB,SAAS,GAAGV;QACtB,MAAMW,aAAa,CAACC,QAAgBC,QAAkBpB,UAAUkB,UAAU,GAAGC,QAAQC;QACrF,MAAMC,SAASd,OAAOc,MAAM;QAE5B,IAAIA,OAAOC,QAAQ,KAAK,OAAO;YAC7B,MAAM,EAAEC,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC;YAChC,MAAM,IAAIC,QAAc,CAACC,SAASC;gBAChC,MAAMC,MAAiB,IAAIJ,OAAOzB,MAAM;oBACtC,0FAA0F;oBAC1F,iFAAiF;oBACjF,GAAIuB,OAAOO,SAAS,GAAG;wBAAEA,WAAWP,OAAOO,SAAS;oBAAC,IAAI,CAAC,CAAC;oBAC3DC,UAAUR,OAAOQ,QAAQ;oBACzBC,SAAST,OAAOS,OAAO;oBACvBC,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hB,QAAc,CAACC,SAASC;gBAChC,MAAMoB,MAAM,IAAIC;gBAChB7C,QAAQ,IAAM4C,IAAI5C,KAAK;gBACvB4C,IAAIzB,MAAM,CAAC2B,UAAU,GAAG,CAACC,IAAMA,EAAEC,gBAAgB,IAAIhC,WAAW+B,EAAE9B,MAAM,EAAE8B,EAAE7B,KAAK;gBACjF0B,IAAIK,MAAM,GAAG,IAAOL,IAAIM,MAAM,IAAI,OAAON,IAAIM,MAAM,GAAG,MAAM3B,YAAYC,OAAO,IAAI/B,MAAM,CAAC,oBAAoB,EAAEmD,IAAIM,MAAM,CAAC,CAAC,CAAC;gBAC7HN,IAAIO,OAAO,GAAG,IAAM3B,OAAO,IAAI/B,MAAM;gBACrCmD,IAAIQ,OAAO,GAAG,IAAM5B,OAAOhC;gBAC3B,MAAM6D,OAAO,IAAIC;gBACjBD,KAAKE,MAAM,CAACpC,OAAOqC,SAAS,IAAI,QAAQ5D,MAAMA,KAAKY,IAAI;gBACvDoC,IAAIa,IAAI,CAAC,QAAQtC,OAAOsB,GAAG;gBAC3BG,IAAIc,IAAI,CAACL;YACX;QACF;QACA,OAAOhD;IACT;IAEA,MAAMsD,OAAOvD,MAAMwD,OAAO,CAAC;QACzB7D,WAAW;QACXC,QAAQ;IACV;IAEA,OAAO;QACL6D;YACE5D,cAAc;YACdD;QACF;QACA,IAAIG;YACF,OAAOA;QACT;QACAwD;QACAvB;YACElC,SAAS;YACTH,UAAUqC;QACZ;QACAC;YACEnC,SAAS;YACTH,UAAUsC;QACZ;IACF;AACF,EAAC"}
@@ -14,6 +14,7 @@ export declare const usePluginApi: (collectionSlug: string) => {
14
14
  provider?: string;
15
15
  size: number;
16
16
  title?: string;
17
+ type?: string;
17
18
  }) => Promise<import("../types.js").CreateUploadResult>;
18
19
  deleteCaption: (id: number | string, language: string) => Promise<{
19
20
  captions: import("../index.js").CaptionTrack[];
@@ -24,6 +25,7 @@ export declare const usePluginApi: (collectionSlug: string) => {
24
25
  downloads: (id: number | string) => Promise<{
25
26
  downloads: import("../index.js").Downloads;
26
27
  }>;
28
+ get: (id: number | string) => Promise<import("../types.js").VideoDoc>;
27
29
  generateCaption: (id: number | string, language: string) => Promise<{
28
30
  captions: import("../index.js").CaptionTrack[];
29
31
  }>;
@@ -34,6 +36,9 @@ export declare const usePluginApi: (collectionSlug: string) => {
34
36
  sync: (id: number | string) => Promise<{
35
37
  doc: import("../types.js").VideoDoc;
36
38
  }>;
39
+ webhookStatus: () => Promise<{
40
+ providers: import("../types.js").WebhookStatus[];
41
+ }>;
37
42
  uploadCaption: (id: number | string, language: string, file: File) => Promise<{
38
43
  captions: import("../index.js").CaptionTrack[];
39
44
  }>;
@@ -0,0 +1,35 @@
1
+ import type { CreateUploadResult } from '../types.js';
2
+ import type { PluginApi } from './api.js';
3
+ export type QueuedUploadStatus = 'cancelled' | 'done' | 'error' | 'paused' | 'queued' | 'uploading';
4
+ export type QueuedUpload = {
5
+ error?: string;
6
+ file: File;
7
+ /** Stable key for lists. */
8
+ key: string;
9
+ loaded: number;
10
+ /** Set once the document exists. */
11
+ result?: CreateUploadResult;
12
+ status: QueuedUploadStatus;
13
+ total: number;
14
+ };
15
+ export type UploadQueueOptions = {
16
+ /** Uploads running at once. Default 3. */
17
+ concurrency?: number;
18
+ /** Called when a file has reached the provider. */
19
+ onUploaded?: (result: CreateUploadResult, file: File) => void;
20
+ /** Provider id for the new documents. Default: the plugin's default provider. */
21
+ provider?: string;
22
+ };
23
+ /**
24
+ * Uploads several files, `concurrency` at a time, each to its own new document (titled after the
25
+ * file). Every item can be paused, resumed, cancelled and retried on its own.
26
+ */
27
+ export declare const useUploadQueue: (api: PluginApi, { concurrency, onUploaded, provider }?: UploadQueueOptions) => {
28
+ add: (files: File[] | FileList) => void;
29
+ cancel: (key: string) => void;
30
+ clearFinished: () => void;
31
+ items: QueuedUpload[];
32
+ pause: (key: string) => void;
33
+ resume: (key: string) => void;
34
+ retry: (key: string) => void;
35
+ };
@@ -0,0 +1,135 @@
1
+ 'use client';
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import { uploadVideoFile } from './uploadFile.js';
4
+ let nextKey = 0;
5
+ /**
6
+ * Uploads several files, `concurrency` at a time, each to its own new document (titled after the
7
+ * file). Every item can be paused, resumed, cancelled and retried on its own.
8
+ */ export const useUploadQueue = (api, { concurrency = 3, onUploaded, provider } = {})=>{
9
+ const [items, setItems] = useState([]);
10
+ const controllers = useRef(new Map());
11
+ const onUploadedRef = useRef(onUploaded);
12
+ onUploadedRef.current = onUploaded;
13
+ const patch = useCallback((key, change)=>{
14
+ setItems((prev)=>prev.map((item)=>item.key === key ? {
15
+ ...item,
16
+ ...change
17
+ } : item));
18
+ }, []);
19
+ const begin = useCallback((item)=>{
20
+ const controller = uploadVideoFile(api, item.file, {
21
+ provider
22
+ }, {
23
+ onCreated: (result)=>patch(item.key, {
24
+ result
25
+ }),
26
+ onProgress: (loaded, total)=>patch(item.key, {
27
+ loaded,
28
+ total
29
+ })
30
+ });
31
+ controllers.current.set(item.key, controller);
32
+ controller.done.then((result)=>{
33
+ patch(item.key, {
34
+ loaded: item.file.size,
35
+ result,
36
+ status: 'done'
37
+ });
38
+ onUploadedRef.current?.(result, item.file);
39
+ }, (err)=>{
40
+ setItems((prev)=>prev.map((i)=>i.key === item.key && i.status !== 'cancelled' ? {
41
+ ...i,
42
+ error: err.message || 'Upload failed',
43
+ status: 'error'
44
+ } : i));
45
+ });
46
+ void controller.done.catch(()=>undefined).finally(()=>controllers.current.delete(item.key));
47
+ }, [
48
+ api,
49
+ patch,
50
+ provider
51
+ ]);
52
+ // Start queued items while fewer than `concurrency` are running (paused uploads keep their slot).
53
+ useEffect(()=>{
54
+ const active = items.filter((i)=>i.status === 'uploading' || i.status === 'paused').length;
55
+ const free = Math.max(0, concurrency - active);
56
+ const next = items.filter((i)=>i.status === 'queued').slice(0, free);
57
+ if (next.length === 0) {
58
+ return;
59
+ }
60
+ const keys = new Set(next.map((i)=>i.key));
61
+ setItems((prev)=>prev.map((i)=>keys.has(i.key) ? {
62
+ ...i,
63
+ status: 'uploading'
64
+ } : i));
65
+ next.forEach(begin);
66
+ }, [
67
+ begin,
68
+ concurrency,
69
+ items
70
+ ]);
71
+ // Stop everything still running when the component goes away.
72
+ useEffect(()=>{
73
+ const running = controllers.current;
74
+ return ()=>running.forEach((c)=>c.cancel());
75
+ }, []);
76
+ const add = useCallback((files)=>{
77
+ const added = Array.from(files).map((file)=>({
78
+ file,
79
+ key: `upload-${++nextKey}`,
80
+ loaded: 0,
81
+ status: 'queued',
82
+ total: file.size
83
+ }));
84
+ setItems((prev)=>[
85
+ ...prev,
86
+ ...added
87
+ ]);
88
+ }, []);
89
+ const pause = useCallback((key)=>{
90
+ controllers.current.get(key)?.pause();
91
+ patch(key, {
92
+ status: 'paused'
93
+ });
94
+ }, [
95
+ patch
96
+ ]);
97
+ const resume = useCallback((key)=>{
98
+ controllers.current.get(key)?.resume();
99
+ patch(key, {
100
+ status: 'uploading'
101
+ });
102
+ }, [
103
+ patch
104
+ ]);
105
+ const cancel = useCallback((key)=>{
106
+ controllers.current.get(key)?.cancel();
107
+ patch(key, {
108
+ status: 'cancelled'
109
+ });
110
+ }, [
111
+ patch
112
+ ]);
113
+ /** Uploads a failed or cancelled file again, as a new document. */ const retry = useCallback((key)=>patch(key, {
114
+ error: undefined,
115
+ loaded: 0,
116
+ result: undefined,
117
+ status: 'queued'
118
+ }), [
119
+ patch
120
+ ]);
121
+ /** Removes finished, failed and cancelled items from the list. */ const clearFinished = useCallback(()=>{
122
+ setItems((prev)=>prev.filter((i)=>i.status === 'queued' || i.status === 'uploading' || i.status === 'paused'));
123
+ }, []);
124
+ return {
125
+ add,
126
+ cancel,
127
+ clearFinished,
128
+ items,
129
+ pause,
130
+ resume,
131
+ retry
132
+ };
133
+ };
134
+
135
+ //# sourceMappingURL=useUploadQueue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/components/useUploadQueue.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport type { CreateUploadResult } from '../types.js'\nimport type { PluginApi } from './api.js'\n\nimport { uploadVideoFile, type VideoUploadController } from './uploadFile.js'\n\nexport type QueuedUploadStatus = 'cancelled' | 'done' | 'error' | 'paused' | 'queued' | 'uploading'\n\nexport type QueuedUpload = {\n error?: string\n file: File\n /** Stable key for lists. */\n key: string\n loaded: number\n /** Set once the document exists. */\n result?: CreateUploadResult\n status: QueuedUploadStatus\n total: number\n}\n\nexport type UploadQueueOptions = {\n /** Uploads running at once. Default 3. */\n concurrency?: number\n /** Called when a file has reached the provider. */\n onUploaded?: (result: CreateUploadResult, file: File) => void\n /** Provider id for the new documents. Default: the plugin's default provider. */\n provider?: string\n}\n\nlet nextKey = 0\n\n/**\n * Uploads several files, `concurrency` at a time, each to its own new document (titled after the\n * file). Every item can be paused, resumed, cancelled and retried on its own.\n */\nexport const useUploadQueue = (api: PluginApi, { concurrency = 3, onUploaded, provider }: UploadQueueOptions = {}) => {\n const [items, setItems] = useState<QueuedUpload[]>([])\n const controllers = useRef(new Map<string, VideoUploadController>())\n const onUploadedRef = useRef(onUploaded)\n onUploadedRef.current = onUploaded\n\n const patch = useCallback((key: string, change: Partial<QueuedUpload>) => {\n setItems((prev) => prev.map((item) => (item.key === key ? { ...item, ...change } : item)))\n }, [])\n\n const begin = useCallback(\n (item: QueuedUpload) => {\n const controller = uploadVideoFile(\n api,\n item.file,\n { provider },\n {\n onCreated: (result) => patch(item.key, { result }),\n onProgress: (loaded, total) => patch(item.key, { loaded, total }),\n },\n )\n controllers.current.set(item.key, controller)\n controller.done.then(\n (result) => {\n patch(item.key, { loaded: item.file.size, result, status: 'done' })\n onUploadedRef.current?.(result, item.file)\n },\n (err: Error) => {\n setItems((prev) =>\n prev.map((i) =>\n i.key === item.key && i.status !== 'cancelled' ? { ...i, error: err.message || 'Upload failed', status: 'error' } : i,\n ),\n )\n },\n )\n void controller.done.catch(() => undefined).finally(() => controllers.current.delete(item.key))\n },\n [api, patch, provider],\n )\n\n // Start queued items while fewer than `concurrency` are running (paused uploads keep their slot).\n useEffect(() => {\n const active = items.filter((i) => i.status === 'uploading' || i.status === 'paused').length\n const free = Math.max(0, concurrency - active)\n const next = items.filter((i) => i.status === 'queued').slice(0, free)\n if (next.length === 0) {\n return\n }\n const keys = new Set(next.map((i) => i.key))\n setItems((prev) => prev.map((i) => (keys.has(i.key) ? { ...i, status: 'uploading' } : i)))\n next.forEach(begin)\n }, [begin, concurrency, items])\n\n // Stop everything still running when the component goes away.\n useEffect(() => {\n const running = controllers.current\n return () => running.forEach((c) => c.cancel())\n }, [])\n\n const add = useCallback((files: File[] | FileList) => {\n const added = Array.from(files).map(\n (file): QueuedUpload => ({ file, key: `upload-${++nextKey}`, loaded: 0, status: 'queued', total: file.size }),\n )\n setItems((prev) => [...prev, ...added])\n }, [])\n\n const pause = useCallback(\n (key: string) => {\n controllers.current.get(key)?.pause()\n patch(key, { status: 'paused' })\n },\n [patch],\n )\n\n const resume = useCallback(\n (key: string) => {\n controllers.current.get(key)?.resume()\n patch(key, { status: 'uploading' })\n },\n [patch],\n )\n\n const cancel = useCallback(\n (key: string) => {\n controllers.current.get(key)?.cancel()\n patch(key, { status: 'cancelled' })\n },\n [patch],\n )\n\n /** Uploads a failed or cancelled file again, as a new document. */\n const retry = useCallback(\n (key: string) => patch(key, { error: undefined, loaded: 0, result: undefined, status: 'queued' }),\n [patch],\n )\n\n /** Removes finished, failed and cancelled items from the list. */\n const clearFinished = useCallback(() => {\n setItems((prev) => prev.filter((i) => i.status === 'queued' || i.status === 'uploading' || i.status === 'paused'))\n }, [])\n\n return { add, cancel, clearFinished, items, pause, resume, retry }\n}\n"],"names":["useCallback","useEffect","useRef","useState","uploadVideoFile","nextKey","useUploadQueue","api","concurrency","onUploaded","provider","items","setItems","controllers","Map","onUploadedRef","current","patch","key","change","prev","map","item","begin","controller","file","onCreated","result","onProgress","loaded","total","set","done","then","size","status","err","i","error","message","catch","undefined","finally","delete","active","filter","length","free","Math","max","next","slice","keys","Set","has","forEach","running","c","cancel","add","files","added","Array","from","pause","get","resume","retry","clearFinished"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAKhE,SAASC,eAAe,QAAoC,kBAAiB;AAyB7E,IAAIC,UAAU;AAEd;;;CAGC,GACD,OAAO,MAAMC,iBAAiB,CAACC,KAAgB,EAAEC,cAAc,CAAC,EAAEC,UAAU,EAAEC,QAAQ,EAAsB,GAAG,CAAC,CAAC;IAC/G,MAAM,CAACC,OAAOC,SAAS,GAAGT,SAAyB,EAAE;IACrD,MAAMU,cAAcX,OAAO,IAAIY;IAC/B,MAAMC,gBAAgBb,OAAOO;IAC7BM,cAAcC,OAAO,GAAGP;IAExB,MAAMQ,QAAQjB,YAAY,CAACkB,KAAaC;QACtCP,SAAS,CAACQ,OAASA,KAAKC,GAAG,CAAC,CAACC,OAAUA,KAAKJ,GAAG,KAAKA,MAAM;oBAAE,GAAGI,IAAI;oBAAE,GAAGH,MAAM;gBAAC,IAAIG;IACrF,GAAG,EAAE;IAEL,MAAMC,QAAQvB,YACZ,CAACsB;QACC,MAAME,aAAapB,gBACjBG,KACAe,KAAKG,IAAI,EACT;YAAEf;QAAS,GACX;YACEgB,WAAW,CAACC,SAAWV,MAAMK,KAAKJ,GAAG,EAAE;oBAAES;gBAAO;YAChDC,YAAY,CAACC,QAAQC,QAAUb,MAAMK,KAAKJ,GAAG,EAAE;oBAAEW;oBAAQC;gBAAM;QACjE;QAEFjB,YAAYG,OAAO,CAACe,GAAG,CAACT,KAAKJ,GAAG,EAAEM;QAClCA,WAAWQ,IAAI,CAACC,IAAI,CAClB,CAACN;YACCV,MAAMK,KAAKJ,GAAG,EAAE;gBAAEW,QAAQP,KAAKG,IAAI,CAACS,IAAI;gBAAEP;gBAAQQ,QAAQ;YAAO;YACjEpB,cAAcC,OAAO,GAAGW,QAAQL,KAAKG,IAAI;QAC3C,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types.js';
2
2
  import type { PluginApi } from './api.js';
3
+ import { type VideoUploadOptions } from './uploadFile.js';
3
4
  export type UploadState = {
4
5
  error: string;
5
6
  phase: 'error';
@@ -19,8 +20,7 @@ export type UploadState = {
19
20
  };
20
21
  /**
21
22
  * Uploads a file directly from the browser to the video provider, with whichever protocol the provider
22
- * chose: a multipart `post`, resumable `tus`, or `put-chunked`. `tus-js-client` is only loaded when a
23
- * tus upload starts.
23
+ * chose: a multipart `post`, resumable `tus` or `put-chunked` (see `uploadVideoFile`), as React state.
24
24
  */
25
25
  export declare const useVideoUpload: (api: PluginApi) => {
26
26
  cancel: () => void;
@@ -28,10 +28,6 @@ export declare const useVideoUpload: (api: PluginApi) => {
28
28
  pause: () => void;
29
29
  reset: () => void;
30
30
  resume: () => void;
31
- start: (file: File, options?: {
32
- id?: number | string;
33
- provider?: string;
34
- title?: string;
35
- }) => Promise<CreateUploadResult | null>;
31
+ start: (file: File, options?: VideoUploadOptions) => Promise<CreateUploadResult | null>;
36
32
  state: UploadState;
37
33
  };
@@ -1,130 +1,40 @@
1
1
  'use client';
2
2
  import { useCallback, useRef, useState } from 'react';
3
- import { ChunkedUpload } from './chunkedUpload.js';
3
+ import { uploadVideoFile } from './uploadFile.js';
4
4
  /**
5
5
  * Uploads a file directly from the browser to the video provider, with whichever protocol the provider
6
- * chose: a multipart `post`, resumable `tus`, or `put-chunked`. `tus-js-client` is only loaded when a
7
- * tus upload starts.
6
+ * chose: a multipart `post`, resumable `tus` or `put-chunked` (see `uploadVideoFile`), as React state.
8
7
  */ export const useVideoUpload = (api)=>{
9
8
  const [state, setState] = useState({
10
9
  phase: 'idle'
11
10
  });
12
- const pausableRef = useRef(null);
13
- const cancelRef = useRef(null);
11
+ const controllerRef = useRef(null);
14
12
  const start = useCallback(async (file, options = {})=>{
15
13
  setState({
16
14
  phase: 'preparing'
17
15
  });
18
- let result;
16
+ const controller = uploadVideoFile(api, file, options, {
17
+ onCreated: (result)=>setState({
18
+ loaded: 0,
19
+ paused: false,
20
+ phase: 'uploading',
21
+ result,
22
+ total: file.size
23
+ }),
24
+ onProgress: (loaded, total)=>setState((prev)=>prev.phase === 'uploading' ? {
25
+ ...prev,
26
+ loaded,
27
+ total
28
+ } : prev)
29
+ });
30
+ controllerRef.current = controller;
19
31
  try {
20
- result = await api.createUpload({
21
- filename: file.name,
22
- id: options.id,
23
- provider: options.provider,
24
- size: file.size,
25
- title: options.title
26
- });
27
- } catch (err) {
32
+ const result = await controller.done;
28
33
  setState({
29
- error: err.message,
30
- phase: 'error'
34
+ phase: 'done',
35
+ result
31
36
  });
32
- return null;
33
- }
34
- setState({
35
- loaded: 0,
36
- paused: false,
37
- phase: 'uploading',
38
- result,
39
- total: file.size
40
- });
41
- const onProgress = (loaded, total)=>setState((prev)=>prev.phase === 'uploading' ? {
42
- ...prev,
43
- loaded,
44
- total
45
- } : prev);
46
- const upload = result.upload;
47
- try {
48
- if (upload.protocol === 'tus') {
49
- const { Upload } = await import('tus-js-client');
50
- await new Promise((resolve, reject)=>{
51
- const tus = new Upload(file, {
52
- // tus-js-client casts the option with Number(), so an explicit undefined would become NaN
53
- // (empty PATCH requests forever). Leave it out to keep the default: one request.
54
- ...upload.chunkSize ? {
55
- chunkSize: upload.chunkSize
56
- } : {},
57
- endpoint: upload.endpoint,
58
- headers: upload.headers,
59
- metadata: {
60
- filename: file.name,
61
- filetype: file.type,
62
- ...upload.metadata
63
- },
64
- onError: reject,
65
- onProgress,
66
- onSuccess: ()=>resolve(),
67
- retryDelays: [
68
- 0,
69
- 1000,
70
- 3000,
71
- 5000,
72
- 10000
73
- ],
74
- uploadSize: file.size,
75
- uploadUrl: upload.uploadUrl
76
- });
77
- pausableRef.current = {
78
- pause: ()=>void tus.abort(),
79
- resume: ()=>tus.start()
80
- };
81
- cancelRef.current = ()=>{
82
- // Ask the server to discard the partial upload; not every tus server supports termination.
83
- tus.abort(true).catch(()=>undefined);
84
- reject(new Error('Upload cancelled'));
85
- };
86
- tus.start();
87
- });
88
- } else if (upload.protocol === 'put-chunked') {
89
- const chunked = new ChunkedUpload({
90
- chunkSize: upload.chunkSize,
91
- file,
92
- headers: upload.headers,
93
- onProgress,
94
- url: upload.url
95
- });
96
- await new Promise((resolve, reject)=>{
97
- let cancelled = false;
98
- const run = ()=>chunked.start().then(resolve, (err)=>{
99
- // A pause aborts the request in flight; only real failures (or a cancel) end the upload.
100
- if (cancelled || err.name !== 'AbortError') {
101
- reject(cancelled ? new Error('Upload cancelled') : err);
102
- }
103
- });
104
- pausableRef.current = {
105
- pause: ()=>chunked.pause(),
106
- resume: ()=>void run()
107
- };
108
- cancelRef.current = ()=>{
109
- cancelled = true;
110
- chunked.pause();
111
- };
112
- void run();
113
- });
114
- } else {
115
- await new Promise((resolve, reject)=>{
116
- const xhr = new XMLHttpRequest();
117
- cancelRef.current = ()=>xhr.abort();
118
- xhr.upload.onprogress = (e)=>e.lengthComputable && onProgress(e.loaded, e.total);
119
- xhr.onload = ()=>xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (HTTP ${xhr.status})`));
120
- xhr.onerror = ()=>reject(new Error('Network error during upload'));
121
- xhr.onabort = ()=>reject(new Error('Upload cancelled'));
122
- const form = new FormData();
123
- form.append(upload.fieldName ?? 'file', file, file.name);
124
- xhr.open('POST', upload.url);
125
- xhr.send(form);
126
- });
127
- }
37
+ return result;
128
38
  } catch (err) {
129
39
  setState({
130
40
  error: err.message || 'Upload failed',
@@ -132,33 +42,29 @@ import { ChunkedUpload } from './chunkedUpload.js';
132
42
  });
133
43
  return null;
134
44
  } finally{
135
- pausableRef.current = null;
136
- cancelRef.current = null;
45
+ if (controllerRef.current === controller) {
46
+ controllerRef.current = null;
47
+ }
137
48
  }
138
- setState({
139
- phase: 'done',
140
- result
141
- });
142
- return result;
143
49
  }, [
144
50
  api
145
51
  ]);
146
52
  const pause = useCallback(()=>{
147
- pausableRef.current?.pause();
53
+ controllerRef.current?.pause();
148
54
  setState((prev)=>prev.phase === 'uploading' ? {
149
55
  ...prev,
150
56
  paused: true
151
57
  } : prev);
152
58
  }, []);
153
59
  const resume = useCallback(()=>{
154
- pausableRef.current?.resume();
60
+ controllerRef.current?.resume();
155
61
  setState((prev)=>prev.phase === 'uploading' ? {
156
62
  ...prev,
157
63
  paused: false
158
64
  } : prev);
159
65
  }, []);
160
66
  const cancel = useCallback(()=>{
161
- cancelRef.current?.();
67
+ controllerRef.current?.cancel();
162
68
  setState({
163
69
  error: 'Upload cancelled',
164
70
  phase: 'error'
@@ -169,7 +75,7 @@ import { ChunkedUpload } from './chunkedUpload.js';
169
75
  }), []);
170
76
  return {
171
77
  cancel,
172
- canPause: Boolean(pausableRef.current),
78
+ canPause: Boolean(controllerRef.current?.canPause),
173
79
  pause,
174
80
  reset,
175
81
  resume,