@lightblues/jig 0.0.11 → 0.1.1
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/README.md +3 -1
- package/dist/canvas/bridge.d.ts +110 -0
- package/dist/canvas/bridge.js +255 -0
- package/dist/canvas/build.d.ts +25 -0
- package/dist/canvas/build.js +54 -0
- package/dist/canvas/compile.d.ts +29 -0
- package/dist/canvas/compile.js +218 -0
- package/dist/canvas/context.d.ts +43 -0
- package/dist/canvas/context.js +79 -0
- package/dist/canvas/document.d.ts +50 -0
- package/dist/canvas/document.js +128 -0
- package/dist/canvas/frame.d.ts +65 -0
- package/dist/canvas/frame.js +197 -0
- package/dist/canvas/names.d.ts +1 -0
- package/dist/canvas/names.js +6 -0
- package/dist/canvas/protocol.d.ts +93 -0
- package/dist/canvas/protocol.js +152 -0
- package/dist/canvas/runtime.d.ts +25 -0
- package/dist/canvas/runtime.js +110 -0
- package/dist/canvas/server.d.ts +5 -0
- package/dist/canvas/server.js +8 -0
- package/dist/canvas/state.d.ts +31 -0
- package/dist/canvas/state.js +72 -0
- package/dist/canvas/store.d.ts +39 -0
- package/dist/canvas/store.js +82 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/markdown/blocks.d.ts +123 -0
- package/dist/markdown/blocks.js +166 -0
- package/dist/markdown/index.d.ts +24 -0
- package/dist/markdown/index.js +182 -1
- package/dist/markdown/mermaid.d.ts +34 -0
- package/dist/markdown/mermaid.js +84 -0
- package/dist/markdown/react.d.ts +30 -0
- package/dist/markdown/react.js +57 -0
- package/package.json +55 -3
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/state`: React bindings of the canvas store: `CanvasStateProvider` and the hooks canvases and kit components call. The same
|
|
2
|
+
// hooks work in-page (tier A: the provider's callbacks go to the host) and in the frame (tier B: the runtime's
|
|
3
|
+
// provider holds a store bridged over postMessage). Cursor's names are kept: `useCanvasState`, `useCanvasAction`.
|
|
4
|
+
import { createContext, createElement, useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
|
5
|
+
import { CanvasStore } from "./store.js";
|
|
6
|
+
export { CanvasStore } from "./store.js";
|
|
7
|
+
export { LIMITS } from "./protocol.js";
|
|
8
|
+
const StoreContext = createContext(null);
|
|
9
|
+
/** One surface's state. Several providers on one page keep separate state. */
|
|
10
|
+
export function CanvasStateProvider(props) {
|
|
11
|
+
const { store: given, surface, initial, values, theme, children } = props;
|
|
12
|
+
const made = useRef(null);
|
|
13
|
+
if (!given && (!made.current || made.current.surface !== (surface ?? '')))
|
|
14
|
+
made.current = new CanvasStore({ surface, initial: values ?? initial, theme });
|
|
15
|
+
const store = given ?? made.current;
|
|
16
|
+
// The latest callbacks, without making a new store. A given store keeps its own (the frame runtime's bridge).
|
|
17
|
+
if (!given)
|
|
18
|
+
store.options = { ...store.options, onState: props.onState, onEvent: props.onEvent, onAction: props.onAction, onDrop: props.onDrop };
|
|
19
|
+
const first = useRef(true);
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
if (first.current)
|
|
22
|
+
return void (first.current = false);
|
|
23
|
+
if (values)
|
|
24
|
+
store.replace(values);
|
|
25
|
+
}, [store, values]);
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
if (theme)
|
|
28
|
+
store.setTheme(theme);
|
|
29
|
+
}, [store, theme]);
|
|
30
|
+
return createElement(StoreContext.Provider, { value: store }, children);
|
|
31
|
+
}
|
|
32
|
+
const noSubscribe = () => () => { };
|
|
33
|
+
/**
|
|
34
|
+
* `useState` whose value the host keeps per surface (and the agent can read). Outside a provider it is a plain
|
|
35
|
+
* `useState`. Values must be JSON; a write over a limit is dropped (`LIMITS`).
|
|
36
|
+
*/
|
|
37
|
+
export function useCanvasState(key, defaultValue) {
|
|
38
|
+
const store = useContext(StoreContext);
|
|
39
|
+
const fallback = useRef(defaultValue);
|
|
40
|
+
const [local, setLocal] = useState(defaultValue);
|
|
41
|
+
const read = () => store?.get(key);
|
|
42
|
+
const stored = useSyncExternalStore(store ? store.subscribe : noSubscribe, read, read);
|
|
43
|
+
const value = store ? (store.has(key) ? stored : fallback.current) : local;
|
|
44
|
+
const set = useCallback((action) => {
|
|
45
|
+
if (!store)
|
|
46
|
+
return setLocal(action);
|
|
47
|
+
const prev = (store.has(key) ? store.get(key) : fallback.current);
|
|
48
|
+
const next = typeof action === 'function' ? action(prev) : action;
|
|
49
|
+
store.set(key, next);
|
|
50
|
+
}, [store, key]);
|
|
51
|
+
return [value, set];
|
|
52
|
+
}
|
|
53
|
+
/** `(name, data) => void`: an append-only event the host stores and the agent reads (a guess, a result). */
|
|
54
|
+
export function useCanvasEvent() {
|
|
55
|
+
const store = useContext(StoreContext);
|
|
56
|
+
return useCallback((name, data = null) => void store?.event(name, data), [store]);
|
|
57
|
+
}
|
|
58
|
+
/** A stable `dispatch` for buttons. The host decides what each action does, and acts only during a click. */
|
|
59
|
+
export function useCanvasAction() {
|
|
60
|
+
const store = useContext(StoreContext);
|
|
61
|
+
return useCallback((action) => void store?.action(action), [store]);
|
|
62
|
+
}
|
|
63
|
+
/** The host's theme kind (`light` / `dark`); `light` outside a provider. */
|
|
64
|
+
export function useCanvasTheme() {
|
|
65
|
+
const store = useContext(StoreContext);
|
|
66
|
+
const read = () => store?.theme ?? 'light';
|
|
67
|
+
return useSyncExternalStore(store ? store.subscribe : noSubscribe, read, read);
|
|
68
|
+
}
|
|
69
|
+
/** The surface id of the nearest provider, `''` outside one. */
|
|
70
|
+
export function useCanvasSurface() {
|
|
71
|
+
return useContext(StoreContext)?.surface ?? '';
|
|
72
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type CanvasAction, type CanvasState, type ThemeKind } from './protocol.ts';
|
|
2
|
+
export interface CanvasStoreOptions {
|
|
3
|
+
/** The host's id for this surface (`"lemma:econ/fig-growth"`, `"artifact:<id>"`, `"msg:<id>/<n>"`). */
|
|
4
|
+
surface?: string;
|
|
5
|
+
/** Saved values. */
|
|
6
|
+
initial?: CanvasState;
|
|
7
|
+
theme?: ThemeKind;
|
|
8
|
+
/** A `useCanvasState` write: latest wins, the host debounces and stores it. */
|
|
9
|
+
onState?: (key: string, value: unknown) => void;
|
|
10
|
+
/** A `useCanvasEvent` call: append-only, sent at once. */
|
|
11
|
+
onEvent?: (name: string, data: unknown) => void;
|
|
12
|
+
/** A `useCanvasAction` dispatch: the host decides, during a click only. */
|
|
13
|
+
onAction?: (action: CanvasAction) => void;
|
|
14
|
+
/** A write, event or action dropped by the store's checks (the same limits as the frame bridge). */
|
|
15
|
+
onDrop?: (reason: string) => void;
|
|
16
|
+
}
|
|
17
|
+
export declare class CanvasStore {
|
|
18
|
+
readonly surface: string;
|
|
19
|
+
private values;
|
|
20
|
+
private kind;
|
|
21
|
+
private readonly listeners;
|
|
22
|
+
/** Callbacks; the provider swaps them for the latest props. */
|
|
23
|
+
options: CanvasStoreOptions;
|
|
24
|
+
constructor(options?: CanvasStoreOptions);
|
|
25
|
+
get snapshot(): CanvasState;
|
|
26
|
+
get theme(): ThemeKind;
|
|
27
|
+
has(key: string): boolean;
|
|
28
|
+
get(key: string): unknown;
|
|
29
|
+
/** A write from the page: kept, shown, and passed to `onState`. False when a limit drops it. */
|
|
30
|
+
set(key: string, value: unknown): boolean;
|
|
31
|
+
/** Values from the host (another device or the agent changed them): shown, not sent back. */
|
|
32
|
+
replace(values: CanvasState): void;
|
|
33
|
+
setTheme(kind: ThemeKind): void;
|
|
34
|
+
event(name: string, data?: unknown): boolean;
|
|
35
|
+
action(action: CanvasAction): boolean;
|
|
36
|
+
subscribe: (listener: () => void) => (() => void);
|
|
37
|
+
private notify;
|
|
38
|
+
private drop;
|
|
39
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The in-page state store behind the canvas hooks: one per surface. Pure (no React, no DOM): the React provider wraps
|
|
2
|
+
// it for tier A, and the frame runtime connects it to postMessage for tier B.
|
|
3
|
+
import { EVENT_NAME, isJson, jsonSize, LIMITS } from "./protocol.js";
|
|
4
|
+
export class CanvasStore {
|
|
5
|
+
surface;
|
|
6
|
+
values;
|
|
7
|
+
kind;
|
|
8
|
+
listeners = new Set();
|
|
9
|
+
/** Callbacks; the provider swaps them for the latest props. */
|
|
10
|
+
options;
|
|
11
|
+
constructor(options = {}) {
|
|
12
|
+
this.options = options;
|
|
13
|
+
this.surface = options.surface ?? '';
|
|
14
|
+
this.values = { ...(options.initial ?? {}) };
|
|
15
|
+
this.kind = options.theme ?? 'light';
|
|
16
|
+
}
|
|
17
|
+
get snapshot() {
|
|
18
|
+
return this.values;
|
|
19
|
+
}
|
|
20
|
+
get theme() {
|
|
21
|
+
return this.kind;
|
|
22
|
+
}
|
|
23
|
+
has(key) {
|
|
24
|
+
return Object.hasOwn(this.values, key);
|
|
25
|
+
}
|
|
26
|
+
get(key) {
|
|
27
|
+
return this.has(key) ? this.values[key] : undefined;
|
|
28
|
+
}
|
|
29
|
+
/** A write from the page: kept, shown, and passed to `onState`. False when a limit drops it. */
|
|
30
|
+
set(key, value) {
|
|
31
|
+
if (typeof key !== 'string' || !key || key.length > LIMITS.key)
|
|
32
|
+
return this.drop('state: bad key');
|
|
33
|
+
if (!isJson(value))
|
|
34
|
+
return this.drop(`state ${key}: not JSON`);
|
|
35
|
+
const next = { ...this.values, [key]: value };
|
|
36
|
+
if (jsonSize(next) > LIMITS.state)
|
|
37
|
+
return this.drop(`state ${key}: surface state over ${LIMITS.state} chars`);
|
|
38
|
+
if (this.has(key) && Object.is(this.values[key], value))
|
|
39
|
+
return true;
|
|
40
|
+
this.values = next;
|
|
41
|
+
this.notify();
|
|
42
|
+
this.options.onState?.(key, value);
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
/** Values from the host (another device or the agent changed them): shown, not sent back. */
|
|
46
|
+
replace(values) {
|
|
47
|
+
this.values = { ...values };
|
|
48
|
+
this.notify();
|
|
49
|
+
}
|
|
50
|
+
setTheme(kind) {
|
|
51
|
+
if (kind === this.kind)
|
|
52
|
+
return;
|
|
53
|
+
this.kind = kind;
|
|
54
|
+
this.notify();
|
|
55
|
+
}
|
|
56
|
+
event(name, data = null) {
|
|
57
|
+
if (typeof name !== 'string' || !EVENT_NAME.test(name))
|
|
58
|
+
return this.drop(`event: bad name`);
|
|
59
|
+
if (!isJson(data) || jsonSize(data) > LIMITS.eventData)
|
|
60
|
+
return this.drop(`event ${name}: data not JSON or over ${LIMITS.eventData} chars`);
|
|
61
|
+
this.options.onEvent?.(name, data);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
action(action) {
|
|
65
|
+
if (!action || typeof action !== 'object' || typeof action.type !== 'string' || !isJson(action) || jsonSize(action) > LIMITS.action)
|
|
66
|
+
return this.drop('action: not a JSON object with a type');
|
|
67
|
+
this.options.onAction?.(action);
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
subscribe = (listener) => {
|
|
71
|
+
this.listeners.add(listener);
|
|
72
|
+
return () => this.listeners.delete(listener);
|
|
73
|
+
};
|
|
74
|
+
notify() {
|
|
75
|
+
for (const listener of [...this.listeners])
|
|
76
|
+
listener();
|
|
77
|
+
}
|
|
78
|
+
drop(reason) {
|
|
79
|
+
this.options.onDrop?.(reason);
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const parts: readonly ["agent-paseo", "agent-pi", "agent-chat", "markdown"];
|
|
1
|
+
export declare const parts: readonly ["agent-paseo", "agent-pi", "agent-chat", "markdown", "canvas"];
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @lightblues/jig: reusable parts for my apps. Each part is its own subpath export; this root only names the parts.
|
|
2
|
-
export const parts = ['agent-paseo', 'agent-pi', 'agent-chat', 'markdown'];
|
|
2
|
+
export const parts = ['agent-paseo', 'agent-pi', 'agent-chat', 'markdown', 'canvas'];
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** What a block's `parse` returns. */
|
|
2
|
+
export type BlockResult<T = unknown> = {
|
|
3
|
+
ok: true;
|
|
4
|
+
value: T;
|
|
5
|
+
} | {
|
|
6
|
+
ok: false;
|
|
7
|
+
errors: string[];
|
|
8
|
+
};
|
|
9
|
+
/** The part of a Standard Schema (zod ≥ 3.24, valibot, arktype) `blocks` uses. https://standardschema.dev */
|
|
10
|
+
export type StandardSchemaLike<T = unknown> = {
|
|
11
|
+
readonly '~standard': {
|
|
12
|
+
readonly version: 1;
|
|
13
|
+
readonly validate: (value: unknown) => {
|
|
14
|
+
readonly value: T;
|
|
15
|
+
readonly issues?: undefined;
|
|
16
|
+
} | {
|
|
17
|
+
readonly issues: readonly {
|
|
18
|
+
readonly message: string;
|
|
19
|
+
readonly path?: readonly unknown[];
|
|
20
|
+
}[];
|
|
21
|
+
} | Promise<unknown>;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export type BlockSpec<T = unknown> = {
|
|
25
|
+
/** Validates the parsed body: a `{ok, value} | {ok: false, errors}` function, or a Standard Schema object. It should be strict (unknown fields are errors). */
|
|
26
|
+
parse: ((raw: unknown) => BlockResult<T>) | StandardSchemaLike<T>;
|
|
27
|
+
/**
|
|
28
|
+
* Body format. `yaml` (the default when `createMarkdown` has a `yaml` parser) also reads JSON; `json` without one;
|
|
29
|
+
* `text`: the body as a string, unparsed.
|
|
30
|
+
*/
|
|
31
|
+
format?: 'yaml' | 'json' | 'text';
|
|
32
|
+
/** Fields holding Markdown, as paths (`caption`, `steps[].note`, `a.b`): rendered after validation through the safe instance, the value becomes HTML. */
|
|
33
|
+
md?: string[];
|
|
34
|
+
/** The same, rendered inline (no `<p>`). */
|
|
35
|
+
mdInline?: string[];
|
|
36
|
+
/** Fields holding URLs, by path: checked with `urlAllowed(url, kind, links.allow)`; one refused URL makes the block invalid. */
|
|
37
|
+
urls?: Record<string, 'link' | 'image'>;
|
|
38
|
+
};
|
|
39
|
+
export type BlockLimits = {
|
|
40
|
+
/** Longest block body (characters). Default 20,000. */
|
|
41
|
+
maxBody?: number;
|
|
42
|
+
/** Blocks per document; later ones are invalid. Default 50 (a host may pass 10 for a chat answer). */
|
|
43
|
+
maxBlocks?: number;
|
|
44
|
+
/** Deepest nesting of objects and arrays in a parsed body. Default 20. */
|
|
45
|
+
maxDepth?: number;
|
|
46
|
+
/** Most values (objects, arrays, scalars) in a parsed body. Default 10,000. */
|
|
47
|
+
maxNodes?: number;
|
|
48
|
+
};
|
|
49
|
+
export declare const BLOCK_LIMITS: Required<BlockLimits>;
|
|
50
|
+
/** Aliases a YAML body may use (`yaml`'s `maxAliasCount`): a billion-laughs body stops at once. */
|
|
51
|
+
export declare const YAML_MAX_ALIASES = 50;
|
|
52
|
+
export declare const BLOCK_NAME: RegExp;
|
|
53
|
+
/** The part of the `yaml` package (`import * as YAML from 'yaml'`) used: `parseDocument(src, options)`. */
|
|
54
|
+
export type YamlLike = {
|
|
55
|
+
parseDocument(src: string, options?: Record<string, unknown>): {
|
|
56
|
+
errors: readonly {
|
|
57
|
+
message: string;
|
|
58
|
+
}[];
|
|
59
|
+
warnings: readonly {
|
|
60
|
+
message: string;
|
|
61
|
+
}[];
|
|
62
|
+
toJS(options?: Record<string, unknown>): unknown;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
/** A block that parsed and validated. `source` is its body as written: equal sources mean equal values. */
|
|
66
|
+
export type Block<T = unknown> = {
|
|
67
|
+
key: string;
|
|
68
|
+
name: string;
|
|
69
|
+
value: T;
|
|
70
|
+
source: string;
|
|
71
|
+
line: number;
|
|
72
|
+
};
|
|
73
|
+
/** A registered fence still open while streaming: a placeholder slot, no value yet. */
|
|
74
|
+
export type PendingBlock = {
|
|
75
|
+
key: string;
|
|
76
|
+
name: string;
|
|
77
|
+
line: number;
|
|
78
|
+
};
|
|
79
|
+
/** A registered fence that failed: it renders as its escaped source with the errors. */
|
|
80
|
+
export type BlockError = {
|
|
81
|
+
key: string;
|
|
82
|
+
name: string;
|
|
83
|
+
line: number;
|
|
84
|
+
errors: string[];
|
|
85
|
+
};
|
|
86
|
+
export type BlockEnv = {
|
|
87
|
+
blocks: Block[];
|
|
88
|
+
pending: PendingBlock[];
|
|
89
|
+
errors: BlockError[];
|
|
90
|
+
};
|
|
91
|
+
/** Runs a block's validator: a function or a Standard Schema. A throw or an async schema is an error. */
|
|
92
|
+
export declare function validate<T>(parse: BlockSpec<T>['parse'], raw: unknown): BlockResult<T>;
|
|
93
|
+
/** Depth, size and key checks on a parsed body (aliases already bounded by the parser). */
|
|
94
|
+
export declare function checkShape(v: unknown, limits: Required<BlockLimits>): string | null;
|
|
95
|
+
/** Parses a body by format. `yaml` with jig's safety options: core schema, unknown tags refused, aliases bounded, unique keys. */
|
|
96
|
+
export declare function parseBody(body: string, format: 'yaml' | 'json' | 'text', yaml?: YamlLike): BlockResult<unknown>;
|
|
97
|
+
/**
|
|
98
|
+
* Replaces each value at `path` (`a.b`, `list[].x`) with `f(value)`; returns an error string from `f`, or null.
|
|
99
|
+
* The value is copied along the path so the caller's object is not changed.
|
|
100
|
+
*/
|
|
101
|
+
export declare function mapPath(root: unknown, path: string, f: (v: unknown, at: string) => {
|
|
102
|
+
value: unknown;
|
|
103
|
+
} | string): {
|
|
104
|
+
value: unknown;
|
|
105
|
+
} | string;
|
|
106
|
+
/**
|
|
107
|
+
* A card as a block: ```` ```<name>\n<JSON>\n``` ````. JSON is also YAML, so a host that reads blocks as YAML reads it
|
|
108
|
+
* too. The fence is longer than any backtick run in the body. `name` must match `[a-z][a-z0-9-]*`.
|
|
109
|
+
*/
|
|
110
|
+
export declare function toBlock(name: string, value: unknown): string;
|
|
111
|
+
/**
|
|
112
|
+
* The first fenced block in `text` back as `{ name, value }` (the body read as JSON, or with `yaml` when given), or
|
|
113
|
+
* `null` when there is no closed fence. Validation is the caller's (`createMarkdown`'s `blocks`, or the card's schema).
|
|
114
|
+
*/
|
|
115
|
+
export declare function fromBlock(text: string, yaml?: YamlLike): {
|
|
116
|
+
name: string;
|
|
117
|
+
value: unknown;
|
|
118
|
+
} | null;
|
|
119
|
+
/** `ACTIVITY_SNAPSHOT` `card.<kind>` content → a block (`toBlock(kind, content)`). */
|
|
120
|
+
export declare function cardToBlock(card: {
|
|
121
|
+
activityType: string;
|
|
122
|
+
content: unknown;
|
|
123
|
+
}): string;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Fenced blocks with validated params (J008 tier A): ```name fences whose name the host registered become slots
|
|
2
|
+
// `<div data-jig-block="name" data-jig-key="name-0"></div>`; the parsed params come back beside the HTML, never in it.
|
|
3
|
+
// No imports: the YAML parser and the validators are the host's.
|
|
4
|
+
export const BLOCK_LIMITS = { maxBody: 20_000, maxBlocks: 50, maxDepth: 20, maxNodes: 10_000 };
|
|
5
|
+
/** Aliases a YAML body may use (`yaml`'s `maxAliasCount`): a billion-laughs body stops at once. */
|
|
6
|
+
export const YAML_MAX_ALIASES = 50;
|
|
7
|
+
export const BLOCK_NAME = /^[a-z][a-z0-9-]*$/;
|
|
8
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
9
|
+
function isStandard(p) {
|
|
10
|
+
return typeof p === 'object' && p !== null && '~standard' in p;
|
|
11
|
+
}
|
|
12
|
+
/** Runs a block's validator: a function or a Standard Schema. A throw or an async schema is an error. */
|
|
13
|
+
export function validate(parse, raw) {
|
|
14
|
+
try {
|
|
15
|
+
if (isStandard(parse)) {
|
|
16
|
+
const r = parse['~standard'].validate(raw);
|
|
17
|
+
if (r instanceof Promise) {
|
|
18
|
+
r.catch(() => { });
|
|
19
|
+
return { ok: false, errors: ['async schemas are not supported'] };
|
|
20
|
+
}
|
|
21
|
+
if (r.issues)
|
|
22
|
+
return { ok: false, errors: r.issues.map((i) => (i.path?.length ? `${i.path.map((p) => (typeof p === 'object' && p && 'key' in p ? String(p.key) : String(p))).join('.')}: ` : '') + i.message) };
|
|
23
|
+
return { ok: true, value: r.value };
|
|
24
|
+
}
|
|
25
|
+
const r = parse(raw);
|
|
26
|
+
if (r && r.ok === true)
|
|
27
|
+
return r;
|
|
28
|
+
if (r && r.ok === false)
|
|
29
|
+
return { ok: false, errors: r.errors?.length ? r.errors.map(String) : ['invalid'] };
|
|
30
|
+
return { ok: false, errors: ['parse returned neither {ok: true} nor {ok: false}'] };
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
return { ok: false, errors: [String(err?.message ?? err)] };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Depth, size and key checks on a parsed body (aliases already bounded by the parser). */
|
|
37
|
+
export function checkShape(v, limits) {
|
|
38
|
+
let nodes = 0;
|
|
39
|
+
const seen = new Set();
|
|
40
|
+
const walk = (x, depth) => {
|
|
41
|
+
if (++nodes > limits.maxNodes)
|
|
42
|
+
return `more than ${limits.maxNodes} values`;
|
|
43
|
+
if (typeof x !== 'object' || x === null)
|
|
44
|
+
return null;
|
|
45
|
+
if (depth >= limits.maxDepth)
|
|
46
|
+
return `nested deeper than ${limits.maxDepth}`;
|
|
47
|
+
if (seen.has(x))
|
|
48
|
+
return 'repeated (aliased) values are not allowed'; // a tree: one object in one place
|
|
49
|
+
seen.add(x);
|
|
50
|
+
if (Array.isArray(x)) {
|
|
51
|
+
for (const y of x) {
|
|
52
|
+
const e = walk(y, depth + 1);
|
|
53
|
+
if (e)
|
|
54
|
+
return e;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const proto = Object.getPrototypeOf(x);
|
|
59
|
+
if (proto !== Object.prototype && proto !== null)
|
|
60
|
+
return 'only plain objects, arrays and scalars';
|
|
61
|
+
for (const k of Object.keys(x)) {
|
|
62
|
+
if (FORBIDDEN_KEYS.has(k))
|
|
63
|
+
return `key "${k}" is not allowed`;
|
|
64
|
+
const e = walk(x[k], depth + 1);
|
|
65
|
+
if (e)
|
|
66
|
+
return e;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
};
|
|
71
|
+
return walk(v, 0);
|
|
72
|
+
}
|
|
73
|
+
/** Parses a body by format. `yaml` with jig's safety options: core schema, unknown tags refused, aliases bounded, unique keys. */
|
|
74
|
+
export function parseBody(body, format, yaml) {
|
|
75
|
+
if (format === 'text')
|
|
76
|
+
return { ok: true, value: body };
|
|
77
|
+
try {
|
|
78
|
+
if (format === 'json')
|
|
79
|
+
return { ok: true, value: JSON.parse(body) };
|
|
80
|
+
const doc = yaml.parseDocument(body, { schema: 'core', customTags: [], uniqueKeys: true, merge: false, prettyErrors: false, strict: true, logLevel: 'silent' });
|
|
81
|
+
// A warning is an unknown tag (`!custom`, `!!js/function`): refused, not read as a string.
|
|
82
|
+
const bad = doc.errors[0] ?? doc.warnings[0];
|
|
83
|
+
if (bad)
|
|
84
|
+
throw new Error(bad.message);
|
|
85
|
+
return { ok: true, value: doc.toJS({ maxAliasCount: YAML_MAX_ALIASES }) };
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
return { ok: false, errors: [`${format === 'json' ? 'JSON' : 'YAML'}: ${String(err?.message ?? err).split('\n')[0]}`] };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const parsePath = (p) => p.split('.').map((s) => (s.endsWith('[]') ? { key: s.slice(0, -2), each: true } : { key: s, each: false }));
|
|
92
|
+
/**
|
|
93
|
+
* Replaces each value at `path` (`a.b`, `list[].x`) with `f(value)`; returns an error string from `f`, or null.
|
|
94
|
+
* The value is copied along the path so the caller's object is not changed.
|
|
95
|
+
*/
|
|
96
|
+
export function mapPath(root, path, f) {
|
|
97
|
+
const steps = parsePath(path);
|
|
98
|
+
const go = (v, i, at) => {
|
|
99
|
+
if (i === steps.length)
|
|
100
|
+
return f(v, at);
|
|
101
|
+
if (typeof v !== 'object' || v === null || Array.isArray(v))
|
|
102
|
+
return { value: v };
|
|
103
|
+
const { key, each } = steps[i];
|
|
104
|
+
if (!Object.hasOwn(v, key))
|
|
105
|
+
return { value: v };
|
|
106
|
+
const child = v[key];
|
|
107
|
+
const here = at ? `${at}.${key}` : key;
|
|
108
|
+
let next;
|
|
109
|
+
if (each) {
|
|
110
|
+
if (child === undefined || child === null)
|
|
111
|
+
return { value: v };
|
|
112
|
+
if (!Array.isArray(child))
|
|
113
|
+
return `${here}: expected a list`;
|
|
114
|
+
const out = [];
|
|
115
|
+
for (let j = 0; j < child.length; j++) {
|
|
116
|
+
const r = go(child[j], i + 1, `${here}[${j}]`);
|
|
117
|
+
if (typeof r === 'string')
|
|
118
|
+
return r;
|
|
119
|
+
out.push(r.value);
|
|
120
|
+
}
|
|
121
|
+
next = out;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
const r = go(child, i + 1, here);
|
|
125
|
+
if (typeof r === 'string')
|
|
126
|
+
return r;
|
|
127
|
+
next = r.value;
|
|
128
|
+
}
|
|
129
|
+
return { value: { ...v, [key]: next } };
|
|
130
|
+
};
|
|
131
|
+
return go(root, 0, '');
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* A card as a block: ```` ```<name>\n<JSON>\n``` ````. JSON is also YAML, so a host that reads blocks as YAML reads it
|
|
135
|
+
* too. The fence is longer than any backtick run in the body. `name` must match `[a-z][a-z0-9-]*`.
|
|
136
|
+
*/
|
|
137
|
+
export function toBlock(name, value) {
|
|
138
|
+
if (!BLOCK_NAME.test(name))
|
|
139
|
+
throw new Error(`block name must match ${BLOCK_NAME}: ${JSON.stringify(name)}`);
|
|
140
|
+
const body = JSON.stringify(value, null, 2);
|
|
141
|
+
if (body === undefined)
|
|
142
|
+
throw new Error('toBlock: value is not JSON');
|
|
143
|
+
const longest = Math.max(0, ...[...body.matchAll(/`+/g)].map((m) => m[0].length));
|
|
144
|
+
const fence = '`'.repeat(Math.max(3, longest + 1));
|
|
145
|
+
return `${fence}${name}\n${body}\n${fence}\n`;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* The first fenced block in `text` back as `{ name, value }` (the body read as JSON, or with `yaml` when given), or
|
|
149
|
+
* `null` when there is no closed fence. Validation is the caller's (`createMarkdown`'s `blocks`, or the card's schema).
|
|
150
|
+
*/
|
|
151
|
+
export function fromBlock(text, yaml) {
|
|
152
|
+
const m = /^ {0,3}(`{3,}|~{3,})[ \t]*([a-z][a-z0-9-]*)[^\n]*\n([\s\S]*?)\n? {0,3}\1[ \t]*$/m.exec(text);
|
|
153
|
+
if (!m)
|
|
154
|
+
return null;
|
|
155
|
+
const r = parseBody(m[3], yaml ? 'yaml' : 'json', yaml);
|
|
156
|
+
if (!r.ok)
|
|
157
|
+
throw new Error(r.errors.join('; '));
|
|
158
|
+
return { name: m[2], value: r.value };
|
|
159
|
+
}
|
|
160
|
+
/** `ACTIVITY_SNAPSHOT` `card.<kind>` content → a block (`toBlock(kind, content)`). */
|
|
161
|
+
export function cardToBlock(card) {
|
|
162
|
+
const m = /^card\.(.+)$/.exec(card.activityType);
|
|
163
|
+
if (!m)
|
|
164
|
+
throw new Error(`not a card activity: ${card.activityType}`);
|
|
165
|
+
return toBlock(m[1], card.content);
|
|
166
|
+
}
|
package/dist/markdown/index.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import MarkdownIt from 'markdown-it';
|
|
2
2
|
import { closeOpenMarkdown, type CloseOpenMarkdownOptions } from './close.ts';
|
|
3
|
+
import { type BlockEnv, type BlockLimits, type BlockSpec, type YamlLike } from './blocks.ts';
|
|
3
4
|
export { closeOpenMarkdown, type CloseOpenMarkdownOptions };
|
|
5
|
+
export { BLOCK_LIMITS, BLOCK_NAME, YAML_MAX_ALIASES, cardToBlock, fromBlock, toBlock, type Block, type BlockError, type BlockLimits, type BlockResult, type BlockSpec, type PendingBlock, type StandardSchemaLike, type YamlLike, } from './blocks.ts';
|
|
6
|
+
export { drawMermaid, MERMAID_CONFIG, type MermaidLike, type DrawMermaidOptions } from './mermaid.ts';
|
|
4
7
|
type Md = InstanceType<typeof MarkdownIt>;
|
|
5
8
|
/** The part of the `katex` module texmath uses. */
|
|
6
9
|
export type KatexLike = {
|
|
@@ -83,13 +86,34 @@ export type MarkdownOptions = {
|
|
|
83
86
|
plugins?: (Plugin | [Plugin, ...unknown[]])[];
|
|
84
87
|
/** Passed to `closeOpenMarkdown` as `strip` when rendering with `streaming: true` (a half-written host marker). */
|
|
85
88
|
streamingStrip?: RegExp;
|
|
89
|
+
/**
|
|
90
|
+
* Fenced blocks: a fence ```` ```name ```` whose name (`[a-z][a-z0-9-]*`, the first word of the info string) is
|
|
91
|
+
* registered renders as an empty slot `<div data-jig-block="name" data-jig-key="name-0"></div>`; its validated params
|
|
92
|
+
* come back from `renderDocument` beside the HTML. An invalid one renders as its escaped source with the errors.
|
|
93
|
+
*/
|
|
94
|
+
blocks?: Record<string, BlockSpec<any>>;
|
|
95
|
+
/** The `yaml` package (`import * as YAML from 'yaml'`), for YAML block bodies. Without it, bodies are JSON. */
|
|
96
|
+
yaml?: YamlLike;
|
|
97
|
+
/** Limits on blocks (body size, count, depth, values); the host may tighten them. */
|
|
98
|
+
blockLimits?: BlockLimits;
|
|
99
|
+
/**
|
|
100
|
+
* ```` ```mermaid ```` fences become `mermaid` blocks (value `{ source }`) whose slot holds the escaped source until
|
|
101
|
+
* the host draws it (`drawMermaid`). Off by default.
|
|
102
|
+
*/
|
|
103
|
+
mermaid?: boolean;
|
|
86
104
|
};
|
|
87
105
|
export type RenderOptions = {
|
|
88
106
|
/** The text is a partial answer: close what it left open first (`closeOpenMarkdown`). */
|
|
89
107
|
streaming?: boolean;
|
|
90
108
|
};
|
|
109
|
+
/** `renderDocument`'s result: the HTML with its slots, and what goes in them. */
|
|
110
|
+
export type MarkdownDocument = BlockEnv & {
|
|
111
|
+
html: string;
|
|
112
|
+
};
|
|
91
113
|
export type Markdown = {
|
|
92
114
|
render(text: string, opts?: RenderOptions): string;
|
|
115
|
+
/** `render`, plus the blocks: `{ html, blocks: [{key, name, value, source, line}], pending, errors }`. */
|
|
116
|
+
renderDocument(text: string, opts?: RenderOptions): MarkdownDocument;
|
|
93
117
|
/** The markdown-it instance, for `md.use(...)` and render rules; the same rules as `plugins` apply. */
|
|
94
118
|
md: Md;
|
|
95
119
|
};
|