@jskit-ai/uploads-image-web 0.2.4 → 0.2.5

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.
@@ -0,0 +1,2 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Image upload</title></head><body><div id="app"></div><script type="module" src="/main.js"></script></body></html>
@@ -0,0 +1,105 @@
1
+ import { computed, createApp, h, onBeforeUnmount, onMounted, reactive, ref } from "vue";
2
+ import "../../src/client/styles/index.js";
3
+ import { createImageUploadRuntime } from "../../src/client/composables/createImageUploadRuntime.js";
4
+ import { createManagedImageAssetRuntime } from "../../src/client/composables/createManagedImageAssetRuntime.js";
5
+
6
+ let csrfToken = "";
7
+
8
+ async function readCsrfToken() {
9
+ if (!csrfToken) {
10
+ const response = await fetch("/api/session", { credentials: "include" });
11
+ csrfToken = String((await response.json()).csrfToken || "");
12
+ }
13
+ return csrfToken;
14
+ }
15
+
16
+ function renderList(className, entries) {
17
+ return h("ul", { class: className }, entries.map((entry) => h("li", entry)));
18
+ }
19
+
20
+ // users-web's account avatar: the options accountSettingsAvatarUploadRuntime.js passes, plus the asset and delete
21
+ // options the managed runtime offers for removing it.
22
+ const AvatarPage = {
23
+ setup() {
24
+ const feedback = reactive([]);
25
+ const settings = reactive({ avatarVersion: "1" });
26
+ const selectedAvatarFileName = ref("");
27
+ const avatar = createManagedImageAssetRuntime({
28
+ uploadEndpoint: "/api/settings/profile/avatar",
29
+ fieldName: "avatar",
30
+ selectedFileName: selectedAvatarFileName,
31
+ resolveRequestHeaders: async () => ({
32
+ "csrf-token": await readCsrfToken()
33
+ }),
34
+ onUploadSuccess: ({ data }) => {
35
+ settings.avatarVersion = String(data.profile.avatar.version);
36
+ },
37
+ reportFeedback: (entry) => {
38
+ feedback.push(`${entry.severity} ${entry.channel}: ${entry.message}`);
39
+ },
40
+ resolveUploadErrorMessage: ({ error, response, defaultMessage }) => {
41
+ const body = response?.body && typeof response.body === "object" ? response.body : {};
42
+ return String(body.fieldErrors?.avatar || body.error || error?.message || defaultMessage);
43
+ },
44
+ messages: {
45
+ uploadSuccess: "Avatar uploaded.",
46
+ uploadError: "Unable to upload the avatar."
47
+ },
48
+ source: "fixture.account-settings:avatar",
49
+ hasAsset: computed(() => Boolean(settings.avatarVersion)),
50
+ assetVersion: computed(() => settings.avatarVersion),
51
+ resolveAssetUrl: ({ uploadEndpoint, assetVersion }) => `${uploadEndpoint}?v=${assetVersion}`,
52
+ onDeleteSuccess: () => {
53
+ settings.avatarVersion = "";
54
+ }
55
+ });
56
+ onMounted(() => avatar.setup());
57
+ onBeforeUnmount(() => avatar.destroy());
58
+
59
+ return () => h("main", [
60
+ h("button", { type: "button", onClick: () => avatar.openEditor() }, "Change avatar"),
61
+ h("button", {
62
+ type: "button",
63
+ disabled: avatar.isDeleting.value || !avatar.hasAsset.value,
64
+ onClick: () => avatar.deleteAsset()
65
+ }, avatar.isDeleting.value ? "Removing…" : "Remove avatar"),
66
+ h("p", { class: "fixture-selected" }, `Selected: ${avatar.selectedFileName.value || "nothing"}`),
67
+ h("p", { class: "fixture-asset" }, `Asset: ${avatar.assetUrl.value || "none"}`),
68
+ renderList("fixture-feedback", feedback)
69
+ ]);
70
+ }
71
+ };
72
+
73
+ // The upload runtime as whs2 calls it: an endpoint and the four callbacks every application supplies, leaving
74
+ // onSelectedFileNameChanged, onInvalidResponse and onUnavailable to their defaults.
75
+ const SignaturePage = {
76
+ setup() {
77
+ const events = reactive([]);
78
+ const signature = createImageUploadRuntime({
79
+ endpoint: "/api/signature",
80
+ resolveRequestHeaders: async () => ({
81
+ "csrf-token": await readCsrfToken(),
82
+ "x-fixture-unset": null
83
+ }),
84
+ onUploadSuccess: ({ data, file }) => {
85
+ events.push(`success ${file.name}: ${JSON.stringify(data)}`);
86
+ },
87
+ onUploadError: ({ file, error, response }) => {
88
+ events.push(`error ${file.name} ${response?.status}: ${error.message}`);
89
+ },
90
+ onRestrictionFailed: ({ file, error }) => {
91
+ events.push(`restriction ${file?.name}: ${error.message}`);
92
+ }
93
+ });
94
+ onMounted(() => signature.setup());
95
+ onBeforeUnmount(() => signature.destroy());
96
+
97
+ return () => h("main", [
98
+ h("button", { type: "button", onClick: () => signature.openEditor() }, "Upload signature"),
99
+ renderList("fixture-events", events)
100
+ ]);
101
+ }
102
+ };
103
+
104
+ const pages = { "/avatar": AvatarPage, "/signature": SignaturePage };
105
+ createApp(pages[window.location.pathname] || { render: () => h("p", "No such fixture page.") }).mount("#app");
@@ -0,0 +1,13 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { defineConfig } from "vite";
3
+ import vue from "@vitejs/plugin-vue";
4
+
5
+ export default defineConfig({
6
+ root: fileURLToPath(new URL("./", import.meta.url)),
7
+ plugins: [vue()],
8
+ // The same pre-bundling the package's client metadata asks of an application.
9
+ optimizeDeps: {
10
+ include: ["@uppy/core", "@uppy/dashboard", "@uppy/image-editor", "@uppy/compressor", "@uppy/xhr-upload"]
11
+ },
12
+ server: { host: "127.0.0.1", strictPort: true }
13
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/uploads-image-web",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -10,11 +10,12 @@
10
10
  "./client/composables/createImageUploadRuntime": "./src/client/composables/createImageUploadRuntime.js",
11
11
  "./client/composables/createManagedImageAssetRuntime": "./src/client/composables/createManagedImageAssetRuntime.js",
12
12
  "./client/styles": "./src/client/styles/index.js",
13
+ "./client/types": "./src/client/types.js",
13
14
  "./shared": "./src/shared/index.js",
14
15
  "./locales/en.json": "./locales/en.json"
15
16
  },
16
17
  "dependencies": {
17
- "@jskit-ai/uploads-runtime": "0.2.4",
18
+ "@jskit-ai/uploads-runtime": "0.2.5",
18
19
  "@uppy/compressor": "^3.1.0",
19
20
  "@uppy/core": "^5.2.0",
20
21
  "@uppy/dashboard": "^5.1.1",
@@ -22,7 +23,7 @@
22
23
  "@uppy/xhr-upload": "^5.1.1"
23
24
  },
24
25
  "peerDependencies": {
25
- "@jskit-ai/kernel": "0.2.4",
26
+ "@jskit-ai/kernel": "0.2.5",
26
27
  "vue": "^3.5.13"
27
28
  },
28
29
  "description": "Reusable client-side image upload runtime with pre-upload image editing.",
@@ -72,6 +73,10 @@
72
73
  "subpath": "./client/styles",
73
74
  "summary": "Exports Uppy CSS side effects for image upload UIs."
74
75
  },
76
+ {
77
+ "subpath": "./client/types",
78
+ "summary": "Types of the image upload runtimes' options and results."
79
+ },
75
80
  {
76
81
  "subpath": "./shared",
77
82
  "summary": "Exports shared image upload defaults."
@@ -3,6 +3,7 @@ import Dashboard from "@uppy/dashboard";
3
3
  import ImageEditor from "@uppy/image-editor";
4
4
  import Compressor from "@uppy/compressor";
5
5
  import XHRUpload from "@uppy/xhr-upload";
6
+ import { normalizeObject } from "@jskit-ai/kernel/shared/support/normalize";
6
7
  import {
7
8
  DEFAULT_IMAGE_COMPRESSOR_OPTIONS,
8
9
  DEFAULT_IMAGE_DASHBOARD_OPTIONS,
@@ -11,13 +12,12 @@ import {
11
12
  DEFAULT_IMAGE_UPLOAD_MAX_BYTES
12
13
  } from "../../shared/imageUploadDefaults.js";
13
14
  import { parseUploadResponse } from "../support/parseUploadResponse.js";
14
- import { stopImageEditor } from "../support/stopImageEditor.js";
15
+ import { closeDashboard, stopImageEditor } from "../support/uppyPlugins.js";
15
16
  import { useJskitText } from "../i18n.js";
16
17
 
17
- function normalizeObject(value) {
18
- return value && typeof value === "object" ? value : {};
19
- }
18
+ function ignoreUploadEvent() {}
20
19
 
20
+ /** @param {import("../types.js").ImageUploadRuntimeOptions} options */
21
21
  function createImageUploadRuntime({
22
22
  endpoint = "",
23
23
  method = "POST",
@@ -31,20 +31,21 @@ function createImageUploadRuntime({
31
31
  imageEditorOptions = {},
32
32
  compressorOptions = {},
33
33
  parseResponse = parseUploadResponse,
34
- resolveRequestHeaders = null,
35
- onSelectedFileNameChanged = null,
36
- onUploadSuccess = null,
37
- onInvalidResponse = null,
38
- onUploadError = null,
39
- onRestrictionFailed = null,
40
- onUnavailable = null,
41
- dependencies = {}
42
- } = {}) {
43
- const UppyClass = dependencies.UppyClass || Uppy;
44
- const DashboardPlugin = dependencies.DashboardPlugin || Dashboard;
45
- const ImageEditorPlugin = dependencies.ImageEditorPlugin || ImageEditor;
46
- const CompressorPlugin = dependencies.CompressorPlugin || Compressor;
47
- const XHRUploadPlugin = dependencies.XHRUploadPlugin || XHRUpload;
34
+ resolveRequestHeaders,
35
+ onSelectedFileNameChanged = ignoreUploadEvent,
36
+ onUploadSuccess,
37
+ onInvalidResponse = ignoreUploadEvent,
38
+ onUploadError,
39
+ onRestrictionFailed,
40
+ onUnavailable = ignoreUploadEvent,
41
+ dependencies: {
42
+ UppyClass = Uppy,
43
+ DashboardPlugin = Dashboard,
44
+ ImageEditorPlugin = ImageEditor,
45
+ CompressorPlugin = Compressor,
46
+ XHRUploadPlugin = XHRUpload
47
+ } = {}
48
+ }) {
48
49
  let uploadUppy = null;
49
50
 
50
51
  const normalizedAllowedMimeTypes =
@@ -64,9 +65,7 @@ function createImageUploadRuntime({
64
65
  });
65
66
 
66
67
  function emitSelectedFileName(fileName) {
67
- if (typeof onSelectedFileNameChanged === "function") {
68
- onSelectedFileNameChanged(String(fileName || ""));
69
- }
68
+ onSelectedFileNameChanged(String(fileName || ""));
70
69
  }
71
70
 
72
71
  function setup() {
@@ -92,10 +91,7 @@ function createImageUploadRuntime({
92
91
  ...normalizeObject(dashboardOptions),
93
92
  note: dashboardNote,
94
93
  doneButtonHandler: () => {
95
- const dashboard = uppy.getPlugin("Dashboard");
96
- if (dashboard && typeof dashboard.closeModal === "function") {
97
- dashboard.closeModal();
98
- }
94
+ closeDashboard(uppy);
99
95
  }
100
96
  });
101
97
 
@@ -116,10 +112,7 @@ function createImageUploadRuntime({
116
112
  fieldName: normalizedFieldName,
117
113
  withCredentials: withCredentials !== false,
118
114
  onBeforeRequest: async (xhr) => {
119
- const headers =
120
- typeof resolveRequestHeaders === "function"
121
- ? normalizeObject(await resolveRequestHeaders({ xhr, uppy }))
122
- : {};
115
+ const headers = normalizeObject(await resolveRequestHeaders({ xhr, uppy }));
123
116
  for (const [headerName, headerValue] of Object.entries(headers)) {
124
117
  if (headerValue == null) {
125
118
  continue;
@@ -154,47 +147,39 @@ function createImageUploadRuntime({
154
147
  uppy.on("upload-success", (file, response) => {
155
148
  const data = response?.body;
156
149
  if (!data || typeof data !== "object") {
157
- if (typeof onInvalidResponse === "function") {
158
- onInvalidResponse({
159
- file,
160
- response,
161
- uppy
162
- });
163
- }
164
- return;
165
- }
166
-
167
- if (typeof onUploadSuccess === "function") {
168
- onUploadSuccess({
169
- data,
150
+ onInvalidResponse({
170
151
  file,
171
152
  response,
172
153
  uppy
173
154
  });
155
+ return;
174
156
  }
175
157
 
158
+ onUploadSuccess({
159
+ data,
160
+ file,
161
+ response,
162
+ uppy
163
+ });
164
+
176
165
  emitSelectedFileName("");
177
166
  });
178
167
 
179
168
  uppy.on("upload-error", (file, error, response) => {
180
- if (typeof onUploadError === "function") {
181
- onUploadError({
182
- file,
183
- error,
184
- response,
185
- uppy
186
- });
187
- }
169
+ onUploadError({
170
+ file,
171
+ error,
172
+ response,
173
+ uppy
174
+ });
188
175
  });
189
176
 
190
177
  uppy.on("restriction-failed", (file, error) => {
191
- if (typeof onRestrictionFailed === "function") {
192
- onRestrictionFailed({
193
- file,
194
- error,
195
- uppy
196
- });
197
- }
178
+ onRestrictionFailed({
179
+ file,
180
+ error,
181
+ uppy
182
+ });
198
183
  });
199
184
 
200
185
  uppy.on("complete", (result) => {
@@ -216,16 +201,13 @@ function createImageUploadRuntime({
216
201
  function openEditor() {
217
202
  setup();
218
203
 
219
- const uppy = uploadUppy;
220
- if (!uppy) {
221
- if (typeof onUnavailable === "function") {
222
- onUnavailable();
223
- }
204
+ if (!uploadUppy) {
205
+ onUnavailable();
224
206
  return;
225
207
  }
226
208
 
227
- const dashboard = uppy.getPlugin("Dashboard");
228
- if (dashboard && typeof dashboard.openModal === "function") {
209
+ const dashboard = uploadUppy.getPlugin("Dashboard");
210
+ if (dashboard) {
229
211
  dashboard.openModal();
230
212
  }
231
213
  }
@@ -1,5 +1,7 @@
1
1
  import { computed, ref, unref } from "vue";
2
+ import { normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
3
  import { createImageUploadRuntime } from "./createImageUploadRuntime.js";
4
+ import { closeDashboard } from "../support/uppyPlugins.js";
3
5
  import { useJskitText } from "../i18n.js";
4
6
 
5
7
  // Message keys; a caller's messages may be keys or plain text, rendered with
@@ -17,33 +19,8 @@ const DEFAULT_MANAGED_IMAGE_ASSET_MESSAGES = Object.freeze({
17
19
  changeError: "jskit.uploads.imageAsset.changeError"
18
20
  });
19
21
 
20
- function normalizeText(value) {
21
- return String(value || "").trim();
22
- }
23
-
24
- function normalizeObject(value) {
25
- return value && typeof value === "object" ? value : {};
26
- }
27
-
28
- function normalizeWritableRef(value, fallbackValue = "") {
29
- if (value && typeof value === "object" && "value" in value) {
30
- return value;
31
- }
32
-
33
- return ref(normalizeText(fallbackValue));
34
- }
35
-
36
- function closeDashboard(uppy) {
37
- const dashboard = uppy?.getPlugin?.("Dashboard");
38
- if (!dashboard || typeof dashboard.closeModal !== "function") {
39
- return;
40
- }
41
-
42
- dashboard.closeModal();
43
- }
44
-
45
22
  async function readJsonResponse(response) {
46
- const contentType = normalizeText(response?.headers?.get?.("content-type")).toLowerCase();
23
+ const contentType = normalizeText(response.headers.get("content-type")).toLowerCase();
47
24
  if (!contentType.includes("application/json")) {
48
25
  return null;
49
26
  }
@@ -88,36 +65,61 @@ function normalizeDeleteResult(result) {
88
65
  };
89
66
  }
90
67
 
68
+ /** The delete an application gets unless it supplies its own. */
69
+ async function requestDeleteWithFetch({ endpoint, method, headers, fetch }) {
70
+ const response = await fetch(endpoint, {
71
+ method,
72
+ credentials: "include",
73
+ headers
74
+ });
75
+
76
+ return {
77
+ body: await readJsonResponse(response),
78
+ response
79
+ };
80
+ }
81
+
82
+ function assetUrlFromUploadEndpoint({ uploadEndpoint }) {
83
+ return uploadEndpoint;
84
+ }
85
+
86
+ function keepDefaultMessage({ defaultMessage }) {
87
+ return defaultMessage;
88
+ }
89
+
90
+ function ignoreDeleteSuccess() {}
91
+
92
+ /** @param {import("../types.js").ManagedImageAssetRuntimeOptions} options */
91
93
  function createManagedImageAssetRuntime({
92
94
  uploadEndpoint = "",
93
95
  deleteEndpoint = "",
94
96
  fieldName = "file",
95
97
  hasAsset = false,
96
98
  assetVersion = "",
97
- selectedFileName = null,
98
- resolveAssetUrl = null,
99
- resolveRequestHeaders = null,
100
- onUploadSuccess = null,
101
- onDeleteSuccess = null,
102
- resolveUploadErrorMessage = null,
103
- resolveDeleteErrorMessage = null,
104
- deleteRequest = null,
105
- reportFeedback = null,
99
+ selectedFileName = ref(""),
100
+ resolveAssetUrl = assetUrlFromUploadEndpoint,
101
+ resolveRequestHeaders,
102
+ onUploadSuccess,
103
+ onDeleteSuccess = ignoreDeleteSuccess,
104
+ resolveUploadErrorMessage = keepDefaultMessage,
105
+ resolveDeleteErrorMessage = keepDefaultMessage,
106
+ deleteRequest = requestDeleteWithFetch,
107
+ reportFeedback,
106
108
  messages = {},
107
109
  uploadOptions = {},
108
110
  deleteMethod = "DELETE",
109
111
  source = "uploads-image-web.managed-image-asset",
110
- dependencies = {}
111
- } = {}) {
112
+ dependencies: {
113
+ createImageUploadRuntimeFactory = createImageUploadRuntime,
114
+ fetchImpl = globalThis.fetch.bind(globalThis)
115
+ } = {}
116
+ }) {
112
117
  const { t, text } = useJskitText();
113
- const createImageUploadRuntimeFactory = dependencies.createImageUploadRuntimeFactory || createImageUploadRuntime;
114
- const fetchImpl = dependencies.fetchImpl || globalThis.fetch?.bind(globalThis);
115
118
  const normalizedMessages = {
116
119
  ...DEFAULT_MANAGED_IMAGE_ASSET_MESSAGES,
117
120
  ...normalizeObject(messages)
118
121
  };
119
122
  const messageText = (name) => text(normalizedMessages[name]);
120
- const selectedFileNameRef = normalizeWritableRef(selectedFileName);
121
123
  const isDeleting = ref(false);
122
124
  const normalizedFieldName = normalizeText(fieldName || "file") || "file";
123
125
  const normalizedDeleteMethod = normalizeText(deleteMethod || "DELETE").toUpperCase() || "DELETE";
@@ -135,10 +137,6 @@ function createManagedImageAssetRuntime({
135
137
  return "";
136
138
  }
137
139
 
138
- if (typeof resolveAssetUrl !== "function") {
139
- return normalizedUploadEndpoint.value;
140
- }
141
-
142
140
  return normalizeText(
143
141
  resolveAssetUrl({
144
142
  uploadEndpoint: normalizedUploadEndpoint.value,
@@ -160,7 +158,7 @@ function createManagedImageAssetRuntime({
160
158
  dedupeKey = ""
161
159
  } = {}) {
162
160
  const normalizedMessage = normalizeText(message);
163
- if (!normalizedMessage || typeof reportFeedback !== "function") {
161
+ if (!normalizedMessage) {
164
162
  return;
165
163
  }
166
164
 
@@ -173,10 +171,6 @@ function createManagedImageAssetRuntime({
173
171
  }
174
172
 
175
173
  async function resolveHeaders(action, endpoint) {
176
- if (typeof resolveRequestHeaders !== "function") {
177
- return {};
178
- }
179
-
180
174
  return normalizeObject(
181
175
  await resolveRequestHeaders({
182
176
  action,
@@ -189,14 +183,10 @@ function createManagedImageAssetRuntime({
189
183
  }
190
184
 
191
185
  function updateSelectedFileName(fileName = "") {
192
- selectedFileNameRef.value = normalizeText(fileName);
186
+ selectedFileName.value = normalizeText(fileName);
193
187
  }
194
188
 
195
189
  async function runChangeHandler(handler, payload) {
196
- if (typeof handler !== "function") {
197
- return;
198
- }
199
-
200
190
  try {
201
191
  await Promise.resolve(handler(payload));
202
192
  } catch (error) {
@@ -215,9 +205,6 @@ function createManagedImageAssetRuntime({
215
205
  response,
216
206
  fallbackMessage: messageText("uploadError")
217
207
  });
218
- if (typeof resolveUploadErrorMessage !== "function") {
219
- return fallbackMessage;
220
- }
221
208
 
222
209
  return resolveMessage(
223
210
  resolveUploadErrorMessage({
@@ -236,9 +223,6 @@ function createManagedImageAssetRuntime({
236
223
  body,
237
224
  fallbackMessage: messageText("deleteError")
238
225
  });
239
- if (typeof resolveDeleteErrorMessage !== "function") {
240
- return fallbackMessage;
241
- }
242
226
 
243
227
  return resolveMessage(
244
228
  resolveDeleteErrorMessage({
@@ -282,7 +266,7 @@ function createManagedImageAssetRuntime({
282
266
  resolveRequestHeaders: async () => resolveHeaders("upload", endpoint),
283
267
  onSelectedFileNameChanged: updateSelectedFileName,
284
268
  onUploadSuccess: async (payload) => {
285
- closeDashboard(payload?.uppy);
269
+ closeDashboard(payload.uppy);
286
270
  updateSelectedFileName("");
287
271
  report({
288
272
  message: messageText("uploadSuccess"),
@@ -332,7 +316,9 @@ function createManagedImageAssetRuntime({
332
316
 
333
317
  function setup() {
334
318
  const runtime = ensureUploadRuntime();
335
- runtime?.setup?.();
319
+ if (runtime) {
320
+ runtime.setup();
321
+ }
336
322
  }
337
323
 
338
324
  function openEditor() {
@@ -366,16 +352,6 @@ function createManagedImageAssetRuntime({
366
352
  return;
367
353
  }
368
354
 
369
- if (typeof deleteRequest !== "function" && typeof fetchImpl !== "function") {
370
- report({
371
- message: messageText("deleteUnavailable"),
372
- severity: "error",
373
- channel: "banner",
374
- dedupeKey: `${source}:delete-unavailable`
375
- });
376
- return;
377
- }
378
-
379
355
  let response = null;
380
356
  let body = null;
381
357
 
@@ -383,37 +359,24 @@ function createManagedImageAssetRuntime({
383
359
  try {
384
360
  const headers = await resolveHeaders("delete", endpoint);
385
361
 
386
- if (typeof deleteRequest === "function") {
387
- const deleteResult = normalizeDeleteResult(
388
- await deleteRequest({
389
- endpoint,
390
- method: normalizedDeleteMethod,
391
- headers,
392
- fetch: fetchImpl,
393
- uploadEndpoint: normalizedUploadEndpoint.value,
394
- deleteEndpoint: endpoint,
395
- fieldName: normalizedFieldName
396
- })
397
- );
398
- response = deleteResult.response;
399
- body = deleteResult.body;
400
- if (response && response.ok === false) {
401
- const requestError = new Error(t("jskit.uploads.imageAsset.deleteRequestFailed"));
402
- requestError.response = response;
403
- requestError.body = body;
404
- throw requestError;
405
- }
406
- } else {
407
- response = await fetchImpl(endpoint, {
362
+ const deleteResult = normalizeDeleteResult(
363
+ await deleteRequest({
364
+ endpoint,
408
365
  method: normalizedDeleteMethod,
409
- credentials: "include",
410
- headers
411
- });
412
- body = await readJsonResponse(response);
413
-
414
- if (!response.ok) {
415
- throw new Error(t("jskit.uploads.imageAsset.deleteRequestFailed"));
416
- }
366
+ headers,
367
+ fetch: fetchImpl,
368
+ uploadEndpoint: normalizedUploadEndpoint.value,
369
+ deleteEndpoint: endpoint,
370
+ fieldName: normalizedFieldName
371
+ })
372
+ );
373
+ response = deleteResult.response;
374
+ body = deleteResult.body;
375
+ if (response && response.ok === false) {
376
+ const requestError = new Error(t("jskit.uploads.imageAsset.deleteRequestFailed"));
377
+ requestError.response = response;
378
+ requestError.body = body;
379
+ throw requestError;
417
380
  }
418
381
 
419
382
  updateSelectedFileName("");
@@ -442,16 +405,16 @@ function createManagedImageAssetRuntime({
442
405
  }
443
406
  }
444
407
 
445
- return Object.freeze({
408
+ return {
446
409
  assetUrl,
447
410
  deleteAsset,
448
411
  destroy,
449
412
  hasAsset: normalizedHasAsset,
450
413
  isDeleting,
451
414
  openEditor,
452
- selectedFileName: selectedFileNameRef,
415
+ selectedFileName,
453
416
  setup
454
- });
417
+ };
455
418
  }
456
419
 
457
420
  export {
@@ -0,0 +1,19 @@
1
+ // A plugin's name finds nothing once the Uppy instance has removed it, or when dashboardOptions gave it another id.
2
+
3
+ /** @param {import("../types.js").ImageUppy} uppy */
4
+ function closeDashboard(uppy) {
5
+ const dashboard = uppy.getPlugin("Dashboard");
6
+ if (dashboard) {
7
+ dashboard.closeModal();
8
+ }
9
+ }
10
+
11
+ /** @param {import("../types.js").ImageUppy} uppy */
12
+ function stopImageEditor(uppy) {
13
+ const imageEditor = uppy.getPlugin("ImageEditor");
14
+ if (imageEditor) {
15
+ imageEditor.stop();
16
+ }
17
+ }
18
+
19
+ export { closeDashboard, stopImageEditor };
@@ -0,0 +1,110 @@
1
+ // The types of what uploads-image-web's client hands out and receives across its files.
2
+
3
+ /** @typedef {ReturnType<typeof import("./composables/createImageUploadRuntime.js").createImageUploadRuntime>} ImageUploadRuntime */
4
+ /** @typedef {ReturnType<typeof import("./composables/createManagedImageAssetRuntime.js").createManagedImageAssetRuntime>} ManagedImageAssetRuntime */
5
+
6
+ /**
7
+ * The Uppy instance behind a runtime, as far as this package and an application's callbacks use it.
8
+ * @typedef {object} ImageUppy
9
+ * @property {(id: string) => any} getPlugin Undefined for a plugin the instance does not hold.
10
+ * @property {() => void} clear
11
+ * @property {() => void} destroy
12
+ */
13
+
14
+ /**
15
+ * The classes a runtime builds on, replaceable one by one.
16
+ * @typedef {object} ImageUploadDependencies
17
+ * @property {new (options: object) => any} [UppyClass]
18
+ * @property {unknown} [DashboardPlugin]
19
+ * @property {unknown} [ImageEditorPlugin]
20
+ * @property {unknown} [CompressorPlugin]
21
+ * @property {unknown} [XHRUploadPlugin]
22
+ */
23
+
24
+ /**
25
+ * What the upload-success callback receives.
26
+ * @typedef {object} ImageUploadSuccess
27
+ * @property {Record<string, unknown>} data The server's response body.
28
+ * @property {unknown} file
29
+ * @property {unknown} response
30
+ * @property {ImageUppy} uppy
31
+ */
32
+
33
+ /**
34
+ * What an application supplies to edit and upload an image.
35
+ * @typedef {object} ImageUploadRuntimeOptions
36
+ * @property {string} [endpoint]
37
+ * @property {string} [method]
38
+ * @property {string} [fieldName]
39
+ * @property {boolean} [withCredentials]
40
+ * @property {number} [maxNumberOfFiles]
41
+ * @property {string[]} [allowedMimeTypes]
42
+ * @property {number} [maxUploadBytes]
43
+ * @property {string} [note] The dashboard's note; empty for the package's own.
44
+ * @property {object} [dashboardOptions]
45
+ * @property {object} [imageEditorOptions]
46
+ * @property {object} [compressorOptions]
47
+ * @property {(xhr: XMLHttpRequest) => unknown} [parseResponse]
48
+ * @property {(request: { xhr: XMLHttpRequest, uppy: ImageUppy }) => Promise<Record<string, unknown>> | Record<string, unknown>} resolveRequestHeaders
49
+ * @property {(fileName: string) => void} [onSelectedFileNameChanged]
50
+ * @property {(success: ImageUploadSuccess) => unknown} onUploadSuccess
51
+ * @property {(failure: { file: unknown, response: unknown, uppy: ImageUppy }) => void} [onInvalidResponse]
52
+ * @property {(failure: { file: unknown, error: Error, response: unknown, uppy: ImageUppy }) => void} onUploadError
53
+ * @property {(failure: { file: unknown, error: Error, uppy: ImageUppy }) => void} onRestrictionFailed
54
+ * @property {() => void} [onUnavailable] Called when the editor is opened outside a browser.
55
+ * @property {ImageUploadDependencies} [dependencies]
56
+ */
57
+
58
+ /**
59
+ * One message for the application to show.
60
+ * @typedef {object} ImageAssetFeedback
61
+ * @property {string} message
62
+ * @property {string} severity
63
+ * @property {string} channel
64
+ * @property {string} dedupeKey
65
+ */
66
+
67
+ /**
68
+ * What a delete request receives. An application's own request may ignore `fetch`.
69
+ * @typedef {object} ImageAssetDeleteRequest
70
+ * @property {string} endpoint
71
+ * @property {string} method
72
+ * @property {Record<string, unknown>} headers
73
+ * @property {typeof fetch} fetch
74
+ * @property {string} uploadEndpoint
75
+ * @property {string} deleteEndpoint
76
+ * @property {string} fieldName
77
+ */
78
+
79
+ /**
80
+ * The classes and functions a managed runtime builds on, replaceable one by one.
81
+ * @typedef {object} ManagedImageAssetDependencies
82
+ * @property {(options: ImageUploadRuntimeOptions) => ImageUploadRuntime} [createImageUploadRuntimeFactory]
83
+ * @property {typeof fetch} [fetchImpl]
84
+ */
85
+
86
+ /**
87
+ * What an application supplies to manage one image asset: upload, delete and where to show it.
88
+ * @typedef {object} ManagedImageAssetRuntimeOptions
89
+ * @property {import("vue").MaybeRef<string>} [uploadEndpoint] Empty until the asset has a home.
90
+ * @property {import("vue").MaybeRef<string>} [deleteEndpoint] Empty to use the upload endpoint.
91
+ * @property {string} [fieldName]
92
+ * @property {import("vue").MaybeRef<boolean>} [hasAsset]
93
+ * @property {import("vue").MaybeRef<string>} [assetVersion]
94
+ * @property {import("vue").Ref<string>} [selectedFileName] The application's own ref for the chosen file's name.
95
+ * @property {(asset: { uploadEndpoint: string, deleteEndpoint: string, hasAsset: boolean, assetVersion: string, fieldName: string }) => string} [resolveAssetUrl]
96
+ * @property {(request: { action: string, uploadEndpoint: string, deleteEndpoint: string, endpoint: string, fieldName: string }) => Promise<Record<string, unknown>> | Record<string, unknown>} resolveRequestHeaders
97
+ * @property {(success: ImageUploadSuccess) => unknown} onUploadSuccess
98
+ * @property {(success: { data: unknown, response: unknown }) => unknown} [onDeleteSuccess]
99
+ * @property {(failure: { error: Error, response: unknown, fieldName: string, defaultMessage: string }) => string} [resolveUploadErrorMessage]
100
+ * @property {(failure: { error: Error, response: unknown, body: unknown, fieldName: string, defaultMessage: string }) => string} [resolveDeleteErrorMessage]
101
+ * @property {(request: ImageAssetDeleteRequest) => Promise<unknown>} [deleteRequest]
102
+ * @property {(feedback: ImageAssetFeedback) => void} reportFeedback
103
+ * @property {Record<string, string>} [messages] Message keys or plain text, by name.
104
+ * @property {Partial<ImageUploadRuntimeOptions>} [uploadOptions]
105
+ * @property {string} [deleteMethod]
106
+ * @property {string} [source] Names the feature in dedupe keys.
107
+ * @property {ManagedImageAssetDependencies} [dependencies]
108
+ */
109
+
110
+ export {};
@@ -169,3 +169,90 @@ test("createImageUploadRuntime reports unavailable editor outside browser enviro
169
169
  runtime.openEditor();
170
170
  assert.deepEqual(unavailableCalls, [true]);
171
171
  });
172
+
173
+ test("createImageUploadRuntime stops and closes only the plugins the instance still holds", () => {
174
+ const restoreWindow = setWindowStub();
175
+ let fakeUppy = null;
176
+
177
+ try {
178
+ const runtime = createImageUploadRuntime({
179
+ dependencies: {
180
+ UppyClass: class extends FakeUppy {
181
+ constructor(options) {
182
+ super(options);
183
+ fakeUppy = this;
184
+ }
185
+ },
186
+ DashboardPlugin: { name: "Dashboard" },
187
+ ImageEditorPlugin: { name: "ImageEditor" },
188
+ CompressorPlugin: { name: "Compressor" },
189
+ XHRUploadPlugin: { name: "XHRUpload" }
190
+ }
191
+ });
192
+
193
+ runtime.setup();
194
+ const imageEditor = fakeUppy.plugins.get("ImageEditor");
195
+ fakeUppy.eventHandlers.get("dashboard:modal-closed")();
196
+ assert.equal(imageEditor.stopCount, 1);
197
+
198
+ fakeUppy.plugins.clear();
199
+ fakeUppy.eventHandlers.get("dashboard:modal-closed")();
200
+ fakeUppy.pluginOptions.get("Dashboard").doneButtonHandler();
201
+ runtime.openEditor();
202
+ assert.equal(imageEditor.stopCount, 1);
203
+ } finally {
204
+ restoreWindow();
205
+ }
206
+ });
207
+
208
+ test("createImageUploadRuntime runs without the callbacks an application leaves out", async () => {
209
+ const restoreWindow = setWindowStub();
210
+ let fakeUppy = null;
211
+
212
+ try {
213
+ const successes = [];
214
+ const runtime = createImageUploadRuntime({
215
+ endpoint: "/api/evidence-files/upload",
216
+ resolveRequestHeaders: async () => ({}),
217
+ onUploadSuccess: ({ data }) => {
218
+ successes.push(data);
219
+ },
220
+ onUploadError() {},
221
+ onRestrictionFailed() {},
222
+ dependencies: {
223
+ UppyClass: class extends FakeUppy {
224
+ constructor(options) {
225
+ super(options);
226
+ fakeUppy = this;
227
+ }
228
+ },
229
+ DashboardPlugin: { name: "Dashboard" },
230
+ ImageEditorPlugin: { name: "ImageEditor" },
231
+ CompressorPlugin: { name: "Compressor" },
232
+ XHRUploadPlugin: { name: "XHRUpload" }
233
+ }
234
+ });
235
+
236
+ runtime.setup();
237
+ fakeUppy.eventHandlers.get("file-added")({ name: "site.png" });
238
+ fakeUppy.eventHandlers.get("file-editor:complete")({ name: "site-edited.png" });
239
+ fakeUppy.eventHandlers.get("file-removed")();
240
+ fakeUppy.eventHandlers.get("upload-success")({}, { body: "" });
241
+ fakeUppy.eventHandlers.get("upload-success")({}, { body: { id: "1" } });
242
+
243
+ assert.deepEqual(successes, [{ id: "1" }]);
244
+ } finally {
245
+ restoreWindow();
246
+ }
247
+ });
248
+
249
+ test("createImageUploadRuntime opens nothing outside a browser when no onUnavailable is given", () => {
250
+ const runtime = createImageUploadRuntime({
251
+ resolveRequestHeaders: async () => ({}),
252
+ onUploadSuccess() {},
253
+ onUploadError() {},
254
+ onRestrictionFailed() {}
255
+ });
256
+
257
+ runtime.openEditor();
258
+ });
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { ref } from "vue";
3
+ import { reactive, ref } from "vue";
4
4
  import { createManagedImageAssetRuntime } from "../src/client/composables/createManagedImageAssetRuntime.js";
5
5
 
6
6
  function createFakeUploadRuntimeFactory(createdRuntimes) {
@@ -152,6 +152,7 @@ test("createManagedImageAssetRuntime reports configured upload and delete errors
152
152
  const runtime = createManagedImageAssetRuntime({
153
153
  uploadEndpoint: "/api/pets/1/photo",
154
154
  fieldName: "photo",
155
+ resolveRequestHeaders: async () => ({}),
155
156
  reportFeedback: (payload) => {
156
157
  feedbackEvents.push(payload);
157
158
  },
@@ -194,3 +195,70 @@ test("createManagedImageAssetRuntime reports configured upload and delete errors
194
195
  ["Selected photo is invalid.", "Cannot delete this photo."]
195
196
  );
196
197
  });
198
+
199
+ test("createManagedImageAssetRuntime needs only what every application supplies", async () => {
200
+ const createdRuntimes = [];
201
+ const feedbackEvents = [];
202
+ const fetchCalls = [];
203
+
204
+ const runtime = createManagedImageAssetRuntime({
205
+ uploadEndpoint: "/api/pets/1/photo",
206
+ hasAsset: true,
207
+ resolveRequestHeaders: async () => ({}),
208
+ onUploadSuccess() {},
209
+ reportFeedback: (payload) => {
210
+ feedbackEvents.push(payload);
211
+ },
212
+ dependencies: {
213
+ createImageUploadRuntimeFactory: createFakeUploadRuntimeFactory(createdRuntimes),
214
+ fetchImpl: async (url, options) => {
215
+ fetchCalls.push([url, options.method]);
216
+ return createJsonResponse({ ok: true });
217
+ }
218
+ }
219
+ });
220
+
221
+ assert.equal(runtime.assetUrl.value, "/api/pets/1/photo");
222
+
223
+ runtime.setup();
224
+ createdRuntimes[0].options.onSelectedFileNameChanged("pet.png");
225
+ assert.equal(runtime.selectedFileName.value, "pet.png");
226
+
227
+ await runtime.deleteAsset();
228
+
229
+ assert.deepEqual(fetchCalls, [["/api/pets/1/photo", "DELETE"]]);
230
+ assert.equal(runtime.selectedFileName.value, "");
231
+ assert.deepEqual(feedbackEvents.map((entry) => entry.severity), ["success"]);
232
+ });
233
+
234
+ test("createManagedImageAssetRuntime does nothing on setup without an upload endpoint", () => {
235
+ const createdRuntimes = [];
236
+
237
+ const runtime = createManagedImageAssetRuntime({
238
+ resolveRequestHeaders: async () => ({}),
239
+ onUploadSuccess() {},
240
+ reportFeedback() {},
241
+ dependencies: {
242
+ createImageUploadRuntimeFactory: createFakeUploadRuntimeFactory(createdRuntimes)
243
+ }
244
+ });
245
+
246
+ runtime.setup();
247
+ assert.deepEqual(createdRuntimes, []);
248
+ });
249
+
250
+ test("createManagedImageAssetRuntime holds refs a caller can read through reactive state", () => {
251
+ const runtime = reactive(createManagedImageAssetRuntime({
252
+ uploadEndpoint: "/api/pets/1/photo",
253
+ hasAsset: true,
254
+ resolveRequestHeaders: async () => ({}),
255
+ onUploadSuccess() {},
256
+ reportFeedback() {},
257
+ dependencies: {
258
+ createImageUploadRuntimeFactory: createFakeUploadRuntimeFactory([])
259
+ }
260
+ }));
261
+
262
+ assert.equal(runtime.assetUrl, "/api/pets/1/photo");
263
+ assert.equal(runtime.isDeleting, false);
264
+ });
@@ -17,6 +17,8 @@ test("uploads-image-web exports are explicit and aligned with usage", () => {
17
17
  "./client",
18
18
  "./client/composables/createImageUploadRuntime",
19
19
  "./client/composables/createManagedImageAssetRuntime",
20
+ // The options contracts applications and users-web implement.
21
+ "./client/types",
20
22
  "./shared",
21
23
  // The generated client bootstrap registers the package's English catalog.
22
24
  "./locales/en.json"
@@ -0,0 +1,314 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { fileURLToPath } from "node:url";
4
+ import { chromium, expect } from "@playwright/test";
5
+ import { createChromiumLaunchOptions, startViteFixture, stopProcess } from "../../../tooling/testUtils/browserFixture.mjs";
6
+
7
+ const ALLOWED_TYPES_MESSAGE = "You can only upload: image/jpeg, image/png, image/webp";
8
+ // What Uppy's XHR upload hands upload-error for any HTTP error: its own network-error text and the XMLHttpRequest,
9
+ // which has no parsed body. It retries three times first.
10
+ const UPPY_HTTP_ERROR_MESSAGE = "This looks like a network error, the endpoint might be blocked by an internet provider or a firewall.";
11
+ const UPPY_ATTEMPTS_PER_FAILED_UPLOAD = 4;
12
+
13
+ function createDeferred() {
14
+ let resolve;
15
+ const promise = new Promise((done) => {
16
+ resolve = done;
17
+ });
18
+ return { promise, resolve };
19
+ }
20
+
21
+ // A request the fixture server holds: `arrived` settles when it comes in, `release` lets it answer.
22
+ function createGate() {
23
+ return { arrived: createDeferred(), release: createDeferred() };
24
+ }
25
+
26
+ async function arrival(gate, label) {
27
+ let timer;
28
+ const timeout = new Promise((_resolve, reject) => {
29
+ timer = setTimeout(() => reject(new Error(`No ${label} request arrived.`)), 15_000);
30
+ });
31
+ try {
32
+ await Promise.race([gate.arrived.promise, timeout]);
33
+ } finally {
34
+ clearTimeout(timer);
35
+ }
36
+ }
37
+
38
+ // A real JPEG at full quality, drawn by the browser, so the compressor has something to save.
39
+ async function createPhoto(page, { width, height }) {
40
+ const base64 = await page.evaluate(async ({ width: canvasWidth, height: canvasHeight }) => {
41
+ const canvas = document.createElement("canvas");
42
+ canvas.width = canvasWidth;
43
+ canvas.height = canvasHeight;
44
+ const context = canvas.getContext("2d");
45
+ const gradient = context.createLinearGradient(0, 0, canvasWidth, canvasHeight);
46
+ gradient.addColorStop(0, "#0b6e4f");
47
+ gradient.addColorStop(1, "#f2a541");
48
+ context.fillStyle = gradient;
49
+ context.fillRect(0, 0, canvasWidth, canvasHeight);
50
+ let seed = 7;
51
+ for (let index = 0; index < 400; index += 1) {
52
+ seed = (seed * 1103515245 + 12345) % 2147483648;
53
+ context.fillStyle = `hsl(${seed % 360} 70% 50% / 0.6)`;
54
+ context.beginPath();
55
+ context.arc(seed % canvasWidth, (seed >> 8) % canvasHeight, 4 + (seed % 24), 0, Math.PI * 2);
56
+ context.fill();
57
+ }
58
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", 1));
59
+ const bytes = new Uint8Array(await blob.arrayBuffer());
60
+ let binary = "";
61
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
62
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
63
+ }
64
+ return btoa(binary);
65
+ }, { width, height });
66
+ return Buffer.from(base64, "base64");
67
+ }
68
+
69
+ function readJpegSize(bytes) {
70
+ assert.equal(bytes.readUInt16BE(0), 0xffd8, "the uploaded file is a JPEG");
71
+ let offset = 2;
72
+ while (offset + 9 < bytes.length) {
73
+ const marker = bytes[offset + 1];
74
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
75
+ return { height: bytes.readUInt16BE(offset + 5), width: bytes.readUInt16BE(offset + 7) };
76
+ }
77
+ offset += 2 + bytes.readUInt16BE(offset + 2);
78
+ }
79
+ throw new Error("The JPEG has no frame header.");
80
+ }
81
+
82
+ // What reached the server: read while the route holds the request, checked once the page has answered.
83
+ async function readUpload(request) {
84
+ const headers = request.headers();
85
+ const body = request.postDataBuffer();
86
+ const upload = { headers, contentType: headers["content-type"] || "", hasBody: Boolean(body), fields: {}, files: [] };
87
+ if (!body) {
88
+ return upload;
89
+ }
90
+ const form = await new Response(body, { headers: { "content-type": upload.contentType } }).formData();
91
+ for (const [field, value] of form.entries()) {
92
+ if (typeof value === "string") {
93
+ upload.fields[field] = value;
94
+ } else {
95
+ upload.files.push({ field, name: value.name, type: value.type, bytes: Buffer.from(await value.arrayBuffer()) });
96
+ }
97
+ }
98
+ return upload;
99
+ }
100
+
101
+ function assertMultipartUpload(upload, { field, name }) {
102
+ assert.ok(upload.hasBody, "the upload request carries its body");
103
+ assert.match(upload.contentType, /^multipart\/form-data; boundary=/u);
104
+ assert.equal(upload.headers["csrf-token"], "fixture-csrf");
105
+ assert.equal(upload.files.length, 1);
106
+ const [file] = upload.files;
107
+ assert.equal(file.field, field);
108
+ assert.equal(file.name, name);
109
+ assert.equal(file.type, "image/jpeg");
110
+ return file;
111
+ }
112
+
113
+ async function openPage(browser, baseURL) {
114
+ const page = await browser.newPage({ baseURL, viewport: { width: 1280, height: 900 } });
115
+ page.setDefaultTimeout(15_000);
116
+ page.setDefaultNavigationTimeout(60_000);
117
+ const errors = [];
118
+ page.on("pageerror", (error) => errors.push(error.message));
119
+ return { page, errors };
120
+ }
121
+
122
+ function dashboardOf(page) {
123
+ return page.getByRole("dialog").filter({ has: page.getByRole("button", { name: "Close Modal", exact: true }) });
124
+ }
125
+
126
+ function chooseFile(dashboard, file) {
127
+ return dashboard.locator(".uppy-Dashboard-input[type=\"file\"]").first().setInputFiles(file);
128
+ }
129
+
130
+ async function checkManagedAvatar(page) {
131
+ const uploads = [];
132
+ const deletes = [];
133
+ const unexpected = [];
134
+ let uploadReply = { status: 200, json: { profile: { avatar: { version: 2 } } } };
135
+ let deleteReply = null;
136
+ let deleteGate = null;
137
+ await page.route("**/api/**", async (route) => {
138
+ const request = route.request();
139
+ const path = new URL(request.url()).pathname;
140
+ if (request.method() === "GET" && path === "/api/session") {
141
+ await route.fulfill({ json: { csrfToken: "fixture-csrf" } });
142
+ } else if (request.method() === "POST" && path === "/api/settings/profile/avatar") {
143
+ uploads.push(await readUpload(request));
144
+ await route.fulfill(uploadReply);
145
+ } else if (request.method() === "DELETE" && path === "/api/settings/profile/avatar") {
146
+ deletes.push({ csrfToken: request.headers()["csrf-token"] });
147
+ const gate = deleteGate;
148
+ if (gate) {
149
+ gate.arrived.resolve();
150
+ await gate.release.promise;
151
+ }
152
+ await route.fulfill(deleteReply);
153
+ } else {
154
+ unexpected.push(`${request.method()} ${path}`);
155
+ await route.fulfill({ status: 404, json: {} });
156
+ }
157
+ });
158
+ const dashboard = dashboardOf(page);
159
+ const feedback = page.locator(".fixture-feedback li");
160
+ const asset = page.locator(".fixture-asset");
161
+ const selected = page.locator(".fixture-selected");
162
+
163
+ await page.goto("/avatar");
164
+ await expect(asset).toHaveText("Asset: /api/settings/profile/avatar?v=1");
165
+ const photo = await createPhoto(page, { width: 320, height: 240 });
166
+
167
+ // A file of the wrong type is refused before anything is sent.
168
+ await page.getByRole("button", { name: "Change avatar", exact: true }).click();
169
+ await expect(dashboard).toBeVisible();
170
+ await chooseFile(dashboard, { name: "notes.txt", mimeType: "text/plain", buffer: Buffer.from("not an image") });
171
+ await expect(feedback).toHaveText([`error banner: ${ALLOWED_TYPES_MESSAGE}`]);
172
+ await expect(selected).toHaveText("Selected: nothing");
173
+ await dashboard.getByRole("button", { name: "Close Modal", exact: true }).click();
174
+ await expect(dashboard).toHaveCount(0);
175
+
176
+ // Choose a photo, crop it square in the image editor, upload it.
177
+ await page.getByRole("button", { name: "Change avatar", exact: true }).click();
178
+ await expect(dashboard).toBeVisible();
179
+ await chooseFile(dashboard, { name: "photo.jpg", mimeType: "image/jpeg", buffer: photo });
180
+ await expect(selected).toHaveText("Selected: photo.jpg");
181
+ await dashboard.getByRole("button", { name: "Edit file photo.jpg", exact: true }).click();
182
+ await expect(dashboard.locator(".cropper-crop-box")).toBeVisible();
183
+ await dashboard.getByRole("button", { name: "Crop square", exact: true }).click();
184
+ await dashboard.locator(".uppy-DashboardContent-save").click();
185
+ await expect(dashboard.locator(".cropper-crop-box")).toHaveCount(0);
186
+ await dashboard.getByRole("button", { name: "Upload 1 file", exact: true }).click();
187
+ await expect(dashboard).toHaveCount(0);
188
+ await expect(asset).toHaveText("Asset: /api/settings/profile/avatar?v=2");
189
+ await expect(selected).toHaveText("Selected: nothing");
190
+ await expect(feedback).toHaveText([`error banner: ${ALLOWED_TYPES_MESSAGE}`, "success snackbar: Avatar uploaded."]);
191
+ assert.equal(uploads.length, 1);
192
+ const uploaded = assertMultipartUpload(uploads[0], { field: "avatar", name: "photo.jpg" });
193
+ const size = readJpegSize(uploaded.bytes);
194
+ assert.equal(size.width, size.height, `the editor's square crop is what was sent, got ${size.width}x${size.height}`);
195
+ assert.ok(size.width <= 240, `the crop fits the 320x240 photo, got ${size.width}`);
196
+
197
+ // A server error is reported and leaves the avatar as it was.
198
+ uploadReply = { status: 422, json: { error: "Avatar is too small.", fieldErrors: { avatar: "Use an image of at least 64 pixels." } } };
199
+ await page.getByRole("button", { name: "Change avatar", exact: true }).click();
200
+ await expect(dashboard).toBeVisible();
201
+ await chooseFile(dashboard, { name: "photo.jpg", mimeType: "image/jpeg", buffer: photo });
202
+ await dashboard.getByRole("button", { name: "Upload 1 file", exact: true }).click();
203
+ await expect(feedback.last()).toHaveText(`error banner: ${UPPY_HTTP_ERROR_MESSAGE}`);
204
+ assert.equal(uploads.length, 1 + UPPY_ATTEMPTS_PER_FAILED_UPLOAD);
205
+ await expect(asset).toHaveText("Asset: /api/settings/profile/avatar?v=2");
206
+ await dashboard.getByRole("button", { name: "Close Modal", exact: true }).click();
207
+ await expect(dashboard).toHaveCount(0);
208
+
209
+ // Removing: busy while the server answers; a refusal keeps the avatar, a success clears it.
210
+ const remove = page.getByRole("button", { name: "Remove avatar", exact: true });
211
+ deleteReply = { status: 500, json: { error: "Avatar is locked." } };
212
+ deleteGate = createGate();
213
+ await remove.click();
214
+ await arrival(deleteGate, "delete");
215
+ await expect(page.getByRole("button", { name: "Removing…", exact: true })).toBeDisabled();
216
+ deleteGate.release.resolve();
217
+ deleteGate = null;
218
+ await expect(feedback.last()).toHaveText("error banner: Avatar is locked.");
219
+ await expect(asset).toHaveText("Asset: /api/settings/profile/avatar?v=2");
220
+ await expect(remove).toBeEnabled();
221
+ deleteReply = { status: 200, json: { profile: { avatar: null } } };
222
+ await remove.click();
223
+ await expect(feedback.last()).toHaveText("success snackbar: Image removed.");
224
+ await expect(asset).toHaveText("Asset: none");
225
+ await expect(remove).toBeDisabled();
226
+
227
+ assert.deepEqual(deletes, [{ csrfToken: "fixture-csrf" }, { csrfToken: "fixture-csrf" }]);
228
+ assert.deepEqual(unexpected, []);
229
+ }
230
+
231
+ async function checkUploadRuntime(page) {
232
+ const uploads = [];
233
+ const unexpected = [];
234
+ let uploadReply = { status: 200, json: { id: "signature-1" } };
235
+ await page.route("**/api/**", async (route) => {
236
+ const request = route.request();
237
+ const path = new URL(request.url()).pathname;
238
+ if (request.method() === "GET" && path === "/api/session") {
239
+ await route.fulfill({ json: { csrfToken: "fixture-csrf" } });
240
+ } else if (request.method() === "POST" && path === "/api/signature") {
241
+ uploads.push(await readUpload(request));
242
+ await route.fulfill(uploadReply);
243
+ } else {
244
+ unexpected.push(`${request.method()} ${path}`);
245
+ await route.fulfill({ status: 404, json: {} });
246
+ }
247
+ });
248
+ const dashboard = dashboardOf(page);
249
+ const events = page.locator(".fixture-events li");
250
+
251
+ await page.goto("/signature");
252
+ const photo = await createPhoto(page, { width: 640, height: 480 });
253
+ await page.getByRole("button", { name: "Upload signature", exact: true }).click();
254
+ await expect(dashboard).toBeVisible();
255
+ await expect(dashboard).toContainText("Accepted: image/jpeg, image/png, image/webp, max 5MB");
256
+
257
+ // The default restrictions: images only, at most 5 MB.
258
+ await chooseFile(dashboard, { name: "notes.txt", mimeType: "text/plain", buffer: Buffer.from("not an image") });
259
+ await expect(events).toHaveText([`restriction notes.txt: ${ALLOWED_TYPES_MESSAGE}`]);
260
+ await chooseFile(dashboard, { name: "huge.png", mimeType: "image/png", buffer: Buffer.alloc(5 * 1024 * 1024 + 1) });
261
+ await expect(events.last()).toHaveText("restriction huge.png: huge.png exceeds maximum allowed size of 5 MB");
262
+ assert.equal(uploads.length, 0);
263
+
264
+ // A photo goes up compressed, with the resolved headers.
265
+ await chooseFile(dashboard, { name: "photo.jpg", mimeType: "image/jpeg", buffer: photo });
266
+ await dashboard.getByRole("button", { name: "Upload 1 file", exact: true }).click();
267
+ await expect(events.last()).toHaveText("success photo.jpg: {\"id\":\"signature-1\"}");
268
+ assert.equal(uploads.length, 1);
269
+ const uploaded = assertMultipartUpload(uploads[0], { field: "file", name: "photo.jpg" });
270
+ assert.equal(Object.hasOwn(uploads[0].headers, "x-fixture-unset"), false, "a header resolved to null is not sent");
271
+ assert.ok(uploaded.bytes.length < photo.length, `the compressor shrank ${photo.length} bytes, sent ${uploaded.bytes.length}`);
272
+ assert.deepEqual(readJpegSize(uploaded.bytes), { width: 640, height: 480 });
273
+
274
+ // After a success the dashboard is empty again; a server error reaches the error callback.
275
+ uploadReply = { status: 500, json: { error: "Signature storage is unavailable." } };
276
+ await expect(dashboard.locator(".uppy-Dashboard-AddFiles")).toBeVisible();
277
+ await chooseFile(dashboard, { name: "second.jpg", mimeType: "image/jpeg", buffer: photo });
278
+ await dashboard.getByRole("button", { name: "Upload 1 file", exact: true }).click();
279
+ await expect(events.last()).toHaveText(`error second.jpg 500: ${UPPY_HTTP_ERROR_MESSAGE}`);
280
+ assert.equal(uploads.length, 1 + UPPY_ATTEMPTS_PER_FAILED_UPLOAD);
281
+ assert.equal(await events.count(), 4);
282
+ assert.deepEqual(unexpected, []);
283
+ }
284
+
285
+ test("Image uploads run on real Uppy in a real browser", {
286
+ skip: process.env.JSKIT_UPLOADS_IMAGE_WEB_BROWSER !== "1",
287
+ timeout: 240_000
288
+ }, async (t) => {
289
+ const runtime = await startViteFixture({ fixtureRoot: fileURLToPath(new URL("../fixtures/image-upload/", import.meta.url)) });
290
+ let browser;
291
+ try {
292
+ browser = await chromium.launch(createChromiumLaunchOptions());
293
+ for (const [name, check] of [
294
+ ["the managed avatar runtime refuses, edits, uploads, reports a server error and deletes", checkManagedAvatar],
295
+ ["the upload runtime given only its four required callbacks refuses, uploads compressed and reports a server error", checkUploadRuntime]
296
+ ]) {
297
+ await t.test(name, async () => {
298
+ const { page, errors } = await openPage(browser, runtime.baseURL);
299
+ try {
300
+ await check(page);
301
+ assert.deepEqual(errors, []);
302
+ } catch (error) {
303
+ console.error(await page.locator("body").innerText().catch(() => ""));
304
+ throw error;
305
+ } finally {
306
+ await page.close();
307
+ }
308
+ });
309
+ }
310
+ } finally {
311
+ if (browser) await browser.close();
312
+ await stopProcess(runtime);
313
+ }
314
+ });
@@ -41,6 +41,8 @@ function captureDashboardNote(options = {}) {
41
41
 
42
42
  function createManagedRuntime(feedbackEvents, options = {}) {
43
43
  return createManagedImageAssetRuntime({
44
+ resolveRequestHeaders: async () => ({}),
45
+ onUploadSuccess() {},
44
46
  reportFeedback: (payload) => feedbackEvents.push(payload.message),
45
47
  dependencies: {
46
48
  createImageUploadRuntimeFactory: (runtimeOptions) => ({
@@ -114,7 +116,7 @@ test("managed image upload errors show a coded server error in the app's languag
114
116
  error: { message: "Request failed." },
115
117
  response: { body: { error: "Photo is blurry.", code: "validation_failed", params: {} } }
116
118
  });
117
- created[0].options.onUploadSuccess({ data: {} });
119
+ created[0].options.onUploadSuccess({ data: {}, uppy: { getPlugin() {} } });
118
120
 
119
121
  assert.deepEqual(feedbackEvents, ["Convalida non riuscita.", "Photo is blurry.", "Immagine caricata."]);
120
122
  } finally {
@@ -1,8 +0,0 @@
1
- function stopImageEditor(uppy) {
2
- const imageEditor = uppy?.getPlugin?.("ImageEditor");
3
- if (imageEditor && typeof imageEditor.stop === "function") {
4
- imageEditor.stop();
5
- }
6
- }
7
-
8
- export { stopImageEditor };