rewrite scripts into esm

This commit is contained in:
Christian Bromann 2022-06-09 19:49:24 +00:00
parent e0767d02f6
commit ea25891105
25 changed files with 394 additions and 389 deletions

View file

@ -1,8 +1,8 @@
#!/usr/bin/env node
const Octokit = require('@octokit/rest')
const inquirer = require('inquirer')
const shell = require('shelljs')
import Octokit from '@octokit/rest'
import inquirer from 'inquirer'
import shell from 'shelljs'
const activeLTSVersion = 'v6'
const maintenanceLTSVersion = 'v5'

View file

@ -3,17 +3,19 @@
/**
* script to auto update CHANGELOG.md file
*/
const fs = require('node:fs')
const path = require('node:path')
const chalk = require('chalk')
const shell = require('shelljs')
const { Octokit } = require('@octokit/rest')
const { highlight } = require('cli-highlight')
const { Changelog } = require('lerna-changelog')
const { load } = require('lerna-changelog/lib/configuration')
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
import chalk from 'chalk'
import shell from 'shelljs'
import { Octokit } from '@octokit/rest'
import { highlight } from 'cli-highlight'
import { Changelog } from 'lerna-changelog'
import { load } from 'lerna-changelog/lib/configuration'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const root = path.resolve(__dirname, '..')
const { version } = require(path.join(root, 'lerna.json'))
const { version } = await import(path.join(root, 'lerna.json'))
const changelogPath = path.join(root, 'CHANGELOG.md')
if (!process.env.GITHUB_AUTH) {

View file

@ -1,14 +1,17 @@
const PROTOCOLS = {
webdriver: require('../packages/wdio-protocols/protocols/webdriver.json'),
appium: require('../packages/wdio-protocols/protocols/appium.json'),
mjsonwp: require('../packages/wdio-protocols/protocols/mjsonwp.json'),
chromium: require('../packages/wdio-protocols/protocols/chromium.json'),
gecko: require('../packages/wdio-protocols/protocols/gecko.json'),
saucelabs: require('../packages/wdio-protocols/protocols/saucelabs.json'),
selenium: require('../packages/wdio-protocols/protocols/selenium.json'),
jsonwp: require('../packages/wdio-protocols/protocols/jsonwp.json')
import webdriver from '../packages/wdio-protocols/protocols/webdriver.json' assert { type: 'json' }
import appium from '../packages/wdio-protocols/protocols/appium.json' assert { type: 'json' }
import mjsonwp from '../packages/wdio-protocols/protocols/mjsonwp.json' assert { type: 'json' }
import chromium from '../packages/wdio-protocols/protocols/chromium.json' assert { type: 'json' }
import gecko from '../packages/wdio-protocols/protocols/gecko.json' assert { type: 'json' }
import saucelabs from '../packages/wdio-protocols/protocols/saucelabs.json' assert { type: 'json' }
import selenium from '../packages/wdio-protocols/protocols/selenium.json' assert { type: 'json' }
import jsonwp from '../packages/wdio-protocols/protocols/jsonwp.json' assert { type: 'json' }
export const PROTOCOLS = {
webdriver, appium, mjsonwp, chromium,
gecko, saucelabs, selenium, jsonwp
}
const PROTOCOL_NAMES = {
export const PROTOCOL_NAMES = {
appium: 'Appium',
jsonwp: 'JSON Wire Protocol',
mjsonwp: 'Mobile JSON Wire Protocol',
@ -18,15 +21,15 @@ const PROTOCOL_NAMES = {
saucelabs: 'Sauce Labs',
selenium: 'Selenium Standalone'
}
const MOBILE_PROTOCOLS = ['appium', 'mjsonwp']
const VENDOR_PROTOCOLS = ['chromium']
const IGNORED_SUBPACKAGES_FOR_DOCS = [
export const MOBILE_PROTOCOLS = ['appium', 'mjsonwp']
export const VENDOR_PROTOCOLS = ['chromium']
export const IGNORED_SUBPACKAGES_FOR_DOCS = [
'eslint-plugin-wdio',
'wdio-smoke-test-service',
'wdio-smoke-test-reporter'
]
const EDIT_WARNING = `// -------------------- ATTENTION --------------------
export const EDIT_WARNING = `// -------------------- ATTENTION --------------------
// Do not edit this file as it gets auto-generated!
// For edits modify /scripts/templates/*.tpl.d.ts
// Check CONTRIBUTING.md for more details.
@ -34,7 +37,7 @@ const EDIT_WARNING = `// -------------------- ATTENTION --------------------
//
`
const SAUCE_API_DESCRIPTION = `
export const SAUCE_API_DESCRIPTION = `
All commands are only supported on Chrome using Sauce Labs
[Extended Debugging](https://wiki.saucelabs.com/pages/viewpage.action?pageId=70072943)
capabilities. You can enable these by setting the following Sauce options:\n\n
@ -50,7 +53,7 @@ capabilities. You can enable these by setting the following Sauce options:\n\n
\`\`\`
`
const JSONWP_API_DESCRIPTION = `
export const JSONWP_API_DESCRIPTION = `
:::caution depcrecated
The JSONWireProtocol is decrecated and replaced by the [WebDriver](/docs/api/webdriver)
@ -59,17 +62,7 @@ protocol.
:::
`
const PROTOCOL_API_DESCRIPTION = {
export const PROTOCOL_API_DESCRIPTION = {
'saucelabs': SAUCE_API_DESCRIPTION,
'jsonwp': JSONWP_API_DESCRIPTION
}
module.exports = {
PROTOCOLS,
EDIT_WARNING,
PROTOCOL_NAMES,
MOBILE_PROTOCOLS,
VENDOR_PROTOCOLS,
IGNORED_SUBPACKAGES_FOR_DOCS,
PROTOCOL_API_DESCRIPTION
}

View file

@ -1,11 +1,13 @@
#!/usr/bin/env node
const path = require('node:path')
const shell = require('node:shelljs')
const { EventEmitter } = require('node:events')
import url from 'node:url'
import path from 'node:path'
import shell from 'shelljs'
import { EventEmitter } from 'node:events'
const { getSubPackages } = require('./utils/helpers')
import { getSubPackages } from './utils/helpers.js'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const packages = getSubPackages()
/**
@ -22,53 +24,44 @@ const IGNORE_PACKAGES = {
'wdio-types': ['ts-node']
}
;(async () => {
if (process.platform === 'win32') {
return console.log('Skip for windows')
shell.cd(ROOT_DIR)
const brokenPackages = (await Promise.all(packages.map(async (pkg) => {
const packagePath = path.join(ROOT_DIR, 'packages', pkg)
let shellScript = `npx depcheck ${packagePath} --json --ignore-dirs build,tests`
// Workaround for depcheck issue: https://github.com/depcheck/depcheck/issues/526
if (IGNORE_PACKAGES[pkg]) {
shellScript += ` --ignores="${IGNORE_PACKAGES[pkg].join(',')}"`
}
const shellResult = await new Promise((resolve, reject) => shell.exec(shellScript, EXEC_OPTIONS, (code, stdout, stderr) => {
if (stderr) {
console.error('Error :', stderr)
return reject(new Error(stderr))
}
return resolve(stdout)
}))
const result = JSON.parse(shellResult)
result.package = pkg
result.packagePath = packagePath
return result
}))).filter((result) => Object.keys(result.missing).length)
if (brokenPackages.length) {
let message = ''
for (const result of brokenPackages) {
message += `🚨 Broken Dependencies in ${result.package} 🚨\n`
for (const [missingPkg, usage] of Object.entries(result.missing)) {
message += ` * ${missingPkg} missing, used in:\n`
message += usage.map((file) => ` * ${file}`).join('\n')
message += '\n'
}
}
shell.cd(ROOT_DIR)
const brokenPackages = (await Promise.all(packages.map(async (pkg) => {
const packagePath = path.join(ROOT_DIR, 'packages', pkg)
let shellScript = `npx depcheck ${packagePath} --json --ignore-dirs build,tests`
// Workaround for depcheck issue: https://github.com/depcheck/depcheck/issues/526
if (IGNORE_PACKAGES[pkg]) {
shellScript += ` --ignores="${IGNORE_PACKAGES[pkg].join(',')}"`
}
const shellResult = await new Promise((resolve, reject) => shell.exec(shellScript, EXEC_OPTIONS, (code, stdout, stderr) => {
if (stderr) {
console.error('Error :', stderr)
return reject(new Error(stderr))
}
return resolve(stdout)
}))
const result = JSON.parse(shellResult)
result.package = pkg
result.packagePath = packagePath
return result
}))).filter((result) => Object.keys(result.missing).length)
if (brokenPackages.length) {
let message = ''
for (const result of brokenPackages) {
message += `🚨 Broken Dependencies in ${result.package} 🚨\n`
for (const [missingPkg, usage] of Object.entries(result.missing)) {
message += ` * ${missingPkg} missing, used in:\n`
message += usage.map((file) => ` * ${file}`).join('\n')
message += '\n'
}
}
console.log(message)
process.exit(1)
}
console.log('Depcheck passed!')
process.exit(0)
})().catch((err) => {
console.error('Depcheck failed:', err.stack)
console.log(message)
process.exit(1)
})
}
console.log('Depcheck passed!')
process.exit(0)

View file

@ -1,19 +1,31 @@
const fs = require('fs-extra')
const path = require('node:path')
const urljoin = require('url-join')
import fs from 'fs-extra'
import url from 'node:url'
import path from 'node:path'
import urljoin from 'url-join'
const { downloadFromGitHub } = require('../utils')
const { buildPreface } = require('../utils/helpers')
const reporters3rdParty = require('./3rd-party/reporters.json')
const services3rdParty = require('./3rd-party/services.json')
const api3rdParty = require('./3rd-party/api.json')
import { downloadFromGitHub } from '../utils/index.js'
import { buildPreface } from '../utils/helpers.js'
import reporters3rdParty from './3rd-party/reporters.json' assert { type: 'json' }
import services3rdParty from './3rd-party/services.json' assert { type: 'json' }
import api3rdParty from './3rd-party/api.json' assert { type: 'json' }
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const plugins = [{
category: 'docs', namePlural: 'Reporter', nameSingular: 'Reporter', packages3rdParty: reporters3rdParty
category: 'docs',
namePlural: 'Reporter',
nameSingular: 'Reporter',
packages3rdParty: reporters3rdParty
}, {
category: 'docs', namePlural: 'Services', nameSingular: 'Service', packages3rdParty: services3rdParty
category: 'docs',
namePlural: 'Services',
nameSingular: 'Service',
packages3rdParty: services3rdParty
}, {
category: 'api', namePlural: 'Testrunner', nameSingular: '', packages3rdParty: api3rdParty
category: 'api',
namePlural: 'Testrunner',
nameSingular: '',
packages3rdParty: api3rdParty
}]
const githubReadme = '/README.md'
@ -29,7 +41,7 @@ const DOCS_ROOT_DIR = path.join(PROJECT_ROOT_DIR, 'website', 'docs')
* Generate docs for 3rd party reporters and services
* @param {object} sidebars website/sidebars
*/
exports.generate3rdPartyDocs = async (sidebars) => {
export async function generate3rdPartyDocs (sidebars) {
for (const { category, namePlural, nameSingular, packages3rdParty } of plugins) {
const categoryDir = path.join(DOCS_ROOT_DIR, category === 'api' ? 'api' : '')
await fs.ensureDir(categoryDir)

View file

@ -1,7 +1,10 @@
const fs = require('node:fs')
const path = require('node:path')
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
exports.copyContributingDocs = async function () {
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
export async function copyContributingDocs () {
const basePath = path.join(__dirname, '..', '..')
const docsPath = path.join(basePath, 'CONTRIBUTING.md')
const newDocsPath = path.join(basePath, 'website', 'docs', 'Contribute.md')

View file

@ -1,8 +1,11 @@
const fs = require('node:fs')
const path = require('node:path')
const { downloadFromGitHub } = require('../utils')
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
import { downloadFromGitHub } from '../utils/index.js'
exports.downloadAwesomeResources = async function () {
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
export async function downloadAwesomeResources () {
const basePath = path.join(__dirname, '..', '..')
const newDocsPath = path.join(basePath, 'website', 'community', 'Resources.md')
const content = await downloadFromGitHub('https://raw.githubusercontent.com/webdriverio-community/awesome-webdriverio', 'main')

View file

@ -1,14 +1,17 @@
#!/usr/bin/env node
const fs = require('node:fs')
const path = require('node:path')
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
const sidebars = require('../../website/_sidebars.json')
const { generateProtocolDocs } = require('./protocolDocs')
const { generateWdioDocs } = require('./wdioDocs')
const { generateReportersAndServicesDocs } = require('./packagesDocs')
const { generate3rdPartyDocs } = require('./3rdPartyDocs')
const { copyContributingDocs } = require('./copyContributingDocs')
const { downloadAwesomeResources } = require('./downloadAwesomeResources')
import sidebars from '../../website/_sidebars.json' assert { type: 'json' }
import { generateProtocolDocs } from './protocolDocs.js'
import { generateWdioDocs } from './wdioDocs.js'
import { generateReportersAndServicesDocs } from './packagesDocs.js'
import { generate3rdPartyDocs } from './3rdPartyDocs.js'
import { copyContributingDocs } from './copyContributingDocs.js'
import { downloadAwesomeResources } from './downloadAwesomeResources.js'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
function print (title) {
console.log(`
@ -17,35 +20,6 @@ ${title}
//////////////////////////////////////////////////`)
}
async function generateDocs() {
/**
* NOTE: all generate docs functions mutate `sidebars` object!
*/
try {
print('Generate Protocol Docs')
generateProtocolDocs(sidebars)
print('Generate WebdriverIO Docs')
await generateWdioDocs(sidebars)
print('Generate Reporter & Services Docs')
generateReportersAndServicesDocs(sidebars)
await generate3rdPartyDocs(sidebars)
print('Copy over Contributing Guidelines')
await copyContributingDocs()
print('Copy over Awesome Resources')
await downloadAwesomeResources()
writeSidebars(sidebars)
} catch (err) {
// eslint-disable-next-line no-console
console.error(err)
process.exit(1)
}
// eslint-disable-next-line no-console
console.log('=== Docs generated successfully! ===')
}
function writeSidebars(sidebars) {
fs.writeFileSync(
path.join(__dirname, '..', '..', 'website', 'sidebars.json'),
@ -54,4 +28,29 @@ function writeSidebars(sidebars) {
)
}
generateDocs()
/**
* NOTE: all generate docs functions mutate `sidebars` object!
*/
try {
print('Generate Protocol Docs')
generateProtocolDocs(sidebars)
print('Generate WebdriverIO Docs')
await generateWdioDocs(sidebars)
print('Generate Reporter & Services Docs')
generateReportersAndServicesDocs(sidebars)
await generate3rdPartyDocs(sidebars)
print('Copy over Contributing Guidelines')
await copyContributingDocs()
print('Copy over Awesome Resources')
await downloadAwesomeResources()
writeSidebars(sidebars)
// eslint-disable-next-line no-console
console.log('=== Docs generated successfully! ===')
} catch (err) {
// eslint-disable-next-line no-console
console.error(err)
process.exit(1)
}

View file

@ -1,9 +1,11 @@
const fs = require('node:fs')
const path = require('node:path')
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
const { IGNORED_SUBPACKAGES_FOR_DOCS } = require('../constants')
const { getSubPackages, buildPreface } = require('../utils/helpers')
import { IGNORED_SUBPACKAGES_FOR_DOCS } from '../constants.js'
import { getSubPackages, buildPreface } from '../utils/helpers.js'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const plugins = {
reporter: ['Reporter', 'Reporter'],
service: ['Services', 'Service']
@ -13,7 +15,7 @@ const plugins = {
* Generate docs for reporter and services
* @param {object} sidebars website/sidebars
*/
exports.generateReportersAndServicesDocs = (sidebars) => {
export function generateReportersAndServicesDocs (sidebars) {
const packages = getSubPackages(IGNORED_SUBPACKAGES_FOR_DOCS)
for (const [type, [namePlural, nameSingular]] of Object.entries(plugins)) {

View file

@ -1,12 +1,20 @@
const fs = require('fs-extra')
const path = require('node:path')
const ejs = require('ejs')
import path from 'node:path'
import url from 'node:url'
import { createRequire } from 'node:module'
import fs from 'fs-extra'
import ejs from 'ejs'
import {
PROTOCOLS, PROTOCOL_NAMES, MOBILE_PROTOCOLS, VENDOR_PROTOCOLS,
PROTOCOL_API_DESCRIPTION
} from '../constants.js'
const require = createRequire(import.meta.url)
const { repoUrl } = require('../../website/docusaurus.config.js')
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const TEMPLATE_PATH = path.join(__dirname, '..', 'templates', 'api.tpl.ejs')
const {
PROTOCOLS, PROTOCOL_NAMES, MOBILE_PROTOCOLS, VENDOR_PROTOCOLS, PROTOCOL_API_DESCRIPTION
} = require('../constants')
const category = 'api'
const PROJECT_ROOT_DIR = path.join(__dirname, '..', '..', 'website')
@ -16,7 +24,7 @@ const API_DOCS_ROOT_DIR = path.join(PROJECT_ROOT_DIR, 'docs', category)
* Generate Protocol docs
* @param {object} sidebars website/sidebars
*/
exports.generateProtocolDocs = (sidebars) => {
export function generateProtocolDocs (sidebars) {
fs.ensureDirSync(API_DOCS_ROOT_DIR)
const template = fs.readFileSync(TEMPLATE_PATH, 'utf8')
const protocolDocs = {}

View file

@ -1,10 +1,13 @@
const fs = require('node:fs')
const path = require('node:path')
const markdox = require('markdox')
const { promisify } = require('node:util')
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
import markdox from 'markdox'
import { promisify } from 'node:util'
const formatter = require('../utils/formatter')
const compiler = require('../utils/compiler')
import formatter from '../utils/formatter.js'
import compiler from '../utils/compiler.js'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const TEMPLATE_PATH = path.join(__dirname, '..', 'templates', 'api.tpl.ejs')
const MARKDOX_OPTIONS = {
formatter: formatter,
@ -18,7 +21,7 @@ const processDocs = promisify(markdox.process)
* Generate WebdriverIO docs
* @param {object} sidebars website/sidebars
*/
exports.generateWdioDocs = async (sidebars) => {
export async function generateWdioDocs (sidebars) {
const COMMAND_DIR = path.join(__dirname, '..', '..', 'packages', 'webdriverio', 'src', 'commands')
const COMMANDS = {
browser: fs.readdirSync(path.join(COMMAND_DIR, 'browser')),

View file

@ -3,16 +3,19 @@
* This script generates new sub package with initial structure and files
*/
const fs = require('node:fs')
const path = require('node:path')
const shell = require('shelljs')
const inquirer = require('inquirer')
const packageType = ['reporter', 'service', 'runner', 'framework']
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
import shell from 'shelljs'
import inquirer from 'inquirer'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const questions = [{
type: 'list',
name: 'packageType',
message: 'Select sub package type:',
choices: packageType,
choices: ['reporter', 'service', 'runner', 'framework'],
default: 'reporter'
}, {
type: 'input',
@ -20,21 +23,18 @@ const questions = [{
message: 'Provide sub package name:'
}]
inquirer.prompt(questions).then(answers => {
const { packageName, packageType } = answers
const packagesDir = path.join(__dirname, '..', 'packages')
const fullPackageName = `wdio-${packageName}-${packageType}`
const fullScopedPackageName = `@wdio/${packageName}-${packageType}`
const { packageName, packageType } = await inquirer.prompt(questions)
const packagesDir = path.join(__dirname, '..', 'packages')
const fullPackageName = `wdio-${packageName}-${packageType}`
const fullScopedPackageName = `@wdio/${packageName}-${packageType}`
const mainPackageFolder = path.join(packagesDir, fullPackageName)
const mainPackageFolderFiles = [
{
name: '.npmignore',
content: 'src\ntests\ntsconfig.json\ntsconfig.prod.json'
},
{
name: 'tsconfig.json',
content: `{
const mainPackageFolder = path.join(packagesDir, fullPackageName)
const mainPackageFolderFiles = [{
name: '.npmignore',
content: 'src\ntests\ntsconfig.json\ntsconfig.prod.json'
}, {
name: 'tsconfig.json',
content: `{
"extends": "../../tsconfig",
"compilerOptions": {
"baseUrl": ".",
@ -45,10 +45,9 @@ inquirer.prompt(questions).then(answers => {
"src/**/*"
]
}`
},
{
name: 'tsconfig.prod.json',
content: `{
}, {
name: 'tsconfig.prod.json',
content: `{
"extends": "../../tsconfig.prod",
"compilerOptions": {
"baseUrl": ".",
@ -59,17 +58,29 @@ inquirer.prompt(questions).then(answers => {
"src/**/*"
]
}`
},
{
name: 'package.json',
content: `{
}, {
name: 'package.json',
content: `{
"name": "${fullScopedPackageName}",
"version": "0.0.0",
"description": "A WebdriverIO ${packageType} that <provide ${packageType} description>",
"author": "Christian Bromann <mail@bromann.dev>",
"author": "<your-name> <your@email.com>",
"homepage": "https://github.com/webdriverio/webdriverio/tree/main/packages/${fullPackageName}",
"license": "MIT",
"main": "./build/index",
"main": "./build/index.cjs.js",
"type": "module",
"module": "./build/index.js",
"exports": {
".": [
{
"import": "./build/index.js",
"require": "./build/index.cjs.js"
},
"./build/index.cjs.js"
]
},
"types": "./build/index.d.ts",
"typeScriptVersion": "3.8.3",
"engines": {
"node": ">=12.0.0"
},
@ -91,68 +102,53 @@ inquirer.prompt(questions).then(answers => {
"access": "public"
}
}`
},
{
name: 'README.md',
content: `WebdriverIO ${packageName.toUpperCase()} ${packageType.charAt(0).toUpperCase()}${packageType.substr(1)}\n========================`
}
]
}, {
name: 'README.md',
content: `WebdriverIO ${packageName.toUpperCase()} ${packageType.charAt(0).toUpperCase()}${packageType.substr(1)}\n========================`
}]
const srcPackageFolder = path.join(mainPackageFolder, 'src')
const srcPackageFolderFiles = [
{
name: 'index.js',
content: 'export default {}'
}
]
const srcPackageFolder = path.join(mainPackageFolder, 'src')
const srcPackageFolderFiles = [{
name: 'index.js',
content: 'export default {}'
}]
const testsPackageFolder = path.join(mainPackageFolder, 'tests')
const testsPackageFolderFiles = [
{
name: '.eslintrc',
content: `{
"env": {
"jest": true
}
}`
},
{
name: 'example.test.js',
content: `describe('Unit test example', () => {
const testsPackageFolder = path.join(mainPackageFolder, 'tests')
const testsPackageFolderFiles = [{
name: 'example.test.ts',
content: `import { describe, it, expect } from 'vitest'
describe('Unit test example', () => {
it('Test #1', () => {
expect(1).toBe(1)
})
})`
}
]
}]
const existingPackages = fs.readdirSync(packagesDir)
.map(name => path.join(packagesDir, name))
.filter(source => fs.lstatSync(source).isDirectory())
const existingPackages = fs.readdirSync(packagesDir)
.map(name => path.join(packagesDir, name))
.filter(source => fs.lstatSync(source).isDirectory())
const createFile = (file, content) => {
shell.touch(file)
shell.ShellString(content).to(file)
}
const createFile = (file, content) => {
shell.touch(file)
shell.ShellString(content).to(file)
}
if (packageName === '') {
throw new Error('Package name can not be empty')
}
if (packageName === '') {
throw new Error('Package name can not be empty')
}
if (existingPackages.includes(mainPackageFolder)) {
throw new Error(`Package '${fullPackageName}' already exists. Please choose another name.`)
}
if (existingPackages.includes(mainPackageFolder)) {
throw new Error(`Package '${fullPackageName}' already exists. Please choose another name.`)
}
// create package structure
[mainPackageFolder, srcPackageFolder, testsPackageFolder].map(folder => shell.mkdir(folder))
// create package structure
[mainPackageFolder, srcPackageFolder, testsPackageFolder].map(folder => shell.mkdir(folder))
// create main folder files
mainPackageFolderFiles.map(file => createFile(path.join(mainPackageFolder, file.name), file.content))
// create main folder files
mainPackageFolderFiles.map(file => createFile(path.join(mainPackageFolder, file.name), file.content))
// create src folder files
srcPackageFolderFiles.map(file => createFile(path.join(srcPackageFolder, file.name), file.content))
// create src folder files
srcPackageFolderFiles.map(file => createFile(path.join(srcPackageFolder, file.name), file.content))
// create tests folder files
testsPackageFolderFiles.map(file => createFile(path.join(testsPackageFolder, file.name), file.content))
// eslint-disable-next-line no-console
}).catch(err => console.error(err))
// create tests folder files
testsPackageFolderFiles.map(file => createFile(path.join(testsPackageFolder, file.name), file.content))

View file

@ -3,8 +3,11 @@
* This script initialises the playground by linking all package into the /test directory
*/
const path = require('node:path')
const shell = require('shelljs')
import url from 'node:url'
import path from 'node:path'
import shell from 'shelljs'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const packagesDir = path.join(__dirname, '..', 'packages')
const nodeModulesDir = path.join(__dirname, '..', 'packages', 'node_modules')

3
scripts/package.json Normal file
View file

@ -0,0 +1,3 @@
{
"type": "module"
}

View file

@ -4,9 +4,9 @@
* after the release. This script is a little helper to ensure
* this happens.
*/
const shell = require('shelljs')
import shell from 'shelljs'
const { version } = require('../lerna.json')
import pkg from '../lerna.json' assert { type: 'json' }
console.log('\nPushing release tag...')
shell.exec(`git push origin refs/tags/v${version} -f --no-verify`)
shell.exec(`git push origin refs/tags/v${pkg.version} -f --no-verify`)

View file

@ -0,0 +1,28 @@
export const paramTypeMap = {
createWindow: [{
name: 'type',
type: "'tab' | 'window'"
}]
}
export const foo = {
newSession: 'SessionReturn',
status: 'StatusReturn',
getTimeouts: 'Timeouts',
createWindow: 'WindowHandle',
getWindowRect: 'RectReturn',
setWindowRect: 'RectReturn',
maximizeWindow: 'RectReturn',
minimizeWindow: 'RectReturn',
fullscreenWindow: 'RectReturn',
getElementRect: 'RectReturn',
getNamedCookie: 'Cookie',
getStrings: 'StringsReturn',
getSettings: 'SettingsReturn',
getWindowSize: 'RectReturn',
findElement: 'ElementReference',
findElements: 'ElementReference[]',
findElementFromElement: 'ElementReference',
findElementsFromElement: 'ElementReference[]',
getAllCookies: 'Cookie[]'
}

View file

@ -1,14 +1,13 @@
#!/usr/bin/env node
const fs = require('node:fs')
const path = require('node:path')
const camelCase = require('camelcase')
import fs from 'node:fs'
import path from 'node:path'
import camelCase from 'camelcase'
const { PROTOCOLS } = require('../constants')
import { paramTypeMap, returnTypeMap } from './constants.js'
import { PROTOCOLS } from '../constants'
const TYPINGS_PATH = path.join(__dirname, '..', '..', 'packages', 'wdio-protocols', 'src', 'commands')
const returnTypeMap = require('./webdriver-return-types.json')
const paramTypeMap = require('./webdriver-param-types.json')
const INDENTATION = ' '.repeat(4)
const EXAMPLE_INDENTATION = `${INDENTATION} * `

View file

@ -1,8 +0,0 @@
{
"createWindow": [
{
"name": "type",
"type": "'tab' | 'window'"
}
]
}

View file

@ -1,21 +0,0 @@
{
"newSession": "SessionReturn",
"status": "StatusReturn",
"getTimeouts": "Timeouts",
"createWindow": "WindowHandle",
"getWindowRect": "RectReturn",
"setWindowRect": "RectReturn",
"maximizeWindow": "RectReturn",
"minimizeWindow": "RectReturn",
"fullscreenWindow": "RectReturn",
"getElementRect": "RectReturn",
"getNamedCookie": "Cookie",
"getStrings": "StringsReturn",
"getSettings": "SettingsReturn",
"getWindowSize": "RectReturn",
"findElement": "ElementReference",
"findElements": "ElementReference[]",
"findElementFromElement": "ElementReference",
"findElementsFromElement": "ElementReference[]",
"getAllCookies": "Cookie[]"
}

View file

@ -1,15 +1,21 @@
#!/usr/bin/env node
const fs = require('node:fs')
const path = require('node:path')
const { promisify } = require('node:util')
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
import { promisify } from 'node:util'
import { createRequire } from 'node:module'
const mime = require('mime-types')
const readDir = require('recursive-readdir')
import mime from 'mime-types'
import readDir from 'recursive-readdir'
import pkg from '../lerna.json' assert { type: 'json' }
const require = createRequire(import.meta.url)
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const { S3, CloudFront } = require('aws-sdk')
const { version: PKG_VERSION } = require('../lerna.json')
const PKG_VERSION = pkg.version
const PRODUCTION_VERSION = 'v7'
const DISTRIBUTION_ID = process.env.DISTRIBUTION_ID
const BUCKET_NAME = 'webdriver.io'
@ -18,74 +24,68 @@ const UPLOAD_OPTIONS = { partSize: 10 * 1024 * 1024, queueSize: 1 }
const IGNORE_FILE_SUFFIX = ['*.rb']
/* eslint-disable no-console */
;(async () => {
const timestamp = Date.now()
const s3 = new S3()
const files = await readDir(BUILD_DIR, IGNORE_FILE_SUFFIX)
const timestamp = Date.now()
const s3 = new S3()
const files = await readDir(BUILD_DIR, IGNORE_FILE_SUFFIX)
const version = `v${PKG_VERSION.split('.')[0]}`
const bucketName = version === PRODUCTION_VERSION ? BUCKET_NAME : `${version}.${BUCKET_NAME}`
const version = `v${PKG_VERSION.split('.')[0]}`
const bucketName = version === PRODUCTION_VERSION ? BUCKET_NAME : `${version}.${BUCKET_NAME}`
/**
* upload assets
*/
console.log(`Uploading ${BUILD_DIR} to S3 bucket ${bucketName}`)
await Promise.all(files.map((file) => new Promise((resolve, reject) => s3.upload({
Bucket: bucketName,
Key: file.replace(BUILD_DIR + '/', ''),
Body: fs.createReadStream(file),
ContentType: mime.lookup(file),
ACL: 'public-read'
}, UPLOAD_OPTIONS, (err, res) => {
if (err) {
console.error(`Couldn't upload file ${file}: ${err.stack}`)
return reject(err)
}
console.log(`${file} uploaded`)
return resolve(res)
}))))
/**
* invalidate distribution
*/
const distributionId = version === PRODUCTION_VERSION
? DISTRIBUTION_ID
: process.env[`DISTRIBUTION_ID_${version.toUpperCase()}`]
if (distributionId) {
console.log(`Invalidate objects from distribution ${distributionId}`)
const cloudfront = new CloudFront()
const { Invalidation } = await promisify(cloudfront.createInvalidation.bind(cloudfront))({
DistributionId: distributionId,
InvalidationBatch: {
CallerReference: `${timestamp}`,
Paths: { Quantity: 1, Items: ['/*'] }
}
})
console.log(`Created new invalidation with ID ${Invalidation.Id}`)
/**
* upload assets
*/
console.log(`Uploading ${BUILD_DIR} to S3 bucket ${bucketName}`)
await Promise.all(files.map((file) => new Promise((resolve, reject) => s3.upload({
Bucket: bucketName,
Key: file.replace(BUILD_DIR + '/', ''),
Body: fs.createReadStream(file),
ContentType: mime.lookup(file),
ACL: 'public-read'
}, UPLOAD_OPTIONS, (err, res) => {
if (err) {
console.error(`Couldn't upload file ${file}: ${err.stack}`)
return reject(err)
}
/**
* delete old assets
*/
const objects = await promisify(s3.listObjects.bind(s3))({
Bucket: bucketName
console.log(`${file} uploaded`)
return resolve(res)
}))))
/**
* invalidate distribution
*/
const distributionId = version === PRODUCTION_VERSION
? DISTRIBUTION_ID
: process.env[`DISTRIBUTION_ID_${version.toUpperCase()}`]
if (distributionId) {
console.log(`Invalidate objects from distribution ${distributionId}`)
const cloudfront = new CloudFront()
const { Invalidation } = await promisify(cloudfront.createInvalidation.bind(cloudfront))({
DistributionId: distributionId,
InvalidationBatch: {
CallerReference: `${timestamp}`,
Paths: { Quantity: 1, Items: ['/*'] }
}
})
const objectsToDelete = objects.Contents.filter((obj) => (
(obj.LastModified)).getTime() < timestamp)
console.log(`Found ${objectsToDelete.length} outdated objects to remove...`)
console.log(`Created new invalidation with ID ${Invalidation.Id}`)
}
await Promise.all(objectsToDelete.map((obj) => (
promisify(s3.deleteObject.bind(s3))({
Bucket: bucketName,
Key: obj.Key
})
)))
console.log('Deleted obsolete items successfully')
/**
* delete old assets
*/
const objects = await promisify(s3.listObjects.bind(s3))({
Bucket: bucketName
})
const objectsToDelete = objects.Contents.filter((obj) => (
(obj.LastModified)).getTime() < timestamp)
console.log(`Found ${objectsToDelete.length} outdated objects to remove...`)
return
})().then(
() => console.log('Successfully updated webdriver.io docs'),
(err) => console.error(`Error uploading docs: ${err.stack}`)
)
await Promise.all(objectsToDelete.map((obj) => (
promisify(s3.deleteObject.bind(s3))({
Bucket: bucketName,
Key: obj.Key
})
)))
console.log('Deleted obsolete items successfully')
console.log('Successfully updated webdriver.io docs')
/* eslint-enable no-console */

View file

@ -1,3 +1,3 @@
module.exports = function (filepath, data) {
export default function (filepath, data) {
return data.slice(0, data.indexOf('export default function'))
}

View file

@ -1,8 +1,10 @@
const path = require('node:path')
import path from 'node:path'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const { customFields } = require('../../website/docusaurus.config.js')
module.exports = function (docfile) {
export default function (docfile) {
const javadoc = docfile.javadoc[0]
let type = (javadoc.ctx && javadoc.ctx.type)

View file

@ -1,12 +1,15 @@
const shell = require('shelljs')
const path = require('node:path')
import shell from 'shelljs'
import path from 'node:path'
import url from 'node:url'
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
/**
* fetch all sub package names from the package directory
* @param {string[]} ignorePackages a list of packages to be ignored
* @returns {string[]} a list of sub packages
*/
const getSubPackages = (ignorePackages = []) => shell.ls(path.join(__dirname, '..', '..', 'packages')).filter((pkg) => (
export const getSubPackages = (ignorePackages = []) => shell.ls(path.join(__dirname, '..', '..', 'packages')).filter((pkg) => (
/**
* ignore node_modules directory that is created by the link script to test the
* wdio test runner
@ -18,7 +21,7 @@ const getSubPackages = (ignorePackages = []) => shell.ls(path.join(__dirname, '.
!ignorePackages.includes(pkg)
))
function buildPreface(id, title, titleSuffix, editUrl) {
export function buildPreface(id, title, titleSuffix, editUrl) {
return [
'---',
`id: ${id}`,
@ -29,5 +32,3 @@ function buildPreface(id, title, titleSuffix, editUrl) {
'import TabItem from \'@theme/TabItem\';\n'
]
}
module.exports = { getSubPackages, buildPreface }

View file

@ -1,5 +1,3 @@
const request = require('request')
const githubReadme = '/README.md'
const githubHost = 'https://github.com/'
const githubRawHost = 'https://raw.githubusercontent.com/'
@ -10,24 +8,10 @@ const githubRawHost = 'https://raw.githubusercontent.com/'
* @param {string} location file location in repo
* @return {Promise<string>} readme content
*/
function downloadFromGitHub(githubUrl, branch, location = githubReadme) {
return new Promise((resolve, reject) => {
const url = `${githubUrl}/${branch}${location}`.replace(githubHost, githubRawHost)
// eslint-disable-next-line no-console
console.log(`Downloading: ${url}`)
request.get(url, (err, httpResponse, body) => {
if (err || httpResponse.statusCode !== 200 || !body) {
return reject({
err,
statusCode: httpResponse.statusCode,
body
})
}
resolve(body)
})
})
}
module.exports = {
downloadFromGitHub
export async function downloadFromGitHub(githubUrl, branch, location = githubReadme) {
const url = `${githubUrl}/${branch}${location}`.replace(githubHost, githubRawHost)
// eslint-disable-next-line no-console
console.log(`Downloading: ${url}`)
const res = await fetch(url)
return await res.text()
}