office-lib

Agent-oriented XLSX and DOCX tooling for MoonBit

office
xlsx
docx
ooxml
cli
moon add bobzhang/office-lib@0.3.0
Download zip
Author
Version
0.3.0
License
Apache-2.0
Last updated
10 days ago
Downloads
20
README

#bobzhang/office-lib

bobzhang/office-lib is the implementation module behind the published moonx bobzhang/office command. It provides the facade for the XLSX engine in bobzhang/mbtexcel and the DOCX engine in bobzhang/docx2html.

The module is intentionally young and may make breaking changes while the major-parity program in ../docs/office-major-parity.md is underway. Registry publication follows the dependency-first process in ../docs/office-release.md; workspace resolution is not a release gate.

The public facade identifies a structurally valid OOXML package while checking that its extension agrees with its package content. Agent-facing JSON uses one deterministic office.output/1 envelope for success, failure, and warnings:

///|
test "document format names" {
inspect(@office.DocumentFormat::Xlsx.name(), content="xlsx")
inspect(@office.DocumentFormat::Docx.name(), content="docx")
}

The canonical executable exposes only implemented capabilities:

moonx bobzhang/office help moonx bobzhang/office help docx moonx bobzhang/office help xlsx moonx bobzhang/office help all --json moonx bobzhang/office help all --jsonl moonx bobzhang/office identify report.docx --json moonx bobzhang/office create xlsx report.xlsx --sheet Data --json moonx bobzhang/office batch report.xlsx changes.json --out revised.xlsx --json moonx bobzhang/office raw list report.docx --json moonx bobzhang/office raw read report.docx /document --json

docx/word and xlsx/excel are the only format names and aliases. The capability inventory carries a deterministic CRC-32 fingerprint so automation can detect contract drift. Command families publish explicit variant schemas; the raw record describes every list, read, replace, and edit input, output, constraint, and output mode. PowerPoint and MCP are intentionally absent.

bobzhang/office-lib/xlsx provides the bounded mutation SDK behind the canonical creation and batch commands. It prefers xlsx.batch/2, retains exact xlsx.batch/1 behavior and shared resource accounting, validates complete candidates, and publishes through the shared async transaction boundary. See ../docs/office-xlsx-mutations.md.

The bobzhang/office-lib/docx package provides the preservation-safe SDK layer for editing existing DOCX files. Its async transact_docx entry point composes the A4 bounded read and atomic publisher with exact source-pinned byte-splice plans, strict archive-backed DOCX validation, and the authoritative transaction preservation report. It is deliberately not listed by office help yet: the package is the foundation for later user-facing DOCX commands, not a partial CLI promise.

#
OfficeError

pub(all) suberror OfficeError {
UnsupportedFileExtension(String)
InvalidPackage(String)
FormatMismatch(expected~ : DocumentFormat, actual~ : DocumentFormat)
ResourceLimit(kind~ : String, limit~ : Int, actual~ : Int)
Cancelled
} derive(Eq,
Debug
)

Errors produced while identifying a supported Office package.
impl Show for OfficeError

#
OfficeError::equal

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn OfficeError::equal(OfficeError, OfficeError) -> Bool

#
OfficeError::not_equal

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn OfficeError::not_equal(x : OfficeError, y : OfficeError) -> Bool

#
OfficeError::output

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn OfficeError::output(self : OfficeError, logger : &Logger) -> Unit

#
OfficeError::to_repr

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn OfficeError::to_repr(OfficeError) ->
Repr

#
OfficeError::to_string

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn OfficeError::to_string(self : OfficeError) -> String

#
SelectorError

pub(all) suberror SelectorError {
SelectorError(code~ : String, offset~ : Int, input~ : String, message~ : String)
}

A bounded, structured selector parse or validation failure. offset is a zero-based Unicode-scalar position in the original input; input is a bounded echo suitable for diagnostics.

#
SelectorError::output

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn SelectorError::output(self : SelectorError, logger : &Logger) -> Unit

#
SelectorError::to_string

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn SelectorError::to_string(self : SelectorError) -> String

#
CapabilityAction

pub(all) struct CapabilityAction {
name : String
requires : Array[String]
forbids : Array[String]
restrictions : Array[String]
}

The accepted argument shape and path restriction for one action value.

#
CapabilityCommand

pub(all) struct CapabilityCommand {
name : String
summary : String
usage : String
formats : Array[String]
aliases : Array[String]
inputs : Array[CapabilityField]
outputs : Array[CapabilityField]
output_modes : Array[String]
variants : Array[CapabilityVariant]
}

One implemented command exposed by the canonical Office command.

#
CapabilityField

pub(all) struct CapabilityField {
name : String
type_name : String
required : Bool
description : String
}

One declared input or output field in the Office capability registry.

#
CapabilityFormat

pub(all) struct CapabilityFormat {
name : String
aliases : Array[String]
description : String
selector : CapabilitySelector
}

One document format exposed by the canonical Office command.

#
CapabilitySelector

pub(all) struct CapabilitySelector {
schema : String
root : String
status : String
examples : Array[String]
description : String
}

The selector syntax declared for one document format. status describes the strongest implemented behavior and must not imply document access.

#
CapabilityVariant

pub(all) struct CapabilityVariant {
name : String
usage : String
result_schema : String
registry : Json?
inputs : Array[CapabilityField]
outputs : Array[CapabilityField]
constraints : Array[String]
actions : Array[CapabilityAction]
output_modes : Array[String]
}

One conditionally invokable subcommand schema within a command family.

#
CellAddress

pub struct CellAddress {
column : Int
row : Int
}

One validated XLSX A1 cell coordinate. Columns and rows are 1-based; construction stays package-private so invalid coordinates cannot render.

#
CellAddress::column

fn CellAddress::column(self : CellAddress) -> Int

Returns the validated 1-based column index (A = 1, XFD = 16384).

#
CellAddress::render

fn CellAddress::render(self : CellAddress) -> String

Renders this coordinate in canonical uppercase A1 form.

#
CellAddress::row

fn CellAddress::row(self : CellAddress) -> Int

Returns the validated 1-based row index (1 through 1048576).

#
DocumentFormat

pub(all) enum DocumentFormat {
Xlsx
Docx
} derive(Eq,
Debug
)

The document formats supported by the office facade.

#
DocumentFormat::equal

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn DocumentFormat::equal(DocumentFormat, DocumentFormat) -> Bool

#
DocumentFormat::name

fn DocumentFormat::name(self : DocumentFormat) -> String

A deterministic, lowercase name suitable for CLI and JSON output.

#
DocumentFormat::not_equal

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn DocumentFormat::not_equal(x : DocumentFormat, y : DocumentFormat) -> Bool

#
DocumentFormat::output

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn DocumentFormat::output(self : DocumentFormat, logger : &Logger) -> Unit

#
DocumentFormat::to_repr

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn DocumentFormat::to_repr(DocumentFormat) ->
Repr

#
DocumentFormat::to_string

#deprecated("implicit trait-method promotion is being removed; call via the trait")
fn DocumentFormat::to_string(self : DocumentFormat) -> String

#
OfficeSelector

pub struct OfficeSelector {
format : DocumentFormat
segments : ReadOnlyArray[SelectorSegment]
coordinate : SelectorCoordinate?
stability : SelectorStability
}

A parsed, format-explicit office.selector/1 address. Instances originate from the parser or syntax adapters so their canonical-form invariants hold.

#
OfficeSelector::coordinate

Returns the optional XLSX coordinate leaf.

#
OfficeSelector::document_format

fn OfficeSelector::document_format(self : OfficeSelector) -> DocumentFormat

Returns the document format named by this selector.

#
OfficeSelector::render

fn OfficeSelector::render(self : OfficeSelector) -> String

Renders this selector in its unique canonical form.

#
OfficeSelector::segments

fn OfficeSelector::segments(self : OfficeSelector) -> ReadOnlyArray[SelectorSegment]

Returns the validated path segments in document order.

#
OfficeSelector::stability

Returns whether this selector is stable across ordinary positional edits.

#
ProtocolError

pub(all) struct ProtocolError {
code : String
message : String
details : Json?
}

A structured failure carried by the office.output/1 protocol.

#
ProtocolWarning

pub(all) struct ProtocolWarning {
code : String
message : String
}

A structured, machine-actionable warning attached to an Office response.

#
SegmentSelection

pub enum SegmentSelection {
Position(Int)
Key(String, String)
}

The optional selector attached to a named path segment.

#
SelectorCoordinate

pub enum SelectorCoordinate {
Cell(CellAddress)
Range(CellAddress, CellAddress)
}

The XLSX-only coordinate leaf of an Office selector.

#
SelectorSegment

pub struct SelectorSegment {
name : String
selection : SegmentSelection?
}

One named segment in a canonical Office selector. Construction stays package-private so parsed selector invariants cannot be bypassed.

#
SelectorSegment::key_value

fn SelectorSegment::key_value(self : SelectorSegment, key : StringView) -> String?

Returns a named selector value when this segment uses key.

#
SelectorSegment::name

fn SelectorSegment::name(self : SelectorSegment) -> String

Returns the canonical name of this path segment.

#
SelectorSegment::position

fn SelectorSegment::position(self : SelectorSegment) -> Int?

Returns a positional selection when this segment uses one.

#
SelectorSegment::selection

Returns this segment's validated selection, if present.

#
SelectorStability

pub enum SelectorStability {
Stable
SnapshotRelative
}

Whether an address survives ordinary positional edits.

#
SCHEMA_CAPABILITIES

let SCHEMA_CAPABILITIES : String

Versioned schemas shared by capability declarations and result emitters.

#
SCHEMA_CAPABILITY

let SCHEMA_CAPABILITY : String

#
SCHEMA_DOCX_BATCH_RESULT

let SCHEMA_DOCX_BATCH_RESULT : String

#
SCHEMA_DOCX_CREATE_RESULT

let SCHEMA_DOCX_CREATE_RESULT : String

#
SCHEMA_DOCX_ELEMENT

let SCHEMA_DOCX_ELEMENT : String

#
SCHEMA_DOCX_OUTLINE

let SCHEMA_DOCX_OUTLINE : String

#
SCHEMA_DOCX_QUERY

let SCHEMA_DOCX_QUERY : String

#
SCHEMA_DOCX_TEXT

let SCHEMA_DOCX_TEXT : String

#
SCHEMA_DUMP_RESULT

let SCHEMA_DUMP_RESULT : String

Versioned replayable dump schema emitted by office dump.

#
SCHEMA_FINDING_RECORD

let SCHEMA_FINDING_RECORD : String

Versioned finding record carried by validate/issues results.

#
SCHEMA_ISSUES_RESULT

let SCHEMA_ISSUES_RESULT : String

Versioned result schema emitted by office issues.

#
SCHEMA_PREVIEW_RESULT

let SCHEMA_PREVIEW_RESULT : String

Versioned result schema emitted by office preview.

#
SCHEMA_RAW_CHANGE

let SCHEMA_RAW_CHANGE : String

#
SCHEMA_RAW_INVENTORY

let SCHEMA_RAW_INVENTORY : String

#
SCHEMA_RAW_PART

let SCHEMA_RAW_PART : String

#
SCHEMA_RAW_RESULT

let SCHEMA_RAW_RESULT : String

#
SCHEMA_REPLAY_RESULT

let SCHEMA_REPLAY_RESULT : String

Versioned result schema emitted by office replay.

#
SCHEMA_TEMPLATE_RESULT

let SCHEMA_TEMPLATE_RESULT : String

#
SCHEMA_TRANSACTION

let SCHEMA_TRANSACTION : String

#
SCHEMA_VALIDATE_RESULT

let SCHEMA_VALIDATE_RESULT : String

Versioned result schema emitted by office validate.

#
SCHEMA_XLSX_BATCH_RESULT

let SCHEMA_XLSX_BATCH_RESULT : String

#
SCHEMA_XLSX_CREATE_RESULT

let SCHEMA_XLSX_CREATE_RESULT : String

#
SCHEMA_XLSX_ELEMENT

let SCHEMA_XLSX_ELEMENT : String

#
SCHEMA_XLSX_OUTLINE

let SCHEMA_XLSX_OUTLINE : String

#
SCHEMA_XLSX_QUERY

let SCHEMA_XLSX_QUERY : String

#
SCHEMA_XLSX_TEXT

let SCHEMA_XLSX_TEXT : String

#
SELECTOR_MAX_DEPTH

let SELECTOR_MAX_DEPTH : Int

Maximum number of segments after the format root.

#
SELECTOR_MAX_LENGTH

let SELECTOR_MAX_LENGTH : Int

Maximum canonical selector length in Unicode scalar values.

#
SELECTOR_MAX_NAME_LENGTH

let SELECTOR_MAX_NAME_LENGTH : Int

Maximum segment or key name length.

#
SELECTOR_MAX_SELECTIONS

let SELECTOR_MAX_SELECTIONS : Int

Maximum number of bracketed selectors, including an XLSX coordinate leaf.

#
SELECTOR_MAX_VALUE_LENGTH

let SELECTOR_MAX_VALUE_LENGTH : Int

Maximum decoded named-selector value length in Unicode scalar values.

#
XLSX_TRANSACTION_MAX_CANDIDATE_ARCHIVE_BYTES

let XLSX_TRANSACTION_MAX_CANDIDATE_ARCHIVE_BYTES : Int

Maximum aggregate uncompressed bytes retained in a generated XLSX archive before ZIP output sizing and allocation.

#
XLSX_TRANSACTION_MAX_CANDIDATE_ENTRY_BYTES

let XLSX_TRANSACTION_MAX_CANDIDATE_ENTRY_BYTES : Int

Maximum uncompressed bytes retained for one generated XLSX archive entry.

#
XLSX_TRANSACTION_MAX_DECODED_XML_BYTES

let XLSX_TRANSACTION_MAX_DECODED_XML_BYTES : Int

Maximum aggregate XML bytes decoded by one transaction-backed XLSX parse. Together with the token and cell ceilings, this consumes a bounded slice of the shared transaction working reserve.

#
XLSX_TRANSACTION_MAX_MATERIALIZED_CELLS

let XLSX_TRANSACTION_MAX_MATERIALIZED_CELLS : Int

Maximum concrete worksheet cells retained by a transaction-backed workbook.

#
XLSX_TRANSACTION_MAX_ROW_COLUMN_LINES

let XLSX_TRANSACTION_MAX_ROW_COLUMN_LINES : Int

Maximum row/column dimension records an Office batch may project before it applies the plan to a workbook.

#
XLSX_TRANSACTION_MAX_XML_MARKUP_TOKENS

let XLSX_TRANSACTION_MAX_XML_MARKUP_TOKENS : Int

Maximum XML markup-token starts scanned by one transaction-backed parse.

#
capabilities_data

fn capabilities_data(format? : DocumentFormat, operation? : String) -> Json

Returns the versioned capability inventory used by JSON help output.

#
capability_commands

fn capability_commands() -> Array[CapabilityCommand]

Returns implemented command declarations in stable order. An empty formats array marks a format-neutral command.

#
capability_fingerprint

fn capability_fingerprint() -> String

Returns the deterministic CRC-32 fingerprint of every registry declaration.

#
capability_formats

fn capability_formats() -> Array[CapabilityFormat]

Returns the canonical document-format declarations in stable order.

#
capability_records

fn capability_records(format? : DocumentFormat, operation? : String) -> Array[Json]

Returns self-contained registry records in stable order. With a format filter, format-neutral commands are omitted and only commands that operate on that document format remain.

#
detect_archive_format

fn detect_archive_format(path : StringView, archive :
Archive
, max_xml_part_bytes? : Int, max_xml_total_units? : Int, cancelled? : () -> Bool) -> DocumentFormat raise OfficeError

Identifies a structurally valid XLSX or DOCX package from an archive that the caller has already materialized. This lets resource-constrained callers parse with their own ZIP limits without parsing the package a second time.

#
detect_format

fn detect_format(path : StringView, data : BytesView, max_package_bytes? : Int, max_archive_entries? : Int, max_entry_uncompressed_bytes? : Int, max_total_uncompressed_bytes? : Int, max_xml_part_bytes? : Int, max_xml_total_units? : Int, cancelled? : () -> Bool) -> DocumentFormat raise OfficeError

Identifies a structurally valid XLSX or DOCX package.

The file extension and the OOXML main-part content type must agree. The corresponding portable package validator then checks the package before the format is returned.

#
find_capability_command

fn find_capability_command(value : StringView) -> CapabilityCommand?

Finds an implemented command by canonical name or alias.

#
output_failure

fn output_failure(error : ProtocolError, warnings? : Array[ProtocolWarning]) -> Json

Wraps a command failure in the deterministic office.output/1 envelope. The warnings member is omitted when there are no warnings.

#
output_success

fn output_success(data : Json, warnings? : Array[ProtocolWarning]) -> Json

Wraps successful command data in the deterministic office.output/1 envelope. The warnings member is omitted when there are no warnings.

#
parse_selector

fn parse_selector(source : String) -> OfficeSelector raise SelectorError

Parses and validates one bounded, format-explicit office.selector/1 address. The returned AST is the adapter boundary for later resolvers.

#
protocol_error

fn protocol_error(code : String, message : String, details? : Json) -> ProtocolError

Creates a structured Office protocol error.

#
protocol_warning

fn protocol_warning(code : String, message : String) -> ProtocolWarning

Creates a warning for an Office protocol response.

#
resolve_format_alias

fn resolve_format_alias(value : StringView) -> DocumentFormat?

Resolves a canonical format name or supported alias. Matching is ASCII case-insensitive; PowerPoint aliases are deliberately absent.

#
selector_for_xlsx_cell

fn selector_for_xlsx_cell(sheet_name : String, address : String) -> OfficeSelector raise SelectorError

Builds a canonical, syntax-validated selector for one cell on a named worksheet. It does not look up the sheet or cell in a workbook.

#
selector_for_xlsx_range

fn selector_for_xlsx_range(sheet_name : String, range : String) -> OfficeSelector raise SelectorError

Builds a canonical, normalized selector for one rectangular range on a named worksheet. It does not look up the sheet or range in a workbook.

#
selector_for_xlsx_sheet

fn selector_for_xlsx_sheet(sheet_name : String) -> OfficeSelector raise SelectorError

Builds a stable canonical selector for one named worksheet or chart sheet. It validates and quotes the name but does not look it up in a workbook.

#
selector_for_xlsx_workbook

fn selector_for_xlsx_workbook() -> OfficeSelector raise SelectorError

Builds the canonical selector for the workbook singleton.

#
selector_from_docx_projection_path

fn selector_from_docx_projection_path(path : String) -> OfficeSelector raise SelectorError

Converts the DOCX projection paths already emitted by docx text and docx get into the shared canonical selector AST. This adapts syntax only; it does not load a package or resolve the path.

#
sha256_hex

fn sha256_hex(data : BytesView) -> String

Returns the SHA-256 digest of data as a 64-character lowercase hex string.

This is the content digest for office.dump/1 provenance records (source.sha256) and content-addressed asset ids (sha256-<hex>). Deterministic and pure MoonBit on every backend (delegates to moonbitlang/x/crypto), verified against the FIPS 180-2 test vectors in digest_test.mbt.

Example

test {
inspect(
@office.sha256_hex(b"abc"),
content="ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
)
}

Powered by MoonBit

Site sourceReport issuePackagesBuild queueSkillsStatistics

© 2026 mooncakes.io