@kubohiroya/turbowarp-markdown 0.2.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,641 @@
1
+ // Name: TurboWarp Markdown
2
+ // ID: kubohiroyamarkdown
3
+ // Description: Build Markdown documents with immutable reporter blocks.
4
+ // By: Hiroya Kubo
5
+ // License: MPL-2.0
6
+
7
+ (function (Scratch) {
8
+ 'use strict';
9
+
10
+ //#region src/config.ts
11
+ var extensionConfig = {
12
+ id: "kubohiroyamarkdown",
13
+ slug: "turbowarp-markdown",
14
+ name: "TurboWarp Markdown",
15
+ description: "Build Markdown documents with immutable reporter blocks.",
16
+ author: "Hiroya Kubo",
17
+ license: "MPL-2.0",
18
+ unsandboxed: false,
19
+ docsURI: "https://kubohiroya.github.io/turbowarp-markdown/",
20
+ blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNiIgeT0iOCIgd2lkdGg9IjM2IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzJGNjM4NiIvPjxwYXRoIGQ9Ik0xMyAzMFYxOGw1IDcgNS03djEyTTMwIDE4djEyTTI2IDMwaDgiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZmZmZiIgc3Ryb2tlLXdpZHRoPSIzIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48L3N2Zz4="
21
+ };
22
+ var block_definitions_default = {
23
+ extensionName: "TurboWarp Markdown",
24
+ blocks: [
25
+ {
26
+ "opcode": "text",
27
+ "blockType": "REPORTER",
28
+ "text": "text [TEXT]",
29
+ "description": "Creates escaped Markdown text.",
30
+ "arguments": { "TEXT": {
31
+ "type": "STRING",
32
+ "defaultValue": "Hello *world*"
33
+ } }
34
+ },
35
+ {
36
+ "opcode": "bold",
37
+ "blockType": "REPORTER",
38
+ "text": "bold [CONTENT]",
39
+ "description": "Creates bold inline Markdown content.",
40
+ "arguments": { "CONTENT": {
41
+ "type": "STRING",
42
+ "defaultValue": "important"
43
+ } }
44
+ },
45
+ {
46
+ "opcode": "italic",
47
+ "blockType": "REPORTER",
48
+ "text": "italic [CONTENT]",
49
+ "description": "Creates italic inline Markdown content.",
50
+ "arguments": { "CONTENT": {
51
+ "type": "STRING",
52
+ "defaultValue": "note"
53
+ } }
54
+ },
55
+ {
56
+ "opcode": "link",
57
+ "blockType": "REPORTER",
58
+ "text": "link [CONTENT] URL [URL]",
59
+ "description": "Creates a Markdown link with a conservatively validated destination.",
60
+ "arguments": {
61
+ "CONTENT": {
62
+ "type": "STRING",
63
+ "defaultValue": "TurboWarp"
64
+ },
65
+ "URL": {
66
+ "type": "STRING",
67
+ "defaultValue": "https://turbowarp.org/"
68
+ }
69
+ }
70
+ },
71
+ {
72
+ "opcode": "code",
73
+ "blockType": "REPORTER",
74
+ "text": "code [TEXT]",
75
+ "description": "Creates inline code content.",
76
+ "arguments": { "TEXT": {
77
+ "type": "STRING",
78
+ "defaultValue": "status"
79
+ } }
80
+ },
81
+ {
82
+ "opcode": "heading",
83
+ "blockType": "REPORTER",
84
+ "text": "heading [LEVEL] [CONTENT]",
85
+ "description": "Creates a heading with the level clamped to 1 through 6.",
86
+ "arguments": {
87
+ "LEVEL": {
88
+ "type": "NUMBER",
89
+ "defaultValue": 1
90
+ },
91
+ "CONTENT": {
92
+ "type": "STRING",
93
+ "defaultValue": "Sensor"
94
+ }
95
+ }
96
+ },
97
+ {
98
+ "opcode": "paragraph",
99
+ "blockType": "REPORTER",
100
+ "text": "paragraph [CONTENT]",
101
+ "description": "Creates a paragraph block.",
102
+ "arguments": { "CONTENT": {
103
+ "type": "STRING",
104
+ "defaultValue": "ready"
105
+ } }
106
+ },
107
+ {
108
+ "opcode": "quote",
109
+ "blockType": "REPORTER",
110
+ "text": "quote [CONTENT]",
111
+ "description": "Creates a block quote.",
112
+ "arguments": { "CONTENT": {
113
+ "type": "STRING",
114
+ "defaultValue": "quoted"
115
+ } }
116
+ },
117
+ {
118
+ "opcode": "codeBlock",
119
+ "blockType": "REPORTER",
120
+ "text": "code block [TEXT] language [LANGUAGE]",
121
+ "description": "Creates a fenced code block.",
122
+ "arguments": {
123
+ "TEXT": {
124
+ "type": "STRING",
125
+ "defaultValue": "console.log('ok')"
126
+ },
127
+ "LANGUAGE": {
128
+ "type": "STRING",
129
+ "defaultValue": "js"
130
+ }
131
+ }
132
+ },
133
+ {
134
+ "opcode": "listItem",
135
+ "blockType": "REPORTER",
136
+ "text": "list item [CONTENT]",
137
+ "description": "Creates a list item fragment.",
138
+ "arguments": { "CONTENT": {
139
+ "type": "STRING",
140
+ "defaultValue": "item"
141
+ } }
142
+ },
143
+ {
144
+ "opcode": "unorderedList",
145
+ "blockType": "REPORTER",
146
+ "text": "unordered list [ITEMS]",
147
+ "description": "Creates an unordered list from item fragments.",
148
+ "arguments": { "ITEMS": {
149
+ "type": "STRING",
150
+ "defaultValue": ""
151
+ } }
152
+ },
153
+ {
154
+ "opcode": "orderedList",
155
+ "blockType": "REPORTER",
156
+ "text": "ordered list [ITEMS]",
157
+ "description": "Creates an ordered list from item fragments.",
158
+ "arguments": { "ITEMS": {
159
+ "type": "STRING",
160
+ "defaultValue": ""
161
+ } }
162
+ },
163
+ {
164
+ "opcode": "concat",
165
+ "blockType": "REPORTER",
166
+ "text": "[LEFT] followed by [RIGHT]",
167
+ "description": "Creates a new Markdown fragment sequence without mutating either input.",
168
+ "arguments": {
169
+ "LEFT": {
170
+ "type": "STRING",
171
+ "defaultValue": ""
172
+ },
173
+ "RIGHT": {
174
+ "type": "STRING",
175
+ "defaultValue": ""
176
+ }
177
+ }
178
+ },
179
+ {
180
+ "opcode": "render",
181
+ "blockType": "REPORTER",
182
+ "text": "render Markdown [FRAGMENT]",
183
+ "description": "Renders a Markdown fragment to final Markdown text without updating stored validation errors.",
184
+ "arguments": { "FRAGMENT": {
185
+ "type": "STRING",
186
+ "defaultValue": ""
187
+ } }
188
+ },
189
+ {
190
+ "opcode": "renderWithValidation",
191
+ "blockType": "REPORTER",
192
+ "text": "render Markdown with validation [FRAGMENT]",
193
+ "description": "Validates a Markdown fragment, stores any validation errors, and renders final Markdown text.",
194
+ "arguments": { "FRAGMENT": {
195
+ "type": "STRING",
196
+ "defaultValue": ""
197
+ } }
198
+ },
199
+ {
200
+ "opcode": "lastValidationErrors",
201
+ "blockType": "REPORTER",
202
+ "text": "last Markdown validation errors",
203
+ "description": "Returns validation errors stored by the most recent render Markdown with validation block.",
204
+ "arguments": {}
205
+ },
206
+ {
207
+ "opcode": "lastRenderHasValidationErrors",
208
+ "blockType": "BOOLEAN",
209
+ "text": "last rendered Markdown has validation errors?",
210
+ "description": "Reports whether the most recent validated Markdown render stored validation errors.",
211
+ "arguments": {}
212
+ },
213
+ {
214
+ "opcode": "validateMarkdown",
215
+ "blockType": "REPORTER",
216
+ "text": "validate Markdown [FRAGMENT]",
217
+ "description": "Returns simple validation diagnostics for a Markdown fragment.",
218
+ "arguments": { "FRAGMENT": {
219
+ "type": "STRING",
220
+ "defaultValue": ""
221
+ } }
222
+ },
223
+ {
224
+ "opcode": "isValidMarkdown",
225
+ "blockType": "BOOLEAN",
226
+ "text": "Markdown [FRAGMENT] is valid?",
227
+ "description": "Reports whether simple validation found no Markdown errors.",
228
+ "arguments": { "FRAGMENT": {
229
+ "type": "STRING",
230
+ "defaultValue": ""
231
+ } }
232
+ }
233
+ ]
234
+ };
235
+ //#endregion
236
+ //#region src/markdown.ts
237
+ var empty = { kind: "empty" };
238
+ var SAFE_URL_PATTERN = /^(?:https?:|mailto:|tel:|\/|\.\/|\.\.\/|#|\?|$)/iu;
239
+ var lastRenderValidationResult = {
240
+ valid: true,
241
+ issues: []
242
+ };
243
+ function text(value) {
244
+ return {
245
+ kind: "text",
246
+ value
247
+ };
248
+ }
249
+ function bold(content) {
250
+ return {
251
+ kind: "bold",
252
+ content: normalizeContent(content)
253
+ };
254
+ }
255
+ function italic(content) {
256
+ return {
257
+ kind: "italic",
258
+ content: normalizeContent(content)
259
+ };
260
+ }
261
+ function link(content, url) {
262
+ validateSafeUrl(url);
263
+ return {
264
+ kind: "link",
265
+ content: normalizeContent(content),
266
+ url
267
+ };
268
+ }
269
+ function code(value) {
270
+ return {
271
+ kind: "code",
272
+ value
273
+ };
274
+ }
275
+ function heading(level, content) {
276
+ return {
277
+ kind: "heading",
278
+ level: clampHeadingLevel(level),
279
+ content: normalizeContent(content)
280
+ };
281
+ }
282
+ function paragraph(content) {
283
+ return {
284
+ kind: "paragraph",
285
+ content: normalizeContent(content)
286
+ };
287
+ }
288
+ function quote(content) {
289
+ return {
290
+ kind: "quote",
291
+ content: normalizeContent(content)
292
+ };
293
+ }
294
+ function codeBlock(value, language = "") {
295
+ return {
296
+ kind: "codeBlock",
297
+ language: sanitizeLanguage(language),
298
+ value
299
+ };
300
+ }
301
+ function listItem(content) {
302
+ return {
303
+ kind: "listItem",
304
+ content: normalizeContent(content)
305
+ };
306
+ }
307
+ function unorderedList(items) {
308
+ return {
309
+ kind: "list",
310
+ ordered: false,
311
+ items: normalizeItems(items)
312
+ };
313
+ }
314
+ function orderedList(items) {
315
+ return {
316
+ kind: "list",
317
+ ordered: true,
318
+ items: normalizeItems(items)
319
+ };
320
+ }
321
+ function concat(left, right) {
322
+ const children = [...flattenSequence(left), ...flattenSequence(right)].filter((child) => child.kind !== "empty");
323
+ if (children.length === 0) return empty;
324
+ if (children.length === 1) return children[0] ?? empty;
325
+ return {
326
+ kind: "sequence",
327
+ children
328
+ };
329
+ }
330
+ function render(fragment) {
331
+ return renderDocument(fragment);
332
+ }
333
+ function renderWithValidation(fragment) {
334
+ lastRenderValidationResult = validate(fragment);
335
+ return renderDocument(fragment);
336
+ }
337
+ function validate(fragment) {
338
+ const issues = [];
339
+ validateFragment(fragment, "$", [], issues);
340
+ if (fragment.kind === "empty") issues.push({
341
+ severity: "warning",
342
+ path: "$",
343
+ message: "Markdown fragment is empty."
344
+ });
345
+ return {
346
+ valid: issues.every((issue) => issue.severity !== "error"),
347
+ issues
348
+ };
349
+ }
350
+ function isValid(fragment) {
351
+ return validate(fragment).valid;
352
+ }
353
+ function getLastRenderValidationErrors() {
354
+ return lastRenderValidationResult.issues.filter((issue) => issue.severity === "error");
355
+ }
356
+ function formatValidationResult(result) {
357
+ if (result.issues.length === 0) return "valid";
358
+ return result.issues.map((issue) => `${issue.severity}: ${issue.path}: ${issue.message}`).join("\n");
359
+ }
360
+ function formatValidationErrors(issues) {
361
+ if (issues.length === 0) return "";
362
+ return issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
363
+ }
364
+ function getLastRenderValidationErrorText() {
365
+ return formatValidationErrors(getLastRenderValidationErrors());
366
+ }
367
+ function normalizeContent(content) {
368
+ return typeof content === "string" ? text(content) : content;
369
+ }
370
+ function validateFragment(fragment, path, ancestors, issues) {
371
+ const parent = ancestors[ancestors.length - 1];
372
+ const inlineAncestor = ancestors.find((ancestor) => [
373
+ "bold",
374
+ "italic",
375
+ "link"
376
+ ].includes(ancestor.kind));
377
+ if (!isInline(fragment) && inlineAncestor !== void 0) issues.push({
378
+ severity: "error",
379
+ path,
380
+ message: `${fragment.kind} cannot be nested inside ${inlineAncestor.kind}.`
381
+ });
382
+ if (fragment.kind === "listItem" && parent?.kind !== "list") issues.push({
383
+ severity: "error",
384
+ path,
385
+ message: "listItem must be inside a list."
386
+ });
387
+ validateWarnings(fragment, path, issues);
388
+ for (const [index, child] of childFragments(fragment).entries()) validateFragment(child, `${path}.children[${index}]`, [...ancestors, fragment], issues);
389
+ }
390
+ function validateWarnings(fragment, path, issues) {
391
+ if (fragment.kind === "heading" && isEmptyish(fragment.content)) issues.push({
392
+ severity: "warning",
393
+ path,
394
+ message: "heading should have content."
395
+ });
396
+ if (fragment.kind === "paragraph" && isEmptyish(fragment.content)) issues.push({
397
+ severity: "warning",
398
+ path,
399
+ message: "paragraph is empty."
400
+ });
401
+ if (fragment.kind === "link" && isEmptyish(fragment.content)) issues.push({
402
+ severity: "warning",
403
+ path,
404
+ message: "link should have visible content."
405
+ });
406
+ if (fragment.kind === "link" && fragment.url.trim().length === 0) issues.push({
407
+ severity: "warning",
408
+ path,
409
+ message: "link should have a destination URL."
410
+ });
411
+ if (fragment.kind === "list" && fragment.items.length === 0) issues.push({
412
+ severity: "warning",
413
+ path,
414
+ message: "list should contain at least one item."
415
+ });
416
+ }
417
+ function childFragments(fragment) {
418
+ switch (fragment.kind) {
419
+ case "bold":
420
+ case "italic":
421
+ case "link":
422
+ case "heading":
423
+ case "paragraph":
424
+ case "quote":
425
+ case "listItem": return [fragment.content];
426
+ case "list": return fragment.items;
427
+ case "sequence": return fragment.children;
428
+ default: return [];
429
+ }
430
+ }
431
+ function isEmptyish(fragment) {
432
+ if (fragment.kind === "empty") return true;
433
+ if (fragment.kind === "text" || fragment.kind === "code") return fragment.value.length === 0;
434
+ if (fragment.kind === "sequence") return fragment.children.every(isEmptyish);
435
+ return false;
436
+ }
437
+ function renderDocument(fragment) {
438
+ if (fragment.kind === "empty") return "";
439
+ if (fragment.kind === "sequence") {
440
+ if (fragment.children.every((child) => isInline(child) || child.kind === "sequence")) return renderInline(fragment);
441
+ return fragment.children.map(renderDocument).filter(Boolean).join("\n\n");
442
+ }
443
+ if (isInline(fragment)) return renderInline(fragment);
444
+ return renderBlock(fragment);
445
+ }
446
+ function renderBlock(fragment) {
447
+ switch (fragment.kind) {
448
+ case "heading": return `${"#".repeat(fragment.level)} ${renderInlineish(fragment.content)}`;
449
+ case "paragraph": return renderInlineish(fragment.content);
450
+ case "quote": return renderDocument(fragment.content).split("\n").map((line) => line.length === 0 ? ">" : `> ${line}`).join("\n");
451
+ case "codeBlock": return renderCodeBlock(fragment);
452
+ case "list": return fragment.items.map((item, index) => renderListItem(item, fragment.ordered ? `${index + 1}.` : "-")).join("\n");
453
+ case "listItem": return renderInlineish(fragment.content);
454
+ default: return renderDocument(fragment);
455
+ }
456
+ }
457
+ function renderInline(fragment) {
458
+ switch (fragment.kind) {
459
+ case "text": return escapeMarkdownText(fragment.value);
460
+ case "bold": return `**${renderInlineish(fragment.content)}**`;
461
+ case "italic": return `*${renderInlineish(fragment.content)}*`;
462
+ case "link": return `[${renderInlineish(fragment.content)}](${escapeUrl(fragment.url)})`;
463
+ case "code": return renderInlineCode(fragment.value);
464
+ case "sequence": return fragment.children.map(renderInlineish).join("");
465
+ case "empty": return "";
466
+ default: return renderBlock(fragment);
467
+ }
468
+ }
469
+ function renderInlineish(fragment) {
470
+ return isInline(fragment) || fragment.kind === "sequence" ? renderInline(fragment) : renderBlock(fragment);
471
+ }
472
+ function renderCodeBlock(fragment) {
473
+ const fence = longestBacktickRun(fragment.value) >= 3 ? "````" : "```";
474
+ return `${fence}${fragment.language.length > 0 ? fragment.language : ""}\n${fragment.value}\n${fence}`;
475
+ }
476
+ function renderInlineCode(value) {
477
+ const fence = "`".repeat(Math.max(1, longestBacktickRun(value) + 1));
478
+ return `${fence}${value.startsWith("`") || value.endsWith("`") || value.includes("\n") ? ` ${value} ` : value}${fence}`;
479
+ }
480
+ function renderListItem(fragment, marker) {
481
+ const [first = "", ...rest] = renderDocument(fragment.kind === "listItem" ? fragment.content : fragment).split("\n");
482
+ const padding = " ".repeat(marker.length + 1);
483
+ return [`${marker} ${first}`, ...rest.map((line) => `${padding}${line}`)].join("\n");
484
+ }
485
+ function normalizeItems(items) {
486
+ const fragment = normalizeContent(items);
487
+ if (fragment.kind === "sequence") return fragment.children;
488
+ if (fragment.kind === "empty") return [];
489
+ return [fragment];
490
+ }
491
+ function flattenSequence(fragment) {
492
+ if (fragment.kind === "sequence") return fragment.children.flatMap(flattenSequence);
493
+ return [fragment];
494
+ }
495
+ function isInline(fragment) {
496
+ return [
497
+ "text",
498
+ "bold",
499
+ "italic",
500
+ "link",
501
+ "code",
502
+ "empty"
503
+ ].includes(fragment.kind);
504
+ }
505
+ function clampHeadingLevel(level) {
506
+ if (!Number.isFinite(level)) return 1;
507
+ return Math.min(6, Math.max(1, Math.trunc(level)));
508
+ }
509
+ function sanitizeLanguage(language) {
510
+ return language.trim().replace(/[^a-zA-Z0-9_+.-]/gu, "");
511
+ }
512
+ function validateSafeUrl(value) {
513
+ const trimmed = value.trim();
514
+ if (!SAFE_URL_PATTERN.test(trimmed)) throw new TypeError(`Unsafe URL value: ${value}`);
515
+ }
516
+ function escapeMarkdownText(value) {
517
+ return value.replace(/([\\`*_{}[\]()#+\-.!<>|])/gu, "\\$1");
518
+ }
519
+ function escapeUrl(value) {
520
+ return value.trim().replace(/\)/gu, "%29").replace(/\s/gu, "%20");
521
+ }
522
+ function longestBacktickRun(value) {
523
+ return Math.max(0, ...Array.from(value.matchAll(/`+/gu), (match) => match[0]?.length ?? 0));
524
+ }
525
+ //#endregion
526
+ //#region src/extension.ts
527
+ var SERIALIZED_PREFIX = "turbowarp-markdown:v1:";
528
+ var blockDefinitions = block_definitions_default.blocks;
529
+ var MarkdownExtension = class {
530
+ getInfo() {
531
+ return {
532
+ id: extensionConfig.id,
533
+ name: Scratch.translate(block_definitions_default.extensionName),
534
+ docsURI: extensionConfig.docsURI,
535
+ blockIconURI: extensionConfig.blockIconURI,
536
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
537
+ };
538
+ }
539
+ text(args) {
540
+ return encode(text(Scratch.Cast.toString(args.TEXT)));
541
+ }
542
+ bold(args) {
543
+ return encode(bold(decodeOrText(args.CONTENT)));
544
+ }
545
+ italic(args) {
546
+ return encode(italic(decodeOrText(args.CONTENT)));
547
+ }
548
+ link(args) {
549
+ return encode(link(decodeOrText(args.CONTENT), Scratch.Cast.toString(args.URL)));
550
+ }
551
+ code(args) {
552
+ return encode(code(Scratch.Cast.toString(args.TEXT)));
553
+ }
554
+ heading(args) {
555
+ return encode(heading(Scratch.Cast.toNumber(args.LEVEL), decodeOrText(args.CONTENT)));
556
+ }
557
+ paragraph(args) {
558
+ return encode(paragraph(decodeOrText(args.CONTENT)));
559
+ }
560
+ quote(args) {
561
+ return encode(quote(decodeOrText(args.CONTENT)));
562
+ }
563
+ codeBlock(args) {
564
+ return encode(codeBlock(Scratch.Cast.toString(args.TEXT), Scratch.Cast.toString(args.LANGUAGE)));
565
+ }
566
+ listItem(args) {
567
+ return encode(listItem(decodeOrText(args.CONTENT)));
568
+ }
569
+ unorderedList(args) {
570
+ return encode(unorderedList(decodeOrText(args.ITEMS)));
571
+ }
572
+ orderedList(args) {
573
+ return encode(orderedList(decodeOrText(args.ITEMS)));
574
+ }
575
+ concat(args) {
576
+ return encode(concat(decodeOrText(args.LEFT), decodeOrText(args.RIGHT)));
577
+ }
578
+ render(args) {
579
+ return render(decodeOrText(args.FRAGMENT));
580
+ }
581
+ renderWithValidation(args) {
582
+ return renderWithValidation(decodeOrText(args.FRAGMENT));
583
+ }
584
+ lastValidationErrors() {
585
+ return getLastRenderValidationErrorText();
586
+ }
587
+ lastRenderHasValidationErrors() {
588
+ return getLastRenderValidationErrors().length > 0;
589
+ }
590
+ validateMarkdown(args) {
591
+ return formatValidationResult(validate(decodeOrText(args.FRAGMENT)));
592
+ }
593
+ isValidMarkdown(args) {
594
+ return isValid(decodeOrText(args.FRAGMENT));
595
+ }
596
+ toScratchBlock(block) {
597
+ return {
598
+ opcode: block.opcode,
599
+ blockType: Scratch.BlockType[block.blockType],
600
+ text: Scratch.translate(block.text),
601
+ arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
602
+ type: Scratch.ArgumentType[argument.type],
603
+ defaultValue: argument.defaultValue
604
+ }]))
605
+ };
606
+ }
607
+ };
608
+ function encode(fragment) {
609
+ return `${SERIALIZED_PREFIX}${JSON.stringify(fragment)}`;
610
+ }
611
+ function decodeOrText(value) {
612
+ const raw = Scratch.Cast.toString(value);
613
+ if (!raw.startsWith(SERIALIZED_PREFIX)) return text(raw);
614
+ return parseFragment(raw.slice(22));
615
+ }
616
+ function parseFragment(json) {
617
+ const parsed = JSON.parse(json);
618
+ if (!isFragment(parsed)) throw new TypeError("Invalid serialized Markdown fragment.");
619
+ return parsed;
620
+ }
621
+ function isFragment(value) {
622
+ if (typeof value !== "object" || value === null) return false;
623
+ const record = value;
624
+ if (record.kind === "empty") return true;
625
+ if (record.kind === "text" || record.kind === "code") return typeof record.value === "string";
626
+ if (record.kind === "bold" || record.kind === "italic" || record.kind === "paragraph") return isFragment(record.content);
627
+ if (record.kind === "link") return typeof record.url === "string" && isFragment(record.content);
628
+ if (record.kind === "heading") return typeof record.level === "number" && isFragment(record.content);
629
+ if (record.kind === "quote" || record.kind === "listItem") return isFragment(record.content);
630
+ if (record.kind === "codeBlock") return typeof record.language === "string" && typeof record.value === "string";
631
+ if (record.kind === "list") return typeof record.ordered === "boolean" && Array.isArray(record.items) && record.items.every(isFragment);
632
+ if (record.kind === "sequence") return Array.isArray(record.children) && record.children.every(isFragment);
633
+ return false;
634
+ }
635
+ //#endregion
636
+ //#region src/index.ts
637
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
638
+ Scratch.extensions.register(new MarkdownExtension());
639
+ //#endregion
640
+
641
+ })(Scratch);
@@ -0,0 +1,23 @@
1
+ # アーキテクチャ
2
+
3
+ [English](architecture.md)
4
+
5
+ ## モデル
6
+
7
+ Markdown は immutable な inline、block、sequence、empty フラグメントとして表現します。builder 操作は入力を変更せず、新しい値を返します。Markdown 文字列は `render` でのみ生成します。
8
+
9
+ ## 安全方針
10
+
11
+ 通常 text は Markdown 構文文字をエスケープし、ユーザー文字列を raw Markdown として解釈しません。inline code と fenced code block は決定的な delimiter を選びます。link destination は `javascript:` などの実行可能 URL scheme を拒否します。raw Markdown ブロックは v1 では提供しません。
12
+
13
+ ## バリデーション
14
+
15
+ validator は軽量なツリーチェックです。`render Markdown [FRAGMENT]` は validation なしでレンダリングします。`render Markdown with validation [FRAGMENT]` はレンダリング前に validation を実行し、直近の validated render の validation 結果を保持します。保持された error 文字列は `last Markdown validation errors`、boolean 状態は `last rendered Markdown has validation errors?` から取得できます。
16
+
17
+ これは HTTP レスポンス処理との連携点です。server 拡張は validation 付き render ブロックを使い、その後で保持済み error を確認し、必要ならレスポンス本文を説明付きエラーページに差し替え、同じ診断をログに出せます。
18
+
19
+ `listItem` が list の外にある場合や、inline 専用フラグメントの中に block fragment が入る場合は error として報告します。空フラグメント、空 list、空 heading、表示内容や URL のない link などは warning として報告します。完全な CommonMark conformance checker の代替ではありません。
20
+
21
+ ## TurboWarp 境界
22
+
23
+ reporter block 間では `turbowarp-markdown:v1:` 接頭辞付きの値を渡します。content 引数に通常文字列が渡された場合は text fragment として扱います。