fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNewPost = void 0;
/**
* Creates new post.
*
* @param this
* @param options Options to create new post.
*/
async function createNewPost(options = {}) {
const query = new URLSearchParams();
const { postType, title, content, excerpt } = options;
if (postType) {
query.set('post_type', postType);
}
if (title) {
query.set('post_title', title);
}
if (content) {
query.set('content', content);
}
if (excerpt) {
query.set('excerpt', excerpt);
}
await this.visitAdminPage('post-new.php', query.toString());
await this.editor.setPreferences('core/edit-post', {
welcomeGuide: options.showWelcomeGuide ?? false,
fullscreenMode: false,
});
}
exports.createNewPost = createNewPost;
//# sourceMappingURL=create-new-post.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"create-new-post.js","sourceRoot":"","sources":["../../src/admin/create-new-post.ts"],"names":[],"mappings":";;;AAaA;;;;;GAKG;AACI,KAAK,UAAU,aAAa,CAElC,UAA0B,EAAE;IAE5B,MAAM,KAAK,GAAG,IAAI,eAAe,EAAE,CAAC;IACpC,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAEtD,IAAK,QAAQ,EAAG,CAAC;QAChB,KAAK,CAAC,GAAG,CAAE,WAAW,EAAE,QAAQ,CAAE,CAAC;IACpC,CAAC;IACD,IAAK,KAAK,EAAG,CAAC;QACb,KAAK,CAAC,GAAG,CAAE,YAAY,EAAE,KAAK,CAAE,CAAC;IAClC,CAAC;IACD,IAAK,OAAO,EAAG,CAAC;QACf,KAAK,CAAC,GAAG,CAAE,SAAS,EAAE,OAAO,CAAE,CAAC;IACjC,CAAC;IACD,IAAK,OAAO,EAAG,CAAC;QACf,KAAK,CAAC,GAAG,CAAE,SAAS,EAAE,OAAO,CAAE,CAAC;IACjC,CAAC;IAED,MAAM,IAAI,CAAC,cAAc,CAAE,cAAc,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAE,CAAC;IAE9D,MAAM,IAAI,CAAC,MAAM,CAAC,cAAc,CAAE,gBAAgB,EAAE;QACnD,YAAY,EAAE,OAAO,CAAC,gBAAgB,IAAI,KAAK;QAC/C,cAAc,EAAE,KAAK;KACrB,CAAE,CAAC;AACL,CAAC;AA1BD,sCA0BC"}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.editPost = void 0;
/**
* Open the post with given ID in the editor.
*
* @param this
* @param postId Post ID to visit.
*/
async function editPost(postId) {
const query = new URLSearchParams();
query.set('post', String(postId));
query.set('action', 'edit');
await this.visitAdminPage('post.php', query.toString());
await this.editor.setPreferences('core/edit-post', {
welcomeGuide: false,
fullscreenMode: false,
});
}
exports.editPost = editPost;
//# sourceMappingURL=edit-post.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"edit-post.js","sourceRoot":"","sources":["../../src/admin/edit-post.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,QAAQ,CAAe,MAAuB;IACnE,MAAM,KAAK,GAAG,IAAI,eAAe,EAAE,CAAC;IAEpC,KAAK,CAAC,GAAG,CAAE,MAAM,EAAE,MAAM,CAAE,MAAM,CAAE,CAAE,CAAC;IACtC,KAAK,CAAC,GAAG,CAAE,QAAQ,EAAE,MAAM,CAAE,CAAC;IAE9B,MAAM,IAAI,CAAC,cAAc,CAAE,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAE,CAAC;IAE1D,MAAM,IAAI,CAAC,MAAM,CAAC,cAAc,CAAE,gBAAgB,EAAE;QACnD,YAAY,EAAE,KAAK;QACnB,cAAc,EAAE,KAAK;KACrB,CAAE,CAAC;AACL,CAAC;AAZD,4BAYC"}

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPageError = void 0;
/**
* Regular expression matching a displayed PHP error within a markup string.
*
* @see https://github.com/php/php-src/blob/598175e/main/main.c#L1257-L1297
*/
const REGEXP_PHP_ERROR = /(<b>)?(Fatal error|Recoverable fatal error|Warning|Parse error|Notice|Strict Standards|Deprecated|Unknown error)(<\/b>)?: (.*?) in (.*?) on line (<b>)?\d+(<\/b>)?/;
/**
* Returns a promise resolving to one of either a string or null. A string will
* be resolved if an error message is present in the contents of the page. If no
* error is present, a null value will be resolved instead. This requires the
* environment be configured to display errors.
*
* @see http://php.net/manual/en/function.error-reporting.php
*
* @param this
* @return Promise resolving to a string or null, depending whether a page error is present.
*/
async function getPageError() {
const content = await this.page.content();
const match = content.match(REGEXP_PHP_ERROR);
return match ? match[0] : null;
}
exports.getPageError = getPageError;
//# sourceMappingURL=get-page-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"get-page-error.js","sourceRoot":"","sources":["../../src/admin/get-page-error.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACH,MAAM,gBAAgB,GACrB,oKAAoK,CAAC;AAEtK;;;;;;;;;;GAUG;AACI,KAAK,UAAU,YAAY;IACjC,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAE,gBAAgB,CAAE,CAAC;IAChD,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAE,CAAC,CAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAClC,CAAC;AAJD,oCAIC"}

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Admin = void 0;
/**
* Internal dependencies
*/
const create_new_post_1 = require("./create-new-post");
const get_page_error_1 = require("./get-page-error");
const visit_admin_page_1 = require("./visit-admin-page");
const edit_post_1 = require("./edit-post");
const visit_site_editor_1 = require("./visit-site-editor");
class Admin {
page;
context;
browser;
pageUtils;
editor;
constructor({ page, pageUtils, editor }) {
this.page = page;
this.context = page.context();
this.browser = this.context.browser();
this.pageUtils = pageUtils;
this.editor = editor;
}
/** @borrows createNewPost as this.createNewPost */
createNewPost = create_new_post_1.createNewPost.bind(this);
/** @borrows editPost as this.editPost */
editPost = edit_post_1.editPost.bind(this);
/** @borrows getPageError as this.getPageError */
getPageError = get_page_error_1.getPageError.bind(this);
/** @borrows visitAdminPage as this.visitAdminPage */
visitAdminPage = visit_admin_page_1.visitAdminPage.bind(this);
/** @borrows visitSiteEditor as this.visitSiteEditor */
visitSiteEditor = visit_site_editor_1.visitSiteEditor.bind(this);
}
exports.Admin = Admin;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/admin/index.ts"],"names":[],"mappings":";;;AAKA;;GAEG;AACH,uDAAkD;AAClD,qDAAgD;AAChD,yDAAoD;AACpD,2CAAuC;AACvC,2DAAsD;AAUtD,MAAa,KAAK;IACjB,IAAI,CAAO;IACX,OAAO,CAAiB;IACxB,OAAO,CAAU;IACjB,SAAS,CAAY;IACrB,MAAM,CAAS;IAEf,YAAa,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAyB;QAC9D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC9B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAG,CAAC;QACvC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;IAED,mDAAmD;IACnD,aAAa,GAAyB,+BAAa,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACjE,yCAAyC;IACzC,QAAQ,GAAoB,oBAAQ,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAClD,iDAAiD;IACjD,YAAY,GAAwB,6BAAY,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAC9D,qDAAqD;IACrD,cAAc,GAA0B,iCAAc,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACpE,uDAAuD;IACvD,eAAe,GAA2B,mCAAe,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;CACvE;AAzBD,sBAyBC"}

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.visitAdminPage = void 0;
/**
* External dependencies
*/
const path_1 = require("path");
/**
* Visits admin page and handle errors.
*
* @param this
* @param adminPath String to be serialized as pathname.
* @param query String to be serialized as query portion of URL.
*/
async function visitAdminPage(adminPath, query) {
await this.page.goto((0, path_1.join)('wp-admin', adminPath) + (query ? `?${query}` : ''));
// Handle upgrade required screen
if (this.pageUtils.isCurrentURL('wp-admin/upgrade.php')) {
// Click update
await this.page.click('.button.button-large.button-primary');
// Click continue
await this.page.click('.button.button-large');
}
if (this.pageUtils.isCurrentURL('wp-login.php')) {
throw new Error('Not logged in');
}
const error = await this.getPageError();
if (error) {
throw new Error('Unexpected error in page content: ' + error);
}
}
exports.visitAdminPage = visitAdminPage;
//# sourceMappingURL=visit-admin-page.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"visit-admin-page.js","sourceRoot":"","sources":["../../src/admin/visit-admin-page.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,+BAA4B;AAO5B;;;;;;GAMG;AACI,KAAK,UAAU,cAAc,CAEnC,SAAiB,EACjB,KAAc;IAEd,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CACnB,IAAA,WAAI,EAAE,UAAU,EAAE,SAAS,CAAE,GAAG,CAAE,KAAK,CAAC,CAAC,CAAC,IAAK,KAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAE,CAC9D,CAAC;IAEF,iCAAiC;IACjC,IAAK,IAAI,CAAC,SAAS,CAAC,YAAY,CAAE,sBAAsB,CAAE,EAAG,CAAC;QAC7D,eAAe;QACf,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAE,qCAAqC,CAAE,CAAC;QAC/D,iBAAiB;QACjB,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAE,sBAAsB,CAAE,CAAC;IACjD,CAAC;IAED,IAAK,IAAI,CAAC,SAAS,CAAC,YAAY,CAAE,cAAc,CAAE,EAAG,CAAC;QACrD,MAAM,IAAI,KAAK,CAAE,eAAe,CAAE,CAAC;IACpC,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;IACxC,IAAK,KAAK,EAAG,CAAC;QACb,MAAM,IAAI,KAAK,CAAE,oCAAoC,GAAG,KAAK,CAAE,CAAC;IACjE,CAAC;AACF,CAAC;AAzBD,wCAyBC"}

View File

@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.visitSiteEditor = void 0;
/**
* Visits the Site Editor main page.
*
* @param this
* @param options Options to visit the site editor.
*/
async function visitSiteEditor(options = {}) {
const { postId, postType, path, canvas } = options;
const query = new URLSearchParams();
if (postId) {
query.set('postId', String(postId));
}
if (postType) {
query.set('postType', postType);
}
if (path) {
query.set('path', path);
}
if (canvas) {
query.set('canvas', canvas);
}
const canvasLoader = this.page.locator(
// Spinner was used instead of the progress bar in an earlier version of
// the site editor.
'.edit-site-canvas-loader, .edit-site-canvas-spinner');
await this.visitAdminPage('site-editor.php', query.toString());
// Try waiting for the canvas loader to appear first, so that the locator
// that waits for it to disappear doesn't resolve prematurely.
await canvasLoader.waitFor().catch(() => { });
/**
* @todo This is a workaround for the fact that the editor canvas is seen as
* ready and visible before the loading spinner is hidden. Ideally, the
* content underneath the loading overlay should be marked inert until the
* loading is done.
*/
await canvasLoader.waitFor({
state: 'hidden',
// Bigger timeout is needed for larger entities, like the Large Post
// HTML fixture that we load for performance tests, which often doesn't
// make it under the default timeout value.
timeout: 60_000,
});
if (!options.showWelcomeGuide) {
await this.editor.setPreferences('core/edit-site', {
welcomeGuide: false,
welcomeGuideStyles: false,
welcomeGuidePage: false,
welcomeGuideTemplate: false,
});
}
}
exports.visitSiteEditor = visitSiteEditor;
//# sourceMappingURL=visit-site-editor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"visit-site-editor.js","sourceRoot":"","sources":["../../src/admin/visit-site-editor.ts"],"names":[],"mappings":";;;AAaA;;;;;GAKG;AACI,KAAK,UAAU,eAAe,CAEpC,UAA6B,EAAE;IAE/B,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IACnD,MAAM,KAAK,GAAG,IAAI,eAAe,EAAE,CAAC;IAEpC,IAAK,MAAM,EAAG,CAAC;QACd,KAAK,CAAC,GAAG,CAAE,QAAQ,EAAE,MAAM,CAAE,MAAM,CAAE,CAAE,CAAC;IACzC,CAAC;IACD,IAAK,QAAQ,EAAG,CAAC;QAChB,KAAK,CAAC,GAAG,CAAE,UAAU,EAAE,QAAQ,CAAE,CAAC;IACnC,CAAC;IACD,IAAK,IAAI,EAAG,CAAC;QACZ,KAAK,CAAC,GAAG,CAAE,MAAM,EAAE,IAAI,CAAE,CAAC;IAC3B,CAAC;IACD,IAAK,MAAM,EAAG,CAAC;QACd,KAAK,CAAC,GAAG,CAAE,QAAQ,EAAE,MAAM,CAAE,CAAC;IAC/B,CAAC;IAED,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO;IACrC,wEAAwE;IACxE,mBAAmB;IACnB,qDAAqD,CACrD,CAAC;IAEF,MAAM,IAAI,CAAC,cAAc,CAAE,iBAAiB,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAE,CAAC;IAEjE,yEAAyE;IACzE,8DAA8D;IAC9D,MAAM,YAAY,CAAC,OAAO,EAAE,CAAC,KAAK,CAAE,GAAG,EAAE,GAAE,CAAC,CAAE,CAAC;IAE/C;;;;;OAKG;IACH,MAAM,YAAY,CAAC,OAAO,CAAE;QAC3B,KAAK,EAAE,QAAQ;QACf,oEAAoE;QACpE,uEAAuE;QACvE,2CAA2C;QAC3C,OAAO,EAAE,MAAM;KACf,CAAE,CAAC;IAEJ,IAAK,CAAE,OAAO,CAAC,gBAAgB,EAAG,CAAC;QAClC,MAAM,IAAI,CAAC,MAAM,CAAC,cAAc,CAAE,gBAAgB,EAAE;YACnD,YAAY,EAAE,KAAK;YACnB,kBAAkB,EAAE,KAAK;YACzB,gBAAgB,EAAE,KAAK;YACvB,oBAAoB,EAAE,KAAK;SAC3B,CAAE,CAAC;IACL,CAAC;AACF,CAAC;AAtDD,0CAsDC"}

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WP_BASE_URL = exports.WP_PASSWORD = exports.WP_USERNAME = exports.WP_ADMIN_USER = void 0;
const { WP_USERNAME = 'admin', WP_PASSWORD = 'password', WP_BASE_URL = 'http://localhost:8889', } = process.env;
exports.WP_USERNAME = WP_USERNAME;
exports.WP_PASSWORD = WP_PASSWORD;
exports.WP_BASE_URL = WP_BASE_URL;
const WP_ADMIN_USER = {
username: WP_USERNAME,
password: WP_PASSWORD,
};
exports.WP_ADMIN_USER = WP_ADMIN_USER;
//# sourceMappingURL=config.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":";;;AAAA,MAAM,EACL,WAAW,GAAG,OAAO,EACrB,WAAW,GAAG,UAAU,EACxB,WAAW,GAAG,uBAAuB,GACrC,GAAG,OAAO,CAAC,GAAG,CAAC;AAOQ,kCAAW;AAAE,kCAAW;AAAE,kCAAW;AAL7D,MAAM,aAAa,GAAG;IACrB,QAAQ,EAAE,WAAW;IACrB,QAAQ,EAAE,WAAW;CACZ,CAAC;AAEF,sCAAa"}

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clickBlockOptionsMenuItem = void 0;
/**
* Clicks a block toolbar button.
*
* @param this
* @param label The text string of the button label.
*/
async function clickBlockOptionsMenuItem(label) {
await this.clickBlockToolbarButton('Options');
await this.page
.getByRole('menu', { name: 'Options' })
.getByRole('menuitem', { name: label })
.click();
}
exports.clickBlockOptionsMenuItem = clickBlockOptionsMenuItem;
//# sourceMappingURL=click-block-options-menu-item.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"click-block-options-menu-item.js","sourceRoot":"","sources":["../../src/editor/click-block-options-menu-item.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,yBAAyB,CAAgB,KAAa;IAC3E,MAAM,IAAI,CAAC,uBAAuB,CAAE,SAAS,CAAE,CAAC;IAChD,MAAM,IAAI,CAAC,IAAI;SACb,SAAS,CAAE,MAAM,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAE;SACxC,SAAS,CAAE,UAAU,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAE;SACxC,KAAK,EAAE,CAAC;AACX,CAAC;AAND,8DAMC"}

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clickBlockToolbarButton = void 0;
/**
* Clicks a block toolbar button.
*
* @param this
* @param label The text string of the button label.
*/
async function clickBlockToolbarButton(label) {
await this.showBlockToolbar();
const blockToolbar = this.page.locator('role=toolbar[name="Block tools"i]');
const button = blockToolbar.locator(`role=button[name="${label}"]`);
await button.click();
}
exports.clickBlockToolbarButton = clickBlockToolbarButton;
//# sourceMappingURL=click-block-toolbar-button.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"click-block-toolbar-button.js","sourceRoot":"","sources":["../../src/editor/click-block-toolbar-button.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,uBAAuB,CAAgB,KAAa;IACzE,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;IAE9B,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CACrC,mCAAmC,CACnC,CAAC;IACF,MAAM,MAAM,GAAG,YAAY,CAAC,OAAO,CAAE,qBAAsB,KAAM,IAAI,CAAE,CAAC;IAExE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;AACtB,CAAC;AATD,0DASC"}

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBlocks = void 0;
/**
* Returns the edited blocks.
*
* @param this
* @param options
* @param options.clientId Limit the results to be only under a partial tree of the specified clientId.
* @param options.full Whether to return the full block data or just the name and attributes.
*
* @return The blocks.
*/
async function getBlocks({ clientId, full = false } = {}) {
await this.page.waitForFunction(() => window?.wp?.blocks && window?.wp?.data);
return await this.page.evaluate(([_full, _clientId]) => {
// Serialize serializable attributes of blocks.
function serializeAttributes(attributes) {
return Object.fromEntries(Object.entries(attributes).map(([key, value]) => {
// Serialize RichTextData to string.
if (value instanceof window.wp.richText.RichTextData) {
return [key, value.toString()];
}
return [key, value];
}));
}
// Remove other unpredictable properties like clientId from blocks for testing purposes.
function recursivelyTransformBlocks(blocks) {
return blocks.map((block) => ({
name: block.name,
attributes: serializeAttributes(block.attributes),
innerBlocks: recursivelyTransformBlocks(block.innerBlocks),
}));
}
const blocks = window.wp.data
.select('core/block-editor')
.getBlocks(_clientId);
// The editor might still contain an unmodified empty block even when it's technically "empty".
if (blocks.length === 1 &&
window.wp.blocks.isUnmodifiedDefaultBlock(blocks[0])) {
return [];
}
return _full ? blocks : recursivelyTransformBlocks(blocks);
}, [full, clientId]);
}
exports.getBlocks = getBlocks;
//# sourceMappingURL=get-blocks.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"get-blocks.js","sourceRoot":"","sources":["../../src/editor/get-bl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SAAS,CAAE,SAAS,CAAa,CAAC;QAEpC,+FAA+F;QAC/F,IACC,MAAM,CAAC,MAAM,KAAK,CAAC;YACnB,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,wBAAwB,CAAE,MAAM,CAAE,CAAC,CAAE,CAAE,EACvD,CAAC;YACF,OAAO,EAAE,CAAC;QACX,CAAC;QAED,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,0BAA0B,CAAE,MAAM,CAAE,CAAC;IAC9D,CAAC,EACD,CAAE,IAAI,EAAE,QAAQ,CAAE,CAClB,CAAC;AACH,CAAC;AAtDD,8BAsDC"}

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEditedPostContent = void 0;
/**
* Returns a promise which resolves with the edited post content (HTML string).
*
* @param this
*
* @return Promise resolving with post content markup.
*/
async function getEditedPostContent() {
await this.page.waitForFunction(() => window?.wp?.data);
return await this.page.evaluate(() => window.wp.data.select('core/editor').getEditedPostContent());
}
exports.getEditedPostContent = getEditedPostContent;
//# sourceMappingURL=get-edited-post-content.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"get-edited-post-content.js","sourceRoot":"","sources":["../../src/editor/get-edited-post-content.ts"],"names":[],"mappings":";;;AAKA;;;;;;GAMG;AACI,KAAK,UAAU,oBAAoB;IACzC,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAAE,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,EAAE,IAAI,CAAE,CAAC;IAE1D,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAE,GAAG,EAAE,CACrC,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAE,aAAa,CAAE,CAAC,oBAAoB,EAAE,CAC7D,CAAC;AACH,CAAC;AAND,oDAMC"}

View File

@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Editor = void 0;
/**
* Internal dependencies
*/
const click_block_options_menu_item_1 = require("./click-block-options-menu-item");
const click_block_toolbar_button_1 = require("./click-block-toolbar-button");
const get_blocks_1 = require("./get-blocks");
const get_edited_post_content_1 = require("./get-edited-post-content");
const insert_block_1 = require("./insert-block");
const open_document_settings_sidebar_1 = require("./open-document-settings-sidebar");
const preview_1 = require("./preview");
const publish_post_1 = require("./publish-post");
const save_draft_1 = require("./save-draft");
const select_blocks_1 = require("./select-blocks");
const set_content_1 = require("./set-content");
const set_preferences_1 = require("./set-preferences");
const show_block_toolbar_1 = require("./show-block-toolbar");
const site_editor_1 = require("./site-editor");
const set_is_fixed_toolbar_1 = require("./set-is-fixed-toolbar");
const switch_to_legacy_canvas_1 = require("./switch-to-legacy-canvas");
const transform_block_to_1 = require("./transform-block-to");
class Editor {
browser;
page;
context;
constructor({ page }) {
this.page = page;
this.context = page.context();
this.browser = this.context.browser();
}
get canvas() {
return this.page.frameLocator('[name="editor-canvas"]');
}
/** @borrows clickBlockOptionsMenuItem as this.clickBlockOptionsMenuItem */
clickBlockOptionsMenuItem = click_block_options_menu_item_1.clickBlockOptionsMenuItem.bind(this);
/** @borrows clickBlockToolbarButton as this.clickBlockToolbarButton */
clickBlockToolbarButton = click_block_toolbar_button_1.clickBlockToolbarButton.bind(this);
/** @borrows getBlocks as this.getBlocks */
getBlocks = get_blocks_1.getBlocks.bind(this);
/** @borrows getEditedPostContent as this.getEditedPostContent */
getEditedPostContent = get_edited_post_content_1.getEditedPostContent.bind(this);
/** @borrows insertBlock as this.insertBlock */
insertBlock = insert_block_1.insertBlock.bind(this);
/** @borrows openDocumentSettingsSidebar as this.openDocumentSettingsSidebar */
openDocumentSettingsSidebar = open_document_settings_sidebar_1.openDocumentSettingsSidebar.bind(this);
/** @borrows openPreviewPage as this.openPreviewPage */
openPreviewPage = preview_1.openPreviewPage.bind(this);
/** @borrows publishPost as this.publishPost */
publishPost = publish_post_1.publishPost.bind(this);
/** @borrows saveDraft as this.saveDraft */
saveDraft = save_draft_1.saveDraft.bind(this);
/** @borrows saveSiteEditorEntities as this.saveSiteEditorEntities */
saveSiteEditorEntities = site_editor_1.saveSiteEditorEntities.bind(this);
/** @borrows selectBlocks as this.selectBlocks */
selectBlocks = select_blocks_1.selectBlocks.bind(this);
/** @borrows setContent as this.setContent */
setContent = set_content_1.setContent.bind(this);
/** @borrows setPreferences as this.setPreferences */
setPreferences = set_preferences_1.setPreferences.bind(this);
/** @borrows showBlockToolbar as this.showBlockToolbar */
showBlockToolbar = show_block_toolbar_1.showBlockToolbar.bind(this);
/** @borrows setIsFixedToolbar as this.setIsFixedToolbar */
setIsFixedToolbar = set_is_fixed_toolbar_1.setIsFixedToolbar.bind(this);
/** @borrows switchToLegacyCanvas as this.switchToLegacyCanvas */
switchToLegacyCanvas = switch_to_legacy_canvas_1.switchToLegacyCanvas.bind(this);
/** @borrows transformBlockTo as this.transformBlockTo */
transformBlockTo = transform_block_to_1.transformBlockTo.bind(this);
}
exports.Editor = Editor;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/editor/index.ts"],"names":[],"mappings":";;;AAUA;;GAEG;AACH,mFAA4E;AAC5E,6EAAuE;AACvE,6CAAyC;AACzC,uEAAiE;AACjE,iDAA6C;AAC7C,qFAA+E;AAC/E,uCAA4C;AAC5C,iDAA6C;AAC7C,6CAAyC;AACzC,mDAA+C;AAC/C,+CAA2C;AAC3C,uDAAmD;AACnD,6DAAwD;AACxD,+CAAuD;AACvD,iEAA2D;AAC3D,uEAAiE;AACjE,6DAAwD;AAMxD,MAAa,MAAM;IAClB,OAAO,CAAU;IACjB,IAAI,CAAO;IACX,OAAO,CAAiB;IAExB,YAAa,EAAE,IAAI,EAA0B;QAC5C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC9B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,O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;IAC1E,2DAA2D;IAC3D,iBAAiB,GAChB,wCAAiB,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAChC,iEAAiE;IACjE,oBAAoB,GACnB,8CAAoB,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACnC,yDAAyD;IACzD,gBAAgB,GAA4B,qCAAgB,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;CAC1E;AAxDD,wBAwDC"}

View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertBlock = void 0;
/**
* Insert a block.
*
* @param this
* @param blockRepresentation Inserted block representation.
* @param options
* @param options.clientId Client ID of the parent block to insert into.
*/
async function insertBlock(blockRepresentation, { clientId } = {}) {
await this.page.waitForFunction(() => window?.wp?.blocks && window?.wp?.data);
await this.page.evaluate(([_blockRepresentation, _clientId]) => {
function recursiveCreateBlock({ name, attributes = {}, innerBlocks = [], }) {
return window.wp.blocks.createBlock(name, attributes, innerBlocks.map((innerBlock) => recursiveCreateBlock(innerBlock)));
}
const block = recursiveCreateBlock(_blockRepresentation);
window.wp.data
.dispatch('core/block-editor')
.insertBlock(block, undefined, _clientId);
}, [blockRepresentation, clientId]);
}
exports.insertBlock = insertBlock;
//# sourceMappingURL=insert-block.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"insert-block.js","sourceRoot":"","sources":["../../src/editor/insert-block.ts"],"names":[],"mappings":";;;AAWA;;;;;;;GAOG;AACH,KAAK,UAAU,WAAW,CAEzB,mBAAwC,EACxC,EAAE,QAAQ,KAA4B,EAAE;IAExC,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAC9B,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,IAAI,MAAM,EAAE,EAAE,EAAE,IAAI,CAC5C,CAAC;IAEF,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CACvB,CAAE,CAAE,oBAAoB,EAAE,SAAS,CAAE,EAAG,EAAE;QACzC,SAAS,oBAAoB,CAAE,EAC9B,IAAI,EACJ,UAAU,GAAG,EAAE,EACf,WAAW,GAAG,EAAE,GACK;YACrB,OAAO,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,WAAW,CAClC,IAAI,EACJ,UAAU,EACV,WAAW,CAAC,GAAG,CAAE,CAAE,UAAU,EAAG,EAAE,CACjC,oBAAoB,CAAE,UAAU,CAAE,CAClC,CACD,CAAC;QACH,CAAC;QACD,MAAM,KAAK,GAAG,oBAAoB,CAAE,oBAAoB,CAAE,CAAC;QAE3D,MAAM,CAAC,EAAE,CAAC,IAAI;aACZ,QAAQ,CAAE,mBAAmB,CAAE;aAC/B,WAAW,CAAE,KAAK,EAAE,SAAS,EAAE,SAAS,CAAE,CAAC;IAC9C,CAAC,EACD,CAAE,mBAAmB,EAAE,QAAQ,CAAW,CAC1C,CAAC;AACH,CAAC;AAGQ,kCAAW"}

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.openDocumentSettingsSidebar = void 0;
/**
* Clicks on the button in the header which opens Document Settings sidebar when
* it is closed.
*
* @param this
*/
async function openDocumentSettingsSidebar() {
const toggleButton = this.page
.getByRole('region', { name: 'Editor top bar' })
.getByRole('button', {
name: 'Settings',
disabled: false,
});
const isClosed = (await toggleButton.getAttribute('aria-expanded')) === 'false';
if (isClosed) {
await toggleButton.click();
await this.page
.getByRole('region', { name: 'Editor settings' })
.getByRole('button', { name: 'Close Settings' })
.waitFor();
}
}
exports.openDocumentSettingsSidebar = openDocumentSettingsSidebar;
//# sourceMappingURL=open-document-settings-sidebar.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"open-document-settings-sidebar.js","sourceRoot":"","sources":["../../src/editor/open-document-settings-sidebar.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,2BAA2B;IAChD,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI;SAC5B,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAE;SACjD,SAAS,CAAE,QAAQ,EAAE;QACrB,IAAI,EAAE,UAAU;QAChB,QAAQ,EAAE,KAAK;KACf,CAAE,CAAC;IAEL,MAAM,QAAQ,GACb,CAAE,MAAM,YAAY,CAAC,YAAY,CAAE,eAAe,CAAE,CAAE,KAAK,OAAO,CAAC;IAEpE,IAAK,QAAQ,EAAG,CAAC;QAChB,MAAM,YAAY,CAAC,KAAK,EAAE,CAAC;QAC3B,MAAM,IAAI,CAAC,IAAI;aACb,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAE;aAClD,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAE;aACjD,OAAO,EAAE,CAAC;IACb,CAAC;AACF,CAAC;AAlBD,kEAkBC"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.openPreviewPage = void 0;
/**
* Opens the preview page of an edited post.
*
* @param this
*
* @return preview page.
*/
async function openPreviewPage() {
const editorTopBar = this.page.locator('role=region[name="Editor top bar"i]');
const previewButton = editorTopBar.locator('role=button[name="View"i]');
await previewButton.click();
const [previewPage] = await Promise.all([
this.context.waitForEvent('page'),
this.page.click('role=menuitem[name="Preview in new tab"i]'),
]);
return previewPage;
}
exports.openPreviewPage = openPreviewPage;
//# sourceMappingURL=preview.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"preview.js","sourceRoot":"","sources":["../../src/editor/preview.ts"],"names":[],"mappings":";;;AAUA;;;;;;GAMG;AACI,KAAK,UAAU,eAAe;IACpC,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CACrC,qCAAqC,CACrC,CAAC;IACF,MAAM,aAAa,GAAG,YAAY,CAAC,OAAO,CAAE,2BAA2B,CAAE,CAAC;IAE1E,MAAM,aAAa,CAAC,KAAK,EAAE,CAAC;IAE5B,MAAM,CAAE,WAAW,CAAE,GAAG,MAAM,OAAO,CAAC,GAAG,CAAE;QAC1C,IAAI,CAAC,OAAO,CAAC,YAAY,CAAE,MAAM,CAAE;QACnC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAE,2CAA2C,CAAE;KAC9D,CAAE,CAAC;IAEJ,OAAO,WAAW,CAAC;AACpB,CAAC;AAdD,0CAcC"}

View File

@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.publishPost = void 0;
/**
* Publishes the post, resolving once the request is complete (once a notice
* is displayed).
*
* @param this
*/
async function publishPost() {
// If we have changes in other entities, the label is `Save` instead of `Publish`.
const saveButton = this.page
.getByRole('region', { name: 'Editor top bar' })
.getByRole('button', { name: 'Save', exact: true });
const publishButton = this.page
.getByRole('region', { name: 'Editor top bar' })
.getByRole('button', { name: 'Publish', exact: true });
const buttonToClick = (await saveButton.isVisible())
? saveButton
: publishButton;
await buttonToClick.click();
const entitiesSaveButton = this.page
.getByRole('region', { name: 'Editor publish' })
.getByRole('button', { name: 'Save', exact: true });
const isEntitiesSavePanelVisible = await entitiesSaveButton.isVisible();
// Save any entities.
if (isEntitiesSavePanelVisible) {
// Handle saving entities.
await entitiesSaveButton.click();
}
// Handle saving just the post.
await this.page.click('role=region[name="Editor publish"i] >> role=button[name="Publish"i]');
await this.page
.getByRole('button', { name: 'Dismiss this notice' })
.filter({ hasText: 'published' })
.waitFor();
const postId = new URL(this.page.url()).searchParams.get('post');
return typeof postId === 'string' ? parseInt(postId, 10) : null;
}
exports.publishPost = publishPost;
//# sourceMappingURL=publish-post.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"publish-post.js","sourceRoot":"","sources":["../../src/editor/publish-post.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,WAAW;IAChC,kFAAkF;IAClF,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI;SAC1B,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAE;SAC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G,CAAE,MAAM,CAAE,CAAC;IAErE,OAAO,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAE,MAAM,EAAE,EAAE,CAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACnE,CAAC;AApCD,kCAoCC"}

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveDraft = void 0;
/**
* Saves the post as a draft, resolving once the request is complete (once a notice
* is displayed).
*/
async function saveDraft() {
await this.page
.getByRole('region', { name: 'Editor top bar' })
.getByRole('button', { name: 'Save draft' })
.click();
await this.page
.getByRole('button', { name: 'Dismiss this notice' })
.filter({ hasText: 'Draft saved' })
.waitFor();
}
exports.saveDraft = saveDraft;
//# sourceMappingURL=save-draft.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"save-draft.js","sourceRoot":"","sources":["../../src/editor/save-draft.ts"],"names":[],"mappings":";;;AAKA;;;GAGG;AACI,KAAK,UAAU,SAAS;IAC9B,MAAM,IAAI,CAAC,IAAI;SACb,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAE;SACjD,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,CAAE;SAC7C,KAAK,EAAE,CAAC;IAEV,MAAM,IAAI,CAAC,IAAI;SACb,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,qBAAqB,EAAE,CAAE;SACtD,MAAM,CAAE,EAAE,OAAO,EAAE,aAAa,EAAE,CAAE;SACpC,OAAO,EAAE,CAAC;AACb,CAAC;AAVD,8BAUC"}

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.selectBlocks = void 0;
async function selectBlocks(startSelectorOrLocator, endSelectorOrLocator) {
const startBlock = typeof startSelectorOrLocator === 'string'
? this.canvas.locator(startSelectorOrLocator)
: startSelectorOrLocator;
const endBlock = typeof endSelectorOrLocator === 'string'
? this.canvas.locator(endSelectorOrLocator)
: endSelectorOrLocator;
const startClientId = await startBlock.getAttribute('data-block');
const endClientId = await endBlock?.getAttribute('data-block');
if (endClientId) {
await this.page.evaluate(([startId, endId]) => {
// @ts-ignore
wp.data
.dispatch('core/block-editor')
.multiSelect(startId, endId);
}, [startClientId, endClientId]);
}
else {
await this.page.evaluate(([clientId]) => {
// @ts-ignore
wp.data.dispatch('core/block-editor').selectBlock(clientId);
}, [startClientId]);
}
}
exports.selectBlocks = selectBlocks;
//# sourceMappingURL=select-blocks.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"select-blocks.js","sourceRoot":"","sources":["../../src/editor/select-blocks.ts"],"names":[],"mappings":";;;AAUO,KAAK,UAAU,YAAY,CAEjC,sBAAwC,EACxC,oBAAuC;IAEvC,MAAM,UAAU,GACf,OAAO,sBAAsB,KAAK,QAAQ;QACzC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAE,sBAAsB,CAAE;QAC/C,CAAC,CAAC,sBAAsB,CAAC;IAE3B,MAAM,QAAQ,GACb,OAAO,oBAAoB,KAAK,QAAQ;QACvC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAE,oBAAoB,CAAE;QAC7C,CAAC,CAAC,oBAAoB,CAAC;IAEzB,MAAM,aAAa,GAAG,MAAM,UAAU,CAAC,YAAY,CAAE,YAAY,CAAE,CAAC;IACpE,MAAM,WAAW,GAAG,MAAM,QAAQ,EAAE,YAAY,CAAE,YAAY,CAAE,CAAC;IAEjE,IAAK,WAAW,EAAG,CAAC;QACnB,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CACvB,CAAE,CAAE,OAAO,EAAE,KAAK,CAAE,EAAG,EAAE;YACxB,aAAa;YACb,EAAE,CAAC,IAAI;iBACL,QAAQ,CAAE,mBAAmB,CAAE;iBAC/B,WAAW,CAAE,OAAO,EAAE,KAAK,CAAE,CAAC;QACjC,CAAC,EACD,CAAE,aAAa,EAAE,WAAW,CAAE,CAC9B,CAAC;IACH,CAAC;SAAM,CAAC;QACP,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CACvB,CAAE,CAAE,QAAQ,CAAE,EAAG,EAAE;YAClB,aAAa;YACb,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAE,mBAAmB,CAAE,CAAC,WAAW,CAAE,QAAQ,CAAE,CAAC;QACjE,CAAC,EACD,CAAE,aAAa,CAAE,CACjB,CAAC;IACH,CAAC;AACF,CAAC;AArCD,oCAqCC"}

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setContent = void 0;
/**
* Set the content of the editor.
*
* @param this
* @param html Serialized block HTML.
*/
async function setContent(html) {
await this.page.waitForFunction(() => window?.wp?.blocks && window?.wp?.data);
await this.page.evaluate((_html) => {
const blocks = window.wp.blocks.parse(_html);
window.wp.data.dispatch('core/block-editor').resetBlocks(blocks);
}, html);
}
exports.setContent = setContent;
//# sourceMappingURL=set-content.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"set-content.js","sourceRoot":"","sources":["../../src/editor/set-content.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACH,KAAK,UAAU,UAAU,CAAgB,IAAY;IACpD,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAC9B,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,IAAI,MAAM,EAAE,EAAE,EAAE,IAAI,CAC5C,CAAC;IAEF,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAE,CAAE,KAAK,EAAG,EAAE;QACrC,MAAM,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAE,KAAK,CAAE,CAAC;QAE/C,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAE,mBAAmB,CAAE,CAAC,WAAW,CAAE,MAAM,CAAE,CAAC;IACtE,CAAC,EAAE,IAAI,CAAE,CAAC;AACX,CAAC;AAEQ,gCAAU"}

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setIsFixedToolbar = void 0;
/**
* Toggles the fixed toolbar option.
*
* @param this
* @param isFixed Boolean value true/false for on/off.
*/
async function setIsFixedToolbar(isFixed) {
await this.page.waitForFunction(() => window?.wp?.data);
await this.page.evaluate((_isFixed) => {
window.wp.data
.dispatch('core/preferences')
.set('core', 'fixedToolbar', _isFixed);
}, isFixed);
}
exports.setIsFixedToolbar = setIsFixedToolbar;
//# sourceMappingURL=set-is-fixed-toolbar.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"set-is-fixed-toolbar.js","sourceRoot":"","sources":["../../src/editor/set-is-fixed-toolbar.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,iBAAiB,CAAgB,OAAgB;IACtE,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAAE,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,EAAE,IAAI,CAAE,CAAC;IAE1D,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAE,CAAE,QAAQ,EAAG,EAAE;QACxC,MAAM,CAAC,EAAE,CAAC,IAAI;aACZ,QAAQ,CAAE,kBAAkB,CAAE;aAC9B,GAAG,CAAE,MAAM,EAAE,cAAc,EAAE,QAAQ,CAAE,CAAC;IAC3C,CAAC,EAAE,OAAO,CAAE,CAAC;AACd,CAAC;AARD,8CAQC"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setPreferences = void 0;
/**
* Set the preferences of the editor.
*
* @param this
* @param context Context to set preferences for.
* @param preferences Preferences to set.
*/
async function setPreferences(context, preferences) {
await this.page.waitForFunction(() => window?.wp?.data);
await this.page.evaluate(async (props) => {
for (const [key, value] of Object.entries(props.preferences)) {
await window.wp.data
.dispatch('core/preferences')
.set(props.context, key, value);
}
}, { context, preferences });
}
exports.setPreferences = setPreferences;
//# sourceMappingURL=set-preferences.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"set-preferences.js","sourceRoot":"","sources":["../../src/editor/set-preferences.ts"],"names":[],"mappings":";;;AAUA;;;;;;GAMG;AACI,KAAK,UAAU,cAAc,CAEnC,OAA2B,EAC3B,WAAkC;IAElC,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAAE,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,EAAE,IAAI,CAAE,CAAC;IAE1D,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CACvB,KAAK,EAAG,KAAK,EAAG,EAAE;QACjB,KAAM,MAAM,CAAE,GAAG,EAAE,KAAK,CAAE,IAAI,MAAM,CAAC,OAAO,CAC3C,KAAK,CAAC,WAAW,CACjB,EAAG,CAAC;YACJ,MAAM,MAAM,CAAC,EAAE,CAAC,IAAI;iBAClB,QAAQ,CAAE,kBAAkB,CAAE;iBAC9B,GAAG,CAAE,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK,CAAE,CAAC;QACpC,CAAC;IACF,CAAC,EACD,EAAE,OAAO,EAAE,WAAW,EAAE,CACxB,CAAC;AACH,CAAC;AAnBD,wCAmBC"}

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.showBlockToolbar = void 0;
/**
* The block toolbar is not always visible while typing.
* Call this function to reveal it.
*
* @param this
*/
async function showBlockToolbar() {
// Move the mouse to disable the isTyping mode. We need at least three
// mousemove events for it to work across windows (iframe). With three
// moves, it's a guarantee that at least two will be in the same window.
// Two events are required for the flag to be unset.
await this.page.mouse.move(50, 50);
await this.page.mouse.move(75, 75);
await this.page.mouse.move(100, 100);
}
exports.showBlockToolbar = showBlockToolbar;
//# sourceMappingURL=show-block-toolbar.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"show-block-toolbar.js","sourceRoot":"","sources":["../../src/editor/show-block-toolbar.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,gBAAgB;IACrC,sEAAsE;IACtE,sEAAsE;IACtE,wEAAwE;IACxE,oDAAoD;IACpD,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAE,EAAE,EAAE,EAAE,CAAE,CAAC;IACrC,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAE,EAAE,EAAE,EAAE,CAAE,CAAC;IACrC,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAE,GAAG,EAAE,GAAG,CAAE,CAAC;AACxC,CAAC;AARD,4CAQC"}

View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveSiteEditorEntities = void 0;
/**
* Save entities in the site editor. Assumes the editor is in a dirty state.
*
* @param this
* @param options
*/
async function saveSiteEditorEntities(options = {}) {
const editorTopBar = this.page.getByRole('region', {
name: 'Editor top bar',
});
// If we have changes in a single entity which can be published the label is `Publish`.
const saveButton = editorTopBar.getByRole('button', {
name: 'Save',
exact: true,
});
const publishButton = editorTopBar.getByRole('button', {
name: 'Publish',
});
const publishButtonIsVisible = !(await saveButton.isVisible());
// First Save button in the top bar.
const buttonToClick = publishButtonIsVisible ? publishButton : saveButton;
await buttonToClick.click();
if (!options.isOnlyCurrentEntityDirty) {
// Second Save button in the entities panel.
await this.page
.getByRole('region', {
name: /(Editor publish|Save panel)/,
})
.getByRole('button', { name: 'Save', exact: true })
.click();
}
// The text in the notice can be different based on the edited entity, whether
// we are saving multiple entities and whether we publish or update. So for now,
// we locate it based on the last part.
await this.page
.getByRole('button', { name: 'Dismiss this notice' })
.getByText(/(updated|published)\./)
.waitFor();
}
exports.saveSiteEditorEntities = saveSiteEditorEntities;
//# sourceMappingURL=site-editor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"site-editor.js","sourceRoot":"","sources":["../../src/editor/site-editor.ts"],"names":[],"mappings":";;;AAUA;;;;;GAKG;AACI,KAAK,UAAU,sBAAsB,CAE3C,UAAmB,EAAE;IAErB,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,CAAE,QAAQ,EAAE;QACnD,IAAI,EAAE,gBAAgB;KACtB,CAAE,CAAC;IAEJ,uFAAuF;IACvF,MAAM,UAAU,GAAG,YAAY,CAAC,SAAS,CAAE,QAAQ,EAAE;QACpD,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,IAAI;KACX,CAAE,CAAC;IACJ,MAAM,aAAa,GAAG,YAAY,CAAC,SAAS,CAAE,QAAQ,EAAE;QACvD,IAAI,EAAE,SAAS;KACf,CAAE,CAAC;IACJ,MAAM,sBAAsB,GAAG,CAAE,CAAE,MAAM,UAAU,CAAC,SAAS,EAAE,CAAE,CAAC;IAClE,oCAAoC;IACpC,MAAM,aAAa,GAAG,sBAAsB,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,UAAU,CAAC;IAC1E,MAAM,aAAa,CAAC,KAAK,EAAE,CAAC;IAE5B,IAAK,CAAE,OAAO,CAAC,wBAAwB,EAAG,CAAC;QAC1C,4CAA4C;QAC5C,MAAM,IAAI,CAAC,IAAI;aACb,SAAS,CAAE,QAAQ,EAAE;YACrB,IAAI,EAAE,6BAA6B;SACnC,CAAE;aACF,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,CAAE;aACpD,KAAK,EAAE,CAAC;IACX,CAAC;IACD,8EAA8E;IAC9E,gFAAgF;IAChF,uCAAuC;IACvC,MAAM,IAAI,CAAC,IAAI;SACb,SAAS,CAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,qBAAqB,EAAE,CAAE;SACtD,SAAS,CAAE,uBAAuB,CAAE;SACpC,OAAO,EAAE,CAAC;AACb,CAAC;AArCD,wDAqCC"}

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.switchToLegacyCanvas = void 0;
/**
* Switches to legacy (non-iframed) canvas.
*
* @param this
*/
async function switchToLegacyCanvas() {
await this.page.waitForFunction(() => window?.wp?.blocks);
await this.page.evaluate(() => {
window.wp.blocks.registerBlockType('test/v2', {
apiVersion: '2',
title: 'test',
});
});
}
exports.switchToLegacyCanvas = switchToLegacyCanvas;
//# sourceMappingURL=switch-to-legacy-canvas.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"switch-to-legacy-canvas.js","sourceRoot":"","sources":["../../src/editor/switch-to-legacy-canvas.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACI,KAAK,UAAU,oBAAoB;IACzC,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAAE,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,CAAE,CAAC;IAE5D,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAE,GAAG,EAAE;QAC9B,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,iBAAiB,CAAE,SAAS,EAAE;YAC9C,UAAU,EAAE,GAAG;YACf,KAAK,EAAE,MAAM;SACb,CAAE,CAAC;IACL,CAAC,CAAE,CAAC;AACL,CAAC;AATD,oDASC"}

View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformBlockTo = void 0;
/**
* Clicks the default block appender.
*
* @param this
* @param name Block name.
*/
async function transformBlockTo(name) {
await this.page.waitForFunction(() => window?.wp?.blocks && window?.wp?.data);
await this.page.evaluate(([blockName]) => {
const clientIds = window.wp.data
.select('core/block-editor')
.getSelectedBlockClientIds();
const blocks = window.wp.data
.select('core/block-editor')
.getBlocksByClientId(clientIds);
window.wp.data
.dispatch('core/block-editor')
.replaceBlocks(clientIds, window.wp.blocks.switchToBlockType(blocks, blockName));
}, [name]);
}
exports.transformBlockTo = transformBlockTo;
//# sourceMappingURL=transform-block-to.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"transform-block-to.js","sourceRoot":"","sources":["../../src/editor/transform-block-to.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,gBAAgB,CAAgB,IAAY;IACjE,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAC9B,GAAG,EAAE,CAAC,MAAM,EAAE,EAAE,EAAE,MAAM,IAAI,MAAM,EAAE,EAAE,EAAE,IAAI,CAC5C,CAAC;IAEF,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,CACvB,CAAE,CAAE,SAAS,CAAE,EAAG,EAAE;QACnB,MAAM,SAAS,GAAG,MAAM,CAAC,EAAE,CAAC,IAAI;aAC9B,MAAM,CAAE,mBAAmB,CAAE;aAC7B,yBAAyB,EAAE,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC,IAAI;aAC3B,MAAM,CAAE,mBAAmB,CAAE;aAC7B,mBAAmB,CAAE,SAAS,CAAE,CAAC;QACnC,MAAM,CAAC,EAAE,CAAC,IAAI;aACZ,QAAQ,CAAE,mBAAmB,CAAE;aAC/B,aAAa,CACb,SAAS,EACT,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,iBAAiB,CAAE,MAAM,EAAE,SAAS,CAAE,CACvD,CAAC;IACJ,CAAC,EACD,CAAE,IAAI,CAAE,CACR,CAAC;AACH,CAAC;AAtBD,4CAsBC"}

View File

@@ -0,0 +1,34 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.expect = exports.test = exports.Lighthouse = exports.Metrics = exports.RequestUtils = exports.PageUtils = exports.Editor = exports.Admin = void 0;
__exportStar(require("./types"), exports);
var admin_1 = require("./admin");
Object.defineProperty(exports, "Admin", { enumerable: true, get: function () { return admin_1.Admin; } });
var editor_1 = require("./editor");
Object.defineProperty(exports, "Editor", { enumerable: true, get: function () { return editor_1.Editor; } });
var page_utils_1 = require("./page-utils");
Object.defineProperty(exports, "PageUtils", { enumerable: true, get: function () { return page_utils_1.PageUtils; } });
var request_utils_1 = require("./request-utils");
Object.defineProperty(exports, "RequestUtils", { enumerable: true, get: function () { return request_utils_1.RequestUtils; } });
var metrics_1 = require("./metrics");
Object.defineProperty(exports, "Metrics", { enumerable: true, get: function () { return metrics_1.Metrics; } });
var lighthouse_1 = require("./lighthouse");
Object.defineProperty(exports, "Lighthouse", { enumerable: true, get: function () { return lighthouse_1.Lighthouse; } });
var test_1 = require("./test");
Object.defineProperty(exports, "test", { enumerable: true, get: function () { return test_1.test; } });
Object.defineProperty(exports, "expect", { enumerable: true, get: function () { return test_1.expect; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,0CAAwB;AACxB,iCAAgC;AAAvB,8FAAA,KAAK,OAAA;AACd,mCAAkC;AAAzB,gGAAA,MAAM,OAAA;AACf,2CAAyC;AAAhC,uGAAA,SAAS,OAAA;AAClB,iDAA+C;AAAtC,6GAAA,YAAY,OAAA;AACrB,qCAAoC;AAA3B,kGAAA,OAAO,OAAA;AAChB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AACnB,+BAAsC;AAA7B,4FAAA,IAAI,OAAA;AAAE,8FAAA,MAAM,OAAA"}

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lighthouse = void 0;
const lighthouse = require("lighthouse/core/index.cjs");
class Lighthouse {
page;
port;
constructor({ page, port }) {
this.page = page;
this.port = port;
}
/**
* Returns the Lighthouse report for the current URL.
*
* Runs several Lighthouse audits in a separate browser window and returns
* the summary.
*/
async getReport() {
// From https://github.com/GoogleChrome/lighthouse/blob/d149e9c1b628d5881ca9ca451278d99ff1b31d9a/core/config/default-config.js#L433-L503
const audits = {
'largest-contentful-paint': 'LCP',
'total-blocking-time': 'TBT',
interactive: 'TTI',
'cumulative-layout-shift': 'CLS',
'experimental-interaction-to-next-paint': 'INP',
};
const report = await lighthouse(this.page.url(), { port: this.port }, {
extends: 'lighthouse:default',
settings: {
// "provided" means no throttling.
// TODO: Make configurable.
throttlingMethod: 'provided',
// Default is "mobile".
// See https://github.com/GoogleChrome/lighthouse/blob/main/docs/emulation.md
// TODO: Make configurable.
formFactor: 'desktop',
screenEmulation: {
disabled: true,
},
// Speeds up the report.
disableFullPageScreenshot: true,
// Only run certain audits to speed things up.
onlyAudits: Object.keys(audits),
},
});
const result = {};
if (!report) {
return result;
}
const { lhr } = report;
for (const [audit, acronym] of Object.entries(audits)) {
result[acronym] = lhr.audits[audit]?.numericValue || 0;
}
return result;
}
}
exports.Lighthouse = Lighthouse;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/lighthouse/index.ts"],"names":[],"mappings":";;;AAIA,wDAAwD;AAOxD,MAAa,UAAU;IACtB,IAAI,CAAO;IACX,IAAI,CAAS;IAEb,YAAa,EAAE,IAAI,EAAE,IAAI,EAA8B;QACtD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,SAAS;QACd,wIAAwI;QACxI,MAAM,MAAM,GAAG;YACd,0BAA0B,EAAE,KAAK;YACjC,qBAAqB,EAAE,KAAK;YAC5B,WAAW,EAAE,KAAK;YAClB,yBAAyB,EAAE,KAAK;YAChC,wCAAwC,EAAE,KAAK;SAC/C,CAAC;QAEF,MAAM,MAAM,GAAG,MAAM,UAAU,CAC9B,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,EACf,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,EACnB;YACC,OAAO,EAAE,oBAAoB;YAC7B,QAAQ,EAAE;gBACT,kCAAkC;gBAClC,2BAA2B;gBAC3B,gBAAgB,EAAE,UAAU;gBAC5B,uBAAuB;gBACvB,6EAA6E;gBAC7E,2BAA2B;gBAC3B,UAAU,EAAE,SAAS;gBACrB,eAAe,EAAE;oBAChB,QAAQ,EAAE,IAAI;iBACd;gBACD,wBAAwB;gBACxB,yBAAyB,EAAE,IAAI;gBAC/B,8CAA8C;gBAC9C,UAAU,EAAE,MAAM,CAAC,IAAI,CAAE,MAAM,CAAE;aACjC;SACD,CACD,CAAC;QAEF,MAAM,MAAM,GAA6B,EAAE,CAAC;QAE5C,IAAK,CAAE,MAAM,EAAG,CAAC;YAChB,OAAO,MAAM,CAAC;QACf,CAAC;QAED,MAAM,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC;QAEvB,KAAM,MAAM,CAAE,KAAK,EAAE,OAAO,CAAE,IAAI,MAAM,CAAC,OAAO,CAAE,MAAM,CAAE,EAAG,CAAC;YAC7D,MAAM,CAAE,OAAO,CAAE,GAAG,GAAG,CAAC,MAAM,CAAE,KAAK,CAAE,EAAE,YAAY,IAAI,CAAC,CAAC;QAC5D,CAAC;QAED,OAAO,MAAM,CAAC;IACf,CAAC;CACD;AA/DD,gCA+DC"}

View File

@@ -0,0 +1,256 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Metrics = void 0;
const path_1 = require("path");
class Metrics {
browser;
page;
trace;
webVitals = {};
constructor({ page }) {
this.page = page;
this.browser = page.context().browser();
this.trace = { traceEvents: [] };
}
/**
* Returns durations from the Server-Timing header.
*
* @param fields Optional fields to filter.
*/
async getServerTiming(fields = []) {
return this.page.evaluate((f) => performance.getEntriesByType('navigation')[0].serverTiming.reduce((acc, entry) => {
if (f.length === 0 || f.includes(entry.name)) {
acc[entry.name] = entry.duration;
}
return acc;
}, {}), fields);
}
/**
* Returns time to first byte (TTFB) using the Navigation Timing API.
*
* @see https://web.dev/ttfb/#measure-ttfb-in-javascript
*
* @return TTFB value.
*/
async getTimeToFirstByte() {
return await this.page.evaluate(() => {
const { responseStart, startTime } = performance.getEntriesByType('navigation')[0];
return responseStart - startTime;
});
}
/**
* Returns the Largest Contentful Paint (LCP) value using the dedicated API.
*
* @see https://w3c.github.io/largest-contentful-paint/
* @see https://web.dev/lcp/#measure-lcp-in-javascript
*
* @return LCP value.
*/
async getLargestContentfulPaint() {
return await this.page.evaluate(() => new Promise((resolve) => {
new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
// The last entry is the largest contentful paint.
const largestPaintEntry = entries.at(-1);
resolve(largestPaintEntry?.startTime || 0);
}).observe({
type: 'largest-contentful-paint',
buffered: true,
});
}));
}
/**
* Returns the Cumulative Layout Shift (CLS) value using the dedicated API.
*
* @see https://github.com/WICG/layout-instability
* @see https://web.dev/cls/#measure-layout-shifts-in-javascript
*
* @return CLS value.
*/
async getCumulativeLayoutShift() {
return await this.page.evaluate(() => new Promise((resolve) => {
let CLS = 0;
new PerformanceObserver((l) => {
const entries = l.getEntries();
entries.forEach((entry) => {
if (!entry.hadRecentInput) {
CLS += entry.value;
}
});
resolve(CLS);
}).observe({
type: 'layout-shift',
buffered: true,
});
}));
}
/**
* Returns the loading durations using the Navigation Timing API. All the
* durations exclude the server response time.
*
* @return Object with loading metrics durations.
*/
async getLoadingDurations() {
return await this.page.evaluate(() => {
const [{ requestStart, responseStart, responseEnd, domContentLoadedEventEnd, loadEventEnd, },] = performance.getEntriesByType('navigation');
const paintTimings = performance.getEntriesByType('paint');
const firstPaintStartTime = paintTimings.find(({ name }) => name === 'first-paint').startTime;
const firstContentfulPaintStartTime = paintTimings.find(({ name }) => name === 'first-contentful-paint').startTime;
return {
// Server side metric.
serverResponse: responseStart - requestStart,
// For client side metrics, consider the end of the response (the
// browser receives the HTML) as the start time (0).
firstPaint: firstPaintStartTime - responseEnd,
domContentLoaded: domContentLoadedEventEnd - responseEnd,
loaded: loadEventEnd - responseEnd,
firstContentfulPaint: firstContentfulPaintStartTime - responseEnd,
timeSinceResponseEnd: performance.now() - responseEnd,
};
});
}
/**
* Starts Chromium tracing with predefined options for performance testing.
*
* @param options Options to pass to `browser.startTracing()`.
*/
async startTracing(options = {}) {
return await this.browser.startTracing(this.page, {
screenshots: false,
categories: ['devtools.timeline'],
...options,
});
}
/**
* Stops Chromium tracing and saves the trace.
*/
async stopTracing() {
const traceBuffer = await this.browser.stopTracing();
const traceJSON = JSON.parse(traceBuffer.toString());
this.trace = traceJSON;
}
/**
* @return Durations of all traced `keydown`, `keypress`, and `keyup`
* events.
*/
getTypingEventDurations() {
return [
this.getEventDurations('keydown'),
this.getEventDurations('keypress'),
this.getEventDurations('keyup'),
];
}
/**
* @return Durations of all traced `focus` and `focusin` events.
*/
getSelectionEventDurations() {
return [
this.getEventDurations('focus'),
this.getEventDurations('focusin'),
];
}
/**
* @return Durations of all traced `click` events.
*/
getClickEventDurations() {
return [this.getEventDurations('click')];
}
/**
* @return Durations of all traced `mouseover` and `mouseout` events.
*/
getHoverEventDurations() {
return [
this.getEventDurations('mouseover'),
this.getEventDurations('mouseout'),
];
}
/**
* @param eventType Type of event to filter.
* @return Durations of all events of a given type.
*/
getEventDurations(eventType) {
if (this.trace.traceEvents.length === 0) {
throw new Error('No trace events found. Did you forget to call stopTracing()?');
}
return this.trace.traceEvents
.filter((item) => item.cat === 'devtools.timeline' &&
item.name === 'EventDispatch' &&
item?.args?.data?.type === eventType &&
!!item.dur)
.map((item) => (item.dur ? item.dur / 1000 : 0));
}
/**
* Initializes the web-vitals library upon next page navigation.
*
* Defaults to automatically triggering the navigation,
* but it can also be done manually.
*
* @example
* ```js
* await metrics.initWebVitals();
* console.log( await metrics.getWebVitals() );
* ```
*
* @example
* ```js
* await metrics.initWebVitals( false );
* await page.goto( '/some-other-page' );
* console.log( await metrics.getWebVitals() );
* ```
*
* @param reload Whether to force navigation by reloading the current page.
*/
async initWebVitals(reload = true) {
await this.page.addInitScript({
path: (0, path_1.join)(__dirname, '../../../../node_modules/web-vitals/dist/web-vitals.umd.cjs'),
});
await this.page.exposeFunction('__reportVitals__', (data) => {
const measurement = JSON.parse(data);
this.webVitals[measurement.name] = measurement.value;
});
await this.page.addInitScript(() => {
const reportVitals = (measurement) => window.__reportVitals__(JSON.stringify(measurement));
window.addEventListener('DOMContentLoaded', () => {
// @ts-ignore
window.webVitals.onCLS(reportVitals);
// @ts-ignore
window.webVitals.onFCP(reportVitals);
// @ts-ignore
window.webVitals.onFID(reportVitals);
// @ts-ignore
window.webVitals.onINP(reportVitals);
// @ts-ignore
window.webVitals.onLCP(reportVitals);
// @ts-ignore
window.webVitals.onTTFB(reportVitals);
});
});
if (reload) {
// By reloading the page the script will be applied.
await this.page.reload();
}
}
/**
* Returns web vitals as collected by the web-vitals library.
*
* If the web-vitals library hasn't been loaded on the current page yet,
* it will be initialized with a page reload.
*
* Reloads the page to force web-vitals to report all collected metrics.
*
* @return {WebVitalsMeasurements} Web vitals measurements.
*/
async getWebVitals() {
// Reset values.
this.webVitals = {};
const hasScript = await this.page.evaluate(() => typeof window.webVitals !== 'undefined');
if (!hasScript) {
await this.initWebVitals();
}
// Trigger navigation so the web-vitals library reports values on unload.
await this.page.reload();
return this.webVitals;
}
}
exports.Metrics = Metrics;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,120 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dragFiles = void 0;
/**
* External dependencies
*/
const promises_1 = require("fs/promises");
const path_1 = require("path");
const mime_1 = require("mime");
/**
* Simulate dragging files from outside the current page.
*
* @param this
* @param files The files to be dragged.
* @return The methods of the drag operation.
*/
async function dragFiles(files) {
const filesList = Array.isArray(files) ? files : [files];
const fileObjects = await Promise.all(filesList.map(async (filePathOrObject) => {
if (typeof filePathOrObject !== 'string') {
return {
name: filePathOrObject.name,
mimeType: filePathOrObject.mimeType ||
(0, mime_1.getType)(filePathOrObject.name),
base64: filePathOrObject.buffer.toString('base64'),
};
}
const base64 = await (0, promises_1.readFile)(filePathOrObject, 'base64');
const name = (0, path_1.basename)(filePathOrObject);
return {
name,
mimeType: (0, mime_1.getType)(filePathOrObject),
base64,
};
}));
// CDP doesn't actually support dragging files, this is only a _good enough_
// dummy data so that it will correctly send the relevant events.
const dragData = {
items: fileObjects.map((fileObject) => ({
mimeType: fileObject.mimeType ?? 'File',
data: fileObject.base64,
})),
files: fileObjects.map((fileObject) => fileObject.name),
// Copy = 1, Link = 2, Move = 16.
dragOperationsMask: 1,
};
const cdpSession = await this.context.newCDPSession(this.page);
const position = {
x: 0,
y: 0,
};
return {
/**
* Drag the files over an element (fires `dragenter` and `dragover` events).
*
* @param selectorOrLocator A selector or a locator to search for an element.
* @param options The optional options.
* @param options.position A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
*/
dragOver: async (selectorOrLocator, options = {}) => {
const locator = typeof selectorOrLocator === 'string'
? this.page.locator(selectorOrLocator)
: selectorOrLocator;
const boundingBox = await locator.boundingBox();
if (!boundingBox) {
throw new Error('Cannot find the element or the element is not visible on the viewport.');
}
position.x =
boundingBox.x +
(options.position?.x ?? boundingBox.width / 2);
position.y =
boundingBox.y +
(options.position?.y ?? boundingBox.height / 2);
await cdpSession.send('Input.dispatchDragEvent', {
type: 'dragEnter',
...position,
data: dragData,
});
await cdpSession.send('Input.dispatchDragEvent', {
type: 'dragOver',
...position,
data: dragData,
});
},
/**
* Drop the files at the current position.
*/
drop: async () => {
const topMostElement = await this.page.evaluateHandle(({ x, y }) => {
const element = document.elementFromPoint(x, y);
if (element instanceof HTMLIFrameElement) {
const offsetBox = element.getBoundingClientRect();
return element.contentDocument.elementFromPoint(x - offsetBox.x, y - offsetBox.y);
}
return element;
}, position);
const elementHandle = topMostElement.asElement();
if (!elementHandle) {
throw new Error('Element not found.');
}
const dataTransfer = await elementHandle.evaluateHandle(async (_node, _fileObjects) => {
const dt = new DataTransfer();
const fileInstances = await Promise.all(_fileObjects.map(async (fileObject) => {
const blob = await fetch(`data:${fileObject.mimeType};base64,${fileObject.base64}`).then((res) => res.blob());
return new File([blob], fileObject.name, {
type: fileObject.mimeType ?? undefined,
});
}));
fileInstances.forEach((file) => {
dt.items.add(file);
});
return dt;
}, fileObjects);
await elementHandle.dispatchEvent('drop', { dataTransfer });
await cdpSession.detach();
},
};
}
exports.dragFiles = dragFiles;
//# sourceMappingURL=drag-files.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"drag-files.js","sourceRoot":"","sources":["../../src/page-utils/drag-files.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,0CAAuC;AACvC,+BAAgC;AAChC,+BAA+B;AAkB/B;;;;;;GAMG;AACH,KAAK,UAAU,SAAS,CAEvB,KAAoD;IAEpD,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAE,KAAK,CAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAAK,CAAE,CAAC;IAC7D,MAAM,WAAW,GAAG,MAAM,OAAO,CAAC,GAAG,CACpC,SAAS,CAAC,GAAG,CAAE,KAAK,EAAG,gBAAgB,EAAG,EAAE;QAC3C,IAAK,OAAO,gBAAgB,KAAK,QAAQ,EAAG,CAAC;YAC5C,OAAO;gBACN,IAAI,EAAE,gBAAgB,CAAC,IAAI;gBAC3B,QAAQ,EACP,gBAAgB,CAAC,QAAQ;oBACzB,IAAA,cAAO,EAAE,gBAAgB,CAAC,IAAI,CAAE;gBACjC,MAAM,EAAE,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAE,QAAQ,CAAE;aACpD,CAAC;QACH,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,IAAA,mBAAQ,EAAE,gBAAgB,EAAE,QAAQ,CAAE,CAAC;QAC5D,MAAM,IAAI,GAAG,IAAA,eA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KAAK,EAAG,KAAK,EAAE,YAAY,EAAG,EAAE;gBAC/B,MAAM,EAAE,GAAG,IAAI,YAAY,EAAE,CAAC;gBAC9B,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,GAAG,CACtC,YAAY,CAAC,GAAG,CAAE,KAAK,EAAG,UAAe,EAAG,EAAE;oBAC7C,MAAM,IAAI,GAAG,MAAM,KAAK,CACvB,QAAS,UAAU,CAAC,QAAS,WAAY,UAAU,CAAC,MAAO,EAAE,CAC7D,CAAC,IAAI,CAAE,CAAE,GAAG,EAAG,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAE,CAAC;oBAChC,OAAO,IAAI,IAAI,CAAE,CAAE,IAAI,CAAE,EAAE,UAAU,CAAC,IAAI,EAAE;wBAC3C,IAAI,EAAE,UAAU,CAAC,QAAQ,IAAI,SAAS;qBACtC,CAAE,CAAC;gBACL,CAAC,CAAE,CACH,CAAC;gBAEF,aAAa,CAAC,OAAO,CAAE,CAAE,IAAI,EAAG,EAAE;oBACjC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAE,IAAI,CAAE,CAAC;gBACtB,CAAC,CAAE,CAAC;gBAEJ,OAAO,EAAE,CAAC;YACX,CAAC,EACD,WAAW,CACX,CAAC;YAEF,MAAM,aAAa,CAAC,aAAa,CAAE,MAAM,EAAE,EAAE,YAAY,EAAE,CAAE,CAAC;YAE9D,MAAM,UAAU,CAAC,MAAM,EAAE,CAAC;QAC3B,CAAC;KACD,CAAC;AACH,CAAC;AAEQ,8BAAS"}

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PageUtils = void 0;
/**
* Internal dependencies
*/
const drag_files_1 = require("./drag-files");
const is_current_url_1 = require("./is-current-url");
const press_keys_1 = require("./press-keys");
const set_browser_viewport_1 = require("./set-browser-viewport");
class PageUtils {
browser;
page;
context;
constructor({ page }) {
this.page = page;
this.context = page.context();
this.browser = this.context.browser();
}
/** @borrows dragFiles as this.dragFiles */
dragFiles = drag_files_1.dragFiles.bind(this);
/** @borrows isCurrentURL as this.isCurrentURL */
isCurrentURL = is_current_url_1.isCurrentURL.bind(this);
/** @borrows pressKeys as this.pressKeys */
pressKeys = press_keys_1.pressKeys.bind(this);
/** @borrows setBrowserViewport as this.setBrowserViewport */
setBrowserViewport = set_browser_viewport_1.setBrowserViewport.bind(this);
/** @borrows setClipboardData as this.setClipboardData */
setClipboardData = press_keys_1.setClipboardData.bind(this);
}
exports.PageUtils = PageUtils;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/page-utils/index.ts"],"names":[],"mappings":";;;AAKA;;GAEG;AACH,6CAAyC;AACzC,qDAAgD;AAChD,6CAA2D;AAC3D,iEAA4D;AAM5D,MAAM,SAAS;IACd,OAAO,CAAU;IACjB,IAAI,CAAO;IACX,OAAO,CAAiB;IAExB,YAAa,EAAE,IAAI,EAA6B;QAC/C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC9B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAG,CAAC;IACxC,CAAC;IAED,2CAA2C;IAC3C,SAAS,GAAqB,sBAAS,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACrD,iDAAiD;IACjD,YAAY,GAAwB,6BAAY,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAC9D,2CAA2C;IAC3C,SAAS,GAAqB,sBAAS,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACrD,6DAA6D;IAC7D,kBAAkB,GACjB,yCAAkB,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACjC,yDAAyD;IACzD,gBAAgB,GAA4B,6BAAgB,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;CAC1E;AAEQ,8BAAS"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCurrentURL = void 0;
/**
* Internal dependencies
*/
const config_1 = require("../config");
/**
* Checks if current path of the URL matches the provided path.
*
* @param this
* @param path String to be serialized as pathname.
*
* @return Boolean represents whether current URL is or not a WordPress path.
*/
function isCurrentURL(path) {
const currentURL = new URL(this.page.url());
const expectedURL = new URL(path, config_1.WP_BASE_URL);
return expectedURL.pathname === currentURL.pathname;
}
exports.isCurrentURL = isCurrentURL;
//# sourceMappingURL=is-current-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"is-current-url.js","sourceRoot":"","sources":["../../src/page-utils/is-current-url.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,sCAAwC;AAGxC;;;;;;;GAOG;AACH,SAAgB,YAAY,CAAmB,IAAY;IAC1D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAE,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAE,CAAC;IAC9C,MAAM,WAAW,GAAG,IAAI,GAAG,CAAE,IAAI,EAAE,oBAAW,CAAE,CAAC;IAEjD,OAAO,WAAW,CAAC,QAAQ,KAAK,UAAU,CAAC,QAAQ,CAAC;AACrD,CAAC;AALD,oCAKC"}

View File

@@ -0,0 +1,134 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pressKeys = exports.setClipboardData = void 0;
/**
* External dependencies
*/
const change_case_1 = require("change-case");
/**
* WordPress dependencies
*/
const keycodes_1 = require("@wordpress/keycodes");
let clipboardDataHolder = {
'text/plain': '',
'text/html': '',
'rich-text': '',
};
/**
* Sets the clipboard data that can be pasted with
* `pressKeys( 'primary+v' )`.
*
* @param this
* @param clipboardData
* @param clipboardData.plainText
* @param clipboardData.html
*/
function setClipboardData({ plainText = '', html = '' }) {
clipboardDataHolder = {
'text/plain': plainText,
'text/html': html,
'rich-text': '',
};
}
exports.setClipboardData = setClipboardData;
async function emulateClipboard(page, type) {
clipboardDataHolder = await page.evaluate(([_type, _clipboardData]) => {
const canvasDoc =
// @ts-ignore
document.activeElement?.contentDocument ?? document;
const event = new ClipboardEvent(_type, {
bubbles: true,
cancelable: true,
clipboardData: new DataTransfer(),
});
if (!event.clipboardData) {
throw new Error('ClipboardEvent.clipboardData is null');
}
if (_type === 'paste') {
event.clipboardData.setData('text/plain', _clipboardData['text/plain']);
event.clipboardData.setData('text/html', _clipboardData['text/html']);
event.clipboardData.setData('rich-text', _clipboardData['rich-text']);
}
else {
const selection = canvasDoc.defaultView.getSelection();
const plainText = selection.toString();
let html = plainText;
if (selection.rangeCount) {
const range = selection.getRangeAt(0);
const fragment = range.cloneContents();
html = Array.from(fragment.childNodes)
.map((node) => node.outerHTML ??
node.nodeValue)
.join('');
}
event.clipboardData.setData('text/plain', plainText);
event.clipboardData.setData('text/html', html);
}
canvasDoc.activeElement.dispatchEvent(event);
return {
'text/plain': event.clipboardData.getData('text/plain'),
'text/html': event.clipboardData.getData('text/html'),
'rich-text': event.clipboardData.getData('rich-text'),
};
}, [type, clipboardDataHolder]);
}
const isAppleOS = () => process.platform === 'darwin';
const isWebkit = (page) => page.context().browser().browserType().name() === 'webkit';
const browserCache = new WeakMap();
const getHasNaturalTabNavigation = async (page) => {
if (!isAppleOS() || !isWebkit(page)) {
return true;
}
if (browserCache.has(page.context().browser())) {
return browserCache.get(page.context().browser());
}
const testPage = await page.context().newPage();
await testPage.setContent(`<button>1</button><button>2</button>`);
await testPage.getByText('1').focus();
await testPage.keyboard.press('Tab');
const featureDetected = await testPage
.getByText('2')
.evaluate((node) => node === document.activeElement);
browserCache.set(page.context().browser(), featureDetected);
await testPage.close();
return featureDetected;
};
const modifiers = {
...keycodes_1.modifiers,
shiftAlt: (_isApple) => _isApple() ? [keycodes_1.SHIFT, keycodes_1.ALT] : [keycodes_1.SHIFT, keycodes_1.CTRL],
};
async function pressKeys(key, { times, ...pressOptions } = {}) {
const hasNaturalTabNavigation = await getHasNaturalTabNavigation(this.page);
let command;
if (key.toLowerCase() === 'primary+c') {
command = () => emulateClipboard(this.page, 'copy');
}
else if (key.toLowerCase() === 'primary+x') {
command = () => emulateClipboard(this.page, 'cut');
}
else if (key.toLowerCase() === 'primary+v') {
command = () => emulateClipboard(this.page, 'paste');
}
else {
const keys = key.split('+').flatMap((keyCode) => {
if (Object.prototype.hasOwnProperty.call(modifiers, keyCode)) {
return modifiers[keyCode](isAppleOS).map((modifier) => modifier === keycodes_1.CTRL ? 'Control' : (0, change_case_1.capitalCase)(modifier));
}
else if (keyCode === 'Tab' && !hasNaturalTabNavigation) {
return ['Alt', 'Tab'];
}
return keyCode;
});
const normalizedKeys = keys.join('+');
command = () => this.page.keyboard.press(normalizedKeys);
}
times = times ?? 1;
for (let i = 0; i < times; i += 1) {
await command();
if (times > 1 && pressOptions.delay) {
await this.page.waitForTimeout(pressOptions.delay);
}
}
}
exports.pressKeys = pressKeys;
//# sourceMappingURL=press-keys.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"press-keys.js","sourceRoot":"","sources":["../../src/page-utils/press-keys.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,6CAA0C;AAQ1C;;GAEG;AACH,kDAK6B;AAE7B,IAAI,mBAAmB,GAInB;IACH,YAAY,EAAE,EAAE;IAChB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,EAAE;CACf,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAgB,gBAAgB,CAE/B,EAAE,SAAS,GAAG,EAAE,EAAE,IAAI,GAAG,EAAE,EAAE;IAE7B,mBAAmB,GAAG;QACrB,YAAY,EAAE,SAAS;QACvB,WAAW,EAAE,IAAI;QACjB,WAAW,EAAE,EAAE;KACf,CAAC;AACH,CAAC;AATD,4CASC;AAED,KAAK,UAAU,gBAAgB,CAAE,IAAU,EAAE,IAA8B;IAC1E,mBAAmB,GAAG,MAAM,IAAI,CAAC,QAAQ,CACxC,CAAE,CAAE,KAAK,EAAE,cAAc,CAAE,EAAG,EAAE;QAC/B,MAAM,SAAS;QACd,aAAa;QACb,QAAQ,CAAC,aAA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AAE,YAAY,CAAC,KAAK,CAAE,CAAC;QACtD,CAAC;IACF,CAAC;AACF,CAAC;AA1CD,8BA0CC"}

View File

@@ -0,0 +1,47 @@
"use strict";
/**
* Named viewport options.
*
* @typedef {"large"|"medium"|"small"} WPDimensionsName
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.setBrowserViewport = void 0;
/**
* Viewport dimensions object.
*
* @typedef {Object} WPViewportDimensions
*
* @property {number} width Width, in pixels.
* @property {number} height Height, in pixels.
*/
/**
* Predefined viewport dimensions to reference by name.
*
* @enum {WPViewportDimensions}
*
* @type {Record<WPDimensionsName, WPViewportDimensions>}
*/
const PREDEFINED_DIMENSIONS = {
large: { width: 960, height: 700 },
medium: { width: 768, height: 700 },
small: { width: 600, height: 700 },
};
/**
* Valid argument argument type from which to derive viewport dimensions.
*
* @typedef {WPDimensionsName|WPViewportDimensions} WPViewport
*/
/**
* Sets browser viewport to specified type.
*
* @this {import('./').PageUtils}
* @param {WPViewport} viewport Viewport name or dimensions object to assign.
*/
async function setBrowserViewport(viewport) {
const dimensions = typeof viewport === 'string'
? PREDEFINED_DIMENSIONS[viewport]
: viewport;
await this.page.setViewportSize(dimensions);
}
exports.setBrowserViewport = setBrowserViewport;
//# sourceMappingURL=set-browser-viewport.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"set-browser-viewport.js","sourceRoot":"","sources":["../../src/page-utils/set-browser-viewport.js"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH;;;;;;;GAOG;AAEH;;;;;;GAMG;AACH,MAAM,qBAAqB,GAAG;IAC7B,KAAK,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;IAClC,MAAM,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;IACnC,KAAK,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;CAClC,CAAC;AAEF;;;;GAIG;AAEH;;;;;GAKG;AACI,KAAK,UAAU,kBAAkB,CAAE,QAAQ;IACjD,MAAM,UAAU,GACf,OAAO,QAAQ,KAAK,QAAQ;QAC3B,CAAC,CAAC,qBAAqB,CAAE,QAAQ,CAAE;QACnC,CAAC,CAAC,QAAQ,CAAC;IAEb,MAAM,IAAI,CAAC,IAAI,CAAC,eAAe,CAAE,UAAU,CAAE,CAAC;AAC/C,CAAC;AAPD,gDAOC"}

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBlock = exports.deleteAllBlocks = void 0;
/**
* Delete all blocks using REST API.
*
* @see https://developer.wordpress.org/rest-api/reference/blocks/#list-editor-blocks
* @param this
*/
async function deleteAllBlocks() {
// List all blocks.
// https://developer.wordpress.org/rest-api/reference/blocks/#list-editor-blocks
const blocks = await this.rest({
path: '/wp/v2/blocks',
params: {
per_page: 100,
// All possible statuses.
status: 'publish,future,draft,pending,private,trash',
},
});
// Delete blocks.
// https://developer.wordpress.org/rest-api/reference/blocks/#delete-a-editor-block
// "/wp/v2/posts" not yet supports batch requests.
await this.batchRest(blocks.map((block) => ({
method: 'DELETE',
path: `/wp/v2/blocks/${block.id}?force=true`,
})));
}
exports.deleteAllBlocks = deleteAllBlocks;
/**
* Creates a new block using the REST API.
*
* @see https://developer.wordpress.org/rest-api/reference/blocks/#create-a-editor-block.
* @param this
* @param payload Block payload.
*/
async function createBlock(payload) {
const block = await this.rest({
path: '/wp/v2/blocks',
method: 'POST',
data: { ...payload },
});
return block;
}
exports.createBlock = createBlock;
//# sourceMappingURL=blocks.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"blocks.js","sourceRoot":"","sources":["../../src/request-utils/blocks.ts"],"names":[],"mappings":";;;AAgBA;;;;;GAKG;AACI,KAAK,UAAU,eAAe;IACpC,mBAAmB;IACnB,gFAAgF;IAChF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAE;QAC/B,IAAI,EAAE,eAAe;QACrB,MAAM,EAAE;YACP,QAAQ,EAAE,GAAG;YACb,yBAAyB;YACzB,MAAM,EAAE,4CAA4C;SACpD;KACD,CAAE,CAAC;IAEJ,iBAAiB;IACjB,mFAAmF;IACnF,kDAAkD;IAClD,MAAM,IAAI,CAAC,SAAS,CACnB,MAAM,CAAC,GAAG,CAAE,CAAE,KAAqB,EAAG,EAAE,CAAC,CAAE;QAC1C,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,iBAAkB,KAAK,CAAC,EAAG,aAAa;KAC9C,CAAE,CAAE,CACL,CAAC;AACH,CAAC;AArBD,0CAqBC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,WAAW,CAEhC,OAA2B;IAE3B,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,IAAI,CAAE;QAC9B,IAAI,EAAE,eAAe;QACrB,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE;KACpB,CAAE,CAAC;IAEJ,OAAO,KAAK,CAAC;AACd,CAAC;AAXD,kCAWC"}

View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteAllComments = exports.createComment = void 0;
/**
* Create new comment using the REST API.
*
* @param this
* @param payload
*/
async function createComment(payload) {
const currentUser = await this.rest({
path: '/wp/v2/users/me',
method: 'GET',
});
const author = currentUser.id;
const comment = await this.rest({
method: 'POST',
path: '/wp/v2/comments',
data: { ...payload, author },
});
return comment;
}
exports.createComment = createComment;
/**
* Delete all comments using the REST API.
*
* @param this
*/
async function deleteAllComments() {
// List all comments.
// https://developer.wordpress.org/rest-api/reference/comments/#list-comments
const comments = await this.rest({
path: '/wp/v2/comments',
params: {
per_page: 100,
// All possible statuses.
status: 'unapproved,approved,spam,trash',
},
});
// Delete all comments one by one.
// https://developer.wordpress.org/rest-api/reference/comments/#delete-a-comment
// "/wp/v2/comments" doesn't support batch requests yet.
await Promise.all(comments.map((comment) => this.rest({
method: 'DELETE',
path: `/wp/v2/comments/${comment.id}`,
params: {
force: true,
},
})));
}
exports.deleteAllComments = deleteAllComments;
//# sourceMappingURL=comments.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"comments.js","sourceRoot":"","sources":["../../src/request-utils/comments.ts"],"names":[],"mappings":";;;AAqBA;;;;;GAKG;AACI,KAAK,UAAU,aAAa,CAElC,OAA6B;IAE7B,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,IAAI,CAAU;QAC5C,IAAI,EAAE,iBAAiB;QACvB,MAAM,EAAE,KAAK;KACb,CAAE,CAAC;IAEJ,MAAM,MAAM,GAAG,WAAW,CAAC,EAAE,CAAC;IAE9B,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,IAAI,CAAa;QAC3C,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,iBAAiB;QACvB,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE;KAC5B,CAAE,CAAC;IAEJ,OAAO,OAAO,CAAC;AAChB,CAAC;AAlBD,sCAkBC;AAED;;;;GAIG;AACI,KAAK,UAAU,iBAAiB;IACtC,qBAAqB;IACrB,6EAA6E;IAC7E,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAE;QACjC,IAAI,EAAE,iBAAiB;QACvB,MAAM,EAAE;YACP,QAAQ,EAAE,GAAG;YACb,yBAAyB;YACzB,MAAM,EAAE,gCAAgC;SACxC;KACD,CAAE,CAAC;IAEJ,kCAAkC;IAClC,gFAAgF;IAChF,wDAAwD;IACxD,MAAM,OAAO,CAAC,GAAG,CAChB,QAAQ,CAAC,GAAG,CAAE,CAAE,OAAgB,EAAG,EAAE,CACpC,IAAI,CAAC,IAAI,CAAE;QACV,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,mBAAoB,OAAO,CAAC,EAAG,EAAE;QACvC,MAAM,EAAE;YACP,KAAK,EAAE,IAAI;SACX;KACD,CAAE,CACH,CACD,CAAC;AACH,CAAC;AA1BD,8CA0BC"}

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setGutenbergExperiments = void 0;
/**
* Sets the Gutenberg experiments.
*
* @param this
* @param experiments Array of experimental flags to enable. Pass in an empty array to disable all experiments.
*/
async function setGutenbergExperiments(experiments) {
const response = await this.request.get('/wp-admin/admin.php?page=gutenberg-experiments');
const html = await response.text();
const nonce = html.match(/name="_wpnonce" value="([^"]+)"/)[1];
await this.request.post('/wp-admin/options.php', {
form: {
option_page: 'gutenberg-experiments',
action: 'update',
_wpnonce: nonce,
_wp_http_referer: '/wp-admin/admin.php?page=gutenberg-experiments',
...Object.fromEntries(experiments.map((experiment) => [
`gutenberg-experiments[${experiment}]`,
1,
])),
submit: 'Save Changes',
},
failOnStatusCode: true,
});
}
exports.setGutenbergExperiments = setGutenbergExperiments;
//# sourceMappingURL=gutenberg-experiments.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"gutenberg-experiments.js","sourceRoot":"","sources":["../../src/request-utils/gutenberg-experiments.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACH,KAAK,UAAU,uBAAuB,CAErC,WAAqB;IAErB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CACtC,gDAAgD,CAChD,CAAC;IACF,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IACnC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAE,iCAAiC,CAAG,CAAE,CAAC,CAAE,CAAC;IAEpE,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAE,uBAAuB,EAAE;QACjD,IAAI,EAAE;YACL,WAAW,EAAE,uBAAuB;YACpC,MAAM,EAAE,QAAQ;YAChB,QAAQ,EAAE,KAAK;YACf,gBAAgB,EAAE,gDAAgD;YAClE,GAAG,MAAM,CAAC,WAAW,CACpB,WAAW,CAAC,GAAG,CAAE,CAAE,UAAU,EAAG,EAAE,CAAC;gBAClC,yBAA0B,UAAW,GAAG;gBACxC,CAAC;aACD,CAAE,CACH;YACD,MAAM,EAAE,cAAc;SACtB;QACD,gBAAgB,EAAE,IAAI;KACtB,CAAE,CAAC;AACL,CAAC;AAEQ,0DAAuB"}

View File

@@ -0,0 +1,158 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestUtils = void 0;
/**
* External dependencies
*/
const fs = require("fs/promises");
const path = require("path");
const test_1 = require("@playwright/test");
/**
* Internal dependencies
*/
const config_1 = require("../config");
const login_1 = require("./login");
const media_1 = require("./media");
const users_1 = require("./users");
const rest_1 = require("./rest");
const plugins_1 = require("./plugins");
const templates_1 = require("./templates");
const themes_1 = require("./themes");
const blocks_1 = require("./blocks");
const comments_1 = require("./comments");
const posts_1 = require("./posts");
const menus_1 = require("./menus");
const pages_1 = require("./pages");
const preferences_1 = require("./preferences");
const site_settings_1 = require("./site-settings");
const widgets_1 = require("./widgets");
const patterns_1 = require("./patterns");
const gutenberg_experiments_1 = require("./gutenberg-experiments");
class RequestUtils {
request;
user;
maxBatchSize;
storageState;
storageStatePath;
baseURL;
pluginsMap = null;
static async setup({ user, storageStatePath, baseURL = config_1.WP_BASE_URL, }) {
let storageState;
if (storageStatePath) {
await fs.mkdir(path.dirname(storageStatePath), {
recursive: true,
});
try {
storageState = JSON.parse(await fs.readFile(storageStatePath, 'utf-8'));
}
catch (error) {
if (error instanceof Error &&
error.code === 'ENOENT') {
// Ignore errors if the state is not found.
}
else {
throw error;
}
}
}
const requestContext = await test_1.request.newContext({
baseURL,
storageState: storageState && {
cookies: storageState.cookies,
origins: [],
},
});
const requestUtils = new this(requestContext, {
user,
storageState,
storageStatePath,
baseURL,
});
return requestUtils;
}
constructor(requestContext, { user = config_1.WP_ADMIN_USER, storageState, storageStatePath, baseURL = config_1.WP_BASE_URL, } = {}) {
this.user = user;
this.request = requestContext;
this.storageStatePath = storageStatePath;
this.storageState = storageState;
this.baseURL = baseURL;
}
/** @borrows login as this.login */
login = login_1.login.bind(this);
/** @borrows setupRest as this.setupRest */
setupRest = rest_1.setupRest.bind(this);
// .bind() drops the generic types. Re-casting it to keep the type signature.
rest = rest_1.rest.bind(this);
/** @borrows getMaxBatchSize as this.getMaxBatchSize */
getMaxBatchSize = rest_1.getMaxBatchSize.bind(this);
// .bind() drops the generic types. Re-casting it to keep the type signature.
batchRest = rest_1.batchRest.bind(this);
/** @borrows getPluginsMap as this.getPluginsMap */
getPluginsMap = plugins_1.getPluginsMap.bind(this);
/** @borrows activatePlugin as this.activatePlugin */
activatePlugin = plugins_1.activatePlugin.bind(this);
/** @borrows deactivatePlugin as this.deactivatePlugin */
deactivatePlugin = plugins_1.deactivatePlugin.bind(this);
/** @borrows activateTheme as this.activateTheme */
activateTheme = themes_1.activateTheme.bind(this);
/** @borrows createBlock as this.createBlock */
createBlock = blocks_1.createBlock.bind(this);
/** @borrows deleteAllBlocks as this.deleteAllBlocks */
deleteAllBlocks = blocks_1.deleteAllBlocks.bind(this);
/** @borrows createPost as this.createPost */
createPost = posts_1.createPost.bind(this);
/** @borrows deleteAllPosts as this.deleteAllPosts */
deleteAllPosts = posts_1.deleteAllPosts.bind(this);
/** @borrows createClassicMenu as this.createClassicMenu */
createClassicMenu = menus_1.createClassicMenu.bind(this);
/** @borrows createNavigationMenu as this.createNavigationMenu */
createNavigationMenu = menus_1.createNavigationMenu.bind(this);
/** @borrows deleteAllMenus as this.deleteAllMenus */
deleteAllMenus = menus_1.deleteAllMenus.bind(this);
/** @borrows getNavigationMenus as this.getNavigationMenus */
getNavigationMenus = menus_1.getNavigationMenus.bind(this);
/** @borrows createComment as this.createComment */
createComment = comments_1.createComment.bind(this);
/** @borrows deleteAllComments as this.deleteAllComments */
deleteAllComments = comments_1.deleteAllComments.bind(this);
/** @borrows deleteAllWidgets as this.deleteAllWidgets */
deleteAllWidgets = widgets_1.deleteAllWidgets.bind(this);
/** @borrows addWidgetBlock as this.addWidgetBlock */
addWidgetBlock = widgets_1.addWidgetBlock.bind(this);
/** @borrows deleteAllTemplates as this.deleteAllTemplates */
deleteAllTemplates = templates_1.deleteAllTemplates.bind(this);
/** @borrows createTemplate as this.createTemplate */
createTemplate = templates_1.createTemplate.bind(this);
/** @borrows resetPreferences as this.resetPreferences */
resetPreferences = preferences_1.resetPreferences.bind(this);
/** @borrows listMedia as this.listMedia */
listMedia = media_1.listMedia.bind(this);
/** @borrows uploadMedia as this.uploadMedia */
uploadMedia = media_1.uploadMedia.bind(this);
/** @borrows deleteMedia as this.deleteMedia */
deleteMedia = media_1.deleteMedia.bind(this);
/** @borrows deleteAllMedia as this.deleteAllMedia */
deleteAllMedia = media_1.deleteAllMedia.bind(this);
/** @borrows createUser as this.createUser */
createUser = users_1.createUser.bind(this);
/** @borrows deleteAllUsers as this.deleteAllUsers */
deleteAllUsers = users_1.deleteAllUsers.bind(this);
/** @borrows getSiteSettings as this.getSiteSettings */
getSiteSettings = site_settings_1.getSiteSettings.bind(this);
/** @borrows updateSiteSettings as this.updateSiteSettings */
updateSiteSettings = site_settings_1.updateSiteSettings.bind(this);
/** @borrows deleteAllPages as this.deleteAllPages */
deleteAllPages = pages_1.deleteAllPages.bind(this);
/** @borrows createPage as this.createPage */
createPage = pages_1.createPage.bind(this);
/** @borrows getCurrentThemeGlobalStylesPostId as this.getCurrentThemeGlobalStylesPostId */
getCurrentThemeGlobalStylesPostId = themes_1.getCurrentThemeGlobalStylesPostId.bind(this);
/** @borrows getThemeGlobalStylesRevisions as this.getThemeGlobalStylesRevisions */
getThemeGlobalStylesRevisions = themes_1.getThemeGlobalStylesRevisions.bind(this);
/** @borrows deleteAllPatternCategories as this.deleteAllPatternCategories */
deleteAllPatternCategories = patterns_1.deleteAllPatternCategories.bind(this);
/** @borrows setGutenbergExperiments as this.setGutenbergExperiments */
setGutenbergExperiments = gutenberg_experiments_1.setGutenbergExperiments.bind(this);
}
exports.RequestUtils = RequestUtils;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/request-utils/index.ts"],"names":[],"m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E,IAAI,CAAE,CAAC;IAC1E,2CAA2C;IAC3C,SAAS,GAAqB,iBAAS,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACrD,+CAA+C;IAC/C,WAAW,GAAuB,mBAAW,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAC3D,+CAA+C;IAC/C,WAAW,GAAuB,mBAAW,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAC3D,qDAAqD;IACrD,cAAc,GAA0B,sBAAc,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACpE,6CAA6C;IAC7C,UAAU,GAAsB,kBAAU,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACxD,qDAAqD;IACrD,cAAc,GAA0B,sBAAc,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACpE,uDAAuD;IACvD,eAAe,GAA2B,+BAAe,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACvE,6DAA6D;IAC7D,kBAAkB,GACjB,kCAAkB,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACjC,qDAAqD;IACrD,cAAc,GAA0B,sBAAc,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACpE,6CAA6C;IAC7C,UAAU,GAAsB,kBAAU,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACxD,2FAA2F;IAC3F,iCAAiC,GAChC,0CAAiC,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAChD,mFAAmF;IACnF,6BAA6B,GAC5B,sCAA6B,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IAC5C,6EAA6E;IAC7E,0BAA0B,GAAG,qCAA0B,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;IACrE,uEAAuE;IACvE,uBAAuB,GACtB,+CAAuB,CAAC,IAAI,CAAE,IAAI,CAAE,CAAC;CACtC;AAGQ,oCAAY"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.login = void 0;
async function login(user = this.user) {
// Login to admin using request context.
let response = await this.request.post('wp-login.php', {
failOnStatusCode: true,
form: {
log: user.username,
pwd: user.password,
},
});
await response.dispose();
// Get the nonce.
response = await this.request.get('wp-admin/admin-ajax.php?action=rest-nonce', {
failOnStatusCode: true,
});
const nonce = await response.text();
return nonce;
}
exports.login = login;
//# sourceMappingURL=login.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"login.js","sourceRoot":"","sources":["../../src/request-utils/login.ts"],"names":[],"mappings":";;;AAUA,KAAK,UAAU,KAAK,CAAsB,OAAa,IAAI,CAAC,IAAI;IAC/D,wCAAwC;IACxC,IAAI,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAE,cAAc,EAAE;QACvD,gBAAgB,EAAE,IAAI;QACtB,IAAI,EAAE;YACL,GAAG,EAAE,IAAI,CAAC,QAAQ;YAClB,GAAG,EAAE,IAAI,CAAC,QAAQ;SAClB;KACD,CAAE,CAAC;IACJ,MAAM,QAAQ,CAAC,OAAO,EAAE,CAAC;IAEzB,iBAAiB;IACjB,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAChC,2CAA2C,EAC3C;QACC,gBAAgB,EAAE,IAAI;KACtB,CACD,CAAC;IACF,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IAEpC,OAAO,KAAK,CAAC;AACd,CAAC;AAEQ,sBAAK"}

View File

@@ -0,0 +1,74 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteAllMedia = exports.deleteMedia = exports.uploadMedia = exports.listMedia = void 0;
/**
* External dependencies
*/
const fs = require("fs");
/**
* List all media files.
*
* @see https://developer.wordpress.org/rest-api/reference/media/#list-media
* @param this
*/
async function listMedia() {
const response = await this.rest({
method: 'GET',
path: '/wp/v2/media',
params: {
per_page: 100,
},
});
return response;
}
exports.listMedia = listMedia;
/**
* Upload a media file.
*
* @see https://developer.wordpress.org/rest-api/reference/media/#create-a-media-item
* @param this
* @param filePathOrData The path or data of the file being uploaded.
*/
async function uploadMedia(filePathOrData) {
const file = typeof filePathOrData === 'string'
? fs.createReadStream(filePathOrData)
: filePathOrData;
const response = await this.rest({
method: 'POST',
path: '/wp/v2/media',
multipart: {
file,
},
});
return response;
}
exports.uploadMedia = uploadMedia;
/**
* delete a media file.
*
* @see https://developer.wordpress.org/rest-api/reference/media/#delete-a-media-item
* @param this
* @param mediaId The ID of the media file.
*/
async function deleteMedia(mediaId) {
const response = await this.rest({
method: 'DELETE',
path: `/wp/v2/media/${mediaId}`,
params: { force: true },
});
return response;
}
exports.deleteMedia = deleteMedia;
/**
* delete all media files.
*
* @param this
*/
async function deleteAllMedia() {
const files = await this.listMedia();
// The media endpoint doesn't support batch request yet.
const responses = await Promise.all(files.map((media) => this.deleteMedia(media.id)));
return responses;
}
exports.deleteAllMedia = deleteAllMedia;
//# sourceMappingURL=media.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"media.js","sourceRoot":"","sources":["../../src/request-utils/media.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,yBAAyB;AAoBzB;;;;;GAKG;AACH,KAAK,UAAU,SAAS;IACvB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAa;QAC5C,MAAM,EAAE,KAAK;QACb,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE;YACP,QAAQ,EAAE,GAAG;SACb;KACD,CAAE,CAAC;IAEJ,OAAO,QAAQ,CAAC;AACjB,CAAC;AA8DQ,8BAAS;AA5DlB;;;;;;GAMG;AACH,KAAK,UAAU,WAAW,CAEzB,cAAsC;IAEtC,MAAM,IAAI,GACT,OAAO,cAAc,KAAK,QAAQ;QACjC,CAAC,CAAC,EAAE,CAAC,gBAAgB,CAAE,cAAc,CAAE;QACvC,CAAC,CAAC,cAAc,CAAC;IAEnB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAW;QAC1C,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,cAAc;QACpB,SAAS,EAAE;YACV,IAAI;SACJ;KACD,CAAE,CAAC;IAEJ,OAAO,QAAQ,CAAC;AACjB,CAAC;AAmCmB,kCAAW;AAjC/B;;;;;;GAMG;AACH,KAAK,UAAU,WAAW,CAAsB,OAAe;IAC9D,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAE;QACjC,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,gBAAiB,OAAQ,EAAE;QACjC,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE;KACvB,CAAE,CAAC;IAEJ,OAAO,QAAQ,CAAC;AACjB,CAAC;AAkBgC,kCAAW;AAhB5C;;;;GAIG;AACH,KAAK,UAAU,cAAc;IAC5B,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;IAErC,wDAAwD;IACxD,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,GAAG,CAClC,KAAK,CAAC,GAAG,CAAE,CAAE,KAAK,EAAG,EAAE,CAAC,IAAI,CAAC,WAAW,CAAE,KAAK,CAAC,EAAE,CAAE,CAAE,CACtD,CAAC;IAEF,OAAO,SAAS,CAAC;AAClB,CAAC;AAE6C,wCAAc"}

View File

@@ -0,0 +1,121 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNavigationMenus = exports.deleteAllMenus = exports.createNavigationMenu = exports.createClassicMenu = void 0;
/**
* Create a classic menu
*
* @param name Menu name.
* @return Menu content.
*/
async function createClassicMenu(name) {
const menuItems = [
{
title: 'Custom link',
url: 'http://localhost:8889/',
type: 'custom',
menu_order: 1,
},
];
const menu = await this.rest({
method: 'POST',
path: `/wp/v2/menus/`,
data: {
name,
},
});
await this.batchRest(menuItems.map((menuItem) => ({
method: 'POST',
path: `/wp/v2/menu-items`,
body: {
menus: menu.id,
object_id: undefined,
...menuItem,
parent: undefined,
},
})));
return menu;
}
exports.createClassicMenu = createClassicMenu;
/**
* Create a navigation menu
*
* @param menuData navigation menu post data.
* @return Menu content.
*/
async function createNavigationMenu(menuData) {
return this.rest({
method: 'POST',
path: `/wp/v2/navigation/`,
data: {
status: 'publish',
...menuData,
},
});
}
exports.createNavigationMenu = createNavigationMenu;
/**
* Delete all navigation and classic menus
*
*/
async function deleteAllMenus() {
const navMenus = await this.rest({
path: `/wp/v2/navigation/`,
data: {
status: [
'publish',
'pending',
'draft',
'auto-draft',
'future',
'private',
'inherit',
'trash',
],
},
});
if (navMenus.length) {
await this.batchRest(navMenus.map((menu) => ({
method: 'DELETE',
path: `/wp/v2/navigation/${menu.id}?force=true`,
})));
}
const classicMenus = await this.rest({
path: `/wp/v2/menus/`,
data: {
status: [
'publish',
'pending',
'draft',
'auto-draft',
'future',
'private',
'inherit',
'trash',
],
},
});
if (classicMenus.length) {
await this.batchRest(classicMenus.map((menu) => ({
method: 'DELETE',
path: `/wp/v2/menus/${menu.id}?force=true`,
})));
}
}
exports.deleteAllMenus = deleteAllMenus;
/**
* Get latest navigation menus
*
* @param args
* @param args.status
* @return {string} Menu content.
*/
async function getNavigationMenus(args) {
const navigationMenus = await this.rest({
method: 'GET',
path: `/wp/v2/navigation/`,
data: args,
});
return navigationMenus;
}
exports.getNavigationMenus = getNavigationMenus;
//# sourceMappingURL=menus.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"menus.js","sourceRoot":"","sources":["../../src/request-utils/menus.ts"],"names":[],"mappings":";;;AAeA;;;;;GAKG;AACI,KAAK,UAAU,iBAAiB,CAAsB,IAAY;IACxE,MAAM,SAAS,GAAG;QACjB;YACC,KAAK,EAAE,aAAa;YACpB,GAAG,EAAE,wBAAwB;YAC7B,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,CAAC;SACb;KACD,CAAC;IAEF,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,IAAI,CAAoB;QAC/C,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,eAAe;QACrB,IAAI,EAAE;YACL,IAAI;SACJ;KACD,CAAE,CAAC;IAEJ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,MAAM,EAAE;gBACP,SAAS;gBACT,SAAS;gBACT,OAAO;gBACP,YAAY;gBACZ,QAAQ;gBACR,SAAS;gBACT,SAAS;gBACT,OAAO;aACP;SACD;KACD,CAAE,CAAC;IAEJ,IAAK,YAAY,CAAC,MAAM,EAAG,CAAC;QAC3B,MAAM,IAAI,CAAC,SAAS,CACnB,YAAY,CAAC,GAAG,CAAE,CAAE,IAAI,EAAG,EAAE,CAAC,CAAE;YAC/B,MAAM,EAAE,QAAQ;YAChB,IAAI,EAAE,gBAAiB,IAAI,CAAC,EAAG,aAAa;SAC5C,CAAE,CAAE,CACL,CAAC;IACH,CAAC;AACF,CAAC;AAlDD,wCAkDC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,kBAAkB,CAEvC,IAA2B;IAE3B,MAAM,eAAe,GAAG,MAAM,IAAI,CAAC,IAAI,CAAsB;QAC5D,MAAM,EAAE,KAAK;QACb,IAAI,EAAE,oBAAoB;QAC1B,IAAI,EAAE,IAAI;KACV,CAAE,CAAC;IACJ,OAAO,eAAe,CAAC;AACxB,CAAC;AAVD,gDAUC"}

View File

@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPage = exports.deleteAllPages = exports.deletePage = void 0;
const PAGE_STATUS = [
'publish',
'future',
'draft',
'pending',
'private',
'trash',
];
async function deletePage(id) {
// https://developer.wordpress.org/rest-api/reference/pages/#delete-a-page
return await this.rest({
method: 'DELETE',
path: `/wp/v2/pages/${id}`,
params: {
force: true,
},
});
}
exports.deletePage = deletePage;
/**
* Delete all pages using REST API.
*
* @param this
*/
async function deleteAllPages() {
// List all pages.
// https://developer.wordpress.org/rest-api/reference/pages/#list-pages
const pages = await this.rest({
path: '/wp/v2/pages',
params: {
per_page: 100,
status: PAGE_STATUS.join(','),
},
});
// Delete all pages one by one.
// "/wp/v2/pages" not yet supports batch requests.
await Promise.all(pages.map((page) => deletePage.call(this, page.id)));
}
exports.deleteAllPages = deleteAllPages;
/**
* Create a new page.
*
* @param this
* @param payload The page payload.
*/
async function createPage(payload) {
// https://developer.wordpress.org/rest-api/reference/pages/#create-a-page
const page = await this.rest({
method: 'POST',
path: `/wp/v2/pages`,
params: payload,
});
return page;
}
exports.createPage = createPage;
//# sourceMappingURL=pages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pages.js","sourceRoot":"","sources":["../../src/request-utils/pages.ts"],"names":[],"mappings":";;;AAKA,MAAM,WAAW,GAAG;IACnB,SAAS;IACT,QAAQ;IACR,OAAO;IACP,SAAS;IACT,SAAS;IACT,OAAO;CACE,CAAC;AAeJ,KAAK,UAAU,UAAU,CAAsB,EAAU;IAC/D,0EAA0E;IAC1E,OAAO,MAAM,IAAI,CAAC,IAAI,CAAE;QACvB,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,gBAAiB,EAAG,EAAE;QAC5B,MAAM,EAAE;YACP,KAAK,EAAE,IAAI;SACX;KACD,CAAE,CAAC;AACL,CAAC;AATD,gCASC;AAED;;;;GAIG;AACI,KAAK,UAAU,cAAc;IACnC,kBAAkB;IAClB,uEAAuE;IACvE,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,IAAI,CAAY;QACxC,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE;YACP,QAAQ,EAAE,GAAG;YAEb,MAAM,EAAE,WAAW,CAAC,IAAI,CAAE,GAAG,CAAE;SAC/B;KACD,CAAE,CAAC;IAEJ,+BAA+B;IAC/B,kDAAkD;IAClD,MAAM,OAAO,CAAC,GAAG,CAChB,KAAK,CAAC,GAAG,CAAE,CAAE,IAAI,EAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAE,IAAI,EAAE,IAAI,CAAC,EAAE,CAAE,CAAE,CACzD,CAAC;AACH,CAAC;AAjBD,wCAiBC;AAED;;;;;GAKG;AACI,KAAK,UAAU,UAAU,CAE/B,OAA0B;IAE1B,0EAA0E;IAC1E,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,IAAI,CAAU;QACrC,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE,OAAO;KACf,CAAE,CAAC;IAEJ,OAAO,IAAI,CAAC;AACb,CAAC;AAZD,gCAYC"}

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteAllPatternCategories = void 0;
/**
* Delete all pattern categories using REST API.
*
* @see https://developer.wordpress.org/rest-api/reference/categories/#list-categories
* @param this
*/
async function deleteAllPatternCategories() {
// List all pattern categories.
// https://developer.wordpress.org/rest-api/reference/categories/#list-categories
const categories = await this.rest({
path: '/wp/v2/wp_pattern_category',
params: {
per_page: 100,
},
});
// Delete pattern categories.
// https://developer.wordpress.org/rest-api/reference/categories/#delete-a-category
// "/wp/v2/category" does not yet supports batch requests.
await this.batchRest(categories.map((category) => ({
method: 'DELETE',
path: `/wp/v2/wp_pattern_category/${category.id}?force=true`,
})));
}
exports.deleteAllPatternCategories = deleteAllPatternCategories;
//# sourceMappingURL=patterns.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"patterns.js","sourceRoot":"","sources":["../../src/request-utils/patterns.ts"],"names":[],"mappings":";;;AAKA;;;;;GAKG;AACI,KAAK,UAAU,0BAA0B;IAC/C,+BAA+B;IAC/B,iFAAiF;IACjF,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,IAAI,CAAE;QACnC,IAAI,EAAE,4BAA4B;QAClC,MAAM,EAAE;YACP,QAAQ,EAAE,GAAG;SACb;KACD,CAAE,CAAC;IAEJ,6BAA6B;IAC7B,mFAAmF;IACnF,0DAA0D;IAC1D,MAAM,IAAI,CAAC,SAAS,CACnB,UAAU,CAAC,GAAG,CAAE,CAAE,QAAwB,EAAG,EAAE,CAAC,CAAE;QACjD,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,8BAA+B,QAAQ,CAAC,EAAG,aAAa;KAC9D,CAAE,CAAE,CACL,CAAC;AACH,CAAC;AAnBD,gEAmBC"}

View File

@@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deactivatePlugin = exports.activatePlugin = exports.getPluginsMap = void 0;
/**
* External dependencies
*/
const change_case_1 = require("change-case");
/**
* Fetch the plugins from API and cache them in memory,
* since they are unlikely to change during testing.
*
* @param this
* @param forceRefetch Force refetch the installed plugins to update the cache.
*/
async function getPluginsMap(forceRefetch = false) {
if (!forceRefetch && this.pluginsMap) {
return this.pluginsMap;
}
const plugins = await this.rest({
path: '/wp/v2/plugins',
});
this.pluginsMap = {};
for (const plugin of plugins) {
// Ideally, we should be using sanitize_title() in PHP rather than kebabCase(),
// but we don't have the exact port of it in JS.
// This is a good approximation though.
const slug = (0, change_case_1.paramCase)(plugin.name.toLowerCase());
this.pluginsMap[slug] = plugin.plugin;
}
return this.pluginsMap;
}
exports.getPluginsMap = getPluginsMap;
/**
* Finds a plugin in the plugin map.
*
* Attempts to provide a helpful error message if not found.
*
* @param slug Plugin slug.
* @param pluginsMap Plugins map.
*/
function getPluginFromMap(slug, pluginsMap) {
const plugin = pluginsMap[slug];
if (!plugin) {
for (const key of Object.keys(pluginsMap)) {
if (key.toLowerCase().replace(/-/g, '') ===
slug.toLowerCase().replace(/-/g, '')) {
throw new Error(`The plugin "${slug}" isn't installed. Did you perhaps mean "${key}"?`);
}
}
throw new Error(`The plugin "${slug}" isn't installed`);
}
return plugin;
}
/**
* Activates an installed plugin.
*
* @param this RequestUtils.
* @param slug Plugin slug.
*/
async function activatePlugin(slug) {
const pluginsMap = await this.getPluginsMap();
const plugin = getPluginFromMap(slug, pluginsMap);
await this.rest({
method: 'PUT',
path: `/wp/v2/plugins/${plugin}`,
data: { status: 'active' },
});
}
exports.activatePlugin = activatePlugin;
/**
* Deactivates an active plugin.
*
* @param this RequestUtils.
* @param slug Plugin slug.
*/
async function deactivatePlugin(slug) {
const pluginsMap = await this.getPluginsMap();
const plugin = getPluginFromMap(slug, pluginsMap);
await this.rest({
method: 'PUT',
path: `/wp/v2/plugins/${plugin}`,
data: { status: 'inactive' },
});
}
exports.deactivatePlugin = deactivatePlugin;
//# sourceMappingURL=plugins.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"plugins.js","sourceRoot":"","sources":["../../src/request-utils/plugins.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,6CAAqD;AAOrD;;;;;;GAMG;AACH,KAAK,UAAU,aAAa,CAAsB,YAAY,GAAG,KAAK;IACrE,IAAK,CAAE,YAAY,IAAI,IAAI,CAAC,UAAU,EAAG,CAAC;QACzC,OAAO,IAAI,CAAC,UAAU,CAAC;IACxB,CAAC;IAED,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,IAAI,CAAE;QAChC,IAAI,EAAE,gBAAgB;KACtB,CAAE,CAAC;IACJ,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;IACrB,KAAM,MAAM,MAAM,IAAI,OAAO,EAAG,CAAC;QAChC,+EAA+E;QAC/E,gDAAgD;QAChD,uCAAuC;QACvC,MAAM,IAAI,GAAG,IAAA,uBAAS,EAAE,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,CAAE,CAAC;QACpD,IAAI,CAAC,UAAU,CAAE,IAAI,CAAE,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,CAAC;IACD,OAAO,IAAI,CAAC,UAAU,CAAC;AACxB,CAAC;AAoEQ,sCAAa;AAlEtB;;;;;;;GAOG;AACH,SAAS,gBAAgB,CACxB,IAAY,EACZ,UAAoC;IAEpC,MAAM,MAAM,GAAG,UAAU,CAAE,IAAI,CAAE,CAAC;IAElC,IAAK,CAAE,MAAM,EAAG,CAAC;QAChB,KAAM,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAE,UAAU,CAAE,EAAG,CAAC;YAC/C,IACC,GAAG,CAAC,WAAW,EAAE,CAAC,OAAO,CAAE,IAAI,EAAE,EAAE,CAAE;gBACrC,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAE,IAAI,EAAE,EAAE,CAAE,EACrC,CAAC;gBACF,MAAM,IAAI,KAAK,CACd,eAAgB,IAAK,4CAA6C,GAAI,IAAI,CAC1E,CAAC;YACH,CAAC;QACF,CAAC;QAED,MAAM,IAAI,KAAK,CAAE,eAAgB,IAAK,mBAAmB,CAAE,CAAC;IAC7D,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,KAAK,UAAU,cAAc,CAAsB,IAAY;IAC9D,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;IAC9C,MAAM,MAAM,GAAG,gBAAgB,CAAE,IAAI,EAAE,UAAU,CAAE,CAAC;IAEpD,MAAM,IAAI,CAAC,IAAI,CAAE;QAChB,MAAM,EAAE,KAAK;QACb,IAAI,EAAE,kBAAmB,MAAO,EAAE;QAClC,IAAI,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE;KAC1B,CAAE,CAAC;AACL,CAAC;AAmBuB,wCAAc;AAjBtC;;;;;GAKG;AACH,KAAK,UAAU,gBAAgB,CAAsB,IAAY;IAChE,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;IAC9C,MAAM,MAAM,GAAG,gBAAgB,CAAE,IAAI,EAAE,UAAU,CAAE,CAAC;IAEpD,MAAM,IAAI,CAAC,IAAI,CAAE;QAChB,MAAM,EAAE,KAAK;QACb,IAAI,EAAE,kBAAmB,MAAO,EAAE;QAClC,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE;KAC5B,CAAE,CAAC;AACL,CAAC;AAEuC,4CAAgB"}

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPost = exports.deleteAllPosts = void 0;
/**
* Delete all posts using REST API.
*
* @param this
*/
async function deleteAllPosts() {
// List all posts.
// https://developer.wordpress.org/rest-api/reference/posts/#list-posts
const posts = await this.rest({
path: '/wp/v2/posts',
params: {
per_page: 100,
// All possible statuses.
status: 'publish,future,draft,pending,private,trash',
},
});
// Delete all posts one by one.
// https://developer.wordpress.org/rest-api/reference/posts/#delete-a-post
// "/wp/v2/posts" not yet supports batch requests.
await Promise.all(posts.map((post) => this.rest({
method: 'DELETE',
path: `/wp/v2/posts/${post.id}`,
params: {
force: true,
},
})));
}
exports.deleteAllPosts = deleteAllPosts;
/**
* Creates a new post using the REST API.
*
* @param this
* @param payload Post attributes.
*/
async function createPost(payload) {
const post = await this.rest({
method: 'POST',
path: `/wp/v2/posts`,
data: { ...payload },
});
return post;
}
exports.createPost = createPost;
//# sourceMappingURL=posts.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"posts.js","sourceRoot":"","sources":["../../src/request-utils/posts.ts"],"names":[],"mappings":";;;AAoBA;;;;GAIG;AACI,KAAK,UAAU,cAAc;IACnC,kBAAkB;IAClB,uEAAuE;IACvE,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,IAAI,CAAY;QACxC,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE;YACP,QAAQ,EAAE,GAAG;YACb,yBAAyB;YACzB,MAAM,EAAE,4CAA4C;SACpD;KACD,CAAE,CAAC;IAEJ,+BAA+B;IAC/B,0EAA0E;IAC1E,kDAAkD;IAClD,MAAM,OAAO,CAAC,GAAG,CAChB,KAAK,CAAC,GAAG,CAAE,CAAE,IAAI,EAAG,EAAE,CACrB,IAAI,CAAC,IAAI,CAAE;QACV,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,gBAAiB,IAAI,CAAC,EAAG,EAAE;QACjC,MAAM,EAAE;YACP,KAAK,EAAE,IAAI;SACX;KACD,CAAE,CACH,CACD,CAAC;AACH,CAAC;AA1BD,wCA0BC;AAED;;;;;GAKG;AACI,KAAK,UAAU,UAAU,CAE/B,OAA0B;IAE1B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,IAAI,CAAU;QACrC,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,cAAc;QACpB,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE;KACpB,CAAE,CAAC;IAEJ,OAAO,IAAI,CAAC;AACb,CAAC;AAXD,gCAWC"}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetPreferences = void 0;
/**
* Reset user preferences
*
* @param this Request utils.
*/
async function resetPreferences() {
await this.rest({
path: '/wp/v2/users/me',
method: 'PUT',
data: {
meta: {
persisted_preferences: {},
},
},
});
}
exports.resetPreferences = resetPreferences;
//# sourceMappingURL=preferences.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"preferences.js","sourceRoot":"","sources":["../../src/request-utils/preferences.ts"],"names":[],"mappings":";;;AAKA;;;;GAIG;AACI,KAAK,UAAU,gBAAgB;IACrC,MAAM,IAAI,CAAC,IAAI,CAAE;QAChB,IAAI,EAAE,iBAAiB;QACvB,MAAM,EAAE,KAAK;QACb,IAAI,EAAE;YACL,IAAI,EAAE;gBACL,qBAAqB,EAAE,EAAE;aACzB;SACD;KACD,CAAE,CAAC;AACL,CAAC;AAVD,4CAUC"}

View File

@@ -0,0 +1,130 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.batchRest = exports.getMaxBatchSize = exports.rest = exports.setupRest = void 0;
/**
* External dependencies
*/
const fs = require("fs/promises");
const path_1 = require("path");
/**
* Internal dependencies
*/
const config_1 = require("../config");
function splitRequestsToChunks(requests, chunkSize) {
const arr = [...requests];
const cache = [];
while (arr.length) {
cache.push(arr.splice(0, chunkSize));
}
return cache;
}
async function getAPIRootURL(request) {
// Discover the API root url using link header.
// See https://developer.wordpress.org/rest-api/using-the-rest-api/discovery/#link-header
const response = await request.head(config_1.WP_BASE_URL);
const links = response.headers().link;
const restLink = links?.match(/<([^>]+)>; rel="https:\/\/api\.w\.org\/"/);
if (!restLink) {
throw new Error(`Failed to discover REST API endpoint.
Link header: ${links}`);
}
const [, rootURL] = restLink;
return rootURL;
}
async function setupRest() {
const [nonce, rootURL] = await Promise.all([
this.login(),
getAPIRootURL(this.request),
]);
const { cookies } = await this.request.storageState();
const storageState = {
cookies,
nonce,
rootURL,
};
if (this.storageStatePath) {
await fs.mkdir((0, path_1.dirname)(this.storageStatePath), { recursive: true });
await fs.writeFile(this.storageStatePath, JSON.stringify(storageState), 'utf-8');
}
this.storageState = storageState;
return storageState;
}
exports.setupRest = setupRest;
async function rest(options) {
const { path, ...fetchOptions } = options;
if (!path) {
throw new Error('"path" is required to make a REST call');
}
if (!this.storageState?.nonce || !this.storageState?.rootURL) {
await this.setupRest();
}
const relativePath = path.startsWith('/') ? path.slice(1) : path;
const url = this.storageState.rootURL + relativePath;
try {
const response = await this.request.fetch(url, {
...fetchOptions,
failOnStatusCode: false,
headers: {
'X-WP-Nonce': this.storageState.nonce,
...(fetchOptions.headers || {}),
},
});
const json = await response.json();
if (!response.ok()) {
throw json;
}
return json;
}
catch (error) {
// Nonce in invalid, retry again with a renewed nonce.
if (typeof error === 'object' &&
error !== null &&
Object.prototype.hasOwnProperty.call(error, 'code') &&
error.code === 'rest_cookie_invalid_nonce') {
await this.setupRest();
return this.rest(options);
}
throw error;
}
}
exports.rest = rest;
/**
* Get the maximum batch size for the REST API.
*
* @param this
* @param forceRefetch Force revalidate the cached max batch size.
*/
async function getMaxBatchSize(forceRefetch = false) {
if (!forceRefetch && this.maxBatchSize) {
return this.maxBatchSize;
}
const response = await this.rest({
method: 'OPTIONS',
path: '/batch/v1',
});
this.maxBatchSize = response.endpoints[0].args.requests.maxItems;
return this.maxBatchSize;
}
exports.getMaxBatchSize = getMaxBatchSize;
async function batchRest(requests) {
const maxBatchSize = await this.getMaxBatchSize();
if (requests.length > maxBatchSize) {
const chunks = splitRequestsToChunks(requests, maxBatchSize);
const chunkResponses = await Promise.all(chunks.map((chunkRequests) => this.batchRest(chunkRequests)));
return chunkResponses.flat();
}
const batchResponses = await this.rest({
method: 'POST',
path: '/batch/v1',
data: {
requests,
validation: 'require-all-validate',
},
});
if (batchResponses.failed) {
throw batchResponses;
}
return batchResponses.responses;
}
exports.batchRest = batchRest;
//#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S,CAEvB,QAAwB;IAExB,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,eAAe,EAAE,CAAC;IAElD,IAAK,QAAQ,CAAC,MAAM,GAAG,YAAY,EAAG,CAAC;QACtC,MAAM,MAAM,GAAG,qBAAqB,CAAE,QAAQ,EAAE,YAAY,CAAE,CAAC;QAE/D,MAAM,cAAc,GAAG,MAAM,OAAO,CAAC,GAAG,CACvC,MAAM,CAAC,GAAG,CAAE,CAAE,aAAa,EAAG,EAAE,CAC/B,IAAI,CAAC,SAAS,CAAmB,aAAa,CAAE,CAChD,CACD,CAAC;QAEF,OAAO,cAAc,CAAC,IAAI,EAAE,CAAC;IAC9B,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,IAAI,CAGjC;QACJ,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,WAAW;QACjB,IAAI,EAAE;YACL,QAAQ;YACR,UAAU,EAAE,sBAAsB;SAClC;KACD,CAAE,CAAC;IAEJ,IAAK,cAAc,CAAC,MAAM,EAAG,CAAC;QAC7B,MAAM,cAAc,CAAC;IACtB,CAAC;IAED,OAAO,cAAc,CAAC,SAAS,CAAC;AACjC,CAAC;AAE0C,8BAAS"}

View File

@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateSiteSettings = exports.getSiteSettings = void 0;
/**
* Get the site settings.
*
* @see https://developer.wordpress.org/rest-api/reference/settings/#retrieve-a-site-setting
*
* @param this RequestUtils.
*/
async function getSiteSettings() {
return await this.rest({
path: '/wp/v2/settings',
method: 'GET',
});
}
exports.getSiteSettings = getSiteSettings;
/**
* Update the site settings.
*
* @see https://developer.wordpress.org/rest-api/reference/settings/#update-a-site-setting
*
* @param this RequestUtils.
* @param siteSettings The partial settings payload to update.
*/
async function updateSiteSettings(siteSettings) {
return await this.rest({
path: '/wp/v2/settings',
method: 'POST',
data: siteSettings,
});
}
exports.updateSiteSettings = updateSiteSettings;
//# sourceMappingURL=site-settings.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"site-settings.js","sourceRoot":"","sources":["../../src/request-utils/site-settings.ts"],"names":[],"mappings":";;;AA0BA;;;;;;GAMG;AACI,KAAK,UAAU,eAAe;IACpC,OAAO,MAAM,IAAI,CAAC,IAAI,CAAkB;QACvC,IAAI,EAAE,iBAAiB;QACvB,MAAM,EAAE,KAAK;KACb,CAAE,CAAC;AACL,CAAC;AALD,0CAKC;AAED;;;;;;;GAOG;AACI,KAAK,UAAU,kBAAkB,CAEvC,YAAqC;IAErC,OAAO,MAAM,IAAI,CAAC,IAAI,CAAkB;QACvC,IAAI,EAAE,iBAAiB;QACvB,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,YAAY;KAClB,CAAE,CAAC;AACL,CAAC;AATD,gDASC"}

View File

@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTemplate = exports.deleteAllTemplates = void 0;
const PATH_MAPPING = {
wp_template: '/wp/v2/templates',
wp_template_part: '/wp/v2/template-parts',
};
/**
* Delete all the templates of given type.
*
* @param this
* @param type - Template type to delete.
*/
async function deleteAllTemplates(type) {
const path = PATH_MAPPING[type];
if (!path) {
throw new Error(`Unsupported template type: ${type}.`);
}
const templates = await this.rest({ path });
for (const template of templates) {
if (!template?.id || !template?.wp_id) {
continue;
}
try {
await this.rest({
method: 'DELETE',
path: `${path}/${template.id}`,
params: { force: true },
});
}
catch (responseError) {
// Disable reason - the error provides valuable feedback about issues with tests.
// eslint-disable-next-line no-console
console.warn(`deleteAllTemplates failed to delete template (id: ${template.wp_id}) with the following error`, responseError);
}
}
}
exports.deleteAllTemplates = deleteAllTemplates;
/**
* Creates a new template using the REST API.
*
* @param this
* @param type Template type to delete.
* @param payload Template attributes.
*/
async function createTemplate(type, payload) {
const template = await this.rest({
method: 'POST',
path: PATH_MAPPING[type],
params: { ...payload, type, status: 'publish', is_wp_suggestion: true },
});
return template;
}
exports.createTemplate = createTemplate;
//# sourceMappingURL=templates.js.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,YAAY,CAAE,IAAI,CAAE;QAC1B,MAAM,EAAE,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,gBAAgB,EAAE,IAAI,EAAE;KACvE,CAAE,CAAC;IAEJ,OAAO,QAAQ,CAAC;AACjB,CAAC;AAE4B,wCAAc"}

View File

@@ -0,0 +1,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getThemeGlobalStylesRevisions = exports.getCurrentThemeGlobalStylesPostId = exports.activateTheme = void 0;
const config_1 = require("../config");
const THEMES_URL = new URL('wp-admin/themes.php', config_1.WP_BASE_URL).href;
async function activateTheme(themeSlug) {
let response = await this.request.get(THEMES_URL);
const html = await response.text();
const optionalFolder = '([a-z0-9-]+%2F)?';
// The `optionalFolder` regex part matches paths with a folder,
// so it will return the first match, which might contain a folder.
// First try to honor the included theme slug, that is, without a folder.
let matchGroup = html.match(`action=activate&amp;stylesheet=${encodeURIComponent(themeSlug)}&amp;_wpnonce=[a-z0-9]+`);
// If the theme is not found, try to match the theme slug with a folder.
if (!matchGroup) {
matchGroup = html.match(`action=activate&amp;stylesheet=${optionalFolder}${encodeURIComponent(themeSlug)}&amp;_wpnonce=[a-z0-9]+`);
}
if (!matchGroup) {
if (html.includes(`data-slug="${themeSlug}"`)) {
// The theme is already activated.
return;
}
throw new Error(`The theme "${themeSlug}" is not installed`);
}
const [activateQuery] = matchGroup;
const activateLink = THEMES_URL + `?${activateQuery}`.replace(/&amp;/g, '&');
response = await this.request.get(activateLink);
await response.dispose();
}
exports.activateTheme = activateTheme;
// https://developer.wordpress.org/rest-api/reference/themes/#definition
async function getCurrentThemeGlobalStylesPostId() {
const themes = await this.rest({
path: '/wp/v2/themes',
});
let themeGlobalStylesId = '';
if (themes && themes.length) {
const currentTheme = themes.find(({ status }) => status === 'active');
const globalStylesURL = currentTheme?._links?.['wp:user-global-styles']?.[0]?.href;
if (globalStylesURL) {
themeGlobalStylesId = globalStylesURL?.split('rest_route=/wp/v2/global-styles/')[1];
}
}
return themeGlobalStylesId;
}
exports.getCurrentThemeGlobalStylesPostId = getCurrentThemeGlobalStylesPostId;
/**
* Deletes all post revisions using the REST API.
*
* @param {} this RequestUtils.
* @param {string|number} parentId Post attributes.
*/
async function getThemeGlobalStylesRevisions(parentId) {
// Lists all global styles revisions.
return await this.rest({
path: `/wp/v2/global-styles/${parentId}/revisions`,
params: {
per_page: 100,
},
});
}
exports.getThemeGlobalStylesRevisions = getThemeGlobalStylesRevisions;
//# sourceMappingURL=themes.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"themes.js","sourceRoot":"","sources":["../../src/request-utils/themes.ts"],"names":[],"mappings":";;;AAIA,sCAAwC;AAExC,MAAM,UAAU,GAAG,IAAI,GAAG,CAAE,qBAAqB,EAAE,oBAAW,CAAE,CAAC,IAAI,CAAC;AAEtE,KAAK,UAAU,aAAa,CAE3B,SAAiB;IAEjB,IAAI,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAE,UAAU,CAAE,CAAC;IACpD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IACnC,MAAM,cAAc,GAAG,kBAAkB,CAAC;IAE1C,+DAA+D;IAC/D,mEAAmE;IACnE,yEAAyE;IACzE,IAAI,UAAU,GAAG,IAAI,CAAC,KAAK,CAC1B,kCAAmC,kBAAkB,CACpD,SAAS,CACR,yBAAyB,CAC3B,CAAC;IAEF,wEAAwE;IACxE,IAAK,CAAE,UAAU,EAAG,CAAC;QACpB,UAAU,GAAG,IAAI,CAAC,KAAK,CACtB,kCAAmC,cAAe,GAAI,kBAAkB,CACvE,SAAS,CACR,yBAAyB,CAC3B,CAAC;IACH,CAAC;IAED,IAAK,CAAE,UAAU,EAAG,CAAC;QACpB,IAAK,IAAI,CAAC,QAAQ,CAAE,cAAe,SAAU,GAAG,CAAE,EAAG,CAAC;YACrD,kCAAkC;YAClC,OAAO;QACR,CAAC;QAED,MAAM,IAAI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,CAAC;AACL,CAAC;AAKA,sEAA6B"}

View File

@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteAllUsers = exports.createUser = void 0;
/**
* List all users.
*
* @see https://developer.wordpress.org/rest-api/reference/users/#list-users
* @param this
*/
async function listUsers() {
const response = await this.rest({
method: 'GET',
path: '/wp/v2/users',
params: {
per_page: 100,
},
});
return response;
}
/**
* Add a test user.
*
* @see https://developer.wordpress.org/rest-api/reference/users/#create-a-user
* @param this
* @param user User data to create.
*/
async function createUser(user) {
const userData = {
username: user.username,
email: user.email,
};
if (user.firstName) {
userData.first_name = user.firstName;
}
if (user.lastName) {
userData.last_name = user.lastName;
}
if (user.password) {
userData.password = user.password;
}
if (user.roles) {
userData.roles = user.roles;
}
const response = await this.rest({
method: 'POST',
path: '/wp/v2/users',
data: userData,
});
return response;
}
exports.createUser = createUser;
/**
* Delete a user.
*
* @see https://developer.wordpress.org/rest-api/reference/users/#delete-a-user
* @param this
* @param userId The ID of the user.
*/
async function deleteUser(userId) {
const response = await this.rest({
method: 'DELETE',
path: `/wp/v2/users/${userId}`,
params: { force: true, reassign: 1 },
});
return response;
}
/**
* Delete all users except main root user.
*
* @param this
*/
async function deleteAllUsers() {
const users = await listUsers.bind(this)();
// The users endpoint doesn't support batch request yet.
const responses = await Promise.all(users
// Do not delete neither root user nor the current user.
.filter((user) => user.id !== 1 && user.name !== this.user.username)
.map((user) => deleteUser.bind(this)(user.id)));
return responses;
}
exports.deleteAllUsers = deleteAllUsers;
//# sourceMappingURL=users.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"users.js","sourceRoot":"","sources":["../../src/request-utils/users.ts"],"names":[],"mappings":";;;AA6BA;;;;;GAKG;AACH,KAAK,UAAU,SAAS;IACvB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAY;QAC3C,MAAM,EAAE,KAAK;QACb,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE;YACP,QAAQ,EAA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