### Runnable Quickstart Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/python-sdk.md A quickstart example demonstrating basic workbook creation, cell manipulation, calculation, and value retrieval. Replace 'python' with the virtual environment's Python executable if built from source. ```python import mog wb = mog.create_workbook() try: ws = wb.active_sheet ws.set_cell("A1", 42) ws.set_cell("A2", "=A1*2") wb.calculate() print(ws.get_value("A2")) finally: wb.dispose() ``` -------------------------------- ### Install and Setup Mog CLI Source: https://github.com/fundamental-research-labs/mog/blob/main/cli/README.md Installs the Mog CLI using npm and adds it to the system's PATH for easy access. This is a prerequisite for using Mog commands. ```bash npm install --prefix "$HOME/.mog/npm" @mog-sdk/cli export PATH="$HOME/.mog/npm/node_modules/.bin:$PATH" mog --help ``` -------------------------------- ### Mog SDK Quickstart Installation and Usage Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/sdk.md This snippet demonstrates how to set up a new Node.js project, install the Mog SDK, and create a basic workbook to set and retrieve cell values. It includes setting a cell with a number, another with a formula, and then logging the result of the formula. The workbook is disposed of in a finally block. ```bash mkdir mog-sdk cd mog-sdk npm init -y npm pkg set type=module npm install @mog-sdk/sdk cat > index.mjs <<'JS' import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook({ userTimezone: 'UTC' }); try { const ws = wb.activeSheet; await ws.setCell('A1', 42); await ws.setCell('A2', '=A1*2'); console.log(await ws.getValue('A2')); } finally { wb.dispose(); } JS node index.mjs ``` -------------------------------- ### Quickstart: Create and Interact with a Workbook Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/README.md This snippet demonstrates how to set up a new project, install the Mog SDK, create a workbook, set cell values, and retrieve a calculated value. It requires Node.js 18 or newer. ```bash mkdir mog-quickstart cd mog-quickstart npm init -y npm pkg set type=module npm install @mog-sdk/sdk cat > index.mjs <<'JS' import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook(); try { const ws = wb.activeSheet; await ws.setCell('A1', 42); await ws.setCell('A2', '=A1*2'); console.log(await ws.getValue('A2')); } finally { wb.dispose(); } JS node index.mjs ``` ```text 84 ``` -------------------------------- ### Quick Start: Building and Analyzing a Dependency Graph Source: https://github.com/fundamental-research-labs/mog/blob/main/compute/core/crates/compute-graph/README.md Demonstrates basic usage of DependencyGraph, including setting precedents, triggering recalculations, and detecting cycles. Requires basic setup of CellId and DepTarget. ```rust use compute_graph::{DependencyGraph, DepTarget}; use compute_graph::positions::CellPosition; use cell_types::{CellId, SheetId, RangePos}; let mut graph = DependencyGraph::new(); let a1 = CellId::from_raw(1); let b1 = CellId::from_raw(2); let c1 = CellId::from_raw(3); // B1 depends on A1; C1 depends on B1 graph.set_precedents(&b1, vec![DepTarget::Cell(a1)]); graph.set_precedents(&c1, vec![DepTarget::Cell(b1)]); // When A1 changes, find affected cells (with position-aware analysis) let null_resolver = |_: &CellId| -> Option { None }; let affected = graph.affected_cells(&[a1], &null_resolver).into_value(); assert!(affected.contains(&a1)); assert!(affected.contains(&b1)); assert!(affected.contains(&c1)); // Cycle detection (also position-aware) assert!(graph.detect_cycles(&null_resolver).into_value().is_empty()); ``` -------------------------------- ### Basic SDK Usage Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/architecture-overview.md Demonstrates the fundamental usage of the Mog SDK, including creating a workbook, setting cell values, and retrieving cell values. Ensure the '@mog-sdk/sdk' package is installed. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook(); const ws = wb.activeSheet; await ws.setCell('A1', 42); await ws.setCell('A2', '=A1*2'); console.log(await ws.getValue('A2')); // 84 wb.dispose(); ``` -------------------------------- ### Public SDK Usage Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/architecture/api-layer.md Demonstrates basic usage of the public SDK, including creating a workbook, setting cell values, and retrieving cell values. Ensure the SDK is installed and imported correctly. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook({ userTimezone: 'UTC' }); const ws = wb.activeSheet; await ws.setCell('A1', 42); await ws.setCell(1, 0, '=A1*2'); // A2 by zero-based row/column console.log(await ws.getValue('A2')); // 84 wb.dispose(); ``` -------------------------------- ### Install mog-sdk Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/python-sdk.md Install the mog-sdk package using pip when a published wheel is available for your platform. ```bash pip install mog-sdk ``` -------------------------------- ### Run Compute Graph Example Source: https://github.com/fundamental-research-labs/mog/blob/main/compute/core/crates/compute-graph/README.md Execute the spreadsheet recalculation example for the compute-graph crate. This demonstrates a practical use case. ```bash cargo run -p compute-graph --example spreadsheet_recalc ``` -------------------------------- ### Start Development Server (Repo Root) Source: https://github.com/fundamental-research-labs/mog/blob/main/dev/app/README.md Run this command from the public repository root to start the Vite development server for the Mog spreadsheet app. ```bash pnpm dev ``` -------------------------------- ### Usage Example for @mog/culture Source: https://github.com/fundamental-research-labs/mog/blob/main/infra/culture/README.md Demonstrates how to import and use functions for getting culture information, normalizing numbers, and detecting currency. ```typescript import { getCulture, normalizeNumber, detectCurrency } from '@mog/culture'; const culture = getCulture('de-DE'); normalizeNumber('1.234,56', culture); // '1234.56' detectCurrency('$1,234.56'); // { symbol: '$', code: 'USD', ... } ``` -------------------------------- ### Install Vite React App and Mog Spreadsheet App Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/spreadsheet-app-embed.md Install a new Vite React app, navigate to its directory, install dependencies, and then install the Mog spreadsheet app package. ```bash npm create vite@latest mog-spreadsheet-app -- --template react-ts cd mog-spreadsheet-app npm install npm install @mog-sdk/spreadsheet-app ``` -------------------------------- ### Start Visual Testing Server Source: https://github.com/fundamental-research-labs/mog/blob/main/canvas/drawing/README.md Launch the visual testing development server for the canvas-lab package. Navigate to the lab directory and run 'pnpm dev' to start the server. ```bash cd canvas/drawing/lab && pnpm dev ``` -------------------------------- ### Install Mog SDK Source: https://github.com/fundamental-research-labs/mog/blob/main/README.md Install the Mog SDK for headless workbook automation in Node.js. Use this command in your project's terminal. ```bash pnpm add @mog-sdk/sdk ``` -------------------------------- ### Install Mog CLI Source: https://github.com/fundamental-research-labs/mog/blob/main/cli/skill/SKILL.md Install the `mog` CLI using npm with a user-local prefix and update the PATH environment variable. ```bash mkdir -p "$HOME/.mog/npm" npm install --prefix "$HOME/.mog/npm" @mog-sdk/cli export PATH="$HOME/.mog/npm/node_modules/.bin:$PATH" mog --help ``` -------------------------------- ### Create and Manipulate Workbook Source: https://github.com/fundamental-research-labs/mog/blob/main/README.md Example of creating a workbook, setting cell values, and retrieving cell values using the Mog SDK in TypeScript. Ensure the SDK is installed. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook(); const ws = wb.activeSheet; await ws.setCell('A1', 42); await ws.setCell('A2', '=A1*2'); console.log(await ws.getCell('A2')); await wb.dispose(); ``` -------------------------------- ### Install Mog Monorepo Dependencies Source: https://github.com/fundamental-research-labs/mog/blob/main/README.md Install all dependencies for the Mog monorepo. This command is typically used when setting up the development environment. ```bash pnpm install --frozen-lockfile ``` -------------------------------- ### Timeline Component Usage Example Source: https://github.com/fundamental-research-labs/mog/blob/main/ui/src/data-views/timeline/README.md Demonstrates how to import and use the Timeline component with sample data, groups, state, handlers, and configuration. Includes examples for bar clicks, double-clicks, drag/resize operations, and group toggling. ```tsx import { Timeline, TimelineState, TimelineBar } from '@mog/ui/data-views/timeline'; // Define your bars const bars: TimelineBar[] = [ { id: 'task-1', title: 'Design Phase', startDate: new Date('2024-01-01'), endDate: new Date('2024-01-15'), color: '#4A90D9', groupId: 'project-a' }, { id: 'task-2', title: 'Development', startDate: new Date('2024-01-16'), endDate: new Date('2024-02-15'), color: '#67B26F', groupId: 'project-a' }, { id: 'milestone-1', title: 'Launch', startDate: new Date('2024-02-20'), endDate: new Date('2024-02-20'), color: '#FF6B6B', isMilestone: true } ]; // Define groups (optional) const groups = [ { id: 'project-a', label: 'Project A', bars: [] } ]; // Define state const [state, setState] = useState({ selection: { selectedBarIds: new Set(), focusedBarId: null }, viewport: { scrollLeft: 0, scrollTop: 0, scale: 'day', viewportStart: new Date('2024-01-01'), viewportEnd: new Date('2024-03-01') }, dragState: null, collapsedGroups: new Set() }); // Render timeline { console.log('Bar clicked:', barId); setState((prev) => ({ ...prev, selection: { ...prev.selection, selectedBarIds: new Set([barId]) } })); }, onBarDoubleClick: (barId) => { console.log('Bar double-clicked:', barId); }, onBarDrag: (barId, newStartDate, newEndDate) => { console.log('Bar dragged:', barId, newStartDate, newEndDate); // Update your data source }, onBarResize: (barId, newStartDate, newEndDate) => { console.log('Bar resized:', barId, newStartDate, newEndDate); // Update your data source }, onGroupToggle: (groupId, collapsed) => { setState((prev) => { const newCollapsed = new Set(prev.collapsedGroups); if (collapsed) { newCollapsed.add(groupId); } else { newCollapsed.delete(groupId); } return { ...prev, collapsedGroups: newCollapsed }; }); } }} config={{ rowHeight: 40, labelColumnWidth: 200, showTodayMarker: true, showWeekends: true }} />; ``` -------------------------------- ### Install @mog-sdk/sheet-view Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/sheet-view.md Install the SheetView package using npm. This command is used to add the necessary library to your project for integrating the Mog canvas grid. ```bash npm install @mog-sdk/sheet-view ``` -------------------------------- ### Check Mog CLI Installation Source: https://github.com/fundamental-research-labs/mog/blob/main/cli/skill/SKILL.md Verify if the `mog` CLI is installed and accessible in the current environment. ```bash command -v mog ``` -------------------------------- ### Mog Execute Code Example Source: https://github.com/fundamental-research-labs/mog/blob/main/cli/skill/SKILL.md Example of code that can be executed using `mog execute`. The code runs in an async function with provided SDK objects. ```javascript await ws.setCell("A1", 42); return await ws.getValue("A1"); ``` -------------------------------- ### Using Statement Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/architecture/README.md Demonstrates using the 'using' statement for managing disposable resources, such as Workbooks. ```typescript await using(wb, async (workbook) => { // ... use workbook ... }) ``` -------------------------------- ### Build for Web (Default) Source: https://github.com/fundamental-research-labs/mog/blob/main/file-io/xlsx/parser/README.md Builds the WASM package for web deployment using pnpm. Ensure Rust and wasm-pack are installed. ```bash # Build for web (default) pnpm build ``` -------------------------------- ### Install Vite and Mog Embed Package Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/embed-web-component.md Use npm to create a new Vite project and install the necessary Mog embed package. This sets up a basic project structure for using the web component. ```bash npm create vite@latest mog-web-component -- --template vanilla cd mog-web-component npm install @mog-sdk/embed ``` -------------------------------- ### Workbook Dispose Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/architecture/README.md Demonstrates the synchronous local cleanup method for a Workbook using wb.dispose(). ```typescript wb.dispose() ``` -------------------------------- ### Compute Core NAPI Usage Example Source: https://github.com/fundamental-research-labs/mog/blob/main/compute/napi/README.md Demonstrates how to use the compute-core-napi addon, including setting the current time, initializing a ComputeEngine, and setting cell values. ```javascript const addon = require('./compute-core-napi.node'); // Static functions addon.computeSetCurrentTime(45292.0); // Class-based engine const engine = new addon.ComputeEngine(JSON.stringify({ sheets: [{ id: '00000000-0000-0000-0000-000000000001', name: 'Sheet1', rows: 100, cols: 26, cells: [], }], })); // Instance methods (snake_case matching the TS bridge client) const initResult = engine.compute_take_init_result(); engine.compute_set_cell( JSON.stringify(sheetId), // [serde] SheetId JSON.stringify(cellId), // [serde] CellId 0, // [prim] row 0, // [prim] col '=A1+A2' // [str] input ); ``` -------------------------------- ### Manage Sheet Handles and Renaming Source: https://github.com/fundamental-research-labs/mog/blob/main/cli/skill/SKILL.md Examples of getting or creating a sheet by name and renaming an existing sheet using workbook methods. ```javascript // Sheet handles, not activation. const model = await workbook.getOrCreateSheet("Model"); await workbook.sheets.rename("Sheet1", "Inputs"); ``` -------------------------------- ### Read and Write Cells Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/python-sdk.md Shows how to set and get cell values using different address notations (A1, tuples) and ranges. Formulas starting with '=' are supported, and `wb.calculate()` should be called before reading formula results. ```python ws.set_cell("A1", "Name") ws.set_cell((1, 0), "Alice") ws.set_cell(1, 1, 92) ws.set_range("A3:B4", [ ["Bob", 85], ["Cora", 97], ]) print(ws.get_value("B2")) print(ws.get_range("A1:B4")) ``` -------------------------------- ### Quick Start: Create and Manipulate Workbook Source: https://github.com/fundamental-research-labs/mog/blob/main/runtime/sdk/README.md Demonstrates the basic steps to create a workbook, set cell values, perform calculations using formulas, and retrieve computed values. Ensure the workbook is disposed after use. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook(); const ws = wb.activeSheet; await ws.setCell('A1', 42); await ws.setCell('A2', 58); await ws.setCell('A3', '=A1+A2'); const val = await ws.getValue('A3'); // 100 await wb.dispose(); ``` -------------------------------- ### Install Dependencies for Vite React App Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/embed-react.md Install necessary dependencies for embedding Mog in a Vite React application. This includes creating a new Vite project and installing the Mog embed SDK. ```bash npm create vite@latest mog-react-embed -- --template react-ts cd mog-react-embed npm install npm install @mog-sdk/embed ``` -------------------------------- ### Create and Run a Mog Script Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/quickstart.md This snippet sets up a Node.js project, installs the Mog SDK, and creates a script to interact with a workbook. It demonstrates creating a workbook, writing values and formulas to cells, and reading computed results. ```bash mkdir mog-quickstart cd mog-quickstart npm init -y npm install @mog-sdk/sdk cat > quickstart.mjs <<'EOF' import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook({ userTimezone: 'UTC' }); try { const ws = wb.activeSheet; console.log(`sheet count: ${wb.sheetCount}`); console.log(`active sheet: ${ws.name}`); await ws.setCell('A1', 42); await ws.setCell(1, 0, 58); // A2, using zero-based row/column indexes await ws.setCell('A3', '=SUM(A1:A2)'); console.log(`A1: ${await ws.getValue('A1')}`); console.log(`A2: ${await ws.getValue('A2')}`); console.log(`A3: ${await ws.getValue('A3')}`); console.log(`A3 formula: ${await ws.getFormula('A3')}`); } finally { await wb.close('skipSave'); } EOF node quickstart.mjs ``` -------------------------------- ### Install Mog SDK Source: https://github.com/fundamental-research-labs/mog/blob/main/runtime/sdk/README.md Instructions for adding the Mog SDK to your project. For monorepos, use 'pnpm add'. For source checkouts, ensure the native Rust addon is built first. ```bash # Monorepo — already available as workspace dependency pnpm add @mog-sdk/sdk # Node/native path: the native Rust addon must be built first in source checkouts cd compute-core-napi && pnpm build ``` -------------------------------- ### Creating Workbooks with Various Options Source: https://github.com/fundamental-research-labs/mog/blob/main/runtime/sdk/README.md Examples of creating a new workbook, loading from a file path, buffer, or with specific import options. Custom document IDs or pre-existing kernel contexts can also be provided. ```typescript // Blank workbook const wb = await createWorkbook(); // From file path const wb = await createWorkbook('data.xlsx'); // From XLSX buffer const wb = await createWorkbook(readFileSync('data.xlsx')); // With import options const wb = await createWorkbook('data.xlsx', { valuesOnly: true }); // Options bag (when you need a custom document ID) const wb = await createWorkbook({ xlsx: buffer, documentId: 'my-doc' }); // Power-user: pre-existing kernel context (browser app path) const wb = await createWorkbook({ ctx, eventBus }); ``` -------------------------------- ### Workbook-Scoped Property Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/architecture/README.md Examples of workbook-scoped properties that are bound to the workbook's lifecycle. These are readonly properties. ```typescript wb.history ``` ```typescript wb.sheets ``` -------------------------------- ### Stateless API Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/architecture/README.md Examples of stateless operations on the Workbook and Worksheet API. These are simple method calls. ```typescript ws.setCell("A1", 42) ``` ```typescript wb.indexToAddress(0, 0) ``` -------------------------------- ### TimelineViewAdapter Integration Example Source: https://github.com/fundamental-research-labs/mog/blob/main/ui/src/data-views/timeline/README.md Demonstrates how to create a `TimelineViewAdapter` to integrate the Timeline component with kernel data stores. It shows data fetching, transformation, and event handling for updating kernel stores. ```typescript // In shell/src/views/timeline/TimelineViewAdapter.ts class TimelineViewAdapter implements IViewAdapter { render() { // 1. Fetch data from kernel stores const records = this.store.getRecords(); // 2. Transform to plain objects const bars: TimelineBar[] = records.map(record => ({ id: record.id.toString(), // RowId → string title: record.getTitle(), startDate: record.getStartDate(), endDate: record.getEndDate(), color: record.getColor(), groupId: record.getGroupId()?.toString() })); // 3. Render Timeline component return ( { // Update kernel store const rowId = RowId.fromString(id); this.store.updateRecord(rowId, { startDate: start, endDate: end }); } }} /> ); } } ``` -------------------------------- ### Install Workflow Engine with Pip Source: https://github.com/fundamental-research-labs/mog/blob/main/infra/platform/workflow/README.md Install the workflow engine package using pip. Use the dev dependencies for development. ```bash pip install -e . # Install with dev dependencies pip install -e ".[dev]" ``` -------------------------------- ### Bootstrap Mog Python SDK Source: https://github.com/fundamental-research-labs/mog/blob/main/compute/pyo3/README.md Navigate to the mog directory and run the check:python-sdk command to bootstrap the Python SDK. ```bash cd ../mog pnpm check:python-sdk ``` -------------------------------- ### Keyboard Event Handling Example Source: https://github.com/fundamental-research-labs/mog/blob/main/kernel/src/keyboard/README.md Demonstrates how to set up the KeyboardEventProcessor and ShortcutMatcher to handle keyboard events and dispatch actions based on classified input and context. Assumes shortcut definitions and a current context are available. ```typescript import { KeyboardEventProcessor, ShortcutMatcher, type KeyboardShortcut } from '@mog/kernel/keyboard'; // 1. Create processor (once) const processor = new KeyboardEventProcessor(); // auto-detects platform // 2. Create matcher with shortcut definitions const matcher = new ShortcutMatcher(shortcuts, processor.platform); // 3. Handle keyboard events document.addEventListener('keydown', (event) => { const classified = processor.processAndClassify(event); switch (classified.type) { case 'shortcut': { const match = matcher.match(classified.input, currentContext); if (match) { event.preventDefault(); dispatch(match.action); } break; } case 'character': // Forward to text input break; case 'navigation': // Handle arrow keys, tab, etc. break; // ... } }); ``` -------------------------------- ### Consumer-Scoped Handle Example Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/architecture/README.md Example of a consumer-scoped state that returns a handle with an explicit cleanup path. Requires handle.dispose() or using. ```typescript wb.viewport.createRegion(sheetId, bounds) ``` -------------------------------- ### Rust Usage Example for Viewport and Mutation Serialization Source: https://github.com/fundamental-research-labs/mog/blob/main/compute/core/crates/compute-wire/README.md Demonstrates how to use compute_wire functions to serialize viewport render data and mutation results in Rust. Includes necessary imports and data structures. ```rust use compute_wire::{ serialize_viewport_binary, serialize_mutation_result, FormatPalette, ViewportRenderData, ViewportRenderCell, flags, constants, }; // Build viewport render data (from engine internals) let data = ViewportRenderData { /* ... */ }; let blob: Vec = serialize_viewport_binary(&data, generation, is_delta, palette_start); // Serialize mutation result after recalc let result = engine.recalc(); let blob: Vec = serialize_mutation_result(&result, &sheet_id, generation); ``` -------------------------------- ### Build mog-sdk from Source Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/python-sdk.md Build the local PyO3 package from a source checkout using Maturin. This is necessary if no compatible wheel is available for your platform. ```bash python3 -m venv compute/pyo3/.venv compute/pyo3/.venv/bin/python -m pip install "maturin>=1.7,<2.0" compute/pyo3/.venv/bin/python -m maturin develop --manifest-path compute/pyo3/Cargo.toml ``` -------------------------------- ### Run the React Development Server Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/embed-react.md Command to start the development server for the React application, allowing you to see the embedded Mog spreadsheet in action. ```bash npm run dev ``` -------------------------------- ### Test File Naming Conventions Examples Source: https://github.com/fundamental-research-labs/mog/blob/main/file-io/xlsx/parser/test-corpus/README.md Examples illustrating the naming conventions for test files, indicating the type of error and affected aspect. ```text - unclosed_cell_tag.xlsx - XML with unclosed `` tag - invalid_cell_ref_zzz.xlsx - Cell with reference "ZZZ99999999" - truncated_mid_row.xlsx - File truncated in the middle of a row element - missing_workbook_rels.xlsx - Missing xl/\_rels/workbook.xml.rels - bad_zip_signature.xlsx - ZIP file with corrupted signature bytes ``` -------------------------------- ### Create and Calculate Workbook Source: https://github.com/fundamental-research-labs/mog/blob/main/compute/pyo3/README.md Demonstrates creating a new workbook, setting cell values, performing calculations, and asserting the result. Ensure the workbook is disposed after use. ```python import mog wb = mog.create_workbook() ws = wb.active_sheet ws.set_cell("A1", 2) ws.set_cell("A2", "=A1*3") wb.calculate() assert ws.get_value("A2") == 6 wb.dispose() ``` -------------------------------- ### API Discovery with `api.describe` Source: https://github.com/fundamental-research-labs/mog/blob/main/runtime/sdk/README.md Inspect Mog API paths to understand available functions and their signatures. ```APIDOC ## API Discovery ### Description Use `api.describe` to inspect Mog API paths and understand available functions. ### Method - `api.describe(path)`: Returns a description of the API path. ### Parameters - `path` (string) - Required - The API path to describe (e.g., 'ws.tables.add'). ### Request Example ```typescript console.log(api.describe('ws.tables.add')); console.log(api.describe('ws.filters.setColumnFilter')); ``` ``` -------------------------------- ### Expected Output of Mog Script Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/quickstart.md This shows the expected console output when running the quickstart Node.js script, including sheet information, cell values, and computed formula results. ```text sheet count: 1 active sheet: Sheet1 A1: 42 A2: 58 A3: 100 A3 formula: =SUM(A1:A2) ``` -------------------------------- ### Mog SDK Quick Start: Workbook and Sheet Operations Source: https://github.com/fundamental-research-labs/mog/blob/main/runtime/sdk/llms.txt Initialize a workbook and access its active sheet to perform operations like writing cells, bulk writes, reading data, and converting to CSV or JSON. Remember to dispose of the workbook when finished. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook(); const ws = wb.activeSheet; // Write cells (formulas auto-recalc) await ws.setCell('A1', 100); await ws.setCell('A2', 200); await ws.setCell('A3', '=SUM(A1:A2)'); console.log(await ws.getValue('A3')); // 300 // Bulk write await ws.setRange('B1', [['Name', 'Score'], ['Alice', 92], ['Bob', 85]]); // Read const data = await ws.getData(); // CellValue[][] const csv = await ws.toCSV(); // RFC 4180 CSV string const json = await ws.toJSON(); // [{ Name: 'Alice', Score: 92 }, ...] await ws.describeRange('A1:B3'); // LLM-friendly text summary // Always dispose when done await wb.dispose(); ``` -------------------------------- ### Drawing Recognition Started Event Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Emitted when the drawing recognition process begins. It includes the sheet ID and the drawing ID for which recognition is starting, along with the IDs of the strokes involved. ```APIDOC ## DrawingRecognitionStartedEvent ### Description Indicates the start of a drawing recognition process. ### Event Type `drawing:recognitionStarted` ### Properties * **type** (string) - The event type, fixed to 'drawing:recognitionStarted'. * **sheetId** (string) - The ID of the sheet containing the drawing. * **drawingId** (string) - The ID of the drawing for which recognition is starting. * **strokeIds** (string[]) - An array of IDs for the strokes being recognized. ``` -------------------------------- ### Managing Sheets within a Workbook Source: https://github.com/fundamental-research-labs/mog/blob/main/runtime/sdk/README.md Illustrates how to work with multiple sheets in a workbook, including getting the sheet count, names, adding new sheets, and getting or creating sheets idempotently. ```typescript const count = wb.sheetCount; const names = wb.sheetNames; const ws2 = await wb.sheets.add('Sheet2'); // Get or create (idempotent) const { sheet, created } = await wb.getOrCreateSheet('Data'); ``` -------------------------------- ### Create, Open, and Export Workbooks Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/python-sdk.md Demonstrates creating a new workbook, opening an existing one from a file path, exporting it to bytes, and disposing of workbook objects. Ensure to handle potential exceptions and dispose of workbooks to free resources. ```python import mog from pathlib import Path wb = mog.create_workbook() wb.dispose() opened = mog.open_workbook("book.xlsx") try: data = opened.to_buffer() Path("book-copy.xlsx").write_bytes(data) finally: opened.dispose() ``` -------------------------------- ### Quick Start: Inspecting Mog Runtimes Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/devtools/README.md Import `@mog/devtools` in development builds to access runtime observability. Use these commands in the browser console to inspect live XState machines, their states, and transitions, or to find slow operations. ```javascript __dt.machines() // See all live XState machines __dt.machine('editor') // Inspect one machine's state + transitions __dt.slow() // Find everything above 16ms __dt.timeline(1000) // Last 1000ms across all runtimes ``` -------------------------------- ### IGatedFormulasAPI Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt API for getting and setting cell formulas. ```APIDOC ## IGatedFormulasAPI ### Description API for getting and setting cell formulas. ### Methods #### `get(sheetId: string, row: number, col: number): string | null` Gets the formula of a specific cell. #### `set(sheetId: string, row: number, col: number, formula: string): void` Sets the formula of a specific cell. ### Parameters * **sheetId** (string) - Required - The ID of the sheet. * **row** (number) - Required - The row number of the cell. * **col** (number) - Required - The column number of the cell. * **formula** (string) - Required - The formula to set. ### Returns * `string | null` - The formula of the cell, or null if no formula is set. * `void` ``` -------------------------------- ### Creating Workbook with WASM Entry and Options Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/sdk.md Example of creating a workbook using the WASM entry point, providing XLSX data as bytes and a WASM module, along with user timezone. ```typescript const wb = await createWasmWorkbook({ xlsx: xlsxBytes, wasmModule: computeWasmModule, userTimezone: 'UTC', }); ``` -------------------------------- ### IGatedFormattingAPI Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt API for getting and setting cell formatting. ```APIDOC ## IGatedFormattingAPI ### Description API for getting and setting cell formatting. ### Methods #### `get(sheetId: string, row: number, col: number): Record` Gets the formatting of a specific cell. #### `set(sheetId: string, row: number, col: number, format: Record): void` Sets the formatting of a specific cell. ### Parameters * **sheetId** (string) - Required - The ID of the sheet. * **row** (number) - Required - The row number of the cell. * **col** (number) - Required - The column number of the cell. * **format** (Record) - Required - The formatting object. ### Returns * `Record` - The formatting object for the cell. * `void` ``` -------------------------------- ### Agent API Guidance Source: https://github.com/fundamental-research-labs/mog/blob/main/runtime/sdk/llms.txt The Mog SDK offers guidance utilities for interacting with LLMs. Use `api.guidance.analyze()` for source preflight checks and `api.guidance.explain()` for dialect explanations and replacement suggestions. ```APIDOC ## Agent API Guidance Use `api.guidance` for LLM-related operations and dialect analysis. ### Methods - `api.guidance.analyze(source)`: Performs preflight analysis on source code. - `api.guidance.explain(query)`: Provides explanations for specific Mog concepts or code snippets. ### Diagnostic Information Each diagnostic object may contain: - `diagnostic.mogReplacements`: Suggested replacement paths or snippets. - `diagnostic.references`: Follow-up queries for `api.guidance.explain`. ### Unsupported Patterns Avoid Microsoft Office JavaScript API patterns such as `Excel.run`, `Office.context`, `context.sync()`, `.load(...)`, `.isNullObject`, Range proxy assignment (`range.values = data`), or `range.format.fill.color`. Use Mog-native APIs instead. ### Example Usage ```typescript // Describe specific Mog methods console.log(api.describe('ws.tables.add')); console.log(api.describe('ws.filters.setColumnFilter')); // Analyze source code const diagnostic = await api.guidance.analyze(sourceCode); // Explain a concept or code snippet await api.guidance.explain('context.workbook.worksheets.getActiveWorksheet'); await api.guidance.explain('wb.activeSheet'); // Preflight check await api.guidance.preflight(sourceCode); // Inspect diagnostic results console.log(diagnostic.mogReplacements); console.log(diagnostic.references); ``` ``` -------------------------------- ### OOXML Guide Formula Evaluator Source: https://github.com/fundamental-research-labs/mog/blob/main/canvas/drawing/shapes/scripts/visual-test.html Evaluates OOXML guide formulas to calculate shape parameters. It supports various mathematical operations and built-in variables like width, height, and angles. Use this function to dynamically compute values for shape geometry based on OOXML specifications. ```javascript // ============================================================================= // OOXML Guide Formula Evaluator (ported from custom-geometry.ts) // ============================================================================= function evaluateGuides(guides, width, height) { const vars = new Map(); // Built-in variables vars.set('w', width); vars.set('h', height); vars.set('wd2', width / 2); vars.set('hd2', height / 2); vars.set('wd4', width / 4); vars.set('hd4', height / 4); vars.set('wd5', width / 5); vars.set('hd5', height / 5); vars.set('wd6', width / 6); vars.set('hd6', height / 6); vars.set('wd8', width / 8); vars.set('hd8', height / 8); vars.set('wd10', width / 10); vars.set('hd10', height / 10); vars.set('wd12', width / 12); vars.set('wd32', width / 32); vars.set('hd32', height / 32); vars.set('l', 0); vars.set('t', 0); vars.set('r', width); vars.set('b', height); vars.set('ss', Math.min(width, height)); vars.set('ls', Math.max(width, height)); vars.set('ssd2', Math.min(width, height) / 2); vars.set('ssd4', Math.min(width, height) / 4); vars.set('ssd6', Math.min(width, height) / 6); vars.set('ssd8', Math.min(width, height) / 8); vars.set('ssd16', Math.min(width, height) / 16); vars.set('ssd32', Math.min(width, height) / 32); // Additional computed built-ins vars.set('vc', height / 2); vars.set('hc', width / 2); // OOXML angle constants in 60000ths of a degree vars.set('cd2', 10800000); vars.set('cd4', 5400000); vars.set('cd8', 2700000); vars.set('3cd4', 16200000); vars.set('3cd8', 8100000); vars.set('5cd8', 13500000); vars.set('7cd8', 18900000); function resolveArg(arg) { const num = Number(arg); if (!isNaN(num)) return num; return vars.get(arg) || 0; } function ooxml60kToRad(val) { return (val * Math.PI) / (180 * 60000); } function radToOoxml60k(rad) { return (rad * 180 * 60000) / Math.PI; } for (const guide of guides) { const formula = guide.fmla.trim(); const parts = formula.split(/\s+/); const op = parts[0]; const a = parts[1] !== undefined ? resolveArg(parts[1]) : 0; const b = parts[2] !== undefined ? resolveArg(parts[2]) : 0; const c = parts[3] !== undefined ? resolveArg(parts[3]) : 0; let result; switch (op) { case 'val': result = a; break; case '*/': result = c !== 0 ? (a * b) / c : 0; break; case '+-': result = a + b - c; break; case '+/': result = c !== 0 ? (a + b) / c : 0; break; case 'sin': result = a * Math.sin(ooxml60kToRad(b)); break; case 'cos': result = a * Math.cos(ooxml60kToRad(b)); break; case 'tan': result = a * Math.tan(ooxml60kToRad(b)); break; case 'at2': result = radToOoxml60k(Math.atan2(b, a)); break; case 'cat2': result = a * Math.cos(Math.atan2(c, b)); break; case 'sat2': result = a * Math.sin(Math.atan2(c, b)); break; case '?:': result = a > 0 ? b : c; break; case 'min': result = Math.min(a, b); break; case 'max': result = Math.max(a, b); break; case 'abs': result = Math.abs(a); break; case 'sqrt': result = Math.sqrt(Math.abs(a)); break; case 'mod': result = Math.sqrt(a * a + b * b + c * c); break; case 'pin': result = b < a ? a : b > c ? c : b; break; default: result = 0; break; } vars.set(guide.name, result); } return vars; } ``` -------------------------------- ### ISchemaBridge Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Interface for starting to listen for validation annotation events from Rust recalc. ```APIDOC ## ISchemaBridge ### Description Interface for starting to listen for validation annotation events from Rust recalc. ### Methods - **start()**: Starts listening for validation annotation events. - Returns: A cleanup function to stop listening. ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/fundamental-research-labs/mog/blob/main/file-io/xlsx/tooling/benchmarks/README.md Execute the entire benchmark suite, including generating test files and running all individual benchmark scripts. This is useful for a complete performance overview or initial setup. ```bash pnpm bench:all ``` -------------------------------- ### WorkbookViewportImpl Usage of DisposableStore Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/internals/spreadsheet/API-DESIGN-PHILOSOPHY.md Example of creating and tracking a ViewportRegionImpl within a DisposableStore in WorkbookViewportImpl. ```typescript class WorkbookViewportImpl { constructor(private computeBridge, private disposables: DisposableStore) {} createRegion(sheetId, bounds, viewportId) { const region = new ViewportRegionImpl(sheetId, bounds, this.computeBridge, viewportId); this.disposables.track(region); return region; } } ``` -------------------------------- ### Creating a Workbook in Headless Node Context Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/internals/spreadsheet/ARCHITECTURE.md Shows how to create a new workbook instance in a headless Node.js environment, specifying user timezone and setting initial data for a range. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook({ userTimezone: "UTC" }); const ws = wb.activeSheet; await ws.setRange(0, 0, [["Name", "Score"], ["Alice", 100]]); ``` -------------------------------- ### CodeExecutionDiagnosticSpan Interface Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Specifies the start and end positions of a diagnostic within source code. ```APIDOC ## CodeExecutionDiagnosticSpan Interface ### Description Marks the location of a diagnostic within the source code using character offsets. ### Interface ```typescript export interface CodeExecutionDiagnosticSpan { /** UTF-16 source offset where the diagnostic starts */ start: number; /** UTF-16 source offset where the diagnostic ends */ end: number; /** 1-based line number */ line: number; /** 1-based column number */ column: number; } ``` ``` -------------------------------- ### Run Pivot Benchmarks Source: https://github.com/fundamental-research-labs/mog/blob/main/compute/core/README.md Execute pivot benchmarks for the compute-pivot crate. ```bash cargo bench -p compute-pivot --bench pivot_benchmarks ``` -------------------------------- ### ITextEffectRenderingBridge Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Interface for starting the TextEffect rendering bridge to subscribe to events for reactive updates. ```APIDOC ## ITextEffectRenderingBridge ### Description Interface for starting the TextEffect rendering bridge to subscribe to events for reactive updates. ### Methods - **start()**: Starts listening for TextEffect rendering events. - Call this after creating the bridge to begin listening for TextEffect rendering events. ``` -------------------------------- ### Run Round-Trip Convenience Script (All Fixtures) Source: https://github.com/fundamental-research-labs/mog/blob/main/file-io/xlsx/parser/README.md Uses a wrapper script to perform round-trip tests on all fixture files. ```bash ./scripts/roundtrip.sh --all ``` -------------------------------- ### StartRotateEvent Interface Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Represents an event signaling the start of a rotation operation for one or more objects. ```APIDOC ## StartRotateEvent ### Description An event fired when a rotation operation begins, detailing the objects to be rotated, the starting mouse position, and the center point for rotation calculations. ### Interface ```typescript export interface StartRotateEvent { type: 'START_ROTATE'; /** IDs of objects to rotate */ objectIds: string[]; /** Starting mouse position */ position: Point; /** Center point for rotation calculation ... } ``` ``` -------------------------------- ### Sample Data Interface Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Interface for providing sample data for preview rendering. ```APIDOC ## SampleData ### Description Provides inline data model for preview rendering. ### Properties * **dataModel** (DataModel) - Inline data model for preview rendering. If undefined, a default 3-node data model is used. * **useDefault** (boolean) - Whether to use the default sample data model. ``` -------------------------------- ### StartResizeEvent Interface Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Represents an event signaling the start of a resize operation for one or more objects. ```APIDOC ## StartResizeEvent ### Description An event indicating the commencement of a resize operation, specifying the objects to be resized, the starting mouse position, and the resize handle used. ### Interface ```typescript export interface StartResizeEvent { type: 'START_RESIZE'; /** IDs of objects to resize */ objectIds: string[]; /** Starting mouse position */ position: Point; /** Which resize handle was grabbed */ ha ... } ``` ``` -------------------------------- ### Fast Publish Readiness Check Source: https://github.com/fundamental-research-labs/mog/blob/main/README.md Perform a quick check for publish readiness across the repository. This is a preliminary check before publishing. ```bash pnpm check:publish-readiness:fast ``` -------------------------------- ### StartDragEvent Interface Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt Represents an event signaling the start of a drag operation for one or more objects. ```APIDOC ## StartDragEvent ### Description An event triggered when a drag operation begins, containing information about the objects being dragged, their initial positions, and their original states. ### Interface ```typescript export interface StartDragEvent { type: 'START_DRAG'; /** IDs of objects to drag */ objectIds: string[]; /** Starting mouse position */ position: Point; /** Original states of all objects */ originalS ... } ``` ``` -------------------------------- ### SpreadsheetAppAPI Source: https://github.com/fundamental-research-labs/mog/blob/main/tools/api-snapshots/@mog-sdk__contracts.api.txt API for interacting with spreadsheets, including getting and setting cell values and ranges. ```APIDOC ## SpreadsheetAppAPI ### Description API for interacting with spreadsheets, including getting and setting cell values and ranges. ### Methods #### getCell * **Description**: Get the value of a specific cell in a sheet. * **Parameters**: * `sheet` (string) - The name of the sheet. * `cell` (string) - The cell identifier (e.g., "A1"). * **Returns**: A Promise that resolves to the cell's value. ```typescript getCell(sheet: string, cell: string): Promise ``` #### setCell * **Description**: Set the value of a specific cell in a sheet. * **Parameters**: * `sheet` (string) - The name of the sheet. * `cell` (string) - The cell identifier (e.g., "A1"). * `value` (WorkflowCellValue) - The value to set. * **Returns**: A Promise that resolves when the cell value is set. ```typescript setCell(sheet: string, cell: string, value: WorkflowCellValue): Promise ``` #### getRange * **Description**: Get all values within a specified range in a sheet. * **Parameters**: * `sheet` (string) - The name of the sheet. * `range` (string) - The range identifier (e.g., "A1:B5"). * **Returns**: A Promise that resolves to a 2D array of cell values. ```typescript getRange(sheet: string, range: string): Promise ``` #### setRange * **Description**: Set values for a specified range in a sheet. * **Parameters**: * `sheet` (string) - The name of the sheet. * `range` (string) - The range identifier (e.g., "A1:B5"). * `values` (WorkflowCellValue[][]) - A 2D array of values to set. * **Returns**: A Promise that resolves when the range values are set. ```typescript setRange(sheet: string, range: string, values: WorkflowCellValue[][]): Promise ``` ``` -------------------------------- ### Creating Workbooks: Blank, From Path, From Bytes, With Options Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/sdk.md Demonstrates various ways to create a workbook: a blank one, from an existing XLSX file path, from XLSX data as bytes, and with specific options including XLSX import settings. ```typescript import { readFile } from 'node:fs/promises'; import { createWorkbook } from '@mog-sdk/sdk'; const blank = await createWorkbook(); const fromPath = await createWorkbook('model.xlsx'); const bytes = new Uint8Array(await readFile('model.xlsx')); const fromBytes = await createWorkbook(bytes); const withOptions = await createWorkbook({ xlsx: bytes, documentId: 'model-1', userTimezone: 'America/Los_Angeles', }); blank.dispose(); fromPath.dispose(); fromBytes.dispose(); withOptions.dispose(); ``` -------------------------------- ### Create Workbook and Interact with Cells Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/architecture/os/kernel.md Demonstrates creating a workbook, setting cell values, performing calculations, and undoing changes. Cell mutations are asynchronous due to Rust compute-core integration. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; const wb = await createWorkbook({ userTimezone: 'UTC' }); const ws = wb.activeSheet; await ws.setCell('A1', 42); await ws.setCell(1, 0, '=A1*2'); // A2 by zero-based row/column const value = await ws.getValue('A2'); await wb.history.undo(); wb.dispose(); ``` -------------------------------- ### Importing createWorkbook from Mog SDK Source: https://github.com/fundamental-research-labs/mog/blob/main/docs/guides/sdk.md Demonstrates the standard way to import the `createWorkbook` function from the root of the `@mog-sdk/sdk` package. ```typescript import { createWorkbook } from '@mog-sdk/sdk'; ```