Skip to content

chore(builder): merge the template builder (preview packages) - #316

Merged
vaceslav merged 182 commits into
mainfrom
feature/builder
Dec 2, 2026
Merged

vaceslav merged 182 commits into
mainfrom
feature/builder

Conversation

@vaceslav

@vaceslav vaceslav commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Merges the template builder (epic #261) from feature/builder into main: code-first generation of Templify templates (.docx and .odt) from C# or from a JSON definition.

Packages (preview, 0.x)

  • TriasDev.Templify.Builder: composers, style sheet, tables, lists, images, header/footer, TOC, conditionals and loops, data contract, localisation, JSON definitions (import/export, schema, outline, patch, preview) and the upload check (TemplateInspector). It ships with the typed path source generator in analyzers/dotnet/cs.
  • TriasDev.Templify.Builder.Testing: a verification kit for consumers.

The whole API is experimental: [assembly: Experimental("TPLB001")]. Consumers opt in with <NoWarn>TPLB001</NoWarn>. Breaking changes are allowed in 0.x and no compatibility is promised. See docs/for-developers/template-builder.md#preview-status.

Release

  • release-please has a second component src (excluding src/TriasDev.Templify), with version.txt, its own changelog and initial-version: 0.1.0.
  • The core component excludes the builder projects, the generator, the sample, the builder tests and docs. Core release notes therefore stay unchanged.
  • The builder packages depend on the core version of the same commit, which is 1.11.0 now. The release workflow refuses a builder release while that core version is not on nuget.org (check-core-released.sh). check-builder-package.sh checks the nuspec dependencies.
  • NuGet Trusted Publishing: the templify-release policy (owner TriasDev, release-please.yml, environment nuget) now covers TriasDev.Templify and TriasDev.Templify.Builder*. The TriasDev prefix is reserved for the organisation. build(builder): release setup for the first preview #289 stays open until the first preview is published.

Core impact

Verification

Issues

Closes #260, #262, #263, #264, #265, #266, #267, #268, #269, #270, #274, #277, #278, #279, #280, #281, #282, #283, #284, #285, #286, #287, #288, #290, #291, #292, #293, #294, #295, #296, #297, #298.

Stay open:

Merge with a merge commit, not squash. The branch history keeps the builder's conventional commits for its first changelog.

Public API direction, internal architecture, DOCX/ODT mapping, verification,
packaging and the phase plan for the code-first template builder (epic #261).
Includes the results of the two spikes: the upload check through
ValidateTemplate with a witness payload (gap filed as #271) and a box as a
one-cell table in both engines.
…cx and .odt (#262)

New package TriasDev.Templify.Builder (0.1.0, own version line) and its test
project. A definition describes paragraphs with literal text and values;
TemplateBuilder.Build writes them as DOCX or ODT, deterministically.

- Public API: ITemplateDefinition, TemplateIdentity, TemplateBuildOptions,
  TemplateBuilder, GeneratedTemplate (bytes, stream, media type, ContentHash),
  TemplateBuildException/BuildDiagnostic, TemplatePath, TemplateComposer,
  BlockComposer, InlineComposer.
- DocxWriter builds the XML with the OpenXML SDK's typed elements and writes
  the package itself: the SDK's packaging gives random relationship ids, a
  random core-properties part name and the current time on every entry.
- OdtWriter writes ODF 1.3 with XLinq; literal white space is encoded so it
  renders exactly. DeterministicZip fixes order, timestamps and attributes.
- Tests: every build passes ValidateTemplate, fills through the engine, passes
  OOXML schema validation / the ODT package checks, and gives the same bytes
  across builds and cultures; LibreOffice round trips for both formats.

Closes #262
…re releases

The core release-please package skips commits whose files all lie in
src/TriasDev.Templify.Builder or tests/TriasDev.Templify.Builder.Tests, so
builder work does not bump TriasDev.Templify. The builder gets its own
release-please component before its first preview release (#261).
…leton

- Spec: the DOCX writer assembles the package itself (the SDK's packaging is
  not deterministic), path syntax is checked where the path is written,
  DeterministicZip is reproducible per OS family, release setup until the
  first preview.
- CLAUDE.md: the builder and its test project in the solution structure.

Closes #270
…d character styles (#263)

Templates get real named styles in both formats, so a downloaded copy stays
editable in Word and LibreOffice and a product's theme drives the design.

- Values: Length (integer 1/1000 pt; 12.Pt(), 25.Mm()), Color (FromHex,
  FromRgb), FontFace (referenced by name, not embedded), TextAlignment.
- ParagraphStyleKey / CharacterStyleKey (id + display name; ids reserved by
  the builder are rejected). StyleSheet.Create: defaults (font, size, colour);
  paragraph styles with BasedOn, Next, font, size, colour, bold, italic,
  spacing, line height (exact, minimum, proportional), alignment, indents,
  keep-with-next, keep-together, outline level; character styles.
- TemplateComposer.Styles and .Properties (title, author, subject);
  Paragraph(style, …) overloads.
- Build reports every style problem at once: duplicate ids or names, unknown
  BasedOn/Next, BasedOn cycles, a style used but not defined, Styles set twice.
  Out-of-range values throw where they are written.
- DOCX: styles.xml (docDefaults with w:lang, Normal, DefaultParagraphFont,
  custom styles; schema order), w:pStyle on paragraphs, core properties.
- ODT: font-face declarations, default style with fo:language/fo:country,
  Standard, named styles with display names; paragraphs whose style has an
  outline level (also through BasedOn) are written as text:h.
- Tests: style XML in both formats, no direct formatting, all diagnostics,
  units and colours, and LibreOffice converting DOCX→ODT and ODT→DOCX keeps
  the display names.

Closes #263
…lt-in style names

Measured in #263: LibreOffice translates a DOCX style named like a built-in
Word style (Body Text) to its own (Text body); own names survive.
…, line and page breaks (#264)

- InlineComposer: Text(text, style), Value(path, format, style) overloads,
  Tab(), LineBreak(). A value takes its run's / span's character style, which
  the engine keeps when it fills the placeholder.
- ValueFormat: the engine's specifiers as a closed set — Date, Number,
  Currency, Uppercase, Lowercase, Raw, the boolean formats, Join (item path,
  quoted separator with escapes) — plus Custom for registered formatters.
  Arguments are checked against the placeholder grammar (no '}', no '{{').
- Literal text containing '{{', also across adjacent pieces, is a build
  error (TB1002): Templify has no escape for it.
- BlockComposer.PageBreak(): a paragraph of its own (DOCX w:br type=page;
  ODT empty paragraph with fo:break-after=page in the automatic style
  TemplifyPageBreak), so it survives when the engine removes the paragraphs
  around it. Style ids starting with 'Templify' are reserved.
- ODT: character styles as text:span; white-space encoding carries over span
  boundaries.
- Tests: every format against TextTemplateProcessor as the oracle, styles on
  runs and spans before and after filling, the brace guard, page breaks
  (LibreOffice: 2 pages vs 1), LibreOffice text of styled inline content.

TabRight() moves to page setup (task 9): it needs the frame width.

Closes #264
… emitter, Switch with mandatory Default (#265)

- Condition: a small AST built from TemplatePath (Eq/NotEq for text and
  numbers, Gt/Ge/Lt/Le, In, Contains/StartsWith/EndsWith, Exists, IsEmpty,
  IsNotEmpty, truthiness by implicit conversion) and combined with !, & and |
  (also declared on TemplatePath, since C# does not use the implicit
  conversion to find operators for two paths). Condition.Raw for text the
  typed API does not cover, checked with ConditionEvaluator.Validate.
- One emitter writes the engine's syntax: precedence with parentheses only
  where needed (not of a compound operand is parenthesised for readability),
  quoted and escaped strings, decimal numbers (the lexer has no exponent),
  [keyword] escaping of paths named like operators.
- BlockComposer.If(...).ElseIf(...).Else(...): Else returns void, so the
  order Templify requires is the only one that can be written; misuse after
  Else or outside the lambda throws.
- BlockComposer.Switch(value, cases): an if/elseif/else chain with
  value = "x" / value in (...); Default is mandatory (TB3001), duplicate
  case values are an error (TB3002); no cases writes the default as is.
- Markers are single-run paragraphs in BuilderStyles.TemplateMarker
  ("Template Marker": Courier New 8 pt grey, kept with next), written only
  when used; a style sheet may redefine it.
- Tests: emitter output (validated by the engine's parser), 18 conditions
  evaluated by the engine in both formats, elseif chains with nesting,
  marker paragraphs and style, page breaks inside a false branch, switch
  cases and default, diagnostics, LibreOffice text of the filled document.

Closes #265
…r access; components (#266)

- BlockComposer.ForEach(collection, itemName, (item, body) => …) writes
  {{#foreach item in collection}} … {{/foreach}} with an always-named
  iteration variable. LoopItem: Self, item["path"], Index/Number/Count
  (values) and IsFirst/IsLast (conditions).
- Paths remember their loop. Build reports a loop variable used outside its
  loop (TB4001), metadata of an outer loop inside a nested one (TB4002: the
  engine's metadata is the innermost loop's) and a root path hidden by a
  loop variable of the same name (TB4003). Item names are checked where
  written: no keywords, no name of an enclosing loop.
- ITemplateComponent + BlockComposer.Component: reusable content composed in
  the caller's loop scope; the model keeps the component as a unit
  (ComponentBlock), the hook for exporting definitions later (#274).
- If, Switch and Value check the scope of every path they use.
- Tests: nested loops with outer and root access and metadata in both
  formats, marker text, loops in conditionals and conditionals on items,
  loops over scalars, item-name and scope diagnostics, a component at the
  root and inside a loop, LibreOffice text of nested loops.

Closes #266
…load (#267)

Every build describes the data it needs (GeneratedTemplate.Contract).

- DataContract: entries (canonical path + usage Value/Collection/Condition)
  collected from values, every condition path (Switch values, the declared
  uses of Condition.Raw), loop collections and component content; loop
  metadata is left out. Loop variables resolve to canonical paths:
  line.description in a loop over order.lines → order.lines[].description.
- Hash: SHA-256 over the sorted entries, independent of language, format and
  theme — equal for every build of a definition.
- ToJson / FromJson (versioned; the hash is recomputed).
- CreateWitness: nested dictionaries with one item per collection and "x"
  per leaf. Filling a template with its own witness raises no missing
  variable and no warning, in both formats.

Closes #267
- TemplateStamp (template id, version, contract hash, language, builder and
  minimum engine version) is written into every template: DOCX
  docProps/custom.xml, ODT meta:user-defined, names prefixed 'Templify.'.
  GeneratedTemplate.Stamp; filled documents keep it.
- TemplateInspector.Inspect: format and stamp of any template.
- TemplateInspector.CheckUpload: syntax (ValidateTemplate), origin by stamp
  (CurrentContract, DifferentContract, OtherTemplate, Unknown) and the paths
  the copy uses that the current contract does not provide — through
  ValidateTemplate with the contract's witness, so hand-edited copies with
  renamed loop variables work. Condition variables are read from the warning
  message until the engine exposes them (#275); comparison operands follow
  with #271.
- TemplateStampRemover.Remove: strips only the builder's properties from a
  filled DOCX/ODT, in place, for documents sent to external recipients.
- Tests: stamp round trip, survives filling, removal keeps other properties
  and the content, upload checks for unchanged, older, hand-cut, renamed,
  broken, unstamped and foreign templates in both formats.

Closes #268
…s the build (#269)

One definition builds every language; a missing text is a build error, not
a silent fallback to the default language.

- ITextCatalog and TextCatalog: FromDictionary (key → language → text),
  FromResourceManager (satellites, plus the neutral resources only for a
  declared neutral language), Combine (later catalogs override), Empty.
  Lookups go from the specific to the neutral culture, never to the
  invariant culture.
- TemplateBuildOptions.Texts; TemplateComposer.Texts (TemplateTexts:
  indexer and Language). Every missing (key, language) is collected once and
  reported with the other errors (TB5001).
- Texts with '{{' are caught by the literal guard like any literal.
- Test harness: build options (language, texts) flow into the fill and the
  determinism check.
- Tests: one definition in two languages and both formats with the same
  contract hash, filled; aggregated missing keys; fallback rules for
  dictionaries and resource managers; Combine.

Closes #269
…TabRight (#277)

- TemplateComposer.Page(p => …): size (A4, A5, Letter, Legal, custom),
  margins, header/footer distances; Header and Footer as block containers
  (paragraphs, values, conditions, components); FirstPage with its own
  header/footer or NoHeader/NoFooter. Without Page a template is A4 with
  25 mm margins — page setup is always written, so documents do not depend
  on the opening application's defaults.
- Inline PageNumber()/PageCount() (optionally styled) and TabRight(): a
  right tab stop at the end of the text frame (moved from #264).
- DOCX: header/footer parts with fixed relationship ids, sectPr (pgSz, pgMar,
  titlePg), PAGE/NUMPAGES complex fields, w:tabs at the frame width.
- ODT: page layout and master page "Standard" with header/footer and ODF 1.3
  header-first/footer-first; ODF's header geometry mapped so the body starts
  where Word starts it; right tab stops as automatic paragraph styles, offset
  by the style's start indent (ODF measures from the indent).
- Header/footer content counts for the data contract, style checks and the
  marker style. Page set twice (TB6001), no room for text (TB6002).
- Tests: page geometry in both formats, header/footer parts and master page,
  filled headers with values and conditions, page fields, contract; with
  LibreOffice + poppler: headers/footers and page numbers per page of the PDF
  and the right tab ending at the right margin in both formats.

Closes #277
…g, spans, header row (#278)

- BlockComposer.Table(t => …): Columns (Fixed widths, Relative weights that
  share what the fixed columns leave of the container frame), Style,
  SpaceAfter, HeaderRow (repeats on every page; header rows come first), Row.
- RowComposer.Cell(text | value | cell => …) and AllowSplit (rows are kept on
  one page by default). CellComposer derives from BlockComposer, so a cell
  holds any block content — paragraphs, conditions, loops, nested tables —
  plus ColumnSpan, Background and VerticalAlignment. BlockComposer is no
  longer sealed (internal constructor: no outside subclasses).
- TableStyleKey + StyleSheetComposer.Table: outer border, row and column
  rules, header rule and background, cell padding — a builder concept each
  writer turns into the format's own formatting.
- Nested tables resolve relative columns against their cell's width.
- Build reports tables without columns (TB7001), fixed columns wider than the
  container (TB7002), rows whose cells do not span the columns (TB7003) and
  undefined table styles. Cell content counts for the contract, style checks
  and markers.
- DOCX: fixed layout, tblGrid from the resolved widths and tcW as the sum of
  the rounded grid columns (no stale grid), borders, shading, gridSpan,
  vAlign, cantSplit/tblHeader; a paragraph between touching tables.
- ODT: automatic table/column/row/cell styles (equal cells share one),
  collapsed per-cell borders, header rows, covered cells.
- Tests: XML of both formats, filling, nested widths, diagnostics, contract;
  LibreOffice + poppler: the header row repeats on page 2 and the columns
  start at the computed positions in the PDF of both formats.

Closes #278
…ps inside cells (#279)

- TableComposer.ForEachRow(collection, itemName, (item, rows) => …) and
  RowsIf(condition, rows => …).ElseIf(…).Else(…); RowsComposer for rows,
  nested row conditionals and nested row loops inside them. Loop scope rules
  (#266) apply to rows and their cells.
- Writers emit marker rows: one cell over the whole grid (DOCX gridSpan +
  full tcW, ODT number-columns-spanned + covered cells) with the marker
  paragraph, which the engine removes.
- Contract: row loop collections and row conditions; markers in rows trigger
  the marker style.
- Fix: a DOCX body, header or footer now always ends with a paragraph. A
  DOCX whose body ended with a table made LibreOffice 26.8's text export loop
  forever (Word keeps that paragraph anyway).
- Tests: row loop with a conditional row and a paragraph loop in a cell, a
  table-level if/else row, empty collections, nested row loops, tables in a
  paragraph loop, marker row shape, contract, scope and cell-count errors,
  LibreOffice text of the filled table and of a table at the end.

Closes #279
…NG/JPEG, alt text, fit (#280)

- ImageSource.Png / Jpeg / FromBytes: pixel size and resolution read from
  the file (PNG IHDR/pHYs, JPEG SOF/JFIF; 96 dpi when none), no new
  dependency — a customer's logo passes in as a theme slot.
- ImageFit: Natural, Width, Height, Within(box); the aspect ratio is kept.
- InlineComposer.Image(...) and BlockComposer.Image(...) (optionally in a
  paragraph style); the alternative text is required.
- DOCX: word/media with each distinct image once, relationships per part
  (body, each header/footer), inline DrawingML with document-wide unique
  docPr ids and the alt text as descr.
- ODT: Pictures/ named by content + manifest entries, draw:frame as a
  character with svg:title/svg:desc.
- Tests: parsing and resolution, fitting, per-part relationships and
  deduplication, ids after the engine clones image rows, ODT frames and
  manifest; LibreOffice + pdfimages: all six images render in both formats.

Closes #280
The CI build (warnings as errors) rejected two private static fields without
the '_' prefix (IDE1006).
- InlineComposer.If(condition, text => …).ElseIf(…).Else(…): text shown by a
  condition inside one paragraph; TextComposer allows text and values
  (optionally styled) and nested inline conditionals, no tabs, breaks or
  images. Separators can sit inside the guard of the piece they precede.
- InlineComposer.Expression(condition, format): {{(condition):yesno}} in the
  engine's stricter inline dialect.
- Writers place the markers as plain runs/text around the branch content;
  the contract records condition and expression paths; style, scope and
  literal-brace checks reach into branches.
- Tests: address line with guarded separators, elseif/else with nesting,
  expressions with yesno/checkbox and strict truthiness, a paragraph holding
  only an inline conditional, styled branch text, contract, misuse;
  LibreOffice text of the resolved paragraphs.

Closes #281
…rojects

The builder package is src/ minus src/TriasDev.Templify, so commits to the
test kit and the generator count for the builder (additional-paths is not a
release-please option and was ignored). version.txt and CHANGELOG.md stay in
src/TriasDev.Templify.Builder (version-file, changelog-path). initial-version
instead of release-as. Core excludes the generator project and docs/, so
builder commits stay out of the core release notes.
… on PRs

publish-builder built and packed with -p:Version, a global property that also
versioned the referenced core project: the builder package depended on
TriasDev.Templify >= 0.1.0 (NuGet resolves core 1.0.0). version.txt is the
version source; the job now checks it against the release, and checks the
packed dependencies (builder → core version, test kit → builder version).
CI packs the builder packages with the same check, and on the builder's
release PR checks that the core it needs is released (before a tag exists).
Outputs follow the builder package's new path (src).
…tor (#274)

JsonSchema.Net ships under a maintenance-fee EULA for commercial users. The
schema TemplateJson.Schema writes uses a handful of draft 2020-12 keywords; a
small validator for exactly those (any other keyword fails the test) keeps the
same tests: the sample export and every vocabulary example are valid, unknown
keys, bad lengths, unknown components and misspelled parameters are not.
Its binary packages ship under the Open Source Maintenance Fee EULA; the
tests use their own validator now.
…ilder

CLAUDE.md: 14 projects with the generator; the LibreOffice step includes the
builder's round trips (poppler). CONTRIBUTING.md: project tree, the builder's
release-please package (src minus src/TriasDev.Templify; additional-paths was
never an option), the chore(builder) title and merge commit for builder
merges, initial-version, the three projects' API files.
A typed data property named Number, Count or Index on a loop item silently
became the loop metadata ({{@Number}} for an article number): every check
stayed green (final review). The metadata now lives under one member,
line.Loop.Index / Number / Count / IsFirst / IsLast, on LoopItem and
LoopItem<T> alike, so such properties are generated as data. TBG001 (a data
property not generated because the API has a member of that name, e.g.
order.Exists) is a warning instead of information.

Experimental API change (TPLB001): LoopItem(.<T>).Index/Number/Count/IsFirst/
IsLast moved to .Loop; new LoopInfo.
…time

ConditionText.Number cast the double to decimal, which is exact on .NET 11
(19.99 → 19.989999999999998436805981328) and rounded on .NET 10: a template's
bytes and its exported JSON differed by runtime. It now writes the shortest
round-trip text, without an exponent.
…he edge

ODF has no table border: every cell carries its edges. A loop row at the
table's edge carried the outer line, and every clone kept it (3 pt between
all loop rows); a conditional row there took the outer line away when its
condition was false. Only a plain row at the template's edge carries the
outer line now; a loop or conditional at an edge gets a 1 pt row of its own
that carries it. DOCX is unchanged (table-level borders). Measured in
LibreOffice renderings for four shapes.
…I review I2)

TemplatePath and TemplatePath<T> format as their placeholder in an
interpolated string, so $"Report {path}" fails the literal-text check
instead of printing the path's name. ToString() stays the dotted path.
# Conflicts:
#	.release-please-manifest.json
@vaceslav vaceslav added the builder TriasDev.Templify.Builder: code-first template generation label Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment