@johnhenry/wsh 0.50.0 → 0.52.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,130 @@
1
+ /**
2
+ * An MCP face for allow-listed object paths (#219): the host names, in `mcp: { tools: [...] }`, which paths of which roots become MCP tools; each gets a host-authored name,
3
+ * description and JSON Schema for its arguments. This module builds the tool definitions; `webmcpTools({ tools })` serves them on the `mcp` channel with the WebMCP bridge's own
4
+ * approval, bounds and untrusted label (so a tool that is not marked read-only asks the person at the page, exactly as a WebMCP tool does).
5
+ *
6
+ * What a tool is: a CALL of one named method (`call: 'window.app.cart.add'`), or a read-only GET of one named value (`get: 'window.document.title'`). Nothing is a tool by being
7
+ * allowed: a path is a tool only if it is written here, and only if the host's allow-list (the same one the objects client is held to) names it for that operation (checked when
8
+ * the host is created; and again on every call, because a call goes through the same checks as an objects call: the allow-list, the names that need listing, the key's
9
+ * `objects:ROOT:OP` capability and `authorize`). No handles, events or callbacks: an argument is plain data validated against the schema, a result is plain data or an error.
10
+ */
11
+
12
+ import { compileSchema } from './objects-schema.mjs';
13
+
14
+ /** The key of the host-only part of a tool definition (see `INTERNAL_TOOL` in `webmcp.mjs`; the same registered symbol, so this file need not import it). */
15
+ const INTERNAL_TOOL = Symbol.for('wsh.webmcp.internal');
16
+
17
+ const TOOL_NAME_RE = /^[A-Za-z0-9_.-]{1,128}$/;
18
+ const TOOL_FIELDS = new Set(['name', 'title', 'description', 'call', 'get', 'inputSchema', 'args', 'readOnly']);
19
+ const NEVER = new Set(['__proto__', 'prototype', 'constructor', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'eval', 'Function', 'import', 'execScript']);
20
+
21
+ export const MCP_TOOL_LIMITS = Object.freeze({
22
+ /** Tools one host may name. */
23
+ maxTools: 64,
24
+ /** Characters of a description. */
25
+ maxDescriptionChars: 2000,
26
+ /** Arguments of a call tool (positional). */
27
+ maxArgs: 16,
28
+ });
29
+
30
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
31
+
32
+ /**
33
+ * @param {object} options
34
+ * @param {unknown} options.mcp - the host's `mcp` option
35
+ * @param {string[]} options.rootNames
36
+ * @param {(kind: 'get' | 'call', root: string, segs: string[]) => void} options.allows - throws (an `ObjectsError`) unless the allow-list names the path for the operation
37
+ * @param {(request: { kind: 'get' | 'call', path: string[], args?: unknown[] }, ctx: object) => Promise<object>} options.invoke - one call through the server's checks
38
+ * @returns {object[]} tool definitions for `webmcpTools({ tools })`
39
+ */
40
+ export function buildMcpTools({ mcp, rootNames, allows, invoke }) {
41
+ if (mcp === undefined) return [];
42
+ if (!isObj(mcp)) throw new TypeError('exposeObjects: mcp must be { tools: [...] }');
43
+ for (const k of Object.keys(mcp)) if (k !== 'tools') throw new TypeError(`exposeObjects: mcp.${k} is not an option (mcp is { tools: [...] }: name each path that becomes a tool; nothing is a tool by being allowed)`);
44
+ if (!Array.isArray(mcp.tools)) throw new TypeError('exposeObjects: mcp.tools must be an array of { name, description, call | get, inputSchema, ... }');
45
+ if (mcp.tools.length > MCP_TOOL_LIMITS.maxTools) throw new TypeError(`exposeObjects: mcp.tools lists at most ${MCP_TOOL_LIMITS.maxTools} tools`);
46
+ const seen = new Set();
47
+ return mcp.tools.map((spec, index) => {
48
+ const label = isObj(spec) && typeof spec.name === 'string' ? `mcp tool "${spec.name.slice(0, 60)}"` : `mcp.tools[${index}]`;
49
+ const fail = (message) => new TypeError(`exposeObjects: ${label}: ${message}`);
50
+ if (!isObj(spec)) throw fail('must be an object');
51
+ for (const k of Object.keys(spec)) if (!TOOL_FIELDS.has(k)) throw fail(`"${k}" is not a field of a tool (${[...TOOL_FIELDS].join(', ')}); events, handles and callbacks have no MCP tool`);
52
+ if (typeof spec.name !== 'string' || !TOOL_NAME_RE.test(spec.name)) throw fail('name must be 1 to 128 characters of letters, digits, "_", "-" and "."');
53
+ if (seen.has(spec.name)) throw fail('is listed twice');
54
+ seen.add(spec.name);
55
+ if (typeof spec.description !== 'string' || spec.description.trim() === '' || spec.description.length > MCP_TOOL_LIMITS.maxDescriptionChars) throw fail(`needs a description of 1 to ${MCP_TOOL_LIMITS.maxDescriptionChars} characters (the far side reads it to decide when to call the tool)`);
56
+ if (spec.title !== undefined && (typeof spec.title !== 'string' || spec.title.length > 200)) throw fail('title must be a string of at most 200 characters');
57
+ const named = [['call', spec.call], ['get', spec.get]].filter(([, v]) => v !== undefined);
58
+ if (named.length !== 1) throw fail('names exactly one of call, get: the path it runs (a path is a tool only if it is written here)');
59
+ const [kind, text] = named[0];
60
+ if (typeof text !== 'string') throw fail(`${kind} must be the path as text`);
61
+ const segs = text.split('.');
62
+ for (const s of segs) {
63
+ if (s === '') throw fail(`${kind} ${JSON.stringify(text.slice(0, 80))} has an empty segment`);
64
+ if (/\*/.test(s)) throw fail(`${kind} must be a literal path, with no wildcard (${JSON.stringify(text.slice(0, 80))})`);
65
+ if (s.includes('(') || s.includes(')')) throw fail(`${kind} must be a literal member path, not one through a call result (${JSON.stringify(text.slice(0, 80))})`);
66
+ if (NEVER.has(s)) throw fail(`${kind} names "${s}", which is never reachable`);
67
+ }
68
+ if (!rootNames.includes(segs[0])) throw fail(`${kind} ${JSON.stringify(text.slice(0, 80))} starts at ${JSON.stringify(segs[0].slice(0, 40))}, which is not a root of this host`);
69
+ if (segs.length < 2) throw fail(`${kind} must name a member of a root, not the root itself`);
70
+ try { allows(kind, segs[0], segs); } catch (e) { throw fail(`${String(e?.message ?? e)} (a tool never widens the allow-list: list the path there, then name it here)`); }
71
+
72
+ if (spec.readOnly !== undefined && typeof spec.readOnly !== 'boolean') throw fail('readOnly must be true or false');
73
+ // Read-only only when the host says so, for a get as for a call: a getter can have effects, and the mark skips the person's approval.
74
+ const readOnly = spec.readOnly === true;
75
+ const schema = spec.inputSchema ?? { type: 'object', properties: {}, additionalProperties: false };
76
+ if (!isObj(schema) || (schema.type !== undefined && schema.type !== 'object')) throw fail('inputSchema must describe an object');
77
+ let compiled;
78
+ try { compiled = compileSchema({ type: 'object', ...schema }, { what: `${label} inputSchema` }); } catch (e) { throw new TypeError(`exposeObjects: ${e.message}`); }
79
+ const properties = isObj(schema.properties) ? Object.keys(schema.properties) : [];
80
+
81
+ let mapping;
82
+ if (kind === 'get') {
83
+ if (spec.args !== undefined) throw fail('args is for a call: a get takes no arguments');
84
+ mapping = null;
85
+ } else if (spec.args === undefined) mapping = properties.length ? 'object' : [];
86
+ else if (spec.args === 'object') mapping = 'object';
87
+ else if (Array.isArray(spec.args) && spec.args.length <= MCP_TOOL_LIMITS.maxArgs && new Set(spec.args).size === spec.args.length && spec.args.every((a) => typeof a === 'string')) {
88
+ for (const a of spec.args) if (!properties.includes(a)) throw fail(`args names "${a.slice(0, 40)}", which is not a property of inputSchema`);
89
+ mapping = spec.args.slice();
90
+ } else throw fail(`args must be 'object' (the input is the one argument) or a list of up to ${MCP_TOOL_LIMITS.maxArgs} property names (the arguments, in order)`);
91
+
92
+ const root = segs[0];
93
+ const op = kind;
94
+ const argsOf = (input) => {
95
+ if (mapping === 'object') return [input];
96
+ const list = mapping.map((name) => (Object.hasOwn(input, name) ? input[name] : undefined));
97
+ while (list.length && list[list.length - 1] === undefined) list.pop();
98
+ return list.map((v) => (v === undefined ? null : v));
99
+ };
100
+ const definition = {
101
+ name: spec.name,
102
+ ...(spec.title ? { title: spec.title } : {}),
103
+ description: spec.description,
104
+ inputSchema: JSON.parse(JSON.stringify({ type: 'object', ...schema })),
105
+ annotations: { readOnlyHint: readOnly },
106
+ [INTERNAL_TOOL]: {
107
+ caller: true,
108
+ // Before the person is asked and before the page runs anything.
109
+ validate: (input) => compiled.validate(input),
110
+ // Listed only to a key that may do this on this root: `mcp:TOOL` and `objects:ROOT:OP` are both needed.
111
+ available: ({ permits } = {}) => !permits || permits({ kind: 'objects', root, op }) === true,
112
+ },
113
+ async execute(input, { signal, who, permits } = {}) {
114
+ const problem = compiled.validate(input);
115
+ if (problem) throw new Error(`invalid arguments: ${problem}`);
116
+ const permit = permits ? (r, o) => permits({ kind: 'objects', root: r, op: o }) === true : undefined;
117
+ const out = await invoke({ kind, path: segs, args: kind === 'call' ? argsOf(input) : [] }, { who, permit, signal });
118
+ if (out && 'u' in out) {
119
+ if (out.u === 'undefined') return { content: [] };
120
+ throw new Error(`the ${kind} of ${text} returned something that is not plain data (${out.u}${out.type ? ` ${out.type}` : ''}): only plain values are carried`);
121
+ }
122
+ const value = out?.v;
123
+ const isPlainObject = value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Uint8Array);
124
+ const rendered = typeof value === 'string' ? value : value instanceof Uint8Array ? `[${value.byteLength} bytes]` : JSON.stringify(value);
125
+ return { content: [{ type: 'text', text: rendered ?? '' }], ...(isPlainObject ? { structuredContent: value } : {}) };
126
+ },
127
+ };
128
+ return definition;
129
+ });
130
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * A small, bounded subset of JSON Schema, for the arguments of an MCP tool made from an object path (#219). The host writes the schema; the far side's arguments are
3
+ * checked against it BEFORE anything runs (before the person at the page is asked, and before the page's function is called). The rule that keeps what is advertised
4
+ * equal to what is enforced: a schema that uses a keyword this validator does not enforce is refused when the host is configured (`compileSchema` throws), so a schema
5
+ * can never promise a check that is not made.
6
+ *
7
+ * Enforced: `type` (one name or a list), `enum`, `const`, `properties`, `required`, `additionalProperties` (a boolean or a schema), `items` (one schema), `minItems`,
8
+ * `maxItems`, `minLength`, `maxLength`, `minimum`, `maximum` and `anyOf`. Annotations that assert nothing are accepted and ignored: `description`, `title`, `default`,
9
+ * `examples`, `format`, `$comment`, `$schema`. Everything else (`$ref`, `pattern`, `oneOf`, `allOf`, `not`, `patternProperties`, `if`, ...) is refused: a regular
10
+ * expression of the host's would run against the far side's text, and a reference needs a resolver.
11
+ *
12
+ * What it checks of a VALUE, whatever the schema says: it is plain data (a JSON-shaped value: no function, no class instance), it nests no deeper than `maxDepth` and has
13
+ * no more than `maxNodes` nodes, and no object has a key that climbs to a prototype (`__proto__`, `constructor`, `prototype`, ...).
14
+ */
15
+
16
+ export const SCHEMA_LIMITS = Object.freeze({
17
+ /** Nesting of a schema, and of a value checked against one. */
18
+ maxDepth: 8,
19
+ /** Nodes of a schema, and nodes visited when a value is checked. */
20
+ maxNodes: 2000,
21
+ /** Properties one object schema lists. */
22
+ maxProperties: 64,
23
+ /** Members of an `enum`, entries of `required` and of `anyOf`. */
24
+ maxList: 64,
25
+ });
26
+
27
+ const TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null', 'object', 'array']);
28
+ const ANNOTATIONS = new Set(['description', 'title', 'default', 'examples', 'format', '$comment', '$schema']);
29
+ const ENFORCED = new Set(['type', 'enum', 'const', 'properties', 'required', 'additionalProperties', 'items', 'minItems', 'maxItems', 'minLength', 'maxLength', 'minimum', 'maximum', 'anyOf']);
30
+ const NEVER_KEYS = new Set(['__proto__', 'prototype', 'constructor', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__']);
31
+
32
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
33
+ const bad = (what, message) => new TypeError(`${what}: ${message}`);
34
+
35
+ const same = (a, b) => {
36
+ if (a === b) return true;
37
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
38
+ try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
39
+ };
40
+
41
+ /**
42
+ * Check a schema and return `{ validate(value) }`, which returns `null` when the value fits and a sentence when it does not (the first problem).
43
+ * @param {object} schema
44
+ * @param {{ what?: string }} [options] - what the schema is for, for the messages
45
+ */
46
+ export function compileSchema(schema, { what = 'inputSchema' } = {}) {
47
+ let nodes = 0;
48
+ const check = (s, depth, at) => {
49
+ if (!isObj(s)) throw bad(what, `${at} must be a schema object`);
50
+ if (depth > SCHEMA_LIMITS.maxDepth) throw bad(what, `${at} nests deeper than ${SCHEMA_LIMITS.maxDepth}`);
51
+ if (++nodes > SCHEMA_LIMITS.maxNodes) throw bad(what, `has more than ${SCHEMA_LIMITS.maxNodes} nodes`);
52
+ for (const k of Object.keys(s)) {
53
+ if (ENFORCED.has(k) || ANNOTATIONS.has(k)) continue;
54
+ throw bad(what, `${at}: the keyword "${k}" is not supported (it could not be enforced, so it would promise a check that is not made)`);
55
+ }
56
+ if (s.type !== undefined) {
57
+ const list = Array.isArray(s.type) ? s.type : [s.type];
58
+ if (list.length === 0 || list.length > TYPES.size || !list.every((t) => TYPES.has(t))) throw bad(what, `${at}.type must be one of ${[...TYPES].join(', ')} (or a list of them)`);
59
+ }
60
+ if (s.enum !== undefined && (!Array.isArray(s.enum) || s.enum.length === 0 || s.enum.length > SCHEMA_LIMITS.maxList)) throw bad(what, `${at}.enum must be a list of 1 to ${SCHEMA_LIMITS.maxList} values`);
61
+ if (s.required !== undefined && (!Array.isArray(s.required) || s.required.length > SCHEMA_LIMITS.maxList || !s.required.every((r) => typeof r === 'string' && !NEVER_KEYS.has(r)))) throw bad(what, `${at}.required must be a list of at most ${SCHEMA_LIMITS.maxList} property names`);
62
+ for (const k of ['minItems', 'maxItems', 'minLength', 'maxLength']) if (s[k] !== undefined && (!Number.isSafeInteger(s[k]) || s[k] < 0)) throw bad(what, `${at}.${k} must be a whole number of at least 0`);
63
+ for (const k of ['minimum', 'maximum']) if (s[k] !== undefined && (typeof s[k] !== 'number' || !Number.isFinite(s[k]))) throw bad(what, `${at}.${k} must be a number`);
64
+ if (s.properties !== undefined) {
65
+ if (!isObj(s.properties)) throw bad(what, `${at}.properties must be an object of schemas`);
66
+ const keys = Object.keys(s.properties);
67
+ if (keys.length > SCHEMA_LIMITS.maxProperties) throw bad(what, `${at}.properties lists more than ${SCHEMA_LIMITS.maxProperties} properties`);
68
+ for (const k of keys) {
69
+ if (NEVER_KEYS.has(k)) throw bad(what, `${at}.properties names "${k}", which is never accepted`);
70
+ check(s.properties[k], depth + 1, `${at}.properties.${k}`);
71
+ }
72
+ }
73
+ if (s.additionalProperties !== undefined && typeof s.additionalProperties !== 'boolean') check(s.additionalProperties, depth + 1, `${at}.additionalProperties`);
74
+ if (s.items !== undefined) check(s.items, depth + 1, `${at}.items`);
75
+ if (s.anyOf !== undefined) {
76
+ if (!Array.isArray(s.anyOf) || s.anyOf.length === 0 || s.anyOf.length > SCHEMA_LIMITS.maxList) throw bad(what, `${at}.anyOf must be a list of 1 to ${SCHEMA_LIMITS.maxList} schemas`);
77
+ s.anyOf.forEach((sub, i) => check(sub, depth + 1, `${at}.anyOf[${i}]`));
78
+ }
79
+ };
80
+ check(schema, 0, '');
81
+
82
+ const typeOk = (t, v) => {
83
+ switch (t) {
84
+ case 'string': return typeof v === 'string';
85
+ case 'number': return typeof v === 'number' && Number.isFinite(v);
86
+ case 'integer': return typeof v === 'number' && Number.isInteger(v);
87
+ case 'boolean': return typeof v === 'boolean';
88
+ case 'null': return v === null;
89
+ case 'object': return isObj(v);
90
+ case 'array': return Array.isArray(v);
91
+ default: return false;
92
+ }
93
+ };
94
+ const label = (at) => (at === '' ? 'the arguments' : `"${at}"`);
95
+
96
+ /** The first problem of `value` against `s`, or null. `budget.nodes` counts what is visited. */
97
+ const walk = (s, value, depth, at, budget) => {
98
+ if (++budget.nodes > SCHEMA_LIMITS.maxNodes) return `${label(at)}: the arguments are too large to check (more than ${SCHEMA_LIMITS.maxNodes} values)`;
99
+ if (depth > SCHEMA_LIMITS.maxDepth) return `${label(at)}: nested deeper than ${SCHEMA_LIMITS.maxDepth}`;
100
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') return `${label(at)} is not plain data`;
101
+ if (s.type !== undefined) {
102
+ const list = Array.isArray(s.type) ? s.type : [s.type];
103
+ if (!list.some((t) => typeOk(t, value))) return `${label(at)} must be ${list.join(' or ')}`;
104
+ }
105
+ if (s.enum !== undefined && !s.enum.some((e) => same(e, value))) return `${label(at)} must be one of ${JSON.stringify(s.enum).slice(0, 120)}`;
106
+ if (s.const !== undefined && !same(s.const, value)) return `${label(at)} must be ${JSON.stringify(s.const).slice(0, 80)}`;
107
+ if (typeof value === 'string') {
108
+ if (s.minLength !== undefined && [...value].length < s.minLength) return `${label(at)} must be at least ${s.minLength} characters`;
109
+ if (s.maxLength !== undefined && [...value].length > s.maxLength) return `${label(at)} must be at most ${s.maxLength} characters`;
110
+ }
111
+ if (typeof value === 'number') {
112
+ if (s.minimum !== undefined && value < s.minimum) return `${label(at)} must be at least ${s.minimum}`;
113
+ if (s.maximum !== undefined && value > s.maximum) return `${label(at)} must be at most ${s.maximum}`;
114
+ }
115
+ if (Array.isArray(value)) {
116
+ if (s.minItems !== undefined && value.length < s.minItems) return `${label(at)} must have at least ${s.minItems} items`;
117
+ if (s.maxItems !== undefined && value.length > s.maxItems) return `${label(at)} must have at most ${s.maxItems} items`;
118
+ for (let i = 0; i < value.length; i++) {
119
+ const p = s.items === undefined ? (value[i] !== null && typeof value[i] === 'object' ? walk({}, value[i], depth + 1, `${at}[${i}]`, budget) : null) : walk(s.items, value[i], depth + 1, `${at}[${i}]`, budget);
120
+ if (p) return p;
121
+ }
122
+ } else if (isObj(value)) {
123
+ const keys = Object.keys(value);
124
+ for (const k of keys) if (NEVER_KEYS.has(k)) return `${label(at)} has the key "${k}", which is never accepted`;
125
+ for (const r of s.required ?? []) if (!Object.hasOwn(value, r)) return `missing required argument "${at === '' ? r : `${at}.${r}`}"`;
126
+ for (const k of keys) {
127
+ const child = at === '' ? k : `${at}.${k}`;
128
+ const known = s.properties !== undefined && Object.hasOwn(s.properties, k);
129
+ if (known) { const p = walk(s.properties[k], value[k], depth + 1, child, budget); if (p) return p; continue; }
130
+ if (s.additionalProperties === false) return `${label(at)} has an argument that is not allowed: "${k}"`;
131
+ const p = walk(isObj(s.additionalProperties) ? s.additionalProperties : {}, value[k], depth + 1, child, budget);
132
+ if (p) return p;
133
+ }
134
+ }
135
+ if (s.anyOf !== undefined) {
136
+ // Every branch sees the same budget, so a hostile value cannot be walked once per branch past the bound.
137
+ if (!s.anyOf.some((sub) => walk(sub, value, depth, at, budget) === null)) return `${label(at)} matches none of the allowed forms`;
138
+ }
139
+ return null;
140
+ };
141
+
142
+ return { schema, validate: (value) => walk(schema, value, 0, '', { nodes: 0 }) };
143
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The text of a TypeScript type that a host supplies for a path (`exposeObjects({ types })`) and a client writes into a `.d.ts` file. It is HOST-AUTHORED text
3
+ * that travels to the far side, so the far side treats it as untrusted: it is never evaluated, only checked here and, if it passes, written out by an explicit
4
+ * call. The check is a small tokenizer, not a parser: it accepts a conservative subset of type syntax (identifiers, string and number literals, and the
5
+ * punctuation of object, tuple, function, union, intersection, generic, conditional and indexed types) and refuses everything that could change what the
6
+ * surrounding declaration means or reach outside it.
7
+ *
8
+ * What it refuses, and why:
9
+ * - any character outside printable ASCII on one line (no newline, so nothing can start a new declaration or a `///` directive);
10
+ * - `/`, `\`, a backtick, `@`, `#`, `%`, `^`, `~`, `!` and `*`: no comment, no escape sequence, no template literal, no decorator;
11
+ * - the words `import`, `export`, `require`, `declare`, `module`, `namespace`, `global`, `typeof`, `class`, `function`, `enum`, `interface`, `eval`: nothing
12
+ * that reads a file, a value or the global scope by name, or declares anything;
13
+ * - unbalanced or mismatched brackets, a `;` outside braces and a `,` outside any bracket: a text cannot close the declaration it sits in or add a member to it;
14
+ * - a text, a string literal, a nesting depth or a total that is over its bound.
15
+ *
16
+ * It does not make the text TRUE: a host can name a type that is wrong, and a type that is too wide or too narrow is a tooling problem, not a hole (a type
17
+ * is erased before anything runs). It makes the text safe to write into a declaration file.
18
+ */
19
+
20
+ export const TYPE_TEXT_LIMITS = Object.freeze({
21
+ /** Characters of one type text. */
22
+ maxTextChars: 1024,
23
+ /** Characters of one string literal inside a type text. */
24
+ maxStringChars: 200,
25
+ /** Nesting of brackets in one type text. */
26
+ maxNesting: 16,
27
+ /** Entries of a type map. */
28
+ maxEntries: 256,
29
+ /** Characters of all the type texts of one root together. */
30
+ maxTotalChars: 32 * 1024,
31
+ });
32
+
33
+ const FORBIDDEN_WORDS = new Set(['import', 'export', 'require', 'declare', 'module', 'namespace', 'global', 'typeof', 'class', 'function', 'enum', 'interface', 'eval']);
34
+ const PUNCTUATION = new Set(['{', '}', '[', ']', '(', ')', '<', '>', '|', '&', ':', ';', ',', '?', '=', '.', '-', '+']);
35
+ const OPEN = { '{': '}', '[': ']', '(': ')', '<': '>' };
36
+ const CLOSE = new Set(Object.values(OPEN));
37
+
38
+ /**
39
+ * Check one type text; returns it unchanged, or throws a `TypeError` that names the rule.
40
+ * @param {unknown} text
41
+ * @param {string} [what] - what the text is for, for the message
42
+ * @returns {string}
43
+ */
44
+ export function checkTypeText(text, what = 'a type text') {
45
+ const fail = (why) => new TypeError(`${what}: ${why}`);
46
+ if (typeof text !== 'string' || text.trim() === '') throw fail('must be a non-empty string');
47
+ if (text.length > TYPE_TEXT_LIMITS.maxTextChars) throw fail(`is over ${TYPE_TEXT_LIMITS.maxTextChars} characters`);
48
+ const stack = [];
49
+ let i = 0;
50
+ while (i < text.length) {
51
+ const c = text[i];
52
+ const code = text.charCodeAt(i);
53
+ if (code < 0x20 || code > 0x7e) throw fail('may hold printable ASCII on one line only');
54
+ if (c === ' ') { i++; continue; }
55
+ if (c === '"' || c === "'") {
56
+ const end = text.indexOf(c, i + 1);
57
+ if (end < 0) throw fail('has a string literal that does not end');
58
+ const body = text.slice(i + 1, end);
59
+ if (body.includes('\\')) throw fail('has a string literal with an escape sequence');
60
+ if (body.length > TYPE_TEXT_LIMITS.maxStringChars) throw fail(`has a string literal over ${TYPE_TEXT_LIMITS.maxStringChars} characters`);
61
+ i = end + 1;
62
+ continue;
63
+ }
64
+ if (/[A-Za-z_$]/.test(c)) {
65
+ let j = i + 1;
66
+ while (j < text.length && /[A-Za-z0-9_$]/.test(text[j])) j++;
67
+ const word = text.slice(i, j);
68
+ if (FORBIDDEN_WORDS.has(word)) throw fail(`may not use the word "${word}"`);
69
+ i = j;
70
+ continue;
71
+ }
72
+ if (/[0-9]/.test(c)) {
73
+ let j = i + 1;
74
+ while (j < text.length && /[0-9._]/.test(text[j])) j++;
75
+ i = j;
76
+ continue;
77
+ }
78
+ if (!PUNCTUATION.has(c)) throw fail(`may not contain "${c}"`);
79
+ // `=>` is an arrow, not a closing angle bracket.
80
+ if (c === '=' && text[i + 1] === '>') { i += 2; continue; }
81
+ if (c in OPEN) {
82
+ stack.push(OPEN[c]);
83
+ if (stack.length > TYPE_TEXT_LIMITS.maxNesting) throw fail(`nests deeper than ${TYPE_TEXT_LIMITS.maxNesting}`);
84
+ } else if (CLOSE.has(c)) {
85
+ if (stack.pop() !== c) throw fail(`has a "${c}" that closes nothing`);
86
+ } else if (c === ';') {
87
+ if (stack[stack.length - 1] !== '}') throw fail('has a ";" outside braces');
88
+ } else if (c === ',') {
89
+ if (stack.length === 0) throw fail('has a "," outside any bracket');
90
+ }
91
+ i++;
92
+ }
93
+ if (stack.length) throw fail('has a bracket that is not closed');
94
+ return text;
95
+ }
@@ -0,0 +1,38 @@
1
+ /** The operations of `wsh-objects` a key may hold on a root. */
2
+ export type ObjectsOp = 'get' | 'call' | 'set' | 'on';
3
+
4
+ /**
5
+ * What a host says one key may do on one root: its `types` answer (`rootDescription(page.window)` fetches it), or the allow-lists a host holds (paths qualified with the
6
+ * root, as in `allow`). `ops` is what the key's capabilities grant on this root (default: all four).
7
+ */
8
+ export interface RootDescription {
9
+ root: string;
10
+ ops?: ObjectsOp[];
11
+ allow: { get?: string[]; call?: string[]; set?: string[]; on?: string[] };
12
+ /** Extra event fields a subscriber may ask for, by event type (`'*'`: any type). */
13
+ eventFields?: Record<string, string[]>;
14
+ /**
15
+ * Host-authored TypeScript type texts, by literal path (`'window.app.cart.add'`; an event as `'window.app.bus@ready'`): `value` (the awaited value of a get),
16
+ * `args` (a tuple type) and `result` (the awaited value) of a call, `data` (what a listener receives) of an event. Checked by `checkTypeText`, bounded, and only
17
+ * for a path an entry allows. Untrusted text: copied into the file, never evaluated.
18
+ */
19
+ types?: Record<string, { value?: string; args?: string; result?: string; data?: string }>;
20
+ version?: number;
21
+ handles?: boolean;
22
+ }
23
+
24
+ /**
25
+ * The text of a `.d.ts` file for one root: only what the key may do, values `unknown` unless the host supplied a type, calls `(...args: unknown[]) => PromiseLike<unknown>`,
26
+ * wildcards untyped, events as typed `on` overloads. Pure: reads nothing, writes nothing, evaluates nothing; throws a `TypeError` on a description or type text it does not accept.
27
+ * @param options.name - the exported type's name (default: the root's name, capitalised, plus `Remote`: `WindowRemote`)
28
+ */
29
+ export function describeRootTypes(description: RootDescription, options?: { name?: string }): string;
30
+
31
+ /** Check the text of one type: returns it, or throws a `TypeError` naming the rule. A conservative subset of type syntax; see the README. */
32
+ export function checkTypeText(text: unknown, what?: string): string;
33
+
34
+ export const TYPE_TEXT_LIMITS: Readonly<{ maxTextChars: number; maxStringChars: number; maxNesting: number; maxEntries: number; maxTotalChars: number }>;
35
+ export const OBJECTS_TYPES_LIMITS: Readonly<{ maxEntries: number; maxEntryChars: number; maxNodes: number; maxEvents: number }>;
36
+
37
+ /** The part of a host's type map that a key holding `ops` may be told. */
38
+ export function narrowTypes(options: { root: string; ops: ObjectsOp[]; allow: RootDescription['allow']; types?: RootDescription['types'] }): NonNullable<RootDescription['types']>;