@kubohiroya/turbowarp-diagnostic-overlay 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.
Files changed (39) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +4 -0
  3. package/README.md +163 -0
  4. package/dist/diagnostic-overlay.js +574 -0
  5. package/dist/lib/block-definitions.json +58 -0
  6. package/dist/lib/composition.d.ts +22 -0
  7. package/dist/lib/composition.d.ts.map +1 -0
  8. package/dist/lib/composition.js +20 -0
  9. package/dist/lib/composition.js.map +1 -0
  10. package/dist/lib/config.d.ts +10 -0
  11. package/dist/lib/config.d.ts.map +1 -0
  12. package/dist/lib/config.js +10 -0
  13. package/dist/lib/config.js.map +1 -0
  14. package/dist/lib/diagnostic.d.ts +30 -0
  15. package/dist/lib/diagnostic.d.ts.map +1 -0
  16. package/dist/lib/diagnostic.js +120 -0
  17. package/dist/lib/diagnostic.js.map +1 -0
  18. package/dist/lib/extension.d.ts +24 -0
  19. package/dist/lib/extension.d.ts.map +1 -0
  20. package/dist/lib/extension.js +94 -0
  21. package/dist/lib/extension.js.map +1 -0
  22. package/dist/lib/index.d.ts +2 -0
  23. package/dist/lib/index.d.ts.map +1 -0
  24. package/dist/lib/index.js +8 -0
  25. package/dist/lib/index.js.map +1 -0
  26. package/dist/lib/overlay.d.ts +39 -0
  27. package/dist/lib/overlay.d.ts.map +1 -0
  28. package/dist/lib/overlay.js +140 -0
  29. package/dist/lib/overlay.js.map +1 -0
  30. package/dist/lib/scratch.d.ts +32 -0
  31. package/dist/lib/scratch.d.ts.map +1 -0
  32. package/dist/lib/scratch.js +2 -0
  33. package/dist/lib/scratch.js.map +1 -0
  34. package/dist/lib/svg-renderer.d.ts +12 -0
  35. package/dist/lib/svg-renderer.d.ts.map +1 -0
  36. package/dist/lib/svg-renderer.js +180 -0
  37. package/dist/lib/svg-renderer.js.map +1 -0
  38. package/docs/specification.md +67 -0
  39. package/package.json +90 -0
@@ -0,0 +1,574 @@
1
+ // Name: Diagnostic Overlay
2
+ // ID: kubohiroyadiagnosticoverlay
3
+ // Description: Render structured diagnostics as safe SVG overlays on the TurboWarp stage.
4
+ // By: Hiroya Kubo
5
+ // License: MPL-2.0
6
+
7
+ (function (Scratch) {
8
+ 'use strict';
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
13
+ const extensionName = "Diagnostic Overlay";
14
+ const blocks = [{ "opcode": "showDiagnostic", "blockType": "COMMAND", "text": "show [SEVERITY] diagnostic [CODE]: [MESSAGE]", "description": "Displays a simple diagnostic on the TurboWarp stage.", "arguments": { "SEVERITY": { "type": "STRING", "defaultValue": "error", "menu": "severityMenu" }, "CODE": { "type": "STRING", "defaultValue": "APP001" }, "MESSAGE": { "type": "STRING", "defaultValue": "Something went wrong." } } }, { "opcode": "showDiagnosticJson", "blockType": "COMMAND", "text": "show diagnostic JSON [DIAGNOSTIC]", "description": "Validates and displays one structured diagnostic JSON object.", "arguments": { "DIAGNOSTIC": { "type": "STRING", "defaultValue": '{"severity":"error","code":"APP001","message":"Something went wrong."}' } } }, { "opcode": "clearDiagnosticOverlay", "blockType": "COMMAND", "text": "clear diagnostic overlay", "description": "Removes the current diagnostic overlay without stopping the project.", "arguments": {} }, { "opcode": "diagnosticOverlayVisible", "blockType": "BOOLEAN", "text": "diagnostic overlay is visible?", "description": "Returns whether a diagnostic overlay is currently visible.", "disableMonitor": true, "arguments": {} }, { "opcode": "diagnosticSvg", "blockType": "REPORTER", "text": "diagnostic SVG for JSON [DIAGNOSTIC]", "description": "Returns safe SVG text for one diagnostic without displaying it.", "disableMonitor": true, "arguments": { "DIAGNOSTIC": { "type": "STRING", "defaultValue": '{"severity":"warning","code":"APP002","message":"Please check the input."}' } } }, { "opcode": "lastDiagnosticJson", "blockType": "REPORTER", "text": "last diagnostic JSON", "description": "Returns the last displayed normalized diagnostic as JSON, or an empty string.", "disableMonitor": true, "arguments": {} }];
15
+ const definitions = {
16
+ extensionName,
17
+ blocks
18
+ };
19
+ const extensionConfig = {
20
+ id: "kubohiroyadiagnosticoverlay",
21
+ name: "Diagnostic Overlay"
22
+ };
23
+ const DIAGNOSTIC_SEVERITIES = ["info", "warning", "error", "fatal"];
24
+ const MAX_JSON_LENGTH = 65536;
25
+ const MAX_CODE_LENGTH = 256;
26
+ const MAX_MESSAGE_LENGTH = 16384;
27
+ const MAX_DETAIL_LENGTH = 32768;
28
+ const MAX_SOURCE_NAME_LENGTH = 2048;
29
+ const MAX_EXCERPT_LENGTH = 32768;
30
+ class DiagnosticValidationError extends Error {
31
+ constructor(path, message) {
32
+ super(`${path}: ${message}`);
33
+ __publicField(this, "path");
34
+ this.path = path;
35
+ this.name = "DiagnosticValidationError";
36
+ }
37
+ }
38
+ function parseDiagnosticJson(input) {
39
+ if (input.length > MAX_JSON_LENGTH) {
40
+ throw new DiagnosticValidationError("$", `JSON exceeds ${MAX_JSON_LENGTH} characters`);
41
+ }
42
+ let value;
43
+ try {
44
+ value = JSON.parse(input);
45
+ } catch (error) {
46
+ const detail = error instanceof Error ? error.message : String(error);
47
+ throw new DiagnosticValidationError("$", `invalid JSON (${detail})`);
48
+ }
49
+ return normalizeDiagnostic(value);
50
+ }
51
+ function normalizeDiagnostic(value) {
52
+ if (!isRecord(value)) {
53
+ throw new DiagnosticValidationError("$", "expected an object");
54
+ }
55
+ const severity = readSeverity(value.severity);
56
+ const code = readRequiredText(value.code, "$.code", MAX_CODE_LENGTH);
57
+ const message = readRequiredText(value.message, "$.message", MAX_MESSAGE_LENGTH);
58
+ const detail = readOptionalText(value.detail, "$.detail", MAX_DETAIL_LENGTH);
59
+ const source = readSource(value.source);
60
+ return Object.freeze({
61
+ severity,
62
+ code,
63
+ message,
64
+ ...detail === void 0 ? {} : { detail },
65
+ ...source === void 0 ? {} : { source }
66
+ });
67
+ }
68
+ function diagnosticToJson(diagnostic) {
69
+ return JSON.stringify(diagnostic);
70
+ }
71
+ function readSeverity(value) {
72
+ if (typeof value !== "string") {
73
+ throw new DiagnosticValidationError("$.severity", "expected a string");
74
+ }
75
+ const normalized = value.trim().toLowerCase();
76
+ if (!isDiagnosticSeverity(normalized)) {
77
+ throw new DiagnosticValidationError(
78
+ "$.severity",
79
+ `expected one of ${DIAGNOSTIC_SEVERITIES.join(", ")}`
80
+ );
81
+ }
82
+ return normalized;
83
+ }
84
+ function readSource(value) {
85
+ if (value === void 0 || value === null) return void 0;
86
+ if (!isRecord(value)) {
87
+ throw new DiagnosticValidationError("$.source", "expected an object");
88
+ }
89
+ const name = readOptionalText(value.name, "$.source.name", MAX_SOURCE_NAME_LENGTH);
90
+ const line = readOptionalPosition(value.line, "$.source.line");
91
+ const column = readOptionalPosition(value.column, "$.source.column");
92
+ const excerpt = readOptionalText(value.excerpt, "$.source.excerpt", MAX_EXCERPT_LENGTH);
93
+ if (name === void 0 && line === void 0 && column === void 0 && excerpt === void 0) {
94
+ return void 0;
95
+ }
96
+ return Object.freeze({
97
+ ...name === void 0 ? {} : { name },
98
+ ...line === void 0 ? {} : { line },
99
+ ...column === void 0 ? {} : { column },
100
+ ...excerpt === void 0 ? {} : { excerpt }
101
+ });
102
+ }
103
+ function readRequiredText(value, path, maxLength) {
104
+ if (typeof value !== "string") {
105
+ throw new DiagnosticValidationError(path, "expected a string");
106
+ }
107
+ const normalized = value.trim();
108
+ if (!normalized) throw new DiagnosticValidationError(path, "must not be empty");
109
+ if (normalized.length > maxLength) {
110
+ throw new DiagnosticValidationError(path, `exceeds ${maxLength} characters`);
111
+ }
112
+ return normalized;
113
+ }
114
+ function readOptionalText(value, path, maxLength) {
115
+ if (value === void 0 || value === null) return void 0;
116
+ if (typeof value !== "string") {
117
+ throw new DiagnosticValidationError(path, "expected a string");
118
+ }
119
+ const normalized = value.trim();
120
+ if (!normalized) return void 0;
121
+ if (normalized.length > maxLength) {
122
+ throw new DiagnosticValidationError(path, `exceeds ${maxLength} characters`);
123
+ }
124
+ return normalized;
125
+ }
126
+ function readOptionalPosition(value, path) {
127
+ if (value === void 0 || value === null) return void 0;
128
+ if (!Number.isSafeInteger(value) || value < 1) {
129
+ throw new DiagnosticValidationError(path, "expected a positive integer");
130
+ }
131
+ return value;
132
+ }
133
+ function isDiagnosticSeverity(value) {
134
+ return DIAGNOSTIC_SEVERITIES.includes(value);
135
+ }
136
+ function isRecord(value) {
137
+ return typeof value === "object" && value !== null && !Array.isArray(value);
138
+ }
139
+ const blockDefinitions = definitions.blocks;
140
+ class DiagnosticOverlayExtension {
141
+ constructor(scratch, controller) {
142
+ __publicField(this, "scratch");
143
+ __publicField(this, "controller");
144
+ __publicField(this, "runtime");
145
+ __publicField(this, "disposed", false);
146
+ __publicField(this, "dispose", () => {
147
+ if (this.disposed) return;
148
+ this.disposed = true;
149
+ this.runtime.off?.("PROJECT_LOADED", this.clearOnProjectLoad);
150
+ this.runtime.off?.("RUNTIME_DISPOSED", this.dispose);
151
+ this.controller.dispose();
152
+ });
153
+ __publicField(this, "clearOnProjectLoad", () => {
154
+ this.controller.clear();
155
+ });
156
+ this.scratch = scratch;
157
+ this.controller = controller;
158
+ this.runtime = scratch.vm.runtime;
159
+ this.runtime.on?.("PROJECT_LOADED", this.clearOnProjectLoad);
160
+ this.runtime.on?.("RUNTIME_DISPOSED", this.dispose);
161
+ }
162
+ getInfo() {
163
+ return {
164
+ id: extensionConfig.id,
165
+ name: this.scratch.translate(definitions.extensionName),
166
+ color1: "#C44747",
167
+ color2: "#A83B3B",
168
+ color3: "#8C3030",
169
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
170
+ menus: {
171
+ severityMenu: {
172
+ acceptReporters: true,
173
+ items: ["info", "warning", "error", "fatal"]
174
+ }
175
+ }
176
+ };
177
+ }
178
+ showDiagnostic(args) {
179
+ const diagnostic = {
180
+ severity: this.severity(args.SEVERITY),
181
+ code: this.string(args.CODE),
182
+ message: this.string(args.MESSAGE)
183
+ };
184
+ this.controller.show(diagnostic);
185
+ }
186
+ showDiagnosticJson(args) {
187
+ this.controller.show(parseDiagnosticJson(this.string(args.DIAGNOSTIC)));
188
+ }
189
+ clearDiagnosticOverlay() {
190
+ this.controller.clear();
191
+ }
192
+ diagnosticOverlayVisible() {
193
+ return this.controller.isVisible();
194
+ }
195
+ diagnosticSvg(args) {
196
+ return this.controller.render(parseDiagnosticJson(this.string(args.DIAGNOSTIC)));
197
+ }
198
+ lastDiagnosticJson() {
199
+ return this.controller.lastDiagnosticJson();
200
+ }
201
+ toScratchBlock(block) {
202
+ return {
203
+ opcode: block.opcode,
204
+ blockType: this.scratch.BlockType[block.blockType],
205
+ text: this.scratch.translate(block.text),
206
+ ...block.disableMonitor ? { disableMonitor: true } : {},
207
+ arguments: Object.fromEntries(
208
+ Object.entries(block.arguments).map(([name, argument]) => [
209
+ name,
210
+ {
211
+ type: this.scratch.ArgumentType[argument.type],
212
+ defaultValue: argument.defaultValue,
213
+ ...argument.menu ? { menu: argument.menu } : {}
214
+ }
215
+ ])
216
+ )
217
+ };
218
+ }
219
+ string(value) {
220
+ return this.scratch.Cast.toString(value);
221
+ }
222
+ severity(value) {
223
+ const severity = this.string(value).trim().toLowerCase();
224
+ if (severity === "info" || severity === "warning" || severity === "error" || severity === "fatal") {
225
+ return severity;
226
+ }
227
+ throw new Error(`Unsupported diagnostic severity: ${severity}`);
228
+ }
229
+ }
230
+ const DEFAULT_OPTIONS = {
231
+ width: 480,
232
+ height: 360,
233
+ maxMessageLines: 3,
234
+ maxDetailLines: 4,
235
+ maxExcerptLines: 4
236
+ };
237
+ const THEMES = {
238
+ info: { accent: "#4CA6FF", label: "INFO" },
239
+ warning: { accent: "#F0C24B", label: "WARNING" },
240
+ error: { accent: "#FF6B6B", label: "ERROR" },
241
+ fatal: { accent: "#FF3B5C", label: "FATAL" }
242
+ };
243
+ const INVALID_XML_CHARACTER = /[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu;
244
+ function renderDiagnosticSvg(input, options = {}) {
245
+ const diagnostic = normalizeDiagnostic(input);
246
+ const resolved = resolveOptions(options);
247
+ const theme = THEMES[diagnostic.severity];
248
+ const padding = Math.max(18, Math.round(resolved.width * 0.055));
249
+ const panelX = Math.max(8, Math.round(resolved.width * 0.025));
250
+ const panelY = Math.max(8, Math.round(resolved.height * 0.035));
251
+ const panelWidth = resolved.width - panelX * 2;
252
+ const panelHeight = resolved.height - panelY * 2;
253
+ const textX = panelX + padding;
254
+ const textWidth = panelWidth - padding * 2;
255
+ const titleSize = clamp(Math.round(resolved.height * 0.047), 13, 18);
256
+ const messageSize = clamp(Math.round(resolved.height * 0.054), 15, 21);
257
+ const bodySize = clamp(Math.round(resolved.height * 0.038), 12, 16);
258
+ const smallSize = clamp(Math.round(resolved.height * 0.033), 11, 14);
259
+ let cursorY = panelY + padding + titleSize;
260
+ const parts = [];
261
+ parts.push(
262
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${resolved.width} ${resolved.height}" role="img" aria-labelledby="diagnostic-title diagnostic-description">`,
263
+ `<title id="diagnostic-title">${escapeXml(`${theme.label} ${diagnostic.code}`)}</title>`,
264
+ `<desc id="diagnostic-description">${escapeXml(accessibleDiagnosticText(diagnostic))}</desc>`,
265
+ `<rect width="${resolved.width}" height="${resolved.height}" fill="#05070A" fill-opacity="0.42"/>`,
266
+ `<rect x="${panelX}" y="${panelY}" width="${panelWidth}" height="${panelHeight}" rx="12" fill="#151922" fill-opacity="0.97" stroke="${theme.accent}" stroke-width="2"/>`,
267
+ `<rect x="${panelX}" y="${panelY}" width="6" height="${panelHeight}" rx="3" fill="${theme.accent}"/>`,
268
+ textElement([`${theme.label} ${diagnostic.code}`], textX, cursorY, titleSize, theme.accent, 700)
269
+ );
270
+ cursorY += Math.round(messageSize * 1.7);
271
+ const messageLines = truncateLines(
272
+ wrapText(diagnostic.message, maxUnits(textWidth, messageSize)),
273
+ resolved.maxMessageLines,
274
+ maxUnits(textWidth, messageSize)
275
+ );
276
+ parts.push(textElement(messageLines, textX, cursorY, messageSize, "#FFFFFF", 700));
277
+ cursorY += lineBlockHeight(messageLines.length, messageSize) + Math.round(bodySize * 0.85);
278
+ if (diagnostic.detail) {
279
+ const detailLines = truncateLines(
280
+ wrapText(diagnostic.detail, maxUnits(textWidth, bodySize)),
281
+ resolved.maxDetailLines,
282
+ maxUnits(textWidth, bodySize)
283
+ );
284
+ parts.push(textElement(detailLines, textX, cursorY, bodySize, "#DCE2EE", 400));
285
+ cursorY += lineBlockHeight(detailLines.length, bodySize) + Math.round(smallSize * 0.9);
286
+ }
287
+ const sourceLabel = formatSource(diagnostic);
288
+ if (sourceLabel) {
289
+ parts.push(textElement([sourceLabel], textX, cursorY, smallSize, "#AEB8CA", 600));
290
+ cursorY += Math.round(smallSize * 1.65);
291
+ }
292
+ if (diagnostic.source?.excerpt) {
293
+ const excerptY = cursorY - Math.round(smallSize * 0.78);
294
+ const availableHeight = panelY + panelHeight - padding - excerptY;
295
+ const possibleLines = Math.max(1, Math.floor(availableHeight / (smallSize * 1.35)));
296
+ const excerptLineLimit = Math.min(resolved.maxExcerptLines, possibleLines);
297
+ const excerptPadding = Math.max(8, Math.round(smallSize * 0.8));
298
+ const excerptWidth = textWidth - excerptPadding * 2;
299
+ const excerptLines = truncateLines(
300
+ wrapText(diagnostic.source.excerpt, maxUnits(excerptWidth, smallSize)),
301
+ excerptLineLimit,
302
+ maxUnits(excerptWidth, smallSize)
303
+ );
304
+ const excerptHeight = lineBlockHeight(excerptLines.length, smallSize) + excerptPadding * 2;
305
+ parts.push(
306
+ `<rect x="${textX}" y="${excerptY}" width="${textWidth}" height="${excerptHeight}" rx="5" fill="#090C12" stroke="#303848"/>`,
307
+ textElement(
308
+ excerptLines,
309
+ textX + excerptPadding,
310
+ excerptY + excerptPadding + smallSize,
311
+ smallSize,
312
+ "#E7ECF5",
313
+ 400,
314
+ "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"
315
+ )
316
+ );
317
+ }
318
+ parts.push("</svg>");
319
+ return parts.join("");
320
+ }
321
+ function accessibleDiagnosticText(diagnostic) {
322
+ return [
323
+ diagnostic.severity.toUpperCase(),
324
+ diagnostic.code,
325
+ diagnostic.message,
326
+ diagnostic.detail,
327
+ formatSource(diagnostic),
328
+ diagnostic.source?.excerpt
329
+ ].filter((part) => Boolean(part)).join(". ");
330
+ }
331
+ function escapeXml(value) {
332
+ return value.replace(INVALID_XML_CHARACTER, "�").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
333
+ }
334
+ function resolveOptions(options) {
335
+ return {
336
+ width: positiveInteger(options.width, DEFAULT_OPTIONS.width, 160, 4096),
337
+ height: positiveInteger(options.height, DEFAULT_OPTIONS.height, 120, 4096),
338
+ maxMessageLines: positiveInteger(options.maxMessageLines, DEFAULT_OPTIONS.maxMessageLines, 1, 12),
339
+ maxDetailLines: positiveInteger(options.maxDetailLines, DEFAULT_OPTIONS.maxDetailLines, 1, 20),
340
+ maxExcerptLines: positiveInteger(options.maxExcerptLines, DEFAULT_OPTIONS.maxExcerptLines, 1, 20)
341
+ };
342
+ }
343
+ function positiveInteger(value, fallback, min, max) {
344
+ if (value === void 0) return fallback;
345
+ if (!Number.isFinite(value)) return fallback;
346
+ return clamp(Math.round(value), min, max);
347
+ }
348
+ function textElement(lines, x, y, size, fill, weight, family = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif') {
349
+ const lineHeight = Math.round(size * 1.35);
350
+ const tspans = lines.map(
351
+ (line, index) => `<tspan x="${x}" dy="${index === 0 ? 0 : lineHeight}">${escapeXml(line)}</tspan>`
352
+ ).join("");
353
+ return `<text x="${x}" y="${y}" fill="${fill}" font-family="${escapeXml(family)}" font-size="${size}" font-weight="${weight}" xml:space="preserve">${tspans}</text>`;
354
+ }
355
+ function wrapText(value, limit) {
356
+ const lines = [];
357
+ for (const paragraph of value.replaceAll("\r\n", "\n").replaceAll("\r", "\n").split("\n")) {
358
+ if (!paragraph) {
359
+ lines.push(" ");
360
+ continue;
361
+ }
362
+ let current = "";
363
+ let units = 0;
364
+ for (const character of Array.from(paragraph)) {
365
+ const nextUnits = characterUnits(character);
366
+ if (current && units + nextUnits > limit) {
367
+ lines.push(current.trimEnd());
368
+ current = character.trimStart();
369
+ units = current ? nextUnits : 0;
370
+ } else {
371
+ current += character;
372
+ units += nextUnits;
373
+ }
374
+ }
375
+ if (current || lines.length === 0) lines.push(current.trimEnd());
376
+ }
377
+ return lines;
378
+ }
379
+ function truncateLines(lines, limit, lineUnits) {
380
+ if (lines.length <= limit) return lines;
381
+ const result = lines.slice(0, limit);
382
+ const lastIndex = result.length - 1;
383
+ const last = result[lastIndex] ?? "";
384
+ result[lastIndex] = appendEllipsis(last, lineUnits);
385
+ return result;
386
+ }
387
+ function appendEllipsis(value, limit) {
388
+ const ellipsis = "…";
389
+ let result = value.trimEnd();
390
+ while (result && textUnits(result) + characterUnits(ellipsis) > limit) {
391
+ result = Array.from(result).slice(0, -1).join("").trimEnd();
392
+ }
393
+ return `${result}${ellipsis}`;
394
+ }
395
+ function characterUnits(character) {
396
+ if (/\p{Mark}/u.test(character)) return 0;
397
+ if (/\s/u.test(character)) return 0.35;
398
+ if (/^[\u0020-\u007e]$/u.test(character)) return 0.58;
399
+ return 1;
400
+ }
401
+ function textUnits(value) {
402
+ return Array.from(value).reduce((total, character) => total + characterUnits(character), 0);
403
+ }
404
+ function maxUnits(width, fontSize) {
405
+ return Math.max(8, width / fontSize);
406
+ }
407
+ function lineBlockHeight(lineCount, fontSize) {
408
+ return fontSize + Math.max(0, lineCount - 1) * Math.round(fontSize * 1.35);
409
+ }
410
+ function formatSource(diagnostic) {
411
+ const source = diagnostic.source;
412
+ if (!source) return void 0;
413
+ const position = [
414
+ source.line === void 0 ? void 0 : `line ${source.line}`,
415
+ source.column === void 0 ? void 0 : `column ${source.column}`
416
+ ].filter((part) => part !== void 0).join(", ");
417
+ if (source.name && position) return `${source.name} — ${position}`;
418
+ return source.name ?? (position || void 0);
419
+ }
420
+ function clamp(value, min, max) {
421
+ return Math.min(max, Math.max(min, value));
422
+ }
423
+ class DiagnosticOverlayController {
424
+ constructor(host, svgOptions = {}) {
425
+ __publicField(this, "host");
426
+ __publicField(this, "svgOptions");
427
+ __publicField(this, "lastDiagnostic", null);
428
+ this.host = host;
429
+ this.svgOptions = svgOptions;
430
+ }
431
+ show(input) {
432
+ const diagnostic = normalizeDiagnostic(input);
433
+ const svg = renderDiagnosticSvg(diagnostic, this.svgOptions);
434
+ this.host.showSvg(svg, accessibleDiagnosticText(diagnostic));
435
+ this.lastDiagnostic = diagnostic;
436
+ return svg;
437
+ }
438
+ render(input) {
439
+ return renderDiagnosticSvg(normalizeDiagnostic(input), this.svgOptions);
440
+ }
441
+ clear() {
442
+ this.host.clear();
443
+ this.lastDiagnostic = null;
444
+ }
445
+ isVisible() {
446
+ return this.host.isVisible();
447
+ }
448
+ lastDiagnosticJson() {
449
+ return this.lastDiagnostic === null ? "" : diagnosticToJson(this.lastDiagnostic);
450
+ }
451
+ dispose() {
452
+ this.lastDiagnostic = null;
453
+ this.host.dispose();
454
+ }
455
+ }
456
+ class BrowserStageOverlayHost {
457
+ constructor(canvas, document = canvas.ownerDocument) {
458
+ __publicField(this, "canvas");
459
+ __publicField(this, "document");
460
+ __publicField(this, "container");
461
+ __publicField(this, "parent");
462
+ __publicField(this, "window");
463
+ __publicField(this, "resizeObserver", null);
464
+ __publicField(this, "changedParentPosition", false);
465
+ __publicField(this, "previousParentPosition", "");
466
+ __publicField(this, "disposed", false);
467
+ __publicField(this, "updateGeometry", () => {
468
+ if (this.disposed) return;
469
+ const canvasRect = this.canvas.getBoundingClientRect();
470
+ const parentRect = this.parent.getBoundingClientRect();
471
+ const left = canvasRect.left - parentRect.left + this.parent.scrollLeft;
472
+ const top = canvasRect.top - parentRect.top + this.parent.scrollTop;
473
+ Object.assign(this.container.style, {
474
+ left: `${left}px`,
475
+ top: `${top}px`,
476
+ width: `${canvasRect.width}px`,
477
+ height: `${canvasRect.height}px`
478
+ });
479
+ });
480
+ this.canvas = canvas;
481
+ this.document = document;
482
+ const parent = canvas.parentElement;
483
+ if (!parent) throw new Error("TurboWarp renderer canvas has no parent element.");
484
+ this.parent = parent;
485
+ this.window = document.defaultView;
486
+ this.container = document.createElement("div");
487
+ this.container.dataset.turbowarpDiagnosticOverlay = "true";
488
+ this.container.setAttribute("role", "alert");
489
+ this.container.setAttribute("aria-live", "assertive");
490
+ this.container.hidden = true;
491
+ Object.assign(this.container.style, {
492
+ position: "absolute",
493
+ pointerEvents: "none",
494
+ overflow: "hidden",
495
+ zIndex: "2147483647"
496
+ });
497
+ const position = this.window?.getComputedStyle(parent).position ?? parent.style.position;
498
+ if (!position || position === "static") {
499
+ this.previousParentPosition = parent.style.position;
500
+ parent.style.position = "relative";
501
+ this.changedParentPosition = true;
502
+ }
503
+ parent.append(this.container);
504
+ this.updateGeometry();
505
+ this.window?.addEventListener("resize", this.updateGeometry);
506
+ const ResizeObserverConstructor = this.window?.ResizeObserver;
507
+ if (ResizeObserverConstructor) {
508
+ const resizeObserver = new ResizeObserverConstructor(this.updateGeometry);
509
+ this.resizeObserver = resizeObserver;
510
+ resizeObserver.observe(canvas);
511
+ }
512
+ }
513
+ showSvg(svg, accessibleText) {
514
+ this.ensureActive();
515
+ const Parser = this.window?.DOMParser ?? globalThis.DOMParser;
516
+ if (!Parser) throw new Error("DOMParser is not available.");
517
+ const parsed = new Parser().parseFromString(svg, "image/svg+xml");
518
+ if (parsed.querySelector("parsererror") || parsed.documentElement.localName !== "svg") {
519
+ throw new Error("Generated diagnostic SVG is invalid.");
520
+ }
521
+ const imported = this.document.importNode(
522
+ parsed.documentElement,
523
+ true
524
+ );
525
+ imported.style.width = "100%";
526
+ imported.style.height = "100%";
527
+ imported.style.display = "block";
528
+ this.container.replaceChildren(imported);
529
+ this.container.setAttribute("aria-label", accessibleText);
530
+ this.updateGeometry();
531
+ this.container.hidden = false;
532
+ }
533
+ clear() {
534
+ if (this.disposed) return;
535
+ this.container.hidden = true;
536
+ this.container.removeAttribute("aria-label");
537
+ this.container.replaceChildren();
538
+ }
539
+ isVisible() {
540
+ return !this.disposed && !this.container.hidden;
541
+ }
542
+ dispose() {
543
+ if (this.disposed) return;
544
+ this.disposed = true;
545
+ this.resizeObserver?.disconnect();
546
+ this.resizeObserver = null;
547
+ this.window?.removeEventListener("resize", this.updateGeometry);
548
+ this.container.remove();
549
+ if (this.changedParentPosition && this.parent.style.position === "relative") {
550
+ this.parent.style.position = this.previousParentPosition;
551
+ }
552
+ }
553
+ ensureActive() {
554
+ if (this.disposed) throw new Error("Diagnostic overlay host has been disposed.");
555
+ }
556
+ }
557
+ function createDiagnosticOverlayComposition(scratch, options = {}) {
558
+ const runtime = scratch.vm.runtime;
559
+ const host = options.host ?? new BrowserStageOverlayHost(runtime.renderer.canvas);
560
+ const controller = new DiagnosticOverlayController(host, {
561
+ width: runtime.stageWidth ?? 480,
562
+ height: runtime.stageHeight ?? 360,
563
+ ...options.svg
564
+ });
565
+ const extension2 = new DiagnosticOverlayExtension(scratch, controller);
566
+ return { extension: extension2, controller, host };
567
+ }
568
+ if (!Scratch.extensions.unsandboxed) {
569
+ throw new Error(`${extensionConfig.name} must run unsandboxed.`);
570
+ }
571
+ const { extension } = createDiagnosticOverlayComposition(Scratch);
572
+ Scratch.extensions.register(extension);
573
+
574
+ })(Scratch);
@@ -0,0 +1,58 @@
1
+ {
2
+ "extensionName": "Diagnostic Overlay",
3
+ "blocks": [
4
+ {
5
+ "opcode": "showDiagnostic",
6
+ "blockType": "COMMAND",
7
+ "text": "show [SEVERITY] diagnostic [CODE]: [MESSAGE]",
8
+ "description": "Displays a simple diagnostic on the TurboWarp stage.",
9
+ "arguments": {
10
+ "SEVERITY": { "type": "STRING", "defaultValue": "error", "menu": "severityMenu" },
11
+ "CODE": { "type": "STRING", "defaultValue": "APP001" },
12
+ "MESSAGE": { "type": "STRING", "defaultValue": "Something went wrong." }
13
+ }
14
+ },
15
+ {
16
+ "opcode": "showDiagnosticJson",
17
+ "blockType": "COMMAND",
18
+ "text": "show diagnostic JSON [DIAGNOSTIC]",
19
+ "description": "Validates and displays one structured diagnostic JSON object.",
20
+ "arguments": {
21
+ "DIAGNOSTIC": { "type": "STRING", "defaultValue": "{\"severity\":\"error\",\"code\":\"APP001\",\"message\":\"Something went wrong.\"}" }
22
+ }
23
+ },
24
+ {
25
+ "opcode": "clearDiagnosticOverlay",
26
+ "blockType": "COMMAND",
27
+ "text": "clear diagnostic overlay",
28
+ "description": "Removes the current diagnostic overlay without stopping the project.",
29
+ "arguments": {}
30
+ },
31
+ {
32
+ "opcode": "diagnosticOverlayVisible",
33
+ "blockType": "BOOLEAN",
34
+ "text": "diagnostic overlay is visible?",
35
+ "description": "Returns whether a diagnostic overlay is currently visible.",
36
+ "disableMonitor": true,
37
+ "arguments": {}
38
+ },
39
+ {
40
+ "opcode": "diagnosticSvg",
41
+ "blockType": "REPORTER",
42
+ "text": "diagnostic SVG for JSON [DIAGNOSTIC]",
43
+ "description": "Returns safe SVG text for one diagnostic without displaying it.",
44
+ "disableMonitor": true,
45
+ "arguments": {
46
+ "DIAGNOSTIC": { "type": "STRING", "defaultValue": "{\"severity\":\"warning\",\"code\":\"APP002\",\"message\":\"Please check the input.\"}" }
47
+ }
48
+ },
49
+ {
50
+ "opcode": "lastDiagnosticJson",
51
+ "blockType": "REPORTER",
52
+ "text": "last diagnostic JSON",
53
+ "description": "Returns the last displayed normalized diagnostic as JSON, or an empty string.",
54
+ "disableMonitor": true,
55
+ "arguments": {}
56
+ }
57
+ ]
58
+ }
@@ -0,0 +1,22 @@
1
+ import { DiagnosticOverlayExtension } from './extension.js';
2
+ import { DiagnosticOverlayController } from './overlay.js';
3
+ import type { DiagnosticOverlayHost } from './overlay.js';
4
+ import type { ScratchApi } from './scratch.js';
5
+ import type { DiagnosticSvgOptions } from './svg-renderer.js';
6
+ export * from './config.js';
7
+ export * from './diagnostic.js';
8
+ export * from './overlay.js';
9
+ export * from './scratch.js';
10
+ export * from './svg-renderer.js';
11
+ export { DiagnosticOverlayExtension };
12
+ export interface DiagnosticOverlayCompositionOptions {
13
+ host?: DiagnosticOverlayHost;
14
+ svg?: DiagnosticSvgOptions;
15
+ }
16
+ export interface DiagnosticOverlayComposition {
17
+ extension: DiagnosticOverlayExtension;
18
+ controller: DiagnosticOverlayController;
19
+ host: DiagnosticOverlayHost;
20
+ }
21
+ export declare function createDiagnosticOverlayComposition(scratch: ScratchApi, options?: DiagnosticOverlayCompositionOptions): DiagnosticOverlayComposition;
22
+ //# sourceMappingURL=composition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composition.d.ts","sourceRoot":"","sources":["../../src/composition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,0BAA0B,EAAC,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAA0B,2BAA2B,EAAC,MAAM,cAAc,CAAC;AAClF,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,cAAc,CAAC;AACxD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,cAAc,CAAC;AAC7C,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,mBAAmB,CAAC;AAE5D,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAC,0BAA0B,EAAC,CAAC;AAEpC,MAAM,WAAW,mCAAmC;IAClD,IAAI,CAAC,EAAE,qBAAqB,CAAC;IAC7B,GAAG,CAAC,EAAE,oBAAoB,CAAC;CAC5B;AAED,MAAM,WAAW,4BAA4B;IAC3C,SAAS,EAAE,0BAA0B,CAAC;IACtC,UAAU,EAAE,2BAA2B,CAAC;IACxC,IAAI,EAAE,qBAAqB,CAAC;CAC7B;AAED,wBAAgB,kCAAkC,CAChD,OAAO,EAAE,UAAU,EACnB,OAAO,GAAE,mCAAwC,GAChD,4BAA4B,CAU9B"}
@@ -0,0 +1,20 @@
1
+ import { DiagnosticOverlayExtension } from './extension.js';
2
+ import { BrowserStageOverlayHost, DiagnosticOverlayController } from './overlay.js';
3
+ export * from './config.js';
4
+ export * from './diagnostic.js';
5
+ export * from './overlay.js';
6
+ export * from './scratch.js';
7
+ export * from './svg-renderer.js';
8
+ export { DiagnosticOverlayExtension };
9
+ export function createDiagnosticOverlayComposition(scratch, options = {}) {
10
+ const runtime = scratch.vm.runtime;
11
+ const host = options.host ?? new BrowserStageOverlayHost(runtime.renderer.canvas);
12
+ const controller = new DiagnosticOverlayController(host, {
13
+ width: runtime.stageWidth ?? 480,
14
+ height: runtime.stageHeight ?? 360,
15
+ ...options.svg
16
+ });
17
+ const extension = new DiagnosticOverlayExtension(scratch, controller);
18
+ return { extension, controller, host };
19
+ }
20
+ //# sourceMappingURL=composition.js.map