### First JavaScript Example Source: https://github.com/loro-dev/loro/blob/main/skills/loro/references/fit-and-architecture.md A basic example demonstrating the creation of a Loro document, insertion of items into a list, exporting an update, and importing it into another document. ```typescript import { LoroDoc } from "loro-crdt"; const docA = new LoroDoc(); const listA = docA.getList("items"); listA.insert(0, "A"); listA.insert(1, "B"); const update = docA.export({ mode: "update" }); const docB = new LoroDoc(); docB.import(update); console.log(docB.toJSON()); // { items: ["A", "B"] } ``` -------------------------------- ### Quick Start Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Basic usage example demonstrating index creation, comparison, and JSON stringification. ```ts import { FractionalIndex, compare } from "@loro-dev/fractional-index"; const first = FractionalIndex.default(); const before = FractionalIndex.newBefore(first); const after = FractionalIndex.newAfter(first); const middle = FractionalIndex.newBetween(first, after); console.log(first); // "80" console.log(before); // "7F80" console.log(after); // "8180" console.log(middle); // "817F80" const ordered = [after, first, before].sort(compare); console.log(ordered); // ["7F80", "80", "8180"] JSON.stringify({ position: first }); // "{\"position\":\"80\"}" ``` -------------------------------- ### Install Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Installation instructions for pnpm, npm, and yarn. ```sh pnpm add @loro-dev/fractional-index ``` ```sh npm install @loro-dev/fractional-index ``` ```sh yarn add @loro-dev/fractional-index ``` -------------------------------- ### Practical Examples Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/ide.md A collection of practical examples combining different `moon ide` commands and options. ```bash # Find public function definition moon ide goto-definition -tags 'pub fn' -query 'maximum' # Find all references to a struct moon ide find-references -tags 'struct' -query 'Rectangle' # Find trait implementations moon ide goto-definition -tags 'impl' -query 'Show for MyType' # Find errors in specific package moon ide goto-definition -tags 'error' -query '@mymodule/parser ParseError' # Find symbol across multiple packages moon ide goto-definition -query '@moonbitlang/x @moonbitlang/core encode' # Combine package filtering with tags moon ide goto-definition -tags 'pub fn' -query '@username/myapp helper' ``` -------------------------------- ### Package Importing Example Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Example of calling an imported function from a package in MoonBit. ```mbt ///| /// In main.mbt after importing "username/hello/liba" in `moon.pkg.json` fn main { println(@liba.hello()) // Calls hello() from liba package } ``` -------------------------------- ### Bounded Generation Example Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Example of bounded index generation using `generateNEvenly`. ```ts const lower = FractionalIndex.newBefore(FractionalIndex.default()); const upper = FractionalIndex.newAfter(FractionalIndex.default()); const values = FractionalIndex.generateNEvenly(lower, upper, 100); ``` -------------------------------- ### `moon doc` Examples Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Examples of using the `moon doc` command for API discovery, including searching for String methods and exploring package symbols. ```bash # search for String methods in standard library: $ moon doc "String" type String pub fn String::add(String, String) -> String # ... more methods omitted ... $ moon doc "@buffer" # list all symbols in package buffer: moonbitlang/core/buffer fn from_array(ArrayView[Byte]) -> Buffer ``` -------------------------------- ### Symbol Name Query Examples Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/ide.md Examples demonstrating how to use the `-query` flag for fuzzy symbol name searching with package filtering. ```bash # Find any symbol named 'symbol' moon ide goto-definition -query 'symbol' # Find methods of a specific type moon ide goto-definition -query 'Type::method' # Find trait method implementations moon ide goto-definition -query 'Trait for Type with method' # Find symbol in specific package using @pkg prefix moon ide goto-definition -query '@moonbitlang/x encode' # Find symbol in multiple packages (searches in pkg1 OR pkg2) moon ide goto-definition -query '@username/mymodule/pkg1 @username/mymodule/pkg2 helper' # Find symbol in nested package moon ide goto-definition -query '@username/mymodule/mypkg helper' ``` -------------------------------- ### Before and After Index Creation Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Example of creating indexes before and after a base index. ```ts const base = FractionalIndex.default(); const before = FractionalIndex.newBefore(base); // "7F80" const after = FractionalIndex.newAfter(base); // "8180" ``` -------------------------------- ### Good example: use labeled and optional parameters Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Example demonstrating the use of labeled and optional parameters in MoonBit function definitions and tests. ```mbt ///| fn g( positional : Int, required~ : Int, optional? : Int, // no default => Option optional_with_default? : Int = 42, // default => plain Int ) -> String { // These are the inferred types inside the function body. let _ : Int = positional let _ : Int = required let _ : Int? = optional let _ : Int = optional_with_default "\{positional},\{required},\{optional},\{optional_with_default}" } ///| test { inspect(g(1, required=2), content="1,2,None,42") inspect(g(1, required=2, optional=3), content="1,2,Some(3),42") inspect(g(1, required=4, optional_with_default=100), content="1,4,None,100") } ``` -------------------------------- ### Bad example: `arg : APIOptions` (use labeled optional parameters instead) Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Example demonstrating why using a struct to group options is not idiomatic in MoonBit, recommending labeled optional parameters instead. ```mbt ///| /// Do not use struct to group options. struct APIOptions { width : Int? height : Int? } ///| fn not_idiomatic(opts : APIOptions, arg : Int) -> Unit { } ///| test { // Hard to use in call site not_idiomatic({ width : Some(5), height : None }, 10) not_idiomatic({ width : None, height : None }, 10) } ``` -------------------------------- ### BoolRle Encoding Examples Source: https://github.com/loro-dev/loro/blob/main/docs/encoding.md Provides concrete examples of BoolRle encoding for various boolean sequences, illustrating the resulting varint arrays. ```plaintext Examples: - [T, T, F, F, F] → [0x00, 0x02, 0x03] (0 false, 2 true, 3 false) - [F, F, F, T, T] → [0x03, 0x02] (3 false, 2 true) - [T, T, T, T, T] → [0x00, 0x05] (0 false, 5 true) - [F, F, F] → [0x03] (3 false) - [T, T, T, F, F, T] → [0x00, 0x03, 0x02, 0x01] (0 false, 3 true, 2 false, 1 true) ``` -------------------------------- ### Jitter Default Example Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Example of adding jitter to a default index. ```ts const index = FractionalIndex.jitterDefault({ jitter: 3 }); console.log(index.length); // 8 hex chars: 0x80 plus 3 random bytes ``` -------------------------------- ### Deterministic Jitter Example Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Example of using a `randomByte` function for deterministic jitter. ```ts const bytes = [1, 2, 3]; let offset = 0; const index = FractionalIndex.jitterDefault({ jitter: 3, randomByte: () => bytes[offset++], }); console.log(index); // "80010203" ``` -------------------------------- ### Parsing and Serialization Example Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Demonstrates how to parse a hex string into a FractionalIndex and log it. Also includes compatibility notes. ```typescript const fromHex = FractionalIndex.fromHexString("80ff"); console.log(fromHex); // "80FF" ``` -------------------------------- ### Tag-based Filtering Examples Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/ide.md Examples showing how to use the `-tags` flag for pre-filtering symbols by visibility and type, including logical operators. ```bash # Public functions only moon ide goto-definition -tags 'pub fn' -query 'my_func' # Functions or constants moon ide goto-definition -tags 'fn | const' -query 'helper' # Public functions or constants moon ide goto-definition -tags 'pub (fn | const)' -query 'api' # Public types or traits moon ide goto-definition -tags 'pub (type | trait)' -query 'MyType' ``` -------------------------------- ### Typical Package configuration (moon.pkg.json) Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Example configuration for `moon.pkg.json`. ```json { "is_main": true, // Creates executable when true "import": [ // Package dependencies "username/hello/liba", // Simple import, use @liba.foo() to call functions { "path": "moonbitlang/x/encoding", "alias": "libb" // Custom alias, use @libb.encode() to call functions } ], "test-import": [...], // Imports for black-box tests, similar to import "wbtest-import": [...] // Imports for white-box tests, similar to import (rarely used) } ``` -------------------------------- ### Default Index Creation Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Example of creating a default index. ```ts const index = FractionalIndex.default(); // "80" ``` -------------------------------- ### Docstring Test Example Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md An example of a public API with a docstring test, showcasing the `sum_array` function and its expected behavior. ```mbt ///| /// Get the largest element of a non-empty `Array`. /// /// # Example /// ```mbt check /// test { /// inspect(sum_array([1, 2, 3, 4, 5, 6]), content="21") /// } /// ``` /// /// # Panics /// Panics if the `xs` is empty. pub fn sum_array(xs : Array[Int]) -> Int { xs.fold(init=0, (a, b) => a + b) } ``` -------------------------------- ### Delete Start IDs Encoding (serde_columnar) Source: https://github.com/loro-dev/loro/blob/main/docs/encoding.md Explains the `serde_columnar` encoding strategy for delete start IDs. It uses `DeltaRle` for `peer_idx`, `counter`, and `len` columns. ```text ┌──────────────────────────────────────────────────────────────────┐ │ Delete Start IDs (serde_columnar) │ ├───────────────┬──────────────────────────────────────────────────┤ │ Column │ Strategy │ ├───────────────┼──────────────────────────────────────────────────┤ │ peer_idx │ usize, DeltaRle │ │ counter │ i32, DeltaRle │ │ len │ isize, DeltaRle │ └───────────────┴──────────────────────────────────────────────────┘ ``` -------------------------------- ### Typical Module configuration (moon.mod.json) Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Example configuration for `moon.mod.json`. ```json { "name": "username/hello", // Required format for published modules "version": "0.1.0", "source": ".", // Source directory(optional, default: ".") "repository": "", // Git repository URL "keywords": [], // Search keywords "description": "...", // Module description "deps": { // Dependencies from mooncakes.io, using`moon add` to add dependencies "moonbitlang/x": "0.4.6" } } ``` -------------------------------- ### Pattern Matching Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/references/moonbit-language-fundamentals.mbt.md Illustrates pattern matching on arrays, structs, and StringViews, including examples of destructuring and conditional matching. ```mbt ///| #warnings("-unused_value") test "pattern match over Array, struct and StringView" { let arr : Array[Int] = [10, 20, 25, 30] match arr { [] => ... // empty array [single] => ... // single element [first, .. middle, rest] => { let _ : ArrayView[Int] = middle // middle is ArrayView[Int] assert_true(first is 10 && middle is [20, 25] && rest is 30) } } fn process_point(point : Point) -> Unit { match point { { x: 0, y: 0 } => ... { x, y } if x == y => ... { x, .. } if x < 0 => ... ... } } /// StringView pattern matching for parsing fn is_palindrome(s : StringView) -> Bool { loop s { [] | [_] => true [a, .. rest, b] if a == b => continue rest // a is of type Char, rest is of type StringView _ => false } } } ``` -------------------------------- ### DeltaOfDelta Encoding Example Source: https://github.com/loro-dev/loro/blob/main/docs/encoding.md Illustrates the efficiency of DeltaOfDelta encoding for a simple sequence of integers. Demonstrates how a sequence of deltas can be represented with minimal bits. ```text Example: Encoding [1, 2, 3, 4, 5, 6] - Values: 1, 2, 3, 4, 5, 6 - Deltas: 1, 1, 1, 1, 1 (all +1) - Delta-of-deltas: 0, 0, 0, 0 (after first delta) - Each 0 encodes as single "0" bit → 5 bits total for 6 values! ``` -------------------------------- ### Example: Root Map with Child Map Source: https://github.com/loro-dev/loro/blob/main/crates/loro-internal/docs/mergeable-container-id.md Illustrates the encoding for a child map nested under a root map. ```text 🤝:$state>note-1 with Root.container_type = Map ``` -------------------------------- ### Importing a local package in moon.pkg.json Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Example of how to import a locally created package (e.g., 'fib') in the moon.pkg.json file. ```json { "import": [ "username/hello/fib", ... ] } ``` -------------------------------- ### Container ID Example Source: https://github.com/loro-dev/loro/blob/main/scripts/doc-tests-tests/example.txt Shows how to get the unique ID of a container within a Loro document. ```typescript import { LoroDoc } from "loro-crdt"; const doc = new LoroDoc(); const list = doc.getList("list"); const containerId = list.id; ``` -------------------------------- ### Get Container By ID Example Source: https://github.com/loro-dev/loro/blob/main/scripts/doc-tests-tests/example.txt Demonstrates how to retrieve a container from a Loro document using its unique ID. ```typescript import { LoroDoc } from "loro-crdt"; const doc = new LoroDoc(); let text = doc.getText("text"); const textId = text.id; text = doc.getContainerById(textId); ``` -------------------------------- ### Generated Embedded Code Example Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/references/advanced-moonbit-build.md Example of generated MoonBit code from embedding a text file. ```mbt check ///| let data : String = #|hello, #|world #| ``` -------------------------------- ### Snapshot Testing Example Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.mbt.md Demonstrates how to use `inspect` for snapshot testing in MoonBit. It shows the basic usage and the update workflow. ```moonbit inspect(value, content="...") // or inspect(value) ``` -------------------------------- ### Example MoonBit Project Layout Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Illustrates the typical directory and file structure of a MoonBit project, including module and package definitions. ```text my_module ├── moon.mod.json # Module metadata, source field(optional) specifies the source directory of the module ├── moon.pkg.json # Package metadata (each directory is a package like Golang) ├── README.mbt.md # Markdown with tested code blocks (`test "..." { ... }`) ├── README.md -> README.mbt.md ├── cmd # Command line directory │ └── main │ ├── main.mbt │ └── moon.pkg.json # executable package with {"is_main": true} ├── liba/ # Library packages │ └── moon.pkg.json # Referenced by other packages as `@username/my_module/liba` │ └── libb/ # Library packages │ └── moon.pkg.json # Referenced by other packages as `@username/my_module/liba/libb` ├── user_pkg.mbt # Root packages, referenced by other packages as `@username/my_module` ├── user_pkg_wbtest.mbt # White-box tests (only needed for testing internal private members, similar to Golang's package mypackage) └── user_pkg_test.mbt # Black-box tests └── ... # More package files, symbols visible to current package (like Golang) ``` -------------------------------- ### General Constructor Source: https://github.com/loro-dev/loro/blob/main/packages/fractional-index/README.md Demonstrates the general constructor `FractionalIndex.new(lower, upper)` mirroring Rust's `FractionalIndex::new`. ```ts FractionalIndex.new(undefined, undefined); // default "80" FractionalIndex.new(existing, undefined); // after existing FractionalIndex.new(undefined, existing); // before existing FractionalIndex.new(left, right); // between left and right ``` -------------------------------- ### Docstring Test Example Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.mbt.md An example of a docstring test for the `sum_array` function in MoonBit, including its signature and a test case. ```moonbit ///|\n/// Get the largest element of a non-empty `Array`.\n///\n/// # Example\n/// ```mbt check\n/// test {\n/// inspect(sum_array([1, 2, 3, 4, 5, 6]), content="21")\n/// }\n/// ```\n///\n/// # Panics\n/// Panics if the `xs` is empty.\npub fn sum_array(xs : Array[Int]) -> Int {\n xs.fold(init=0, (a, b) => a + b)\n} ``` -------------------------------- ### Container Type Example Source: https://github.com/loro-dev/loro/blob/main/scripts/doc-tests-tests/example.txt Demonstrates how to use container types to create different sub-containers within a Loro document. ```typescript import { LoroDoc, LoroText } from "loro-crdt"; const doc = new LoroDoc(); const list = doc.getList("list"); list.insert(0, 100); const text = list.insertContainer(1, new LoroText()); ``` -------------------------------- ### Using `moon ide outline` and `moon ide find-references` Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.mbt.md Examples of using `moon ide outline` to scan packages or files for symbols and `moon ide find-references` to locate symbol usages. ```bash $ moon ide outline . spec.mbt: L003 | pub(all) enum CStandard { ... L013 | pub(all) struct Position { ... $ moon ide outline parser.mbt ... $ moon ide find-references TranslationUnit ... ``` -------------------------------- ### Test filtering example Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Example of how to filter tests to run only those matching a specific pattern, such as methods within a Float class. ```shell moon test float/float_test.mbt --filter "Float::*" ``` -------------------------------- ### Export Updates Example Source: https://github.com/loro-dev/loro/blob/main/scripts/doc-tests-tests/example.txt Illustrates how to export updates from a Loro document, including exporting all updates and updates from a specific version. ```typescript import { LoroDoc } from "loro-crdt"; const doc = new LoroDoc(); const text = doc.getText("text"); text.insert(0, "Hello"); // get all updates of the doc const updates = doc.export({ mode: "update" }); const version = doc.oplogVersion(); text.insert(5, " World"); // get updates from specific version to the latest version const updates2 = doc.exportFrom(version); ``` -------------------------------- ### Text Delete Operation Source: https://github.com/loro-dev/loro/blob/main/docs/JsonSchema.md Represents an operation to delete a specified length of text starting from a given position. Requires the start ID of the deleted element. ```typescript type TextDeleteOp = { "type": "delete", "pos": number, "len": number, "start_id": OpID } ``` -------------------------------- ### Synchronize Loro Documents Source: https://github.com/loro-dev/loro/blob/main/README.md Demonstrates synchronizing two Loro documents (docA and docB) by exporting and importing updates. This example shows how to initialize documents, insert data, export updates, import updates, and verify document states after synchronization. ```typescript import { expect, test } from "vitest"; import { LoroDoc, LoroList } from "loro-crdt"; test("sync example", () => { // Sync two docs with two rounds of exchanges // Initialize document A const docA = new LoroDoc(); const listA: LoroList = docA.getList("list"); listA.insert(0, "A"); listA.insert(1, "B"); listA.insert(2, "C"); // Export all updates from docA const bytes: Uint8Array = docA.export({ mode: "update" }); // Simulate sending `bytes` across the network to another peer, B const docB = new LoroDoc(); // Peer B imports the updates from A docB.import(bytes); // B's state matches A's state expect(docB.toJSON()).toStrictEqual({ list: ["A", "B", "C"], }); // Get the current version of docB const version = docB.oplogVersion(); // Simulate editing at B: delete item 'B' const listB: LoroList = docB.getList("list"); listB.delete(1, 1); // Export the updates from B since the last sync point const bytesB: Uint8Array = docB.export({ mode: "update", from: version }); // Simulate sending `bytesB` back across the network to A // A imports the updates from B docA.import(bytesB); // A has the same state as B expect(docA.toJSON()).toStrictEqual({ list: ["A", "C"], }); }); ``` -------------------------------- ### ListDeleteOp Structure Source: https://github.com/loro-dev/loro/blob/main/docs/JsonSchema.md Represents a delete operation within a List. Specifies the starting position, the length of the content to delete, and the ID of the starting element deleted. ```typescript type ListDeleteOp = { "type": "delete", "pos": number, "len": number, "start_id": OpID } ``` -------------------------------- ### Typical Package configuration (`moon.pkg.json`) Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.mbt.md Example structure for a `moon.pkg.json` file, defining package imports and test imports. ```json { "is_main": true, // Creates executable when true "import": [ "username/hello/liba", // Simple import, use @liba.foo() to call functions { "path": "moonbitlang/x/encoding", "alias": "libb" // Custom alias, use @libb.encode() to call functions } ], "test-import": [...], // Imports for black-box tests, similar to import "wbtest-import": [...] // Imports for white-box tests, similar to import (rarely used) } ``` -------------------------------- ### Discovering functions with `moon doc` Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.mbt.md Examples of using `moon doc` to find specific functions or use globbing to find related functions within a package. ```bash $ moon doc "@buffer.new" # list the specific function in a package: package "moonbitlang/core/buffer" pub fn new(size_hint? : Int) -> Buffer Creates ... omitted ... $ moon doc "String::*rev*" # globbing package "moonbitlang/core/string" pub fn String::rev(String) -> String Returns ... omitted ... # ... more pub fn String::rev_find(String, StringView) -> Int? Returns ... omitted ... ``` -------------------------------- ### Using `moon ide peek-def` for definition context Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.mbt.md Demonstrates how to use `moon ide peek-def` to find the definition of a symbol, including specifying a location with `-loc`. ```bash $ moon ide peek-def Parser::read_u32_leb128 Definition found at file src/parse.mbt | ///| L45:|"///"| L46:|fn Parser::read_u32_leb128(self : Parser) -> UInt raise ParseError { L47:| ... ...:| } $ moon ide peek-def Parser -loc src/parse.mbt:46:4 Definition found at file src/parse.mbt | ///| 2 | priv struct Parser { | ^^^^^^ | bytes : Bytes | mut pos : Int | } | ``` ```bash $ moon ide peek-def String::rev Found 1 symbols matching 'String::rev': `pub fn String::rev` in package moonbitlang/core/builtin at /Users/usrname/.moon/lib/core/builtin/string_methods.mbt:1039-1044 1039 | ///| | /// Returns a new string with the characters in reverse order. It respects | /// Unicode characters and surrogate pairs but not grapheme clusters. | pub fn String::rev(self : String) -> String { | self[:].rev() | } ``` -------------------------------- ### String Interpolation Basics Source: https://github.com/loro-dev/loro/blob/main/skills/moonbit/SKILL.md Illustrates string interpolation using curly braces and the StringBuilder for constructing strings. ```mbt ///| test "string interpolation basics" { let name : String = "Moon" let config = { "cache": 123 } let version = 1.0 println("Hello {name} v{version}") // "Hello Moon v1.0" // ❌ Wrong - quotes inside interpolation not allowed: // println(" - Checking if 'cache' section exists: {config["cache"]}") // ✅ Correct - extract to variable first: let has_key = config["cache"] // `"` not allowed in interpolation println(" - Checking if 'cache' section exists: {has_key}") let sb = StringBuilder::new() sb..write_char('[') // dotdot for imperative method chaining ..write_view([1,2,3].map((x) => "{x}").join(',')) ..write_char(']') inspect(sb.to_string(), content="[1,2,3]") } ```