Files
feuerwerk/src/editor/plugins/pluginApi.ts
T
adminandClaude Opus 5.5 14972d057f
game-maker / gate (push) Successful in 3m53s
game-maker / suite (push) Successful in 11m55s
Refactoring round 8: hide data files, safe saves, Esc as Cancel (#85)
Recurring cleanup round over the code since round 7 (bc688f3). The
issue now also asks to fix bugs and small inconsistencies found on the
way, so unlike the rounds before, this one changes behaviour in a few
places. Duplicated code in api went from 23 clones with 228 lines to
none (jscpd, at least 50 tokens). In src it stays at 22 clones with
271 lines, the same before and after.

Bugs:
- nginx served project and snapshot files as they were, so anyone who
  knew a project id could read it without signing in. Every file the
  API writes now goes through AtomicFile (temp file, mode, rename).
  Projects, snapshots, releases, accounts and sessions are 0640, and
  nginx answers 403 for them.
- Any signed-in account could delete a shared image, font or sound,
  which projects of other accounts may wear. Deleting one is now for
  administrators only. The editor never deleted a file, so the
  client's delete is gone.
- Two saves of one project could run at once. The lock file was
  removed after each save, so a waiting save and the next one locked
  different files. The lock file now stays, and deleting a project
  takes the lock as well.
- Bytes that are no picture got a 500 instead of a 422, because the
  error handler also threw for warnings silenced with @.
- A session file was rewritten in place. A request reading it at that
  moment found it empty and was signed out. It is replaced atomically.
- Delete did nothing for a shape picked in the vector art list. Delete
  now goes through removeSelection, one case per kind of selection,
  and a kind without a case fails the type check.

Inconsistencies:
- Escape on a question does what its Cancel does. Cancel on "Delete
  project?" and "Restore snapshot?" leads back to the picker or the
  list like the other questions did, and so does deleting a project.
- Editor texts use American spelling throughout, like the port names:
  48 British spellings in 45 lines (colour, centre, initialised).
- objectName and groupName replace eleven copies of "own name, else
  the asset's" and three of "Group". One copy fell back to the object
  id instead of "?".

Duplicates, dead code, comments:
- routeFiles serves images, fonts and sounds instead of three copies.
  HashedFileStore holds what the three stores shared: keeping a file
  under its hash with its name, listing and deleting. The stores keep
  only which bytes they take and what a record says.
- AtomicFile replaces nine copies of temp file plus rename.
- removeShapes is the one way the canvas, the inspector button and
  Delete take shapes out.
- GraphInterpreter.fire was called by tests only. The 54 calls use a
  helper in tests/helpers.ts now.
- FileStore.delete, HttpFileStore.delete and the PluginApi type were
  unused. A doc comment in actions.ts sat above the wrong function.

Checked and left as is:
- solidCells is used by tests only. It is the per-cell view before the
  merge into rectangles, the one place the largest-scale rule shows.
- An undo checker ran all 124 commands of the unit tests and compared
  the project before and after undo. The only differences are empty
  ports, groups and notes lists where there were none, which the file
  format drops anyway.

Docs:
- README: the check sum.
- Wiki, own commit: API (admin-only deletes, 422, file modes, lock
  file), Home (the "Not yet" list named three things that exist),
  Concepts, Keyboard, Vector art, Architecture and Development, and
  the 38 characters Gitea flagged as ambiguous on eight pages.
- .gitignore: the lock files, and pasted-*.png in any folder, which
  keeps the screenshot archive out.

Tests:
- ./check.sh: 195 files, 2817 tests, exit 0 (+2 for the name helpers).
- PHP: accounts 52 in the web container and 53 in the CI image with
  the race test (+2), snapshots 15 (+1), releases 20.
- Full e2e run: ALL PASSED, 1586 checks (+6 in 12, 47, 49 and 50).
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks. The example
  project files were restored byte for byte afterwards.
- The file stores of HEAD and of this commit give byte-identical
  output for the live folders and for store, list and delete in a
  throwaway folder.
- Counter-checks, all fail as expected: a 500 for bad bytes fails 12,
  no admin check fails 49, removing the lock file again loses saves
  in 3 of 3 runs (151 to 170 of 321), Delete ignoring shapes fails 47,
  Escape that only closes fails 50, and dropping the shape case fails
  the type check (TS2366).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 18:12:55 +02:00

113 lines
4.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Widget } from '../../ui';
import { NodeBoard } from './NodeBoard';
/** The API version this editor offers. A plugin names the one it was written for in `meta.api`. */
export const PLUGIN_API_VERSION = 1;
export interface PluginAsset {
id: string;
name: string;
type: string;
}
/** What the editor lends the API – narrow, so the API can be exercised without an editor. */
export interface PluginHost {
assets(): PluginAsset[];
/** Called after every change to the model; returns the unsubscribe. */
onProjectChange(listener: () => void): () => void;
/** Whether a tab of this id exists already, built in or added by a plugin. */
hasTab(id: string): boolean;
addTab(id: string, label: string, content: Widget): void;
/** Takes a plugin's tab away again, its content with it. */
removeTab(id: string): void;
}
/**
* The host as one plugin sees it: every listener it subscribes and every tab it adds is written
* into `scope`, so switching the plugin off can take them away. An unsubscribe the plugin calls
* itself stays harmless when the scope calls it again.
*/
export function scopedHost(host: PluginHost, scope: { add(cleanup: () => void): void }): PluginHost {
return {
...host,
onProjectChange(listener) {
let off: (() => void) | null = host.onProjectChange(listener);
const unsubscribe = () => {
off?.();
off = null;
};
scope.add(unsubscribe);
return unsubscribe;
},
addTab(id, label, content) {
host.addTab(id, label, content);
scope.add(() => host.removeTab(id));
},
};
}
/** A change of the asset list, as `project.on('change')` sees it: ids, names and types in order. */
function assetSignature(assets: readonly PluginAsset[]): string {
return JSON.stringify(assets.map((a) => [a.id, a.name, a.type]));
}
function requireString(value: unknown, what: string): string {
if (typeof value !== 'string' || value === '') throw new TypeError(`${what} must be a non-empty string`);
return value;
}
/**
* The `api` a plugin's `activate` receives, version 1: read the assets and hear when they change,
* add a tab, and build its content from `api.ui`. Every plugin gets its own, so what it does can
* be told apart in the console.
*/
export function createPluginApi(pluginId: string, host: PluginHost) {
const project = Object.freeze({
assets: (): PluginAsset[] => host.assets().map(({ id, name, type }) => ({ id, name, type })),
/**
* Only a change a plugin can see calls back: the model changes on every step of a drag, the
* asset list almost never. A listener that throws is reported and stays subscribed.
*/
on(event: string, listener: () => void): () => void {
if (event !== 'change') throw new Error(`Unknown project event "${event}" – API v1 knows "change"`);
if (typeof listener !== 'function') throw new TypeError('project.on needs a listener function');
let seen = assetSignature(host.assets());
return host.onProjectChange(() => {
const next = assetSignature(host.assets());
if (next === seen) return;
seen = next;
try {
listener();
} catch (error) {
console.error(`[plugin ${pluginId}] change listener failed:`, error);
}
});
},
});
const tabs = Object.freeze({
/** False, with a warning, when the id is taken – by a built-in tab or an earlier plugin. */
add(tab: { id: unknown; label: unknown; create: unknown }): boolean {
const id = requireString(tab.id, 'tabs.add: id');
const label = requireString(tab.label, 'tabs.add: label');
if (typeof tab.create !== 'function') throw new TypeError('tabs.add: create must be a function');
if (host.hasTab(id)) {
console.warn(`[plugin ${pluginId}] a tab "${id}" exists already – not added`);
return false;
}
const content: unknown = (tab.create as () => unknown)();
if (!(content instanceof Widget))
throw new TypeError(`tabs.add: create must return a widget from api.ui (tab "${id}")`);
host.addTab(id, label, content);
return true;
},
});
return Object.freeze({
version: PLUGIN_API_VERSION,
project,
tabs,
ui: Object.freeze({ NodeBoard }),
});
}