Skip to content

Commit

Permalink
Convert ts (#45)
Browse files Browse the repository at this point in the history
* chore: update git ignore

* tools: initial convert to ts

* tools: migrate ts files

* chore: add ts build to release pipeline

* chore: remove old config file

* chore: remove reference to old config types

* chore: add changeset

* chore: update changeset
  • Loading branch information
heyMP authored Aug 3, 2024
1 parent 41365b8 commit a242c0f
Show file tree
Hide file tree
Showing 13 changed files with 305 additions and 141 deletions.
10 changes: 10 additions & 0 deletions .changeset/swift-planets-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"@heymp/scratchpad": minor
---

⚠️ Change config types directory.

```js
export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
});
```
3 changes: 3 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ jobs:
- name: Install Dependencies
run: yarn

- name: Build TS
run: yarn run build

- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
node_modules

src/**.js
src/**.d.ts
src/**.d.ts.map
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ in your `.ts` files:
An alternative to using the CLI flags, you can create `scratchpad.config.js`.

```js
export default /** @type {import('@heymp/scratchpad/config').Config} */ ({
export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
devtools: true,
url: 'https://internal-rhdc-review-itmktgwsa-hklqgj.apps.int.spoke.preprod.us-west-2.aws.paas.redhat.com/en/test-page-2',
headless: true,
Expand All @@ -120,7 +120,7 @@ This allows you to interact with the Playwright API to perform actions like bloc
network requests or navigating to different urls.

```js
export default /** @type {import('@heymp/scratchpad/config').Config} */ ({
export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
devtools: true,
playwright: async (args) => {
const { context, page } = args;
Expand Down
89 changes: 1 addition & 88 deletions bin/cli.js
Original file line number Diff line number Diff line change
@@ -1,90 +1,3 @@
#!/usr/bin/env node

import fs from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Command } from 'commander';
import { browser } from '../src/browser.js';
import { getConfig } from '../src/config.js';
import * as esbuild from 'esbuild';

// Get pkg info
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkg = JSON.parse(fs.readFileSync(join(__dirname, '../package.json'), 'utf8'));

const program = new Command();
program
.argument('<file>', 'file to execute in the browser.')
.option('--headless [boolean]', 'specify running the browser in headless mode.')
.option('--devtools [boolean]', 'open browser devtools automatically.')
.option('--ts-write [boolean]', 'write the js output of the target ts file.')
.option('--url [string]', 'specify a specific url to execute the code in.')
.version(pkg.version)
program.parse(process.argv);

const file = program.args.at(0);
const config = await getConfig();
const opts = { ...config, ...program.opts()};

class Processor extends EventTarget {
constructor() {
super();
this.url = opts['url'];
this.headless = opts['headless'];
this.devtools = opts['devtools'];
this.tsWrite = opts['tsWrite'];
this.playwrightConfig = opts['playwright'];
this._func = '';
this.watcher();
browser(this);
}

get func() {
return this._func;
}

set func(func) {
this._func = func;
this.dispatchEvent(new Event('change'));
}

watcher() {
if (!fs.existsSync(file)) {
throw new Error(`${file} file not found.`);
}
// execute it immediately then start watcher
this.build();
fs.watchFile(file, { interval: 100 }, () => {
this.build();
});
}

async build() {
try {
if (file.endsWith('.ts')) {
const { outputFiles: [stdout]} = await esbuild.build({
entryPoints: [file],
format: 'esm',
bundle: true,
write: false,
});
this.func = new TextDecoder().decode(stdout.contents);
if (this.tsWrite) {
fs.writeFile(join(process.cwd(), file.replace(/\.ts$/g, '.js')), this.func, 'utf8', () => {});
}
}
else {
this.func = fs.readFileSync(file, 'utf8');
}
} catch (e) {
console.error(e);
}
}

start() {
this.dispatchEvent(new Event('change'));
}
}

new Processor();
import '../src/cli.js';
15 changes: 0 additions & 15 deletions config.d.ts

This file was deleted.

8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"files": [
"bin/cli.js",
"src/**",
"config.d.ts",
"types.d.ts"
],
"dependencies": {
Expand All @@ -18,11 +17,14 @@
"playwright": "^1.44.1"
},
"scripts": {
"start": "node ./bin/cli.js --",
"build": "tsc",
"build:watch": "tsc -w",
"release": "npx @changesets/cli publish"
},
"devDependencies": {
"@changesets/cli": "^2.27.1"
"@changesets/cli": "^2.27.1",
"@types/node": "^22.1.0",
"typescript": "^5.5.4"
},
"publishConfig": {
"access": "public"
Expand Down
20 changes: 13 additions & 7 deletions src/browser.js → src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import playwright from 'playwright';
import util from 'node:util';
import type { Processor } from './cli.js';
util.inspect.defaultOptions.maxArrayLength = null;
util.inspect.defaultOptions.depth = null;

function nodelog(value) {
function nodelog(value:any) {
console.log(value);
}

export async function browser(processor) {
export async function browser(processor: Processor) {
// Launch the browser
const browser = await playwright['chromium'].launch({
headless: !!processor.headless,
Expand All @@ -33,18 +34,19 @@ export async function browser(processor) {
});
});

await page.exposeFunction('nodelog', (...value) => {
await page.exposeFunction('nodelog', (...value: any) => {
console.log(...value);
});

async function execute() {
page.evaluate(async (func) => {
function log(...value) {
function log(...value: any[]) {
setTimeout(() => {
console.log(...value);
}, 100);
nodelog(
...value.flatMap(i => {
// @ts-ignore
...value.flatMap((i: any) => {
const protoName = Object.prototype.toString.call(i);
const protoNamePrettyPrint = protoName.replace('object ', '').replace(/\[|\]/g, '') + ':';
if (protoName === '[object Array]') {
Expand Down Expand Up @@ -89,8 +91,12 @@ export async function browser(processor) {
}
})()
`);
} catch (Error) {
log(Error.toString())
} catch (error) {
if (!(error instanceof Error)) {
log(`An unkown error has occurred.`);
return;
}
log(error.toString())
}
},
processor.func
Expand Down
97 changes: 97 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/usr/bin/env node

import fs from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Command } from 'commander';
import { browser } from './browser.js';
import { getConfig } from './config.js';
import * as esbuild from 'esbuild';

// Get pkg info
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkg = JSON.parse(fs.readFileSync(join(__dirname, '../package.json'), 'utf8'));

const program = new Command();
program
.argument('<file>', 'file to execute in the browser.')
.option('--headless [boolean]', 'specify running the browser in headless mode.')
.option('--devtools [boolean]', 'open browser devtools automatically.')
.option('--ts-write [boolean]', 'write the js output of the target ts file.')
.option('--url [string]', 'specify a specific url to execute the code in.')
.version(pkg.version)
program.parse(process.argv);

const file = program.args.at(0);
const config = await getConfig();
const opts = { ...config, ...program.opts()};

export class Processor extends EventTarget {
url = opts['url'];
headless = opts['headless'];
devtools = opts['devtools'];
tsWrite = opts['tsWrite'];
playwrightConfig = opts['playwright'];
_func = '';

constructor() {
super();
this.watcher();
browser(this);
}

get func() {
return this._func;
}

set func(func) {
this._func = func;
this.dispatchEvent(new Event('change'));
}

watcher() {
if (!file) {
throw new Error(`${file} file not found.`);
}
if (!fs.existsSync(file)) {
throw new Error(`${file} file not found.`);
}
// execute it immediately then start watcher
this.build();
fs.watchFile(join(file), { interval: 100 }, () => {
this.build();
});
}

async build() {
try {
if (!file) {
throw new Error(`${file} file not found.`);
}
if (file.endsWith('.ts')) {
const { outputFiles: [stdout]} = await esbuild.build({
entryPoints: [file],
format: 'esm',
bundle: true,
write: false,
});
this.func = new TextDecoder().decode(stdout.contents);
if (this.tsWrite) {
fs.writeFile(join(process.cwd(), file.replace(/\.ts$/g, '.js')), this.func, 'utf8', () => {});
}
}
else {
this.func = fs.readFileSync(file, 'utf8');
}
} catch (e) {
console.error(e);
}
}

start() {
this.dispatchEvent(new Event('change'));
}
}

new Processor();
26 changes: 0 additions & 26 deletions src/config.js

This file was deleted.

41 changes: 41 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { join } from 'node:path';
import { stat } from 'node:fs/promises';
import type { Page, BrowserContext, Browser } from 'playwright';

export type PlaywrightConfig = {
page: Page,
context: BrowserContext,
browser: Browser,
}

export type Config = {
headless?: boolean;
devtools?: boolean;
tsWrite?: boolean;
url?: string;
playwright?: (page: PlaywrightConfig) => Promise<void>
}

const exists = (path:string) => stat(path).then(() => true, () => false);

async function importConfig(rootDir:string) {
const path = join(rootDir, './scratchpad.config.js');
if (await exists(path)) {
return import(path)
.then(x => x.default)
.catch(e => {
console.error(e);
return {};
});
} else {
return {};
}
}

export async function getConfig() {
const rootDir = process.cwd();
return {
...await importConfig(rootDir),
}
}

Loading

0 comments on commit a242c0f

Please sign in to comment.