Bookmark this: tool.io/document/source-code
Tool.io Document Source Code
Browse the implementation files for Tool.io Document.tool.ts typescript
export type ToolDocumentBlock =
| { kind: 'paragraph'; text: string }
| {
kind: 'heading';
level: 1 | 2 | 3 | 4 | 5 | 6;
text: string;
}
| {
kind: 'table';
columns: { id: string; label: string }[];
rows: unknown[][];
}
| { kind: 'equation'; display: boolean; latex: string }
| { kind: 'code'; code: string; language: string }
| { kind: 'image'; alt: string; source: string }
| { kind: 'chart'; data: unknown; chartType: string };
export type ToolDocument = {
blocks: ToolDocumentBlock[];
kind: 'document';
version: 1;
};
const isRecord = (
value: unknown
): value is Record<string, unknown> =>
typeof value === 'object' &&
value !== null &&
!Array.isArray(value);
const isBlock = (
value: unknown
): value is ToolDocumentBlock => {
if (!isRecord(value) || typeof value.kind !== 'string')
return false;
switch (value.kind) {
case 'paragraph':
return typeof value.text === 'string';
case 'heading':
return (
typeof value.text === 'string' &&
Number.isSafeInteger(value.level) &&
Number(value.level) >= 1 &&
Number(value.level) <= 6
);
case 'table':
return (
Array.isArray(value.columns) &&
Array.isArray(value.rows)
);
case 'equation':
return (
typeof value.display === 'boolean' &&
typeof value.latex === 'string'
);
case 'code':
return (
typeof value.code === 'string' &&
typeof value.language === 'string'
);
case 'image':
return (
typeof value.alt === 'string' &&
typeof value.source === 'string'
);
case 'chart':
return (
typeof value.chartType === 'string' && 'data' in value
);
default:
return false;
}
};
export const isToolDocument = (
value: unknown
): value is ToolDocument =>
isRecord(value) &&
value.kind === 'document' &&
value.version === 1 &&
Array.isArray(value.blocks) &&
value.blocks.every(isBlock);
export const createToolDocument = (
blocks: ToolDocumentBlock[]
): ToolDocument => ({
blocks,
kind: 'document',
version: 1
});
export const normalizeDocument = (input: unknown): string => {
let value = input;
if (typeof input === 'string') {
try {
value = JSON.parse(input);
} catch {
return '';
}
}
return isToolDocument(value)
? JSON.stringify(value, null, 2)
: '';
};
export const Tool: TypeTool = {
name: 'Tool.io Document',
slug: 'document',
intro:
'Validate and normalize a versioned Tool.io document for export and tool chaining.',
tool: normalizeDocument,
i: [
{
example:
'{"blocks":[{"kind":"paragraph","text":"Hello"}],"kind":"document","version":1}',
label: 'Document',
placeholder: 'Enter document JSON',
render: 'textarea',
type: 'text'
}
],
o: [
{
example:
'{\n "blocks": [\n ...\n ],\n "kind": "document",\n "version": 1\n}',
label: 'Document',
placeholder: 'Validated document will appear here...',
render: 'textarea',
type: 'text'
}
]
};
export default Tool;
Description
Browse the implementation files for Tool.io Document.