| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 (function() { 2 "use strict"; 3 var wp; 4 (wp ||= {}).uploadMedia = (() => { 5 var __create = Object.create; 6 var __defProp = Object.defineProperty; 7 var __getOwnPropDesc = Object.getOwnPropertyDescriptor; 8 var __getOwnPropNames = Object.getOwnPropertyNames; 9 var __getProtoOf = Object.getPrototypeOf; 10 var __hasOwnProp = Object.prototype.hasOwnProperty; 11 var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { 12 get: (a, b) => (typeof require !== "undefined" ? require : a)[b] 13 }) : x)(function(x) { 14 if (typeof require !== "undefined") return require.apply(this, arguments); 15 throw Error('Dynamic require of "' + x + '" is not supported'); 16 }); 17 var __commonJS = (cb, mod) => function __require2() { 18 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; 19 }; 20 var __export = (target, all) => { 21 for (var name in all) 22 __defProp(target, name, { get: all[name], enumerable: true }); 23 }; 24 var __copyProps = (to, from, except, desc) => { 25 if (from && typeof from === "object" || typeof from === "function") { 26 for (let key of __getOwnPropNames(from)) 27 if (!__hasOwnProp.call(to, key) && key !== except) 28 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); 29 } 30 return to; 31 }; 32 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( 33 // If the importer is in node compatibility mode or this is not an ESM 34 // file that has been converted to a CommonJS file using a Babel- 35 // compatible transform (i.e. "__esModule" has not been set), then set 36 // "default" to the CommonJS "module.exports" for node compatibility. 37 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, 38 mod 39 )); 40 var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); 41 42 // package-external:@wordpress/data 43 var require_data = __commonJS({ 44 "package-external:@wordpress/data"(exports, module) { 45 module.exports = window.wp.data; 46 } 47 }); 48 49 // package-external:@wordpress/i18n 50 var require_i18n = __commonJS({ 51 "package-external:@wordpress/i18n"(exports, module) { 52 module.exports = window.wp.i18n; 53 } 54 }); 55 56 // package-external:@wordpress/blob 57 var require_blob = __commonJS({ 58 "package-external:@wordpress/blob"(exports, module) { 59 module.exports = window.wp.blob; 60 } 61 }); 62 63 // package-external:@wordpress/private-apis 64 var require_private_apis = __commonJS({ 65 "package-external:@wordpress/private-apis"(exports, module) { 66 module.exports = window.wp.privateApis; 67 } 68 }); 69 70 // package-external:@wordpress/element 71 var require_element = __commonJS({ 72 "package-external:@wordpress/element"(exports, module) { 73 module.exports = window.wp.element; 74 } 75 }); 76 77 // package-external:@wordpress/compose 78 var require_compose = __commonJS({ 79 "package-external:@wordpress/compose"(exports, module) { 80 module.exports = window.wp.compose; 81 } 82 }); 83 84 // vendor-external:react/jsx-runtime 85 var require_jsx_runtime = __commonJS({ 86 "vendor-external:react/jsx-runtime"(exports, module) { 87 module.exports = window.ReactJSXRuntime; 88 } 89 }); 90 91 // packages/upload-media/build-module/index.mjs 92 var index_exports = {}; 93 __export(index_exports, { 94 ErrorCode: () => ErrorCode, 95 MediaUploadProvider: () => provider_default, 96 UploadError: () => UploadError, 97 clearFeatureDetectionCache: () => clearFeatureDetectionCache, 98 detectClientSideMediaSupport: () => detectClientSideMediaSupport, 99 getErrorMessage: () => getErrorMessage, 100 getHeicConversionAdvice: () => getHeicConversionAdvice, 101 getHeicUnsupportedMessage: () => getHeicUnsupportedMessage, 102 isClientSideMediaSupported: () => isClientSideMediaSupported, 103 isClientSideSupportedFormat: () => isClientSideSupportedFormat, 104 isHeicCanvasSupported: () => isHeicCanvasSupported, 105 isHeicFile: () => isHeicFile, 106 store: () => store 107 }); 108 109 // packages/upload-media/build-module/store/index.mjs 110 var import_data = __toESM(require_data(), 1); 111 112 // packages/upload-media/build-module/store/types.mjs 113 var Type = /* @__PURE__ */ ((Type2) => { 114 Type2["Unknown"] = "REDUX_UNKNOWN"; 115 Type2["Add"] = "ADD_ITEM"; 116 Type2["Prepare"] = "PREPARE_ITEM"; 117 Type2["Cancel"] = "CANCEL_ITEM"; 118 Type2["Remove"] = "REMOVE_ITEM"; 119 Type2["RetryItem"] = "RETRY_ITEM"; 120 Type2["ScheduleRetry"] = "SCHEDULE_RETRY"; 121 Type2["PauseItem"] = "PAUSE_ITEM"; 122 Type2["ResumeItem"] = "RESUME_ITEM"; 123 Type2["PauseQueue"] = "PAUSE_QUEUE"; 124 Type2["ResumeQueue"] = "RESUME_QUEUE"; 125 Type2["OperationStart"] = "OPERATION_START"; 126 Type2["OperationFinish"] = "OPERATION_FINISH"; 127 Type2["AddOperations"] = "ADD_OPERATIONS"; 128 Type2["CacheBlobUrl"] = "CACHE_BLOB_URL"; 129 Type2["RevokeBlobUrls"] = "REVOKE_BLOB_URLS"; 130 Type2["UpdateProgress"] = "UPDATE_PROGRESS"; 131 Type2["AccumulateSubSize"] = "ACCUMULATE_SUB_SIZE"; 132 Type2["UpdateSettings"] = "UPDATE_SETTINGS"; 133 return Type2; 134 })(Type || {}); 135 var ItemStatus = /* @__PURE__ */ ((ItemStatus2) => { 136 ItemStatus2["Queued"] = "QUEUED"; 137 ItemStatus2["Processing"] = "PROCESSING"; 138 ItemStatus2["Paused"] = "PAUSED"; 139 ItemStatus2["PendingRetry"] = "PENDING_RETRY"; 140 ItemStatus2["Uploaded"] = "UPLOADED"; 141 ItemStatus2["Error"] = "ERROR"; 142 return ItemStatus2; 143 })(ItemStatus || {}); 144 var OperationType = /* @__PURE__ */ ((OperationType2) => { 145 OperationType2["Prepare"] = "PREPARE"; 146 OperationType2["Upload"] = "UPLOAD"; 147 OperationType2["ResizeCrop"] = "RESIZE_CROP"; 148 OperationType2["Rotate"] = "ROTATE"; 149 OperationType2["TranscodeImage"] = "TRANSCODE_IMAGE"; 150 OperationType2["TranscodeGif"] = "TRANSCODE_GIF"; 151 OperationType2["ThumbnailGeneration"] = "THUMBNAIL_GENERATION"; 152 OperationType2["Finalize"] = "FINALIZE"; 153 OperationType2["DetectUltraHdr"] = "DETECT_ULTRAHDR"; 154 return OperationType2; 155 })(OperationType || {}); 156 157 // packages/upload-media/build-module/store/constants.mjs 158 var STORE_NAME = "core/upload-media"; 159 var DEFAULT_MAX_CONCURRENT_UPLOADS = 5; 160 var DEFAULT_MAX_CONCURRENT_IMAGE_PROCESSING = 2; 161 var DEFAULT_RETRY_SETTINGS = { 162 maxRetryAttempts: 3, 163 initialRetryDelayMs: 1e3, 164 maxRetryDelayMs: 3e4, 165 backoffMultiplier: 2, 166 retryJitter: 0.1 167 }; 168 var CLIENT_SIDE_SUPPORTED_MIME_TYPES = [ 169 "image/jpeg", 170 "image/png", 171 "image/gif", 172 "image/webp", 173 "image/avif" 174 ]; 175 var HEIC_MIME_TYPES = [ 176 "image/heic", 177 "image/heif" 178 ]; 179 180 // packages/upload-media/build-module/store/reducer.mjs 181 var noop = () => { 182 }; 183 var DEFAULT_STATE = { 184 queue: [], 185 queueStatus: "active", 186 blobUrls: {}, 187 settings: { 188 mediaUpload: noop, 189 maxConcurrentUploads: DEFAULT_MAX_CONCURRENT_UPLOADS, 190 maxConcurrentImageProcessing: DEFAULT_MAX_CONCURRENT_IMAGE_PROCESSING, 191 retry: { ...DEFAULT_RETRY_SETTINGS } 192 }, 193 failureCount: 0 194 }; 195 function reducer(state = DEFAULT_STATE, action = { type: Type.Unknown }) { 196 switch (action.type) { 197 case Type.PauseQueue: { 198 return { 199 ...state, 200 queueStatus: "paused" 201 }; 202 } 203 case Type.ResumeQueue: { 204 return { 205 ...state, 206 queueStatus: "active" 207 }; 208 } 209 case Type.PauseItem: 210 return { 211 ...state, 212 queue: state.queue.map( 213 (item) => item.id === action.id ? { 214 ...item, 215 status: ItemStatus.Paused 216 } : item 217 ) 218 }; 219 case Type.ResumeItem: 220 return { 221 ...state, 222 queue: state.queue.map( 223 (item) => item.id === action.id ? { 224 ...item, 225 status: ItemStatus.Processing 226 } : item 227 ) 228 }; 229 case Type.Add: 230 return { 231 ...state, 232 queue: [...state.queue, action.item] 233 }; 234 case Type.Cancel: { 235 const cancelled = state.queue.find( 236 (item) => item.id === action.id 237 ); 238 return { 239 ...state, 240 failureCount: cancelled && !cancelled.parentId ? state.failureCount + 1 : state.failureCount, 241 queue: state.queue.map( 242 (item) => item.id === action.id ? { 243 ...item, 244 error: action.error 245 } : item 246 ) 247 }; 248 } 249 case Type.RetryItem: 250 return { 251 ...state, 252 queue: state.queue.map( 253 (item) => item.id === action.id ? { 254 ...item, 255 status: ItemStatus.Processing, 256 error: void 0, 257 retryCount: (item.retryCount ?? 0) + 1, 258 abortController: new AbortController(), 259 /* 260 * The failed operation is still recorded on 261 * the item: nothing finishes it when it 262 * fails, and while the item waits out the 263 * backoff that is what keeps it out of the 264 * concurrency pools. Clear it now that the 265 * item is about to run again, so processItem 266 * does not mistake it for an operation still 267 * in flight and skip the retry. 268 */ 269 currentOperation: void 0 270 } : item 271 ) 272 }; 273 case Type.ScheduleRetry: 274 return { 275 ...state, 276 queue: state.queue.map( 277 (item) => item.id === action.id ? { 278 ...item, 279 status: ItemStatus.PendingRetry, 280 error: action.error, 281 retryCount: action.retryCount, 282 nextRetryTimestamp: action.nextRetryTimestamp 283 } : item 284 ) 285 }; 286 case Type.Remove: 287 return { 288 ...state, 289 queue: state.queue.filter((item) => item.id !== action.id) 290 }; 291 case Type.OperationStart: { 292 return { 293 ...state, 294 queue: state.queue.map( 295 (item) => item.id === action.id ? { 296 ...item, 297 currentOperation: action.operation 298 } : item 299 ) 300 }; 301 } 302 case Type.AddOperations: 303 return { 304 ...state, 305 queue: state.queue.map((item) => { 306 if (item.id !== action.id) { 307 return item; 308 } 309 return { 310 ...item, 311 operations: [ 312 ...item.operations || [], 313 ...action.operations 314 ] 315 }; 316 }) 317 }; 318 case Type.OperationFinish: 319 return { 320 ...state, 321 queue: state.queue.map((item) => { 322 if (item.id !== action.id) { 323 return item; 324 } 325 const operations = item.operations ? item.operations.slice(1) : []; 326 const attachment = item.attachment || action.item.attachment ? { 327 ...item.attachment, 328 ...action.item.attachment 329 } : void 0; 330 return { 331 ...item, 332 currentOperation: void 0, 333 operations, 334 ...action.item, 335 attachment, 336 additionalData: { 337 ...item.additionalData, 338 ...action.item.additionalData 339 } 340 }; 341 }) 342 }; 343 case Type.CacheBlobUrl: { 344 const blobUrls = state.blobUrls[action.id] || []; 345 return { 346 ...state, 347 blobUrls: { 348 ...state.blobUrls, 349 [action.id]: [...blobUrls, action.blobUrl] 350 } 351 }; 352 } 353 case Type.RevokeBlobUrls: { 354 const newBlobUrls = { ...state.blobUrls }; 355 delete newBlobUrls[action.id]; 356 return { 357 ...state, 358 blobUrls: newBlobUrls 359 }; 360 } 361 case Type.UpdateProgress: 362 return { 363 ...state, 364 queue: state.queue.map( 365 (item) => item.id === action.id ? { 366 ...item, 367 progress: action.progress 368 } : item 369 ) 370 }; 371 case Type.AccumulateSubSize: 372 return { 373 ...state, 374 queue: state.queue.map( 375 (item) => item.id === action.id ? { 376 ...item, 377 subSizes: [ 378 ...item.subSizes || [], 379 action.subSize 380 ] 381 } : item 382 ) 383 }; 384 case Type.UpdateSettings: { 385 return { 386 ...state, 387 settings: { 388 ...state.settings, 389 ...action.settings 390 } 391 }; 392 } 393 } 394 return state; 395 } 396 var reducer_default = reducer; 397 398 // packages/upload-media/build-module/store/selectors.mjs 399 var selectors_exports = {}; 400 __export(selectors_exports, { 401 getItems: () => getItems, 402 getSettings: () => getSettings, 403 isUploading: () => isUploading, 404 isUploadingById: () => isUploadingById, 405 isUploadingByUrl: () => isUploadingByUrl 406 }); 407 function getItems(state) { 408 return state.queue; 409 } 410 function isUploading(state) { 411 return state.queue.length >= 1; 412 } 413 function isUploadingByUrl(state, url) { 414 return state.queue.some( 415 (item) => item.attachment?.url === url || item.sourceUrl === url 416 ); 417 } 418 function isUploadingById(state, attachmentId) { 419 return state.queue.some( 420 (item) => item.attachment?.id === attachmentId || item.sourceAttachmentId === attachmentId 421 ); 422 } 423 function getSettings(state) { 424 return state.settings; 425 } 426 427 // packages/upload-media/build-module/store/private-selectors.mjs 428 var private_selectors_exports = {}; 429 __export(private_selectors_exports, { 430 getActiveImageProcessingCount: () => getActiveImageProcessingCount, 431 getActiveUploadCount: () => getActiveUploadCount, 432 getActiveVideoProcessingCount: () => getActiveVideoProcessingCount, 433 getAllItems: () => getAllItems, 434 getBlobUrls: () => getBlobUrls, 435 getFailedItems: () => getFailedItems, 436 getFailureCount: () => getFailureCount, 437 getItem: () => getItem, 438 getItemProgress: () => getItemProgress, 439 getPendingImageProcessing: () => getPendingImageProcessing, 440 getPendingUploads: () => getPendingUploads, 441 getPendingVideoProcessing: () => getPendingVideoProcessing, 442 hasPendingItemsByParentId: () => hasPendingItemsByParentId, 443 isBatchUploaded: () => isBatchUploaded, 444 isPaused: () => isPaused 445 }); 446 function getAllItems(state) { 447 return state.queue; 448 } 449 function getFailureCount(state) { 450 return state.failureCount; 451 } 452 function getItem(state, id) { 453 return state.queue.find((item) => item.id === id); 454 } 455 function isBatchUploaded(state, batchId) { 456 const batchItems = state.queue.filter( 457 (item) => batchId === item.batchId 458 ); 459 return batchItems.length === 0; 460 } 461 function isPaused(state) { 462 return state.queueStatus === "paused"; 463 } 464 function getBlobUrls(state, id) { 465 return state.blobUrls[id] || []; 466 } 467 function getActiveUploadCount(state) { 468 return state.queue.filter( 469 (item) => item.currentOperation === OperationType.Upload 470 ).length; 471 } 472 function getPendingUploads(state) { 473 return state.queue.filter((item) => { 474 const nextOperation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0]; 475 return nextOperation === OperationType.Upload && item.currentOperation !== OperationType.Upload; 476 }); 477 } 478 function getActiveImageProcessingCount(state) { 479 return state.queue.filter( 480 (item) => item.currentOperation === OperationType.ResizeCrop || item.currentOperation === OperationType.Rotate 481 ).length; 482 } 483 function getActiveVideoProcessingCount(state) { 484 return state.queue.filter( 485 (item) => item.currentOperation === OperationType.TranscodeGif 486 ).length; 487 } 488 function getPendingImageProcessing(state) { 489 return state.queue.filter((item) => { 490 const nextOperation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0]; 491 return (nextOperation === OperationType.ResizeCrop || nextOperation === OperationType.Rotate) && item.currentOperation !== OperationType.ResizeCrop && item.currentOperation !== OperationType.Rotate; 492 }); 493 } 494 function getPendingVideoProcessing(state) { 495 return state.queue.filter((item) => { 496 const nextOperation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0]; 497 return nextOperation === OperationType.TranscodeGif && item.currentOperation !== OperationType.TranscodeGif; 498 }); 499 } 500 function getFailedItems(state) { 501 return state.queue.filter((item) => item.error !== void 0); 502 } 503 function hasPendingItemsByParentId(state, parentId) { 504 return state.queue.some((item) => item.parentId === parentId); 505 } 506 function getItemProgress(state, id) { 507 const item = state.queue.find((i) => i.id === id); 508 return item?.progress; 509 } 510 511 // packages/upload-media/build-module/store/actions.mjs 512 var actions_exports = {}; 513 __export(actions_exports, { 514 addItems: () => addItems, 515 cancelItem: () => cancelItem, 516 executeRetry: () => executeRetry, 517 retryItem: () => retryItem, 518 scheduleRetry: () => scheduleRetry 519 }); 520 521 // node_modules/.store/uuid@14.0.2-ALlTd6-Rf9bZs703d7TIjQ/node_modules/uuid/dist/stringify.js 522 var byteToHex = []; 523 for (let i = 0; i < 256; ++i) { 524 byteToHex.push((i + 256).toString(16).slice(1)); 525 } 526 function unsafeStringify(arr, offset = 0) { 527 return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); 528 } 529 530 // node_modules/.store/uuid@14.0.2-ALlTd6-Rf9bZs703d7TIjQ/node_modules/uuid/dist/rng.js 531 var rnds8 = new Uint8Array(16); 532 function rng() { 533 return crypto.getRandomValues(rnds8); 534 } 535 536 // node_modules/.store/uuid@14.0.2-ALlTd6-Rf9bZs703d7TIjQ/node_modules/uuid/dist/v4.js 537 function v4(options, buf, offset) { 538 if (!buf && !options && crypto.randomUUID) { 539 return crypto.randomUUID(); 540 } 541 return _v4(options, buf, offset); 542 } 543 function _v4(options, buf, offset) { 544 options = options || {}; 545 const rnds = options.random ?? options.rng?.() ?? rng(); 546 if (rnds.length < 16) { 547 throw new Error("Random bytes length must be >= 16"); 548 } 549 rnds[6] = rnds[6] & 15 | 64; 550 rnds[8] = rnds[8] & 63 | 128; 551 if (buf) { 552 offset = offset || 0; 553 if (offset < 0 || offset + 16 > buf.length) { 554 throw new RangeError(`UUID byte range $offset}:$offset + 15} is out of buffer bounds`); 555 } 556 for (let i = 0; i < 16; ++i) { 557 buf[offset + i] = rnds[i]; 558 } 559 return buf; 560 } 561 return unsafeStringify(rnds); 562 } 563 var v4_default = v4; 564 565 // packages/upload-media/build-module/store/actions.mjs 566 var import_i18n4 = __toESM(require_i18n(), 1); 567 568 // packages/upload-media/build-module/store/utils/retry.mjs 569 function calculateRetryDelay(options) { 570 const { attempt, initialDelay, maxDelay, multiplier, jitter } = options; 571 const exponentialDelay = initialDelay * Math.pow(multiplier, attempt - 1); 572 const cappedDelay = Math.min(exponentialDelay, maxDelay); 573 const jitterFactor = 1 + (Math.random() * 2 - 1) * jitter; 574 return Math.floor(cappedDelay * jitterFactor); 575 } 576 var RETRYABLE_MESSAGE_PATTERNS = [ 577 /network/i, 578 /timeout/i, 579 /ECONNRESET/i, 580 /fetch failed/i, 581 /connection/i, 582 /socket/i, 583 /ETIMEDOUT/i, 584 /ENOTFOUND/i, 585 /Could not get a valid response/i, 586 /Failed to fetch/i, 587 /Load failed/i 588 ]; 589 function shouldRetryError(error, retryCount, maxRetries) { 590 if (retryCount >= maxRetries) { 591 return false; 592 } 593 const message = typeof error === "string" ? error : error?.message || ""; 594 return RETRYABLE_MESSAGE_PATTERNS.some( 595 (pattern) => pattern.test(message) 596 ); 597 } 598 var retryTimers = /* @__PURE__ */ new Map(); 599 function clearRetryTimer(id) { 600 const pendingTimer = retryTimers.get(id); 601 if (pendingTimer !== void 0) { 602 clearTimeout(pendingTimer); 603 retryTimers.delete(id); 604 } 605 } 606 607 // packages/upload-media/build-module/feature-detection.mjs 608 var cachedResult = null; 609 function detectClientSideMediaSupport() { 610 if (cachedResult !== null) { 611 return cachedResult; 612 } 613 if (typeof WebAssembly === "undefined") { 614 cachedResult = { 615 supported: false, 616 reason: "WebAssembly is not supported in this browser." 617 }; 618 return cachedResult; 619 } 620 if (typeof SharedArrayBuffer === "undefined") { 621 cachedResult = { 622 supported: false, 623 reason: "SharedArrayBuffer is not available. This may be due to missing cross-origin isolation headers." 624 }; 625 return cachedResult; 626 } 627 if (typeof Worker === "undefined") { 628 cachedResult = { 629 supported: false, 630 reason: "Web Workers are not supported in this browser." 631 }; 632 return cachedResult; 633 } 634 if (typeof navigator !== "undefined" && "deviceMemory" in navigator && navigator.deviceMemory <= 2) { 635 cachedResult = { 636 supported: false, 637 reason: "Device has insufficient memory for client-side media processing." 638 }; 639 return cachedResult; 640 } 641 if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency < 2) { 642 cachedResult = { 643 supported: false, 644 reason: "Device has insufficient CPU cores for client-side media processing." 645 }; 646 return cachedResult; 647 } 648 if (typeof navigator !== "undefined") { 649 const connection = navigator.connection; 650 if (connection) { 651 if (connection.saveData) { 652 cachedResult = { 653 supported: false, 654 reason: "Data saver mode is enabled." 655 }; 656 return cachedResult; 657 } 658 if (connection.effectiveType === "slow-2g" || connection.effectiveType === "2g") { 659 cachedResult = { 660 supported: false, 661 reason: "Network connection is too slow for client-side media processing." 662 }; 663 return cachedResult; 664 } 665 } 666 } 667 if (typeof window !== "undefined") { 668 try { 669 const testBlob = new Blob([""], { 670 type: "application/javascript" 671 }); 672 const testUrl = URL.createObjectURL(testBlob); 673 try { 674 const testWorker = new Worker(testUrl); 675 testWorker.terminate(); 676 } finally { 677 URL.revokeObjectURL(testUrl); 678 } 679 } catch { 680 cachedResult = { 681 supported: false, 682 reason: "The site's Content Security Policy (CSP) does not allow blob: workers. The worker-src directive must include blob: to enable client-side media processing." 683 }; 684 return cachedResult; 685 } 686 } 687 cachedResult = { supported: true }; 688 return cachedResult; 689 } 690 function isClientSideMediaSupported() { 691 return detectClientSideMediaSupport().supported; 692 } 693 function isHeicCanvasSupported() { 694 return typeof createImageBitmap !== "undefined" && typeof OffscreenCanvas !== "undefined"; 695 } 696 function clearFeatureDetectionCache() { 697 cachedResult = null; 698 } 699 var BYTES_PER_PIXEL = 4; 700 var INTERLACED_MEMORY_BUDGET = 0.75 * 1024 * 1024 * 1024; 701 var BASELINE_MEMORY_BUDGET = 1.5 * 1024 * 1024 * 1024; 702 function exceedsClientProcessingMemory(dimensions) { 703 const { width, height, interlaced } = dimensions; 704 const estimatedBytes = width * height * BYTES_PER_PIXEL; 705 const budget = interlaced ? INTERLACED_MEMORY_BUDGET : BASELINE_MEMORY_BUDGET; 706 return estimatedBytes > budget; 707 } 708 709 // packages/upload-media/build-module/image-file.mjs 710 var ImageFile = class extends File { 711 width = 0; 712 height = 0; 713 originalWidth = 0; 714 originalHeight = 0; 715 get wasResized() { 716 return (this.originalWidth || 0) > this.width || (this.originalHeight || 0) > this.height; 717 } 718 constructor(file, width, height, originalWidth, originalHeight) { 719 super([file], file.name, { 720 type: file.type, 721 lastModified: file.lastModified 722 }); 723 this.width = width; 724 this.height = height; 725 this.originalWidth = originalWidth; 726 this.originalHeight = originalHeight; 727 } 728 }; 729 730 // packages/upload-media/build-module/utils.mjs 731 function convertBlobToFile(fileOrBlob) { 732 if (fileOrBlob instanceof File) { 733 return fileOrBlob; 734 } 735 if ("name" in fileOrBlob && typeof fileOrBlob.name === "string") { 736 return new File([fileOrBlob], fileOrBlob.name, { 737 type: fileOrBlob.type, 738 lastModified: fileOrBlob.lastModified 739 }); 740 } 741 const ext = fileOrBlob.type.split("/")[1]; 742 const mediaType = "application/pdf" === fileOrBlob.type ? "document" : fileOrBlob.type.split("/")[0]; 743 return new File([fileOrBlob], `$mediaType}.$ext}`, { 744 type: fileOrBlob.type 745 }); 746 } 747 function renameFile(file, name) { 748 return new File([file], name, { 749 type: file.type, 750 lastModified: file.lastModified 751 }); 752 } 753 function cloneFile(file) { 754 return renameFile(file, file.name); 755 } 756 function getFileBasename(name) { 757 return name.includes(".") ? name.split(".").slice(0, -1).join(".") : name; 758 } 759 function isAnimatedGif(buffer) { 760 const view = new Uint8Array(buffer); 761 if (view.length < 4 || view[0] !== 71 || view[1] !== 73 || view[2] !== 70 || view[3] !== 56) { 762 return false; 763 } 764 let frameCount = 0; 765 for (let i = 0; i < view.length - 2; i++) { 766 if (view[i] === 0 && view[i + 1] === 33 && view[i + 2] === 249) { 767 frameCount++; 768 if (frameCount > 1) { 769 return true; 770 } 771 } 772 } 773 return false; 774 } 775 var FILE_TYPE_BOX_BYTES = 64; 776 var HEIC_BRANDS = [ 777 "heic", 778 "heix", 779 "heim", 780 "heis", 781 "hevc", 782 "hevx", 783 "hevm", 784 "hevs", 785 "mif1", 786 "msf1" 787 ]; 788 var AVIF_BRANDS = ["avif", "avis"]; 789 function isHeicBuffer(buffer) { 790 const view = new Uint8Array(buffer); 791 const readBrand = (offset) => String.fromCharCode(...view.subarray(offset, offset + 4)); 792 if (view.length < 12 || readBrand(4) !== "ftyp") { 793 return false; 794 } 795 const boxEnd = Math.min( 796 view.length, 797 new DataView(buffer).getUint32(0) 798 ); 799 const brands = [readBrand(8)]; 800 for (let offset = 16; offset + 4 <= boxEnd; offset += 4) { 801 brands.push(readBrand(offset)); 802 } 803 if (brands.some((brand) => AVIF_BRANDS.includes(brand))) { 804 return false; 805 } 806 return brands.some((brand) => HEIC_BRANDS.includes(brand)); 807 } 808 async function isHeicFile(file) { 809 if (HEIC_MIME_TYPES.includes(file.type)) { 810 return true; 811 } 812 if (file.type && !file.type.startsWith("image/")) { 813 return false; 814 } 815 try { 816 return isHeicBuffer( 817 await file.slice(0, FILE_TYPE_BOX_BYTES).arrayBuffer() 818 ); 819 } catch { 820 return false; 821 } 822 } 823 function isClientSideSupportedFormat(file) { 824 const type = (file.type || "").toLowerCase(); 825 if (CLIENT_SIDE_SUPPORTED_MIME_TYPES.includes(type) || HEIC_MIME_TYPES.includes(type)) { 826 return true; 827 } 828 return /\.hei[cf]$/i.test(file.name || ""); 829 } 830 831 // packages/upload-media/build-module/store/utils/index.mjs 832 var vipsModulePromise; 833 var vipsModule; 834 function loadVipsModule() { 835 if (!vipsModulePromise) { 836 vipsModulePromise = import("@wordpress/vips/worker").then( 837 (mod) => { 838 vipsModule = mod; 839 return mod; 840 } 841 ); 842 } 843 return vipsModulePromise; 844 } 845 async function vipsConvertImageFormat(id, file, type, options = {}) { 846 const { vipsConvertImageFormat: convertImageFormat } = await loadVipsModule(); 847 const buffer = await convertImageFormat( 848 id, 849 await file.arrayBuffer(), 850 file.type, 851 type, 852 options 853 ); 854 const ext = type.split("/")[1]; 855 const fileName = `$getFileBasename(file.name)}.$ext}`; 856 return new File([new Blob([buffer])], fileName, { 857 type 858 }); 859 } 860 async function vipsEncodeCanvasAsJpeg(id, canvas, source, quality) { 861 const { width, height } = canvas; 862 if (exceedsClientProcessingMemory({ width, height, interlaced: true })) { 863 return null; 864 } 865 const { vipsEncodePixelsAsJpeg: encodePixelsAsJpeg } = await loadVipsModule(); 866 const ctx = canvas.getContext("2d"); 867 if (!ctx) { 868 throw new Error("Could not get canvas 2d context"); 869 } 870 const pixels = ctx.getImageData(0, 0, width, height).data.buffer; 871 const buffer = await encodePixelsAsJpeg(id, pixels, width, height, { 872 quality, 873 metadataSource: await source.arrayBuffer() 874 }); 875 return new Blob([buffer], { type: "image/jpeg" }); 876 } 877 async function vipsHasTransparency(url) { 878 const { vipsHasTransparency: hasTransparency } = await loadVipsModule(); 879 const response = await fetch(url); 880 if (!response.ok) { 881 throw new Error(`Failed to fetch image: $response.status}`); 882 } 883 return hasTransparency(await response.arrayBuffer()); 884 } 885 async function vipsGetUltraHdrInfo(buffer) { 886 const { vipsGetUltraHdrInfo: getUltraHdrInfo } = await loadVipsModule(); 887 return getUltraHdrInfo(buffer); 888 } 889 async function vipsResizeImage(id, file, resize, options = {}) { 890 const { 891 smartCrop = false, 892 addSuffix = false, 893 signal, 894 scaledSuffix, 895 quality, 896 stripMeta, 897 maxBitdepth, 898 preserveAnimation 899 } = options; 900 if (signal?.aborted) { 901 throw new Error("Operation aborted"); 902 } 903 const { vipsResizeImage: resizeImage } = await loadVipsModule(); 904 const { buffer, width, height, originalWidth, originalHeight } = await resizeImage(id, await file.arrayBuffer(), file.type, resize, { 905 smartCrop, 906 quality, 907 stripMeta, 908 maxBitdepth, 909 preserveAnimation 910 }); 911 let fileName = file.name; 912 const wasResized = originalWidth > width || originalHeight > height; 913 if (wasResized) { 914 const basename = getFileBasename(file.name); 915 if (scaledSuffix) { 916 fileName = file.name.replace(basename, `$basename}-scaled`); 917 } else if (addSuffix) { 918 fileName = file.name.replace( 919 basename, 920 `$basename}-$width}x$height}` 921 ); 922 } 923 } 924 const resultFile = new ImageFile( 925 new File( 926 [new Blob([buffer], { type: file.type })], 927 fileName, 928 { 929 type: file.type 930 } 931 ), 932 width, 933 height, 934 originalWidth, 935 originalHeight 936 ); 937 return resultFile; 938 } 939 async function vipsRotateImage(id, file, orientation, signal) { 940 if (signal?.aborted) { 941 throw new Error("Operation aborted"); 942 } 943 if (orientation === 1) { 944 return file; 945 } 946 const { vipsRotateImage: rotateImage } = await loadVipsModule(); 947 const { buffer, width, height } = await rotateImage( 948 id, 949 await file.arrayBuffer(), 950 file.type, 951 orientation 952 ); 953 const basename = getFileBasename(file.name); 954 const fileName = file.name.replace(basename, `$basename}-rotated`); 955 const resultFile = new ImageFile( 956 new File( 957 [new Blob([buffer], { type: file.type })], 958 fileName, 959 { 960 type: file.type 961 } 962 ), 963 width, 964 height 965 ); 966 return resultFile; 967 } 968 async function vipsCancelOperations(id) { 969 if (!vipsModule) { 970 return false; 971 } 972 return vipsModule.vipsCancelOperations(id); 973 } 974 function terminateVipsWorker() { 975 if (vipsModule) { 976 vipsModule.terminateVipsWorker(); 977 } 978 } 979 var completedVipsOperations = 0; 980 var MAX_VIPS_OPS_BEFORE_RECYCLE = 50; 981 function maybeRecycleVipsWorker(activeImageProcessingCount) { 982 completedVipsOperations++; 983 if (completedVipsOperations >= MAX_VIPS_OPS_BEFORE_RECYCLE && activeImageProcessingCount === 0) { 984 terminateVipsWorker(); 985 completedVipsOperations = 0; 986 } 987 } 988 989 // packages/upload-media/build-module/store/utils/video-conversion.mjs 990 var UNSUPPORTED_ERROR_PREFIX = "Unsupported"; 991 var SIZE_LIMIT_ERROR_PREFIX = `$UNSUPPORTED_ERROR_PREFIX}: GIF exceeds maximum conversion size`; 992 var CONVERSION_TIMEOUT_ERROR_PREFIX = "GIF to video conversion timed out"; 993 var DEFAULT_CONVERSION_TIMEOUT = 3e4; 994 function isUnsupportedConversionError(error) { 995 return error instanceof Error && error.message.startsWith(UNSUPPORTED_ERROR_PREFIX); 996 } 997 function isSizeLimitConversionError(error) { 998 return error instanceof Error && error.message.startsWith(SIZE_LIMIT_ERROR_PREFIX); 999 } 1000 function isConversionTimeoutError(error) { 1001 return error instanceof Error && error.message.startsWith(CONVERSION_TIMEOUT_ERROR_PREFIX); 1002 } 1003 var videoConversionModulePromise; 1004 var videoConversionModule; 1005 function loadVideoConversionModule() { 1006 if (!videoConversionModulePromise) { 1007 videoConversionModulePromise = import("@wordpress/video-conversion/worker").then((mod) => { 1008 videoConversionModule = mod; 1009 return mod; 1010 }).catch((error) => { 1011 videoConversionModulePromise = void 0; 1012 throw error; 1013 }); 1014 } 1015 return videoConversionModulePromise; 1016 } 1017 async function convertGifToVideo(id, file, outputMimeType, { 1018 maxDimensions, 1019 timeout = DEFAULT_CONVERSION_TIMEOUT, 1020 maxTotalPixels 1021 } = {}) { 1022 const mod = await loadVideoConversionModule(); 1023 const conversion = mod.convertGifToVideo( 1024 id, 1025 file, 1026 outputMimeType, 1027 maxDimensions, 1028 maxTotalPixels 1029 ); 1030 let buffer; 1031 if (timeout > 0) { 1032 let timer; 1033 try { 1034 buffer = await Promise.race([ 1035 conversion, 1036 new Promise((_, reject) => { 1037 timer = setTimeout(() => { 1038 reject( 1039 new Error( 1040 `$CONVERSION_TIMEOUT_ERROR_PREFIX} after $timeout}ms` 1041 ) 1042 ); 1043 }, timeout); 1044 }) 1045 ]); 1046 } catch (error) { 1047 if (isConversionTimeoutError(error)) { 1048 conversion.catch(() => { 1049 }); 1050 mod.cancelGifToVideoOperations(id).catch(() => { 1051 }); 1052 } 1053 throw error; 1054 } finally { 1055 clearTimeout(timer); 1056 } 1057 } else { 1058 buffer = await conversion; 1059 } 1060 const ext = outputMimeType === "video/webm" ? "webm" : "mp4"; 1061 const fileName = `$getFileBasename(file.name)}.$ext}`; 1062 return new File( 1063 [new Blob([buffer], { type: outputMimeType })], 1064 fileName, 1065 { type: outputMimeType } 1066 ); 1067 } 1068 async function cancelGifToVideoOperations(id) { 1069 const mod = videoConversionModule ?? (videoConversionModulePromise ? await videoConversionModulePromise.catch(() => void 0) : void 0); 1070 if (!mod) { 1071 return false; 1072 } 1073 return mod.cancelGifToVideoOperations(id); 1074 } 1075 function terminateVideoConversionWorker() { 1076 if (videoConversionModule) { 1077 videoConversionModule.terminateVideoConversionWorker(); 1078 return; 1079 } 1080 if (videoConversionModulePromise) { 1081 void videoConversionModulePromise.then((mod) => mod.terminateVideoConversionWorker()).catch(() => { 1082 }); 1083 } 1084 } 1085 1086 // packages/upload-media/build-module/store/utils/debug-logger.mjs 1087 function isDebugEnabled() { 1088 return true; 1089 } 1090 function debug(message, ...args) { 1091 if (!isDebugEnabled()) { 1092 return; 1093 } 1094 console.debug(`[upload-media] $message}`, ...args); 1095 } 1096 function measure(options) { 1097 if (!isDebugEnabled()) { 1098 return; 1099 } 1100 const { 1101 measureName, 1102 startTime, 1103 endTime = performance.now(), 1104 tooltipText, 1105 properties 1106 } = options; 1107 const detail = { 1108 devtools: { 1109 dataType: "track-entry", 1110 track: "Upload Media", 1111 tooltipText, 1112 properties: properties?.map(([key, value]) => ({ 1113 key, 1114 value 1115 })) 1116 } 1117 }; 1118 try { 1119 performance.measure(measureName, { 1120 start: startTime, 1121 end: endTime, 1122 detail 1123 }); 1124 } catch { 1125 } 1126 } 1127 1128 // packages/upload-media/build-module/upload-error.mjs 1129 var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => { 1130 ErrorCode2["EMPTY_FILE"] = "EMPTY_FILE"; 1131 ErrorCode2["SIZE_ABOVE_LIMIT"] = "SIZE_ABOVE_LIMIT"; 1132 ErrorCode2["MIME_TYPE_NOT_SUPPORTED"] = "MIME_TYPE_NOT_SUPPORTED"; 1133 ErrorCode2["MIME_TYPE_NOT_ALLOWED_FOR_USER"] = "MIME_TYPE_NOT_ALLOWED_FOR_USER"; 1134 ErrorCode2["HEIC_DECODE_ERROR"] = "HEIC_DECODE_ERROR"; 1135 ErrorCode2["IMAGE_TRANSCODING_ERROR"] = "IMAGE_TRANSCODING_ERROR"; 1136 ErrorCode2["IMAGE_ROTATION_ERROR"] = "IMAGE_ROTATION_ERROR"; 1137 ErrorCode2["MEDIA_TRANSCODING_ERROR"] = "MEDIA_TRANSCODING_ERROR"; 1138 ErrorCode2["GIF_TRANSCODING_ERROR"] = "GIF_TRANSCODING_ERROR"; 1139 ErrorCode2["MEDIA_FINALIZE_ERROR"] = "MEDIA_FINALIZE_ERROR"; 1140 ErrorCode2["GENERAL"] = "GENERAL"; 1141 return ErrorCode2; 1142 })(ErrorCode || {}); 1143 var UploadError = class extends Error { 1144 code; 1145 file; 1146 constructor({ code, message, file, cause }) { 1147 super(message, { cause }); 1148 Object.setPrototypeOf(this, new.target.prototype); 1149 this.code = code; 1150 this.file = file; 1151 } 1152 }; 1153 1154 // packages/upload-media/build-module/validate-mime-type.mjs 1155 var import_i18n = __toESM(require_i18n(), 1); 1156 function validateMimeType(file, allowedTypes) { 1157 if (!allowedTypes) { 1158 return; 1159 } 1160 const isAllowedType = allowedTypes.some((allowedType) => { 1161 if (allowedType.includes("/")) { 1162 return allowedType === file.type; 1163 } 1164 return file.type.startsWith(`$allowedType}/`); 1165 }); 1166 if (file.type && !isAllowedType) { 1167 throw new UploadError({ 1168 code: ErrorCode.MIME_TYPE_NOT_SUPPORTED, 1169 message: (0, import_i18n.sprintf)( 1170 // translators: %s: file name. 1171 (0, import_i18n.__)("%s: Sorry, this file type is not supported here."), 1172 file.name 1173 ), 1174 file 1175 }); 1176 } 1177 } 1178 1179 // packages/upload-media/build-module/validate-mime-type-for-user.mjs 1180 var import_i18n2 = __toESM(require_i18n(), 1); 1181 1182 // packages/upload-media/build-module/get-mime-types-array.mjs 1183 function getMimeTypesArray(wpMimeTypesObject) { 1184 if (!wpMimeTypesObject) { 1185 return null; 1186 } 1187 return Object.entries(wpMimeTypesObject).flatMap( 1188 ([extensionsString, mime]) => { 1189 const [type] = mime.split("/"); 1190 const extensions = extensionsString.split("|"); 1191 return [ 1192 mime, 1193 ...extensions.map( 1194 (extension) => `$type}/$extension}` 1195 ) 1196 ]; 1197 } 1198 ); 1199 } 1200 1201 // packages/upload-media/build-module/validate-mime-type-for-user.mjs 1202 function validateMimeTypeForUser(file, wpAllowedMimeTypes) { 1203 const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes); 1204 if (!allowedMimeTypesForUser) { 1205 return; 1206 } 1207 const isAllowedMimeTypeForUser = allowedMimeTypesForUser.includes( 1208 file.type 1209 ); 1210 if (file.type && !isAllowedMimeTypeForUser) { 1211 throw new UploadError({ 1212 code: ErrorCode.MIME_TYPE_NOT_ALLOWED_FOR_USER, 1213 message: (0, import_i18n2.sprintf)( 1214 // translators: %s: file name. 1215 (0, import_i18n2.__)( 1216 "%s: Sorry, you are not allowed to upload this file type." 1217 ), 1218 file.name 1219 ), 1220 file 1221 }); 1222 } 1223 } 1224 1225 // packages/upload-media/build-module/validate-file-size.mjs 1226 var import_i18n3 = __toESM(require_i18n(), 1); 1227 function validateFileSize(file, maxUploadFileSize) { 1228 if (file.size <= 0) { 1229 throw new UploadError({ 1230 code: ErrorCode.EMPTY_FILE, 1231 message: (0, import_i18n3.sprintf)( 1232 // translators: %s: file name. 1233 (0, import_i18n3.__)("%s: This file is empty."), 1234 file.name 1235 ), 1236 file 1237 }); 1238 } 1239 if (maxUploadFileSize && file.size > maxUploadFileSize) { 1240 throw new UploadError({ 1241 code: ErrorCode.SIZE_ABOVE_LIMIT, 1242 message: (0, import_i18n3.sprintf)( 1243 // translators: %s: file name. 1244 (0, import_i18n3.__)( 1245 "%s: This file exceeds the maximum upload size for this site." 1246 ), 1247 file.name 1248 ), 1249 file 1250 }); 1251 } 1252 } 1253 1254 // packages/upload-media/build-module/store/actions.mjs 1255 function addItems({ 1256 files, 1257 onChange, 1258 onSuccess, 1259 onError, 1260 onBatchSuccess, 1261 additionalData, 1262 allowedTypes 1263 }) { 1264 return async ({ select: select2, dispatch }) => { 1265 const batchId = v4_default(); 1266 for (const file of files) { 1267 try { 1268 validateMimeType(file, allowedTypes); 1269 validateMimeTypeForUser( 1270 file, 1271 select2.getSettings().allowedMimeTypes 1272 ); 1273 } catch (error) { 1274 onError?.(error); 1275 continue; 1276 } 1277 try { 1278 validateFileSize( 1279 file, 1280 select2.getSettings().maxUploadFileSize 1281 ); 1282 } catch (error) { 1283 onError?.(error); 1284 continue; 1285 } 1286 dispatch.addItem({ 1287 file, 1288 batchId, 1289 onChange, 1290 onSuccess, 1291 onBatchSuccess, 1292 onError, 1293 additionalData 1294 }); 1295 } 1296 }; 1297 } 1298 function cancelItem(id, error, silent = false) { 1299 return async ({ select: select2, dispatch }) => { 1300 const item = select2.getItem(id); 1301 if (!item) { 1302 return; 1303 } 1304 clearRetryTimer(id); 1305 if (!silent && error && !item.parentId && !item.attachment?.id) { 1306 const settings = select2.getSettings(); 1307 const retrySettings = settings.retry; 1308 if (retrySettings) { 1309 const retryCount = item.retryCount ?? 0; 1310 const maxRetries = retrySettings.maxRetryAttempts; 1311 if (shouldRetryError(error, retryCount, maxRetries)) { 1312 dispatch.scheduleRetry(id, error); 1313 return; 1314 } 1315 } 1316 } 1317 item.abortController?.abort(); 1318 vipsCancelOperations(id).catch(() => { 1319 }); 1320 cancelGifToVideoOperations(id).catch(() => { 1321 }); 1322 if (!silent) { 1323 const { onError } = item; 1324 onError?.(error ?? new Error("Upload cancelled")); 1325 if (!onError && error && !item.parentId) { 1326 console.error("Upload cancelled", error); 1327 } 1328 } else { 1329 debug( 1330 `Item cancelled: $item.file.name} (item $id}): $error instanceof Error ? error.message : error}` 1331 ); 1332 } 1333 const { currentOperation, parentId, batchId } = item; 1334 dispatch({ 1335 type: Type.Cancel, 1336 id, 1337 error 1338 }); 1339 dispatch.removeItem(id); 1340 dispatch.revokeBlobUrls(id); 1341 if (currentOperation === OperationType.ResizeCrop || currentOperation === OperationType.Rotate) { 1342 for (const pending of select2.getPendingImageProcessing()) { 1343 dispatch.processItem(pending.id); 1344 } 1345 } 1346 if (currentOperation === OperationType.Upload) { 1347 for (const pending of select2.getPendingUploads()) { 1348 dispatch.processItem(pending.id); 1349 } 1350 } 1351 if (currentOperation === OperationType.TranscodeGif) { 1352 for (const pending of select2.getPendingVideoProcessing()) { 1353 dispatch.processItem(pending.id); 1354 } 1355 } 1356 if (currentOperation === OperationType.ResizeCrop || currentOperation === OperationType.Rotate || currentOperation === OperationType.TranscodeImage) { 1357 maybeRecycleVipsWorker(select2.getActiveImageProcessingCount()); 1358 } 1359 if (parentId) { 1360 const parentItem = select2.getItem(parentId); 1361 if (parentItem) { 1362 const isOptionalCompanion = item.additionalData?.image_size === "animated_video" || item.additionalData?.image_size === "animated_video_poster"; 1363 if (select2.hasPendingItemsByParentId(parentId)) { 1364 if (parentItem.operations && parentItem.operations.length > 0) { 1365 dispatch.processItem(parentId); 1366 } 1367 } else if (parentItem.subSizes && parentItem.subSizes.length > 0 || isOptionalCompanion) { 1368 if (parentItem.operations && parentItem.operations.length > 0) { 1369 dispatch.processItem(parentId); 1370 } 1371 } else { 1372 const parentAttachmentId = parentItem.attachment?.id; 1373 const { mediaDelete } = select2.getSettings(); 1374 if (parentAttachmentId && mediaDelete) { 1375 mediaDelete(parentAttachmentId).catch(() => { 1376 }); 1377 } 1378 await dispatch.cancelItem( 1379 parentId, 1380 new UploadError({ 1381 code: error instanceof UploadError && error.code || ErrorCode.GENERAL, 1382 message: error?.message || (0, import_i18n4.__)("The image could not be uploaded."), 1383 file: parentItem.file, 1384 cause: error instanceof Error ? error : void 0 1385 }) 1386 ); 1387 } 1388 } 1389 } 1390 if (batchId && select2.isBatchUploaded(batchId)) { 1391 debug(`Batch completed: $batchId}`); 1392 item.onBatchSuccess?.(); 1393 } 1394 }; 1395 } 1396 function retryItem(id) { 1397 return async ({ select: select2, dispatch }) => { 1398 const item = select2.getItem(id); 1399 if (!item) { 1400 return; 1401 } 1402 if (!item.error) { 1403 return; 1404 } 1405 dispatch({ 1406 type: Type.RetryItem, 1407 id 1408 }); 1409 dispatch.processItem(id); 1410 }; 1411 } 1412 function scheduleRetry(id, error) { 1413 return async ({ select: select2, dispatch }) => { 1414 const item = select2.getItem(id); 1415 if (!item) { 1416 return; 1417 } 1418 const settings = select2.getSettings(); 1419 const retrySettings = settings.retry; 1420 if (!retrySettings) { 1421 return; 1422 } 1423 const currentRetryCount = item.retryCount ?? 0; 1424 const delay = calculateRetryDelay({ 1425 attempt: currentRetryCount + 1, 1426 initialDelay: retrySettings.initialRetryDelayMs, 1427 maxDelay: retrySettings.maxRetryDelayMs, 1428 multiplier: retrySettings.backoffMultiplier, 1429 jitter: retrySettings.retryJitter 1430 }); 1431 const timerId = setTimeout(() => { 1432 retryTimers.delete(id); 1433 dispatch.executeRetry(id); 1434 }, delay); 1435 retryTimers.set(id, timerId); 1436 dispatch({ 1437 type: Type.ScheduleRetry, 1438 id, 1439 error, 1440 retryCount: currentRetryCount, 1441 nextRetryTimestamp: Date.now() + delay 1442 }); 1443 }; 1444 } 1445 function executeRetry(id) { 1446 return async ({ select: select2, dispatch }) => { 1447 const item = select2.getItem(id); 1448 if (!item || item.status !== ItemStatus.PendingRetry) { 1449 return; 1450 } 1451 if (select2.isPaused()) { 1452 return; 1453 } 1454 dispatch({ 1455 type: Type.RetryItem, 1456 id 1457 }); 1458 dispatch.processItem(id); 1459 }; 1460 } 1461 1462 // packages/upload-media/build-module/store/private-actions.mjs 1463 var private_actions_exports = {}; 1464 __export(private_actions_exports, { 1465 addItem: () => addItem, 1466 addSideloadItem: () => addSideloadItem, 1467 detectUltraHdr: () => detectUltraHdr, 1468 finalizeItem: () => finalizeItem, 1469 finishOperation: () => finishOperation, 1470 generateThumbnails: () => generateThumbnails, 1471 getTranscodeImageOperation: () => getTranscodeImageOperation, 1472 pauseItem: () => pauseItem, 1473 pauseQueue: () => pauseQueue, 1474 prepareItem: () => prepareItem, 1475 processItem: () => processItem, 1476 removeItem: () => removeItem, 1477 resizeCropItem: () => resizeCropItem, 1478 resumeQueue: () => resumeQueue, 1479 revokeBlobUrls: () => revokeBlobUrls, 1480 rotateItem: () => rotateItem, 1481 sideloadItem: () => sideloadItem, 1482 transcodeGifItem: () => transcodeGifItem, 1483 transcodeImageItem: () => transcodeImageItem, 1484 updateItemProgress: () => updateItemProgress, 1485 updateSettings: () => updateSettings, 1486 uploadItem: () => uploadItem 1487 }); 1488 var import_blob = __toESM(require_blob(), 1); 1489 var import_i18n6 = __toESM(require_i18n(), 1); 1490 1491 // packages/upload-media/build-module/heic-parser.mjs 1492 var Reader = class { 1493 view; 1494 buffer; 1495 pos; 1496 constructor(buffer, offset = 0) { 1497 this.buffer = buffer; 1498 this.view = new DataView(buffer); 1499 this.pos = offset; 1500 } 1501 u8() { 1502 const v = this.view.getUint8(this.pos); 1503 this.pos += 1; 1504 return v; 1505 } 1506 u16() { 1507 const v = this.view.getUint16(this.pos); 1508 this.pos += 2; 1509 return v; 1510 } 1511 u32() { 1512 const v = this.view.getUint32(this.pos); 1513 this.pos += 4; 1514 return v; 1515 } 1516 u64() { 1517 const hi = this.view.getUint32(this.pos); 1518 const lo = this.view.getUint32(this.pos + 4); 1519 this.pos += 8; 1520 return hi * 4294967296 + lo; 1521 } 1522 /** 1523 * Read a variable-width unsigned integer (0, 4 or 8 bytes). 1524 * 1525 * @param size Byte width to read (0, 4, or 8). 1526 */ 1527 uN(size) { 1528 if (size === 0) { 1529 return 0; 1530 } 1531 if (size === 4) { 1532 return this.u32(); 1533 } 1534 if (size === 8) { 1535 return this.u64(); 1536 } 1537 throw new Error(`Unsupported uint size: $size}`); 1538 } 1539 str(len) { 1540 let s = ""; 1541 for (let i = 0; i < len; i++) { 1542 s += String.fromCharCode(this.view.getUint8(this.pos + i)); 1543 } 1544 this.pos += len; 1545 return s; 1546 } 1547 bytes(len) { 1548 const b = new Uint8Array(this.buffer, this.pos, len); 1549 this.pos += len; 1550 return new Uint8Array(b); 1551 } 1552 }; 1553 function readBox(r) { 1554 if (r.pos + 8 > r.view.byteLength) { 1555 return null; 1556 } 1557 const offset = r.pos; 1558 let size = r.u32(); 1559 const type = r.str(4); 1560 let headerSize = 8; 1561 if (size === 1) { 1562 size = r.u64(); 1563 headerSize = 16; 1564 } else if (size === 0) { 1565 size = r.view.byteLength - offset; 1566 } 1567 return { type, offset, size, headerSize }; 1568 } 1569 function findBoxes(r, start, end) { 1570 const boxes = []; 1571 r.pos = start; 1572 while (r.pos < end) { 1573 const box = readBox(r); 1574 if (!box || box.size < 8) { 1575 break; 1576 } 1577 boxes.push(box); 1578 r.pos = box.offset + box.size; 1579 } 1580 return boxes; 1581 } 1582 function findBox(r, start, end, type) { 1583 r.pos = start; 1584 while (r.pos < end) { 1585 const box = readBox(r); 1586 if (!box || box.size < 8) { 1587 break; 1588 } 1589 if (box.type === type) { 1590 return box; 1591 } 1592 r.pos = box.offset + box.size; 1593 } 1594 return void 0; 1595 } 1596 function parsePitm(r, box) { 1597 r.pos = box.offset + box.headerSize; 1598 const version = r.u8(); 1599 r.pos += 3; 1600 return version === 0 ? r.u16() : r.u32(); 1601 } 1602 function parseIloc(r, box) { 1603 r.pos = box.offset + box.headerSize; 1604 const version = r.u8(); 1605 r.pos += 3; 1606 const byte1 = r.u8(); 1607 const offsetSize = byte1 >> 4 & 15; 1608 const lengthSize = byte1 & 15; 1609 const byte2 = r.u8(); 1610 const baseOffsetSize = byte2 >> 4 & 15; 1611 const indexSize = version >= 1 ? byte2 & 15 : 0; 1612 const itemCount = version < 2 ? r.u16() : r.u32(); 1613 const items = /* @__PURE__ */ new Map(); 1614 for (let i = 0; i < itemCount; i++) { 1615 const itemId = version < 2 ? r.u16() : r.u32(); 1616 let constructionMethod = 0; 1617 if (version === 1 || version === 2) { 1618 const cm = r.u16(); 1619 constructionMethod = cm & 15; 1620 } 1621 r.u16(); 1622 const baseOffset = r.uN(baseOffsetSize); 1623 const extentCount = r.u16(); 1624 const extents = []; 1625 for (let j = 0; j < extentCount; j++) { 1626 if (version >= 1) { 1627 r.uN(indexSize); 1628 } 1629 const extOffset = r.uN(offsetSize); 1630 const extLength = r.uN(lengthSize); 1631 extents.push({ 1632 offset: baseOffset + extOffset, 1633 length: extLength 1634 }); 1635 } 1636 items.set(itemId, { constructionMethod, extents }); 1637 } 1638 return items; 1639 } 1640 function parseIpma(r, box) { 1641 r.pos = box.offset + box.headerSize; 1642 const vf = r.u32(); 1643 const version = vf >>> 24; 1644 const flags = vf & 16777215; 1645 const largeIndex = (flags & 1) !== 0; 1646 const entryCount = r.u32(); 1647 const associations = /* @__PURE__ */ new Map(); 1648 for (let i = 0; i < entryCount; i++) { 1649 const itemId = version < 1 ? r.u16() : r.u32(); 1650 const assocCount = r.u8(); 1651 const indices = []; 1652 for (let j = 0; j < assocCount; j++) { 1653 if (largeIndex) { 1654 indices.push(r.u16() & 32767); 1655 } else { 1656 indices.push(r.u8() & 127); 1657 } 1658 } 1659 associations.set(itemId, indices); 1660 } 1661 return associations; 1662 } 1663 function parseIspe(r, box) { 1664 r.pos = box.offset + box.headerSize + 4; 1665 return { width: r.u32(), height: r.u32() }; 1666 } 1667 function parseIrot(r, box) { 1668 r.pos = box.offset + box.headerSize; 1669 return (r.u8() & 3) * 90; 1670 } 1671 function parseIinf(r, box) { 1672 r.pos = box.offset + box.headerSize; 1673 const version = r.u8(); 1674 r.pos += 3; 1675 const entryCount = version === 0 ? r.u16() : r.u32(); 1676 const itemTypes = /* @__PURE__ */ new Map(); 1677 const entriesStart = r.pos; 1678 const boxEnd = box.offset + box.size; 1679 const infeBoxes = findBoxes(r, entriesStart, boxEnd); 1680 for (let i = 0; i < Math.min(entryCount, infeBoxes.length); i++) { 1681 const infe = infeBoxes[i]; 1682 if (infe.type !== "infe") { 1683 continue; 1684 } 1685 r.pos = infe.offset + infe.headerSize; 1686 const infeVersion = r.u8(); 1687 r.pos += 3; 1688 if (infeVersion >= 2) { 1689 const itemId = infeVersion === 2 ? r.u16() : r.u32(); 1690 r.u16(); 1691 const itemType = r.str(4); 1692 itemTypes.set(itemId, itemType); 1693 } 1694 } 1695 return itemTypes; 1696 } 1697 function parseIref(r, box, refType) { 1698 r.pos = box.offset + box.headerSize; 1699 const version = r.u8(); 1700 r.pos += 3; 1701 const refs = /* @__PURE__ */ new Map(); 1702 const boxEnd = box.offset + box.size; 1703 while (r.pos < boxEnd) { 1704 const refBox = readBox(r); 1705 if (!refBox || refBox.size < 8) { 1706 break; 1707 } 1708 r.pos = refBox.offset + refBox.headerSize; 1709 const fromId = version === 0 ? r.u16() : r.u32(); 1710 const refCount = r.u16(); 1711 const toIds = []; 1712 for (let i = 0; i < refCount; i++) { 1713 toIds.push(version === 0 ? r.u16() : r.u32()); 1714 } 1715 if (refBox.type === refType) { 1716 refs.set(fromId, toIds); 1717 } 1718 r.pos = refBox.offset + refBox.size; 1719 } 1720 return refs; 1721 } 1722 function reverseBits32(n) { 1723 n = n >>> 1 & 1431655765 | (n & 1431655765) << 1; 1724 n = n >>> 2 & 858993459 | (n & 858993459) << 2; 1725 n = n >>> 4 & 252645135 | (n & 252645135) << 4; 1726 n = n >>> 8 & 16711935 | (n & 16711935) << 8; 1727 n = n >>> 16 | n << 16; 1728 return n >>> 0; 1729 } 1730 function buildCodecString(r, recordOffset) { 1731 r.pos = recordOffset; 1732 r.u8(); 1733 const byte1 = r.u8(); 1734 const profileSpace = byte1 >> 6 & 3; 1735 const tierFlag = byte1 >> 5 & 1; 1736 const profileIdc = byte1 & 31; 1737 const compatFlags = r.u32(); 1738 const constraintBytes = r.bytes(6); 1739 const levelIdc = r.u8(); 1740 const spacePrefix = profileSpace > 0 ? String.fromCharCode(64 + profileSpace) : ""; 1741 const compatHex = reverseBits32(compatFlags).toString(16).toUpperCase(); 1742 const tierChar = tierFlag ? "H" : "L"; 1743 let lastNonZero = -1; 1744 for (let i = 5; i >= 0; i--) { 1745 if (constraintBytes[i] !== 0) { 1746 lastNonZero = i; 1747 break; 1748 } 1749 } 1750 let constraintStr = ""; 1751 if (lastNonZero >= 0) { 1752 const parts = []; 1753 for (let i = 0; i <= lastNonZero; i++) { 1754 parts.push(constraintBytes[i].toString(16).toUpperCase()); 1755 } 1756 constraintStr = "." + parts.join("."); 1757 } 1758 return `hvc1.$spacePrefix}$profileIdc}.$compatHex}.$tierChar}$levelIdc}$constraintStr}`; 1759 } 1760 function readItemData(buffer, loc, idatOffset) { 1761 const baseOffset = loc.constructionMethod === 1 ? idatOffset : 0; 1762 for (const ext of loc.extents) { 1763 if (baseOffset + ext.offset + ext.length > buffer.byteLength) { 1764 throw new Error( 1765 "HEIC item data extends past the end of the file" 1766 ); 1767 } 1768 } 1769 if (loc.extents.length === 1) { 1770 const ext = loc.extents[0]; 1771 const start = baseOffset + ext.offset; 1772 return new Uint8Array(buffer.slice(start, start + ext.length)); 1773 } 1774 let totalLength = 0; 1775 for (const ext of loc.extents) { 1776 totalLength += ext.length; 1777 } 1778 const data = new Uint8Array(totalLength); 1779 let pos = 0; 1780 for (const ext of loc.extents) { 1781 const start = baseOffset + ext.offset; 1782 data.set( 1783 new Uint8Array(buffer.slice(start, start + ext.length)), 1784 pos 1785 ); 1786 pos += ext.length; 1787 } 1788 return data; 1789 } 1790 function findHvcProperties(propIndices, properties) { 1791 let hvcCBox; 1792 let ispeBox; 1793 let irotBox; 1794 for (const idx of propIndices) { 1795 if (idx < 1 || idx > properties.length) { 1796 continue; 1797 } 1798 const prop = properties[idx - 1]; 1799 if (prop.type === "hvcC" && !hvcCBox) { 1800 hvcCBox = prop; 1801 } 1802 if (prop.type === "ispe" && !ispeBox) { 1803 ispeBox = prop; 1804 } 1805 if (prop.type === "irot" && !irotBox) { 1806 irotBox = prop; 1807 } 1808 } 1809 if (!hvcCBox) { 1810 throw new Error("No HEVC configuration (hvcC) found"); 1811 } 1812 if (!ispeBox) { 1813 throw new Error("No image dimensions (ispe) found"); 1814 } 1815 return { hvcCBox, ispeBox, irotBox }; 1816 } 1817 function parseHeic(buffer) { 1818 const r = new Reader(buffer); 1819 const fileEnd = buffer.byteLength; 1820 const metaBox = findBox(r, 0, fileEnd, "meta"); 1821 if (!metaBox) { 1822 throw new Error("No meta box found in HEIC file"); 1823 } 1824 const metaChildStart = metaBox.offset + metaBox.headerSize + 4; 1825 const metaEnd = metaBox.offset + metaBox.size; 1826 const children = findBoxes(r, metaChildStart, metaEnd); 1827 const pitmBox = children.find((b) => b.type === "pitm"); 1828 const ilocBox = children.find((b) => b.type === "iloc"); 1829 const iprpBox = children.find((b) => b.type === "iprp"); 1830 const iinfBox = children.find((b) => b.type === "iinf"); 1831 const irefBox = children.find((b) => b.type === "iref"); 1832 const idatBox = children.find((b) => b.type === "idat"); 1833 const idatOffset = idatBox ? idatBox.offset + idatBox.headerSize : 0; 1834 if (!pitmBox || !ilocBox || !iprpBox) { 1835 throw new Error("Missing required boxes (pitm, iloc, iprp) in HEIC"); 1836 } 1837 const primaryId = parsePitm(r, pitmBox); 1838 const locations = parseIloc(r, ilocBox); 1839 const iprpStart = iprpBox.offset + iprpBox.headerSize; 1840 const iprpEnd = iprpBox.offset + iprpBox.size; 1841 const iprpChildren = findBoxes(r, iprpStart, iprpEnd); 1842 const ipcoBox = iprpChildren.find((b) => b.type === "ipco"); 1843 const ipmaBox = iprpChildren.find((b) => b.type === "ipma"); 1844 if (!ipcoBox || !ipmaBox) { 1845 throw new Error("Missing ipco or ipma in HEIC properties"); 1846 } 1847 const allAssoc = parseIpma(r, ipmaBox); 1848 const ipcoStart = ipcoBox.offset + ipcoBox.headerSize; 1849 const ipcoEnd = ipcoBox.offset + ipcoBox.size; 1850 const properties = findBoxes(r, ipcoStart, ipcoEnd); 1851 let primaryItemType = "hvc1"; 1852 if (iinfBox) { 1853 const itemTypes = parseIinf(r, iinfBox); 1854 const t = itemTypes.get(primaryId); 1855 if (t) { 1856 primaryItemType = t; 1857 } 1858 } 1859 if (primaryItemType === "grid") { 1860 return parseGridImage( 1861 r, 1862 buffer, 1863 primaryId, 1864 locations, 1865 allAssoc, 1866 properties, 1867 irefBox, 1868 idatOffset 1869 ); 1870 } 1871 const primaryLoc = locations.get(primaryId); 1872 if (!primaryLoc || primaryLoc.extents.length === 0) { 1873 throw new Error(`No location data for primary item $primaryId}`); 1874 } 1875 const primaryPropIndices = allAssoc.get(primaryId); 1876 if (!primaryPropIndices || primaryPropIndices.length === 0) { 1877 throw new Error("No property associations for primary item"); 1878 } 1879 const { hvcCBox, ispeBox, irotBox } = findHvcProperties( 1880 primaryPropIndices, 1881 properties 1882 ); 1883 const hvcCDataStart = hvcCBox.offset + hvcCBox.headerSize; 1884 const hvcCDataSize = hvcCBox.size - hvcCBox.headerSize; 1885 const description = new Uint8Array( 1886 buffer.slice(hvcCDataStart, hvcCDataStart + hvcCDataSize) 1887 ); 1888 const codecString = buildCodecString(r, hvcCDataStart); 1889 const { width, height } = parseIspe(r, ispeBox); 1890 const rotation = irotBox ? parseIrot(r, irotBox) : 0; 1891 return { 1892 codecString, 1893 description, 1894 tiles: [ 1895 { 1896 data: readItemData(buffer, primaryLoc, idatOffset), 1897 x: 0, 1898 y: 0 1899 } 1900 ], 1901 tileWidth: width, 1902 tileHeight: height, 1903 outputWidth: width, 1904 outputHeight: height, 1905 rotation, 1906 exifOrientation: rotation === 0 ? getUnappliedExifOrientation(buffer) : 1 1907 }; 1908 } 1909 function parseGridImage(r, buffer, gridItemId, locations, allAssoc, properties, irefBox, idatOffset) { 1910 const gridLoc = locations.get(gridItemId); 1911 if (!gridLoc || gridLoc.extents.length === 0) { 1912 throw new Error("No location data for grid item"); 1913 } 1914 const gridData = readItemData(buffer, gridLoc, idatOffset); 1915 const largeFields = gridData.length > 1 && (gridData[1] & 1) !== 0; 1916 const minGridSize = largeFields ? 12 : 8; 1917 if (gridData.length < minGridSize) { 1918 throw new Error( 1919 `Grid descriptor too short: $gridData.length} bytes` 1920 ); 1921 } 1922 const rows = gridData[2] + 1; 1923 const columns = gridData[3] + 1; 1924 const gv = new DataView(gridData.buffer, gridData.byteOffset); 1925 let outputWidth; 1926 let outputHeight; 1927 if (largeFields) { 1928 outputWidth = gv.getUint32(4); 1929 outputHeight = gv.getUint32(8); 1930 } else { 1931 outputWidth = gv.getUint16(4); 1932 outputHeight = gv.getUint16(6); 1933 } 1934 if (!irefBox) { 1935 throw new Error("Grid image requires iref box"); 1936 } 1937 const dimgRefs = parseIref(r, irefBox, "dimg"); 1938 const tileItemIds = dimgRefs.get(gridItemId); 1939 if (!tileItemIds || tileItemIds.length === 0) { 1940 throw new Error("No tile references found for grid item"); 1941 } 1942 const expectedTiles = rows * columns; 1943 if (tileItemIds.length < expectedTiles) { 1944 throw new Error( 1945 `Grid expects $expectedTiles} tiles but found $tileItemIds.length}` 1946 ); 1947 } 1948 const firstTileProps = allAssoc.get(tileItemIds[0]); 1949 if (!firstTileProps || firstTileProps.length === 0) { 1950 throw new Error("No property associations for tile item"); 1951 } 1952 const { hvcCBox, ispeBox } = findHvcProperties( 1953 firstTileProps, 1954 properties 1955 ); 1956 const gridProps = allAssoc.get(gridItemId) || []; 1957 let irotBox; 1958 for (const idx of gridProps) { 1959 if (idx >= 1 && idx <= properties.length) { 1960 const prop = properties[idx - 1]; 1961 if (prop.type === "irot") { 1962 irotBox = prop; 1963 break; 1964 } 1965 } 1966 } 1967 const hvcCDataStart = hvcCBox.offset + hvcCBox.headerSize; 1968 const hvcCDataSize = hvcCBox.size - hvcCBox.headerSize; 1969 const description = new Uint8Array( 1970 buffer.slice(hvcCDataStart, hvcCDataStart + hvcCDataSize) 1971 ); 1972 const codecString = buildCodecString(r, hvcCDataStart); 1973 const { width: tileWidth, height: tileHeight } = parseIspe(r, ispeBox); 1974 const tiles = []; 1975 for (let row = 0; row < rows; row++) { 1976 for (let col = 0; col < columns; col++) { 1977 const tileIdx = row * columns + col; 1978 const tileId = tileItemIds[tileIdx]; 1979 const tileLoc = locations.get(tileId); 1980 if (!tileLoc || tileLoc.extents.length === 0) { 1981 throw new Error(`No location data for tile item $tileId}`); 1982 } 1983 tiles.push({ 1984 data: readItemData(buffer, tileLoc, idatOffset), 1985 x: col * tileWidth, 1986 y: row * tileHeight 1987 }); 1988 } 1989 } 1990 const rotation = irotBox ? parseIrot(r, irotBox) : 0; 1991 return { 1992 codecString, 1993 description, 1994 tiles, 1995 tileWidth, 1996 tileHeight, 1997 outputWidth, 1998 outputHeight, 1999 rotation, 2000 exifOrientation: rotation === 0 ? getUnappliedExifOrientation(buffer) : 1 2001 }; 2002 } 2003 function readTiffOrientation(payload) { 2004 if (payload.length < 8) { 2005 return 1; 2006 } 2007 const view = new DataView( 2008 payload.buffer, 2009 payload.byteOffset, 2010 payload.byteLength 2011 ); 2012 let tiffStart = 0; 2013 const firstWord = view.getUint16(0); 2014 if (firstWord !== 18761 && firstWord !== 19789) { 2015 tiffStart = view.getUint32(0) + 4; 2016 } 2017 if (tiffStart + 8 > payload.length) { 2018 return 1; 2019 } 2020 const byteOrder = view.getUint16(tiffStart); 2021 let little; 2022 if (byteOrder === 18761) { 2023 little = true; 2024 } else if (byteOrder === 19789) { 2025 little = false; 2026 } else { 2027 return 1; 2028 } 2029 const ifd0 = tiffStart + view.getUint32(tiffStart + 4, little); 2030 if (ifd0 + 2 > payload.length) { 2031 return 1; 2032 } 2033 const entryCount = view.getUint16(ifd0, little); 2034 for (let i = 0; i < entryCount; i++) { 2035 const entry = ifd0 + 2 + i * 12; 2036 if (entry + 12 > payload.length) { 2037 break; 2038 } 2039 if (view.getUint16(entry, little) === 274) { 2040 const value = view.getUint16(entry + 8, little); 2041 return value >= 1 && value <= 8 ? value : 1; 2042 } 2043 } 2044 return 1; 2045 } 2046 function findMeta(r) { 2047 const metaBox = findBox(r, 0, r.view.byteLength, "meta"); 2048 if (!metaBox) { 2049 return null; 2050 } 2051 const start = metaBox.offset + metaBox.headerSize + 4; 2052 const end = metaBox.offset + metaBox.size; 2053 return { box: metaBox, children: findBoxes(r, start, end) }; 2054 } 2055 function parseExifOrientation(buffer) { 2056 try { 2057 const r = new Reader(buffer); 2058 const meta = findMeta(r); 2059 if (!meta) { 2060 return 1; 2061 } 2062 const iinfBox = meta.children.find((b) => b.type === "iinf"); 2063 const ilocBox = meta.children.find((b) => b.type === "iloc"); 2064 if (!iinfBox || !ilocBox) { 2065 return 1; 2066 } 2067 const itemTypes = parseIinf(r, iinfBox); 2068 let exifItemId; 2069 for (const [id, type] of itemTypes) { 2070 if (type === "Exif") { 2071 exifItemId = id; 2072 break; 2073 } 2074 } 2075 if (exifItemId === void 0) { 2076 return 1; 2077 } 2078 const loc = parseIloc(r, ilocBox).get(exifItemId); 2079 if (!loc || loc.extents.length === 0) { 2080 return 1; 2081 } 2082 const idatBox = meta.children.find((b) => b.type === "idat"); 2083 const idatOffset = idatBox ? idatBox.offset + idatBox.headerSize : 0; 2084 return readTiffOrientation(readItemData(buffer, loc, idatOffset)); 2085 } catch { 2086 return 1; 2087 } 2088 } 2089 function hasNativeTransform(r) { 2090 const meta = findMeta(r); 2091 if (!meta) { 2092 return false; 2093 } 2094 const iprp = meta.children.find((b) => b.type === "iprp"); 2095 if (!iprp) { 2096 return false; 2097 } 2098 const ipco = findBox( 2099 r, 2100 iprp.offset + iprp.headerSize, 2101 iprp.offset + iprp.size, 2102 "ipco" 2103 ); 2104 if (!ipco) { 2105 return false; 2106 } 2107 const start = ipco.offset + ipco.headerSize; 2108 const end = ipco.offset + ipco.size; 2109 return Boolean( 2110 findBox(r, start, end, "irot") || findBox(r, start, end, "imir") 2111 ); 2112 } 2113 function getUnappliedExifOrientation(buffer) { 2114 try { 2115 if (hasNativeTransform(new Reader(buffer))) { 2116 return 1; 2117 } 2118 } catch { 2119 return 1; 2120 } 2121 return parseExifOrientation(buffer); 2122 } 2123 2124 // packages/upload-media/build-module/heic-support.mjs 2125 var import_i18n5 = __toESM(require_i18n(), 1); 2126 function detectBrowserFamily() { 2127 if (typeof navigator === "undefined") { 2128 return null; 2129 } 2130 const brands = navigator.userAgentData?.brands; 2131 if (brands?.length) { 2132 if (brands.some(({ brand }) => /Chromium/i.test(brand))) { 2133 return "chromium"; 2134 } 2135 } 2136 const userAgent = navigator.userAgent || ""; 2137 if (/Firefox|FxiOS/i.test(userAgent)) { 2138 return "firefox"; 2139 } 2140 if (/Chrome|Chromium|CriOS|Edg|OPR/i.test(userAgent)) { 2141 return "chromium"; 2142 } 2143 if (/Safari/i.test(userAgent)) { 2144 return "safari"; 2145 } 2146 return null; 2147 } 2148 function detectPlatform() { 2149 if (typeof navigator === "undefined") { 2150 return "other"; 2151 } 2152 const platform = navigator.userAgentData?.platform || navigator.userAgent || ""; 2153 if (/iPhone|iPad|iPod|iOS/i.test(platform)) { 2154 return "other"; 2155 } 2156 if (/macOS|Mac OS X|Macintosh/i.test(platform)) { 2157 return "macos"; 2158 } 2159 if (/Windows/i.test(platform)) { 2160 return "windows"; 2161 } 2162 if (/Android|CrOS|Chrome OS/i.test(platform)) { 2163 return "other"; 2164 } 2165 if (/Linux|X11/i.test(platform)) { 2166 return "linux"; 2167 } 2168 return "other"; 2169 } 2170 function getBrowserName() { 2171 if (detectBrowserFamily() === "chromium") { 2172 const brands = navigator.userAgentData?.brands ?? []; 2173 const userAgent = navigator.userAgent || ""; 2174 if (brands.some(({ brand }) => /Edge/i.test(brand)) || /Edg\//i.test(userAgent)) { 2175 return "Edge"; 2176 } 2177 if (brands.some(({ brand }) => /Opera/i.test(brand)) || /OPR\//i.test(userAgent)) { 2178 return "Opera"; 2179 } 2180 return "Chrome"; 2181 } 2182 switch (detectBrowserFamily()) { 2183 case "firefox": 2184 return "Firefox"; 2185 case "safari": 2186 return "Safari"; 2187 default: 2188 return null; 2189 } 2190 } 2191 function getHeicConversionAdvice() { 2192 const platform = detectPlatform(); 2193 const family = detectBrowserFamily(); 2194 if (platform === "macos") { 2195 if (family === "chromium") { 2196 return (0, import_i18n5.__)( 2197 "Safari usually can, or you can upload a JPEG instead." 2198 ); 2199 } 2200 if (family !== "safari") { 2201 return (0, import_i18n5.__)( 2202 "Safari or Chrome usually can, or you can upload a JPEG instead." 2203 ); 2204 } 2205 } 2206 if (platform === "windows" && family === "firefox") { 2207 return (0, import_i18n5.__)("Chrome or Edge might, or you can upload a JPEG instead."); 2208 } 2209 return (0, import_i18n5.__)("You can upload a JPEG instead."); 2210 } 2211 function getHeicUnsupportedMessage() { 2212 const platform = detectPlatform(); 2213 const family = detectBrowserFamily(); 2214 const browserName = getBrowserName(); 2215 let cause; 2216 if (platform === "linux") { 2217 cause = (0, import_i18n5.__)( 2218 "HEIC photos can't be decoded on Linux, so unfortunately we couldn't convert this one." 2219 ); 2220 } else if (family === "firefox") { 2221 cause = (0, import_i18n5.__)( 2222 "Firefox can't read HEIC photos, so we couldn't convert this one." 2223 ); 2224 } else if (browserName && platform === "windows") { 2225 cause = (0, import_i18n5.sprintf)( 2226 /* translators: %s: browser name, e.g. "Chrome". */ 2227 (0, import_i18n5.__)( 2228 "%s couldn't decode HEIC on this PC, so we couldn't convert this one." 2229 ), 2230 browserName 2231 ); 2232 } else if (browserName && platform === "macos") { 2233 cause = (0, import_i18n5.sprintf)( 2234 /* translators: %s: browser name, e.g. "Safari". */ 2235 (0, import_i18n5.__)( 2236 "%s couldn't decode HEIC on this Mac, so we couldn't convert this one." 2237 ), 2238 browserName 2239 ); 2240 } else if (browserName) { 2241 cause = (0, import_i18n5.sprintf)( 2242 /* translators: %s: browser name, e.g. "Chrome". */ 2243 (0, import_i18n5.__)( 2244 "%s couldn't decode HEIC on this device, so we couldn't convert this one." 2245 ), 2246 browserName 2247 ); 2248 } else { 2249 cause = (0, import_i18n5.__)( 2250 "This browser can't read HEIC photos, so we couldn't convert this one." 2251 ); 2252 } 2253 return `$cause} $getHeicConversionAdvice()}`; 2254 } 2255 2256 // packages/upload-media/build-module/canvas-utils.mjs 2257 var IMAGE_DECODER_TIMEOUT = 15e3; 2258 var HeicUnsupportedError = class extends Error { 2259 }; 2260 async function canvasConvertToJpeg(file, quality = 0.82, encode) { 2261 const canvas = await decodeToCanvas(file); 2262 const jpegBlob = await encodeCanvas(canvas, quality, encode); 2263 return new File([jpegBlob], `$getFileBasename(file.name)}.jpg`, { 2264 type: "image/jpeg" 2265 }); 2266 } 2267 async function encodeCanvas(canvas, quality, encode) { 2268 if (encode) { 2269 try { 2270 const encoded = await encode(canvas, quality); 2271 if (encoded) { 2272 return encoded; 2273 } 2274 } catch { 2275 } 2276 } 2277 return canvas.convertToBlob({ type: "image/jpeg", quality }); 2278 } 2279 async function decodeToCanvas(file) { 2280 try { 2281 const bitmap = await createImageBitmap(file); 2282 try { 2283 const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); 2284 const ctx = canvas.getContext("2d"); 2285 if (!ctx) { 2286 throw new Error("Could not get canvas 2d context"); 2287 } 2288 ctx.drawImage(bitmap, 0, 0); 2289 return canvas; 2290 } finally { 2291 bitmap.close(); 2292 } 2293 } catch { 2294 } 2295 if (typeof ImageDecoder !== "undefined") { 2296 const supported = await ImageDecoder.isTypeSupported(file.type); 2297 if (supported) { 2298 const decoder = new ImageDecoder({ 2299 type: file.type, 2300 data: file.stream() 2301 }); 2302 let videoFrame; 2303 let timeoutId; 2304 let timedOut = false; 2305 try { 2306 const decoded = await Promise.race([ 2307 decoder.decode(), 2308 new Promise((_resolve, reject) => { 2309 timeoutId = setTimeout(() => { 2310 timedOut = true; 2311 decoder.close(); 2312 reject( 2313 new Error("ImageDecoder decode timed out") 2314 ); 2315 }, IMAGE_DECODER_TIMEOUT); 2316 }) 2317 ]); 2318 videoFrame = decoded.image; 2319 } catch (error) { 2320 if (!timedOut) { 2321 throw error; 2322 } 2323 } finally { 2324 clearTimeout(timeoutId); 2325 if (!timedOut) { 2326 decoder.close(); 2327 } 2328 } 2329 if (videoFrame) { 2330 try { 2331 const canvas = new OffscreenCanvas( 2332 videoFrame.displayWidth, 2333 videoFrame.displayHeight 2334 ); 2335 const ctx = canvas.getContext("2d"); 2336 if (!ctx) { 2337 throw new Error("Could not get canvas 2d context"); 2338 } 2339 ctx.drawImage(videoFrame, 0, 0); 2340 return canvas; 2341 } finally { 2342 videoFrame.close(); 2343 } 2344 } 2345 } 2346 } 2347 let heicData; 2348 try { 2349 heicData = parseHeic(await file.arrayBuffer()); 2350 } catch (error) { 2351 throw new Error("The HEIC file could not be parsed", { 2352 cause: error 2353 }); 2354 } 2355 if (typeof VideoDecoder !== "undefined") { 2356 let supported = false; 2357 try { 2358 const support = await VideoDecoder.isConfigSupported({ 2359 codec: heicData.codecString 2360 }); 2361 supported = support.supported === true; 2362 } catch { 2363 } 2364 if (supported) { 2365 const canvas = new OffscreenCanvas( 2366 heicData.outputWidth, 2367 heicData.outputHeight 2368 ); 2369 const ctx = canvas.getContext("2d"); 2370 if (!ctx) { 2371 throw new Error("Could not get canvas 2d context"); 2372 } 2373 for (const tile of heicData.tiles) { 2374 const frame = await decodeHevcFrame( 2375 heicData.codecString, 2376 heicData.description, 2377 heicData.tileWidth, 2378 heicData.tileHeight, 2379 tile.data 2380 ); 2381 try { 2382 ctx.drawImage(frame, tile.x, tile.y); 2383 } finally { 2384 frame.close(); 2385 } 2386 } 2387 return heicData.rotation !== 0 ? applyRotation(canvas, heicData.rotation) : applyExifOrientation(canvas, heicData.exifOrientation); 2388 } 2389 } 2390 throw new HeicUnsupportedError(getHeicUnsupportedMessage()); 2391 } 2392 function applyRotation(source, rotation) { 2393 if (rotation === 0) { 2394 return source; 2395 } 2396 const swap = rotation === 90 || rotation === 270; 2397 const w = swap ? source.height : source.width; 2398 const h = swap ? source.width : source.height; 2399 const rotated = new OffscreenCanvas(w, h); 2400 const ctx = rotated.getContext("2d"); 2401 if (!ctx) { 2402 return source; 2403 } 2404 ctx.translate(w / 2, h / 2); 2405 ctx.rotate(-rotation * Math.PI / 180); 2406 ctx.drawImage(source, -source.width / 2, -source.height / 2); 2407 return rotated; 2408 } 2409 function applyExifOrientation(source, orientation) { 2410 if (orientation <= 1 || orientation > 8) { 2411 return source; 2412 } 2413 const { width: sw, height: sh } = source; 2414 const swap = orientation >= 5; 2415 const out = new OffscreenCanvas(swap ? sh : sw, swap ? sw : sh); 2416 const ctx = out.getContext("2d"); 2417 if (!ctx) { 2418 return source; 2419 } 2420 switch (orientation) { 2421 case 2: 2422 ctx.transform(-1, 0, 0, 1, sw, 0); 2423 break; 2424 case 3: 2425 ctx.transform(-1, 0, 0, -1, sw, sh); 2426 break; 2427 case 4: 2428 ctx.transform(1, 0, 0, -1, 0, sh); 2429 break; 2430 case 5: 2431 ctx.transform(0, 1, 1, 0, 0, 0); 2432 break; 2433 case 6: 2434 ctx.transform(0, 1, -1, 0, sh, 0); 2435 break; 2436 case 7: 2437 ctx.transform(0, -1, -1, 0, sh, sw); 2438 break; 2439 case 8: 2440 ctx.transform(0, -1, 1, 0, 0, sw); 2441 break; 2442 } 2443 ctx.drawImage(source, 0, 0); 2444 return out; 2445 } 2446 function decodeHevcFrame(codec, description, width, height, data) { 2447 return new Promise((resolve, reject) => { 2448 const decoder = new VideoDecoder({ 2449 output: (frame) => { 2450 decoder.close(); 2451 resolve(frame); 2452 }, 2453 error: (e) => { 2454 if (decoder.state !== "closed") { 2455 decoder.close(); 2456 } 2457 reject(e); 2458 } 2459 }); 2460 decoder.configure({ 2461 codec, 2462 codedWidth: width, 2463 codedHeight: height, 2464 description 2465 }); 2466 decoder.decode( 2467 new EncodedVideoChunk({ 2468 type: "key", 2469 timestamp: 0, 2470 data 2471 }) 2472 ); 2473 decoder.flush().catch((e) => { 2474 if (decoder.state !== "closed") { 2475 decoder.close(); 2476 } 2477 reject(e); 2478 }); 2479 }); 2480 } 2481 2482 // packages/upload-media/build-module/get-image-dimensions.mjs 2483 var MAX_HEADER_BYTES = 512 * 1024; 2484 function parseJpeg(view) { 2485 let offset = 2; 2486 while (offset < view.byteLength) { 2487 if (view.getUint8(offset) !== 255) { 2488 return null; 2489 } 2490 while (offset < view.byteLength && view.getUint8(offset) === 255) { 2491 offset++; 2492 } 2493 if (offset >= view.byteLength) { 2494 return null; 2495 } 2496 const marker = view.getUint8(offset); 2497 offset++; 2498 if (marker === 1 || marker >= 208 && marker <= 217) { 2499 continue; 2500 } 2501 if (marker === 218) { 2502 return null; 2503 } 2504 if (offset + 2 > view.byteLength) { 2505 return null; 2506 } 2507 const segmentLength = view.getUint16(offset); 2508 if (segmentLength < 2) { 2509 return null; 2510 } 2511 const isStartOfFrame = marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204; 2512 if (isStartOfFrame) { 2513 if (offset + 7 > view.byteLength) { 2514 return null; 2515 } 2516 const height = view.getUint16(offset + 3); 2517 const width = view.getUint16(offset + 5); 2518 const interlaced = marker === 194 || marker === 198 || marker === 202 || marker === 206; 2519 return { width, height, interlaced }; 2520 } 2521 offset += segmentLength; 2522 } 2523 return null; 2524 } 2525 function parsePng(view) { 2526 if (view.byteLength < 29) { 2527 return null; 2528 } 2529 const isIhdr = view.getUint8(12) === 73 && // I 2530 view.getUint8(13) === 72 && // H 2531 view.getUint8(14) === 68 && // D 2532 view.getUint8(15) === 82; 2533 if (!isIhdr) { 2534 return null; 2535 } 2536 const width = view.getUint32(16); 2537 const height = view.getUint32(20); 2538 const interlaceMethod = view.getUint8(28); 2539 return { width, height, interlaced: interlaceMethod !== 0 }; 2540 } 2541 async function getImageDimensions(file) { 2542 try { 2543 const headerBytes = Math.min(file.size, MAX_HEADER_BYTES); 2544 const buffer = await file.slice(0, headerBytes).arrayBuffer(); 2545 const view = new DataView(buffer); 2546 if (view.byteLength >= 3 && view.getUint16(0) === 65496) { 2547 return parseJpeg(view); 2548 } 2549 if (view.byteLength >= 8 && view.getUint32(0) === 2303741511 && view.getUint32(4) === 218765834) { 2550 return parsePng(view); 2551 } 2552 return null; 2553 } catch { 2554 return null; 2555 } 2556 } 2557 2558 // packages/upload-media/build-module/stub-file.mjs 2559 var StubFile = class extends File { 2560 constructor(fileName = "stub-file") { 2561 super([], fileName); 2562 } 2563 }; 2564 2565 // packages/upload-media/build-module/store/private-actions.mjs 2566 var DEFAULT_OUTPUT_QUALITY = 0.82; 2567 var ultraHdrItems = /* @__PURE__ */ new Set(); 2568 function addItem({ 2569 file: fileOrBlob, 2570 batchId, 2571 onChange, 2572 onSuccess, 2573 onBatchSuccess, 2574 onError, 2575 additionalData = {}, 2576 sourceUrl, 2577 sourceAttachmentId, 2578 abortController, 2579 operations 2580 }) { 2581 return async ({ dispatch }) => { 2582 const itemId = v4_default(); 2583 const file = convertBlobToFile(fileOrBlob); 2584 let blobUrl; 2585 if (!(file instanceof StubFile)) { 2586 blobUrl = (0, import_blob.createBlobURL)(file); 2587 dispatch({ 2588 type: Type.CacheBlobUrl, 2589 id: itemId, 2590 blobUrl 2591 }); 2592 } 2593 dispatch({ 2594 type: Type.Add, 2595 item: { 2596 id: itemId, 2597 batchId, 2598 status: ItemStatus.Processing, 2599 sourceFile: cloneFile(file), 2600 file, 2601 attachment: { 2602 url: blobUrl 2603 }, 2604 additionalData: { 2605 generate_sub_sizes: false, 2606 ...additionalData 2607 }, 2608 onChange, 2609 onSuccess, 2610 onBatchSuccess, 2611 onError, 2612 sourceUrl, 2613 sourceAttachmentId, 2614 abortController: abortController || new AbortController(), 2615 operations: Array.isArray(operations) ? operations : [OperationType.Prepare] 2616 } 2617 }); 2618 dispatch.processItem(itemId); 2619 }; 2620 } 2621 function addSideloadItem({ 2622 file, 2623 onChange, 2624 additionalData, 2625 operations, 2626 batchId, 2627 parentId 2628 }) { 2629 return ({ dispatch }) => { 2630 const itemId = v4_default(); 2631 dispatch({ 2632 type: Type.Add, 2633 item: { 2634 id: itemId, 2635 batchId, 2636 status: ItemStatus.Processing, 2637 sourceFile: cloneFile(file), 2638 file, 2639 onChange, 2640 additionalData: { 2641 ...additionalData 2642 }, 2643 parentId, 2644 operations: Array.isArray(operations) ? operations : [OperationType.Prepare], 2645 abortController: new AbortController() 2646 } 2647 }); 2648 dispatch.processItem(itemId); 2649 }; 2650 } 2651 function processItem(id) { 2652 return async ({ select: select2, dispatch }) => { 2653 if (select2.isPaused()) { 2654 return; 2655 } 2656 const item = select2.getItem(id); 2657 if (!item) { 2658 return; 2659 } 2660 if (item.currentOperation) { 2661 return; 2662 } 2663 const { 2664 attachment, 2665 onChange, 2666 onSuccess, 2667 onBatchSuccess, 2668 batchId, 2669 parentId 2670 } = item; 2671 const operation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0]; 2672 const operationArgs = Array.isArray(item.operations?.[0]) ? item.operations[0][1] : void 0; 2673 if (operation === OperationType.Upload) { 2674 const settings = select2.getSettings(); 2675 const activeCount = select2.getActiveUploadCount(); 2676 if (activeCount >= settings.maxConcurrentUploads) { 2677 return; 2678 } 2679 } 2680 if (operation === OperationType.ResizeCrop || operation === OperationType.Rotate) { 2681 const settings = select2.getSettings(); 2682 const activeCount = select2.getActiveImageProcessingCount(); 2683 if (activeCount >= settings.maxConcurrentImageProcessing) { 2684 return; 2685 } 2686 } 2687 if (operation === OperationType.TranscodeGif) { 2688 const activeCount = select2.getActiveVideoProcessingCount(); 2689 if (activeCount >= 1) { 2690 return; 2691 } 2692 } 2693 if (attachment) { 2694 const isHeicUrl = attachment.url && /\.hei[cf]$/i.test(attachment.url); 2695 if (!isHeicUrl) { 2696 onChange?.([attachment]); 2697 } 2698 } 2699 if (!operation) { 2700 if (parentId || !parentId && !select2.hasPendingItemsByParentId(id)) { 2701 if (attachment) { 2702 onSuccess?.([attachment]); 2703 } 2704 dispatch.removeItem(id); 2705 dispatch.revokeBlobUrls(id); 2706 if (batchId && select2.isBatchUploaded(batchId)) { 2707 onBatchSuccess?.(); 2708 } 2709 } 2710 if (parentId && batchId && select2.isBatchUploaded(batchId)) { 2711 const parentItem = select2.getItem(parentId); 2712 if (!parentItem) { 2713 return; 2714 } 2715 if (parentItem.operations && parentItem.operations.length > 0) { 2716 dispatch.processItem(parentId); 2717 return; 2718 } 2719 if (attachment) { 2720 parentItem.onSuccess?.([attachment]); 2721 } 2722 dispatch.removeItem(parentId); 2723 dispatch.revokeBlobUrls(parentId); 2724 if (parentItem.batchId && select2.isBatchUploaded(parentItem.batchId)) { 2725 parentItem.onBatchSuccess?.(); 2726 } 2727 } 2728 return; 2729 } 2730 if (operation === OperationType.Finalize && select2.hasPendingItemsByParentId(id)) { 2731 return; 2732 } 2733 dispatch({ 2734 type: Type.OperationStart, 2735 id, 2736 operation 2737 }); 2738 debug( 2739 `Starting operation $operation} for $item.file.name} (item $item.id})` 2740 ); 2741 switch (operation) { 2742 case OperationType.Prepare: 2743 dispatch.prepareItem(item.id); 2744 break; 2745 case OperationType.ResizeCrop: 2746 dispatch.resizeCropItem( 2747 item.id, 2748 operationArgs 2749 ); 2750 break; 2751 case OperationType.Rotate: 2752 dispatch.rotateItem( 2753 item.id, 2754 operationArgs 2755 ); 2756 break; 2757 case OperationType.TranscodeImage: 2758 dispatch.transcodeImageItem( 2759 item.id, 2760 operationArgs 2761 ); 2762 break; 2763 case OperationType.TranscodeGif: 2764 dispatch.transcodeGifItem( 2765 item.id, 2766 operationArgs 2767 ); 2768 break; 2769 case OperationType.Upload: 2770 if (item.parentId) { 2771 dispatch.sideloadItem(id); 2772 } else { 2773 dispatch.uploadItem(id); 2774 } 2775 break; 2776 case OperationType.ThumbnailGeneration: 2777 dispatch.generateThumbnails(id); 2778 break; 2779 case OperationType.Finalize: 2780 dispatch.finalizeItem(id); 2781 break; 2782 case OperationType.DetectUltraHdr: 2783 dispatch.detectUltraHdr(id); 2784 break; 2785 } 2786 }; 2787 } 2788 function pauseQueue() { 2789 return { 2790 type: Type.PauseQueue 2791 }; 2792 } 2793 function resumeQueue() { 2794 return async ({ select: select2, dispatch }) => { 2795 dispatch({ 2796 type: Type.ResumeQueue 2797 }); 2798 for (const item of select2.getAllItems()) { 2799 if (item.status === ItemStatus.PendingRetry) { 2800 dispatch.executeRetry(item.id); 2801 } else { 2802 dispatch.processItem(item.id); 2803 } 2804 } 2805 }; 2806 } 2807 function pauseItem(id) { 2808 return async ({ dispatch }) => { 2809 dispatch({ 2810 type: Type.PauseItem, 2811 id 2812 }); 2813 }; 2814 } 2815 function removeItem(id) { 2816 return async ({ select: select2, dispatch }) => { 2817 const item = select2.getItem(id); 2818 if (!item) { 2819 return; 2820 } 2821 ultraHdrItems.delete(id); 2822 clearRetryTimer(id); 2823 dispatch({ 2824 type: Type.Remove, 2825 id 2826 }); 2827 if (select2.getAllItems().length === 0) { 2828 terminateVipsWorker(); 2829 terminateVideoConversionWorker(); 2830 } 2831 }; 2832 } 2833 function finishOperation(id, updates) { 2834 return async ({ select: select2, dispatch }) => { 2835 const item = select2.getItem(id); 2836 const previousOperation = item?.currentOperation; 2837 dispatch({ 2838 type: Type.OperationFinish, 2839 id, 2840 item: updates 2841 }); 2842 dispatch.processItem(id); 2843 if (previousOperation === OperationType.Upload) { 2844 const pendingUploads = select2.getPendingUploads(); 2845 for (const pendingItem of pendingUploads) { 2846 dispatch.processItem(pendingItem.id); 2847 } 2848 } 2849 if (previousOperation === OperationType.ResizeCrop || previousOperation === OperationType.Rotate) { 2850 const pendingItems = select2.getPendingImageProcessing(); 2851 for (const pendingItem of pendingItems) { 2852 dispatch.processItem(pendingItem.id); 2853 } 2854 } 2855 if (previousOperation === OperationType.TranscodeGif) { 2856 const pendingItems = select2.getPendingVideoProcessing(); 2857 for (const pendingItem of pendingItems) { 2858 dispatch.processItem(pendingItem.id); 2859 } 2860 } 2861 if (previousOperation === OperationType.ResizeCrop || previousOperation === OperationType.Rotate || previousOperation === OperationType.TranscodeImage) { 2862 maybeRecycleVipsWorker(select2.getActiveImageProcessingCount()); 2863 } 2864 }; 2865 } 2866 var VALID_IMAGE_FORMATS = ["jpeg", "webp", "avif", "png", "gif"]; 2867 function isValidImageFormat(format) { 2868 return VALID_IMAGE_FORMATS.includes(format); 2869 } 2870 async function getTranscodeImageOperation(file, outputMimeType, interlaced = false, quality = DEFAULT_OUTPUT_QUALITY) { 2871 if (file.type === "image/png" && outputMimeType === "image/jpeg") { 2872 const blobUrl = (0, import_blob.createBlobURL)(file); 2873 try { 2874 const hasAlpha = await vipsHasTransparency(blobUrl); 2875 if (hasAlpha) { 2876 return null; 2877 } 2878 } catch { 2879 return null; 2880 } finally { 2881 (0, import_blob.revokeBlobURL)(blobUrl); 2882 } 2883 } 2884 const formatPart = outputMimeType.split("/")[1]; 2885 if (!isValidImageFormat(formatPart)) { 2886 return null; 2887 } 2888 return [ 2889 OperationType.TranscodeImage, 2890 { 2891 outputFormat: formatPart, 2892 outputQuality: quality, 2893 interlaced 2894 } 2895 ]; 2896 } 2897 function prepareItem(id) { 2898 return async ({ select: select2, dispatch }) => { 2899 const item = select2.getItem(id); 2900 if (!item) { 2901 return; 2902 } 2903 const { file } = item; 2904 const operations = []; 2905 const settings = select2.getSettings(); 2906 if (file.type === "image/gif" && settings.gifConvert !== false && typeof ImageDecoder !== "undefined" && typeof VideoEncoder !== "undefined") { 2907 let isAnimated = false; 2908 try { 2909 isAnimated = isAnimatedGif(await file.arrayBuffer()); 2910 } catch { 2911 isAnimated = false; 2912 } 2913 if (isAnimated) { 2914 let hasTransparency = false; 2915 const blobUrl = (0, import_blob.createBlobURL)(file); 2916 try { 2917 hasTransparency = await vipsHasTransparency(blobUrl); 2918 } catch { 2919 hasTransparency = true; 2920 } finally { 2921 (0, import_blob.revokeBlobURL)(blobUrl); 2922 } 2923 if (!hasTransparency) { 2924 operations.push( 2925 OperationType.Upload, 2926 OperationType.ThumbnailGeneration, 2927 OperationType.Finalize 2928 ); 2929 dispatch({ 2930 type: Type.AddOperations, 2931 id, 2932 operations 2933 }); 2934 dispatch.finishOperation(id, { 2935 animatedGifFile: item.file 2936 }); 2937 return; 2938 } 2939 } 2940 } 2941 let heicJpeg = null; 2942 const isHeic = await isHeicFile(file); 2943 const isMisnamedHeic = isHeic && !HEIC_MIME_TYPES.includes(file.type); 2944 const isImage = file.type.startsWith("image/") || isHeic; 2945 const isVipsSupported = !isHeic && CLIENT_SIDE_SUPPORTED_MIME_TYPES.includes(file.type); 2946 const heicFile = isMisnamedHeic ? new File([file], `$getFileBasename(file.name)}.heic`, { 2947 type: HEIC_MIME_TYPES[0], 2948 lastModified: file.lastModified 2949 }) : file; 2950 let tooLargeForClient = false; 2951 if (isImage && isVipsSupported) { 2952 const dimensions = await getImageDimensions(file); 2953 if (dimensions && exceedsClientProcessingMemory(dimensions)) { 2954 tooLargeForClient = true; 2955 } 2956 } 2957 if (file.type === "image/jpeg" && !isHeic && !tooLargeForClient) { 2958 operations.push(OperationType.DetectUltraHdr); 2959 } 2960 if (isImage && isVipsSupported && !tooLargeForClient) { 2961 operations.push( 2962 OperationType.Upload, 2963 OperationType.ThumbnailGeneration, 2964 OperationType.Finalize 2965 ); 2966 } else if (isImage && isHeic) { 2967 const encode = isClientSideMediaSupported() ? (canvas, quality) => vipsEncodeCanvasAsJpeg(id, canvas, heicFile, quality) : void 0; 2968 try { 2969 heicJpeg = await canvasConvertToJpeg( 2970 heicFile, 2971 settings.imageQuality ?? DEFAULT_OUTPUT_QUALITY, 2972 encode 2973 ); 2974 } catch (error) { 2975 const unsupported = error instanceof HeicUnsupportedError; 2976 dispatch.cancelItem( 2977 id, 2978 new UploadError({ 2979 code: unsupported ? ErrorCode.HEIC_DECODE_ERROR : ErrorCode.IMAGE_TRANSCODING_ERROR, 2980 message: unsupported ? getHeicUnsupportedMessage() : (0, import_i18n6.__)( 2981 "This HEIC image could not be converted. Try converting it to JPEG before uploading." 2982 ), 2983 file, 2984 cause: error instanceof Error ? error : void 0 2985 }) 2986 ); 2987 return; 2988 } 2989 operations.push( 2990 OperationType.Upload, 2991 OperationType.ThumbnailGeneration, 2992 OperationType.Finalize 2993 ); 2994 } else { 2995 operations.push(OperationType.Upload); 2996 } 2997 dispatch({ 2998 type: Type.AddOperations, 2999 id, 3000 operations 3001 }); 3002 let updates; 3003 if (isHeic && heicJpeg) { 3004 const vipsAvailable = isClientSideMediaSupported(); 3005 updates = { 3006 file: heicJpeg, 3007 sourceFile: heicJpeg, 3008 originalHeicFile: heicFile, 3009 additionalData: { 3010 ...item.additionalData, 3011 generate_sub_sizes: !vipsAvailable, 3012 convert_format: true 3013 } 3014 }; 3015 } else if (!isVipsSupported || !isImage || tooLargeForClient) { 3016 updates = { 3017 additionalData: { 3018 ...item.additionalData, 3019 generate_sub_sizes: true, 3020 convert_format: true 3021 } 3022 }; 3023 } else { 3024 updates = { 3025 additionalData: { 3026 ...item.additionalData, 3027 generate_sub_sizes: false 3028 } 3029 }; 3030 } 3031 dispatch.finishOperation(id, updates); 3032 }; 3033 } 3034 function detectUltraHdr(id) { 3035 return async ({ select: select2, dispatch }) => { 3036 const item = select2.getItem(id); 3037 if (!item) { 3038 return; 3039 } 3040 let info; 3041 try { 3042 const buffer = await item.file.arrayBuffer(); 3043 info = await vipsGetUltraHdrInfo(buffer); 3044 } catch { 3045 } 3046 if (info) { 3047 ultraHdrItems.add(id); 3048 } 3049 dispatch.finishOperation(id, {}); 3050 }; 3051 } 3052 function uploadItem(id) { 3053 return async ({ select: select2, dispatch }) => { 3054 const item = select2.getItem(id); 3055 if (!item) { 3056 return; 3057 } 3058 const startTime = performance.now(); 3059 let finished = false; 3060 const finishUpload = (attachment) => { 3061 if (finished) { 3062 return; 3063 } 3064 finished = true; 3065 measure({ 3066 measureName: `Upload $item.file.name}`, 3067 startTime, 3068 tooltipText: item.file.name, 3069 properties: [ 3070 ["Item ID", item.id], 3071 ["File name", item.file.name] 3072 ] 3073 }); 3074 dispatch.finishOperation(id, { attachment }); 3075 }; 3076 select2.getSettings().mediaUpload({ 3077 filesList: [item.file], 3078 additionalData: item.additionalData, 3079 signal: item.abortController?.signal, 3080 // The queue's own items drive upload progress UI and save 3081 // locking; without this, consumers that track uploads themselves 3082 // (e.g. the editor's progress snackbar) would count this file a 3083 // second time. 3084 isTransportOnly: true, 3085 onFileChange: ([attachment]) => { 3086 if (attachment && !(0, import_blob.isBlobURL)(attachment.url)) { 3087 finishUpload(attachment); 3088 } 3089 }, 3090 onSuccess: ([attachment]) => { 3091 finishUpload(attachment); 3092 }, 3093 onError: (error) => { 3094 dispatch.cancelItem(id, error); 3095 } 3096 }); 3097 }; 3098 } 3099 function sideloadItem(id) { 3100 return async ({ select: select2, dispatch }) => { 3101 const item = select2.getItem(id); 3102 if (!item) { 3103 return; 3104 } 3105 const { post, ...additionalData } = item.additionalData; 3106 const mediaSideload = select2.getSettings().mediaSideload; 3107 if (!mediaSideload) { 3108 dispatch.finishOperation(id, {}); 3109 return; 3110 } 3111 const startTime = performance.now(); 3112 mediaSideload({ 3113 file: item.file, 3114 attachmentId: post, 3115 additionalData, 3116 signal: item.abortController?.signal, 3117 onSuccess: (subSize) => { 3118 measure({ 3119 measureName: `Sideload $item.file.name}`, 3120 startTime, 3121 tooltipText: item.file.name, 3122 properties: [ 3123 ["Item ID", item.id], 3124 ["File name", item.file.name] 3125 ] 3126 }); 3127 if (item.parentId) { 3128 dispatch({ 3129 type: Type.AccumulateSubSize, 3130 id: item.parentId, 3131 subSize 3132 }); 3133 } 3134 dispatch.finishOperation(id, {}); 3135 }, 3136 onError: (error) => { 3137 dispatch.cancelItem(id, error); 3138 } 3139 }); 3140 }; 3141 } 3142 function resizeCropItem(id, args) { 3143 return async ({ select: select2, dispatch }) => { 3144 const item = select2.getItem(id); 3145 if (!item) { 3146 return; 3147 } 3148 if (!args?.resize) { 3149 dispatch.finishOperation(id, { 3150 file: item.file 3151 }); 3152 return; 3153 } 3154 const startTime = performance.now(); 3155 const addSuffix = Boolean(item.parentId); 3156 const scaledSuffix = Boolean(args.isThresholdResize); 3157 const { 3158 imageStripMeta, 3159 imageMaxBitDepth, 3160 generateAnimatedImageSubsizes 3161 } = select2.getSettings(); 3162 try { 3163 const file = await vipsResizeImage( 3164 item.id, 3165 item.file, 3166 args.resize, 3167 { 3168 smartCrop: false, 3169 addSuffix, 3170 signal: item.abortController?.signal, 3171 scaledSuffix, 3172 quality: args.quality, 3173 stripMeta: imageStripMeta, 3174 maxBitdepth: imageMaxBitDepth, 3175 preserveAnimation: false !== generateAnimatedImageSubsizes 3176 } 3177 ); 3178 measure({ 3179 measureName: `ResizeCrop $item.file.name}`, 3180 startTime, 3181 tooltipText: item.file.name, 3182 properties: [ 3183 ["Item ID", item.id], 3184 ["File name", item.file.name] 3185 ] 3186 }); 3187 const blobUrl = (0, import_blob.createBlobURL)(file); 3188 dispatch({ 3189 type: Type.CacheBlobUrl, 3190 id, 3191 blobUrl 3192 }); 3193 dispatch.finishOperation(id, { 3194 file, 3195 attachment: { 3196 url: blobUrl 3197 } 3198 }); 3199 } catch (error) { 3200 dispatch.cancelItem( 3201 id, 3202 new UploadError({ 3203 code: ErrorCode.IMAGE_TRANSCODING_ERROR, 3204 message: (0, import_i18n6.__)( 3205 "The web server cannot generate responsive image sizes for this image. Convert it to JPEG or PNG before uploading." 3206 ), 3207 file: item.file, 3208 cause: error instanceof Error ? error : void 0 3209 }) 3210 ); 3211 } 3212 }; 3213 } 3214 function rotateItem(id, args) { 3215 return async ({ select: select2, dispatch }) => { 3216 const item = select2.getItem(id); 3217 if (!item) { 3218 return; 3219 } 3220 if (!args?.orientation || args.orientation === 1) { 3221 dispatch.finishOperation(id, { 3222 file: item.file 3223 }); 3224 return; 3225 } 3226 const startTime = performance.now(); 3227 try { 3228 const file = await vipsRotateImage( 3229 item.id, 3230 item.file, 3231 args.orientation, 3232 item.abortController?.signal 3233 ); 3234 measure({ 3235 measureName: `Rotate $item.file.name}`, 3236 startTime, 3237 tooltipText: item.file.name, 3238 properties: [ 3239 ["Item ID", item.id], 3240 ["File name", item.file.name] 3241 ] 3242 }); 3243 const blobUrl = (0, import_blob.createBlobURL)(file); 3244 dispatch({ 3245 type: Type.CacheBlobUrl, 3246 id, 3247 blobUrl 3248 }); 3249 dispatch.finishOperation(id, { 3250 file, 3251 attachment: { 3252 url: blobUrl 3253 } 3254 }); 3255 } catch (error) { 3256 dispatch.cancelItem( 3257 id, 3258 new UploadError({ 3259 code: ErrorCode.IMAGE_ROTATION_ERROR, 3260 message: (0, import_i18n6.__)( 3261 "The web server cannot generate responsive image sizes for this image. Convert it to JPEG or PNG before uploading." 3262 ), 3263 file: item.file, 3264 cause: error instanceof Error ? error : void 0 3265 }) 3266 ); 3267 } 3268 }; 3269 } 3270 function transcodeImageItem(id, args) { 3271 return async ({ select: select2, dispatch }) => { 3272 const item = select2.getItem(id); 3273 if (!item) { 3274 return; 3275 } 3276 if (!args?.outputFormat) { 3277 dispatch.finishOperation(id, { 3278 file: item.file 3279 }); 3280 return; 3281 } 3282 const startTime = performance.now(); 3283 const outputMimeType = `image/$args.outputFormat}`; 3284 const quality = args.outputQuality ?? DEFAULT_OUTPUT_QUALITY; 3285 const interlaced = args.interlaced ?? false; 3286 const { imageStripMeta, imageMaxBitDepth } = select2.getSettings(); 3287 try { 3288 const file = await vipsConvertImageFormat( 3289 item.id, 3290 item.file, 3291 outputMimeType, 3292 { 3293 quality, 3294 interlaced, 3295 stripMeta: imageStripMeta, 3296 maxBitdepth: imageMaxBitDepth 3297 } 3298 ); 3299 measure({ 3300 measureName: `Transcode $item.file.name}`, 3301 startTime, 3302 tooltipText: item.file.name, 3303 properties: [ 3304 ["Item ID", item.id], 3305 ["File name", item.file.name] 3306 ] 3307 }); 3308 const blobUrl = (0, import_blob.createBlobURL)(file); 3309 dispatch({ 3310 type: Type.CacheBlobUrl, 3311 id, 3312 blobUrl 3313 }); 3314 dispatch.finishOperation(id, { 3315 file, 3316 attachment: { 3317 url: blobUrl 3318 } 3319 }); 3320 } catch (error) { 3321 dispatch.cancelItem( 3322 id, 3323 new UploadError({ 3324 code: ErrorCode.MEDIA_TRANSCODING_ERROR, 3325 message: "Image could not be transcoded to the target format", 3326 file: item.file, 3327 cause: error instanceof Error ? error : void 0 3328 }) 3329 ); 3330 } 3331 }; 3332 } 3333 function transcodeGifItem(id, args) { 3334 return async ({ select: select2, dispatch }) => { 3335 const item = select2.getItem(id); 3336 if (!item) { 3337 return; 3338 } 3339 const outputFormat = args?.outputFormat ?? "mp4"; 3340 const outputMimeType = `video/$outputFormat}`; 3341 const gifFile = item.file; 3342 try { 3343 const file = await convertGifToVideo( 3344 item.id, 3345 gifFile, 3346 outputMimeType, 3347 { 3348 timeout: args?.timeout, 3349 maxTotalPixels: args?.maxTotalPixels 3350 } 3351 ); 3352 dispatch.finishOperation(id, { file }); 3353 dispatch.addSideloadItem({ 3354 file: gifFile, 3355 batchId: v4_default(), 3356 parentId: item.parentId, 3357 additionalData: { 3358 post: item.additionalData?.post, 3359 image_size: "animated_video_poster", 3360 convert_format: false 3361 }, 3362 operations: [ 3363 [ 3364 OperationType.TranscodeImage, 3365 { 3366 outputFormat: "jpeg", 3367 outputQuality: DEFAULT_OUTPUT_QUALITY, 3368 interlaced: false 3369 } 3370 ], 3371 OperationType.Upload 3372 ] 3373 }); 3374 } catch (error) { 3375 if (isUnsupportedConversionError(error)) { 3376 if (isSizeLimitConversionError(error)) { 3377 debug( 3378 `Skipping GIF to video conversion: $error instanceof Error ? error.message : error}` 3379 ); 3380 } 3381 dispatch.cancelItem( 3382 id, 3383 new Error("Animated GIF conversion unsupported"), 3384 true 3385 ); 3386 return; 3387 } 3388 if (isConversionTimeoutError(error)) { 3389 debug( 3390 `GIF to video conversion timed out; keeping the original GIF only: $error instanceof Error ? error.message : error}` 3391 ); 3392 dispatch.cancelItem( 3393 id, 3394 new Error("Animated GIF conversion timed out"), 3395 true 3396 ); 3397 return; 3398 } 3399 console.error( 3400 "[video-conversion] GIF to video conversion failed:", 3401 error 3402 ); 3403 dispatch.cancelItem( 3404 id, 3405 new UploadError({ 3406 code: ErrorCode.GIF_TRANSCODING_ERROR, 3407 message: "Animated GIF could not be converted to video", 3408 file: item.file, 3409 cause: error instanceof Error ? error : void 0 3410 }), 3411 true 3412 ); 3413 } 3414 }; 3415 } 3416 function generateThumbnails(id) { 3417 return async ({ select: select2, dispatch }) => { 3418 const item = select2.getItem(id); 3419 if (!item) { 3420 return; 3421 } 3422 if (!item.attachment) { 3423 dispatch.finishOperation(id, {}); 3424 return; 3425 } 3426 const attachment = item.attachment; 3427 const settings = select2.getSettings(); 3428 if (item.originalHeicFile && attachment.id) { 3429 dispatch.addSideloadItem({ 3430 file: item.originalHeicFile, 3431 batchId: v4_default(), 3432 parentId: item.id, 3433 additionalData: { 3434 post: attachment.id, 3435 image_size: "source_original", 3436 convert_format: false 3437 }, 3438 operations: [OperationType.Upload] 3439 }); 3440 } 3441 if (item.animatedGifFile && attachment.id) { 3442 const outputFormat = settings.videoOutputFormat === "video/webm" ? "webm" : "mp4"; 3443 dispatch.addSideloadItem({ 3444 file: item.animatedGifFile, 3445 batchId: v4_default(), 3446 parentId: item.id, 3447 additionalData: { 3448 post: attachment.id, 3449 image_size: "animated_video", 3450 convert_format: false 3451 }, 3452 operations: [ 3453 [ 3454 OperationType.TranscodeGif, 3455 { 3456 outputFormat 3457 } 3458 ], 3459 OperationType.Upload 3460 ] 3461 }); 3462 } 3463 let exifOrientation = attachment.exif_orientation || 1; 3464 const sourceType = item.sourceFile.type; 3465 const isHeifFamily = sourceType === "image/avif" || sourceType === "image/heif"; 3466 let needsClientRotation = false; 3467 if (isHeifFamily) { 3468 exifOrientation = getUnappliedExifOrientation( 3469 await item.sourceFile.arrayBuffer() 3470 ); 3471 needsClientRotation = exifOrientation !== 1; 3472 } 3473 let rotatedSource; 3474 { 3475 const needsRotation = exifOrientation !== 1 && !item.file.name.includes("-scaled"); 3476 if ((needsRotation || needsClientRotation) && attachment.id) { 3477 try { 3478 rotatedSource = await vipsRotateImage( 3479 item.id, 3480 item.sourceFile, 3481 exifOrientation, 3482 item.abortController?.signal 3483 ); 3484 } catch { 3485 console.warn( 3486 "Failed to rotate image, continuing with thumbnails" 3487 ); 3488 } 3489 } 3490 if (needsRotation && rotatedSource && attachment.id) { 3491 dispatch.addSideloadItem({ 3492 file: rotatedSource, 3493 batchId: v4_default(), 3494 parentId: item.id, 3495 additionalData: { 3496 post: attachment.id, 3497 image_size: "original", 3498 convert_format: false 3499 }, 3500 operations: [OperationType.Upload] 3501 }); 3502 } 3503 } 3504 if (!item.parentId && attachment.missing_image_sizes && attachment.missing_image_sizes.length > 0) { 3505 const allImageSizes = settings.allImageSizes || {}; 3506 const sizesToGenerate = attachment.missing_image_sizes; 3507 const thumbnailSource = needsClientRotation && rotatedSource ? rotatedSource : item.sourceFile; 3508 const file = attachment.filename ? renameFile(thumbnailSource, attachment.filename) : thumbnailSource; 3509 const batchId = v4_default(); 3510 const isUltraHdr = ultraHdrItems.has(item.id); 3511 const outputMimeType = attachment.image_output_format; 3512 const interlaced = attachment.image_save_progressive ?? false; 3513 const imageQuality = attachment.image_quality; 3514 const fallbackQuality = settings.imageQuality ?? DEFAULT_OUTPUT_QUALITY; 3515 const defaultQuality = typeof imageQuality?.default === "number" ? imageQuality.default / 100 : fallbackQuality; 3516 const qualityForSize = (sizeName) => { 3517 const sized = imageQuality?.sizes?.[sizeName]; 3518 if (typeof sized === "number") { 3519 return sized / 100; 3520 } 3521 return defaultQuality; 3522 }; 3523 let thumbnailTranscodeOperation = null; 3524 if (!isUltraHdr && outputMimeType) { 3525 thumbnailTranscodeOperation = await getTranscodeImageOperation( 3526 thumbnailSource, 3527 outputMimeType, 3528 interlaced, 3529 defaultQuality 3530 ); 3531 } 3532 const dimensionGroups = /* @__PURE__ */ new Map(); 3533 for (const name of sizesToGenerate) { 3534 const imageSize = allImageSizes[name]; 3535 if (!imageSize) { 3536 console.warn( 3537 `Image size "$name}" not found in configuration` 3538 ); 3539 continue; 3540 } 3541 const key = `$imageSize.width}x$imageSize.height}x$imageSize.crop}`; 3542 const group = dimensionGroups.get(key); 3543 if (group) { 3544 group.push(name); 3545 } else { 3546 dimensionGroups.set(key, [name]); 3547 } 3548 } 3549 for (const [, names] of dimensionGroups) { 3550 const imageSize = allImageSizes[names[0]]; 3551 const sizeQuality = qualityForSize(names[0]); 3552 const thumbnailOperations = [ 3553 [ 3554 OperationType.ResizeCrop, 3555 { resize: imageSize, quality: sizeQuality } 3556 ] 3557 ]; 3558 if (!isUltraHdr && thumbnailTranscodeOperation) { 3559 thumbnailOperations.push([ 3560 thumbnailTranscodeOperation[0], 3561 { 3562 ...thumbnailTranscodeOperation[1], 3563 outputQuality: sizeQuality 3564 } 3565 ]); 3566 } 3567 thumbnailOperations.push(OperationType.Upload); 3568 const imageSizeParam = names.length === 1 ? names[0] : names; 3569 dispatch.addSideloadItem({ 3570 file, 3571 batchId, 3572 parentId: item.id, 3573 additionalData: { 3574 // Sideloading does not use the parent post ID but the 3575 // attachment ID as the image sizes need to be added to it. 3576 post: attachment.id, 3577 image_size: imageSizeParam, 3578 convert_format: false 3579 }, 3580 operations: thumbnailOperations 3581 }); 3582 } 3583 { 3584 const { bigImageSizeThreshold } = settings; 3585 if (bigImageSizeThreshold && attachment.id) { 3586 let needsScaling = false; 3587 try { 3588 const bitmap = await createImageBitmap(thumbnailSource); 3589 needsScaling = bitmap.width > bigImageSizeThreshold || bitmap.height > bigImageSizeThreshold; 3590 bitmap.close(); 3591 } catch (err) { 3592 console.warn( 3593 "Could not determine whether the image exceeds the big image size threshold; skipping the scaled version.", 3594 err 3595 ); 3596 } 3597 if (needsScaling) { 3598 const sourceForScaled = attachment.filename ? renameFile(thumbnailSource, attachment.filename) : thumbnailSource; 3599 const scaledOperations = [ 3600 [ 3601 OperationType.ResizeCrop, 3602 { 3603 resize: { 3604 width: bigImageSizeThreshold, 3605 height: bigImageSizeThreshold 3606 }, 3607 isThresholdResize: true, 3608 quality: defaultQuality 3609 } 3610 ] 3611 ]; 3612 if (!isUltraHdr && thumbnailTranscodeOperation) { 3613 scaledOperations.push( 3614 thumbnailTranscodeOperation 3615 ); 3616 } 3617 scaledOperations.push(OperationType.Upload); 3618 dispatch.addSideloadItem({ 3619 file: sourceForScaled, 3620 batchId, 3621 parentId: item.id, 3622 additionalData: { 3623 post: attachment.id, 3624 image_size: "scaled", 3625 convert_format: false 3626 }, 3627 operations: scaledOperations 3628 }); 3629 } 3630 } 3631 } 3632 } 3633 dispatch.finishOperation(id, {}); 3634 }; 3635 } 3636 function finalizeItem(id) { 3637 return async ({ select: select2, dispatch }) => { 3638 const item = select2.getItem(id); 3639 if (!item) { 3640 return; 3641 } 3642 const attachment = item.attachment; 3643 const { mediaFinalize } = select2.getSettings(); 3644 const updates = {}; 3645 if (attachment?.id && mediaFinalize) { 3646 try { 3647 const updatedAttachment = await mediaFinalize( 3648 attachment.id, 3649 item.subSizes || [] 3650 ); 3651 if (updatedAttachment) { 3652 updates.attachment = updatedAttachment; 3653 } 3654 } catch (error) { 3655 console.warn("Media finalization failed:", error); 3656 dispatch.cancelItem( 3657 id, 3658 new UploadError({ 3659 code: ErrorCode.MEDIA_FINALIZE_ERROR, 3660 message: (0, import_i18n6.__)("Could not finalize the upload."), 3661 file: item.file 3662 }) 3663 ); 3664 return; 3665 } 3666 } 3667 dispatch.finishOperation(id, updates); 3668 }; 3669 } 3670 function revokeBlobUrls(id) { 3671 return async ({ select: select2, dispatch }) => { 3672 const blobUrls = select2.getBlobUrls(id); 3673 for (const blobUrl of blobUrls) { 3674 (0, import_blob.revokeBlobURL)(blobUrl); 3675 } 3676 dispatch({ 3677 type: Type.RevokeBlobUrls, 3678 id 3679 }); 3680 }; 3681 } 3682 function updateItemProgress(id, progress) { 3683 return async ({ dispatch }) => { 3684 dispatch({ 3685 type: Type.UpdateProgress, 3686 id, 3687 progress 3688 }); 3689 }; 3690 } 3691 function updateSettings(settings) { 3692 return { 3693 type: Type.UpdateSettings, 3694 settings 3695 }; 3696 } 3697 3698 // packages/upload-media/build-module/lock-unlock.mjs 3699 var import_private_apis = __toESM(require_private_apis(), 1); 3700 var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)( 3701 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.", 3702 "@wordpress/upload-media" 3703 ); 3704 3705 // packages/upload-media/build-module/store/index.mjs 3706 var storeConfig = { 3707 reducer: reducer_default, 3708 selectors: selectors_exports, 3709 actions: actions_exports 3710 }; 3711 var store = (0, import_data.createReduxStore)(STORE_NAME, { 3712 reducer: reducer_default, 3713 selectors: selectors_exports, 3714 actions: actions_exports 3715 }); 3716 if (!(0, import_data.select)(store)) { 3717 (0, import_data.register)(store); 3718 } 3719 unlock(store).registerPrivateActions(private_actions_exports); 3720 unlock(store).registerPrivateSelectors(private_selectors_exports); 3721 3722 // packages/upload-media/build-module/components/provider/index.mjs 3723 var import_element2 = __toESM(require_element(), 1); 3724 var import_data3 = __toESM(require_data(), 1); 3725 3726 // packages/upload-media/build-module/components/provider/with-registry-provider.mjs 3727 var import_element = __toESM(require_element(), 1); 3728 var import_data2 = __toESM(require_data(), 1); 3729 var import_compose = __toESM(require_compose(), 1); 3730 var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); 3731 function getSubRegistry(subRegistries, registry, useSubRegistry) { 3732 if (!useSubRegistry) { 3733 return registry; 3734 } 3735 let subRegistry = subRegistries.get(registry); 3736 if (!subRegistry) { 3737 subRegistry = (0, import_data2.createRegistry)({}, registry); 3738 subRegistry.registerStore(STORE_NAME, storeConfig); 3739 subRegistries.set(registry, subRegistry); 3740 } 3741 return subRegistry; 3742 } 3743 var withRegistryProvider = (0, import_compose.createHigherOrderComponent)( 3744 (WrappedComponent) => ({ useSubRegistry = true, ...props }) => { 3745 const registry = (0, import_data2.useRegistry)(); 3746 const [subRegistries] = (0, import_element.useState)(() => /* @__PURE__ */ new WeakMap()); 3747 const subRegistry = getSubRegistry( 3748 subRegistries, 3749 registry, 3750 useSubRegistry 3751 ); 3752 if (subRegistry === registry) { 3753 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WrappedComponent, { registry, ...props }); 3754 } 3755 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_data2.RegistryProvider, { value: subRegistry, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WrappedComponent, { registry: subRegistry, ...props }) }); 3756 }, 3757 "withRegistryProvider" 3758 ); 3759 var with_registry_provider_default = withRegistryProvider; 3760 3761 // packages/upload-media/build-module/components/provider/index.mjs 3762 var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); 3763 var MediaUploadProvider = with_registry_provider_default((props) => { 3764 const { children, settings } = props; 3765 const { updateSettings: updateSettings2 } = unlock((0, import_data3.useDispatch)(store)); 3766 (0, import_element2.useEffect)(() => { 3767 updateSettings2(settings); 3768 }, [settings, updateSettings2]); 3769 return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children }); 3770 }); 3771 var provider_default = MediaUploadProvider; 3772 3773 // packages/upload-media/build-module/error-messages.mjs 3774 var import_i18n7 = __toESM(require_i18n(), 1); 3775 function getErrorMessage(code, fileName) { 3776 const messages = { 3777 [ErrorCode.EMPTY_FILE]: { 3778 title: (0, import_i18n7.__)("Empty file"), 3779 description: (0, import_i18n7.sprintf)( 3780 /* translators: %s: file name */ 3781 (0, import_i18n7.__)('"%s" is empty.'), 3782 fileName 3783 ), 3784 action: (0, import_i18n7.__)("Please choose a different file.") 3785 }, 3786 [ErrorCode.SIZE_ABOVE_LIMIT]: { 3787 title: (0, import_i18n7.__)("File too large"), 3788 description: (0, import_i18n7.sprintf)( 3789 /* translators: %s: file name */ 3790 (0, import_i18n7.__)('"%s" exceeds the maximum upload size.'), 3791 fileName 3792 ), 3793 action: (0, import_i18n7.__)("Please reduce the file size and try again.") 3794 }, 3795 [ErrorCode.MIME_TYPE_NOT_SUPPORTED]: { 3796 title: (0, import_i18n7.__)("Unsupported file type"), 3797 description: (0, import_i18n7.sprintf)( 3798 /* translators: %s: file name */ 3799 (0, import_i18n7.__)('"%s" is not a supported file type.'), 3800 fileName 3801 ), 3802 action: (0, import_i18n7.__)("Please upload a different file format.") 3803 }, 3804 [ErrorCode.MIME_TYPE_NOT_ALLOWED_FOR_USER]: { 3805 title: (0, import_i18n7.__)("File type not allowed"), 3806 description: (0, import_i18n7.sprintf)( 3807 /* translators: %s: file name */ 3808 (0, import_i18n7.__)('You are not allowed to upload "%s".'), 3809 fileName 3810 ), 3811 action: (0, import_i18n7.__)("Please contact your site administrator.") 3812 }, 3813 [ErrorCode.HEIC_DECODE_ERROR]: { 3814 title: (0, import_i18n7.__)("HEIC decode failed"), 3815 description: (0, import_i18n7.sprintf)( 3816 /* translators: %s: file name */ 3817 (0, import_i18n7.__)('Failed to decode HEIC file "%s".'), 3818 fileName 3819 ), 3820 action: getHeicConversionAdvice() 3821 }, 3822 [ErrorCode.IMAGE_TRANSCODING_ERROR]: { 3823 title: (0, import_i18n7.__)("Image processing failed"), 3824 description: (0, import_i18n7.sprintf)( 3825 /* translators: %s: file name */ 3826 (0, import_i18n7.__)('Failed to process "%s".'), 3827 fileName 3828 ), 3829 action: (0, import_i18n7.__)("The image may be corrupted. Try a different file.") 3830 }, 3831 [ErrorCode.IMAGE_ROTATION_ERROR]: { 3832 title: (0, import_i18n7.__)("Image rotation failed"), 3833 description: (0, import_i18n7.sprintf)( 3834 /* translators: %s: file name */ 3835 (0, import_i18n7.__)('Failed to rotate "%s".'), 3836 fileName 3837 ), 3838 action: (0, import_i18n7.__)("The image may be corrupted. Try a different file.") 3839 }, 3840 [ErrorCode.MEDIA_TRANSCODING_ERROR]: { 3841 title: (0, import_i18n7.__)("Media processing failed"), 3842 description: (0, import_i18n7.sprintf)( 3843 /* translators: %s: file name */ 3844 (0, import_i18n7.__)('Failed to convert "%s" to the target format.'), 3845 fileName 3846 ), 3847 action: (0, import_i18n7.__)("The file may be corrupted. Try a different file.") 3848 }, 3849 [ErrorCode.MEDIA_FINALIZE_ERROR]: { 3850 title: (0, import_i18n7.__)("Upload failed"), 3851 description: (0, import_i18n7.sprintf)( 3852 /* translators: %s: file name */ 3853 (0, import_i18n7.__)('Could not finalize the upload of "%s".'), 3854 fileName 3855 ), 3856 action: (0, import_i18n7.__)("Please try again.") 3857 }, 3858 [ErrorCode.GENERAL]: { 3859 title: (0, import_i18n7.__)("Upload failed"), 3860 description: (0, import_i18n7.sprintf)( 3861 /* translators: %s: file name */ 3862 (0, import_i18n7.__)('Failed to upload "%s".'), 3863 fileName 3864 ), 3865 action: (0, import_i18n7.__)("Please try again.") 3866 } 3867 }; 3868 return messages[code] || { 3869 title: (0, import_i18n7.__)("Upload failed"), 3870 description: (0, import_i18n7.sprintf)( 3871 /* translators: %s: file name */ 3872 (0, import_i18n7.__)('Failed to upload "%s".'), 3873 fileName 3874 ), 3875 action: (0, import_i18n7.__)("Please try again.") 3876 }; 3877 } 3878 return __toCommonJS(index_exports); 3879 })(); 3880 (window.wp ||= {}).uploadMedia = wp.uploadMedia; 3881 })();
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Sat Nov 21 08:20:02 2026 | Cross-referenced by PHPXref |