8000 Fix many ESlint errors by hoodmane · Pull Request #1265 · pyscript/pyscript · GitHub
[go: up one dir, main page]

Skip to content

Fix many ESlint errors #1265

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 30 commits into from
Mar 13, 2023
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
564e1e1
Unvendor toml package
hoodmane Mar 8, 2023
04ae065
Fix many ESlint errors
hoodmane Mar 8, 2023
6ae4d7f
Put back Record
hoodmane Mar 8, 2023
144efac
Fix typescript compilation
hoodmane Mar 8, 2023
09be677
Merge branch 'unvendor-toml' into fix-lints
hoodmane Mar 8, 2023
ad00491
Fix lints
hoodmane Mar 8, 2023
2e158d4
Try @iarna/toml instead
hoodmane Mar 8, 2023
ed61b1e
Fix import
hoodmane Mar 8, 2023
81b4c35
Use @ltd/j-toml
hoodmane Mar 8, 2023
81878c8
Update test
hoodmane Mar 8, 2023
dcdfc93
Use toml-j0.4
hoodmane Mar 8, 2023
6154b5c
Merge branch 'unvendor-toml' into fix-lints
hoodmane Mar 8, 2023
3c6fe2d
Some changes
hoodmane Mar 8, 2023
54ab4b3
Fix toml import
hoodmane Mar 9, 2023
8bb9ec4
Merge branch 'unvendor-toml' into fix-lints
hoodmane Mar 9, 2023
40324ab
Try adding eslint gha job
hoodmane Mar 9, 2023
d68c6e7
Add forgotten checkout action
hoodmane Mar 9, 2023
bcb9d92
Force CI to run
hoodmane Mar 9, 2023
336782a
Blah
hoodmane Mar 9, 2023
054ada0
Fix
hoodmane Mar 9, 2023
859f127
Revert changes to github workflow
hoodmane Mar 9, 2023
281328b
Merge branch 'main' into fix-lints
hoodmane Mar 9, 2023
06ea704
Fix lints
hoodmane Mar 9, 2023
c36eb05
wget toml-j0.4 type definitions
hoodmane Mar 9, 2023
be92a41
Merge branch 'main' into fix-lints
hoodmane Mar 9, 2023
46efde1
Add toml-j types workaround to eslint workflow
hoodmane Mar 9, 2023
999d43c
Apply formatter
hoodmane Mar 9, 2023
cd4e014
Merge branch 'main' into fix-lints
hoodmane Mar 13, 2023
8963fe6
Use @hoodmane/toml-j0.4
hoodmane Mar 13, 2023
80dff89
Import from @hoodmane/toml-j0.4
hoodmane Mar 13, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions pyscriptjs/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@ module.exports = {
plugins: ['@typescript-eslint'],
ignorePatterns: ['node_modules'],
rules: {
'no-prototype-builtins': 'warn',
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-call': 'warn',
'@typescript-eslint/no-unsafe-return': 'warn',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/restrict-plus-operands': 'warn',
'@typescript-eslint/no-empty-function': 'warn',
'no-prototype-builtins': 'error',
'@typescript-eslint/no-unused-vars': ['error', { args: 'none' }],
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/restrict-plus-operands': 'error',
'@typescript-eslint/no-empty-function': 'error',
},
};
3 changes: 3 additions & 0 deletions pyscriptjs/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ setup:
make check-node
make check-npm
npm install
# toml-j0.4 left out its types from the npm dist
# See https://github.com/jakwings/toml-j0.4/pull/8
cd node_modules/toml-j0.4 && wget https://raw.githubusercontent.com/jakwings/toml-j0.4/v1.1.1/toml.d.ts
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tedpatrick workaround for toml-j0.4's missing types

$(CONDA_EXE) env $(shell [ -d $(env) ] && echo update || echo create) -p $(env) --file environment.yml
$(conda_run) playwright install
$(CONDA_EXE) install -c anaconda pytest -y
Expand Down
9 changes: 5 additions & 4 deletions pyscriptjs/src/components/pyrepl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { basicSetup, EditorView } from 'codemirror';
import { python } from '@codemirror/lang-python';
import { indentUnit } from '@codemirror/language';
import { Compartment } from '@codemirror/state';
import { keymap } from '@codemirror/view';
import { keymap, Command } from '@codemirror/view';
import { defaultKeymap } from '@codemirror/commands';
import { oneDarkTheme } from '@codemirror/theme-one-dark';

Expand Down Expand Up @@ -68,8 +68,8 @@ export function make_PyRepl(interpreter: InterpreterClient) {
languageConf.of(python()),
keymap.of([
...defaultKeymap,
{ key: 'Ctrl-Enter', run: this.execute.bind(this), preventDefault: true },
{ key: 'Shift-Enter', run: this.execute.bind(this), preventDefault: true },
{ key: 'Ctrl-Enter', run: this.execute.bind(this) as Command, preventDefault: true },
{ key: 'Shift-Enter', run: this.execute.bind(this) as Command, preventDefault: true },
]),
];

Expand Down Expand Up @@ -134,7 +134,7 @@ export function make_PyRepl(interpreter: InterpreterClient) {
runButton.id = 'runButton';
runButton.className = 'absolute py-repl-run-button';
runButton.innerHTML = RUNBUTTON;
runButton.addEventListener('click', this.execute.bind(this));
runButton.addEventListener('click', this.execute.bind(this) as (e: MouseEvent) => void);
return runButton;
}

Expand Down Expand Up @@ -166,6 +166,7 @@ export function make_PyRepl(interpreter: InterpreterClient) {
outEl.innerHTML = '';

// execute the python code
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pyResult = (await pyExec(interpreter, pySrc, outEl)).result;

// display the value of the last evaluated expression (REPL-style)
Expand Down
18 changes: 11 additions & 7 deletions pyscriptjs/src/components/pyscript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function make_PyScript(interpreter: InterpreterClient, app: PyScriptApp)
* 6D40
* Concurrent access to the multiple py-script tags is thus avoided.
*/
let releaseLock: any;
let releaseLock: () => void;
try {
releaseLock = await app.tagExecutionLock();
ensureUniqueId(this);
Expand All @@ -35,13 +35,15 @@ export function make_PyScript(interpreter: InterpreterClient, app: PyScriptApp)
this.innerHTML = '';

app.plugins.beforePyScriptExec({ interpreter: interpreter, src: pySrc, pyScriptTag: this });
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
const result = (await pyExec(interpreter, pySrc, this)).result;
app.plugins.afterPyScriptExec({
interpreter: interpreter,
src: pySrc,
pyScriptTag: this,
result: result,
});
/* eslint-enable @typescript-eslint/no-unsafe-assignment */
} finally {
releaseLock();
}
Expand All @@ -53,7 +55,8 @@ export function make_PyScript(interpreter: InterpreterClient, app: PyScriptApp)
try {
const response = await robustFetch(url);
return await response.text();
} catch (e) {
} catch (err) {
const e = err as Error;
_createAlertBanner(e.message);
this.innerHTML = '';
throw e;
Expand Down Expand Up @@ -163,15 +166,15 @@ const pyAttributeToEvent: Map<string, string> = new Map<string, string>([
]);

/** Initialize all elements with py-* handlers attributes */
export function initHandlers(interpreter: InterpreterClient) {
export async function initHandlers(interpreter: InterpreterClient) {
logger.debug('Initializing py-* event handlers...');
for (const pyAttribute of pyAttributeToEvent.keys()) {
createElementsWithEventListeners(interpreter, pyAttribute);
await createElementsWithEventListeners(interpreter, pyAttribute);
}
}

/** Initializes an element with the given py-on* attribute and its handler */
function createElementsWithEventListeners(interpreter: InterpreterClient, pyAttribute: string) {
async function createElementsWithEventListeners(interpreter: InterpreterClient, pyAttribute: string) {
const matches: NodeListOf<HTMLElement> = document.querySelectorAll(`[${pyAttribute}]`);
for (const el of matches) {
// If the element doesn't have an id, let's add one automatically!
Expand All @@ -195,7 +198,7 @@ function createElementsWithEventListeners(interpreter: InterpreterClient, pyAttr
// the source code may contain a syntax error, which will cause
// the splashscreen to not be removed.
try {
interpreter.run(source);
await interpreter.run(source);
} catch (e) {
logger.error((e as Error).message);
}
Expand All @@ -204,7 +207,8 @@ function createElementsWithEventListeners(interpreter: InterpreterClient, pyAttr
void (async () => {
try {
await interpreter.run(handlerCode);
} catch (err) {
} catch (e) {
const err = e as Error;
displayPyException(err, el.parentElement);
}
})();
Expand Down
13 changes: 6 additions & 7 deletions pyscriptjs/src/components/pywidget.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { PyProxy } from 'pyodide';
import type { PyProxy, PyProxyCallable } from 'pyodide';
import { getLogger } from '../logger';
import { robustFetch } from '../fetch';
import { InterpreterClient } from '../interpreter_client';
Expand All @@ -13,8 +13,8 @@ function createWidget(interpreter: InterpreterClient, name: string, code: string
name: string = name;
klass: string = klass;
code: string = code;
proxy: PyProxy;
proxyClass: any;
proxy: PyProxy & { connect(): void };
proxyClass: PyProxyCallable;

constructor() {
super();
Expand All @@ -28,8 +28,8 @@ function createWidget(interpreter: InterpreterClient, name: string, code: string

async connectedCallback() {
await interpreter.runButDontRaise(this.code);
this.proxyClass = interpreter.globals.get(this.klass);
this.proxy = this.proxyClass(this);
this.proxyClass = interpreter.globals.get(this.klass) as PyProxyCallable;
this.proxy = this.proxyClass(this) as PyProxy & { connect(): void };
this.proxy.connect();
this.registerWidget();
}
Expand All @@ -39,9 +39,8 @@ function createWidget(interpreter: InterpreterClient, name: string, code: string
interpreter.globals.set(this.id, this.proxy);
}
}
/* eslint-disable @typescript-eslint/no-unused-vars */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const xPyWidget = customElements.define(name, CustomWidget);
/* eslint-enable @typescript-eslint/no-unused-vars */
}

export function make_PyWidget(interpreter: InterpreterClient) {
Expand Down
7 changes: 4 additions & 3 deletions pyscriptjs/src/interpreter_client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AppConfig } from './pyconfig';
import { RemoteInterpreter } from './remote_interpreter';
import type { PyProxy } from 'pyodide';
import type { PyProxyDict } from 'pyodide';
import { getLogger } from './logger';
import type { Stdio } from './stdio';

Expand All @@ -16,7 +16,7 @@ export class InterpreterClient extends Object {
/**
* global symbols table for the underlying interface.
* */
globals: PyProxy;
globals: PyProxyDict;
stdio: Stdio;

constructor(config: AppConfig, stdio: Stdio) {
Expand All @@ -32,14 +32,15 @@ export class InterpreterClient extends Object {
* */
async initializeRemote(): Promise<void> {
await this._remote.loadInterpreter(this.config, this.stdio);
this.globals = this._remote.globals;
this.globals = this._remote.globals as PyProxyDict;
}

/**
* delegates the code to be run to the underlying interface of
* the remote interpreter.
* Python exceptions are turned into JS exceptions.
* */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async run(code: string): Promise<{ result: any }> {
return await this._remote.run(code);
}
Expand Down
6 changes: 3 additions & 3 deletions pyscriptjs/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ interface Logger {
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string, ...args: unknown[]): void;
error(message: string | Error, ...args: unknown[]): void;
}

const _cache = new Map<string, Logger>();
Expand All @@ -44,8 +44,8 @@ function getLogger(prefix: string): Logger {
function _makeLogger(prefix: string): Logger {
prefix = `[${prefix}] `;

function make(level: string) {
const out_fn = console[level].bind(console);
function make(level: 'info' | 'debug' | 'warn' | 'error') {
const out_fn = console[level].bind(console) as typeof console.log;
function fn(fmt: string, ...args: unknown[]) {
out_fn(prefix + fmt, ...args);
}
Expand Down
14 changes: 8 additions & 6 deletions pyscriptjs/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { loadConfigFromElement } from './pyconfig';
import type { AppConfig } from './pyconfig';
import { InterpreterClient } from './interpreter_client';
import { version } from './version';
import { PluginManager, define_custom_element } from './plugin';
import { PluginManager, define_custom_element, Plugin } from './plugin';
import { make_PyScript, initHandlers, mountElements } from './components/pyscript';
import { getLogger } from './logger';
import { showWarning, globalExport, createLock } from './utils';
Expand All @@ -16,6 +16,7 @@ import { PyTerminalPlugin } from './plugins/pyterminal';
import { SplashscreenPlugin } from './plugins/splashscreen';
import { ImportmapPlugin } from './plugins/importmap';
import { StdioDirector as StdioDirector } from './plugins/stdiodirector';
import type { PyProxy } from 'pyodide';
// eslint-disable-next-line
// @ts-ignore
import pyscript from './python/pyscript/__init__.py';
Expand Down Expand Up @@ -190,7 +191,7 @@ export class PyScriptApp {
// lifecycle (8)
createCustomElements(interpreter);

initHandlers(interpreter);
await initHandlers(interpreter);

// NOTE: interpreter message is used by integration tests to know that
// pyscript initialization has complete. If you change it, you need to
Expand All @@ -208,8 +209,8 @@ export class PyScriptApp {
logger.info('importing pyscript');

// Save and load pyscript.py from FS
interpreter._remote.interface.FS.mkdirTree('/home/pyodide/pyscript');
interpreter._remote.interface.FS.writeFile('pyscript/__init__.py', pyscript);
interpreter._remote.FS.mkdirTree('/home/pyodide/pyscript');
interpreter._remote.FS.writeFile('pyscript/__init__.py', pyscript as string);
//Refresh the module cache so Python consistently finds pyscript module
interpreter._remote.invalidate_module_path_cache();

Expand All @@ -218,6 +219,7 @@ export class PyScriptApp {
const pyscript_module = interpreter._remote.interface.pyimport('pyscript');
pyscript_module.define_custom_element = define_custom_element;
pyscript_module.showWarning = showWarning;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
pyscript_module._set_version_info(version);
pyscript_module.destroy();

Expand Down Expand Up @@ -303,7 +305,7 @@ export class PyScriptApp {
const blobFile = new File([pluginBlob], 'plugin.js', { type: 'text/javascript' });
const fileUrl = URL.createObjectURL(blobFile);

const module = await import(fileUrl);
const module = (await import(fileUrl)) as { default: { new (): Plugin } };
// Note: We have to put module.default in a variable
// because we have seen weird behaviour when doing
// new module.default() directly.
Expand Down Expand Up @@ -346,7 +348,7 @@ export class PyScriptApp {
// interpreter API level and allow each one to implement it in its own way
const module = interpreter._remote.interface.pyimport(modulename);
if (typeof module.plugin !== 'undefined') {
const py_plugin = module.plugin;
const py_plugin = module.plugin as PyProxy & { init(app: PyScriptApp): void };
py_plugin.init(this);
this.plugins.addPythonPlugin(py_plugin);
} else {
Expand Down
35 changes: 27 additions & 8 deletions pyscriptjs/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access,
@typescript-eslint/no-unsafe-call,
@typescript-eslint/no-explicit-any,
@typescript-eslint/no-unsafe-assignment */

import type { AppConfig } from './pyconfig';
import type { UserError } from './exceptions';
import { getLogger } from './logger';
Expand All @@ -20,7 +25,9 @@ export class Plugin {
* This hook should **NOT** contain expensive operations, else it delays
* the download of the python interpreter which is initiated later.
*/
configure(config: AppConfig) {}
configure(_config: AppConfig) {
/* empty */
}

/** The preliminary initialization phase is complete and we are about to
* download and launch the Python interpreter.
Expand All @@ -32,14 +39,18 @@ export class Plugin {
* This hook should **NOT** contain expensive operations, else it delays
* the download of the python interpreter which is initiated later.
*/
beforeLaunch(config: AppConfig) {}
beforeLaunch(_config: AppConfig) {
/* empty */
}

/** The Python interpreter has been launched, the virtualenv has been
* installed and we are ready to execute user code.
*
* The <py-script> tags will be executed after this hook.
*/
afterSetup(interpreter: InterpreterClient) {}
afterSetup(_interpreter: InterpreterClient) {
/* empty */
}

/** The source of a <py-script>> tag has been fetched, and we're about
* to evaluate that source using the provided interpreter.
Expand All @@ -48,7 +59,9 @@ export class Plugin {
* @param options.src {string} The Python source code to be evaluated
* @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation
*/
beforePyScriptExec(options: { interpreter: InterpreterClient; src: string; pyScriptTag: PyScriptTag }) {}
beforePyScriptExec(_options: { interpreter: InterpreterClient; src: string; pyScriptTag: PyScriptTag }) {
/* empty */
}

/** The Python in a <py-script> has just been evaluated, but control
* has not been ceded back to the JavaScript event loop yet
Expand All @@ -58,22 +71,28 @@ export class Plugin {
* @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation
* @param options.result The returned result of evaluating the Python (if any)
*/
afterPyScriptExec(options: {
afterPyScriptExec(_options: {
interpreter: InterpreterClient;
src: string;
pyScriptTag: PyScriptTag;
result: any;
}) {}
}) {
/* empty */
}

/** Startup complete. The interpreter is initialized and ready, user
* scripts have been executed: the main initialization logic ends here and
* the page is ready to accept user interactions.
*/
afterStartup(interpreter: InterpreterClient) {}
afterStartup(_interpreter: InterpreterClient) {
/* empty */
}

/** Called when an UserError is raised
*/
onUserError(error: UserError) {}
onUserError(_error: UserError) {
/* empty */
}
}

export class PluginManager {
Expand Down
3 changes: 2 additions & 1 deletion pyscriptjs/src/plugins/importmap.ts
< 7670 div class="js-file-content Details-content--hidden position-relative" data-hydro-view="{"event_type":"pull_request.select_diff_range","payload":{"actor_id":null,"pull_request_id":1267789703,"repository_id":461710233,"diff_type":"UNIFIED","whitespace_ignored":false,"originating_url":"https://github.com/pyscript/pyscript/pull/1265/files/c36eb05f662f3fcebcbdf650c25ada477da7b2e6","user_id":null}}" data-hydro-view-hmac="89d5004fa00e2e8b4905c5e2847c65cb9fa86269e240543bd85f160774e825c3">
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export class ImportmapPlugin extends Plugin {
const importmap: ImportMapType = (() => {
try {
return JSON.parse(node.textContent) as ImportMapType;
} catch (error) {
} catch (e) {
const error = e as Error;
showWarning('Failed to parse import map: ' + error.message);
}
})();
Expand Down
Loading
0