@antelopejs/interface-dms-mailing 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -118,7 +118,7 @@ export interface TemplateDeclaration {
118
118
  testData?: Record<string, unknown>;
119
119
  author?: string;
120
120
  }
121
- export type DeclarationOutcome = "created" | "updated" | "unchanged" | "kept";
121
+ export type DeclarationOutcome = "created" | "kept";
122
122
  export interface DeclareTemplateResult {
123
123
  templateId: string;
124
124
  slug: string;
package/docs/1.index.md CHANGED
@@ -116,13 +116,13 @@ Accepted events update the send timeline, status and engagement counters, publis
116
116
 
117
117
  ## Ship templates as code
118
118
 
119
- A project can declare its transactional templates from backend code instead of creating them in the dashboard. A newly created template claims its slug, is published as v1 with history, and is ready for `SendTemplate` when the call resolves. Existing templates remain subject to the ownership and lifecycle rules below: `unchanged` and `kept` do not guarantee that an archived or unpublished template is sendable.
119
+ A project can declare its transactional templates from backend code instead of creating them in the dashboard. The content is written once, when the tenant is provisioned (see [When to call](#when-to-call)), and belongs to the tenant from then on: nothing replays it on a later boot. A newly created template claims its slug, is published as v1 with history, and is ready for `SendTemplate` when the call resolves.
120
120
 
121
121
  `DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender` and `ImportSends` require an explicit `tenantId`, in TypeScript and at runtime. Omission, an empty string or whitespace-only input rejects before any write, with `invalid_template`, `invalid_category`, `invalid_sender` or `invalid_import` respectively and `tenantId` in the message. There is no default fallback. Passing `DEFAULT_TENANT_ID` explicitly remains valid. This requirement identifies the target; it proves neither authorization nor completed provisioning. Trusted application code must enforce both. Existing `SendTemplate` and `RecordEmailEvent` contracts are unchanged.
122
122
 
123
123
  ### Names and labels in several languages
124
124
 
125
- A template's `name` and a category's `label` are `LocalizedText`: one text per language, `{ en: "Welcome", fr: "Bienvenue" }`. The `en` text is required (`LOCALIZED_TEXT_FALLBACK_LOCALE`): a reader whose language has no text reads it. They are stored as localized fields (`@Localized`), so the dashboard shows, searches and sorts each user's own language, sent by the DMS frontend in `x-content-language`. Do not pass `$` i18n keys: a name is content, not a translation key. A user renaming a template in the dashboard writes the language they work in, which counts as a change (`kept`).
125
+ A template's `name` and a category's `label` are `LocalizedText`: one text per language, `{ en: "Welcome", fr: "Bienvenue" }`. The `en` text is required (`LOCALIZED_TEXT_FALLBACK_LOCALE`): a reader whose language has no text reads it. They are stored as localized fields (`@Localized`), so the dashboard shows, searches and sorts each user's own language, sent by the DMS frontend in `x-content-language`. Do not pass `$` i18n keys: a name is content, not a translation key. A user renaming a template in the dashboard writes the language they work in.
126
126
 
127
127
  ### DeclareTemplate
128
128
 
@@ -144,7 +144,7 @@ interface TemplateDeclaration {
144
144
  author?: string; // shown as "updated by" / "published by"; "system" when absent
145
145
  }
146
146
 
147
- type DeclarationOutcome = "created" | "updated" | "unchanged" | "kept";
147
+ type DeclarationOutcome = "created" | "kept";
148
148
 
149
149
  interface DeclareTemplateResult {
150
150
  templateId: string;
@@ -158,22 +158,11 @@ declare function DeclareTemplate(
158
158
  ): Promise<DeclareTemplateResult>;
159
159
  ```
160
160
 
161
- The slug is the key the caller chooses. Calling `DeclareTemplate` on every boot or hot reload is the intended use, and it never creates a second template. The module stores a fingerprint of the declaration it last applied (name, category, content, variables and test data) on the template and decides as follows:
161
+ The slug is the key the caller chooses. A slug the tenant does not have yet is created and published as v1 (`created`). A slug it already has, declared before or made in the dashboard, is left as it is (`kept`): the call writes nothing, so a retried provisioning never creates a second template nor overwrites a user's work.
162
162
 
163
- | The template under that slug | Outcome | What is written |
164
- | --- | --- | --- |
165
- | does not exist | `created` | the template, published as v1 |
166
- | was declared with the same declaration | `unchanged` | no content or lifecycle change, whatever a user did since; interrupted history may be repaired |
167
- | was declared before, is still `live` with no draft and holds exactly what the last declaration wrote | `updated` | the new declaration, published (a new version when content or variables changed) |
168
- | was edited, holds a draft, was unpublished or archived since, or was made in the dashboard | `kept` | no content or lifecycle change; interrupted history may be repaired |
163
+ The declaration follows the dashboard's rules: the slug pattern and length of a new template, a non-blank name, content and variable declarations valid for the editor, at least one locale and a subject in every locale (what **Publish** requires). A creation also requires a category the workspace settings declare (or none). Validation errors use `invalid_template`, `unknown_category`, `nothing_to_publish` or `empty_subject`; their messages identify the invalid input, and they do not publish a template.
169
164
 
170
- So a user's work always wins: once someone edits a declared template, the code stops refreshing it until the template holds exactly what the code last declared again. Archive a declared template to take it out of use for good; a declared template deleted in the dashboard is created again by the next call, since the code that declares it is the code that sends it.
171
-
172
- Publication compares the template's semantic revision and commits content, metadata and the declaration fingerprint together. An intervening dashboard edit causes a reread and ownership check instead of an overwrite; repeated contention rejects with `declaration_conflict`. A concurrent caller can finish an unmodified initial declaration left by an interrupted creator, but cannot publish over a user-edited seed.
173
-
174
- The declaration follows the dashboard's rules: the slug pattern and length of a new template, a non-blank name, content and variable declarations valid for the editor, at least one locale and a subject in every locale (what **Publish** requires). A creation or refresh also requires a category the workspace settings declare (or none); `unchanged` and `kept` do not fail merely because a user removed the original category. Validation errors use `invalid_template`, `unknown_category`, `nothing_to_publish` or `empty_subject`; their messages identify the invalid input, and they do not publish a template.
175
-
176
- A storage or attention-refresh failure can reject after publication commits. The committed template retains the complete latest version so history and numbered-version previews remain readable if the history insert fails; a later declaration or publication repairs that row before replacing the snapshot. Retry the same declaration after resolving the storage problem. An indeterminate database mutation rejects without automatic retry or rollback: rejection is not proof that nothing changed.
165
+ A storage or attention-refresh failure can reject after publication commits. The committed template retains the complete latest version so history and numbered-version previews remain readable if the history insert fails; a later publication repairs that row before replacing the snapshot. An indeterminate database mutation rejects without automatic retry or rollback: rejection is not proof that nothing changed.
177
166
 
178
167
  ### DeclareTemplateCategory
179
168
 
@@ -187,7 +176,7 @@ interface TemplateCategoryDeclaration {
187
176
 
188
177
  interface DeclareTemplateCategoryResult {
189
178
  id: string;
190
- outcome: "created" | "updated" | "unchanged" | "kept";
179
+ outcome: "created" | "kept";
191
180
  }
192
181
 
193
182
  declare function DeclareTemplateCategory(
@@ -195,7 +184,7 @@ declare function DeclareTemplateCategory(
195
184
  ): Promise<DeclareTemplateCategoryResult>;
196
185
  ```
197
186
 
198
- Adds a category to the workspace settings (`created`), relabels one still as last declared (`updated`), or does nothing (`unchanged`). A category a user relabelled or removed since, and one that existed before any declaration (the defaults `orders`, `account`, `billing`, `marketing` and `forms` among them), is left as it is (`kept`): a removed category is never added back. A label another category already has rejects with `invalid_category`. Declarations of one workspace run one after the other within one process; this queue is not a cross-process lock and does not serialize dashboard settings writes. Coordinate concurrent category/settings writers externally. Declare a category before templates that name it.
187
+ Adds a category to the workspace settings (`created`). An id the settings already hold, the defaults `orders`, `account`, `billing`, `marketing` and `forms` among them, is left as it is (`kept`). A label another category already has rejects with `invalid_category`. Declarations of one workspace run one after the other within one process; this queue is not a cross-process lock and does not serialize dashboard settings writes. Coordinate concurrent category/settings writers externally. Declare a category before templates that name it.
199
188
 
200
189
  ### DeclareSender
201
190
 
@@ -214,23 +203,20 @@ Writes the Sender section of the workspace settings, so a fresh workspace sends
214
203
 
215
204
  ### When to call
216
205
 
217
- The calls wait for the module and for the DMS database, so start order never makes them fail: a call made before `@antelopejs/dms-mailing` is constructed is queued by the interface, and a call made before the DMS opened its database waits for it. The DMS opens it in its own `start()`, after every module's `construct()`, so:
218
-
219
- - in `construct()`, register lifecycle consumers synchronously, without calling or awaiting declarations: this ensures registration precedes startup reconciliation;
220
- - in `start()`, perform explicitly scoped global work, not consumer registration that can race reconciliation. A `construct()` awaiting declarations would wait for database startup, which only runs after every `construct()` returned;
221
- - in a `Hook.DATABASE_INITIALIZED` handler, do not await them either: the hook's handlers run one after the other.
206
+ Call these functions from a `Hook.TENANT_BEING_PROVISIONED` handler, registered in your module's `construct()`. The DMS fires that hook once for each tenant, when the tenant is created. For the `default` tenant, it fires on the DMS start that creates it, after every `DATABASE_INITIALIZED` handler has finished. A SaaS module fires it for each workspace it creates. The mailing tables are ready by then, so the calls do not wait for anything.
222
207
 
223
- `start()` runs for the process, not for each SaaS workspace. Database readiness does not mean a tenant has completed provisioning. The following application function receives its authorized target from its caller; it is not an implicit default-tenant startup initializer.
208
+ Do not call them from `start()` or a `DATABASE_INITIALIZED` handler. They run on every boot, and the content a workspace starts with is written once. After that, it belongs to the workspace.
224
209
 
225
210
  ```ts docs-check
211
+ import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";
226
212
  import {
227
213
  DeclareTemplate,
228
214
  DeclareTemplateCategory,
229
215
  } from "@antelopejs/interface-dms-mailing";
230
216
 
231
- export async function declareMailingContent(tenantId: string): Promise<void> {
217
+ async function declareMailingContent(tenantId: string): Promise<void> {
232
218
  await DeclareTemplateCategory({ tenantId, id: "subscriptions", label: { en: "Subscriptions", fr: "Abonnements" }, icon: "i-ph-repeat" });
233
- const result = await DeclareTemplate({
219
+ await DeclareTemplate({
234
220
  tenantId,
235
221
  slug: "subscription-renewed",
236
222
  name: { en: "Subscription renewed", fr: "Abonnement renouvelé" },
@@ -259,45 +245,15 @@ export async function declareMailingContent(tenantId: string): Promise<void> {
259
245
  testData: { customer: { firstName: "Sofie" }, plan: { name: "Pro" } },
260
246
  author: "Release script",
261
247
  });
262
- if (result.outcome === "kept") {
263
- // Preserve the user's content and lifecycle; it may be archived.
264
- }
265
248
  }
266
- ```
267
-
268
- ### Initialize new SaaS workspaces
269
-
270
- For an application using dms-saas, register a durable `created` consumer through `RegisterWorkspaceLifecycleConsumer` from `@antelopejs/interface-dms-saas/workspace-lifecycle`. Register it synchronously in the application's `construct()`, before startup reconciliation begins; the async consumer executes later. The `created` transition follows workspace preparation and payment; delivery is **at least once**. `TENANT_BEING_PROVISIONED` is a different, prepayment hook: an error aborts creation, with no automatic replay or compensation of consumer effects.
271
-
272
- The following is an **integration skeleton**, not a standalone persistence implementation. The application must implement the durable operation ledger and resource binding described in the comments before returning a receipt. Mailing neither depends on dms-saas nor registers this consumer.
273
-
274
- ```typescript
275
- import { RegisterWorkspaceLifecycleConsumer } from "@antelopejs/interface-dms-saas/workspace-lifecycle";
276
- import { declareMailingContent } from "./mailing-content"; // application function above
277
249
 
278
250
  export function construct(): void {
279
- RegisterWorkspaceLifecycleConsumer({
280
- name: "application.mailing",
281
- transitions: ["created"],
282
- async consume({ tenantId, operationId }) {
283
- // Application responsibility: deduplicate concurrent/replayed operationId
284
- // durably, returning the recorded receipt for completed operations.
285
- await declareMailingContent(tenantId);
286
- // Persist the resource bindings and completed operation before returning
287
- // its durable receiptId. A crash here must be recoverable on redelivery.
288
- // Return { receiptId, ... } from that application-owned durable record.
289
- throw new Error("Implement durable operation binding and receipt storage");
290
- },
251
+ RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId }) => {
252
+ await declareMailingContent(tenantId);
291
253
  });
292
254
  }
293
255
  ```
294
256
 
295
- Use `operationId` as the durable deduplication key. Idempotent declarations make their own retries safe; they do not make arbitrary consumer side effects exactly-once. Never acknowledge success with a fabricated receipt or before resources are durably associated with the operation. Do not await declarations from `construct()` while database startup is still blocked; consumer registration and consumer execution are distinct.
296
-
297
- ### Update existing SaaS workspaces
298
-
299
- A new deployment does not emit `created` for every existing tenant. Apply code updates or backfills through an application-owned, authorized tenant inventory. For each candidate, check `IsWorkspaceProvisioningCommitted(tenantId)` from the same workspace-lifecycle entry point before declaring or importing. Proceed only on `true`; skip an uncommitted tenant, and treat lookup/inventory errors as failures, never permission to proceed. Preserve progress for retries and coordinate category/settings writers. This is separate from initializing a newly created workspace, and it must never silently fall back to the default tenant.
300
-
301
257
  ## ImportSends
302
258
 
303
259
  ```ts [Contract]
@@ -340,7 +296,7 @@ declare function ImportSends(params: SendImport): Promise<ImportSendsResult>;
340
296
 
341
297
  **An import, not a send.** `SendTemplate` stamps every send with the current time, and the Overview, the template statistics and the send log read sends by that date: history from another provider, or a demo data set, cannot be replayed through it. `ImportSends` writes past sends with their own `sentAt` and events instead. Nothing is delivered, and no suppression, realtime update, automation or owner notification follows: import the suppression list separately if the old provider kept one.
342
298
 
343
- Each entry names a template of the workspace (its published version is recorded) and is keyed by its `importId`: an entry imported before is skipped untouched, so the call can run on every boot. The events can come in any order; the send's status, open and click counters, error and soft-bounce flag follow from them as if the webhook had reported them, and an entry without events is `sent`. An unknown template rejects the whole call with `template_not_found` before anything is written; an invalid entry rejects it with `invalid_import`, naming the field (`sends.3.to`). The log retention applies to imported sends like to any other: one older than the workspace's retention (90 days by default) goes at the next nightly run, so a demo data set should stay within it.
299
+ Each entry names a template of the workspace (its published version is recorded) and is keyed by its `importId`: an entry imported before is skipped untouched, so a retried provisioning imports nothing twice. The events can come in any order; the send's status, open and click counters, error and soft-bounce flag follow from them as if the webhook had reported them, and an entry without events is `sent`. An unknown template rejects the whole call with `template_not_found` before anything is written; an invalid entry rejects it with `invalid_import`, naming the field (`sends.3.to`). The log retention applies to imported sends like to any other: one older than the workspace's retention (90 days by default) goes at the next nightly run, so a demo data set should stay within it.
344
300
 
345
301
  Events are sorted by `at` and deduplicated before storage and counting: `details.eventId` identifies provider retries; without it, the type, timestamp and serialized details must match. The earliest sorted occurrence is kept. Import IDs are scoped by tenant, not by provider: prefix them when importing more than one provider's identifier space.
346
302
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/interface-dms-mailing",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "AntelopeJS interface for the DMS mailing module: send templates and report e-mail events from any module.",
5
5
  "keywords": [
6
6
  "antelopejs",
@@ -57,6 +57,7 @@
57
57
  "@antelopejs/interface-email": ">=0.0.6 <1.0.0"
58
58
  },
59
59
  "devDependencies": {
60
+ "@antelopejs/interface-dms": ">=0.9.0 <1.0.0",
60
61
  "@antelopejs/tooling-configs": ">=0.0.9 <1.0.0",
61
62
  "@types/node": "^24.0.0",
62
63
  "oxfmt": "^0.66.0",