@basthon/kernel-javascript 0.87.0 → 0.89.0

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/lib/kernel.d.ts CHANGED
@@ -1,12 +1,39 @@
1
1
  import { KernelMainBase } from "@basthon/kernel-base/worker";
2
2
  import type { KernelOptions } from "@basthon/kernel-base";
3
3
  import { JavaScriptKernelWorker } from "./worker";
4
+ /**
5
+ * The JavaScript kernel (main thread side): the code runs in its worker
6
+ * (see `JavaScriptKernelWorker`).
7
+ */
4
8
  export declare class JavaScriptKernel extends KernelMainBase<JavaScriptKernelWorker> {
9
+ /**
10
+ * @param options - The kernel's options.
11
+ */
5
12
  constructor(options: KernelOptions);
13
+ /**
14
+ * Create the kernel's worker (an opaque origin worker, see
15
+ * `KernelMainBase.newWorker`).
16
+ */
6
17
  protected newWorker(): Worker;
18
+ /**
19
+ * The kernel's language (see `KernelBase.language`).
20
+ */
7
21
  language(): string;
22
+ /**
23
+ * The language's name, as displayed (see `KernelBase.languageName`).
24
+ */
8
25
  languageName(): string;
26
+ /**
27
+ * The extensions of the files installed as modules (see
28
+ * `KernelBase.moduleExts`).
29
+ */
9
30
  moduleExts(): string[];
31
+ /**
32
+ * The console's prompt (see `KernelBase.ps1`).
33
+ */
10
34
  ps1(): string;
35
+ /**
36
+ * The console's continuation prompt (see `KernelBase.ps2`).
37
+ */
11
38
  ps2(): string;
12
39
  }
package/lib/kernel.js CHANGED
@@ -1,26 +1,53 @@
1
1
  import { KernelMainBase } from "@basthon/kernel-base/worker";
2
+ /**
3
+ * The JavaScript kernel (main thread side): the code runs in its worker
4
+ * (see `JavaScriptKernelWorker`).
5
+ */
2
6
  export class JavaScriptKernel extends KernelMainBase {
7
+ /**
8
+ * @param options - The kernel's options.
9
+ */
3
10
  constructor(options) {
4
11
  super(options);
5
12
  }
13
+ /**
14
+ * Create the kernel's worker (an opaque origin worker, see
15
+ * `KernelMainBase.newWorker`).
16
+ */
6
17
  newWorker() {
7
18
  return new Worker(new URL("./comlink-worker.js", import.meta.url), {
8
19
  //@ts-ignore
9
20
  sandboxed: true, // removing this line will cause security issues
10
21
  });
11
22
  }
23
+ /**
24
+ * The kernel's language (see `KernelBase.language`).
25
+ */
12
26
  language() {
13
27
  return "javascript";
14
28
  }
29
+ /**
30
+ * The language's name, as displayed (see `KernelBase.languageName`).
31
+ */
15
32
  languageName() {
16
- return "Javascript";
33
+ return "JavaScript";
17
34
  }
35
+ /**
36
+ * The extensions of the files installed as modules (see
37
+ * `KernelBase.moduleExts`).
38
+ */
18
39
  moduleExts() {
19
40
  return ["js"];
20
41
  }
42
+ /**
43
+ * The console's prompt (see `KernelBase.ps1`).
44
+ */
21
45
  ps1() {
22
46
  return " js> ";
23
47
  }
48
+ /**
49
+ * The console's continuation prompt (see `KernelBase.ps2`).
50
+ */
24
51
  ps2() {
25
52
  return "...> ";
26
53
  }
package/lib/worker.d.ts CHANGED
@@ -1,24 +1,86 @@
1
1
  import { KernelWorkerBase } from "@basthon/kernel-base/worker";
2
+ /**
3
+ * The JavaScript kernel's worker: the code is evaluated in the worker's
4
+ * global scope (no page: no `document`); `console.log` and
5
+ * `console.error` print, `prompt` asks for an input, and the global
6
+ * `basthon` object gives the kernel's functions (`sleep`, `display`,
7
+ * `createCanvas`, `displayLiveCanvas`, `download`...).
8
+ */
2
9
  export declare class JavaScriptKernelWorker extends KernelWorkerBase {
10
+ /**
11
+ * @param options - The kernel's options (see `KernelWorkerBase`).
12
+ */
3
13
  constructor(options?: any);
14
+ /**
15
+ * The kernel's language (see `KernelWorkerBase.language`).
16
+ */
4
17
  language(): string;
18
+ /**
19
+ * Redirect `console.info` and `console.warn` to the outputs and print the
20
+ * uncaught errors.
21
+ */
5
22
  protected _init(): Promise<void>;
23
+ /**
24
+ * Evaluate code in the global scope (see `KernelWorkerBase._eval`):
25
+ * `console.log` and `console.error` print on stdout and stderr, a returned
26
+ * promise is awaited.
27
+ *
28
+ * @param data - The evaluation's data.
29
+ * @param code - The code.
30
+ * @returns The value of the code (inspected, `text/plain`), or `undefined`.
31
+ */
6
32
  protected _eval(data: any, code: string): Promise<any>;
7
33
  /**
8
- * Display a canvas created with basthon.createCanvas(width, height) (to
9
- * be called by the user's code as basthon.displayLiveCanvas(canvas)).
10
- * The canvas is live: its drawings are displayed and it receives mouse
11
- * events (keyboard ones on canvas.ownerDocument), as a canvas of a page
12
- * (see kernel-base's canvas/worker/live-canvas.ts).
34
+ * Display a canvas created with `basthon.createCanvas(width, height)` (to
35
+ * be called by the user's code as `basthon.displayLiveCanvas(canvas)`).
36
+ * The canvas is live: its drawings are displayed and it receives the mouse
37
+ * events (and the keyboard ones on `canvas.ownerDocument`), as a canvas of
38
+ * a page (see kernel-base's `canvas/worker/live-canvas.ts`).
39
+ *
40
+ * @param canvas - The canvas.
13
41
  */
14
42
  displayLiveCanvas(canvas: OffscreenCanvas | HTMLCanvasElement): Promise<void>;
43
+ /**
44
+ * Download a file (`basthon.download(content, filename)` in the user's
45
+ * code): a string is the text of the file (encoded in UTF-8), as the main
46
+ * thread only accepts bytes or data URLs.
47
+ *
48
+ * @param content - The file's content: text or bytes.
49
+ * @param filename - The name of the saved file.
50
+ */
51
+ download(content: Uint8Array | string, filename: string): void;
52
+ /**
53
+ * No filesystem: the file is ignored (an error is printed).
54
+ *
55
+ * @param filename - The file's name.
56
+ * @param content - The file's content.
57
+ */
15
58
  putFile(filename: string, content: ArrayBuffer): void;
59
+ /**
60
+ * Run a `.js` module in the global scope.
61
+ *
62
+ * @param filename - The module's file name.
63
+ * @param content - The module's content.
64
+ * @throws If it is not a `.js` file.
65
+ */
16
66
  putModule(filename: string, content: ArrayBuffer): Promise<void>;
67
+ /**
68
+ * Complete the last word: the properties of an object after `a.b.` (its
69
+ * own and inherited ones, the path being made of names only, nothing is
70
+ * called), otherwise the keywords and the names of the global scope.
71
+ * Functions get a `(`, names starting with `__` are only completed after
72
+ * a `_`.
73
+ *
74
+ * @param code - The code before the cursor.
75
+ * @returns `[completions, start]`.
76
+ */
17
77
  complete(code: string): Promise<[string[], number] | []>;
18
78
  /**
19
- * Is the source ready to be evaluated or want we more? It wants more
20
- * when it does not parse because it ends too early (e.g. an unclosed
21
- * block): as Python's codeop.
79
+ * Does the code need more lines? Yes when it doesn't parse because it
80
+ * ends too early (e.g. an unclosed block), as Python's `codeop`.
81
+ *
82
+ * @param code - The lines typed so far.
83
+ * @returns `true` if the code is incomplete.
22
84
  */
23
85
  more(code: string): Promise<boolean>;
24
86
  }
package/lib/worker.js CHANGED
@@ -2,12 +2,20 @@ import { parse } from "acorn";
2
2
  import objectInspect from "object-inspect";
3
3
  import { KernelWorkerBase } from "@basthon/kernel-base/worker";
4
4
  const PARSE_OPTIONS = { ecmaVersion: "latest", sourceType: "script" };
5
+ // the keywords completed at the top level (see complete)
6
+ const KEYWORDS = `async await break case catch class const continue debugger
7
+ default delete do else export extends false finally for function if import
8
+ in instanceof let new null of return static super switch this throw true try
9
+ typeof undefined var void while with yield`.split(/\s+/);
5
10
  /**
6
- * Code where the top-level declarations (let, const and class) are global
7
- * variables (var), as in a browser's console: they persist from an
8
- * evaluation to the next (the code is evaluated by an indirect eval where
9
- * they would be local to the evaluation). Unchanged if it does not parse
10
- * (the evaluation reports the error).
11
+ * The code where the top-level declarations (`let`, `const` and `class`)
12
+ * are global variables (`var`), as in a browser's console: they persist
13
+ * from an evaluation to the next (the code is evaluated by an indirect
14
+ * `eval`, where they would be local to the evaluation).
15
+ *
16
+ * @param code - The code.
17
+ * @returns The changed code (unchanged if it doesn't parse: the
18
+ * evaluation reports the error).
11
19
  */
12
20
  const persistentDeclarations = (code) => {
13
21
  let program;
@@ -36,22 +44,45 @@ const persistentDeclarations = (code) => {
36
44
  result = result.slice(0, start) + replacement + result.slice(end);
37
45
  return result;
38
46
  };
47
+ /**
48
+ * The JavaScript kernel's worker: the code is evaluated in the worker's
49
+ * global scope (no page: no `document`); `console.log` and
50
+ * `console.error` print, `prompt` asks for an input, and the global
51
+ * `basthon` object gives the kernel's functions (`sleep`, `display`,
52
+ * `createCanvas`, `displayLiveCanvas`, `download`...).
53
+ */
39
54
  export class JavaScriptKernelWorker extends KernelWorkerBase {
55
+ /**
56
+ * @param options - The kernel's options (see `KernelWorkerBase`).
57
+ */
40
58
  constructor(options) {
41
59
  // do not forget to call the parent constructor
42
60
  super(options);
43
61
  }
62
+ /**
63
+ * The kernel's language (see `KernelWorkerBase.language`).
64
+ */
44
65
  language() {
45
66
  return "javascript";
46
67
  }
47
- /*
48
- * Initialize the kernel.
68
+ /**
69
+ * Redirect `console.info` and `console.warn` to the outputs and print the
70
+ * uncaught errors.
49
71
  */
50
72
  async _init() {
51
73
  console.info = (...args) => console.log(...args);
52
74
  console.warn = (...args) => console.error(...args);
53
75
  globalThis.addEventListener("error", (e) => console.error(e.toString()));
54
76
  }
77
+ /**
78
+ * Evaluate code in the global scope (see `KernelWorkerBase._eval`):
79
+ * `console.log` and `console.error` print on stdout and stderr, a returned
80
+ * promise is awaited.
81
+ *
82
+ * @param data - The evaluation's data.
83
+ * @param code - The code.
84
+ * @returns The value of the code (inspected, `text/plain`), or `undefined`.
85
+ */
55
86
  async _eval(data, code) {
56
87
  console.log = (...args) => {
57
88
  this.sendStdoutStream(data, args.join(" ") + "\n");
@@ -66,20 +97,48 @@ export class JavaScriptKernelWorker extends KernelWorkerBase {
66
97
  : { "text/plain": objectInspect(result) };
67
98
  }
68
99
  /**
69
- * Display a canvas created with basthon.createCanvas(width, height) (to
70
- * be called by the user's code as basthon.displayLiveCanvas(canvas)).
71
- * The canvas is live: its drawings are displayed and it receives mouse
72
- * events (keyboard ones on canvas.ownerDocument), as a canvas of a page
73
- * (see kernel-base's canvas/worker/live-canvas.ts).
100
+ * Display a canvas created with `basthon.createCanvas(width, height)` (to
101
+ * be called by the user's code as `basthon.displayLiveCanvas(canvas)`).
102
+ * The canvas is live: its drawings are displayed and it receives the mouse
103
+ * events (and the keyboard ones on `canvas.ownerDocument`), as a canvas of
104
+ * a page (see kernel-base's `canvas/worker/live-canvas.ts`).
105
+ *
106
+ * @param canvas - The canvas.
74
107
  */
75
108
  displayLiveCanvas(canvas) {
76
109
  const promise = super.displayLiveCanvas(canvas);
77
110
  this.addEvalPromise(promise);
78
111
  return promise;
79
112
  }
113
+ /**
114
+ * Download a file (`basthon.download(content, filename)` in the user's
115
+ * code): a string is the text of the file (encoded in UTF-8), as the main
116
+ * thread only accepts bytes or data URLs.
117
+ *
118
+ * @param content - The file's content: text or bytes.
119
+ * @param filename - The name of the saved file.
120
+ */
121
+ download(content, filename) {
122
+ if (typeof content === "string")
123
+ content = new TextEncoder().encode(content);
124
+ super.download(content, filename);
125
+ }
126
+ /**
127
+ * No filesystem: the file is ignored (an error is printed).
128
+ *
129
+ * @param filename - The file's name.
130
+ * @param content - The file's content.
131
+ */
80
132
  putFile(filename, content) {
81
133
  console.error(`File ${filename} not added since putFile has no mean in the JS context.`);
82
134
  }
135
+ /**
136
+ * Run a `.js` module in the global scope.
137
+ *
138
+ * @param filename - The module's file name.
139
+ * @param content - The module's content.
140
+ * @throws If it is not a `.js` file.
141
+ */
83
142
  async putModule(filename, content) {
84
143
  const ext = filename.split(".").pop();
85
144
  switch (ext) {
@@ -93,18 +152,61 @@ export class JavaScriptKernelWorker extends KernelWorkerBase {
93
152
  throw { message: "Only '.js' files supported." };
94
153
  }
95
154
  }
155
+ /**
156
+ * Complete the last word: the properties of an object after `a.b.` (its
157
+ * own and inherited ones, the path being made of names only, nothing is
158
+ * called), otherwise the keywords and the names of the global scope.
159
+ * Functions get a `(`, names starting with `__` are only completed after
160
+ * a `_`.
161
+ *
162
+ * @param code - The code before the cursor.
163
+ * @returns `[completions, start]`.
164
+ */
96
165
  async complete(code) {
97
- // basic completion based on global object
98
- const vars = Object.getOwnPropertyNames(self);
99
- const words = code.match(/(\w+)$/) ?? [];
100
- const word = words[0] ?? "";
101
- const matches = vars.filter((v) => v.startsWith(word));
102
- return [matches, code.length - word.length];
166
+ const [, path, word] = /((?:[\w$]+\??\.)*)([\w$]*)$/.exec(code);
167
+ // a member of what is not a path of names (f()., a[0]., "s".) is not
168
+ // completed
169
+ const before = code[code.length - path.length - word.length - 1] ?? "";
170
+ if (/[.)\]"'`]/.test(before))
171
+ return [];
172
+ // a.b?.c. -> ["a", "b", "c"]
173
+ const names = path.split(/\??\./).slice(0, -1);
174
+ const candidates = new Set(names.length === 0 ? KEYWORDS : []);
175
+ let owner = self;
176
+ try {
177
+ for (const name of names)
178
+ owner = owner?.[name];
179
+ if (owner == null)
180
+ return [];
181
+ for (let o = Object(owner); o != null; o = Object.getPrototypeOf(o))
182
+ for (const name of Object.getOwnPropertyNames(o))
183
+ if (/^[\w$]+$/.test(name))
184
+ candidates.add(name);
185
+ }
186
+ catch {
187
+ return [];
188
+ }
189
+ const matches = [];
190
+ for (const name of candidates) {
191
+ if (!name.startsWith(word))
192
+ continue;
193
+ if (name.startsWith("__") && !word.startsWith("_"))
194
+ continue;
195
+ let value;
196
+ try {
197
+ value = KEYWORDS.includes(name) ? undefined : owner[name];
198
+ }
199
+ catch { }
200
+ matches.push(typeof value === "function" ? `${name}(` : name);
201
+ }
202
+ return [matches.sort(), code.length - word.length];
103
203
  }
104
204
  /**
105
- * Is the source ready to be evaluated or want we more? It wants more
106
- * when it does not parse because it ends too early (e.g. an unclosed
107
- * block): as Python's codeop.
205
+ * Does the code need more lines? Yes when it doesn't parse because it
206
+ * ends too early (e.g. an unclosed block), as Python's `codeop`.
207
+ *
208
+ * @param code - The lines typed so far.
209
+ * @returns `true` if the code is incomplete.
108
210
  */
109
211
  async more(code) {
110
212
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basthon/kernel-javascript",
3
- "version": "0.87.0",
3
+ "version": "0.89.0",
4
4
  "description": "Basthon - JavaScript Kernel",
5
5
  "homepage": "https://basthon.fr",
6
6
  "bugs": {
@@ -25,7 +25,7 @@
25
25
  "clean": "rimraf lib/"
26
26
  },
27
27
  "dependencies": {
28
- "@basthon/kernel-base": "0.87.0",
28
+ "@basthon/kernel-base": "0.89.0",
29
29
  "acorn": "^8.19.0",
30
30
  "comlink": "^4.4.2",
31
31
  "object-inspect": "^1.13.4"