# Templatical integration spike — #3967

Historical server-v1 boundary below. The subsequent accepted-target integration,
native controls, Swedish source build and v2 validation pipeline are documented
in [the UI contributor contract](newsletter-editor-ui-3967.md). Its explicitly
authorized isolated native browser checks supersede the earlier server-only
no-browser statement; no production or Computer Use authority is implied.

Status: contributor candidate; disabled by default. This is the server draft and
rendering foundation, not a released replacement editor. No production schema,
company settings, sendout, existing newsletter or customer account was changed.
The first independent review of application candidate `2812d92b` found no blocking
server-unit defects. Follow-up coverage separately tests create-only/edit-only
roles and escaping of plain button text, image alt and preheader fields. Parent
acceptance and the remaining whole-card gates below are still required.

## Recovered decision and implementation boundary

The #2957 decision of 2026-09-25 (human comment 11729; detailed agent comment 9805)
selected a bounded Templatical spike, pinned server MJML compilation, common final
rendering, quality validation and a real email-client matrix. Legacy data stays on
its existing editor/renderer. Conversion is a separate decision.

No prior Templatical source, prototype or package integration was found in the
inspected repository refs, project docs or Nuhet durable memory. This candidate
starts from local master `ee4d973fe3e4a91f428ea09dbc274131bab8a045`, in the task-owned
`codex/3967-templatical-spike` worktree. The separately reviewed #2957 candidate
`316174719085440548a6df255e35b3b3faaa8379` and its previews remain parent-owned.
The already-present origin/master reference is ahead of this base; root must
select the eventual integration target. The new route include is the only change
to an existing application source file.

## Local contract

`tools/newsletter-renderer/package-lock.json` pins Templatical renderer, types and
quality 0.46.0, MJML 5.4.0 and the complete dependency tree. Use `npm ci` in that
directory. PHP runs the Node CLI with an argument array, JSON stdin, a 256 KiB
document limit, a ten-second timeout and a stripped child environment. No caller
can supply a command, MJML, include path, compiler option, HTML block or custom
block. No render-time URL fetch is part of the adapter.

MJML 5.4.1 was initially evaluated, but its new beautifier dependencies declare a
Node range excluding installed Node 25.8.2 and 22.22.0. The candidate instead pins
5.4.0. No machine runtime was installed or changed.

The v1 schema intentionally supports only paragraphs, titles, HTTPS images,
buttons, dividers, spacers and unnested one/two/three-column sections. Every
supported block appears in the compiler fixtures. It validates required SDK
fields, unique IDs, bounded dimensions/counts, rich-text markup and URLs. Unknown
fields or unsupported blocks reject the save, preserving the prior revision.
SDK quality errors reject; warnings remain available in the compiler response.
Rendered HTML is capped below 100,000 UTF-8 bytes; plain text uses the same HTML.

New `newsletter_editor_drafts` and `newsletter_editor_revisions` tables hold the
validated JSON, name, revision author, exact compiled HTML/text, pipeline ID and
content hash. Create/update snapshots are transactional, lock the company against
deletion, and require the current revision on update. A stale save returns 409.
Revisions are append-only through this API. Reopening preserves content; JSON
object key ordering is canonicalized. There is no delete, restore, duplication,
media-library, delivery or legacy-conversion API in this unit.

## Routes and opt-in

All paths start with `/newsletter-editor/drafts` and use Nuhet's existing web,
session authentication, CSRF and throttle middleware. The config defaults to
`enabled=false` and an empty integer `company_ids` list. Both gates must match
before access. Company identity comes from the authenticated Nuhet session;
supplied company/author/compiler fields are ignored. Create requires the existing
`newsletterCreate` permission; reopen/update/preview/history require
`newsletterEdit`. Every draft lookup includes the active company, even for admins.

| Method | Path suffix | Result |
| --- | --- | --- |
| POST | `/` | Validate, compile and create revision 1 |
| GET | `/{id}` | Reopen saved document and compiled artifacts |
| PUT | `/{id}` | Validate/compile and save if `revision` still matches |
| GET | `/{id}/preview` | Exact saved HTML, private/no-store, sandbox CSP |
| GET | `/{id}/history` | Own-company revision metadata |

Rollback consists of disabling the config or removing the company's opt-in. This
does not delete saved drafts. New drafts cannot enter existing `newsletters` or
`sendouts` tables, so unselected companies and legacy workflows are unchanged.
The migration was exercised only in isolated in-memory SQLite tests, never on a
shared/local preview or production database.

## Verification and remaining gates

Run:

```sh
cd tools/newsletter-renderer
npm ci --ignore-scripts
npm test
npm audit --audit-level=low
cd ../..
php vendor/phpunit/phpunit/phpunit tests/Feature/NewsletterEditorDraftTest.php
```

The three compiler fixtures cover Swedish/English content, merge-link preservation,
preheader, a multi-column image/button layout, and every allowed block. They prove
deterministic server output and safe rejection; they do not prove inbox rendering.
An additional test uses the pinned SDK's actual template/block factories for all
seven accepted block types, rather than relying solely on handwritten JSON.
Feature tests exercise the real PHP-to-Node process and SQLite persistence behind
the real application routes/middleware. SQLite establishes sequential stale-save
rejection, not MySQL concurrent-lock behavior.

Required next gates for the whole #3967 card:

- Accept the independent review and final test-only corrections at parent/root.
- Select the integration base without changing the #2957 reviewed candidate.
- Mount the pinned editor SDK, restrict its palette/settings to the accepted
  schema, map Swedish UI strings, and verify desktop/tablet/keyboard behavior.
- Decide the phone-authoring boundary. Current upstream documentation explicitly
  describes a desktop-class editor and a default small-screen notice below about
  768px. Parent provisionally authorized retaining that notice and phone-safe
  saved-draft preview/status for the local spike, with desktop/larger-tablet
  authoring. Final phone-authoring/pilot acceptance remains with Jonathan; the
  provisional path does not authorize rollout or a custom mobile editor.
- Add a maintained Swedish locale to the actual editor UI. The pinned published
  SDK exposes `locale` but no runtime translation-registration contract; upstream
  documents new locales as a source-build addition. Swedish host-page copy or
  `locale: 'sv'` falling back to English cannot establish Swedish editor support.
  Recommended next-unit design: a pinned source build with a Swedish locale and
  key/interpolation parity checks, preserving English. Avoid opaque patches to
  published minified chunks. Source acquisition/build ownership and integration
  target should be explicit before starting that maintained SDK build.
- Integrate revision restore, duplication and tenant-safe media selection.
- Design the publication bridge into shared newsletter output, with identical
  preview/test/production rendering and delivery-time tracking, unsubscribe/GDPR,
  online-link, merge-tag and plain-text substitutions. Tokens in these fixtures
  are contract placeholders; no working unsubscribe/send integration is claimed.
- Verify representative social/video and actual Nuhet templates, message limits,
  Gmail web/iOS/Android, Apple Mail macOS/iOS, Outlook.com/New Outlook, classic
  Windows Outlook, Yahoo and Thunderbird, including dark mode and blocked images.
  Real test mail and service/account access require their existing approvals.
- Apply the project's visual verification workflow before any visible UI handoff.
  Computer Use/browser operation has not been authorized for this session.
- Review cleanup/retention integration before activating this new storage in any
  company. No deployment, migration, license purchase, account or credential work
  is authorized by this candidate.

## Ownership and maintainability

The dedicated #3967 session owns the isolated worktree, compiler dependencies,
test-only storage/cache files and recovery/evidence. Keep the worktree for root
review; cleanup remains with that session after source is durably preserved and
no consumer needs it. No persistent process or database was created.

During relevant source intake, `public/js/editor/editorapp.js` was measured at
1,361 lines. Suggested later split: editor state/network persistence module and
block/directive modules, retaining Angular registration and legacy-save tests.
Migrate state/network first, then directives with browser regression checks. This
candidate does not authorize or perform that legacy refactor.

`routes/web.php` is 873 lines after the two-line include. Recommended separate
maintenance change: extract customer, administration and public route groups in
that order, preserving middleware nesting, names and registration order; verify
the route list and route/security suites after each extraction. This unit already
keeps the new draft endpoints in their own short route file and makes no broader
route refactor.

References: [Templatical editor API](https://docs.templatical.com/api/editor),
[installation](https://docs.templatical.com/getting-started/installation),
[SDK source/license](https://github.com/templatical/sdk).
