From 596540ac32d7601cb3ea25c46b0a924e61faedfc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:26:19 +0000 Subject: [PATCH 01/50] chore(deps): bump follow-redirects from 1.16.1 to 1.16.2 Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.16.1 to 1.16.2. - [Release notes](https://github.com/follow-redirects/follow-redirects/releases) - [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.16.1...v1.16.2) --- updated-dependencies: - dependency-name: follow-redirects dependency-version: 1.16.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index efbc5612b..026439810 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17053,9 +17053,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", - "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.2.tgz", + "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", "dev": true, "funding": [ { From c434ed6db6659c49e7a796e58c91173a532a6370 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:02:57 +0000 Subject: [PATCH 02/50] chore(deps-dev): bump eslint from 10.13.0 to 10.14.0 Bumps [eslint](https://github.com/eslint/eslint) from 10.13.0 to 10.14.0. - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/compare/v10.13.0...v10.14.0) --- updated-dependencies: - dependency-name: eslint dependency-version: 10.14.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- package-lock.json | 20 ++++++++++---------- package.json | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/package-lock.json b/package-lock.json index 834ce1807..300cdb55e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,7 +45,7 @@ "css-unicode-loader": "^1.0.3", "cssnano": "^9.9.0", "dotenv": "^18.0.9", - "eslint": "^10.13.0", + "eslint": "^10.14.0", "eslint-plugin-jest": "^29.17.0", "eslint-plugin-react-hooks": "^7.0.1", "file-loader": "^6.2.0", @@ -14979,9 +14979,9 @@ } }, "node_modules/eslint": { - "version": "10.13.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.13.0.tgz", - "integrity": "sha512-UohDjD4zSzEwhf58M3O7vc/ycc8O1I7dNlhtD0WxE8Px8EHNJKtUwzBqrzeGhisRuv2ag4sAYswszCJRgKXYUg==", + "version": "10.14.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.14.0.tgz", + "integrity": "sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==", "dev": true, "license": "MIT", "workspaces": [ @@ -14994,7 +14994,7 @@ "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.3", - "@humanfs/node": "^0.16.6", + "@humanfs/node": "^0.16.8", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", @@ -15015,7 +15015,7 @@ "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.2.5", + "minimatch": "^10.2.6", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, @@ -21207,13 +21207,13 @@ "license": "ISC" }, "node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.5" + "brace-expansion": "^5.0.8" }, "engines": { "node": "18 || 20 || >=22" diff --git a/package.json b/package.json index a69da913b..6d3422f2a 100644 --- a/package.json +++ b/package.json @@ -93,7 +93,7 @@ "css-unicode-loader": "^1.0.3", "cssnano": "^9.9.0", "dotenv": "^18.0.9", - "eslint": "^10.13.0", + "eslint": "^10.14.0", "eslint-plugin-jest": "^29.17.0", "eslint-plugin-react-hooks": "^7.0.1", "file-loader": "^6.2.0", From cf7bffb8120898a802fac4947b27b6b768de3f5f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:03:15 +0000 Subject: [PATCH 03/50] chore(deps-dev): bump globals from 17.13.0 to 17.14.0 Bumps [globals](https://github.com/sindresorhus/globals) from 17.13.0 to 17.14.0. - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.13.0...v17.14.0) --- updated-dependencies: - dependency-name: globals dependency-version: 17.14.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 834ce1807..f991d4c28 100644 --- a/package-lock.json +++ b/package-lock.json @@ -49,7 +49,7 @@ "eslint-plugin-jest": "^29.17.0", "eslint-plugin-react-hooks": "^7.0.1", "file-loader": "^6.2.0", - "globals": "^17.13.0", + "globals": "^17.14.0", "grunt": "^1.5.2", "grunt-contrib-clean": "^2.0.0", "grunt-contrib-compress": "^2.0.0", @@ -16748,9 +16748,9 @@ } }, "node_modules/globals": { - "version": "17.13.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-17.13.0.tgz", - "integrity": "sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==", + "version": "17.14.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", + "integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index a69da913b..a2fe57cdb 100644 --- a/package.json +++ b/package.json @@ -97,7 +97,7 @@ "eslint-plugin-jest": "^29.17.0", "eslint-plugin-react-hooks": "^7.0.1", "file-loader": "^6.2.0", - "globals": "^17.13.0", + "globals": "^17.14.0", "grunt": "^1.5.2", "grunt-contrib-clean": "^2.0.0", "grunt-contrib-compress": "^2.0.0", From f071e7a5bb9cf6a61adfb3378463beb801ad133a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:03:25 +0000 Subject: [PATCH 04/50] chore(deps-dev): bump webpack-cli from 7.2.3 to 7.3.1 Bumps [webpack-cli](https://github.com/webpack/webpack-cli) from 7.2.3 to 7.3.1. - [Release notes](https://github.com/webpack/webpack-cli/releases) - [Changelog](https://github.com/webpack/webpack-cli/blob/main/CHANGELOG.md) - [Commits](https://github.com/webpack/webpack-cli/compare/webpack-cli@7.2.3...webpack-cli@7.3.1) --- updated-dependencies: - dependency-name: webpack-cli dependency-version: 7.3.1 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- package-lock.json | 30 ++++++++++++++++-------------- package.json | 2 +- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/package-lock.json b/package-lock.json index 834ce1807..eef9e7233 100644 --- a/package-lock.json +++ b/package-lock.json @@ -71,7 +71,7 @@ "taffydb": "^2.7.3", "terser-webpack-plugin": "^5.3.14", "webpack": "^5.112.2", - "webpack-cli": "^7.2.3", + "webpack-cli": "^7.3.1", "wp-hookdoc": "^0.2.0" }, "engines": { @@ -28469,19 +28469,17 @@ } }, "node_modules/webpack-cli": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-7.2.3.tgz", - "integrity": "sha512-vDFU7jrfCctnN7jJQWPl+V26B51GLp11prVZXg50oeonsgeBzSTJEWmXkjHsOjTgMjlPOQM8GWLh33X9RN/0ow==", + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-7.3.1.tgz", + "integrity": "sha512-enXzN0/2fWHX3tP2gpTV6U8/zz5RSbfWjSAc0VXOi0+hOY4ePdHanA+2kxrAC/SX0LHO4fOX5c9G1TdwpvUj/g==", "dev": true, "license": "MIT", "dependencies": { "@discoveryjs/json-ext": "^1.1.0", "commander": "^14.0.3", - "cross-spawn": "^7.0.6", "envinfo": "^7.21.0", - "import-local": "^3.2.0", "interpret": "^3.1.1", - "rechoir": "^0.8.0", + "rechoir": "^1.0.0", "webpack-merge": "^6.0.1" }, "bin": { @@ -28495,6 +28493,7 @@ "url": "https://opencollective.com/webpack" }, "peerDependencies": { + "@bomb.sh/tab": "^0.0.22", "js-yaml": "^4.0.0 || ^5.0.0", "json5": "^2.2.3", "toml": "^3.0.0 || ^4.0.0 || ^5.0.0", @@ -28503,6 +28502,9 @@ "webpack-dev-server": "^5.0.0 || ^6.0.0" }, "peerDependenciesMeta": { + "@bomb.sh/tab": { + "optional": true + }, "js-yaml": { "optional": true }, @@ -28551,16 +28553,16 @@ } }, "node_modules/webpack-cli/node_modules/rechoir": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz", - "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-1.0.0.tgz", + "integrity": "sha512-vyBa7bWz11iJRwzJR0nGLt6r45bymWfYXAgd1FmP08BNP/DHAVabgpGPyEXQmBtKvhgxi17SQz2szhvkberQsg==", "dev": true, "license": "MIT", - "dependencies": { - "resolve": "^1.20.0" - }, "engines": { - "node": ">= 10.13.0" + "node": ">= 22.15.0" + }, + "funding": { + "url": "https://github.com/sponsors/gulpjs" } }, "node_modules/webpack-dev-middleware": { diff --git a/package.json b/package.json index a69da913b..6fe1f7c00 100644 --- a/package.json +++ b/package.json @@ -119,7 +119,7 @@ "taffydb": "^2.7.3", "terser-webpack-plugin": "^5.3.14", "webpack": "^5.112.2", - "webpack-cli": "^7.2.3", + "webpack-cli": "^7.3.1", "wp-hookdoc": "^0.2.0" }, "overrides": { From e767ef98f01f1d359f6800ffd8bedefc5e0d64c3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:05:49 +0000 Subject: [PATCH 05/50] chore(deps-dev): bump php-stubs/woocommerce-stubs from 11.2.0 to 11.2.1 Bumps [php-stubs/woocommerce-stubs](https://github.com/php-stubs/woocommerce-stubs) from 11.2.0 to 11.2.1. - [Commits](https://github.com/php-stubs/woocommerce-stubs/compare/v11.2.0...v11.2.1) --- updated-dependencies: - dependency-name: php-stubs/woocommerce-stubs dependency-version: 11.2.1 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- composer.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/composer.lock b/composer.lock index cbf065734..366f99cf6 100644 --- a/composer.lock +++ b/composer.lock @@ -464,16 +464,16 @@ }, { "name": "php-stubs/woocommerce-stubs", - "version": "v11.2.0", + "version": "v11.2.1", "source": { "type": "git", "url": "https://github.com/php-stubs/woocommerce-stubs.git", - "reference": "fb590c1c2a26c47aa5da2c6c51a707130e8a389c" + "reference": "8cfdb86cad90da64441317e1bebe5f71a437a074" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-stubs/woocommerce-stubs/zipball/fb590c1c2a26c47aa5da2c6c51a707130e8a389c", - "reference": "fb590c1c2a26c47aa5da2c6c51a707130e8a389c", + "url": "https://api.github.com/repos/php-stubs/woocommerce-stubs/zipball/8cfdb86cad90da64441317e1bebe5f71a437a074", + "reference": "8cfdb86cad90da64441317e1bebe5f71a437a074", "shasum": "" }, "require": { @@ -502,9 +502,9 @@ ], "support": { "issues": "https://github.com/php-stubs/woocommerce-stubs/issues", - "source": "https://github.com/php-stubs/woocommerce-stubs/tree/v11.2.0" + "source": "https://github.com/php-stubs/woocommerce-stubs/tree/v11.2.1" }, - "time": "2026-10-07T19:02:59+00:00" + "time": "2026-10-09T20:26:55+00:00" }, { "name": "php-stubs/wordpress-stubs", From d46b2960e01e09b6d51260064fb7cb527ab8bb5b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:05:53 +0000 Subject: [PATCH 06/50] chore(deps-dev): bump phpstan/phpstan from 2.3.2 to 2.3.4 Bumps [phpstan/phpstan](https://github.com/phpstan/phpstan-phar-composer-source) from 2.3.2 to 2.3.4. - [Commits](https://github.com/phpstan/phpstan-phar-composer-source/commits) --- updated-dependencies: - dependency-name: phpstan/phpstan dependency-version: 2.3.4 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- composer.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.lock b/composer.lock index cbf065734..09aded188 100644 --- a/composer.lock +++ b/composer.lock @@ -992,11 +992,11 @@ }, { "name": "phpstan/phpstan", - "version": "2.3.2", + "version": "2.3.4", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/18bc23a0682f08591529377d271b5c4dfe9ed1dd", - "reference": "18bc23a0682f08591529377d271b5c4dfe9ed1dd", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/f20ce6f3c82556cfcfc086b152445a12d1d64fff", + "reference": "f20ce6f3c82556cfcfc086b152445a12d1d64fff", "shasum": "" }, "require": { @@ -1052,7 +1052,7 @@ "type": "github" } ], - "time": "2026-10-24T11:36:00+00:00" + "time": "2026-10-28T22:38:53+00:00" }, { "name": "phpunit/php-code-coverage", From 4840e868aad84bace0f66614fa51b7242b0e295e Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Mon, 9 Nov 2026 15:56:56 +0530 Subject: [PATCH 07/50] test(e2e): Cover the media storage modes Add an e2e spec for the three storage settings. It checks that "Cloudinary only" keeps the local files during the delete delay and removes them after it, that "Cloudinary and WordPress" downloads the full-quality files again, and that the low resolution mode keeps a smaller local copy. In each mode the image must still load from Cloudinary. Cleanup removes the Cloudinary assets through the API. Deleting an attachment removes its asset only when the plugin thinks it is synced, and after a storage change it is not. --- tests/e2e/cloudinary-storage-modes.spec.js | 367 +++++++++++++++++++++ 1 file changed, 367 insertions(+) create mode 100644 tests/e2e/cloudinary-storage-modes.spec.js diff --git a/tests/e2e/cloudinary-storage-modes.spec.js b/tests/e2e/cloudinary-storage-modes.spec.js new file mode 100644 index 000000000..716906adb --- /dev/null +++ b/tests/e2e/cloudinary-storage-modes.spec.js @@ -0,0 +1,367 @@ +/** + * External dependencies + */ +const fs = require( 'fs' ); +const path = require( 'path' ); +const { test, expect } = require( './fixtures' ); + +/** + * Internal dependencies + */ +const { ensureCloudinaryConnected } = require( './utils/connection' ); +const { expectCloudinaryUrl } = require( './utils/delivery' ); +const { saveSettings } = require( './utils/settings' ); +const { wpCli, wpEvalFile } = require( './utils/wizard' ); + +const FIXTURE_PATH = path.join( __dirname, 'fixtures', 'test-image.jpg' ); +const FIXTURE_BYTES = fs.statSync( FIXTURE_PATH ).size; + +/** + * Settings pinned for the spec, restored in afterAll. Without lazy load + * the server writes the delivery URL into `src`. Each test then sets the + * storage mode (`offload`) it needs. + * + * @type {Record} + */ +const SETTINGS = { + use_lazy_load: 'off', + auto_sync: 'on', + offload: 'dual_full', +}; + +let cloudName; + +/** @type {Record|null} */ +let previousSettings = null; + +/** + * IDs of every attachment and post the spec creates, removed in afterAll. + * + * @type {number[]} + */ +let createdIds = []; + +/** + * IDs of the attachments in `createdIds`, whose Cloudinary assets afterAll + * removes. + * + * @type {number[]} + */ +let attachmentIds = []; + +/** + * The image the "Cloudinary only" tests move between storage modes. + * + * @type {{ attachmentId: number, postLink: string }|null} + */ +let offloaded = null; + +/** + * Upload the fixture image and publish a post with it in an image block. + * + * The timestamp in the filename gives a fresh public ID, so no asset from + * an earlier run applies. + * + * @param {Object} requestUtils RequestUtils fixture. + * @param {string} label Part of the filename and post title. + * @return {Promise<{ attachmentId: number, postLink: string }>} The created items. + */ +async function createImagePost( requestUtils, label ) { + const stamp = Date.now(); + const media = await requestUtils.rest( { + method: 'POST', + path: '/wp/v2/media', + headers: { + 'Content-Type': 'image/jpeg', + 'Content-Disposition': `attachment; filename="storage-${ label }-${ stamp }.jpg"`, + }, + data: fs.readFileSync( FIXTURE_PATH ), + } ); + createdIds.push( media.id ); + attachmentIds.push( media.id ); + + const post = await requestUtils.rest( { + method: 'POST', + path: '/wp/v2/posts', + data: { + status: 'publish', + title: `Cloudinary storage ${ label } e2e ${ stamp }`, + content: + `\n` + + `
\n` + + ``, + }, + } ); + createdIds.push( post.id ); + + return { attachmentId: media.id, postLink: post.link }; +} + +/** + * Read the local storage state of an attachment. + * + * @param {number} attachmentId The attachment ID. + * @return {{ file: string, exists: boolean, bytes: number, sizes: Record, storage: string, delay: string }} The state. + */ +function storageState( attachmentId ) { + return JSON.parse( + wpEvalFile( ` + $id = ${ Number( attachmentId ) }; + $media = get_plugin_instance()->get_component( 'media' ); + $file = get_attached_file( $id ); + $meta = wp_get_attachment_metadata( $id ); + $sizes = array(); + if ( ! empty( $meta['sizes'] ) ) { + foreach ( $meta['sizes'] as $name => $size ) { + $sizes[ $name ] = file_exists( path_join( dirname( $file ), $size['file'] ) ); + } + } + clearstatcache(); + echo wp_json_encode( + array( + 'file' => $file, + 'exists' => file_exists( $file ), + 'bytes' => file_exists( $file ) ? filesize( $file ) : 0, + 'sizes' => $sizes, + 'storage' => (string) $media->get_post_meta( $id, Sync::META_KEYS['storage'], true ), + 'delay' => (string) get_post_meta( $id, Sync::META_KEYS['delay'], true ), + ) + ); + ` ) + ); +} + +/** + * Move the start of the "Cloudinary only" delay back, so the next sync + * removes the local files without a one-minute wait. + * + * @param {number} attachmentId The attachment ID. + */ +function endOffloadDelay( attachmentId ) { + wpEvalFile( ` + update_post_meta( + ${ Number( attachmentId ) }, + Sync::META_KEYS['delay'], + time() - \\Cloudinary\\Sync\\Storage::DELETE_DELAY - 1 + ); + ` ); +} + +/** + * Remove the Cloudinary assets of attachments. + * + * Deleting an attachment removes its asset only when the plugin thinks the + * attachment is synced, and a changed storage setting makes it out of + * sync. So remove the assets directly, or they stay in the account. + * + * @param {number[]} ids Attachment IDs. + */ +function destroyRemoteAssets( ids ) { + wpEvalFile( ` + $plugin = get_plugin_instance(); + $media = $plugin->get_component( 'media' ); + $api = $plugin->get_component( 'connect' )->api; + foreach ( array( ${ ids.map( Number ).join( ', ' ) } ) as $id ) { + if ( $media->has_public_id( $id ) ) { + $api->destroy( + $media->get_resource_type( $id ), + array( + 'public_id' => $media->get_public_id( $id ), + 'invalidate' => true, + ) + ); + } + } + ` ); +} + +/** + * Sync one attachment synchronously instead of waiting for the auto-sync + * queue. + * + * Not `wp cloudinary sync`: that syncs every attachment in the library, + * and a storage change replaces or removes the local files of each one. + * + * @param {number} attachmentId The attachment ID. + */ +function sync( attachmentId ) { + wpEvalFile( ` + get_plugin_instance() + ->get_component( 'sync' ) + ->managers['push'] + ->process_assets( ${ Number( attachmentId ) } ); + ` ); +} + +/** + * Open the post and check that its image loads from Cloudinary. + * + * @param {import('@playwright/test').Page} page + * @param {{ attachmentId: number, postLink: string }} item The post to open. + */ +async function expectImageFromCloudinary( page, { attachmentId, postLink } ) { + await page.goto( postLink ); + + const img = page + .locator( `.wp-block-image img.wp-image-${ attachmentId }` ) + .first(); + await expect( img ).toBeVisible(); + await expect + .poll( () => img.evaluate( ( el ) => el.complete && el.naturalWidth ), { + message: 'the image should load', + } ) + .toBeGreaterThan( 0 ); + + expectCloudinaryUrl( await img.getAttribute( 'src' ), cloudName ); +} + +// @serial: needs real credentials in `cloudinary_connect` to sync assets, +// while every analytics spec overwrites that option with fake ones. It also +// changes the storage setting, which every other delivery spec depends on. +test.describe( 'Cloudinary storage modes', { tag: '@serial' }, () => { + test.describe.configure( { mode: 'serial' } ); + + test.beforeAll( () => { + ( { cloudName } = ensureCloudinaryConnected() ); + previousSettings = saveSettings( SETTINGS ); + } ); + + test.afterAll( () => { + try { + if ( previousSettings ) { + saveSettings( previousSettings ); + previousSettings = null; + } + } finally { + offloaded = null; + const ids = createdIds; + const assets = attachmentIds; + createdIds = []; + attachmentIds = []; + + if ( assets.length ) { + try { + destroyRemoteAssets( assets ); + } catch ( e ) { + console.warn( + 'Cleanup of the Cloudinary assets failed:', + e.message + ); + } + } + + // WP-CLI rather than REST for the same reason as the image + // delivery spec: `force=true` on a `?rest_route=` URL is fragile. + for ( const id of ids ) { + try { + wpCli( [ 'post', 'delete', String( id ), '--force' ] ); + } catch ( e ) { + console.warn( + `Cleanup of post ${ id } failed:`, + e.message + ); + } + } + } + } ); + + test( '"Cloudinary only" removes the local files after the delay', async ( { + page, + requestUtils, + } ) => { + saveSettings( { offload: 'cld' } ); + offloaded = await createImagePost( requestUtils, 'cld' ); + const { attachmentId } = offloaded; + + sync( attachmentId ); + + // The plugin waits Storage::DELETE_DELAY before it removes the + // local files, so a failed upload cannot lose the only copy. + let state = storageState( attachmentId ); + expect( + state.exists, + 'the local file should stay during the delay' + ).toBe( true ); + expect( state.delay, 'the delay should start' ).not.toBe( '' ); + expect( state.storage, 'storage should not be set yet' ).not.toBe( + 'cld' + ); + + endOffloadDelay( attachmentId ); + sync( attachmentId ); + + state = storageState( attachmentId ); + expect( state.storage ).toBe( 'cld' ); + expect( + state.exists, + `the local file ${ state.file } should be removed` + ).toBe( false ); + expect( + Object.keys( state.sizes ).length, + 'the attachment should keep its size metadata' + ).toBeGreaterThan( 0 ); + for ( const [ name, exists ] of Object.entries( state.sizes ) ) { + expect( + exists, + `the local "${ name }" size file should be removed` + ).toBe( false ); + } + + // With no local copy left, Cloudinary is the only source. + await expectImageFromCloudinary( page, offloaded ); + } ); + + test( '"Cloudinary and WordPress" downloads the local files again', async ( { + page, + } ) => { + expect( + offloaded, + 'the previous test should offload an image' + ).not.toBeNull(); + const { attachmentId } = offloaded; + + saveSettings( { offload: 'dual_full' } ); + sync( attachmentId ); + + const state = storageState( attachmentId ); + expect( state.storage ).toBe( 'dual_full' ); + expect( + state.exists, + `the local file ${ state.file } should be downloaded again` + ).toBe( true ); + expect( + state.bytes, + 'the local file should be the full-quality original' + ).toBe( FIXTURE_BYTES ); + expect( Object.keys( state.sizes ).length ).toBeGreaterThan( 0 ); + for ( const [ name, exists ] of Object.entries( state.sizes ) ) { + expect( + exists, + `the local "${ name }" size file should be generated again` + ).toBe( true ); + } + + await expectImageFromCloudinary( page, offloaded ); + } ); + + test( '"Cloudinary and WordPress (low resolution)" keeps a smaller local copy', async ( { + page, + requestUtils, + } ) => { + saveSettings( { offload: 'dual_low' } ); + const item = await createImagePost( requestUtils, 'dual-low' ); + + sync( item.attachmentId ); + + const state = storageState( item.attachmentId ); + expect( state.storage ).toBe( 'dual_low' ); + expect( state.exists, 'a local file should stay' ).toBe( true ); + expect( + state.bytes, + 'the local file should be the low-quality version' + ).toBeLessThan( FIXTURE_BYTES ); + + // Delivery still uses the full-quality original on Cloudinary. + await expectImageFromCloudinary( page, item ); + } ); +} ); From f6cf7c6ac4f8833c90c70940fc93b848b2bde280 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Mon, 9 Nov 2026 19:04:45 +0530 Subject: [PATCH 08/50] test(e2e): Cover delete sync to Cloudinary Add an e2e spec that deletes a synced attachment through the REST API and through "Delete permanently" in the Media Library, and checks through the Admin API that its Cloudinary asset is removed. The spec syncs only its own attachments, and cleanup removes any asset a failed test leaves. --- tests/e2e/cloudinary-delete-sync.spec.js | 217 +++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 tests/e2e/cloudinary-delete-sync.spec.js diff --git a/tests/e2e/cloudinary-delete-sync.spec.js b/tests/e2e/cloudinary-delete-sync.spec.js new file mode 100644 index 000000000..d06267f0c --- /dev/null +++ b/tests/e2e/cloudinary-delete-sync.spec.js @@ -0,0 +1,217 @@ +/** + * External dependencies + */ +const fs = require( 'fs' ); +const path = require( 'path' ); +const { test, expect } = require( './fixtures' ); + +/** + * Internal dependencies + */ +const { ensureCloudinaryConnected } = require( './utils/connection' ); +const { wpCli, wpEvalFile } = require( './utils/wizard' ); + +const FIXTURE_PATH = path.join( __dirname, 'fixtures', 'test-image.jpg' ); + +/** + * Attachment IDs the spec creates. afterAll deletes the ones a test did + * not delete. + * + * @type {number[]} + */ +let attachmentIds = []; + +/** + * Public IDs of the Cloudinary assets the spec creates. afterAll removes + * the ones a test did not remove. + * + * @type {string[]} + */ +let publicIds = []; + +/** + * Encode a value as a PHP expression that decodes it back. + * + * @param {unknown} value Any JSON-serializable value. + * @return {string} PHP expression. + */ +function phpJson( value ) { + const encoded = Buffer.from( JSON.stringify( value ) ).toString( 'base64' ); + return `json_decode( base64_decode( '${ encoded }' ), true )`; +} + +/** + * Upload the fixture image and sync it to Cloudinary. + * + * Syncs only this attachment through the push sync, which is what the + * auto-sync queue runs, so other media in the test site is not touched. + * + * @param {Object} requestUtils RequestUtils fixture. + * @param {string} label Part of the filename. + * @return {Promise<{ attachmentId: number, publicId: string }>} The synced attachment. + */ +async function uploadAndSync( requestUtils, label ) { + const media = await requestUtils.rest( { + method: 'POST', + path: '/wp/v2/media', + headers: { + 'Content-Type': 'image/jpeg', + 'Content-Disposition': `attachment; filename="delete-${ label }-${ Date.now() }.jpg"`, + }, + data: fs.readFileSync( FIXTURE_PATH ), + } ); + attachmentIds.push( media.id ); + + const synced = JSON.parse( + wpEvalFile( ` + $id = ${ Number( media.id ) }; + $plugin = get_plugin_instance(); + $plugin->get_component( 'sync' )->managers['push']->process_assets( $id ); + $media = $plugin->get_component( 'media' ); + echo wp_json_encode( + array( + 'publicId' => $media->has_public_id( $id ) ? $media->get_public_id( $id ) : '', + 'synced' => $plugin->get_component( 'sync' )->is_synced( $id, true ), + ) + ); + ` ) + ); + expect( synced.publicId, 'the image should get a public ID' ).toBeTruthy(); + publicIds.push( synced.publicId ); + expect( synced.synced, 'the image should be fully synced' ).toBe( true ); + + return { attachmentId: media.id, publicId: synced.publicId }; +} + +/** + * Check through the Admin API if an image asset exists on Cloudinary. + * + * @param {string} publicId The public ID. + * @return {boolean} True when the asset exists. + */ +function remoteAssetExists( publicId ) { + // Only a 404 means the asset is gone. Any other API error must fail + // the test, or a timeout would look like a successful delete. + const result = wpEvalFile( ` + $details = get_plugin_instance() + ->get_component( 'connect' ) + ->api + ->get_asset_details( ${ phpJson( publicId ) }, 'image' ); + if ( ! is_wp_error( $details ) ) { + echo 'exists'; + } elseif ( 404 === (int) $details->get_error_code() ) { + echo 'missing'; + } else { + echo 'error ' . $details->get_error_code() . ': ' . $details->get_error_message(); + } + ` ); + if ( 'exists' !== result && 'missing' !== result ) { + throw new Error( + `Could not check the Cloudinary asset ${ publicId }: ${ result }` + ); + } + return 'exists' === result; +} + +/** + * Forget an attachment that a test deleted, so afterAll does not delete it + * again. + * + * @param {number} attachmentId The attachment ID. + */ +function forgetAttachment( attachmentId ) { + attachmentIds = attachmentIds.filter( ( id ) => id !== attachmentId ); +} + +// @serial: needs real credentials in `cloudinary_connect` to sync assets, +// while every analytics spec overwrites that option with fake ones. +test.describe( 'Cloudinary delete sync', { tag: '@serial' }, () => { + test.beforeAll( () => { + ensureCloudinaryConnected(); + } ); + + test.afterAll( () => { + const ids = attachmentIds; + const assets = publicIds; + attachmentIds = []; + publicIds = []; + + // Remove the assets directly, so a failed test does not leave + // them in the Cloudinary account. + if ( assets.length ) { + try { + wpEvalFile( ` + $api = get_plugin_instance()->get_component( 'connect' )->api; + foreach ( ${ phpJson( assets ) } as $public_id ) { + $api->destroy( 'image', array( 'public_id' => $public_id ) ); + } + ` ); + } catch ( e ) { + console.warn( + 'Cleanup of the Cloudinary assets failed:', + e.message + ); + } + } + + for ( const id of ids ) { + try { + wpCli( [ 'post', 'delete', String( id ), '--force' ] ); + } catch ( e ) { + console.warn( `Cleanup of post ${ id } failed:`, e.message ); + } + } + } ); + + test( 'deleting an attachment through REST removes its Cloudinary asset', async ( { + requestUtils, + } ) => { + const { attachmentId, publicId } = await uploadAndSync( + requestUtils, + 'rest' + ); + expect( + remoteAssetExists( publicId ), + 'the asset should exist on Cloudinary before the delete' + ).toBe( true ); + + await requestUtils.deleteMedia( attachmentId ); + forgetAttachment( attachmentId ); + + expect( + remoteAssetExists( publicId ), + 'the asset should be removed from Cloudinary' + ).toBe( false ); + } ); + + test( '"Delete permanently" in the Media Library removes the Cloudinary asset', async ( { + admin, + page, + requestUtils, + } ) => { + const { attachmentId, publicId } = await uploadAndSync( + requestUtils, + 'library' + ); + expect( remoteAssetExists( publicId ) ).toBe( true ); + + await admin.visitAdminPage( 'upload.php', 'mode=list' ); + const row = page.locator( `#post-${ attachmentId }` ); + await row.hover(); + + page.once( 'dialog', ( dialog ) => dialog.accept() ); + await Promise.all( [ + page.waitForURL( /upload\.php.*deleted=1/ ), + row.locator( 'a.submitdelete' ).click(), + ] ); + forgetAttachment( attachmentId ); + + await expect( page.locator( `#post-${ attachmentId }` ) ).toHaveCount( + 0 + ); + expect( + remoteAssetExists( publicId ), + 'the asset should be removed from Cloudinary' + ).toBe( false ); + } ); +} ); From d8df72766278c38d87cbaf295a5ddb9eb6bfcc6a Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Tue, 10 Nov 2026 13:58:20 +0530 Subject: [PATCH 09/50] test(e2e): Address storage spec review Fail at once when a sync saves an error, check the size files in the low resolution mode, and destroy the suffixed public ID as delete sync does. --- tests/e2e/cloudinary-storage-modes.spec.js | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/tests/e2e/cloudinary-storage-modes.spec.js b/tests/e2e/cloudinary-storage-modes.spec.js index 716906adb..1b8b6e346 100644 --- a/tests/e2e/cloudinary-storage-modes.spec.js +++ b/tests/e2e/cloudinary-storage-modes.spec.js @@ -166,7 +166,7 @@ function destroyRemoteAssets( ids ) { $api->destroy( $media->get_resource_type( $id ), array( - 'public_id' => $media->get_public_id( $id ), + 'public_id' => $media->get_public_id( $id, true ), 'invalidate' => true, ) ); @@ -182,15 +182,22 @@ function destroyRemoteAssets( ids ) { * Not `wp cloudinary sync`: that syncs every attachment in the library, * and a storage change replaces or removes the local files of each one. * + * `process_assets()` does not report a failure, so fail here on the sync + * error it saves. Otherwise the test fails later on a check that does not + * show the cause. + * * @param {number} attachmentId The attachment ID. */ function sync( attachmentId ) { - wpEvalFile( ` + const error = wpEvalFile( ` + $id = ${ Number( attachmentId ) }; get_plugin_instance() ->get_component( 'sync' ) ->managers['push'] - ->process_assets( ${ Number( attachmentId ) } ); + ->process_assets( $id ); + echo (string) get_post_meta( $id, Sync::META_KEYS['sync_error'], true ); ` ); + expect( error, `attachment ${ attachmentId } should sync` ).toBe( '' ); } /** @@ -360,6 +367,13 @@ test.describe( 'Cloudinary storage modes', { tag: '@serial' }, () => { state.bytes, 'the local file should be the low-quality version' ).toBeLessThan( FIXTURE_BYTES ); + expect( Object.keys( state.sizes ).length ).toBeGreaterThan( 0 ); + for ( const [ name, exists ] of Object.entries( state.sizes ) ) { + expect( + exists, + `the local "${ name }" size file should be generated from the low-quality version` + ).toBe( true ); + } // Delivery still uses the full-quality original on Cloudinary. await expectImageFromCloudinary( page, item ); From ea3da84d9119cd2c4d26f230d6451292ace1e6fa Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Tue, 10 Nov 2026 13:59:16 +0530 Subject: [PATCH 10/50] test(e2e): Share phpJson from the settings util --- tests/e2e/cloudinary-delete-sync.spec.js | 12 +----------- tests/e2e/utils/settings.js | 1 + 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/tests/e2e/cloudinary-delete-sync.spec.js b/tests/e2e/cloudinary-delete-sync.spec.js index d06267f0c..b11dda99b 100644 --- a/tests/e2e/cloudinary-delete-sync.spec.js +++ b/tests/e2e/cloudinary-delete-sync.spec.js @@ -9,6 +9,7 @@ const { test, expect } = require( './fixtures' ); * Internal dependencies */ const { ensureCloudinaryConnected } = require( './utils/connection' ); +const { phpJson } = require( './utils/settings' ); const { wpCli, wpEvalFile } = require( './utils/wizard' ); const FIXTURE_PATH = path.join( __dirname, 'fixtures', 'test-image.jpg' ); @@ -29,17 +30,6 @@ let attachmentIds = []; */ let publicIds = []; -/** - * Encode a value as a PHP expression that decodes it back. - * - * @param {unknown} value Any JSON-serializable value. - * @return {string} PHP expression. - */ -function phpJson( value ) { - const encoded = Buffer.from( JSON.stringify( value ) ).toString( 'base64' ); - return `json_decode( base64_decode( '${ encoded }' ), true )`; -} - /** * Upload the fixture image and sync it to Cloudinary. * diff --git a/tests/e2e/utils/settings.js b/tests/e2e/utils/settings.js index 3c6720d29..328316e38 100644 --- a/tests/e2e/utils/settings.js +++ b/tests/e2e/utils/settings.js @@ -62,6 +62,7 @@ function readSettings( slugs ) { } module.exports = { + phpJson, readSettings, saveSettings, }; From 136be400a522db8ceaf9f10c09b0d3fc5e35501a Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Mon, 2 Nov 2026 17:47:08 +0530 Subject: [PATCH 11/50] refactor(e2e): Move gallery helpers to a shared util Move galleryBlock(), openGallery() and collectImageUrls() out of the gallery delivery spec into tests/e2e/utils/gallery.js, so the custom domain spec can render the Gallery block the same way. --- tests/e2e/cloudinary-gallery-delivery.spec.js | 74 ++------------ tests/e2e/utils/gallery.js | 98 +++++++++++++++++++ 2 files changed, 106 insertions(+), 66 deletions(-) create mode 100644 tests/e2e/utils/gallery.js diff --git a/tests/e2e/cloudinary-gallery-delivery.spec.js b/tests/e2e/cloudinary-gallery-delivery.spec.js index a301c2be0..6c5f98904 100644 --- a/tests/e2e/cloudinary-gallery-delivery.spec.js +++ b/tests/e2e/cloudinary-gallery-delivery.spec.js @@ -10,17 +10,17 @@ const { test, expect } = require( './fixtures' ); */ const { ensureCloudinaryConnected } = require( './utils/connection' ); const { expectCloudinaryUrl, srcsetUrls } = require( './utils/delivery' ); +const { + collectImageUrls, + galleryBlock, + openGallery: openGalleryAt, +} = require( './utils/gallery' ); const { wpCli } = require( './utils/wizard' ); const FIXTURE_PATH = path.join( __dirname, 'fixtures', 'test-image.jpg' ); const IMAGE_COUNT = 3; const INITIAL_COLUMNS = 3; -const CONTAINER = 'cld-gallery-e2e'; - -// The Cloudinary Gallery Widget is loaded from product-gallery.cloudinary.com -// and renders on `window.load`, so allow for a slow third-party fetch. -const WIDGET_TIMEOUT = 30_000; let cloudName; @@ -33,71 +33,13 @@ let cloudName; let created = null; /** - * Build the serialized `cloudinary/gallery` block. The inner markup must - * match the block's `save()` output exactly, or the editor flags the block - * as invalid when the layout test opens the post. - * - * @param {Object[]} selectedImages Response of the plugin's `image_data` endpoint. - * @param {Object} layout Layout attributes. - * @param {string} layout.mode `expanded` or `classic`. - * @param {number} layout.columns Column count (expanded mode only). - * @return {string} Block markup. - */ -function galleryBlock( selectedImages, { mode, columns } ) { - const attributes = { - container: CONTAINER, - selectedImages, - displayProps_mode: mode, - displayProps_columns: columns, - }; - - return ( - `\n` + - `
\n` + - `` - ); -} - -/** - * Open the published post and wait for the Gallery Widget to finish - * rendering every image in the main viewer. + * Open the published post and wait for every gallery image to render. * * @param {import('@playwright/test').Page} page * @return {Promise} The widget root. */ -async function openGallery( page ) { - await page.goto( created.postLink ); - - const gallery = page.locator( - `.${ CONTAINER } [data-test="gallery-wrap"]` - ); - await expect( - gallery, - 'the Gallery Widget should render into the block container' - ).toBeVisible( { timeout: WIDGET_TIMEOUT } ); - - await expect( - gallery.locator( - '[data-test="gallery-viewer-wrap"] [data-test="image-wrap"][data-ready="true"]' - ) - ).toHaveCount( IMAGE_COUNT, { timeout: WIDGET_TIMEOUT } ); - - return gallery; -} - -/** - * Read the `src` and `srcset` attributes of the given images. - * - * @param {import('@playwright/test').Locator} images - * @return {Promise>} Attributes per image. - */ -async function collectImageUrls( images ) { - return images.evaluateAll( ( nodes ) => - nodes.map( ( img ) => ( { - src: img.getAttribute( 'src' ), - srcset: img.getAttribute( 'srcset' ), - } ) ) - ); +function openGallery( page ) { + return openGalleryAt( page, created.postLink, IMAGE_COUNT ); } // @serial: needs real credentials in `cloudinary_connect` to sync assets, diff --git a/tests/e2e/utils/gallery.js b/tests/e2e/utils/gallery.js new file mode 100644 index 000000000..7948429a6 --- /dev/null +++ b/tests/e2e/utils/gallery.js @@ -0,0 +1,98 @@ +/** + * Helpers for specs that render the Cloudinary Gallery block. + */ + +const { expect } = require( '../fixtures' ); + +/** + * Class of the block container the Gallery Widget renders into. + * + * @type {string} + */ +const GALLERY_CONTAINER = 'cld-gallery-e2e'; + +/** + * The Cloudinary Gallery Widget is loaded from product-gallery.cloudinary.com + * and renders on `window.load`, so allow for a slow third-party fetch. + * + * @type {number} + */ +const WIDGET_TIMEOUT = 30_000; + +/** + * Build the serialized `cloudinary/gallery` block. The inner markup must + * match the block's `save()` output exactly, or the editor flags the block + * as invalid when a test opens the post. + * + * @param {Object[]} selectedImages Response of the plugin's `image_data` endpoint. + * @param {Object} layout Layout attributes. + * @param {string} layout.mode `expanded` or `classic`. + * @param {number} layout.columns Column count (expanded mode only). + * @return {string} Block markup. + */ +function galleryBlock( selectedImages, { mode, columns } ) { + const attributes = { + container: GALLERY_CONTAINER, + selectedImages, + displayProps_mode: mode, + displayProps_columns: columns, + }; + + return ( + `\n` + + `\n` + + `` + ); +} + +/** + * Open a published post and wait for the Gallery Widget to finish + * rendering every image in the main viewer. + * + * @param {import('@playwright/test').Page} page + * @param {string} postLink Post permalink. + * @param {number} imageCount Number of images in the gallery. + * @return {Promise} The widget root. + */ +async function openGallery( page, postLink, imageCount ) { + await page.goto( postLink ); + + const gallery = page.locator( + `.${ GALLERY_CONTAINER } [data-test="gallery-wrap"]` + ); + await expect( + gallery, + 'the Gallery Widget should render into the block container' + ).toBeVisible( { timeout: WIDGET_TIMEOUT } ); + + await expect( + gallery.locator( + '[data-test="gallery-viewer-wrap"] [data-test="image-wrap"][data-ready="true"]' + ) + ).toHaveCount( imageCount, { timeout: WIDGET_TIMEOUT } ); + + return gallery; +} + +/** + * Read the `src` and `srcset` attributes of the given images. + * + * @param {import('@playwright/test').Locator} images + * @return {Promise>} Attributes per image. + */ +async function collectImageUrls( images ) { + return images.evaluateAll( ( nodes ) => + nodes.map( ( img ) => ( { + src: img.getAttribute( 'src' ), + srcset: img.getAttribute( 'srcset' ), + } ) ) + ); +} + +module.exports = { + GALLERY_CONTAINER, + WIDGET_TIMEOUT, + collectImageUrls, + galleryBlock, + openGallery, +}; From c7f4053aff882d992394402c88ab7ad34ced04f0 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Mon, 2 Nov 2026 17:47:10 +0530 Subject: [PATCH 12/50] test(e2e): Support custom domains in delivery utils - ensureCloudinaryConnected() accepts { cname, privateCdn } and adds them to the connection string. It now fails when the plugin does not save the new string. - expectCloudinaryUrl() accepts { host, cloudName, privateCdn }. - routeCnameToCloudinary() sends requests for a fake custom domain on to res.cloudinary.com, so the images still load. --- tests/e2e/utils/connection.js | 54 +++++++++++++++++++++++++++-- tests/e2e/utils/delivery.js | 64 +++++++++++++++++++++++++++++++---- 2 files changed, 109 insertions(+), 9 deletions(-) diff --git a/tests/e2e/utils/connection.js b/tests/e2e/utils/connection.js index 10950714b..a67e23547 100644 --- a/tests/e2e/utils/connection.js +++ b/tests/e2e/utils/connection.js @@ -28,6 +28,33 @@ function parseCloudName( cloudinaryUrl ) { return match[ 1 ]; } +/** + * Add custom domain parameters to a connection string. + * + * @param {string} cloudinaryUrl The `cloudinary://` connection string. + * @param {Object} options + * @param {string} [options.cname] Custom delivery domain. + * @param {boolean} [options.privateCdn] Set to false to keep the cloud name + * in the delivery path. + * @return {string} The connection string with the parameters added. + */ +function withConnectionParams( cloudinaryUrl, { cname, privateCdn } ) { + const params = new URLSearchParams(); + if ( cname ) { + params.set( 'cname', cname ); + } + if ( false === privateCdn ) { + params.set( 'private_cdn', 'false' ); + } + const query = params.toString(); + if ( ! query ) { + return cloudinaryUrl; + } + return `${ cloudinaryUrl }${ + cloudinaryUrl.includes( '?' ) ? '&' : '?' + }${ query }`; +} + /** * Set the plugin's `cloudinary_connect` option directly so the plugin * is "connected" for the duration of the spec. @@ -36,10 +63,21 @@ function parseCloudName( cloudinaryUrl ) { * NOT pre-populate `cloudinary_connection_signature` or * `cloudinary_status`; the plugin will populate those on first need. * + * With `cname`, the custom domain is added to the connection string the + * same way a user adds it in the settings. The plugin only checks that it + * looks like a domain and never resolves it, so a fake domain works. + * + * @param {Object} [options] + * @param {string} [options.cname] Custom delivery domain. + * @param {boolean} [options.privateCdn] Set to false to keep the cloud name + * in the delivery path. * @return {{ cloudName: string }} The cloud name extracted from the URL. */ -function ensureCloudinaryConnected() { - const cloudinaryUrl = getCloudinaryUrlFromEnv(); +function ensureCloudinaryConnected( options = {} ) { + const cloudinaryUrl = withConnectionParams( + getCloudinaryUrlFromEnv(), + options + ); const cloudName = parseCloudName( cloudinaryUrl ); // Build the JSON payload the plugin expects. @@ -56,6 +94,18 @@ function ensureCloudinaryConnected() { '--format=json', ] ); + // The plugin tests a changed connection string against the API before + // it saves it, and keeps the old one when the test fails. Fail here + // rather than let a spec run against the wrong connection. + const saved = JSON.parse( + wpCli( [ 'option', 'get', 'cloudinary_connect', '--format=json' ] ) + ); + if ( saved?.cloudinary_url !== cloudinaryUrl ) { + throw new Error( + 'The plugin did not save the new Cloudinary connection string. Check that CLOUDINARY_E2E_URL is valid.' + ); + } + return { cloudName }; } diff --git a/tests/e2e/utils/delivery.js b/tests/e2e/utils/delivery.js index db53d43c8..c4771c96a 100644 --- a/tests/e2e/utils/delivery.js +++ b/tests/e2e/utils/delivery.js @@ -4,27 +4,75 @@ const { expect } = require( '../fixtures' ); +/** + * Default Cloudinary delivery host. + * + * @type {string} + */ +const CLOUDINARY_HOST = 'res.cloudinary.com'; + /** * Assert that a given image URL is served by Cloudinary under the * expected cloud name. We intentionally do not assert specific * transformations — those are an implementation detail of the plugin * and may change. * - * @param {string} rawUrl The src or srcset candidate. - * @param {string} expectedCloud The cloud name parsed from CLOUDINARY_E2E_URL. + * Pass an object to check delivery through a custom domain. With + * `privateCdn` (the plugin's default for a custom domain), the path does + * not start with the cloud name. + * + * @param {string} rawUrl The src or srcset candidate. + * @param {string|{ cloudName: string, host?: string, privateCdn?: boolean }} expected The cloud name parsed from + * CLOUDINARY_E2E_URL, or the + * expected host and path form. */ -function expectCloudinaryUrl( rawUrl, expectedCloud ) { +function expectCloudinaryUrl( rawUrl, expected ) { + const { + cloudName, + host = CLOUDINARY_HOST, + privateCdn = false, + } = 'string' === typeof expected ? { cloudName: expected } : expected; + let parsed; try { parsed = new URL( rawUrl ); } catch ( e ) { throw new Error( `Image URL is not parseable: ${ rawUrl }` ); } - expect( parsed.host, `host of ${ rawUrl }` ).toBe( 'res.cloudinary.com' ); + expect( parsed.host, `host of ${ rawUrl }` ).toBe( host ); expect( - parsed.pathname.startsWith( `/${ expectedCloud }/` ), - `pathname of ${ rawUrl } should start with /${ expectedCloud }/` - ).toBe( true ); + parsed.pathname.startsWith( `/${ cloudName }/` ), + `pathname of ${ rawUrl } should ${ + privateCdn ? 'not ' : '' + }start with /${ cloudName }/` + ).toBe( ! privateCdn ); +} + +/** + * Send requests for a fake custom domain on to res.cloudinary.com, so + * images delivered through it still load. + * + * Cloudinary serves a custom domain at the same path, with the cloud name + * at the start of the path only when the domain is not a private CDN. + * + * @param {import('@playwright/test').Page} page + * @param {Object} options + * @param {string} options.cname The fake custom domain. + * @param {string} options.cloudName The cloud name. + * @param {boolean} options.privateCdn Whether the path leaves out the cloud name. + * @return {Promise} + */ +async function routeCnameToCloudinary( + page, + { cname, cloudName, privateCdn } +) { + await page.route( `https://${ cname }/**`, ( route ) => { + const url = new URL( route.request().url() ); + const prefix = privateCdn ? `/${ cloudName }` : ''; + return route.continue( { + url: `https://${ CLOUDINARY_HOST }${ prefix }${ url.pathname }${ url.search }`, + } ); + } ); } /** @@ -74,7 +122,9 @@ function srcsetUrls( srcset ) { } module.exports = { + CLOUDINARY_HOST, expectCloudinaryUrl, parseSrcset, + routeCnameToCloudinary, srcsetUrls, }; From 24b7847e5093beb4a1cf963e5da4ed9807dd5643 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Mon, 2 Nov 2026 17:47:12 +0530 Subject: [PATCH 13/50] test(e2e): Cover delivery through a custom domain Connect with a fake custom domain and check that the image block, the Gallery widget and the Cloudinary video player use it. Check that private_cdn=false keeps the cloud name in the path. Restore the plain connection in afterAll. Refs WPP-1240 --- tests/e2e/cloudinary-cname-delivery.spec.js | 392 ++++++++++++++++++++ 1 file changed, 392 insertions(+) create mode 100644 tests/e2e/cloudinary-cname-delivery.spec.js diff --git a/tests/e2e/cloudinary-cname-delivery.spec.js b/tests/e2e/cloudinary-cname-delivery.spec.js new file mode 100644 index 000000000..657708888 --- /dev/null +++ b/tests/e2e/cloudinary-cname-delivery.spec.js @@ -0,0 +1,392 @@ +/** + * External dependencies + */ +const fs = require( 'fs' ); +const path = require( 'path' ); +const { test, expect } = require( './fixtures' ); + +/** + * Internal dependencies + */ +const { ensureCloudinaryConnected } = require( './utils/connection' ); +const { + expectCloudinaryUrl, + routeCnameToCloudinary, + srcsetUrls, +} = require( './utils/delivery' ); +const { + collectImageUrls, + galleryBlock, + openGallery, +} = require( './utils/gallery' ); +const { wpCli, wpEvalFile } = require( './utils/wizard' ); + +const IMAGE_FIXTURE = path.join( __dirname, 'fixtures', 'test-image.jpg' ); +const VIDEO_FIXTURE = path.join( __dirname, 'fixtures', 'test-video.mp4' ); + +/** + * A fake custom domain. The plugin only checks that it looks like a domain + * and never resolves it. Requests to it are sent on to res.cloudinary.com + * by `routeCnameToCloudinary()`, so the images still load. + * + * @type {string} + */ +const CNAME = 'cdn.e2e-cloudinary.test'; + +const IMAGE_COUNT = 3; + +/** + * Settings pinned for the spec, restored in afterAll. Without lazy load + * the server writes the final URLs into `src` and `srcset`, and the + * breakpoints make sure there is a Cloudinary `srcset` to check. The + * Cloudinary player is what receives the custom domain for video. + * + * @type {Record} + */ +const SETTINGS = { + use_lazy_load: 'off', + enable_breakpoints: 'on', + video_player: 'cld', +}; + +let cloudName; + +/** @type {Record|null} */ +let previousSettings = null; + +/** + * IDs of every attachment and post the spec creates, removed in afterAll. + * Each ID is recorded as soon as it exists, so a setup that fails part way + * is still cleaned up. + * + * @type {number[]} + */ +let createdIds = []; + +/** + * @type {{ imagePost: { link: string, attachmentId: number }, galleryPost: { link: string }, videoPost: { link: string } }|null} + */ +let created = null; + +/** + * Save plugin settings through the settings API and return the old values. + * + * @param {Record} values Setting slug to value. + * @return {Record} Setting slug to the value before the write. + */ +function saveSettings( values ) { + return JSON.parse( + wpEvalFile( ` + $settings = get_plugin_instance()->settings; + $previous = array(); + foreach ( json_decode( '${ JSON.stringify( + values + ) }', true ) as $slug => $value ) { + $setting = $settings->get_setting( $slug ); + $previous[ $slug ] = $setting->get_value(); + $setting->save_value( $value ); + } + echo wp_json_encode( $previous ); + ` ) + ); +} + +/** + * Upload a fixture file through REST and record its ID for cleanup. + * + * The timestamp in the filename gives a fresh public ID, so no CDN cache + * from an earlier run applies. + * + * @param {Object} requestUtils RequestUtils fixture. + * @param {string} fixturePath Path to the fixture. + * @param {string} contentType MIME type of the fixture. + * @param {string} filename Filename for the upload. + * @return {Promise<{ id: number, source_url: string }>} The created attachment. + */ +async function upload( requestUtils, fixturePath, contentType, filename ) { + const media = await requestUtils.rest( { + method: 'POST', + path: '/wp/v2/media', + headers: { + 'Content-Type': contentType, + 'Content-Disposition': `attachment; filename="${ filename }"`, + }, + data: fs.readFileSync( fixturePath ), + } ); + createdIds.push( media.id ); + return media; +} + +/** + * Publish a post and record its ID for cleanup. + * + * @param {Object} requestUtils RequestUtils fixture. + * @param {string} title Post title. + * @param {string} content Serialized block content. + * @return {Promise} The post permalink. + */ +async function publish( requestUtils, title, content ) { + const post = await requestUtils.rest( { + method: 'POST', + path: '/wp/v2/posts', + data: { + status: 'publish', + title: `${ title } ${ Date.now() }`, + content, + }, + } ); + createdIds.push( post.id ); + return post.link; +} + +/** + * Open the image post and return the URLs of the inline image. + * + * @param {import('@playwright/test').Page} page + * @return {Promise} The `src` and every `srcset` URL. + */ +async function imageBlockUrls( page ) { + await page.goto( created.imagePost.link ); + + const img = page + .locator( + `.wp-block-image img.wp-image-${ created.imagePost.attachmentId }` + ) + .first(); + await expect( img ).toBeVisible(); + + // The image only loads if the delivery URL works, which proves the + // path the plugin built on the custom domain is a valid Cloudinary path. + await expect + .poll( () => img.evaluate( ( el ) => el.complete && el.naturalWidth ), { + message: 'the image should load through the custom domain', + } ) + .toBeGreaterThan( 0 ); + + const { src, srcset } = await img.evaluate( ( el ) => ( { + src: el.getAttribute( 'src' ), + srcset: el.getAttribute( 'srcset' ), + } ) ); + expect( src, 'the image should have a src' ).toBeTruthy(); + expect( srcset, 'the image should have a srcset' ).toBeTruthy(); + + return [ src, ...srcsetUrls( srcset ) ]; +} + +// @serial: needs real credentials in `cloudinary_connect` to sync assets, +// while every analytics spec overwrites that option with fake ones. It also +// changes the connection string, which every other delivery spec reads. +test.describe( + 'Cloudinary delivery through a custom domain', + { tag: '@serial' }, + () => { + test.describe.configure( { mode: 'serial' } ); + + test.beforeAll( async ( { requestUtils } ) => { + // Connect with the custom domain before the upload, as a site + // that uses one would be. + ( { cloudName } = ensureCloudinaryConnected( { cname: CNAME } ) ); + previousSettings = saveSettings( SETTINGS ); + + const stamp = Date.now(); + const images = []; + for ( let i = 0; i < IMAGE_COUNT; i++ ) { + images.push( + await upload( + requestUtils, + IMAGE_FIXTURE, + 'image/jpeg', + `cname-e2e-${ stamp }-${ i }.jpg` + ) + ); + } + const attachmentIds = images.map( ( media ) => media.id ); + + // Same endpoint the block editor calls when images are picked + // for a gallery. It syncs each attachment and returns the + // block's `selectedImages` attribute. + const selectedImages = await requestUtils.rest( { + method: 'POST', + path: '/cloudinary/v1/image_data', + data: { images: attachmentIds.map( ( id ) => ( { id } ) ) }, + } ); + expect( + selectedImages, + 'every attachment should sync to Cloudinary' + ).toHaveLength( IMAGE_COUNT ); + + // The local URL from the upload response, as the editor would + // insert it. The plugin replaces it with the delivery URL. + const image = images[ 0 ]; + const imageLink = await publish( + requestUtils, + 'Cloudinary CNAME image e2e', + `\n` + + `
\n` + + `` + ); + + const galleryLink = await publish( + requestUtils, + 'Cloudinary CNAME gallery e2e', + galleryBlock( selectedImages, { + mode: 'expanded', + columns: IMAGE_COUNT, + } ) + ); + + const video = await upload( + requestUtils, + VIDEO_FIXTURE, + 'video/mp4', + `cname-e2e-${ stamp }.mp4` + ); + const videoLink = await publish( + requestUtils, + 'Cloudinary CNAME video e2e', + `\n` + + `
\n` + + `` + ); + + // Same reason as the image delivery spec: sync synchronously + // instead of waiting for the auto-sync queue. + wpCli( [ 'cloudinary', 'sync' ] ); + + created = { + imagePost: { link: imageLink, attachmentId: image.id }, + galleryPost: { link: galleryLink }, + videoPost: { link: videoLink }, + }; + } ); + + test.afterAll( () => { + // Put the plain connection back first: every other delivery + // spec in the serial run expects res.cloudinary.com URLs. + try { + ensureCloudinaryConnected(); + } finally { + if ( previousSettings ) { + saveSettings( previousSettings ); + previousSettings = null; + } + created = null; + const ids = createdIds; + createdIds = []; + + // WP-CLI rather than REST for the same reason as the image + // delivery spec: `force=true` on a `?rest_route=` URL is + // fragile. + for ( const id of ids ) { + try { + wpCli( [ 'post', 'delete', String( id ), '--force' ] ); + } catch ( e ) { + console.warn( + `Cleanup of post ${ id } failed:`, + e.message + ); + } + } + } + } ); + + test( 'image block src and srcset use the custom domain', async ( { + page, + } ) => { + await routeCnameToCloudinary( page, { + cname: CNAME, + cloudName, + privateCdn: true, + } ); + + for ( const url of await imageBlockUrls( page ) ) { + expectCloudinaryUrl( url, { + host: CNAME, + cloudName, + privateCdn: true, + } ); + } + } ); + + test( 'gallery widget images use the custom domain', async ( { + page, + } ) => { + await routeCnameToCloudinary( page, { + cname: CNAME, + cloudName, + privateCdn: true, + } ); + + // Waits until every image reports data-ready="true", which + // needs the custom domain requests to succeed. + const gallery = await openGallery( + page, + created.galleryPost.link, + IMAGE_COUNT + ); + + await expect( + gallery.locator( '[data-test="gallery-viewer-wrap"] img' ), + `the gallery should show exactly ${ IMAGE_COUNT } images` + ).toHaveCount( IMAGE_COUNT ); + + // Every the widget renders, viewer and thumbnails alike. + const attrs = await collectImageUrls( gallery.locator( 'img' ) ); + expect( + attrs.every( ( { src } ) => !! src ), + 'every gallery image should have a src' + ).toBe( true ); + for ( const { src, srcset } of attrs ) { + for ( const url of [ src, ...srcsetUrls( srcset ) ] ) { + expectCloudinaryUrl( url, { + host: CNAME, + cloudName, + privateCdn: true, + } ); + } + } + } ); + + test( 'Cloudinary video player receives the custom domain', async ( { + page, + } ) => { + await page.goto( created.videoPost.link ); + + const iframe = page + .locator( 'figure.wp-block-embed.is-type-video iframe' ) + .first(); + await expect( + iframe, + 'Cloudinary player iframe should be emitted in place of