@kubohiroya/turbowarp-plus-editor-test-runtime 0.0.0-stage → 0.1.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.
@@ -0,0 +1,12 @@
1
+ export interface EditorRuntimeServer {
2
+ /** The page's URL, ending in `/`. */
3
+ url: string;
4
+ close(): Promise<void>;
5
+ }
6
+ export interface EditorRuntimeServerOptions {
7
+ /** A test's page entry, bundled and loaded after the runtime. */
8
+ script?: string;
9
+ /** Files to add or replace, by served path. */
10
+ files?: Record<string, string | Uint8Array>;
11
+ }
12
+ export declare function serveEditorRuntime(options?: EditorRuntimeServerOptions): Promise<EditorRuntimeServer>;
package/node/index.js ADDED
@@ -0,0 +1,56 @@
1
+ // Serves the minimal editor runtime page on a free local port.
2
+ import http from 'node:http';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {build} from 'esbuild';
7
+ import {directory as blocksDirectory, scripts as blockScripts} from '@kubohiroya/turbowarp-plus-editor-test-runtime-blocks';
8
+
9
+ const runtimeDirectory = fileURLToPath(new URL('../dist/', import.meta.url));
10
+ const types = {'.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.svg': 'image/svg+xml',
11
+ '.png': 'image/png', '.cur': 'image/x-icon', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.css': 'text/css'};
12
+
13
+ const page = test => `<!doctype html>
14
+ <meta charset="utf-8">
15
+ <title>Minimal editor runtime</title>
16
+ <style>html, body {margin: 0; height: 100%} #workspace {position: absolute; inset: 0}</style>
17
+ <div id="workspace"></div>
18
+ ${blockScripts.map(file => `<script src="blocks/${file}"></script>`).join('\n')}
19
+ <script src="runtime.js"></script>
20
+ ${test ? '<script src="test.js"></script>\n' : ''}`;
21
+
22
+ // Resolves a request path inside `root`, or null when it would leave it.
23
+ const inside = (root, name) => {
24
+ const file = path.resolve(root, name);
25
+ return file.startsWith(root) ? file : null;
26
+ };
27
+
28
+ /**
29
+ * Starts the server. `script` is a test's page entry: it is bundled with esbuild and loaded after the runtime,
30
+ * so it can call `EditorRuntime.start` and use the package under test. `files` adds or replaces served files.
31
+ */
32
+ export async function serveEditorRuntime({script, files = {}} = {}) {
33
+ const served = {'index.html': page(Boolean(script)), ...files};
34
+ if (script) {
35
+ const result = await build({entryPoints: [script], bundle: true, write: false, format: 'iife', platform: 'browser',
36
+ define: {'process.env.NODE_ENV': '"development"'}, loader: {'.css': 'text'}, logLevel: 'error'});
37
+ served['test.js'] = result.outputFiles[0].text;
38
+ }
39
+ const server = http.createServer(async (request, response) => {
40
+ const name = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname).slice(1) || 'index.html';
41
+ const file = name.startsWith('blocks/') ? inside(blocksDirectory, name.slice('blocks/'.length)) :
42
+ name.startsWith('media/') ? inside(blocksDirectory, name) : inside(runtimeDirectory, name);
43
+ try {
44
+ const body = Object.hasOwn(served, name) ? served[name] : file && await fs.readFile(file);
45
+ if (body === null) throw new Error('outside');
46
+ response.writeHead(200, {'content-type': types[path.extname(name)] ?? 'application/octet-stream'});
47
+ response.end(body);
48
+ } catch {
49
+ response.writeHead(404);
50
+ response.end();
51
+ }
52
+ });
53
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
54
+ const {port} = server.address();
55
+ return {url: `http://127.0.0.1:${port}/`, close: () => new Promise(resolve => server.close(resolve))};
56
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-test-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A minimal TurboWarp Plus Editor runtime for package tests: the Editor's pinned VM and Scratch Blocks with one workspace, implementing the editor host contract",
5
+ "type": "module",
6
+ "license": "MPL-2.0",
7
+ "author": "Hiroya Kubo",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kubohiroya/turbowarp-plus-editor-test-runtime.git"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./node/index.d.ts",
15
+ "default": "./node/index.js"
16
+ },
17
+ "./page": {
18
+ "types": "./page.d.ts"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "node",
24
+ "src",
25
+ "page.d.ts",
26
+ "pins.json",
27
+ "THIRD_PARTY_NOTICES.md",
28
+ "README.md",
29
+ "README.ja.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "test": "npm run build && node --test test/*.test.js",
35
+ "test:browser": "npm run build && node --test test/*.browser.js"
36
+ },
37
+ "dependencies": {
38
+ "@kubohiroya/turbowarp-plus-editor-host": "0.1.0",
39
+ "@kubohiroya/turbowarp-plus-editor-test-runtime-blocks": "0.1.0",
40
+ "esbuild": "0.25.12"
41
+ },
42
+ "devDependencies": {
43
+ "@playwright/test": "1.64.1",
44
+ "@turbowarp/scratch-storage": "2.0.0",
45
+ "@turbowarp/scratch-svg-renderer": "1.1.0",
46
+ "buffer": "4.9.2",
47
+ "scratch-render": "git+https://github.com/TurboWarp/scratch-render.git#655edeb5a7b107aa26fb02a3beb0bbcfb8c350ff",
48
+ "scratch-vm": "git+https://github.com/kubohiroya/scratch-vm.git#3ac5fb7052ffc371f1e615245fcc15d61a368237"
49
+ }
50
+ }
package/page.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ // Types for test pages: the global the runtime defines in the browser.
2
+ import type {EditorHost} from '@kubohiroya/turbowarp-plus-editor-host';
3
+
4
+ export interface EditorRuntimeHost extends EditorHost {
5
+ /** The workspace that shows the VM's editing target. */
6
+ workspace: any;
7
+ /** Loads a project (`project.json` contents) and edits its first sprite. The project is then saved. */
8
+ loadProject(project: string | object): Promise<void>;
9
+ }
10
+ export interface EditorRuntimeOptions {
11
+ locale?: string;
12
+ project?: string | object;
13
+ }
14
+ declare global {
15
+ const EditorRuntime: {start(container: HTMLElement, options?: EditorRuntimeOptions): Promise<EditorRuntimeHost>};
16
+ }
package/pins.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "guiRepository": "kubohiroya/scratch-gui",
3
+ "guiRevision": "eac09baf59a1303d58e257ea8b78a3253c0af035"
4
+ }
@@ -0,0 +1 @@
1
+ export {Buffer} from 'buffer';
package/src/runtime.js ADDED
@@ -0,0 +1,67 @@
1
+ // The minimal editor runtime: the pinned scratch-vm and scratch-blocks, one workspace kept in step with the
2
+ // VM's editing target, and the editor host contract that family packages are written against.
3
+ import VirtualMachine from 'scratch-vm';
4
+ import Blocks from 'scratch-vm/src/engine/blocks.js';
5
+ import {deserializeBlocks} from 'scratch-vm/src/serialization/sb3.js';
6
+ import ScratchStorage from '@turbowarp/scratch-storage';
7
+ import ScratchRender from 'scratch-render';
8
+ import {BitmapAdapter} from '@turbowarp/scratch-svg-renderer';
9
+
10
+ function workspaceXml(vm, target) {
11
+ const variables = Object.assign({}, vm.runtime.getTargetForStage().variables, target.variables);
12
+ const declarations = Object.values(variables).map(variable => variable.toXML()).join('');
13
+ return `<xml xmlns="http://www.w3.org/1999/xhtml"><variables>${declarations}</variables>${target.blocks.toXML(target.comments)}</xml>`;
14
+ }
15
+
16
+ /** Starts a VM and a Blockly workspace in `container` and resolves with the editor host. */
17
+ export async function start(container, {locale = 'en', project} = {}) {
18
+ const Blockly = globalThis.Blockly;
19
+ if (!Blockly) throw new Error('scratch-blocks must be loaded before the runtime');
20
+ const vm = new VirtualMachine();
21
+ // Assets come only from what a test adds to storage; nothing is fetched from the network.
22
+ vm.attachStorage(new ScratchStorage());
23
+ // The VM falls back to drawing default costumes, which needs a renderer; the stage canvas stays off screen.
24
+ const canvas = document.createElement('canvas');
25
+ canvas.width = 480; canvas.height = 360;
26
+ vm.attachRenderer(new ScratchRender(canvas));
27
+ vm.attachV2BitmapAdapter(new BitmapAdapter());
28
+ const workspace = Blockly.inject(container, {
29
+ media: './media/', toolbox: '<xml><category name="Motion" id="motion" colour="#4C97FF" secondaryColour="#3373CC"></category></xml>',
30
+ zoom: {controls: false, wheel: false, startScale: 0.675}, scrollbars: true
31
+ });
32
+ workspace.addChangeListener(vm.blockListener);
33
+ vm.on('workspaceUpdate', data => {
34
+ Blockly.Events.disable();
35
+ try {Blockly.Xml.clearWorkspaceAndLoadFromXml(Blockly.Xml.textToDom(data.xml), workspace);}
36
+ finally {Blockly.Events.enable();}
37
+ });
38
+ let dirty = false;
39
+ const listeners = new Set();
40
+ const notify = () => {for (const listener of listeners) listener();};
41
+ vm.on('PROJECT_CHANGED', () => {dirty = true; notify();});
42
+ vm.start();
43
+ const host = {
44
+ vm, locale, workspace,
45
+ getBlockly: async () => Blockly,
46
+ deserializeBlocks,
47
+ createBlockContainer: () => new Blocks(vm.runtime, true),
48
+ isProjectDirty: () => dirty,
49
+ markSaved() {dirty = false; notify();},
50
+ isRunning: () => vm.runtime.threads.some(thread => !thread.updateMonitor && vm.runtime.isActiveThread(thread)),
51
+ subscribe(listener) {listeners.add(listener); return () => listeners.delete(listener);},
52
+ /** Shows external block changes, as the Editor does after reloading scripts in place. */
53
+ refreshBlockViews(targets) {
54
+ if (targets.includes(vm.editingTarget)) vm.emit('workspaceUpdate', {xml: workspaceXml(vm, vm.editingTarget)});
55
+ vm.emit('EXTERNAL_BLOCKS_RELOADED', targets);
56
+ },
57
+ async loadProject(json) {
58
+ await vm.loadProject(typeof json === 'string' ? json : JSON.stringify(json));
59
+ const sprite = vm.runtime.targets.find(target => !target.isStage) ?? vm.runtime.targets[0];
60
+ vm.setEditingTarget(sprite.id);
61
+ dirty = false;
62
+ notify();
63
+ }
64
+ };
65
+ if (project) await host.loadProject(project);
66
+ return host;
67
+ }