@tecgovtnzwebdev/puppeteer 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@tecgovtnzwebdev/puppeteer",
3
- "version": "3.0.1",
3
+ "version": "3.0.2",
4
4
  "description": "puppeteer helpers",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
+ "files": [
9
+ "/cjs"
10
+ ],
8
11
  "scripts": {
9
12
  "test": "echo \"Error: no test specified\" && exit 1"
10
13
  },
package/checkbox.ts DELETED
@@ -1,54 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
- import { repeatUntil } from './wait-until';
3
-
4
- /**
5
- * Is a checkbox checked?
6
- * @param selector The selector for the HTMLInputElement element.
7
- * @param page The puppeteer page.
8
- * @returns true if the checkbox is checked, false otherwise.
9
- */
10
- export async function isChecked(page: puppeteer.Page, selector: string): Promise<boolean> {
11
- const isChecked = await page.evaluate((selector_: string) => {
12
- const checkbox = document.querySelector(selector_) as HTMLInputElement;
13
- if (!checkbox) {
14
- return null;
15
- }
16
- return checkbox.checked;
17
- }, selector);
18
-
19
- if (isChecked === null) {
20
- throw new Error(`Failed to get the checked value of '${selector}'`);
21
- }
22
-
23
- return isChecked;
24
- }
25
-
26
- /**
27
- * Checks a checkbox.
28
- * @param page The puppeteer page.
29
- * @param selector The selector for the HTMLInputElement element.
30
- */
31
- export async function check(page: puppeteer.Page, selector: string) {
32
- await repeatUntil(async () => {
33
- if (await isChecked(page, selector)) {
34
- return true;
35
- }
36
-
37
- await page.click(selector);
38
- }, `Expected checkbox '${selector}' to be checked`);
39
- }
40
-
41
- /**
42
- * Unchecks a checkbox.
43
- * @param page The puppeteer page.
44
- * @param selector The selector for the HTMLInputElement element.
45
- */
46
- export async function uncheck(page: puppeteer.Page, selector: string) {
47
- await repeatUntil(async () => {
48
- if (!(await isChecked(page, selector))) {
49
- return true;
50
- }
51
-
52
- await page.click(selector);
53
- }, `Expected checkbox '${selector}' to be unchecked`);
54
- }
package/click-helper.ts DELETED
@@ -1,31 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
-
3
- /**
4
- * Clicks an element and waits for the page to navigate to a new URL or to reload.
5
- * @param page The puppeteer page.
6
- * @param elementOrSelector The HTMLElement or string selector to click.
7
- * @param waitOptions Optional wait settings.
8
- * @returns A promise which resolves after the page has navigated.
9
- */
10
- export function clickAndWaitForNavigation (page: puppeteer.Page, elementOrSelector: string | puppeteer.ElementHandle, waitOptions?: puppeteer.WaitForOptions) {
11
- if (typeof elementOrSelector === 'string') {
12
- return clickSelectorAndWaitForNavigation(page, elementOrSelector, waitOptions);
13
- }
14
- else {
15
- return clickElementAndWaitForNavigation(page, elementOrSelector, waitOptions);
16
- }
17
- }
18
-
19
- export async function clickSelectorAndWaitForNavigation (page: puppeteer.Page, selector: string, waitOptions?: puppeteer.WaitForOptions) {
20
- return Promise.all([
21
- page.waitForNavigation(waitOptions),
22
- page.click(selector)
23
- ]);
24
- }
25
-
26
- export async function clickElementAndWaitForNavigation (page: puppeteer.Page, element: puppeteer.ElementHandle, waitOptions?: puppeteer.WaitForOptions) {
27
- return Promise.all([
28
- page.waitForNavigation(waitOptions),
29
- element.click()
30
- ]);
31
- }
@@ -1,19 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
- import { getText } from './get-text';
3
-
4
- /**
5
- * Tries to find an element containing the specified text in its innerText value.
6
- * @param page The puppeteer page.
7
- * @param elementSelector The set of elements to search in.
8
- * @param text The text to search for. This value is case-sensitive.
9
- */
10
- export async function findElementWithText(page: puppeteer.Page, elementSelector: string, text: string) {
11
- const elements = (await page.$$(elementSelector)) as puppeteer.ElementHandle<HTMLElement>[];
12
- for (const element of elements) {
13
- const textOfElement = await getText(page, element);
14
- if (textOfElement && textOfElement.includes(text)) {
15
- return element;
16
- }
17
- }
18
- return null;
19
- };
package/get-attribute.ts DELETED
@@ -1,25 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
- import { assertSuccessfulSelector } from './throw-helper';
3
-
4
- /**
5
- * Get the attirbute value from an element.
6
- * @param page The puppeteer page.
7
- * @param elementSelectorOrHandle An element selector or handle to an element.
8
- * @param attributeName The name of the attribute to get the value for.
9
- */
10
- export async function getAttribute (page: puppeteer.Page, elementSelectorOrHandle: string | puppeteer.ElementHandle<Element>, attributeName: string) {
11
- let element: puppeteer.ElementHandle<Element>;
12
- switch (typeof elementSelectorOrHandle) {
13
- case 'string':
14
- element = (await page.waitForSelector(elementSelectorOrHandle))!;
15
- assertSuccessfulSelector(elementSelectorOrHandle, element);
16
- break;
17
- case 'object':
18
- element = elementSelectorOrHandle;
19
- break;
20
- default:
21
- throw new Error(`Unsupported type ${typeof elementSelectorOrHandle}`);
22
- }
23
-
24
- return await page.evaluate((el, att) => el.getAttribute(att), element, attributeName);
25
- };
package/get-text.ts DELETED
@@ -1,21 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
- import { assertSuccessfulSelector } from './throw-helper';
3
-
4
- /**
5
- * Gets the innerText value of an element.
6
- * @param page The puppeteer page.
7
- * @param elementSelectorOrHandle The HTMLElement or string selector to get the innerText value from.
8
- */
9
- export async function getText(page: puppeteer.Page, elementSelectorOrHandle: string | puppeteer.ElementHandle<HTMLElement>) {
10
- switch (typeof elementSelectorOrHandle) {
11
- case 'string':
12
- const element = (await page.waitForSelector(elementSelectorOrHandle))! as puppeteer.ElementHandle<HTMLElement>;
13
- assertSuccessfulSelector(elementSelectorOrHandle, element);
14
-
15
- return (page.evaluate(el => el.innerText, element)) as Promise<string | null | undefined>;
16
- case 'object':
17
- return (page.evaluate(el => el.innerText, elementSelectorOrHandle)) as Promise<string | null | undefined>;
18
- default:
19
- throw new Error(`Unsupported type ${typeof elementSelectorOrHandle}`);
20
- }
21
- }
package/index.ts DELETED
@@ -1,11 +0,0 @@
1
- export * from './checkbox';
2
- export * from './click-helper';
3
- export * from './find-element-with-text';
4
- export * from './get-attribute';
5
- export * from './get-text';
6
- export * from './input';
7
- export * from './is-visible';
8
- export * from './mail-hog';
9
- export * from './select';
10
- export * from './wait-until';
11
- export * from './wait';
package/input.ts DELETED
@@ -1,35 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
- import { assertSuccessfulSelector } from './throw-helper';
3
-
4
- /**
5
- * Gets the value from an HTMLInputElement.
6
- * @param page The puppeteer page.
7
- * @param elementSelectorOrHandle A selector for a <input /> element, or a handle.
8
- */
9
- export async function getValue (page: puppeteer.Page, elementSelectorOrHandle: string | puppeteer.ElementHandle<HTMLInputElement>) {
10
- switch (typeof elementSelectorOrHandle) {
11
- case 'string':
12
- const element = (await page.waitForSelector(elementSelectorOrHandle))! as puppeteer.ElementHandle<HTMLInputElement>;
13
- assertSuccessfulSelector(elementSelectorOrHandle, element);
14
- return page.evaluate(el => el.value, element);
15
- case 'object':
16
- return page.evaluate(el => el.value, elementSelectorOrHandle);
17
- default:
18
- throw new Error(`Unsupported type ${typeof elementSelectorOrHandle}`);
19
- }
20
- }
21
-
22
- /**
23
- * @param selector A selector for a <input /> element.
24
- * @param text The text to type into the <input />.
25
- */
26
- export async function clearAndType (page: puppeteer.Page, selector: string, text: string) {
27
- const input = (await page.$(selector))! as puppeteer.ElementHandle<HTMLInputElement>;
28
- assertSuccessfulSelector(selector, input);
29
-
30
- await page.evaluate(i => {
31
- i.value = '';
32
- }, input);
33
-
34
- await page.type(selector, text);
35
- }
package/is-visible.ts DELETED
@@ -1,17 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
-
3
- export async function isVisible(page: puppeteer.Page, selectorOrElementHandle: string | puppeteer.ElementHandle) {
4
- const element = typeof selectorOrElementHandle === 'string'
5
- ? await page.$(selectorOrElementHandle)
6
- : selectorOrElementHandle;
7
- if (element === null) {
8
- throw new Error(`Failed to find object`);
9
- }
10
-
11
- return page.evaluate((element: Element) => {
12
- const style = getComputedStyle(element);
13
- const rect = element.getBoundingClientRect();
14
-
15
- return style.visibility !== 'hidden' && !!(rect.bottom || rect.top || rect.height || rect.width) && style.opacity !== '0';
16
- }, element);
17
- }
package/mail-hog.ts DELETED
@@ -1,23 +0,0 @@
1
- import nodeFetch from 'node-fetch';
2
- import parseEmail from 'mailparser';
3
-
4
- export class MailHog {
5
- private _mailHogUrl: string;
6
-
7
- constructor (mailHogUrl: string) {
8
- this._mailHogUrl = mailHogUrl;
9
- }
10
-
11
- /**
12
- * Gets email from the mailhog inbox which match the specified 'to' address.
13
- * @param addressNeedle A 'to' address filter.
14
- */
15
- async get (addressNeedle: string) {
16
- const response = await nodeFetch(`${this._mailHogUrl}/api/v2/search?kind=to&query=${encodeURIComponent(addressNeedle)}`);
17
- const messagesJson = await response.json();
18
-
19
- const messages = messagesJson.items as any[];
20
-
21
- return Promise.all(messages.map(message => parseEmail.simpleParser(message.Raw.Data)));
22
- }
23
- }
@@ -1,16 +0,0 @@
1
- trigger: none
2
-
3
- pool:
4
- vmImage: 'ubuntu-latest'
5
-
6
- steps:
7
- - task: NodeTool@1
8
- displayName: "Install nodejs"
9
- inputs:
10
- version: '22.x'
11
- - script: |
12
- echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
13
- npm publish
14
- displayName: "Publish package to NPM"
15
- env:
16
- NPM_TOKEN: $(NPM_TOKEN)
package/select.ts DELETED
@@ -1,82 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
- import { assertSuccessfulSelector } from './throw-helper';
3
-
4
- /**
5
- * Selects one (or many) dropdown items by matching their <option /> text values.
6
- * @param page The puppeteer page.
7
- * @param selector A selector to a <select /> element.
8
- * @param texts A set of <option /> innerText values to match on.
9
- * @returns An array of option values that have been successfully selected.
10
- */
11
- export async function selectWithText (page: puppeteer.Page, selector: string, ...texts: string[]) {
12
- const select = (await page.$(selector))!;
13
- assertSuccessfulSelector(selector, select);
14
-
15
- const options = await select.$$('option');
16
-
17
- // Pull out just the option value and text
18
- const optionData = (await Promise.all(
19
- options.map(async opt => {
20
- const value = await page.evaluate(element => element.value, opt);
21
- const text = (await page.evaluate(element => element.textContent, opt))?.trim();
22
-
23
- return {
24
- value: value.toString(),
25
- text
26
- };
27
- })
28
- )).filter(opt => opt.text && texts.includes(opt.text));
29
-
30
- return select.select(...optionData.map(opt => opt.value));
31
- }
32
-
33
- /**
34
- * Gets the text of the currently selected option of a <select />.
35
- * @param page The puppeteer page.
36
- * @param selector A selector to a <select /> element.
37
- * @returns
38
- */
39
- export async function getTextOfSelectedOption (page: puppeteer.Page, selector: string) {
40
- const select = (await page.$(selector))!;
41
- assertSuccessfulSelector(selector, select);
42
- return page.evaluate((select: HTMLSelectElement) => {
43
- return select.options[select.selectedIndex].text;
44
- }, select as puppeteer.ElementHandle<HTMLSelectElement>);
45
- }
46
-
47
- /**
48
- * Gets the set of text of the currently selected options of a <select /> element.
49
- * @param page The puppeteer page.
50
- * @param selector A selector to a <select /> element.
51
- */
52
- export async function getTextsOfSelectedOptions (page: puppeteer.Page, selector: string) {
53
- return await page.evaluate((selector_: string) => {
54
- const select = document.querySelector(selector_) as HTMLSelectElement | null;
55
-
56
- if (!select) {
57
- throw new Error(`Could find select element by '${selector}'`);
58
- }
59
-
60
- return Array.from(select.options)
61
- .filter(opt => opt.selected)
62
- .map(opt => opt.innerText);
63
- }, selector);
64
- }
65
-
66
- /**
67
- * Uncheck all options of a select.
68
- * @param page The puppeteer page.
69
- * @param selector A selector to a <select /> element.
70
- */
71
- export async function uncheckAll (page: puppeteer.Page, selector: string) {
72
- await page.evaluate((selector_: string) => {
73
- const select = document.querySelector(selector_) as HTMLSelectElement | null;
74
- if (!select) {
75
- throw new Error(`Could not find select with selector '${selector_}'`);
76
- }
77
-
78
- for (const opt of select.options) {
79
- opt.selected = false;
80
- }
81
- }, selector);
82
- }
package/throw-helper.ts DELETED
@@ -1,8 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
-
3
- export function assertSuccessfulSelector(selector: string, element: puppeteer.ElementHandle | null) {
4
- if (element === null) {
5
- throw new Error(`Failed to find object by selector '${selector}'`);
6
- }
7
- return element;
8
- }
package/tsconfig.json DELETED
@@ -1,71 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
-
5
- /* Basic Options */
6
- // "incremental": true, /* Enable incremental compilation */
7
- "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
8
- "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
9
- // "lib": [], /* Specify library files to be included in the compilation. */
10
- // "allowJs": true, /* Allow javascript files to be compiled. */
11
- // "checkJs": true, /* Report errors in .js files. */
12
- // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
13
- "declaration": true, /* Generates corresponding '.d.ts' file. */
14
- // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15
- // "sourceMap": true, /* Generates corresponding '.map' file. */
16
- // "outFile": "./", /* Concatenate and emit output to single file. */
17
- "outDir": "./cjs", /* Redirect output structure to the directory. */
18
- // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
19
- // "composite": true, /* Enable project compilation */
20
- // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21
- // "removeComments": true, /* Do not emit comments to output. */
22
- // "noEmit": true, /* Do not emit outputs. */
23
- // "importHelpers": true, /* Import emit helpers from 'tslib'. */
24
- // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25
- // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
26
-
27
- /* Strict Type-Checking Options */
28
- "strict": true, /* Enable all strict type-checking options. */
29
- // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
30
- // "strictNullChecks": true, /* Enable strict null checks. */
31
- // "strictFunctionTypes": true, /* Enable strict checking of function types. */
32
- // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33
- // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34
- // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35
- // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36
-
37
- /* Additional Checks */
38
- // "noUnusedLocals": true, /* Report errors on unused locals. */
39
- // "noUnusedParameters": true, /* Report errors on unused parameters. */
40
- // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41
- // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42
- // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
43
- // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
44
-
45
- /* Module Resolution Options */
46
- // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
47
- // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
48
- // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
49
- // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
50
- // "typeRoots": [], /* List of folders to include type definitions from. */
51
- // "types": [], /* Type declaration files to be included in compilation. */
52
- // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
53
- "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
54
- // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
55
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
56
-
57
- /* Source Map Options */
58
- // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
59
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60
- // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
61
- // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
62
-
63
- /* Experimental Options */
64
- // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
65
- // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
66
-
67
- /* Advanced Options */
68
- "skipLibCheck": true, /* Skip type checking of declaration files. */
69
- "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
70
- }
71
- }
package/wait-until.ts DELETED
@@ -1,48 +0,0 @@
1
- import * as puppeteer from 'puppeteer';
2
- import { wait } from './wait';
3
-
4
- /**
5
- * @deprecated Use `repeatUntil` instead.
6
- */
7
- export async function waitUntil(page: puppeteer.Page, waitFunction: () => Promise<boolean>, errorMessage = 'Timed out waiting for something', timeOut = 5000, pollInterval = 100) {
8
- const endTime = Date.now() + timeOut;
9
- let conditionMet = await waitFunction();
10
- while (!conditionMet && Date.now() < endTime) {
11
- await new Promise(resolve => setTimeout(resolve, pollInterval));
12
- conditionMet = await waitFunction();
13
- }
14
- if (!conditionMet) {
15
- throw new Error(errorMessage);
16
- }
17
- }
18
-
19
- /**
20
- * Repeats an operation until a specified condition is met or a timeout occurs.
21
- *
22
- * @param page - The Puppeteer `Page` instance to operate on.
23
- * @param operation - An asynchronous function that returns a boolean indicating whether the condition is met.
24
- * @param errorMessage - The error message to throw if the timeout is reached before the condition is met. Defaults to 'Timed out waiting for something'.
25
- * @param timeOut - The maximum time to wait (in milliseconds) before throwing an error. Defaults to 5000 ms.
26
- * @param pollInterval - The interval (in milliseconds) at which the condition is checked. Defaults to 100 ms.
27
- * @throws Will throw an error with the provided `errorMessage` if the condition is not met within the timeout period.
28
- */
29
- export async function repeatUntil(
30
- operation: () => Promise<boolean | undefined>,
31
- errorMessage = 'Timed out waiting for something',
32
- timeOut = 5000,
33
- pollInterval = 100) {
34
- // The absolute end time this operation should run until (in milliseconds)
35
- const endTime = Date.now() + timeOut;
36
-
37
- do {
38
- // Call the operation and check if it returns true
39
- if (await operation()) {
40
- return;
41
- }
42
-
43
- // Wait for the specified poll interval before checking again
44
- await wait(pollInterval);
45
- } while (Date.now() < endTime);
46
-
47
- throw new Error(errorMessage);
48
- }
package/wait.ts DELETED
@@ -1,9 +0,0 @@
1
- /**
2
- * Waits for a specified period of time.
3
- *
4
- * @param period - The time to wait in milliseconds.
5
- * @returns A promise that resolves after the specified period.
6
- */
7
- export const wait = async (period: number) => {
8
- await new Promise(resolve => setTimeout(resolve, period));
9
- }