@kubohiroya/turbowarp-http-server 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.
- package/LICENSE +373 -0
- package/README.ja.md +346 -0
- package/README.md +874 -0
- package/dist/auth/digest-file.d.ts +17 -0
- package/dist/auth/digest-file.js +90 -0
- package/dist/auth/digest-file.js.map +1 -0
- package/dist/auth/digest.d.ts +23 -0
- package/dist/auth/digest.js +139 -0
- package/dist/auth/digest.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +156 -0
- package/dist/cli.js.map +1 -0
- package/dist/community.d.ts +81 -0
- package/dist/community.js +689 -0
- package/dist/community.js.map +1 -0
- package/dist/digest-cli.d.ts +1 -0
- package/dist/digest-cli.js +159 -0
- package/dist/digest-cli.js.map +1 -0
- package/dist/extension-manifest.json +441 -0
- package/dist/protocol.d.ts +59 -0
- package/dist/protocol.js +71 -0
- package/dist/protocol.js.map +1 -0
- package/dist/server.d.ts +89 -0
- package/dist/server.js +650 -0
- package/dist/server.js.map +1 -0
- package/dist/turbowarp-http-server.js +1110 -0
- package/docs/deployment-targets.ja.md +274 -0
- package/docs/turbowarp-http-server.architecture.html +15149 -0
- package/docs/turbowarp-http-server.architecture.json +1014 -0
- package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.html +32 -0
- package/docs/turbowarp-http-server.architecture.visual-check.json +547 -0
- package/examples/01-hello-form/README.ja.md +46 -0
- package/examples/01-hello-form/server.mjs +59 -0
- package/examples/02-visitor-counter/README.ja.md +39 -0
- package/examples/02-visitor-counter/server.mjs +44 -0
- package/examples/03-message-board/README.ja.md +47 -0
- package/examples/03-message-board/server.mjs +72 -0
- package/examples/04-image-upload/README.ja.md +46 -0
- package/examples/04-image-upload/server.mjs +149 -0
- package/examples/05-live-camera/README.ja.md +47 -0
- package/examples/05-live-camera/server.mjs +147 -0
- package/examples/06-scratch-like-community/README.ja.md +82 -0
- package/examples/06-scratch-like-community/server.mjs +17 -0
- package/examples/README.ja.md +20 -0
- package/package.json +75 -0
- package/schemas/extension-manifest.schema.json +49 -0
- package/src/auth/digest-file.ts +115 -0
- package/src/auth/digest.ts +170 -0
- package/src/block-definitions.json +417 -0
- package/src/cli.ts +172 -0
- package/src/community.ts +815 -0
- package/src/config.ts +12 -0
- package/src/digest-cli.ts +178 -0
- package/src/extension-manifest.ts +149 -0
- package/src/extension.ts +713 -0
- package/src/globals.d.ts +30 -0
- package/src/index.ts +8 -0
- package/src/protocol.ts +132 -0
- package/src/server.ts +880 -0
package/src/extension.ts
ADDED
|
@@ -0,0 +1,713 @@
|
|
|
1
|
+
import {extensionConfig} from './config';
|
|
2
|
+
import definitions from './block-definitions.json';
|
|
3
|
+
import {
|
|
4
|
+
firstValue,
|
|
5
|
+
isForbiddenResponseHeader,
|
|
6
|
+
isValidHttpStatus,
|
|
7
|
+
normalizeHeaderName,
|
|
8
|
+
validateHeaderName,
|
|
9
|
+
validateHeaderValue
|
|
10
|
+
} from './protocol';
|
|
11
|
+
import type {BridgeBody, BridgeRequestMessage, BridgeResponseMessage} from './protocol';
|
|
12
|
+
|
|
13
|
+
type BlockTypeName = 'COMMAND' | 'REPORTER' | 'BOOLEAN' | 'HAT';
|
|
14
|
+
type ArgumentTypeName = 'STRING' | 'NUMBER';
|
|
15
|
+
|
|
16
|
+
interface DefinitionArgument {
|
|
17
|
+
type: ArgumentTypeName;
|
|
18
|
+
defaultValue: string | number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface BlockDefinition {
|
|
22
|
+
opcode: string;
|
|
23
|
+
blockType: BlockTypeName;
|
|
24
|
+
text: string;
|
|
25
|
+
description: string;
|
|
26
|
+
arguments: Record<string, DefinitionArgument>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
|
|
30
|
+
const DEFAULT_SERVER_URL = 'ws://127.0.0.1:8787/ws';
|
|
31
|
+
const ALLOWED_HTML_TAGS = new Set([
|
|
32
|
+
'a',
|
|
33
|
+
'article',
|
|
34
|
+
'body',
|
|
35
|
+
'button',
|
|
36
|
+
'code',
|
|
37
|
+
'dd',
|
|
38
|
+
'div',
|
|
39
|
+
'dl',
|
|
40
|
+
'dt',
|
|
41
|
+
'em',
|
|
42
|
+
'footer',
|
|
43
|
+
'form',
|
|
44
|
+
'h1',
|
|
45
|
+
'h2',
|
|
46
|
+
'h3',
|
|
47
|
+
'h4',
|
|
48
|
+
'h5',
|
|
49
|
+
'h6',
|
|
50
|
+
'header',
|
|
51
|
+
'img',
|
|
52
|
+
'input',
|
|
53
|
+
'label',
|
|
54
|
+
'li',
|
|
55
|
+
'main',
|
|
56
|
+
'ol',
|
|
57
|
+
'p',
|
|
58
|
+
'pre',
|
|
59
|
+
'section',
|
|
60
|
+
'span',
|
|
61
|
+
'strong',
|
|
62
|
+
'table',
|
|
63
|
+
'tbody',
|
|
64
|
+
'td',
|
|
65
|
+
'textarea',
|
|
66
|
+
'th',
|
|
67
|
+
'thead',
|
|
68
|
+
'tr',
|
|
69
|
+
'ul'
|
|
70
|
+
]);
|
|
71
|
+
const VOID_HTML_TAGS = new Set(['img', 'input']);
|
|
72
|
+
const VALID_ATTRIBUTE = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
|
|
73
|
+
const VALID_MARKDOWN_LANGUAGE = /^[a-zA-Z0-9_+.-]*$/;
|
|
74
|
+
const HTTP_REQUEST_HAT_OPCODE = `${extensionConfig.id}_whenHttpRequestReceived`;
|
|
75
|
+
const URL_ATTRIBUTES = new Set(['action', 'cite', 'formaction', 'href', 'poster', 'src', 'xlink:href']);
|
|
76
|
+
const URL_LIST_ATTRIBUTES = new Set(['srcset']);
|
|
77
|
+
const SAFE_URL_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
|
|
78
|
+
|
|
79
|
+
type HtmlNode = HtmlElementNode | HtmlTextNode;
|
|
80
|
+
|
|
81
|
+
interface HtmlElementNode {
|
|
82
|
+
kind: 'element';
|
|
83
|
+
tag: string;
|
|
84
|
+
attributes: Record<string, string>;
|
|
85
|
+
children: string[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface HtmlTextNode {
|
|
89
|
+
kind: 'text';
|
|
90
|
+
text: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface ResponseBuilder {
|
|
94
|
+
status: number;
|
|
95
|
+
headers: Record<string, string[]>;
|
|
96
|
+
body: BridgeBody;
|
|
97
|
+
completed: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface RequestContext {
|
|
101
|
+
request: BridgeRequestMessage;
|
|
102
|
+
response: ResponseBuilder;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export class TurboWarpHttpServerExtension implements TurboWarpExtension {
|
|
106
|
+
private serverUrl = DEFAULT_SERVER_URL;
|
|
107
|
+
private socket: WebSocket | null = null;
|
|
108
|
+
private lastReceivedMessage = '';
|
|
109
|
+
private nextHandleId = 1;
|
|
110
|
+
private readonly httpLogs: unknown[] = [];
|
|
111
|
+
private readonly markdownBuilders = new Map<string, string[]>();
|
|
112
|
+
private readonly htmlNodes = new Map<string, HtmlNode>();
|
|
113
|
+
private readonly requestContexts = new Map<string, RequestContext>();
|
|
114
|
+
private currentRequestContextId = '';
|
|
115
|
+
|
|
116
|
+
public getInfo(): Record<string, unknown> {
|
|
117
|
+
return {
|
|
118
|
+
id: extensionConfig.id,
|
|
119
|
+
name: Scratch.translate(definitions.extensionName),
|
|
120
|
+
docsURI: extensionConfig.docsURI,
|
|
121
|
+
blockIconURI: extensionConfig.blockIconURI,
|
|
122
|
+
blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
public setServerUrl(args: {URL: unknown}): void {
|
|
127
|
+
this.serverUrl = Scratch.Cast.toString(args.URL).trim() || DEFAULT_SERVER_URL;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
public connect(): void {
|
|
131
|
+
if (this.isConnected()) return;
|
|
132
|
+
|
|
133
|
+
this.socket?.close();
|
|
134
|
+
const socket = new WebSocket(this.serverUrl);
|
|
135
|
+
this.socket = socket;
|
|
136
|
+
|
|
137
|
+
socket.addEventListener('message', (event) => {
|
|
138
|
+
this.lastReceivedMessage = this.stringifyMessage(event.data);
|
|
139
|
+
this.recordLogMessage(this.lastReceivedMessage);
|
|
140
|
+
this.receiveBridgeMessage(this.lastReceivedMessage);
|
|
141
|
+
});
|
|
142
|
+
socket.addEventListener('close', () => {
|
|
143
|
+
if (this.socket === socket) this.socket = null;
|
|
144
|
+
});
|
|
145
|
+
socket.addEventListener('error', () => {
|
|
146
|
+
if (this.socket === socket) this.socket = null;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
public disconnect(): void {
|
|
151
|
+
this.socket?.close();
|
|
152
|
+
this.socket = null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
public isConnected(): boolean {
|
|
156
|
+
return this.socket?.readyState === WebSocket.OPEN;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
public sendText(args: {MESSAGE: unknown}): void {
|
|
160
|
+
if (!this.isConnected() || this.socket === null) return;
|
|
161
|
+
this.socket.send(Scratch.Cast.toString(args.MESSAGE));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
public lastMessage(): string {
|
|
165
|
+
return this.lastReceivedMessage;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
public whenHttpRequestReceived(): boolean {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
public useHttpRequest(args: {ID: unknown}): void {
|
|
173
|
+
const id = Scratch.Cast.toString(args.ID);
|
|
174
|
+
if (this.requestContexts.has(id)) this.currentRequestContextId = id;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
public currentRequestId(): string {
|
|
178
|
+
return this.currentContext()?.request.id ?? '';
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
public currentHttpMethod(): string {
|
|
182
|
+
return this.currentContext()?.request.method ?? '';
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
public currentRequestPath(): string {
|
|
186
|
+
return this.currentContext()?.request.path ?? '';
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
public currentRequestUrl(): string {
|
|
190
|
+
return this.currentContext()?.request.url ?? '';
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
public requestHeader(args: {NAME: unknown}): string {
|
|
194
|
+
const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
|
|
195
|
+
return firstValue(this.currentContext()?.request.headers[name]);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
public queryParameter(args: {NAME: unknown}): string {
|
|
199
|
+
return firstValue(this.currentContext()?.request.query[Scratch.Cast.toString(args.NAME)]);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
public pathParameter(args: {NAME: unknown}): string {
|
|
203
|
+
return this.currentContext()?.request.pathParams[Scratch.Cast.toString(args.NAME)] ?? '';
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
public currentRequestBody(): string {
|
|
207
|
+
const body = this.currentContext()?.request.body;
|
|
208
|
+
return body?.kind === 'text' ? body.text : '';
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
public currentRequestContentType(): string {
|
|
212
|
+
return this.requestHeader({NAME: 'content-type'});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
public currentRequestClientAddress(): string {
|
|
216
|
+
return this.currentContext()?.request.clientAddress ?? '';
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
public currentAuthType(): string {
|
|
220
|
+
return this.currentContext()?.request.auth?.type ?? '';
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
public currentAuthenticatedUser(): string {
|
|
224
|
+
const auth = this.currentContext()?.request.auth;
|
|
225
|
+
if (!auth) return '';
|
|
226
|
+
if (typeof auth.username === 'string') return auth.username;
|
|
227
|
+
const profile = auth.profile;
|
|
228
|
+
return firstString(profile?.preferred_username, profile?.email, profile?.name, profile?.sub);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
public currentAuthProvider(): string {
|
|
232
|
+
return this.currentContext()?.request.auth?.provider ?? '';
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
public currentAuthProfileJson(): string {
|
|
236
|
+
const profile = this.currentContext()?.request.auth?.profile;
|
|
237
|
+
return profile ? JSON.stringify(profile) : '';
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
public authProfileField(args: {NAME: unknown}): string {
|
|
241
|
+
const profile = this.currentContext()?.request.auth?.profile;
|
|
242
|
+
const value = readProfileField(profile, Scratch.Cast.toString(args.NAME));
|
|
243
|
+
return stringifyProfileValue(value);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
public currentResponseStatus(): number {
|
|
247
|
+
return this.currentContext()?.response.status ?? 200;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
public setHttpStatus(args: {STATUS: unknown}): void {
|
|
251
|
+
const context = this.mutableCurrentContext();
|
|
252
|
+
if (!context) return;
|
|
253
|
+
const status = Math.trunc(Scratch.Cast.toNumber(args.STATUS));
|
|
254
|
+
if (isValidHttpStatus(status)) context.response.status = status;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
public setResponseHeader(args: {NAME: unknown; VALUE: unknown}): void {
|
|
258
|
+
const context = this.mutableCurrentContext();
|
|
259
|
+
if (!context) return;
|
|
260
|
+
const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
|
|
261
|
+
const value = Scratch.Cast.toString(args.VALUE);
|
|
262
|
+
if (
|
|
263
|
+
validateHeaderName(name) &&
|
|
264
|
+
validateHeaderValue(value) &&
|
|
265
|
+
!isForbiddenResponseHeader(name)
|
|
266
|
+
) {
|
|
267
|
+
context.response.headers[name] = [value];
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
public removeResponseHeader(args: {NAME: unknown}): void {
|
|
272
|
+
const context = this.mutableCurrentContext();
|
|
273
|
+
if (!context) return;
|
|
274
|
+
delete context.response.headers[normalizeHeaderName(Scratch.Cast.toString(args.NAME))];
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
public responseHeader(args: {NAME: unknown}): string {
|
|
278
|
+
const name = normalizeHeaderName(Scratch.Cast.toString(args.NAME));
|
|
279
|
+
return firstValue(this.currentContext()?.response.headers[name]);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
public setResponseBody(args: {BODY: unknown}): void {
|
|
283
|
+
const context = this.mutableCurrentContext();
|
|
284
|
+
if (!context) return;
|
|
285
|
+
context.response.body = {kind: 'text', text: Scratch.Cast.toString(args.BODY)};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
public sendResponse(args: {BODY: unknown}): void {
|
|
289
|
+
const context = this.mutableCurrentContext();
|
|
290
|
+
if (!context) return;
|
|
291
|
+
context.response.body = {kind: 'text', text: Scratch.Cast.toString(args.BODY)};
|
|
292
|
+
this.completeResponse(context);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
public respondWithText(args: {BODY: unknown}): void {
|
|
296
|
+
this.setResponseHeader({NAME: 'content-type', VALUE: 'text/plain; charset=utf-8'});
|
|
297
|
+
this.sendResponse({BODY: args.BODY});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
public respondWithHtml(args: {BODY: unknown}): void {
|
|
301
|
+
this.setResponseHeader({NAME: 'content-type', VALUE: 'text/html; charset=utf-8'});
|
|
302
|
+
this.sendResponse({BODY: args.BODY});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
public respondWithJson(args: {BODY: unknown}): void {
|
|
306
|
+
this.setResponseHeader({NAME: 'content-type', VALUE: 'application/json; charset=utf-8'});
|
|
307
|
+
this.sendResponse({BODY: args.BODY});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
public receiveBridgeRequestForTest(request: BridgeRequestMessage): void {
|
|
311
|
+
this.acceptBridgeRequest(request);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
public recordHttpLog(args: {ENTRY: unknown}): void {
|
|
315
|
+
this.httpLogs.push(this.parseLogEntry(Scratch.Cast.toString(args.ENTRY)));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
public clearHttpLogs(): void {
|
|
319
|
+
this.httpLogs.length = 0;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
public httpLogViewerHtml(): string {
|
|
323
|
+
return this.renderLogViewer(this.httpLogs);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
public httpLogViewerHtmlFromJson(args: {LOGS: unknown}): string {
|
|
327
|
+
return this.renderLogViewer(this.parseLogArray(Scratch.Cast.toString(args.LOGS)));
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
public newMarkdownDocument(): string {
|
|
331
|
+
const handle = this.nextHandle('md');
|
|
332
|
+
this.markdownBuilders.set(handle, []);
|
|
333
|
+
return handle;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
public markdownHeading(args: {DOC: unknown; LEVEL: unknown; TEXT: unknown}): string {
|
|
337
|
+
const handle = this.ensureMarkdownHandle(args.DOC);
|
|
338
|
+
const level = Math.min(6, Math.max(1, Math.trunc(Scratch.Cast.toNumber(args.LEVEL))));
|
|
339
|
+
this.markdownBuilders.get(handle)?.push(`${'#'.repeat(level)} ${escapeMarkdownLine(Scratch.Cast.toString(args.TEXT))}`);
|
|
340
|
+
return handle;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
public markdownParagraph(args: {DOC: unknown; TEXT: unknown}): string {
|
|
344
|
+
const handle = this.ensureMarkdownHandle(args.DOC);
|
|
345
|
+
this.markdownBuilders.get(handle)?.push(escapeMarkdownParagraph(Scratch.Cast.toString(args.TEXT)));
|
|
346
|
+
return handle;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
public markdownBullet(args: {DOC: unknown; TEXT: unknown}): string {
|
|
350
|
+
const handle = this.ensureMarkdownHandle(args.DOC);
|
|
351
|
+
this.markdownBuilders.get(handle)?.push(`- ${escapeMarkdownLine(Scratch.Cast.toString(args.TEXT))}`);
|
|
352
|
+
return handle;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
public markdownCodeBlock(args: {DOC: unknown; CODE: unknown; LANG: unknown}): string {
|
|
356
|
+
const handle = this.ensureMarkdownHandle(args.DOC);
|
|
357
|
+
const language = Scratch.Cast.toString(args.LANG).trim();
|
|
358
|
+
const safeLanguage = VALID_MARKDOWN_LANGUAGE.test(language) ? language : '';
|
|
359
|
+
const code = Scratch.Cast.toString(args.CODE).replace(/```/g, '`\\`\\`');
|
|
360
|
+
this.markdownBuilders.get(handle)?.push(`\`\`\`${safeLanguage}\n${code}\n\`\`\``);
|
|
361
|
+
return handle;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
public renderMarkdown(args: {DOC: unknown}): string {
|
|
365
|
+
return this.markdownBuilders.get(Scratch.Cast.toString(args.DOC))?.join('\n\n') ?? '';
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
public newHtmlElement(args: {TAG: unknown}): string {
|
|
369
|
+
const tag = normalizeHtmlTag(Scratch.Cast.toString(args.TAG));
|
|
370
|
+
const handle = this.nextHandle('html');
|
|
371
|
+
this.htmlNodes.set(handle, {kind: 'element', tag, attributes: {}, children: []});
|
|
372
|
+
return handle;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
public htmlText(args: {TEXT: unknown}): string {
|
|
376
|
+
const handle = this.nextHandle('html');
|
|
377
|
+
this.htmlNodes.set(handle, {kind: 'text', text: Scratch.Cast.toString(args.TEXT)});
|
|
378
|
+
return handle;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
public htmlSetAttribute(args: {NODE: unknown; NAME: unknown; VALUE: unknown}): string {
|
|
382
|
+
const handle = this.ensureHtmlElementHandle(args.NODE);
|
|
383
|
+
const node = this.htmlNodes.get(handle);
|
|
384
|
+
const name = Scratch.Cast.toString(args.NAME).trim();
|
|
385
|
+
const normalizedName = name.toLowerCase();
|
|
386
|
+
const value = Scratch.Cast.toString(args.VALUE);
|
|
387
|
+
if (
|
|
388
|
+
node?.kind === 'element' &&
|
|
389
|
+
VALID_ATTRIBUTE.test(name) &&
|
|
390
|
+
!normalizedName.startsWith('on') &&
|
|
391
|
+
isSafeAttributeValue(normalizedName, value)
|
|
392
|
+
) {
|
|
393
|
+
node.attributes[name] = value;
|
|
394
|
+
}
|
|
395
|
+
return handle;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
public htmlAppendChild(args: {PARENT: unknown; CHILD: unknown}): string {
|
|
399
|
+
const parentHandle = this.ensureHtmlElementHandle(args.PARENT);
|
|
400
|
+
const childHandle = Scratch.Cast.toString(args.CHILD);
|
|
401
|
+
const parent = this.htmlNodes.get(parentHandle);
|
|
402
|
+
if (
|
|
403
|
+
parent?.kind === 'element' &&
|
|
404
|
+
this.htmlNodes.has(childHandle) &&
|
|
405
|
+
parentHandle !== childHandle &&
|
|
406
|
+
!this.hasHtmlDescendant(childHandle, parentHandle, new Set())
|
|
407
|
+
) {
|
|
408
|
+
parent.children.push(childHandle);
|
|
409
|
+
}
|
|
410
|
+
return parentHandle;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
public renderHtml(args: {NODE: unknown}): string {
|
|
414
|
+
return this.renderHtmlNode(Scratch.Cast.toString(args.NODE), new Set());
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
public renderHtmlDocument(args: {TITLE: unknown; BODY: unknown}): string {
|
|
418
|
+
const title = escapeHtml(Scratch.Cast.toString(args.TITLE));
|
|
419
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body>${this.renderHtmlNode(
|
|
420
|
+
Scratch.Cast.toString(args.BODY),
|
|
421
|
+
new Set()
|
|
422
|
+
)}</body></html>`;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private stringifyMessage(message: unknown): string {
|
|
426
|
+
if (typeof message === 'string') return message;
|
|
427
|
+
if (message instanceof ArrayBuffer) return new TextDecoder().decode(message);
|
|
428
|
+
return String(message);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private receiveBridgeMessage(message: string): void {
|
|
432
|
+
try {
|
|
433
|
+
const parsed = JSON.parse(message) as Partial<BridgeRequestMessage>;
|
|
434
|
+
if (parsed.type === 'request' && typeof parsed.id === 'string') {
|
|
435
|
+
this.acceptBridgeRequest(parsed as BridgeRequestMessage);
|
|
436
|
+
}
|
|
437
|
+
} catch {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private acceptBridgeRequest(request: BridgeRequestMessage): void {
|
|
443
|
+
const normalizedRequest: BridgeRequestMessage = {
|
|
444
|
+
...request,
|
|
445
|
+
headers: normalizeHeaderRecord(request.headers),
|
|
446
|
+
query: normalizeValueRecord(request.query),
|
|
447
|
+
pathParams: normalizePathParams(request.pathParams)
|
|
448
|
+
};
|
|
449
|
+
const auth = normalizeAuthContext(request.auth);
|
|
450
|
+
if (auth) normalizedRequest.auth = auth;
|
|
451
|
+
this.requestContexts.set(request.id, {
|
|
452
|
+
request: normalizedRequest,
|
|
453
|
+
response: {
|
|
454
|
+
status: 200,
|
|
455
|
+
headers: {},
|
|
456
|
+
body: {kind: 'empty'},
|
|
457
|
+
completed: false
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
this.currentRequestContextId = request.id;
|
|
461
|
+
this.startRequestHat();
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
private currentContext(): RequestContext | undefined {
|
|
465
|
+
return this.requestContexts.get(this.currentRequestContextId);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private mutableCurrentContext(): RequestContext | undefined {
|
|
469
|
+
const context = this.currentContext();
|
|
470
|
+
return context && !context.response.completed ? context : undefined;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
private completeResponse(context: RequestContext): void {
|
|
474
|
+
if (context.response.completed) return;
|
|
475
|
+
context.response.completed = true;
|
|
476
|
+
const message: BridgeResponseMessage = {
|
|
477
|
+
type: 'response',
|
|
478
|
+
id: context.request.id,
|
|
479
|
+
status: context.response.status,
|
|
480
|
+
headers: context.response.headers,
|
|
481
|
+
body: context.response.body
|
|
482
|
+
};
|
|
483
|
+
this.socket?.send(JSON.stringify(message));
|
|
484
|
+
this.requestContexts.delete(context.request.id);
|
|
485
|
+
if (this.currentRequestContextId === context.request.id) this.currentRequestContextId = '';
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private recordLogMessage(message: string): void {
|
|
489
|
+
const parsed = this.parseLogEntry(message);
|
|
490
|
+
if (isLogLike(parsed)) this.httpLogs.push(parsed);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
private startRequestHat(): void {
|
|
494
|
+
Scratch.vm?.runtime?.startHats?.(HTTP_REQUEST_HAT_OPCODE);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
private parseLogEntry(value: string): unknown {
|
|
498
|
+
try {
|
|
499
|
+
return JSON.parse(value);
|
|
500
|
+
} catch {
|
|
501
|
+
return {message: value};
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
private parseLogArray(value: string): unknown[] {
|
|
506
|
+
const parsed = this.parseLogEntry(value);
|
|
507
|
+
return Array.isArray(parsed) ? parsed : [parsed];
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
private renderLogViewer(logs: readonly unknown[]): string {
|
|
511
|
+
const data = JSON.stringify(logs).replace(/</g, '\\u003c');
|
|
512
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>HTTP Logs</title><style>
|
|
513
|
+
body{margin:0;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;background:#0f172a;color:#e5e7eb}
|
|
514
|
+
header{height:44px;display:flex;align-items:center;padding:0 16px;background:#111827;border-bottom:1px solid #334155}
|
|
515
|
+
#viewport{height:calc(100vh - 45px);overflow:auto;position:relative}
|
|
516
|
+
#spacer{width:1px}.row{position:absolute;left:0;right:0;height:32px;display:grid;grid-template-columns:72px 84px 1fr;gap:10px;align-items:center;padding:0 12px;border-bottom:1px solid #1f2937;box-sizing:border-box;white-space:nowrap}
|
|
517
|
+
.status{color:#93c5fd}.method{color:#86efac}.path{overflow:hidden;text-overflow:ellipsis}
|
|
518
|
+
</style></head><body><header>HTTP logs <span id="count"></span></header><div id="viewport"><div id="spacer"></div><div id="rows"></div></div><script>
|
|
519
|
+
const logs=${data};const rowHeight=32;const viewport=document.getElementById('viewport');const spacer=document.getElementById('spacer');const rows=document.getElementById('rows');document.getElementById('count').textContent='('+logs.length+')';spacer.style.height=(logs.length*rowHeight)+'px';
|
|
520
|
+
function text(v){return v==null?'':String(v)}function render(){const top=viewport.scrollTop;const first=Math.max(0,Math.floor(top/rowHeight)-8);const visible=Math.ceil(viewport.clientHeight/rowHeight)+16;const last=Math.min(logs.length,first+visible);let html='';for(let i=first;i<last;i++){const log=logs[i]||{};const method=text(log.method||log.event||'LOG');const status=text(log.status||'');const path=text(log.path||log.resourceName||log.message||JSON.stringify(log));html+='<div class="row" style="transform:translateY('+(i*rowHeight)+'px)"><span class="method">'+escapeHtml(method)+'</span><span class="status">'+escapeHtml(status)+'</span><span class="path">'+escapeHtml(path)+'</span></div>'}rows.innerHTML=html}
|
|
521
|
+
function escapeHtml(value){return value.replace(/[&<>"']/g,ch=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch]))}viewport.addEventListener('scroll',render);render();
|
|
522
|
+
</script></body></html>`;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
private ensureMarkdownHandle(value: unknown): string {
|
|
526
|
+
const handle = Scratch.Cast.toString(value);
|
|
527
|
+
if (this.markdownBuilders.has(handle)) return handle;
|
|
528
|
+
const next = this.newMarkdownDocument();
|
|
529
|
+
return next;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
private ensureHtmlElementHandle(value: unknown): string {
|
|
533
|
+
const handle = Scratch.Cast.toString(value);
|
|
534
|
+
const node = this.htmlNodes.get(handle);
|
|
535
|
+
if (node?.kind === 'element') return handle;
|
|
536
|
+
return this.newHtmlElement({TAG: 'div'});
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private renderHtmlNode(handle: string, visiting: Set<string>): string {
|
|
540
|
+
if (visiting.has(handle)) return '';
|
|
541
|
+
const node = this.htmlNodes.get(handle);
|
|
542
|
+
if (!node) return '';
|
|
543
|
+
if (node.kind === 'text') return escapeHtml(node.text);
|
|
544
|
+
visiting.add(handle);
|
|
545
|
+
const attributes = Object.entries(node.attributes)
|
|
546
|
+
.map(([name, value]) => ` ${name}="${escapeHtml(value)}"`)
|
|
547
|
+
.join('');
|
|
548
|
+
if (VOID_HTML_TAGS.has(node.tag)) {
|
|
549
|
+
visiting.delete(handle);
|
|
550
|
+
return `<${node.tag}${attributes}>`;
|
|
551
|
+
}
|
|
552
|
+
const children = node.children.map((child) => this.renderHtmlNode(child, visiting)).join('');
|
|
553
|
+
visiting.delete(handle);
|
|
554
|
+
return `<${node.tag}${attributes}>${children}</${node.tag}>`;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
private hasHtmlDescendant(handle: string, targetHandle: string, visited: Set<string>): boolean {
|
|
558
|
+
if (visited.has(handle)) return false;
|
|
559
|
+
visited.add(handle);
|
|
560
|
+
const node = this.htmlNodes.get(handle);
|
|
561
|
+
if (node?.kind !== 'element') return false;
|
|
562
|
+
return node.children.some(
|
|
563
|
+
(child) => child === targetHandle || this.hasHtmlDescendant(child, targetHandle, visited)
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
private nextHandle(prefix: 'md' | 'html'): string {
|
|
568
|
+
const handle = `${prefix}:${this.nextHandleId}`;
|
|
569
|
+
this.nextHandleId += 1;
|
|
570
|
+
return handle;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
private toScratchBlock(block: BlockDefinition): Record<string, unknown> {
|
|
574
|
+
return {
|
|
575
|
+
opcode: block.opcode,
|
|
576
|
+
blockType: Scratch.BlockType[block.blockType],
|
|
577
|
+
text: Scratch.translate(block.text),
|
|
578
|
+
arguments: Object.fromEntries(
|
|
579
|
+
Object.entries(block.arguments).map(([name, argument]) => [
|
|
580
|
+
name,
|
|
581
|
+
{
|
|
582
|
+
type: Scratch.ArgumentType[argument.type],
|
|
583
|
+
defaultValue: argument.defaultValue
|
|
584
|
+
}
|
|
585
|
+
])
|
|
586
|
+
)
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function isLogLike(value: unknown): boolean {
|
|
592
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function normalizeHeaderRecord(headers: Record<string, string[]>): Record<string, string[]> {
|
|
596
|
+
const normalized: Record<string, string[]> = {};
|
|
597
|
+
for (const [name, values] of Object.entries(headers ?? {})) {
|
|
598
|
+
normalized[normalizeHeaderName(name)] = values.map((value) => String(value));
|
|
599
|
+
}
|
|
600
|
+
return normalized;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function normalizeValueRecord(values: Record<string, string[]>): Record<string, string[]> {
|
|
604
|
+
const normalized: Record<string, string[]> = {};
|
|
605
|
+
for (const [name, items] of Object.entries(values ?? {})) {
|
|
606
|
+
normalized[name] = items.map((value) => String(value));
|
|
607
|
+
}
|
|
608
|
+
return normalized;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function normalizePathParams(values: Record<string, string>): Record<string, string> {
|
|
612
|
+
const normalized: Record<string, string> = {};
|
|
613
|
+
for (const [name, value] of Object.entries(values ?? {})) {
|
|
614
|
+
normalized[name] = String(value);
|
|
615
|
+
}
|
|
616
|
+
return normalized;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function normalizeAuthContext(auth: BridgeRequestMessage['auth']): BridgeRequestMessage['auth'] {
|
|
620
|
+
if (typeof auth !== 'object' || auth === null || Array.isArray(auth)) return undefined;
|
|
621
|
+
const type = typeof auth.type === 'string' ? auth.type : '';
|
|
622
|
+
if (!type) return undefined;
|
|
623
|
+
const normalized: NonNullable<BridgeRequestMessage['auth']> = {type};
|
|
624
|
+
if (typeof auth.username === 'string') normalized.username = auth.username;
|
|
625
|
+
if (typeof auth.provider === 'string') normalized.provider = auth.provider;
|
|
626
|
+
if (isPlainRecord(auth.profile)) normalized.profile = normalizeProfile(auth.profile);
|
|
627
|
+
return normalized;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function normalizeProfile(profile: Record<string, unknown>): Record<string, unknown> {
|
|
631
|
+
return JSON.parse(JSON.stringify(profile)) as Record<string, unknown>;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function readProfileField(profile: Record<string, unknown> | undefined, path: string): unknown {
|
|
635
|
+
if (!profile) return undefined;
|
|
636
|
+
const segments = path.split('.').map((segment) => segment.trim()).filter(Boolean);
|
|
637
|
+
if (segments.length === 0) return undefined;
|
|
638
|
+
let value: unknown = profile;
|
|
639
|
+
for (const segment of segments) {
|
|
640
|
+
if (!isPlainRecord(value)) return undefined;
|
|
641
|
+
value = value[segment];
|
|
642
|
+
}
|
|
643
|
+
return value;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function stringifyProfileValue(value: unknown): string {
|
|
647
|
+
if (value === undefined || value === null) return '';
|
|
648
|
+
if (typeof value === 'string') return value;
|
|
649
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
|
650
|
+
return JSON.stringify(value);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function firstString(...values: unknown[]): string {
|
|
654
|
+
return values.find((value): value is string => typeof value === 'string') ?? '';
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
658
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function escapeMarkdownLine(value: string): string {
|
|
662
|
+
return value.replace(/\\/g, '\\\\').replace(/([`*_#[\]])/g, '\\$1').replace(/\r?\n/g, ' ');
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function escapeMarkdownParagraph(value: string): string {
|
|
666
|
+
return value.replace(/\\/g, '\\\\').replace(/([`*_#[\]])/g, '\\$1');
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function normalizeHtmlTag(value: string): string {
|
|
670
|
+
const tag = value.trim().toLowerCase();
|
|
671
|
+
return ALLOWED_HTML_TAGS.has(tag) ? tag : 'div';
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function isSafeAttributeValue(name: string, value: string): boolean {
|
|
675
|
+
if (URL_LIST_ATTRIBUTES.has(name)) return isSafeUrlList(value);
|
|
676
|
+
if (URL_ATTRIBUTES.has(name)) return isSafeUrl(value);
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function isSafeUrlList(value: string): boolean {
|
|
681
|
+
return value
|
|
682
|
+
.split(',')
|
|
683
|
+
.map((candidate) => candidate.trim().split(/\s+/, 1)[0] ?? '')
|
|
684
|
+
.every((url) => isSafeUrl(url));
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
function isSafeUrl(value: string): boolean {
|
|
688
|
+
const trimmed = value.trim();
|
|
689
|
+
if (!trimmed) return true;
|
|
690
|
+
const normalized = stripUrlSchemeSeparators(trimmed);
|
|
691
|
+
const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(normalized)?.[1]?.toLowerCase();
|
|
692
|
+
return scheme === undefined || SAFE_URL_SCHEMES.has(scheme);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function stripUrlSchemeSeparators(value: string): string {
|
|
696
|
+
let result = '';
|
|
697
|
+
for (const character of value) {
|
|
698
|
+
const code = character.charCodeAt(0);
|
|
699
|
+
if (code <= 0x1f || code === 0x7f || /\s/.test(character)) continue;
|
|
700
|
+
result += character;
|
|
701
|
+
}
|
|
702
|
+
return result;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function escapeHtml(value: string): string {
|
|
706
|
+
return value.replace(/[&<>"']/g, (character) => {
|
|
707
|
+
if (character === '&') return '&';
|
|
708
|
+
if (character === '<') return '<';
|
|
709
|
+
if (character === '>') return '>';
|
|
710
|
+
if (character === '"') return '"';
|
|
711
|
+
return ''';
|
|
712
|
+
});
|
|
713
|
+
}
|