@immediately-run/sdk 0.28.0 → 0.30.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 (61) hide show
  1. package/dist/components/HeadingAnchor.cjs +45 -0
  2. package/dist/components/HeadingAnchor.cjs.map +1 -0
  3. package/dist/components/HeadingAnchor.d.cts +29 -0
  4. package/dist/components/HeadingAnchor.d.ts +29 -0
  5. package/dist/components/HeadingAnchor.js +21 -0
  6. package/dist/components/HeadingAnchor.js.map +1 -0
  7. package/dist/components/MDXComponents.cjs +5 -0
  8. package/dist/components/MDXComponents.cjs.map +1 -1
  9. package/dist/components/MDXComponents.d.cts +1 -0
  10. package/dist/components/MDXComponents.d.ts +1 -0
  11. package/dist/components/MDXComponents.js +4 -0
  12. package/dist/components/MDXComponents.js.map +1 -1
  13. package/dist/index.cjs +3 -1
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +6 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +1 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/safeContent/SafeContent.cjs +54 -0
  20. package/dist/safeContent/SafeContent.cjs.map +1 -0
  21. package/dist/safeContent/SafeContent.d.cts +13 -0
  22. package/dist/safeContent/SafeContent.d.ts +13 -0
  23. package/dist/safeContent/SafeContent.js +30 -0
  24. package/dist/safeContent/SafeContent.js.map +1 -0
  25. package/dist/safeContent/index.cjs +43 -0
  26. package/dist/safeContent/index.cjs.map +1 -0
  27. package/dist/safeContent/index.d.cts +6 -0
  28. package/dist/safeContent/index.d.ts +6 -0
  29. package/dist/safeContent/index.js +14 -0
  30. package/dist/safeContent/index.js.map +1 -0
  31. package/dist/safeContent/parseSafeMdast.cjs +69 -0
  32. package/dist/safeContent/parseSafeMdast.cjs.map +1 -0
  33. package/dist/safeContent/parseSafeMdast.d.cts +31 -0
  34. package/dist/safeContent/parseSafeMdast.d.ts +31 -0
  35. package/dist/safeContent/parseSafeMdast.js +35 -0
  36. package/dist/safeContent/parseSafeMdast.js.map +1 -0
  37. package/dist/safeContent/renderMdast.cjs +138 -0
  38. package/dist/safeContent/renderMdast.cjs.map +1 -0
  39. package/dist/safeContent/renderMdast.d.cts +27 -0
  40. package/dist/safeContent/renderMdast.d.ts +27 -0
  41. package/dist/safeContent/renderMdast.js +114 -0
  42. package/dist/safeContent/renderMdast.js.map +1 -0
  43. package/dist/safeContent/sanitizeUrl.cjs +39 -0
  44. package/dist/safeContent/sanitizeUrl.cjs.map +1 -0
  45. package/dist/safeContent/sanitizeUrl.d.cts +9 -0
  46. package/dist/safeContent/sanitizeUrl.d.ts +9 -0
  47. package/dist/safeContent/sanitizeUrl.js +15 -0
  48. package/dist/safeContent/sanitizeUrl.js.map +1 -0
  49. package/dist/safeContent/wikilink.cjs +63 -0
  50. package/dist/safeContent/wikilink.cjs.map +1 -0
  51. package/dist/safeContent/wikilink.d.cts +21 -0
  52. package/dist/safeContent/wikilink.d.ts +21 -0
  53. package/dist/safeContent/wikilink.js +38 -0
  54. package/dist/safeContent/wikilink.js.map +1 -0
  55. package/dist/version.cjs +1 -1
  56. package/dist/version.cjs.map +1 -1
  57. package/dist/version.d.cts +1 -1
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/version.js.map +1 -1
  61. package/package.json +9 -3
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/safeContent/parseSafeMdast.ts"],"sourcesContent":["// The no-acorn parse pipeline for the safe content renderer (TRUST_MODES_SPEC §5.1,\n// empirically verified 2026-07-07 against `@mdx-js/mdx` v3 / `micromark-extension-\n// mdx-jsx`). This is the load-bearing half of the fail-safe: `<Component/>` syntax\n// parses to an element node with **literal** attributes, and every expression\n// (`n={1+1}`, `f={fetch(\"/x\")}`, `{...spread}`) is captured as an **inert raw string\n// with no estree** — because we pass **NO acorn option** to `micromark-extension-mdx-\n// jsx`. There is therefore no evaluator anywhere in the pipeline (fail-safe), unlike\n// `@mdx-js/mdx`'s `compile({format:'mdx'})` which always wires acorn.\n//\n// The §5.1 residual guarantees are also here: the expression micromark extension is\n// **not** enabled (body `{…}` stays literal text), and **no `rehype-raw`** / raw-HTML\n// passthrough exists — raw HTML blocks arrive as inert `html` mdast nodes the renderer\n// prints as text, never injected.\n//\n// `micromark`/`mdast` are ESM-only. They are loaded with a memoised dynamic `import()`\n// (the transpiler's `compile.ts` pattern) so this module sits in the package's CJS\n// build too — a CJS consumer that never renders untrusted content never `require()`s\n// an ESM-only package, and one that does gets it via Node's ESM-from-CJS import. The\n// dynamic load changes only *when* the deps resolve, never the produced tree.\n\n// A minimal structural mdast shape — we deliberately avoid a type dependency on the\n// ESM-only `mdast`/`unist` packages (which would break the CJS build's type surface).\nexport interface SafeMdastNode {\n type: string;\n value?: string;\n name?: string | null;\n url?: string;\n alt?: string | null;\n title?: string | null;\n depth?: number;\n ordered?: boolean;\n lang?: string | null;\n children?: SafeMdastNode[];\n attributes?: SafeMdxAttribute[];\n [key: string]: unknown;\n}\n\nexport interface SafeMdxAttribute {\n type: 'mdxJsxAttribute' | 'mdxJsxExpressionAttribute';\n name?: string;\n // A literal attribute carries a string; an expression attribute carries an\n // `mdxJsxAttributeValueExpression` object (a raw string, NO estree) or a string.\n value?: string | { type: string; value?: string } | null;\n}\n\ntype Deps = {\n fromMarkdown: (\n value: string,\n options: { extensions: unknown[]; mdastExtensions: unknown[] },\n ) => SafeMdastNode;\n mdxJsx: () => unknown;\n mdxJsxFromMarkdown: () => unknown;\n gfm: () => unknown;\n gfmFromMarkdown: () => unknown;\n};\n\nlet depsPromise: Promise<Deps> | null = null;\n\nfunction loadDeps(): Promise<Deps> {\n if (!depsPromise) {\n depsPromise = Promise.all([\n import('mdast-util-from-markdown'),\n import('micromark-extension-mdx-jsx'),\n import('mdast-util-mdx-jsx'),\n import('micromark-extension-gfm'),\n import('mdast-util-gfm'),\n ]).then(\n ([fromMd, mdxJsxExt, mdxJsxMdast, gfmExt, gfmMdast]) =>\n ({\n fromMarkdown: (fromMd as unknown as { fromMarkdown: Deps['fromMarkdown'] }).fromMarkdown,\n mdxJsx: (mdxJsxExt as unknown as { mdxJsx: Deps['mdxJsx'] }).mdxJsx,\n mdxJsxFromMarkdown: (mdxJsxMdast as unknown as { mdxJsxFromMarkdown: Deps['mdxJsxFromMarkdown'] })\n .mdxJsxFromMarkdown,\n gfm: (gfmExt as unknown as { gfm: Deps['gfm'] }).gfm,\n gfmFromMarkdown: (gfmMdast as unknown as { gfmFromMarkdown: Deps['gfmFromMarkdown'] }).gfmFromMarkdown,\n }) as Deps,\n );\n }\n return depsPromise;\n}\n\n/**\n * Parse untrusted Markdown/MDX-syntax source to an mdast tree with **no evaluator in\n * the pipeline**: JSX-as-data (no acorn), GFM on, the expression extension OFF, no\n * raw-HTML re-parse. The returned tree is safe to hand to `renderMdast` — expression\n * attributes are inert strings and raw HTML is inert `html` nodes.\n */\nexport async function parseSafeMdast(source: string): Promise<SafeMdastNode> {\n const { fromMarkdown, mdxJsx, mdxJsxFromMarkdown, gfm, gfmFromMarkdown } = await loadDeps();\n return fromMarkdown(source, {\n // `mdxJsx()` WITHOUT an acorn option → JSX tags + literal attrs; expressions are\n // raw strings, never estree. The mdx *expression* extension is intentionally\n // absent, so `{…}` in body text stays literal. GFM for tables/task-lists.\n extensions: [mdxJsx(), gfm()],\n mdastExtensions: [mdxJsxFromMarkdown(), gfmFromMarkdown()],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAwDA,IAAI,cAAoC;AAExC,SAAS,WAA0B;AACjC,MAAI,CAAC,aAAa;AAChB,kBAAc,QAAQ,IAAI;AAAA,MACxB,OAAO,0BAA0B;AAAA,MACjC,OAAO,6BAA6B;AAAA,MACpC,OAAO,oBAAoB;AAAA,MAC3B,OAAO,yBAAyB;AAAA,MAChC,OAAO,gBAAgB;AAAA,IACzB,CAAC,EAAE;AAAA,MACD,CAAC,CAAC,QAAQ,WAAW,aAAa,QAAQ,QAAQ,OAC/C;AAAA,QACC,cAAe,OAA6D;AAAA,QAC5E,QAAS,UAAoD;AAAA,QAC7D,oBAAqB,YAClB;AAAA,QACH,KAAM,OAA2C;AAAA,QACjD,iBAAkB,SAAqE;AAAA,MACzF;AAAA,IACJ;AAAA,EACF;AACA,SAAO;AACT;AAQA,eAAsB,eAAe,QAAwC;AAC3E,QAAM,EAAE,cAAc,QAAQ,oBAAoB,KAAK,gBAAgB,IAAI,MAAM,SAAS;AAC1F,SAAO,aAAa,QAAQ;AAAA;AAAA;AAAA;AAAA,IAI1B,YAAY,CAAC,OAAO,GAAG,IAAI,CAAC;AAAA,IAC5B,iBAAiB,CAAC,mBAAmB,GAAG,gBAAgB,CAAC;AAAA,EAC3D,CAAC;AACH;","names":[]}
@@ -0,0 +1,31 @@
1
+ interface SafeMdastNode {
2
+ type: string;
3
+ value?: string;
4
+ name?: string | null;
5
+ url?: string;
6
+ alt?: string | null;
7
+ title?: string | null;
8
+ depth?: number;
9
+ ordered?: boolean;
10
+ lang?: string | null;
11
+ children?: SafeMdastNode[];
12
+ attributes?: SafeMdxAttribute[];
13
+ [key: string]: unknown;
14
+ }
15
+ interface SafeMdxAttribute {
16
+ type: 'mdxJsxAttribute' | 'mdxJsxExpressionAttribute';
17
+ name?: string;
18
+ value?: string | {
19
+ type: string;
20
+ value?: string;
21
+ } | null;
22
+ }
23
+ /**
24
+ * Parse untrusted Markdown/MDX-syntax source to an mdast tree with **no evaluator in
25
+ * the pipeline**: JSX-as-data (no acorn), GFM on, the expression extension OFF, no
26
+ * raw-HTML re-parse. The returned tree is safe to hand to `renderMdast` — expression
27
+ * attributes are inert strings and raw HTML is inert `html` nodes.
28
+ */
29
+ declare function parseSafeMdast(source: string): Promise<SafeMdastNode>;
30
+
31
+ export { type SafeMdastNode, type SafeMdxAttribute, parseSafeMdast };
@@ -0,0 +1,31 @@
1
+ interface SafeMdastNode {
2
+ type: string;
3
+ value?: string;
4
+ name?: string | null;
5
+ url?: string;
6
+ alt?: string | null;
7
+ title?: string | null;
8
+ depth?: number;
9
+ ordered?: boolean;
10
+ lang?: string | null;
11
+ children?: SafeMdastNode[];
12
+ attributes?: SafeMdxAttribute[];
13
+ [key: string]: unknown;
14
+ }
15
+ interface SafeMdxAttribute {
16
+ type: 'mdxJsxAttribute' | 'mdxJsxExpressionAttribute';
17
+ name?: string;
18
+ value?: string | {
19
+ type: string;
20
+ value?: string;
21
+ } | null;
22
+ }
23
+ /**
24
+ * Parse untrusted Markdown/MDX-syntax source to an mdast tree with **no evaluator in
25
+ * the pipeline**: JSX-as-data (no acorn), GFM on, the expression extension OFF, no
26
+ * raw-HTML re-parse. The returned tree is safe to hand to `renderMdast` — expression
27
+ * attributes are inert strings and raw HTML is inert `html` nodes.
28
+ */
29
+ declare function parseSafeMdast(source: string): Promise<SafeMdastNode>;
30
+
31
+ export { type SafeMdastNode, type SafeMdxAttribute, parseSafeMdast };
@@ -0,0 +1,35 @@
1
+ let depsPromise = null;
2
+ function loadDeps() {
3
+ if (!depsPromise) {
4
+ depsPromise = Promise.all([
5
+ import("mdast-util-from-markdown"),
6
+ import("micromark-extension-mdx-jsx"),
7
+ import("mdast-util-mdx-jsx"),
8
+ import("micromark-extension-gfm"),
9
+ import("mdast-util-gfm")
10
+ ]).then(
11
+ ([fromMd, mdxJsxExt, mdxJsxMdast, gfmExt, gfmMdast]) => ({
12
+ fromMarkdown: fromMd.fromMarkdown,
13
+ mdxJsx: mdxJsxExt.mdxJsx,
14
+ mdxJsxFromMarkdown: mdxJsxMdast.mdxJsxFromMarkdown,
15
+ gfm: gfmExt.gfm,
16
+ gfmFromMarkdown: gfmMdast.gfmFromMarkdown
17
+ })
18
+ );
19
+ }
20
+ return depsPromise;
21
+ }
22
+ async function parseSafeMdast(source) {
23
+ const { fromMarkdown, mdxJsx, mdxJsxFromMarkdown, gfm, gfmFromMarkdown } = await loadDeps();
24
+ return fromMarkdown(source, {
25
+ // `mdxJsx()` WITHOUT an acorn option → JSX tags + literal attrs; expressions are
26
+ // raw strings, never estree. The mdx *expression* extension is intentionally
27
+ // absent, so `{…}` in body text stays literal. GFM for tables/task-lists.
28
+ extensions: [mdxJsx(), gfm()],
29
+ mdastExtensions: [mdxJsxFromMarkdown(), gfmFromMarkdown()]
30
+ });
31
+ }
32
+ export {
33
+ parseSafeMdast
34
+ };
35
+ //# sourceMappingURL=parseSafeMdast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/safeContent/parseSafeMdast.ts"],"sourcesContent":["// The no-acorn parse pipeline for the safe content renderer (TRUST_MODES_SPEC §5.1,\n// empirically verified 2026-07-07 against `@mdx-js/mdx` v3 / `micromark-extension-\n// mdx-jsx`). This is the load-bearing half of the fail-safe: `<Component/>` syntax\n// parses to an element node with **literal** attributes, and every expression\n// (`n={1+1}`, `f={fetch(\"/x\")}`, `{...spread}`) is captured as an **inert raw string\n// with no estree** — because we pass **NO acorn option** to `micromark-extension-mdx-\n// jsx`. There is therefore no evaluator anywhere in the pipeline (fail-safe), unlike\n// `@mdx-js/mdx`'s `compile({format:'mdx'})` which always wires acorn.\n//\n// The §5.1 residual guarantees are also here: the expression micromark extension is\n// **not** enabled (body `{…}` stays literal text), and **no `rehype-raw`** / raw-HTML\n// passthrough exists — raw HTML blocks arrive as inert `html` mdast nodes the renderer\n// prints as text, never injected.\n//\n// `micromark`/`mdast` are ESM-only. They are loaded with a memoised dynamic `import()`\n// (the transpiler's `compile.ts` pattern) so this module sits in the package's CJS\n// build too — a CJS consumer that never renders untrusted content never `require()`s\n// an ESM-only package, and one that does gets it via Node's ESM-from-CJS import. The\n// dynamic load changes only *when* the deps resolve, never the produced tree.\n\n// A minimal structural mdast shape — we deliberately avoid a type dependency on the\n// ESM-only `mdast`/`unist` packages (which would break the CJS build's type surface).\nexport interface SafeMdastNode {\n type: string;\n value?: string;\n name?: string | null;\n url?: string;\n alt?: string | null;\n title?: string | null;\n depth?: number;\n ordered?: boolean;\n lang?: string | null;\n children?: SafeMdastNode[];\n attributes?: SafeMdxAttribute[];\n [key: string]: unknown;\n}\n\nexport interface SafeMdxAttribute {\n type: 'mdxJsxAttribute' | 'mdxJsxExpressionAttribute';\n name?: string;\n // A literal attribute carries a string; an expression attribute carries an\n // `mdxJsxAttributeValueExpression` object (a raw string, NO estree) or a string.\n value?: string | { type: string; value?: string } | null;\n}\n\ntype Deps = {\n fromMarkdown: (\n value: string,\n options: { extensions: unknown[]; mdastExtensions: unknown[] },\n ) => SafeMdastNode;\n mdxJsx: () => unknown;\n mdxJsxFromMarkdown: () => unknown;\n gfm: () => unknown;\n gfmFromMarkdown: () => unknown;\n};\n\nlet depsPromise: Promise<Deps> | null = null;\n\nfunction loadDeps(): Promise<Deps> {\n if (!depsPromise) {\n depsPromise = Promise.all([\n import('mdast-util-from-markdown'),\n import('micromark-extension-mdx-jsx'),\n import('mdast-util-mdx-jsx'),\n import('micromark-extension-gfm'),\n import('mdast-util-gfm'),\n ]).then(\n ([fromMd, mdxJsxExt, mdxJsxMdast, gfmExt, gfmMdast]) =>\n ({\n fromMarkdown: (fromMd as unknown as { fromMarkdown: Deps['fromMarkdown'] }).fromMarkdown,\n mdxJsx: (mdxJsxExt as unknown as { mdxJsx: Deps['mdxJsx'] }).mdxJsx,\n mdxJsxFromMarkdown: (mdxJsxMdast as unknown as { mdxJsxFromMarkdown: Deps['mdxJsxFromMarkdown'] })\n .mdxJsxFromMarkdown,\n gfm: (gfmExt as unknown as { gfm: Deps['gfm'] }).gfm,\n gfmFromMarkdown: (gfmMdast as unknown as { gfmFromMarkdown: Deps['gfmFromMarkdown'] }).gfmFromMarkdown,\n }) as Deps,\n );\n }\n return depsPromise;\n}\n\n/**\n * Parse untrusted Markdown/MDX-syntax source to an mdast tree with **no evaluator in\n * the pipeline**: JSX-as-data (no acorn), GFM on, the expression extension OFF, no\n * raw-HTML re-parse. The returned tree is safe to hand to `renderMdast` — expression\n * attributes are inert strings and raw HTML is inert `html` nodes.\n */\nexport async function parseSafeMdast(source: string): Promise<SafeMdastNode> {\n const { fromMarkdown, mdxJsx, mdxJsxFromMarkdown, gfm, gfmFromMarkdown } = await loadDeps();\n return fromMarkdown(source, {\n // `mdxJsx()` WITHOUT an acorn option → JSX tags + literal attrs; expressions are\n // raw strings, never estree. The mdx *expression* extension is intentionally\n // absent, so `{…}` in body text stays literal. GFM for tables/task-lists.\n extensions: [mdxJsx(), gfm()],\n mdastExtensions: [mdxJsxFromMarkdown(), gfmFromMarkdown()],\n });\n}\n"],"mappings":"AAwDA,IAAI,cAAoC;AAExC,SAAS,WAA0B;AACjC,MAAI,CAAC,aAAa;AAChB,kBAAc,QAAQ,IAAI;AAAA,MACxB,OAAO,0BAA0B;AAAA,MACjC,OAAO,6BAA6B;AAAA,MACpC,OAAO,oBAAoB;AAAA,MAC3B,OAAO,yBAAyB;AAAA,MAChC,OAAO,gBAAgB;AAAA,IACzB,CAAC,EAAE;AAAA,MACD,CAAC,CAAC,QAAQ,WAAW,aAAa,QAAQ,QAAQ,OAC/C;AAAA,QACC,cAAe,OAA6D;AAAA,QAC5E,QAAS,UAAoD;AAAA,QAC7D,oBAAqB,YAClB;AAAA,QACH,KAAM,OAA2C;AAAA,QACjD,iBAAkB,SAAqE;AAAA,MACzF;AAAA,IACJ;AAAA,EACF;AACA,SAAO;AACT;AAQA,eAAsB,eAAe,QAAwC;AAC3E,QAAM,EAAE,cAAc,QAAQ,oBAAoB,KAAK,gBAAgB,IAAI,MAAM,SAAS;AAC1F,SAAO,aAAa,QAAQ;AAAA;AAAA;AAAA;AAAA,IAI1B,YAAY,CAAC,OAAO,GAAG,IAAI,CAAC;AAAA,IAC5B,iBAAiB,CAAC,mBAAmB,GAAG,gBAAgB,CAAC;AAAA,EAC3D,CAAC;AACH;","names":[]}
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var renderMdast_exports = {};
20
+ __export(renderMdast_exports, {
21
+ renderMdast: () => renderMdast
22
+ });
23
+ module.exports = __toCommonJS(renderMdast_exports);
24
+ var import_react = require("react");
25
+ var import_sanitizeUrl = require("./sanitizeUrl");
26
+ var import_wikilink = require("./wikilink");
27
+ function literalProps(attributes) {
28
+ const props = {};
29
+ for (const attr of attributes ?? []) {
30
+ if (attr.type !== "mdxJsxAttribute") continue;
31
+ if (typeof attr.name !== "string") continue;
32
+ if (typeof attr.value === "string") props[attr.name] = attr.value;
33
+ else if (attr.value === null || attr.value === void 0) props[attr.name] = "";
34
+ }
35
+ return props;
36
+ }
37
+ let keyCounter = 0;
38
+ const nextKey = () => `sc-${keyCounter++}`;
39
+ function renderWiki(token, resolve) {
40
+ const label = token.label ?? token.target;
41
+ const href = resolve?.(token.target);
42
+ const safe = href !== void 0 ? (0, import_sanitizeUrl.sanitizeUrl)(href) : void 0;
43
+ if (safe === void 0) return label;
44
+ return (0, import_react.createElement)("a", { href: safe, "data-wikilink": token.target, key: nextKey() }, label);
45
+ }
46
+ function renderText(value, opts) {
47
+ const parts = (0, import_wikilink.splitWikiLinks)(value);
48
+ if (!parts) return value;
49
+ return parts.map(
50
+ (p, i) => "text" in p ? (0, import_react.createElement)(import_react.Fragment, { key: `t${i}` }, p.text) : (0, import_react.createElement)(import_react.Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink))
51
+ );
52
+ }
53
+ function renderChildren(node, opts) {
54
+ return (node.children ?? []).map((c, i) => renderNode(c, opts, i));
55
+ }
56
+ const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"];
57
+ function renderNode(node, opts, index = 0) {
58
+ const key = `n${index}`;
59
+ switch (node.type) {
60
+ case "root":
61
+ return (0, import_react.createElement)(import_react.Fragment, { key }, ...renderChildren(node, opts));
62
+ case "text":
63
+ return renderText(node.value ?? "", opts);
64
+ case "paragraph":
65
+ return (0, import_react.createElement)("p", { key }, ...renderChildren(node, opts));
66
+ case "heading": {
67
+ const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];
68
+ return (0, import_react.createElement)(tag, { key }, ...renderChildren(node, opts));
69
+ }
70
+ case "strong":
71
+ return (0, import_react.createElement)("strong", { key }, ...renderChildren(node, opts));
72
+ case "emphasis":
73
+ return (0, import_react.createElement)("em", { key }, ...renderChildren(node, opts));
74
+ case "delete":
75
+ return (0, import_react.createElement)("del", { key }, ...renderChildren(node, opts));
76
+ case "inlineCode":
77
+ return (0, import_react.createElement)("code", { key }, node.value ?? "");
78
+ case "code":
79
+ return (0, import_react.createElement)("pre", { key }, (0, import_react.createElement)("code", null, node.value ?? ""));
80
+ case "blockquote":
81
+ return (0, import_react.createElement)("blockquote", { key }, ...renderChildren(node, opts));
82
+ case "list":
83
+ return (0, import_react.createElement)(node.ordered ? "ol" : "ul", { key }, ...renderChildren(node, opts));
84
+ case "listItem":
85
+ return (0, import_react.createElement)("li", { key }, ...renderChildren(node, opts));
86
+ case "thematicBreak":
87
+ return (0, import_react.createElement)("hr", { key });
88
+ case "break":
89
+ return (0, import_react.createElement)("br", { key });
90
+ case "link": {
91
+ const href = (0, import_sanitizeUrl.sanitizeUrl)(node.url);
92
+ if (href === void 0) return (0, import_react.createElement)(import_react.Fragment, { key }, ...renderChildren(node, opts));
93
+ return (0, import_react.createElement)("a", { key, href, title: node.title ?? void 0 }, ...renderChildren(node, opts));
94
+ }
95
+ case "image": {
96
+ const src = (0, import_sanitizeUrl.sanitizeUrl)(node.url);
97
+ if (src === void 0) return node.alt ? (0, import_react.createElement)(import_react.Fragment, { key }, node.alt) : null;
98
+ return (0, import_react.createElement)("img", { key, src, alt: node.alt ?? "", title: node.title ?? void 0 });
99
+ }
100
+ // GFM tables.
101
+ case "table":
102
+ return (0, import_react.createElement)("table", { key }, (0, import_react.createElement)("tbody", null, ...renderChildren(node, opts)));
103
+ case "tableRow":
104
+ return (0, import_react.createElement)("tr", { key }, ...renderChildren(node, opts));
105
+ case "tableCell":
106
+ return (0, import_react.createElement)("td", { key }, ...renderChildren(node, opts));
107
+ // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No
108
+ // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.
109
+ case "html":
110
+ return (0, import_react.createElement)(import_react.Fragment, { key }, node.value ?? "");
111
+ // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.
112
+ case "mdxJsxFlowElement":
113
+ case "mdxJsxTextElement": {
114
+ const name = typeof node.name === "string" ? node.name : "";
115
+ const Component = name ? opts.components?.[name] : void 0;
116
+ const children = renderChildren(node, opts);
117
+ if (!Component) return (0, import_react.createElement)(import_react.Fragment, { key }, ...children);
118
+ return (0, import_react.createElement)(Component, { key, ...literalProps(node.attributes) }, ...children);
119
+ }
120
+ // Inert expression nodes (should not occur — expression extension is off — but be
121
+ // defensive if a tree from elsewhere carries them): render nothing.
122
+ case "mdxFlowExpression":
123
+ case "mdxTextExpression":
124
+ case "mdxjsEsm":
125
+ return null;
126
+ default:
127
+ return node.children ? (0, import_react.createElement)(import_react.Fragment, { key }, ...renderChildren(node, opts)) : null;
128
+ }
129
+ }
130
+ function renderMdast(tree, options = {}) {
131
+ keyCounter = 0;
132
+ return renderNode(tree, options);
133
+ }
134
+ // Annotate the CommonJS export names for ESM import in node:
135
+ 0 && (module.exports = {
136
+ renderMdast
137
+ });
138
+ //# sourceMappingURL=renderMdast.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/safeContent/renderMdast.tsx"],"sourcesContent":["import { createElement, Fragment, type ReactNode } from 'react';\nimport { sanitizeUrl } from './sanitizeUrl';\nimport { splitWikiLinks, type WikiLinkToken } from './wikilink';\nimport type { SafeMdastNode, SafeMdxAttribute } from './parseSafeMdast';\n\n// The mdast→React renderer for the safe content path (TRUST_MODES_SPEC §5.1). PURE\n// and synchronous — it only reads `node.type` off an already-parsed tree, so it\n// carries no ESM dep and is exhaustively unit-testable. Every security property lives\n// here:\n//\n// - **JSX tags resolve ONLY to a component registry, by name.** A `<Component/>`\n// node becomes `registry[name]` with **literal string props only**; an unknown tag\n// renders its children inert (a Fragment, no element) — so author-written `<div\n// onclick=…>`, `<img onerror=…>`, `<script>` never become an intrinsic element with\n// attacker attributes. (Block-level raw HTML arrives as an `html` node, below.)\n// - **Expression attributes are dropped.** `f={fetch(\"/x\")}` / `{...spread}` are\n// `mdxJsxExpressionAttribute` or object-valued `mdxJsxAttribute`s — never passed to\n// a component, never evaluated. (There is also no evaluator to reach — parse used\n// no acorn.)\n// - **Raw HTML is inert text.** `html` nodes render as their literal string via a\n// text node — never `dangerouslySetInnerHTML` (no `rehype-raw`).\n// - **URL-scheme sanitizer** on every `link`/`image` URL (`sanitizeUrl`).\n// - **Wikilinks resolve in-mount only** via an injected resolver; the renderer never\n// fetches.\n\nexport interface SafeContentComponents {\n /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).\n * Looked up by the JSX tag name; anything not here renders inert. */\n [tag: string]: React.ComponentType<Record<string, string>>;\n}\n\nexport interface RenderMdastOptions {\n /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */\n components?: SafeContentComponents;\n /**\n * Resolve a wikilink target to an href, **within the granted mount only** — a pure,\n * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.\n * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert\n * text). Absent ⇒ every wikilink renders as inert text.\n */\n resolveWikiLink?: (target: string) => string | undefined;\n}\n\n/** Extract the literal string props of a JSX element — `mdxJsxAttribute`s whose value\n * is a plain string. Expression attributes (object value) and spreads are DROPPED. */\nfunction literalProps(attributes: SafeMdxAttribute[] | undefined): Record<string, string> {\n const props: Record<string, string> = {};\n for (const attr of attributes ?? []) {\n if (attr.type !== 'mdxJsxAttribute') continue; // drop `{...spread}`\n if (typeof attr.name !== 'string') continue;\n // A literal attribute's value is a string (or null → boolean-ish `true`). An\n // expression value is an object (`mdxJsxAttributeValueExpression`) — DROP it: it\n // is an inert raw string, never a real value, and must never reach a component.\n if (typeof attr.value === 'string') props[attr.name] = attr.value;\n else if (attr.value === null || attr.value === undefined) props[attr.name] = '';\n // object-valued (expression) → skipped\n }\n return props;\n}\n\nlet keyCounter = 0;\nconst nextKey = () => `sc-${keyCounter++}`;\n\n/** Render a wikilink token via the in-mount resolver, or inert text when it can't\n * resolve (never a network call — resolution is the injected mount-scoped callback). */\nfunction renderWiki(token: WikiLinkToken, resolve: RenderMdastOptions['resolveWikiLink']): ReactNode {\n const label = token.label ?? token.target;\n const href = resolve?.(token.target);\n const safe = href !== undefined ? sanitizeUrl(href) : undefined;\n if (safe === undefined) return label; // inert text — unresolved or out-of-mount\n return createElement('a', { href: safe, 'data-wikilink': token.target, key: nextKey() }, label);\n}\n\n/** Render a `text` node, splitting any `[[…]]` wikilinks out of it. */\nfunction renderText(value: string, opts: RenderMdastOptions): ReactNode {\n const parts = splitWikiLinks(value);\n if (!parts) return value;\n return parts.map((p, i) =>\n 'text' in p\n ? createElement(Fragment, { key: `t${i}` }, p.text)\n : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink)),\n );\n}\n\nfunction renderChildren(node: SafeMdastNode, opts: RenderMdastOptions): ReactNode[] {\n return (node.children ?? []).map((c, i) => renderNode(c, opts, i));\n}\n\n// Standard mdast block/inline nodes → a FIXED, safe React element. We control every\n// attribute; author input only reaches text content and (sanitized) URLs.\nconst HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;\n\nfunction renderNode(node: SafeMdastNode, opts: RenderMdastOptions, index = 0): ReactNode {\n const key = `n${index}`;\n switch (node.type) {\n case 'root':\n return createElement(Fragment, { key }, ...renderChildren(node, opts));\n case 'text':\n return renderText(node.value ?? '', opts);\n case 'paragraph':\n return createElement('p', { key }, ...renderChildren(node, opts));\n case 'heading': {\n const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];\n return createElement(tag, { key }, ...renderChildren(node, opts));\n }\n case 'strong':\n return createElement('strong', { key }, ...renderChildren(node, opts));\n case 'emphasis':\n return createElement('em', { key }, ...renderChildren(node, opts));\n case 'delete':\n return createElement('del', { key }, ...renderChildren(node, opts));\n case 'inlineCode':\n return createElement('code', { key }, node.value ?? '');\n case 'code':\n return createElement('pre', { key }, createElement('code', null, node.value ?? ''));\n case 'blockquote':\n return createElement('blockquote', { key }, ...renderChildren(node, opts));\n case 'list':\n return createElement(node.ordered ? 'ol' : 'ul', { key }, ...renderChildren(node, opts));\n case 'listItem':\n return createElement('li', { key }, ...renderChildren(node, opts));\n case 'thematicBreak':\n return createElement('hr', { key });\n case 'break':\n return createElement('br', { key });\n case 'link': {\n const href = sanitizeUrl(node.url);\n // A rejected scheme → render the link TEXT only (inert), never an <a href>.\n if (href === undefined) return createElement(Fragment, { key }, ...renderChildren(node, opts));\n return createElement('a', { key, href, title: node.title ?? undefined }, ...renderChildren(node, opts));\n }\n case 'image': {\n const src = sanitizeUrl(node.url);\n if (src === undefined) return node.alt ? createElement(Fragment, { key }, node.alt) : null;\n return createElement('img', { key, src, alt: node.alt ?? '', title: node.title ?? undefined });\n }\n // GFM tables.\n case 'table':\n return createElement('table', { key }, createElement('tbody', null, ...renderChildren(node, opts)));\n case 'tableRow':\n return createElement('tr', { key }, ...renderChildren(node, opts));\n case 'tableCell':\n return createElement('td', { key }, ...renderChildren(node, opts));\n // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No\n // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.\n case 'html':\n return createElement(Fragment, { key }, node.value ?? '');\n // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.\n case 'mdxJsxFlowElement':\n case 'mdxJsxTextElement': {\n const name = typeof node.name === 'string' ? node.name : '';\n const Component = name ? opts.components?.[name] : undefined;\n const children = renderChildren(node, opts);\n // Unknown tag (not in the registry) OR a fragment `<>` → render children inert,\n // NO element, NO author attributes. This is what neutralizes `<script>`/`<div\n // onclick>`/`<img onerror>` written as JSX.\n if (!Component) return createElement(Fragment, { key }, ...children);\n return createElement(Component, { key, ...literalProps(node.attributes) }, ...children);\n }\n // Inert expression nodes (should not occur — expression extension is off — but be\n // defensive if a tree from elsewhere carries them): render nothing.\n case 'mdxFlowExpression':\n case 'mdxTextExpression':\n case 'mdxjsEsm':\n return null;\n default:\n // Unknown node → render its children (never its raw value as markup).\n return node.children ? createElement(Fragment, { key }, ...renderChildren(node, opts)) : null;\n }\n}\n\n/**\n * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1\n * security property (registry-only JSX, dropped expressions, inert raw HTML, URL\n * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.\n */\nexport function renderMdast(tree: SafeMdastNode, options: RenderMdastOptions = {}): ReactNode {\n keyCounter = 0;\n return renderNode(tree, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAwD;AACxD,yBAA4B;AAC5B,sBAAmD;AA2CnD,SAAS,aAAa,YAAoE;AACxF,QAAM,QAAgC,CAAC;AACvC,aAAW,QAAQ,cAAc,CAAC,GAAG;AACnC,QAAI,KAAK,SAAS,kBAAmB;AACrC,QAAI,OAAO,KAAK,SAAS,SAAU;AAInC,QAAI,OAAO,KAAK,UAAU,SAAU,OAAM,KAAK,IAAI,IAAI,KAAK;AAAA,aACnD,KAAK,UAAU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AK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT;AAEE,aAAO,KAAK,eAAW,4BAAc,uBAAU,EAAE,IAAI,GAAG,GAAG,eAAe,MAAM,IAAI,CAAC,IAAI;AAAA,EAC7F;AACF;AAOO,SAAS,YAAY,MAAqB,UAA8B,CAAC,GAAc;AAC5F,eAAa;AACb,SAAO,WAAW,MAAM,OAAO;AACjC;","names":[]}
@@ -0,0 +1,27 @@
1
+ import { ReactNode } from 'react';
2
+ import { SafeMdastNode } from './parseSafeMdast.cjs';
3
+
4
+ interface SafeContentComponents {
5
+ /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).
6
+ * Looked up by the JSX tag name; anything not here renders inert. */
7
+ [tag: string]: React.ComponentType<Record<string, string>>;
8
+ }
9
+ interface RenderMdastOptions {
10
+ /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */
11
+ components?: SafeContentComponents;
12
+ /**
13
+ * Resolve a wikilink target to an href, **within the granted mount only** — a pure,
14
+ * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.
15
+ * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert
16
+ * text). Absent ⇒ every wikilink renders as inert text.
17
+ */
18
+ resolveWikiLink?: (target: string) => string | undefined;
19
+ }
20
+ /**
21
+ * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1
22
+ * security property (registry-only JSX, dropped expressions, inert raw HTML, URL
23
+ * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.
24
+ */
25
+ declare function renderMdast(tree: SafeMdastNode, options?: RenderMdastOptions): ReactNode;
26
+
27
+ export { type RenderMdastOptions, type SafeContentComponents, renderMdast };
@@ -0,0 +1,27 @@
1
+ import { ReactNode } from 'react';
2
+ import { SafeMdastNode } from './parseSafeMdast.js';
3
+
4
+ interface SafeContentComponents {
5
+ /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).
6
+ * Looked up by the JSX tag name; anything not here renders inert. */
7
+ [tag: string]: React.ComponentType<Record<string, string>>;
8
+ }
9
+ interface RenderMdastOptions {
10
+ /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */
11
+ components?: SafeContentComponents;
12
+ /**
13
+ * Resolve a wikilink target to an href, **within the granted mount only** — a pure,
14
+ * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.
15
+ * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert
16
+ * text). Absent ⇒ every wikilink renders as inert text.
17
+ */
18
+ resolveWikiLink?: (target: string) => string | undefined;
19
+ }
20
+ /**
21
+ * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1
22
+ * security property (registry-only JSX, dropped expressions, inert raw HTML, URL
23
+ * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.
24
+ */
25
+ declare function renderMdast(tree: SafeMdastNode, options?: RenderMdastOptions): ReactNode;
26
+
27
+ export { type RenderMdastOptions, type SafeContentComponents, renderMdast };
@@ -0,0 +1,114 @@
1
+ import { createElement, Fragment } from "react";
2
+ import { sanitizeUrl } from "./sanitizeUrl";
3
+ import { splitWikiLinks } from "./wikilink";
4
+ function literalProps(attributes) {
5
+ const props = {};
6
+ for (const attr of attributes ?? []) {
7
+ if (attr.type !== "mdxJsxAttribute") continue;
8
+ if (typeof attr.name !== "string") continue;
9
+ if (typeof attr.value === "string") props[attr.name] = attr.value;
10
+ else if (attr.value === null || attr.value === void 0) props[attr.name] = "";
11
+ }
12
+ return props;
13
+ }
14
+ let keyCounter = 0;
15
+ const nextKey = () => `sc-${keyCounter++}`;
16
+ function renderWiki(token, resolve) {
17
+ const label = token.label ?? token.target;
18
+ const href = resolve?.(token.target);
19
+ const safe = href !== void 0 ? sanitizeUrl(href) : void 0;
20
+ if (safe === void 0) return label;
21
+ return createElement("a", { href: safe, "data-wikilink": token.target, key: nextKey() }, label);
22
+ }
23
+ function renderText(value, opts) {
24
+ const parts = splitWikiLinks(value);
25
+ if (!parts) return value;
26
+ return parts.map(
27
+ (p, i) => "text" in p ? createElement(Fragment, { key: `t${i}` }, p.text) : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink))
28
+ );
29
+ }
30
+ function renderChildren(node, opts) {
31
+ return (node.children ?? []).map((c, i) => renderNode(c, opts, i));
32
+ }
33
+ const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"];
34
+ function renderNode(node, opts, index = 0) {
35
+ const key = `n${index}`;
36
+ switch (node.type) {
37
+ case "root":
38
+ return createElement(Fragment, { key }, ...renderChildren(node, opts));
39
+ case "text":
40
+ return renderText(node.value ?? "", opts);
41
+ case "paragraph":
42
+ return createElement("p", { key }, ...renderChildren(node, opts));
43
+ case "heading": {
44
+ const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];
45
+ return createElement(tag, { key }, ...renderChildren(node, opts));
46
+ }
47
+ case "strong":
48
+ return createElement("strong", { key }, ...renderChildren(node, opts));
49
+ case "emphasis":
50
+ return createElement("em", { key }, ...renderChildren(node, opts));
51
+ case "delete":
52
+ return createElement("del", { key }, ...renderChildren(node, opts));
53
+ case "inlineCode":
54
+ return createElement("code", { key }, node.value ?? "");
55
+ case "code":
56
+ return createElement("pre", { key }, createElement("code", null, node.value ?? ""));
57
+ case "blockquote":
58
+ return createElement("blockquote", { key }, ...renderChildren(node, opts));
59
+ case "list":
60
+ return createElement(node.ordered ? "ol" : "ul", { key }, ...renderChildren(node, opts));
61
+ case "listItem":
62
+ return createElement("li", { key }, ...renderChildren(node, opts));
63
+ case "thematicBreak":
64
+ return createElement("hr", { key });
65
+ case "break":
66
+ return createElement("br", { key });
67
+ case "link": {
68
+ const href = sanitizeUrl(node.url);
69
+ if (href === void 0) return createElement(Fragment, { key }, ...renderChildren(node, opts));
70
+ return createElement("a", { key, href, title: node.title ?? void 0 }, ...renderChildren(node, opts));
71
+ }
72
+ case "image": {
73
+ const src = sanitizeUrl(node.url);
74
+ if (src === void 0) return node.alt ? createElement(Fragment, { key }, node.alt) : null;
75
+ return createElement("img", { key, src, alt: node.alt ?? "", title: node.title ?? void 0 });
76
+ }
77
+ // GFM tables.
78
+ case "table":
79
+ return createElement("table", { key }, createElement("tbody", null, ...renderChildren(node, opts)));
80
+ case "tableRow":
81
+ return createElement("tr", { key }, ...renderChildren(node, opts));
82
+ case "tableCell":
83
+ return createElement("td", { key }, ...renderChildren(node, opts));
84
+ // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No
85
+ // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.
86
+ case "html":
87
+ return createElement(Fragment, { key }, node.value ?? "");
88
+ // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.
89
+ case "mdxJsxFlowElement":
90
+ case "mdxJsxTextElement": {
91
+ const name = typeof node.name === "string" ? node.name : "";
92
+ const Component = name ? opts.components?.[name] : void 0;
93
+ const children = renderChildren(node, opts);
94
+ if (!Component) return createElement(Fragment, { key }, ...children);
95
+ return createElement(Component, { key, ...literalProps(node.attributes) }, ...children);
96
+ }
97
+ // Inert expression nodes (should not occur — expression extension is off — but be
98
+ // defensive if a tree from elsewhere carries them): render nothing.
99
+ case "mdxFlowExpression":
100
+ case "mdxTextExpression":
101
+ case "mdxjsEsm":
102
+ return null;
103
+ default:
104
+ return node.children ? createElement(Fragment, { key }, ...renderChildren(node, opts)) : null;
105
+ }
106
+ }
107
+ function renderMdast(tree, options = {}) {
108
+ keyCounter = 0;
109
+ return renderNode(tree, options);
110
+ }
111
+ export {
112
+ renderMdast
113
+ };
114
+ //# sourceMappingURL=renderMdast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/safeContent/renderMdast.tsx"],"sourcesContent":["import { createElement, Fragment, type ReactNode } from 'react';\nimport { sanitizeUrl } from './sanitizeUrl';\nimport { splitWikiLinks, type WikiLinkToken } from './wikilink';\nimport type { SafeMdastNode, SafeMdxAttribute } from './parseSafeMdast';\n\n// The mdast→React renderer for the safe content path (TRUST_MODES_SPEC §5.1). PURE\n// and synchronous — it only reads `node.type` off an already-parsed tree, so it\n// carries no ESM dep and is exhaustively unit-testable. Every security property lives\n// here:\n//\n// - **JSX tags resolve ONLY to a component registry, by name.** A `<Component/>`\n// node becomes `registry[name]` with **literal string props only**; an unknown tag\n// renders its children inert (a Fragment, no element) — so author-written `<div\n// onclick=…>`, `<img onerror=…>`, `<script>` never become an intrinsic element with\n// attacker attributes. (Block-level raw HTML arrives as an `html` node, below.)\n// - **Expression attributes are dropped.** `f={fetch(\"/x\")}` / `{...spread}` are\n// `mdxJsxExpressionAttribute` or object-valued `mdxJsxAttribute`s — never passed to\n// a component, never evaluated. (There is also no evaluator to reach — parse used\n// no acorn.)\n// - **Raw HTML is inert text.** `html` nodes render as their literal string via a\n// text node — never `dangerouslySetInnerHTML` (no `rehype-raw`).\n// - **URL-scheme sanitizer** on every `link`/`image` URL (`sanitizeUrl`).\n// - **Wikilinks resolve in-mount only** via an injected resolver; the renderer never\n// fetches.\n\nexport interface SafeContentComponents {\n /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).\n * Looked up by the JSX tag name; anything not here renders inert. */\n [tag: string]: React.ComponentType<Record<string, string>>;\n}\n\nexport interface RenderMdastOptions {\n /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */\n components?: SafeContentComponents;\n /**\n * Resolve a wikilink target to an href, **within the granted mount only** — a pure,\n * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.\n * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert\n * text). Absent ⇒ every wikilink renders as inert text.\n */\n resolveWikiLink?: (target: string) => string | undefined;\n}\n\n/** Extract the literal string props of a JSX element — `mdxJsxAttribute`s whose value\n * is a plain string. Expression attributes (object value) and spreads are DROPPED. */\nfunction literalProps(attributes: SafeMdxAttribute[] | undefined): Record<string, string> {\n const props: Record<string, string> = {};\n for (const attr of attributes ?? []) {\n if (attr.type !== 'mdxJsxAttribute') continue; // drop `{...spread}`\n if (typeof attr.name !== 'string') continue;\n // A literal attribute's value is a string (or null → boolean-ish `true`). An\n // expression value is an object (`mdxJsxAttributeValueExpression`) — DROP it: it\n // is an inert raw string, never a real value, and must never reach a component.\n if (typeof attr.value === 'string') props[attr.name] = attr.value;\n else if (attr.value === null || attr.value === undefined) props[attr.name] = '';\n // object-valued (expression) → skipped\n }\n return props;\n}\n\nlet keyCounter = 0;\nconst nextKey = () => `sc-${keyCounter++}`;\n\n/** Render a wikilink token via the in-mount resolver, or inert text when it can't\n * resolve (never a network call — resolution is the injected mount-scoped callback). */\nfunction renderWiki(token: WikiLinkToken, resolve: RenderMdastOptions['resolveWikiLink']): ReactNode {\n const label = token.label ?? token.target;\n const href = resolve?.(token.target);\n const safe = href !== undefined ? sanitizeUrl(href) : undefined;\n if (safe === undefined) return label; // inert text — unresolved or out-of-mount\n return createElement('a', { href: safe, 'data-wikilink': token.target, key: nextKey() }, label);\n}\n\n/** Render a `text` node, splitting any `[[…]]` wikilinks out of it. */\nfunction renderText(value: string, opts: RenderMdastOptions): ReactNode {\n const parts = splitWikiLinks(value);\n if (!parts) return value;\n return parts.map((p, i) =>\n 'text' in p\n ? createElement(Fragment, { key: `t${i}` }, p.text)\n : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink)),\n );\n}\n\nfunction renderChildren(node: SafeMdastNode, opts: RenderMdastOptions): ReactNode[] {\n return (node.children ?? []).map((c, i) => renderNode(c, opts, i));\n}\n\n// Standard mdast block/inline nodes → a FIXED, safe React element. We control every\n// attribute; author input only reaches text content and (sanitized) URLs.\nconst HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;\n\nfunction renderNode(node: SafeMdastNode, opts: RenderMdastOptions, index = 0): ReactNode {\n const key = `n${index}`;\n switch (node.type) {\n case 'root':\n return createElement(Fragment, { key }, ...renderChildren(node, opts));\n case 'text':\n return renderText(node.value ?? '', opts);\n case 'paragraph':\n return createElement('p', { key }, ...renderChildren(node, opts));\n case 'heading': {\n const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];\n return createElement(tag, { key }, ...renderChildren(node, opts));\n }\n case 'strong':\n return createElement('strong', { key }, ...renderChildren(node, opts));\n case 'emphasis':\n return createElement('em', { key }, ...renderChildren(node, opts));\n case 'delete':\n return createElement('del', { key }, ...renderChildren(node, opts));\n case 'inlineCode':\n return createElement('code', { key }, node.value ?? '');\n case 'code':\n return createElement('pre', { key }, createElement('code', null, node.value ?? ''));\n case 'blockquote':\n return createElement('blockquote', { key }, ...renderChildren(node, opts));\n case 'list':\n return createElement(node.ordered ? 'ol' : 'ul', { key }, ...renderChildren(node, opts));\n case 'listItem':\n return createElement('li', { key }, ...renderChildren(node, opts));\n case 'thematicBreak':\n return createElement('hr', { key });\n case 'break':\n return createElement('br', { key });\n case 'link': {\n const href = sanitizeUrl(node.url);\n // A rejected scheme → render the link TEXT only (inert), never an <a href>.\n if (href === undefined) return createElement(Fragment, { key }, ...renderChildren(node, opts));\n return createElement('a', { key, href, title: node.title ?? undefined }, ...renderChildren(node, opts));\n }\n case 'image': {\n const src = sanitizeUrl(node.url);\n if (src === undefined) return node.alt ? createElement(Fragment, { key }, node.alt) : null;\n return createElement('img', { key, src, alt: node.alt ?? '', title: node.title ?? undefined });\n }\n // GFM tables.\n case 'table':\n return createElement('table', { key }, createElement('tbody', null, ...renderChildren(node, opts)));\n case 'tableRow':\n return createElement('tr', { key }, ...renderChildren(node, opts));\n case 'tableCell':\n return createElement('td', { key }, ...renderChildren(node, opts));\n // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No\n // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.\n case 'html':\n return createElement(Fragment, { key }, node.value ?? '');\n // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.\n case 'mdxJsxFlowElement':\n case 'mdxJsxTextElement': {\n const name = typeof node.name === 'string' ? node.name : '';\n const Component = name ? opts.components?.[name] : undefined;\n const children = renderChildren(node, opts);\n // Unknown tag (not in the registry) OR a fragment `<>` → render children inert,\n // NO element, NO author attributes. This is what neutralizes `<script>`/`<div\n // onclick>`/`<img onerror>` written as JSX.\n if (!Component) return createElement(Fragment, { key }, ...children);\n return createElement(Component, { key, ...literalProps(node.attributes) }, ...children);\n }\n // Inert expression nodes (should not occur — expression extension is off — but be\n // defensive if a tree from elsewhere carries them): render nothing.\n case 'mdxFlowExpression':\n case 'mdxTextExpression':\n case 'mdxjsEsm':\n return null;\n default:\n // Unknown node → render its children (never its raw value as markup).\n return node.children ? createElement(Fragment, { key }, ...renderChildren(node, opts)) : null;\n }\n}\n\n/**\n * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1\n * security property (registry-only JSX, dropped expressions, inert raw HTML, URL\n * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.\n */\nexport function renderMdast(tree: SafeMdastNode, options: RenderMdastOptions = {}): ReactNode {\n keyCounter = 0;\n return renderNode(tree, options);\n}\n"],"mappings":"AAAA,SAAS,eAAe,gBAAgC;AACxD,SAAS,mBAAmB;AAC5B,SAAS,sBAA0C;AA2CnD,SAAS,aAAa,YAAoE;AACxF,QAAM,QAAgC,CAAC;AACvC,aAAW,QAAQ,cAAc,CAAC,GAAG;AACnC,QAAI,KAAK,SAAS,kBAAmB;AACrC,QAAI,OAAO,KAAK,SAAS,SAAU;AAInC,QAAI,OAAO,KAAK,UAAU,SAAU,OAAM,KAAK,IAAI,IAAI,KAAK;AAAA,aACnD,KAAK,UAAU,QAAQ,KAAK,UAAU,OAAW,OAAM,KAAK,IAAI,IAAI;AAAA,EAE/E;AACA,SAAO;AACT;AAEA,IAAI,aAAa;AACjB,MAAM,UAAU,MAAM,MAAM,YAAY;AAIxC,SAAS,WAAW,OAAsB,SAA2D;AACnG,QAAM,QAAQ,MAAM,SAAS,MAAM;AACnC,QAAM,OAAO,UAAU,MAAM,MAAM;AACnC,QAAM,OAAO,SAAS,SAAY,YAAY,IAAI,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ertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var sanitizeUrl_exports = {};
20
+ __export(sanitizeUrl_exports, {
21
+ sanitizeUrl: () => sanitizeUrl
22
+ });
23
+ module.exports = __toCommonJS(sanitizeUrl_exports);
24
+ const SCHEME = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;
25
+ const ALLOWED_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "mailto"]);
26
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F]/g;
27
+ function sanitizeUrl(url) {
28
+ if (typeof url !== "string") return void 0;
29
+ const cleaned = url.replace(CONTROL_CHARS, "").trim();
30
+ if (cleaned === "") return void 0;
31
+ const m = SCHEME.exec(cleaned);
32
+ if (!m) return cleaned;
33
+ return ALLOWED_SCHEMES.has(m[1].toLowerCase()) ? cleaned : void 0;
34
+ }
35
+ // Annotate the CommonJS export names for ESM import in node:
36
+ 0 && (module.exports = {
37
+ sanitizeUrl
38
+ });
39
+ //# sourceMappingURL=sanitizeUrl.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/safeContent/sanitizeUrl.ts"],"sourcesContent":["// URL-scheme sanitizer for the safe content renderer (TRUST_MODES_SPEC §5.1,\n// AGENT_AUTHORING §10). A §5.1 residual requirement: link/image URLs in untrusted\n// content are allowlisted to `http`/`https`/`mailto` and relative URLs; every other\n// scheme — `javascript:`, `data:`, `vbscript:`, `file:`, … — is rejected. We do NOT\n// rely on React to neutralize `javascript:` (it does not, on an `<a href>`), so this\n// is the single chokepoint every rendered `href`/`src` passes through.\n\n// A leading `scheme:` per RFC 3986 (`ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )`).\n// Anything before the first `:` that matches this is an absolute-URI scheme; if the\n// URL has no such prefix it is relative (path/query/fragment) and allowed.\nconst SCHEME = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;\nconst ALLOWED_SCHEMES = new Set(['http', 'https', 'mailto']);\n\n// ASCII control chars (0x00–0x1F, 0x7F) that browsers ignore INSIDE a scheme — the\n// `java\\tscript:` / `java\\nscript:` obfuscation — stripped anywhere before testing.\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS = /[\\u0000-\\u001F\\u007F]/g;\n\n/**\n * Return the URL if its scheme is allowed (or it is relative/anchor), else\n * `undefined`. Control chars are stripped first so an obfuscated scheme cannot slip\n * past. A protocol-relative `//host` URL is treated as relative-with-authority and\n * allowed (it inherits the page's https scheme).\n */\nexport function sanitizeUrl(url: unknown): string | undefined {\n if (typeof url !== 'string') return undefined;\n const cleaned = url.replace(CONTROL_CHARS, '').trim();\n if (cleaned === '') return undefined;\n const m = SCHEME.exec(cleaned);\n if (!m) return cleaned; // no scheme → relative / anchor / query — allowed\n return ALLOWED_SCHEMES.has(m[1].toLowerCase()) ? cleaned : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,MAAM,SAAS;AACf,MAAM,kBAAkB,oBAAI,IAAI,CAAC,QAAQ,SAAS,QAAQ,CAAC;AAK3D,MAAM,gBAAgB;AAQf,SAAS,YAAY,KAAkC;AAC5D,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,QAAQ,eAAe,EAAE,EAAE,KAAK;AACpD,MAAI,YAAY,GAAI,QAAO;AAC3B,QAAM,IAAI,OAAO,KAAK,OAAO;AAC7B,MAAI,CAAC,EAAG,QAAO;AACf,SAAO,gBAAgB,IAAI,EAAE,CAAC,EAAE,YAAY,CAAC,IAAI,UAAU;AAC7D;","names":[]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Return the URL if its scheme is allowed (or it is relative/anchor), else
3
+ * `undefined`. Control chars are stripped first so an obfuscated scheme cannot slip
4
+ * past. A protocol-relative `//host` URL is treated as relative-with-authority and
5
+ * allowed (it inherits the page's https scheme).
6
+ */
7
+ declare function sanitizeUrl(url: unknown): string | undefined;
8
+
9
+ export { sanitizeUrl };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Return the URL if its scheme is allowed (or it is relative/anchor), else
3
+ * `undefined`. Control chars are stripped first so an obfuscated scheme cannot slip
4
+ * past. A protocol-relative `//host` URL is treated as relative-with-authority and
5
+ * allowed (it inherits the page's https scheme).
6
+ */
7
+ declare function sanitizeUrl(url: unknown): string | undefined;
8
+
9
+ export { sanitizeUrl };
@@ -0,0 +1,15 @@
1
+ const SCHEME = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;
2
+ const ALLOWED_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "mailto"]);
3
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F]/g;
4
+ function sanitizeUrl(url) {
5
+ if (typeof url !== "string") return void 0;
6
+ const cleaned = url.replace(CONTROL_CHARS, "").trim();
7
+ if (cleaned === "") return void 0;
8
+ const m = SCHEME.exec(cleaned);
9
+ if (!m) return cleaned;
10
+ return ALLOWED_SCHEMES.has(m[1].toLowerCase()) ? cleaned : void 0;
11
+ }
12
+ export {
13
+ sanitizeUrl
14
+ };
15
+ //# sourceMappingURL=sanitizeUrl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/safeContent/sanitizeUrl.ts"],"sourcesContent":["// URL-scheme sanitizer for the safe content renderer (TRUST_MODES_SPEC §5.1,\n// AGENT_AUTHORING §10). A §5.1 residual requirement: link/image URLs in untrusted\n// content are allowlisted to `http`/`https`/`mailto` and relative URLs; every other\n// scheme — `javascript:`, `data:`, `vbscript:`, `file:`, … — is rejected. We do NOT\n// rely on React to neutralize `javascript:` (it does not, on an `<a href>`), so this\n// is the single chokepoint every rendered `href`/`src` passes through.\n\n// A leading `scheme:` per RFC 3986 (`ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )`).\n// Anything before the first `:` that matches this is an absolute-URI scheme; if the\n// URL has no such prefix it is relative (path/query/fragment) and allowed.\nconst SCHEME = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;\nconst ALLOWED_SCHEMES = new Set(['http', 'https', 'mailto']);\n\n// ASCII control chars (0x00–0x1F, 0x7F) that browsers ignore INSIDE a scheme — the\n// `java\\tscript:` / `java\\nscript:` obfuscation — stripped anywhere before testing.\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS = /[\\u0000-\\u001F\\u007F]/g;\n\n/**\n * Return the URL if its scheme is allowed (or it is relative/anchor), else\n * `undefined`. Control chars are stripped first so an obfuscated scheme cannot slip\n * past. A protocol-relative `//host` URL is treated as relative-with-authority and\n * allowed (it inherits the page's https scheme).\n */\nexport function sanitizeUrl(url: unknown): string | undefined {\n if (typeof url !== 'string') return undefined;\n const cleaned = url.replace(CONTROL_CHARS, '').trim();\n if (cleaned === '') return undefined;\n const m = SCHEME.exec(cleaned);\n if (!m) return cleaned; // no scheme → relative / anchor / query — allowed\n return ALLOWED_SCHEMES.has(m[1].toLowerCase()) ? cleaned : undefined;\n}\n"],"mappings":"AAUA,MAAM,SAAS;AACf,MAAM,kBAAkB,oBAAI,IAAI,CAAC,QAAQ,SAAS,QAAQ,CAAC;AAK3D,MAAM,gBAAgB;AAQf,SAAS,YAAY,KAAkC;AAC5D,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,UAAU,IAAI,QAAQ,eAAe,EAAE,EAAE,KAAK;AACpD,MAAI,YAAY,GAAI,QAAO;AAC3B,QAAM,IAAI,OAAO,KAAK,OAAO;AAC7B,MAAI,CAAC,EAAG,QAAO;AACf,SAAO,gBAAgB,IAAI,EAAE,CAAC,EAAE,YAAY,CAAC,IAAI,UAAU;AAC7D;","names":[]}