# Composition Plans Scripting API

The versioned JSON document is the authoritative composition-plan definition.
The scripting API exposes the operations needed to validate and execute that
JSON. There is no public object-builder alternative.

## Data View

| Method | Returns | Purpose |
| --- | --- | --- |
| `ecSelectionRoot()` | `ecDataNode` | Capture the current selection hierarchy, including records inside collapsed selected groups. |
| `paginate(item, dataNode?)` | none | Populate a page item from the supplied node, or from the current panel selection when omitted. |
| `ecCreateCatalogComposition(logging?)` | `ecCompositionSession` | Begin a transactional composition session; optional logging defaults to false. |

`dsv.ecSelectionRoot()` and the data-node methods require EasyCatalog Scripting,
but do not require Pagination or a composition session. A node passed to
`dsv.paginate()` must belong to the same data source as the Data View. Its full
hierarchy and ordering are used without consuming the node or changing the
panel selection. Populating pagination containers still requires Pagination.

## Composition session

| Method | Returns | Purpose |
| --- | --- | --- |
| `ecSelectionRoot()` | `ecDataNode` | Root of the selected EasyCatalog hierarchy. |
| `ecCompositionManifest()` | `String` | Returns the composition grammar, selected data and document resources, together with `scriptingDocumentation` for this build and `sampleScripts` for hosted examples. |
| `ecValidateCompositionPlanJSON(json)` | `String` | Validate the declarative schema and semantics without composing. |
| `ecCheckCompositionPlanJSON(json, options?)` | `String` | Run a contract, resolution or rollback-safe layout check. |
| `ecNewLayoutArea(target, insideMargins?)` | `ecLayoutArea` | Create a real page, spread or EasyCatalog-container target area. |
| `ecFinish()` | `Boolean` | Commit output and release temporary composition objects. |
| `ecCancel()` | `Boolean` | Roll back output created by the session. |

Read-only session properties are `finished`, which becomes true after
`ecFinish()` or `ecCancel()`, and `log`, which contains the accumulated
structured JSON operation log.

For `ecNewLayoutArea()`, a page item target must be an EasyCatalog container.
Container areas use the container's inner path bounds; `insideMargins` applies
only to page and spread targets.

`ecCheckCompositionPlanJSON()` options are:

```javascript
{
  mode: "contract" | "resolve" | "layout",
  target: pageOrSpreadOrContainer,
  insideMargins: false,
  maximumAreas: 2,
  maximumDepth: 16
}
```

`contract` checks portable JSON only. `resolve` compiles against the selected
EasyCatalog hierarchy and initial target context, evaluates declarative
properties for the resolved data, and verifies required formatting rules and
rule sets without placing or populating output. `layout` adds a bounded trial
composition, so it also tests fit, overflow and continuation behaviour. Resolve
and layout checks are transactional and leave the document unchanged.

### Persistent document cursors

The pagination sample also uses this small resumability extension:

| Method | Returns |
| --- | --- |
| `ecOpenDocumentCursor(document, name, create?, startTarget?, insideMargins?)` | `ecLayoutArea` |
| `ecUpdateDocumentCursor(name, area)` | `Boolean` |
| `ecDocumentCursorState(document, name)` | `String` |
| `ecRemoveDocumentCursor(document, name)` | `Boolean` |

## Data node

The data-node API lets scripts inspect and reshape an EasyCatalog hierarchy.
It is also useful in regular scripts that do not use composition plans. Field
values remain connected to the underlying EasyCatalog data; a node is not a
detached data export. Shaping methods return new hierarchies without changing
the source node or the Data View selection.

| Member | Returns | Purpose |
| --- | --- | --- |
| `name`, `type`, `level`, `path`, `count` | scalar | Structural identity; count is the number of immediate children. |
| `indexInGroup`, `isFirstInGroup`, `isLastInGroup` | scalar | Occurrence context. |
| `ecChildren()` | `ecDataNode[]` | Immediate children. |
| `ecRecords()` | `ecDataNode[]` | Recursive record nodes, including records in child levels. |
| `ecField(name)` | `String` | Raw field value. |
| `ecFormattedField(name)` | `String` | Formatted field value. |
| `ecTabularField(name)` | `ecDataNode` | Enhanced-tabular hierarchy for one record. |
| `ecGroupBy(fields)` | `ecDataNode` | Group regular records by one field or an array of fields, ordered outermost to innermost. Only consecutive matching values share a group; this method does not sort. |
| `ecUngroup(sortField?, sortOrder?, filterField?, filterValue?, maximumRecords?)` | `ecDataNode` | Flatten the hierarchy, optionally sorting, filtering and limiting records. Call `ecUngroup()` to preserve traversal order with no filter or limit. |
| `ecFilter(field, operator, value?)` | `ecDataNode` | Keep matching record branches, preserving source order and surviving groups. |
| `ecSort(field, order?)` | `ecDataNode` | Stable sort of records within each group, recursively; default order is ascending. Group order and positions remain unchanged. |
| `ecSlice(start, count)` | `ecDataNode` | Keep a range of record branches across groups, using a zero-based start and a count, not an end index. |
| `ecDifference(excluded)` | `ecDataNode` | Exclude records present in another node by underlying record identity, preserving source order and surviving groups. |

`ecFilter()` accepts `equals`, `notEquals`, `lessThan`, `lessThanOrEqual`,
`greaterThan`, `greaterThanOrEqual`, `contains`, `startsWith`, `endsWith`,
`isEmpty` and `isMissing`. The value is required except for `isEmpty` and
`isMissing`. Numeric and date fields use their native values; text comparisons
are case-insensitive. Ordinary comparisons exclude missing or empty values.

`ecSort()` accepts `ascending` or `descending`. Equal values keep their prior
order; missing and empty values sort last in either direction. Flatten first
with `ecUngroup()` to sort all records together. For multiple keys, sort the
secondary key first and the primary key last.

`ecFilter()`, `ecSlice()` and `ecDifference()` remove groups left empty and
their empty ancestors. Sorting also removes empty groups. Filtering and slicing
treat a record with child levels as one branch, retaining its descendants.
Consequently, `ecRecords().length` can exceed a slice's count for nested
relational data. Removing a record with `ecDifference()` also removes its
descendants; neither input node is changed.

Both slice arguments must be non-negative integers. A zero count or a start
beyond the available records returns an empty root. In contrast, the optional
`ecUngroup()` maximumRecords argument defaults to zero, meaning no limit. Its
legacy filter compares formatted values exactly; use `ecFilter()` for the
comparison operators above.

For example, populate a selected page item with at most five records and keep
a separate node containing the remaining records:

```javascript
var dsv = app.easycatalogObject.selectedDataView();
if (!dsv || app.selection.length !== 1) {
    throw new Error("Select an EasyCatalog Data View and one page item first.");
}
var source = dsv.ecSelectionRoot().ecUngroup();
var batch = source.ecSort("ID", "descending").ecSlice(0, 5);
var remaining = source.ecDifference(batch);
dsv.paginate(app.selection[0], batch);
```

To create X groups with Y subgroups, substitute your field names here:

```javascript
var grouped = source.ecUngroup()
    .ecSort("Y", "ascending") // Secondary key first.
    .ecSort("X", "ascending") // Primary key last; keeps Y ordered within X.
    .ecGroupBy(["X", "Y"]);   // X -> Y -> records.
```

Composition plans express their own collection and shaping through JSON data
selectors, collectors and `shape`. The scripting methods above do not define
plan structure.

## Layout area

| Method | Returns | Purpose |
| --- | --- | --- |
| `ecNewCompositionPlanFromJSON(json)` | `ecCompositionPlan` | Compile authoritative JSON for this area. |

Useful read-only properties are `width`, `height`, `isEmpty` and `isOverset`.

## Composition plan

| Method | Returns | Purpose |
| --- | --- | --- |
| `ecCompose(maximumAreas?, maximumDepth?, progress?)` | `ecCompositionResult` | Execute the compiled JSON plan. |

The progress callback receives composition context and returns `false` to cancel.

## Composition result

Read-only result properties are:

- `success`
- `cancelled`
- `error`
- `placedCount`
- `areaCount`
- `insertedBoundaryPageCount`
- `insertedBoundarySpreadCount`
- `details`, containing the structured JSON execution report

`details.diagnostics` is the stable machine-readable failure contract. Each
entry contains `code`, `level`, `message`, `stage`, `path` and `recoverable`;
runtime entries add `thread`, `section` and `areaIndex` when those contexts are
known. Treat `code` and `path` as authoritative rather than matching `error`
text. `details.logs` remains the chronological human-readable operation log.

## Declarative runtime decisions

Production JSON cannot bind ExtendScript callbacks. Conditional inclusion,
dynamic section properties and parent selection are expressed by declarative
JSON expressions in `when`, `propertyResolver` and `parentSelector`. This keeps
the persisted plan authoritative, statically checkable and fully explainable.

The optional function passed to `ecCompose()` is only a progress/cancellation
observer. It cannot change the structure, assets or data selected by the plan.

## Physical plan formatting rules

To build a reusable formatting rule whose root is a composition-plan container:

```javascript
pageItem.ecCompositionPlanJSON = planText;
app.easycatalogObject.newFormattingRule(pageItem, "Product Card");
```

The JSON is persisted with the physical EasyCatalog container. The plan is not
reconstructed through scripting builder calls.

For a Threadable physical container, JSON `continuation.container` may extend
the linked container thread onto a newly inserted page or spread after all
authored members are full. The JSON owns the extension kind, optional custom
size, page/spread/spine position and safety limit. The existing container
Threadable property remains the single runtime gate. A declarative
`continuation.parentSelector` is resolved from the first pending data node
before the new parent is applied. No scripting continuation builder or
container-extension property is exposed.
