@antelopejs/interface-dms-saas 0.6.1 → 0.7.0

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.
Files changed (61) hide show
  1. package/README.md +27 -34
  2. package/dist/db/models/billingSettings.model.d.ts +7 -5
  3. package/dist/db/models/creditNotes.model.d.ts +7 -5
  4. package/dist/db/models/features.model.d.ts +7 -5
  5. package/dist/db/models/invoices.model.d.ts +7 -5
  6. package/dist/db/models/legalDocuments.model.d.ts +7 -5
  7. package/dist/db/models/planMigrations.model.d.ts +7 -5
  8. package/dist/db/models/plans.model.d.ts +9 -6
  9. package/dist/db/models/plans.model.js.map +1 -1
  10. package/dist/db/models/platformNotes.model.d.ts +7 -5
  11. package/dist/db/models/refunds.model.d.ts +7 -5
  12. package/dist/db/models/segments.model.d.ts +7 -5
  13. package/dist/db/models/segments.model.js +9 -8
  14. package/dist/db/models/segments.model.js.map +1 -1
  15. package/dist/db/models/stripeWebhookEvents.model.d.ts +7 -5
  16. package/dist/db/models/tenantBillingInfo.model.d.ts +7 -5
  17. package/dist/db/models/tenantBillingState.model.d.ts +7 -5
  18. package/dist/db/models/tenantSubscriptions.model.d.ts +7 -5
  19. package/dist/db/models/tenantSubscriptions.model.js +7 -8
  20. package/dist/db/models/tenantSubscriptions.model.js.map +1 -1
  21. package/dist/db/models/trialConsumptions.model.d.ts +7 -5
  22. package/dist/db/models/update-result.d.ts +8 -1
  23. package/dist/db/models/update-result.js +8 -2
  24. package/dist/db/models/update-result.js.map +1 -1
  25. package/dist/db/models/userSegments.model.d.ts +7 -5
  26. package/dist/db/tables/creditNotes.table.d.ts +1 -1
  27. package/dist/db/tables/creditNotes.table.js.map +1 -1
  28. package/dist/db/tables/features.table.d.ts +3 -1
  29. package/dist/db/tables/features.table.js.map +1 -1
  30. package/dist/db/tables/invoices.table.d.ts +1 -1
  31. package/dist/db/tables/plans.table.d.ts +2 -1
  32. package/dist/db/tables/plans.table.js.map +1 -1
  33. package/dist/db/tables/refunds.table.js.map +1 -1
  34. package/dist/db/tables/segments.table.js +5 -7
  35. package/dist/db/tables/segments.table.js.map +1 -1
  36. package/dist/db/tables/tenantSubscriptions.table.js +4 -3
  37. package/dist/db/tables/tenantSubscriptions.table.js.map +1 -1
  38. package/dist/hidden-filter.js.map +1 -1
  39. package/dist/index.d.ts +1 -0
  40. package/dist/index.js +1 -0
  41. package/dist/index.js.map +1 -1
  42. package/dist/invoice-line-items.d.ts +1 -1
  43. package/dist/invoice-line-items.js +9 -7
  44. package/dist/invoice-line-items.js.map +1 -1
  45. package/dist/json.d.ts +6 -0
  46. package/dist/json.js +3 -0
  47. package/dist/json.js.map +1 -0
  48. package/dist/pages.d.ts +5 -0
  49. package/dist/pages.js.map +1 -1
  50. package/dist/plans.d.ts +2 -2
  51. package/dist/plans.js.map +1 -1
  52. package/dist/provisioning.d.ts +2 -1
  53. package/docs/1.index.md +13 -13
  54. package/docs/2.billing.md +30 -34
  55. package/docs/3.lifecycle-and-usage.md +44 -37
  56. package/docs/4.pages-plans-data.md +24 -23
  57. package/docs/tsconfig.json +9 -1
  58. package/package.json +9 -13
  59. package/dist/db/models/revision.d.ts +0 -1
  60. package/dist/db/models/revision.js +0 -14
  61. package/dist/db/models/revision.js.map +0 -1
package/docs/1.index.md CHANGED
@@ -1,28 +1,29 @@
1
1
  ---
2
2
  title: SaaS interface
3
3
  description: Supported backend imports and side-effect boundaries for modules extending DMS SaaS.
4
+ mode: reference
4
5
  ---
5
6
 
6
- # SaaS interface
7
-
8
- Consumers depend on `@antelopejs/interface-dms-saas`, not the runtime's private services or page controllers. Load `@antelopejs/dms-saas` in the same AntelopeJS project for functions that need an implementation. Compile with `moduleResolution: "bundler"`, `"node16"` or `"nodenext"` so subpaths resolve through the package's exports map.
7
+ Consumers depend on `@antelopejs/interface-dms-saas`, not on the runtime's private services or page controllers. The functions that need an implementation work only when `@antelopejs/dms-saas` is loaded in the same AntelopeJS project. Subpaths resolve through the package's `exports` map, so a consumer compiles with `moduleResolution` set to `"bundler"`, `"node16"` or `"nodenext"`.
9
8
 
10
9
  ## Entry points
11
10
 
12
11
  | Import after `@antelopejs/interface-dms-saas` | Contract |
13
12
  | --- | --- |
14
- | Root | Billing, data API, pages, plans, provisioning and registration exports; `invoiceLineItems` and `tenantLifecycle` namespaces |
13
+ | Root | Billing, data API, JSON, pages, plans, provisioning and registration exports, plus the `invoiceLineItems`, `tenantLifecycle` and `planChanges` namespaces |
15
14
  | `/billing` | [Balances, previews and billing-state recomputation](./2.billing.md) |
16
15
  | `/invoice-line-items` | [Usage providers, line types and key helpers](./3.lifecycle-and-usage.md#invoice-line-items) |
17
16
  | `/plan-changes` | [Inventory policy and guarded Free downgrade](./3.lifecycle-and-usage.md#plan-changes) |
18
17
  | `/tenant-lifecycle` | [Durable lifecycle consumers and provisioning gate](./3.lifecycle-and-usage.md#tenant-lifecycle) |
19
- | `/provisioning`, `/registration` | [Provisioning payload and registration limits](./3.lifecycle-and-usage.md#registration-and-provisioning) |
18
+ | `/provisioning`, `/registration`, `/json` | [Provisioning payload, registration limits and JSON types](./3.lifecycle-and-usage.md#registration-and-provisioning) |
20
19
  | `/pages`, `/page-definitions` | [Page descriptors and extension registration](./4.pages-plans-data.md#page-extensions) |
21
20
  | `/plans` | [Plan projections, localization and pricing helpers](./4.pages-plans-data.md#plan-helpers) |
22
- | `/data-api`, `/hidden-filter` | [HiddenStringFilter](./4.pages-plans-data.md#hiddenstringfilter) |
23
- | `/db`, `/db/models`, `/db/tables` | Canonical SaaS models and table classes; see the data boundary below |
21
+ | `/data-api`, `/hidden-filter` | [`HiddenStringFilter`](./4.pages-plans-data.md#hiddenstringfilter) |
22
+ | `/db`, `/db/models`, `/db/tables` | Canonical SaaS models and table classes, described in [the database section](#database-imports-have-side-effects) |
23
+
24
+ `invoiceLineItems`, `tenantLifecycle` and `planChanges` are namespaces at the root, not flat exports. Each of these modules has its own `internal` proxy namespace, and two `internal` names cannot share one barrel. The direct subpaths export the same functions by name. The `internal` namespaces are implementation plumbing, not consumer APIs.
24
25
 
25
- `invoiceLineItems` and `tenantLifecycle` are namespaces at the root, not flat exports. Use their direct subpaths for individual functions. Their `internal` proxy namespaces are implementation plumbing, not consumer APIs.
26
+ `IsTenantProvisioningCommitted` passes storage errors through. The example below lets them reject, so an unavailable store never grants eligibility.
26
27
 
27
28
  ```ts docs-check
28
29
  import { invoiceLineItems, tenantLifecycle } from "@antelopejs/interface-dms-saas";
@@ -30,19 +31,18 @@ import { invoiceLineItems, tenantLifecycle } from "@antelopejs/interface-dms-saa
30
31
  export const usageKey = invoiceLineItems.buildInvoiceLineKey("example.compute", "minutes");
31
32
 
32
33
  export async function mayProvision(tenantId: string): Promise<boolean> {
33
- // Errors propagate: unavailable storage must not grant eligibility.
34
34
  return tenantLifecycle.IsTenantProvisioningCommitted(tenantId);
35
35
  }
36
36
  ```
37
37
 
38
38
  ## Database imports have side effects
39
39
 
40
- The root does not re-export `db`. Importing `/db` registers the canonical SaaS tables; do not create duplicate table definitions or load the runtime's registration graph to reach them. Prefer `import type` when only a type is needed. The root also exports plan helpers that import database values, so do not assume that a root value import avoids all transitive table registration. Narrow subpaths express which contract the consumer needs.
40
+ The root does not re-export `db`. Importing `/db` registers the canonical SaaS tables. A consumer does not create duplicate table definitions or load the runtime's registration graph to reach them, and uses `import type` when it needs only a type. The root also exports plan helpers that import database values, so a value import from the root can still register tables. A narrow subpath names the contract the consumer needs.
41
41
 
42
- Database exports are persistence primitives, not an authorization or billing-service API. Use tenant-scoped models with the correct tenant, and keep direct writes in trusted import/seed code. Direct writes do not automatically perform all Stripe, lifecycle, cache and directory work of the runtime's normal operations.
42
+ Database exports are persistence classes. They are neither an authorization API nor a billing service. A tenant-scoped model needs the correct tenant, and direct writes belong in trusted import or seed code. A direct write skips the Stripe, lifecycle, cache and directory work that the runtime's own operations do.
43
43
 
44
- After seeding or importing subscription records, call [RecomputeTenantBillingState](./2.billing.md#recomputetenantbillingstate) for each affected tenant once writes finish. This republishes derived billing and directory state; it does not make an arbitrary direct write equivalent to a normal billing operation. When seeding plans, leave `Plan.paymentProviderRefs` empty and never overwrite the runtime's Stripe linkage. See the [plan and Stripe guide](/docs/modules/saas/stripe#plans-and-stripe).
44
+ After seeding or importing subscription records, call [`RecomputeTenantBillingState`](./2.billing.md#recomputetenantbillingstate) for each affected tenant once the writes finish. It republishes the derived billing state and the directory row. It does not turn an arbitrary direct write into a normal billing operation. A plan seed leaves `Plan.paymentProviderRefs` empty and never overwrites the runtime's Stripe link, as the [plan and Stripe guide](/docs/modules/saas/stripe#plans-and-their-stripe-products) explains.
45
45
 
46
- `workspaceSettingsCategory` belongs to `@antelopejs/interface-dms/page`, not this package. There is no SaaS `GetWorkspaceSettingsCategory` export. Use `/pages` for SaaS billing and platform-workspace extension anchors.
46
+ `workspaceSettingsCategory` belongs to `@antelopejs/interface-dms/page`, not to this package. There is no SaaS `GetWorkspaceSettingsCategory` export. `/pages` holds the SaaS billing page and platform workspace extension anchors.
47
47
 
48
48
  The [runtime guide](/docs/modules/saas/extending) covers installation, public screens, UI integration and examples. These pages define the backend consumer contracts.
package/docs/2.billing.md CHANGED
@@ -1,16 +1,14 @@
1
1
  ---
2
2
  title: Billing
3
3
  description: Authorized customer balances and invoice previews, and republishing derived billing state after direct writes.
4
+ mode: reference
4
5
  ---
5
6
 
6
- # Billing
7
-
8
- Import these functions and types from `@antelopejs/interface-dms-saas/billing` or the package root.
7
+ These functions and types are exported from `@antelopejs/interface-dms-saas/billing` and from the package root.
9
8
 
10
9
  ## Read a customer's balance
11
10
 
12
- Use this read when a billing page needs to distinguish credit from money owed.
13
- Pass IDs obtained from your authenticated request, not unchecked request fields.
11
+ The example tells credit from money owed. Its `scope` holds IDs taken from the authenticated request, never unchecked request fields.
14
12
 
15
13
  ```ts docs-check
16
14
  import {
@@ -27,68 +25,66 @@ export async function describeBalance(scope: TenantCustomerBalanceScope): Promis
27
25
  }
28
26
  ```
29
27
 
30
- For an available EUR balance of `-1250`, this returns `1250 EUR minor units in
31
- credit`: €12.50 available for future invoices, not a refund. A provider failure
32
- rejects the call; do not turn it into a zero balance. The reference below covers
33
- all absence reasons and the separate upcoming-invoice estimate.
28
+ For an available EUR balance of `-1250`, the example returns `1250 EUR minor units in credit`. That is €12.50 available for future invoices, not a refund. A provider failure rejects the call, and the example lets it reject instead of reporting a zero balance. The sections below list every absence reason and the separate upcoming invoice estimate.
34
29
 
35
- ## GetTenantCustomerBalance
30
+ ## `GetTenantCustomerBalance`
36
31
 
37
- `GetTenantCustomerBalance(scope: TenantCustomerBalanceScope): Promise<TenantCustomerBalance>` takes `{ tenantId: string, userId: string }` from a trusted authentication boundary. It requires membership and a successful tenant access gate; it rejects unauthorized callers with 403. It does not trust a supplied user ID as proof of authentication.
32
+ `GetTenantCustomerBalance(scope: TenantCustomerBalanceScope): Promise<TenantCustomerBalance>` takes `{ tenantId: string, userId: string }` from a trusted authentication boundary. The user must be a member of the tenant, or the call rejects with 403 `error.tenant_member_required`. The DMS tenant access gate (`AssertTenantAccess`) must then pass. The function does not authenticate the user, so the caller vouches for `userId`.
38
33
 
39
34
  | Result | Fields |
40
35
  | --- | --- |
41
36
  | `AvailableTenantCustomerBalance` | `status: "available"`, `balanceMinorUnits: number`, `currency: string` |
42
37
  | `AbsentTenantCustomerBalance` | `status: "absent"`, `reason: TenantCustomerBalanceAbsenceReason`, `balanceMinorUnits: null`, `currency: null` |
43
38
 
44
- Amounts are Stripe minor units: negative means customer credit, positive means money owed, and zero means settled. Currency is uppercase ISO 4217. Absence reasons are `complimentary`, `customer_not_configured`, `customer_deleted`, and `currency_unavailable`. Stripe read failures reject with 502 and `saas.errors.billing.customer_balance_provider_unavailable`; they are not an absent balance. This call does not charge or refund the customer.
39
+ Amounts are Stripe minor units. A negative amount is customer credit, a positive amount is money owed, and zero is settled. The currency is uppercase ISO 4217. `TenantCustomerBalanceAbsenceReason` is `customer_not_configured`, `complimentary`, `customer_deleted`, or `currency_unavailable`. A Stripe read failure rejects with 502 `saas.errors.billing.customer_balance_provider_unavailable` and is never an absent balance. The call does not charge or refund the customer.
45
40
 
46
- `isComplimentarySubscription(subscription: ComplimentarySubscriptionState | null | undefined): boolean` is a synchronous helper. `ComplimentarySubscriptionState` has `isComplimentary?: boolean | null`; only an explicit `true` returns true. A free plan alone is not the complimentary marker.
41
+ `isComplimentarySubscription(subscription: ComplimentarySubscriptionState | null | undefined): boolean` is a synchronous helper. `ComplimentarySubscriptionState` has `isComplimentary?: boolean | null`. Only an explicit `true` returns true. A free plan alone is not the complimentary marker.
47
42
 
48
- ## GetUpcomingInvoicePreview
43
+ ## `GetUpcomingInvoicePreview`
49
44
 
50
- `GetUpcomingInvoicePreview(scope: UpcomingInvoicePreviewScope): Promise<UpcomingInvoicePreview>` uses the same `{ tenantId, userId }` scope and authorization checks. Stripe failures become an `unavailable` result rather than an invented total; authentication, implementation availability or local storage failures can still reject.
45
+ `GetUpcomingInvoicePreview(scope: UpcomingInvoicePreviewScope): Promise<UpcomingInvoicePreview>` takes the same `{ tenantId, userId }` scope (`UpcomingInvoicePreviewScope`) and runs the same authorization checks. A Stripe failure becomes an `unavailable` result, never an invented total. An authorization failure, a missing implementation or a local storage failure still rejects.
51
46
 
52
47
  | `status` | Result type and reason |
53
48
  | --- | --- |
54
- | `available` | `AvailableUpcomingInvoicePreview`: Stripe priced the next invoice |
55
- | `absent` | `AbsentUpcomingInvoicePreview`: `complimentary`, `free_plan`, `customer_not_configured`, `subscription_not_configured`, or `no_upcoming_invoice` |
56
- | `unavailable` | `UnavailableUpcomingInvoicePreview`: `stripe_not_configured`, `tax_not_configured`, `tax_location_invalid`, `tax_location_required`, `tax_calculation_failed`, `usage_unavailable`, or `provider_error` |
49
+ | `available` | `AvailableUpcomingInvoicePreview`. Stripe priced the next invoice |
50
+ | `absent` | `AbsentUpcomingInvoicePreview`, with `complimentary`, `free_plan`, `customer_not_configured`, `subscription_not_configured`, or `no_upcoming_invoice` |
51
+ | `unavailable` | `UnavailableUpcomingInvoicePreview`, with `stripe_not_configured`, `tax_not_configured`, `tax_location_invalid`, `tax_location_required`, `tax_calculation_failed`, `usage_unavailable`, or `provider_error` |
57
52
 
58
- Both non-available variants have `reason` and `computedAt: string`. The corresponding exported unions are `UpcomingInvoicePreviewAbsenceReason` and `UpcomingInvoicePreviewUnavailableReason`.
53
+ Both other variants have `reason` and `computedAt: string`. Their reason unions are exported as `UpcomingInvoicePreviewAbsenceReason` and `UpcomingInvoicePreviewUnavailableReason`.
59
54
 
60
- An available preview includes these fields. All amounts are integers in the minor units of its uppercase `currency`; all dates are ISO 8601 strings.
55
+ An available preview has the fields below. Every amount is an integer in the minor units of its uppercase `currency`, and every date is an ISO 8601 string.
61
56
 
62
57
  | Fields | Type and meaning |
63
58
  | --- | --- |
64
- | `subtotalMinorUnits`, `totalExcludingTaxMinorUnits`, `taxMinorUnits`, `totalMinorUnits`, `amountDueMinorUnits` | `number`: subtotal before discounts/tax; total after discounts before tax; tax; tax-inclusive total; amount after customer balance |
65
- | `lines`, `hasMoreLines` | `UpcomingInvoiceLine[]`, `boolean`: line page and truncation flag; totals remain complete |
66
- | `taxes`, `taxCountry`, `isReverseCharge` | `UpcomingInvoiceTax[]`, `string \| null`, `boolean` |
67
- | `periodStart`, `periodEnd`, `billingDate`, `computedAt` | `string`: cycle bounds, issue date and computation time |
68
- | `usageThrough` | `string \| null`: end of quoted usage, null without usage lines |
59
+ | `subtotalMinorUnits`, `totalExcludingTaxMinorUnits`, `taxMinorUnits`, `totalMinorUnits`, `amountDueMinorUnits` | `number`. In order, the subtotal before discounts and tax, the total after discounts and before tax, the tax, the total with tax, and the amount due once the customer balance is applied |
60
+ | `lines`, `hasMoreLines` | `UpcomingInvoiceLine[]` and `boolean`. The first page of lines, and whether Stripe returned more. The totals stay complete |
61
+ | `taxes`, `taxCountry`, `isReverseCharge` | `UpcomingInvoiceTax[]`, `string \| null` (uppercase country), `boolean` |
62
+ | `periodStart`, `periodEnd`, `billingDate`, `computedAt` | `string`. The cycle bounds, the issue date and the computation time |
63
+ | `usageThrough` | `string \| null`. The end of the quoted usage, null without usage lines |
69
64
 
70
- `UpcomingInvoiceLine` has `kind: UpcomingInvoiceLineKind` (`subscription`, `usage`, or `invoice_item`), `description: string | null`, `amountMinorUnits: number`, `taxMinorUnits: number`, `quantity: number | null`, `periodStart: string`, `periodEnd: string`, `isProration: boolean`, `usageLineKey: string | null`, and `productId: string | null`. Usage keys are `<provider id>:<key>`; other line kinds have a null usage key.
65
+ `UpcomingInvoiceLine` has `kind: UpcomingInvoiceLineKind` (`subscription`, `usage`, or `invoice_item`), `description: string | null`, `amountMinorUnits: number`, `taxMinorUnits: number`, `quantity: number | null`, `periodStart: string`, `periodEnd: string`, `isProration: boolean`, `usageLineKey: string | null`, and `productId: string | null`. A usage line key is `<provider id>:<key>`. Other line kinds have a null usage key.
71
66
 
72
67
  `UpcomingInvoiceTax` has `amountMinorUnits: number`, `taxableAmountMinorUnits: number | null`, `isInclusive: boolean`, `ratePercentage: number | null`, `isReverseCharge: boolean`, and nullable string fields `country`, `taxType`, `displayName`, `jurisdiction`, and `taxabilityReason`. A reverse charge can produce zero tax with `isReverseCharge: true`.
73
68
 
74
- The preview calls usage providers with `isPreview: true` and can populate a tenant-level shared database cache. It never creates an invoice or charges quoted lines. Usage covers the running cycle so far, not its final total; display `computedAt`. A missing payment method does not itself prevent previewing. Cache lifetime, invalidation and Stripe read timeouts are [runtime configuration](/docs/modules/saas/extending#upcoming-invoice-preview).
69
+ The preview calls usage providers with `isPreview: true` and can store its result in a per-tenant cache in the database, shared by every instance. It never creates an invoice or charges the quoted lines. The usage covers the running cycle so far, not its final total, so a screen shows `computedAt` next to it. A missing payment method alone does not prevent a preview. The cache lifetime, its invalidation and the Stripe read timeout are [runtime configuration](/docs/modules/saas/extending#upcoming-invoice-preview).
70
+
71
+ ## `GetTenantBillingPeriod`
75
72
 
76
- ## GetTenantBillingPeriod
73
+ `GetTenantBillingPeriod(tenantId: string): Promise<TenantBillingPeriod | null>` returns the tenant's current Stripe billing period as a `TenantBillingPeriod`, `{ start: Date, end: Date }`, half-open (`[start, end)`). The period is clipped to the paid usage the same way renewal invoices clip their usage window. A period opened before the paid usage started starts with it, and a guarded downgrade or a closed paid period ends it early. The result is `null` for a free or complimentary tenant, and for a tenant whose subscription has no recorded `currentPeriodStart` and `currentPeriodEnd` yet.
77
74
 
78
- `GetTenantBillingPeriod(tenantId: string): Promise<TenantBillingPeriod | null>` returns the tenant's current Stripe billing period as `{ start: Date, end: Date }`, half-open (`[start, end)`). It is clipped to the paid usage exactly as renewal invoices clip their usage window: a period opened before the paid usage started starts with it, and a guarded downgrade or a closed paid period ends it early. It is `null` for a free or complimentary tenant and for one whose period dms-saas has not recorded yet (`currentPeriodStart` is stored from the subscription webhooks).
75
+ The read is trusted, with no user scope or membership check. Storage errors propagate. It does not call Stripe. A consumer's usage credits can follow another cycle (Cloud resets its allowance on the UTC calendar month), so this period fits only where the invoice period is meant.
79
76
 
80
- This is a trusted read with no user scope or membership check; storage errors propagate. It does not call Stripe. Usage credits in dms-saas consumers may follow another cycle (Cloud resets its allowance on the UTC calendar month): use this period only where you mean the invoice's.
77
+ ## `RecomputeTenantBillingState`
81
78
 
82
- ## RecomputeTenantBillingState
79
+ `RecomputeTenantBillingState(tenantId: string): Promise<void>` republishes the tenant's billing state and its workspace directory fields (plan, seats, MRR, renewal and owner) from the current records. A seed or import calls it once its direct writes finish. The runtime's own billing operations already call it.
83
80
 
84
- `RecomputeTenantBillingState(tenantId: string): Promise<void>` republishes the tenant's billing state and workspace directory fields, including plan, seats, MRR, renewal and owner, from current records. Call it after a seed or import finishes direct writes. Normal runtime billing operations already do this.
81
+ The call is trusted and administrative, with no user scope or membership check, so the caller authorizes the tenant first. It writes derived database state only. It does not change the Stripe subscription, and it does not replace lifecycle delivery or preview cache invalidation. Deleted directory rows and subscriptions whose deletion has started are left alone. Storage errors propagate, and repeated conflicts with a concurrent publication reject after a bounded number of retries. A caller awaits the call and reports a failure instead of showing stale directory state as current.
85
82
 
86
- This is a trusted administrative call with no user scope or membership check. Authorize the tenant before invoking it. It writes derived database state, does not mutate the Stripe subscription, and does not replace lifecycle delivery or preview-cache invalidation. Deleted directory rows and subscriptions whose deletion has started are left alone. Storage errors propagate; repeated concurrent-publication conflicts reject after bounded retries. Await completion and report failures instead of displaying stale directory state as current.
83
+ The example runs after an import has committed every row for tenants the caller already authorized.
87
84
 
88
85
  ```ts docs-check
89
86
  import { RecomputeTenantBillingState } from "@antelopejs/interface-dms-saas/billing";
90
87
 
91
- // Invoke only after the import has committed all rows for these authorized tenants.
92
88
  export async function refreshImportedTenants(tenantIds: readonly string[]): Promise<void> {
93
89
  for (const tenantId of new Set(tenantIds)) {
94
90
  await RecomputeTenantBillingState(tenantId);
@@ -1,13 +1,12 @@
1
1
  ---
2
2
  title: Lifecycle and usage
3
3
  description: Registration extras, durable tenant lifecycle consumers and idempotent invoice usage providers.
4
+ mode: reference
4
5
  ---
5
6
 
6
- # Lifecycle and usage
7
+ These contracts are exported from the direct subpaths below, and from the root's `invoiceLineItems`, `tenantLifecycle` and `planChanges` namespaces. Consumers and providers are registered from the owning module's lifecycle, not from a request handler. A registration is held until SaaS attaches, replayed when SaaS reloads, and dropped when its owner unloads.
7
8
 
8
- Use the direct subpaths below or the root's `invoiceLineItems` and `tenantLifecycle` namespaces. Register consumers/providers from the owning module's lifecycle, not a request handler. Registrations replay when SaaS attaches or reloads and are released when their owner unloads.
9
-
10
- ## Choose when your work should happen
9
+ ## Integration points by task
11
10
 
12
11
  | Task | Integration | Example result |
13
12
  | --- | --- | --- |
@@ -16,15 +15,13 @@ Use the direct subpaths below or the root's `invoiceLineItems` and `tenantLifecy
16
15
  | Pause or resume resources | Lifecycle consumer | SaaS access waits for the required reactivation receipts |
17
16
  | Add measured usage to a bill | Invoice line-item provider | 120 compute minutes produce one priced line |
18
17
 
19
- For that last example, `amountCents: 600` and `quantity: 120` mean a line total
20
- of €6.00 on an EUR invoice, not 120 × €6.00. Your resolver calculates the total;
21
- SaaS does not multiply it by the quantity. See the
22
- [working provider example](/docs/modules/saas/extending#invoice-line-items)
23
- before implementing the contract below.
18
+ In the last row, `amountCents: 600` and `quantity: 120` mean a line total of €6.00 on an EUR invoice, not 120 × €6.00. The resolver calculates the total, and SaaS does not multiply it by the quantity. The [working provider example](/docs/modules/saas/extending#invoice-line-items) implements the contract below.
24
19
 
25
20
  ## Invoice line items
26
21
 
27
- Import from `/invoice-line-items`. `RegisterInvoiceLineItemsProvider(provider: InvoiceLineItemsProvider): void` registers `{ id: string, resolve: InvoiceLineItemsResolver, onUsageGap?: (gap: InvoiceUsageGap) => void }`. `UnregisterInvoiceLineItemsProvider(providerId: string): void` removes it; unknown IDs are ignored. Register during `construct()` and unregister during `stop()`.
22
+ These names are exported from `/invoice-line-items`. `RegisterInvoiceLineItemsProvider(provider: InvoiceLineItemsProvider): void` registers `{ id: string, resolve: InvoiceLineItemsResolver, onUsageGap?: (gap: InvoiceUsageGap) => void }`. `UnregisterInvoiceLineItemsProvider(providerId: string): void` removes it and ignores unknown IDs. A module registers its provider during `construct()` and unregisters it during `stop()`.
23
+
24
+ `InvoiceLineItemsResolution` is the union of two exported interfaces, `InvoiceLineItemsReady` and `InvoiceLineItemsNotReady`.
28
25
 
29
26
  ```ts [Contract]
30
27
  interface InvoiceLineItemsContext {
@@ -65,39 +62,46 @@ type InvoiceLineItemsResolver = (
65
62
  | InvoiceLineItemsResolution;
66
63
  ```
67
64
 
68
- The runtime asks providers for `subscription_cycle` renewal invoices, not initial or one-off invoices. The dates cover the cycle just closed, clipped to the subscription's paid usage period. Complimentary/grace usage is excluded; no provider runs for an empty covered window. Read tenant-scoped, pre-aggregated usage because the resolver runs inside the webhook request or the recovery worker, and return the same lines every time for a closed window.
65
+ The runtime asks providers for `subscription_cycle` renewal invoices, not for initial or one-off invoices. The dates cover the cycle that just closed, clipped to the subscription's paid usage period. Complimentary and grace usage is excluded, and no provider runs for an empty covered window. The resolver runs inside the webhook request or the recovery worker, so it reads tenant-scoped, pre-aggregated usage and returns the same lines every time for a closed window.
69
66
 
70
- `amountCents` is the safe-integer line total in the invoice currency, including negative credits. Quantity and unit are audit metadata, not factors multiplied into the total. Zero amounts are dropped. Empty keys/descriptions, non-safe-integer amounts, keys containing `:`, or combined keys over 150 characters are invalid. Provider IDs must not contain `:`; registration throws if they do. IDs must be globally unique across modules: a collision replaces the earlier provider, and collisions before attachment can collapse silently.
67
+ `amountCents` is the line total in the invoice currency, as a safe integer. A negative amount is a credit. `quantity` and `unit` are audit metadata, never factors of the total. Zero amounts are dropped. A line is invalid when its key or description is empty, its amount is not a safe integer, its key contains `:`, or its provider-prefixed key is longer than 150 characters. A provider ID must not contain `:`, and registration throws if it does. Provider IDs are unique across modules. A second registration with the same ID replaces the first provider, and a clash that happens before SaaS attaches leaves no trace, because the buffer is keyed by ID.
71
68
 
72
- Keep each line key stable. The runtime injects at most one line per invoice/provider/key across webhook replays and concurrent workers. Returning lines is not a guarantee that Stripe accepted the invoice items.
69
+ A line key stays stable from cycle to cycle. The runtime injects at most one line per invoice, provider and key across webhook replays and concurrent workers. A returned line is not proof that Stripe accepted the invoice item.
73
70
 
74
- On a closing invoice the runtime first suspends the draft (`auto_advance=false`) and hands the injection to a durable task. The invoice is always finalized: once every provider's lines are on it, or 48 hours after it was registered with the lines available:
71
+ On a closing invoice the runtime first suspends the draft (`auto_advance=false`) and hands the injection to a durable task. The invoice is always finalized, either once every provider's lines are on it, or 48 hours after the task was registered (`INVOICE_LINE_DEADLINE_MS`) with the lines available. The resolver's answer decides what happens:
75
72
 
76
73
  | Resolver answer | Effect |
77
74
  | --- | --- |
78
- | An array, or `{ status: "ready", lines }` | The lines are injected; an empty array states an empty bill. |
79
- | `{ status: "not_ready", reason }`, or a thrown error | The draft stays suspended and the provider is asked again later; past the deadline, the invoice is finalized without its lines. |
80
- | Anything else | Treated as `not_ready` with reason `invalid_resolution` (`INVALID_RESOLUTION_REASON`); `normalizeInvoiceLineItemsResolution` applies that rule. |
75
+ | An array, or `{ status: "ready", lines }` | The lines are injected. An empty array states an empty bill. |
76
+ | `{ status: "not_ready", reason }`, or a thrown error | The draft stays suspended and the provider is asked again later. Past the deadline, the invoice is finalized without its lines. |
77
+ | Any other value | Read as `not_ready` with the reason `invalid_resolution` (`INVALID_RESOLUTION_REASON`). |
78
+
79
+ `normalizeInvoiceLineItemsResolution(value: InvoiceLineItem[] | InvoiceLineItemsResolution): InvoiceLineItemsResolution` applies the table. It returns `{ status: "ready", lines }` for an array or a well-formed `ready` resolution, and `{ status: "not_ready", reason }` for a `not_ready` one. Any other runtime value, such as a malformed object from an untyped resolver, becomes `not_ready` with `INVALID_RESOLUTION_REASON`. An empty bill is stated, never inferred from a malformed answer.
81
80
 
82
- An invoice finalized without some of its lines — a provider not ready at the deadline, invalid lines, Stripe refusing a line, or a draft changed outside dms-saas — never bills the missing usage: the gap favours the customer. The runtime logs it at error level (`invoice finalized with missing usage`) and calls `onUsageGap` on every provider the invoice was registered with, so the provider can raise an alert and its owner can fix the system. Each reason starts with a stable code (`provider_not_ready`, `managed_lines_unexpected_or_changed`, `before_finalize`, ...) followed by `:` and its detail.
81
+ An invoice can be finalized without some of its lines. The causes include a provider still not ready at the deadline, invalid lines, Stripe refusing a line, and a draft changed outside `@antelopejs/dms-saas`. The missing usage is never billed, so the gap favours the customer. The runtime logs the gap at error level (`invoice finalized with missing usage`) and calls `onUsageGap` on every provider the invoice was registered with, so the provider can raise an alert and its owner can fix the cause. Each reason starts with a stable code, such as `provider_not_ready`, `managed_lines_unexpected_or_changed` or `before_finalize`. Most codes are followed by `:` and a detail.
83
82
 
84
- `periodStart` is inclusive and `periodEnd` exclusive, so two adjacent cycle invoices cover disjoint windows. A preview covers the open cycle up to the request time; it is a quote of the next invoice, not an addition to it. A negative `amountCents` is a credit line.
83
+ `periodStart` is inclusive and `periodEnd` exclusive, so two adjacent cycle invoices cover disjoint windows.
85
84
 
86
- A provider that may still be loading when an invoice is created is listed in the runtime's `invoiceLineRequiredProviders` option so the invoice waits for it. See the [runtime configuration](/docs/modules/saas/configuration).
85
+ A provider that may still be loading when an invoice is created is listed in the runtime's `invoiceLineRequiredProviders` option, so the invoice waits for it. The [runtime configuration](/docs/modules/saas/configuration) describes the option.
87
86
 
88
- Preview calls set `isPreview: true`, use a synthetic `upcoming_<subscription id>` invoice ID, and end at the request time. They quote usage without invoicing it. Do not mutate usage accounting inside a resolver. A failed resolver or invalid line makes the preview unavailable.
87
+ Preview calls set `isPreview: true`, use a synthetic `upcoming_<subscription id>` invoice ID, and end at the request time. A preview quotes the open cycle's usage without invoicing it. It is a quote of the next invoice, not an addition to it. A resolver never changes usage accounting, because a preview can call it at any time. A failed resolver or an invalid line makes the preview `unavailable`.
89
88
 
90
89
  ### Line helpers
91
90
 
92
- `LINE_KEY_SEPARATOR` is `":"`. `buildInvoiceLineKey(providerId: string, key: string): string` joins the two fragments; it does not validate them.
91
+ `LINE_KEY_SEPARATOR` is `":"`. `buildInvoiceLineKey(providerId: string, key: string): string` joins the two fragments and does not validate them.
93
92
 
94
- `selectInvoiceLineItemsToCreate(providerId: string, items: readonly InvoiceLineItem[], alreadyInjectedKeys: ReadonlySet<string>): InvoiceLineItemSelection` is synchronous and has no Stripe side effects. It returns `accepted: PreparedInvoiceLineItem[]` (`{ lineKey, item }`, with trimmed item keys) and `skipped: SkippedInvoiceLineItem[]` (`{ lineKey, reason }`). `SkippedLineItemReason` is `already_invoiced`, `duplicate_key`, `zero_amount`, or `invalid`. The set must contain full provider-prefixed keys. This selection helper does not itself provide transactional idempotency.
93
+ `selectInvoiceLineItemsToCreate(providerId: string, items: readonly InvoiceLineItem[], alreadyInjectedKeys: ReadonlySet<string>): InvoiceLineItemSelection` is synchronous and has no Stripe side effects. It returns `accepted: PreparedInvoiceLineItem[]` (`{ lineKey, item }`, with trimmed item keys) and `skipped: SkippedInvoiceLineItem[]` (`{ lineKey, reason }`). `SkippedLineItemReason` is `already_invoiced`, `duplicate_key`, `zero_amount`, or `invalid`. `alreadyInjectedKeys` holds full provider-prefixed keys. The helper alone gives no transactional idempotency.
95
94
 
96
95
  ## Plan changes
97
96
 
98
- Import from `/plan-changes`. A module that owns tenant inventory (applications, environments, seats it counts) registers the policy SaaS consults before a paid-to-Free downgrade lands:
97
+ These names are exported from `/plan-changes`. A module that owns tenant inventory (applications, environments, the seats it counts) registers the policy that SaaS consults before a paid-to-Free downgrade lands:
99
98
 
100
99
  ```ts [Contract]
100
+ import type {
101
+ PlanChangeIncompatibility,
102
+ PlanChangeValidationRequest,
103
+ } from "@antelopejs/interface-dms-saas/plan-changes";
104
+
101
105
  interface PlanChangePolicy {
102
106
  name: string;
103
107
  validatePlanChange(
@@ -106,21 +110,23 @@ interface PlanChangePolicy {
106
110
  }
107
111
  ```
108
112
 
109
- `RegisterPlanChangePolicy(policy)` registers the sole policy and `UnregisterPlanChangePolicy(name)` removes it; registering opts deferred changes into the guarded paid-to-Free flow. `validatePlanChange` runs for the `preview`, `schedule` and `effective` phases; the effective call runs after DMS tenant admission is paused and earlier membership writers have drained. It must not mutate inventory or call Stripe. A missing policy, when the runtime's `requiredPlanChangePolicy` names one, fails closed.
113
+ `PlanChangeValidationRequest` has `tenantId: string`, `currentPlan: Plan | null`, `targetPlan: Plan`, `operationId: string`, `phase: "preview" | "schedule" | "effective"` and `effectiveAt: Date | null`. `PlanChangeIncompatibility` has `code: string`, `message: string` and an optional `resource: string`.
114
+
115
+ `RegisterPlanChangePolicy(policy: PlanChangePolicy): void` registers the sole policy, and throws when `name` is blank. `UnregisterPlanChangePolicy(name: string): void` removes it, but does not lift the restrictions on changes already persisted. Registering a policy opts deferred changes into the guarded paid-to-Free flow. Guarded paid-to-paid changes are not supported. `validatePlanChange` runs for the `preview`, `schedule` and `effective` phases. The effective call runs after DMS tenant admission is paused and earlier membership writers have drained. The callback does not mutate inventory or call Stripe. When the runtime's `requiredPlanChangePolicy` option names a policy that is not registered, plan changes fail closed. A second policy competing with the first also fails closed.
110
116
 
111
117
  | Function | Use |
112
118
  | --- | --- |
113
- | `GetTenantPlanConstraints(tenantId)` | Current and pending plan, `blocked`/`admissionBlocked` and the incompatibilities, for inventory writers to check after entering their own admission. Read-only, not a reservation. |
114
- | `CountOccupiedSeats(tenantId)` | Occupied seats, including unexpired invitations and excluding platform support. |
115
- | `GetPlanChangeActivation(tenantId)` | `{ planChangeOperationId, operationId, gateId }` of the only downgrade hold an activation consumer may release, or `null`. Match both operation IDs on the lifecycle message, evaluate every DMS access gate (`EvaluateTenantAccess`) and preserve every other denial. |
119
+ | `GetTenantPlanConstraints(tenantId: string): Promise<TenantPlanConstraints>` | `currentPlan`, `pendingPlan`, `effectiveAt`, `planChangeOperationId`, `blocked`, `admissionBlocked` and `incompatibilities`. Inventory writers read it after entering their own admission. It is a read-only snapshot, not a reservation. |
120
+ | `CountOccupiedSeats(tenantId: string): Promise<number>` | Occupied seats, including unexpired invitations and excluding platform support. Not a billing cache and not an atomic quota reservation. |
121
+ | `GetPlanChangeActivation(tenantId: string): Promise<PlanChangeActivation \| null>` | `{ planChangeOperationId, operationId, gateId }` of the only downgrade hold an activation consumer may release, or `null`. The consumer matches both operation IDs on the lifecycle message, evaluates every DMS access gate (`EvaluateTenantAccess`) and keeps every other denial. A `null` result or an error never authorizes a guarded delivery. The snapshot is not a reservation, so the consumer reads it again under its own sleep lock. |
116
122
 
117
- `TenantLifecycleMessage.planChangeOperationId` marks a lifecycle delivery produced by a guarded downgrade; never treat one you cannot authorize as an ordinary resume.
123
+ `TenantLifecycleMessage.planChangeOperationId` (optional) marks a lifecycle delivery produced by a guarded downgrade. A consumer that cannot authorize such a delivery never treats it as an ordinary resume.
118
124
 
119
125
  ## Tenant lifecycle
120
126
 
121
- Import from `/tenant-lifecycle`. `TENANT_LIFECYCLE_TRANSITIONS` contains `created`, `suspended` and `reactivation_requested`; `TenantLifecycleTransition` is their union.
127
+ These names are exported from `/tenant-lifecycle`. `TENANT_LIFECYCLE_TRANSITIONS` contains `created`, `suspended` and `reactivation_requested`, and `TenantLifecycleTransition` is their union.
122
128
 
123
- **Breaking migration:** Update `@antelopejs/interface-dms-saas` and `@antelopejs/dms-saas` together. The old `RegisterWorkspaceLifecycleConsumer`, `UnregisterWorkspaceLifecycleConsumer`, `WorkspaceLifecycle*` types, `WORKSPACE_LIFECYCLE_TRANSITIONS`, `IsWorkspaceProvisioningCommitted`, `/workspace-lifecycle` subpath and root `workspaceLifecycle` namespace are removed, without compatibility aliases. Use the tenant-named API below and root `tenantLifecycle` namespace instead. Persisted consumer IDs, transition values and operation IDs remain unchanged; keep existing consumer names and deduplication keys.
129
+ The package has no workspace-named lifecycle API and no alias for one. `RegisterWorkspaceLifecycleConsumer`, `UnregisterWorkspaceLifecycleConsumer`, the `WorkspaceLifecycle*` types, `WORKSPACE_LIFECYCLE_TRANSITIONS`, `IsWorkspaceProvisioningCommitted`, the `/workspace-lifecycle` subpath and the root `workspaceLifecycle` namespace do not exist. The tenant-named API below and the root `tenantLifecycle` namespace replace them, so this package and `@antelopejs/dms-saas` are upgraded together. Persisted consumer IDs, transition values and operation IDs are the same under both names, so existing consumer names and deduplication keys stay valid.
124
130
 
125
131
  ```ts [Contract]
126
132
  import type { TenantLifecycleTransition } from "@antelopejs/interface-dms-saas/tenant-lifecycle";
@@ -130,6 +136,7 @@ interface TenantLifecycleMessage {
130
136
  operationId: string;
131
137
  transition: TenantLifecycleTransition;
132
138
  requestedAt: Date;
139
+ planChangeOperationId?: string;
133
140
  }
134
141
  interface TenantLifecycleReceipt {
135
142
  receiptId: string;
@@ -149,16 +156,16 @@ declare function UnregisterTenantLifecycleConsumer(name: string): void;
149
156
  declare function IsTenantProvisioningCommitted(tenantId: string): Promise<boolean>;
150
157
  ```
151
158
 
152
- Names must match `/^[a-z][a-z0-9._-]{2,63}$/`; invalid names throw synchronously. Pick a stable unique name and explicitly select transitions. Unregister via the returned handle or by name when the module stops.
159
+ A consumer name matches `/^[a-z][a-z0-9._-]{2,63}$/`, and an invalid name throws synchronously. The name is stable and unique, and `transitions` lists every transition the consumer opts into. The module unregisters the consumer through the returned handle, or by name, when it stops.
153
160
 
154
- Delivery is **at least once**. Deduplicate by `operationId`, durably link provisioned resources, then return a durable receipt. A rejection is not an acknowledgement. Suspension closes SaaS access before delivery; reactivation keeps access closed until every registered required consumer returns a receipt. `created` arrives after ownership, billing and pre-provisioning hooks succeed and the first invoice is paid, or no payment is required.
161
+ Delivery is at least once. A consumer deduplicates by `operationId`, durably links the resources it provisions, then returns a durable receipt. A rejection is not an acknowledgement. Suspension closes SaaS access before delivery. Reactivation keeps access closed until every registered required consumer returns a receipt. `created` arrives after the ownership, billing records and pre-provisioning hooks succeed and the first invoice is paid, or when no payment is required.
155
162
 
156
- `IsTenantProvisioningCommitted` returns false for preparing, unpaid or cancelled self-service workspaces; true for committed creations and legacy/bootstrap tenants without a marker. It is not an existence, membership or access check. Storage and missing-implementation errors propagate; fail closed instead of treating an unavailable check as eligibility.
163
+ `IsTenantProvisioningCommitted` returns false for preparing, unpaid or cancelled self-service workspaces. It returns true for committed creations, and for legacy or bootstrap tenants without a marker. It is not an existence, membership or access check. Storage and missing-implementation errors propagate, and a caller fails closed instead of reading an unavailable check as eligibility.
157
164
 
158
165
  ## Registration and provisioning
159
166
 
160
- `TenantBeingProvisionedPayload` from `/provisioning` has `tenantId: string`, optional `userId: string`, and optional `extras: Record<string, unknown>`. Use it with the DMS `Hook.TENANT_BEING_PROVISIONED` hook; the hook handler returns `Promise<undefined>`, not `Promise<void>`. The runtime fires the hook through DMS `ProvisionTenant`, which registers the workspace's tenant-schema instance before any listener runs. DMS also fires it once for its `default` tenant, at its creation and without `userId`: write a tenant's default data in this hook, never in `start()` or `DATABASE_INITIALIZED`.
167
+ `TenantBeingProvisionedPayload` from `/provisioning` has `tenantId: string`, an optional `userId: string`, and an optional `extras: JsonObject`. `/json` exports `JsonObject` and `JsonValue`. The payload goes with the DMS `Hook.TENANT_BEING_PROVISIONED` hook, whose handler returns `Promise<undefined>`, not `Promise<void>`. The runtime fires the hook through the DMS `ProvisionTenant`, which registers the workspace's tenant-schema instance before any listener runs. DMS also fires the hook once for its `default` tenant, at its creation, without `userId` and with empty `extras`. A tenant's default data is written in this hook, never in `start()` or `DATABASE_INITIALIZED`.
161
168
 
162
- Listeners run serially inside provisioning, while the per-card lock is held, after workspace records exist but before registration returns. A throwing listener cancels registration and rolls back the runtime's tenant, subscription, Stripe customer and password-path account. Do not assume external side effects of your listener roll back automatically. Keep it to bounded persistence work rather than network provisioning; use durable `created` delivery for post-payment resources.
169
+ Listeners run in series inside provisioning, after the workspace records exist and before the first payment is settled or registration returns. When a signed-in user creates another workspace, the runtime also holds that workspace's card for the whole creation. A throwing listener cancels the registration. The runtime then rolls back its own tenant, subscription and Stripe customer, and deletes the account a password registration created. When the rollback itself fails, the runtime logs it and keeps the attempt for reconciliation. External side effects of the listener are not rolled back. A listener does bounded persistence work, not network provisioning, and post-payment resources go through the durable `created` delivery.
163
170
 
164
- Extras reach password and OAuth completion paths unchanged, are absent when nothing was captured, and remain consumer-owned. The runtime does not persist or return them. `/registration` exports `RegistrationExtrasLimits` and `REGISTRATION_EXTRAS_LIMITS`: `maxSerialisedBytes: 4096`, `maxKeys: 64`, `maxDepth: 4`. Public registration also rejects `__proto__`, `constructor`, and `prototype` keys. Rejected extras produce HTTP 400 `saas.errors.registration.extras_*` errors before listeners run.
171
+ The runtime passes `extras` to listeners as the registration captured them, from both the password and the OAuth completion paths. When nothing was captured, listeners receive an empty object. The extras belong to the consumer, and the runtime neither persists nor returns them. `/registration` exports `RegistrationExtrasLimits` and `REGISTRATION_EXTRAS_LIMITS`, which are `maxSerialisedBytes: 4096`, `maxKeys: 64` and `maxDepth: 4`. Public registration also rejects the keys `__proto__`, `constructor` and `prototype`. Rejected extras produce HTTP 400 errors (`saas.errors.registration.extras_invalid`, `extras_too_large` or `extras_too_complex`) before any listener runs.
@@ -1,25 +1,26 @@
1
1
  ---
2
2
  title: Pages, plans and data
3
3
  description: Stable page extension anchors, plan projections and safe use of the canonical data exports.
4
+ mode: reference
4
5
  ---
5
6
 
6
- # Pages, plans and data
7
-
8
7
  These contracts let consumers build backend-declared DMS pages without importing private SaaS controllers.
9
8
 
9
+ Importing `@antelopejs/interface-dms-saas` adds `workspaceScoped?: boolean` to DMS page options. Set it on detail pages whose URL names a record in the current workspace, for example `PageController("project", { displayName: "Project", urlSlug: "project/:id", hidden: true, workspaceScoped: true })`. Switching workspaces from that page lands on the homepage (`HOME_PATH`) instead of reloading the old record's URL. Pages that omit the flag or set it to `false` keep reloading the current URL.
10
+
10
11
  ## Page extensions
11
12
 
12
- Import from `/pages`. `tenantBillingPage` identifies `settings.workspace.billing` at `/settings/workspace/billing`. Its `components` exposes `freeAccessBanner`, `pastDueAlert`, `planCard`, `paymentMethod`, `billingForm`, `refundButton`, and `table` anchors. `TenantBillingPageComponentKey` is the union of those keys; `tenantBillingPageAnchorPaths` maps them to the current nested layout. Use keys instead of copying paths.
13
+ These names are exported from `/pages`. `tenantBillingPage` identifies `settings.workspace.billing` at `/settings/workspace/billing`. Its `components` holds the anchors `freeAccessBanner`, `pastDueAlert`, `planCard`, `paymentMethod`, `billingForm`, `refundButton` and `table`. `TenantBillingPageComponentKey` is the union of those keys. `tenantBillingPageAnchorPaths` maps each key to its path in the current nested layout. An extension names the key, never a copied path.
13
14
 
14
- `RegisterTenantBillingPageExtension(extension: TenantBillingPageExtension): TenantBillingPageExtensionRegistration` registers `{ name: string, components: readonly TenantBillingPageExtensionComponent[] }` and returns `{ unregister(): void }`. Registration may precede page loading; call the handle's `unregister()` during `stop()`.
15
+ `RegisterTenantBillingPageExtension(extension: TenantBillingPageExtension): TenantBillingPageExtensionRegistration` registers `{ name: string, components: readonly TenantBillingPageExtensionComponent[] }` and returns `{ unregister(): void }`. Registration can happen before the page loads. A module calls the handle's `unregister()` during `stop()`.
15
16
 
16
- Each component has `key: string`, `component: Component`, and optional `order: number` (default 0). An anchored component adds `side: "before" | "after"` and `anchorKey: TenantBillingPageComponentKey`; an appended component has optional `side: "end"` and no anchor. These are exported as `TenantBillingPageExtensionComponentBase`, `TenantBillingPageAnchoredExtensionComponent`, and `TenantBillingPageAppendedExtensionComponent`. The plan/payment anchors resolve inside their column's stack, not to an extra grid column.
17
+ Each component has `key: string`, `component: Component` and an optional `order: number` (default 0). An anchored component adds `side: "before" | "after"` and `anchorKey: TenantBillingPageComponentKey`. An appended component has an optional `side: "end"` and no anchor. These shapes are exported as `TenantBillingPageExtensionComponentBase`, `TenantBillingPageAnchoredExtensionComponent` and `TenantBillingPageAppendedExtensionComponent`. The plan and payment anchors resolve inside their column's stack, so a block placed beside one does not add a grid column.
17
18
 
18
- `platformSaasModule: CategoryInfo` is a synchronous descriptor, not the canonical registered module object. `GetPlatformSaasModule(): Promise<CategoryInfo>` resolves that object after runtime attachment and rejects when unavailable. `platformWorkspaceDetailPage` identifies `modules.saas.customers.workspaces.detail`, with `header`, `summary` and `body` anchors.
19
+ `platformSaasModule: CategoryInfo` is a synchronous descriptor, not the canonical registered module object. `GetPlatformSaasModule(): Promise<CategoryInfo>` resolves the registered object once the runtime is attached, and rejects when it is unavailable. `platformWorkspaceDetailPage` identifies `modules.saas.customers.workspaces.detail`, with the anchors `header`, `summary` and `body`.
19
20
 
20
- `RegisterPlatformWorkspaceDetailPageExtension(extension: PlatformWorkspaceDetailPageExtension): PlatformWorkspaceDetailPageExtensionRegistration` accepts `{ name: string, components: readonly PageExtensionComponent[] }` and returns an unregister handle. Use the DMS `PageExtensionComponent` placement contract for these blocks. These registrations do not grant access: the platform detail remains owner-only, and tenant page components need appropriate metadata/permissions.
21
+ `RegisterPlatformWorkspaceDetailPageExtension(extension: PlatformWorkspaceDetailPageExtension): PlatformWorkspaceDetailPageExtensionRegistration` takes `{ name: string, components: readonly PageExtensionComponent[] }` and returns an unregister handle. These blocks follow the DMS `PageExtensionComponent` placement contract. Neither registration grants access. The platform workspace detail page stays reserved to the platform owner, and tenant page components need their own metadata and permissions.
21
22
 
22
- `/page-definitions` exports `MODULES_ROOT_DEFINITION: PageInfo`, `SAAS_MODULE_ID = "saas"`, and `SAAS_MODULE_DEFINITION` (full ID, full slug and module registration metadata). These are descriptors, not runtime registration functions. The workspace settings category itself comes from `@antelopejs/interface-dms/page`.
23
+ `/page-definitions` exports `MODULES_ROOT_DEFINITION: PageInfo`, `SAAS_MODULE_ID` (`"saas"`) and `SAAS_MODULE_DEFINITION`, which holds the full ID, the full slug and the module registration metadata. These are descriptors, not runtime registration functions. The workspace settings category comes from `@antelopejs/interface-dms/page`, as the example shows.
23
24
 
24
25
  ```ts docs-check
25
26
  import { PageController, RegisterPage, workspaceSettingsCategory } from "@antelopejs/interface-dms/page";
@@ -35,31 +36,31 @@ export class WorkspaceRegistriesController extends PageController("registries",
35
36
 
36
37
  ## Plan helpers
37
38
 
38
- Import from `/plans`. These helpers do not charge customers or authorize access.
39
+ These helpers are exported from `/plans`. They do not charge customers or authorize access.
39
40
 
40
41
  | Function | Contract |
41
42
  | --- | --- |
42
- | `monthlyPrice(plan: Plan): number` | Returns the price as a monthly amount; yearly prices divide by 12 |
43
- | `isDowngrade(current: Plan \| null, target: Plan, seats?: number): boolean` | Compares monthly cost, multiplying seat plans by at least one seat; seats default to 1. No current plan returns false; equal cost is not a downgrade |
44
- | `localizeFeature(feature: Feature, locale: string): Feature` | Applies localization to `displayName`, `description`, `tooltip`, and `unit`, listed by exported `FEATURE_LOCALIZED_FIELDS`; missing translations fall back to the table locale (`en`) |
45
- | `localizePlan(plan: Plan, locale: string): Plan` | Applies localization to `name`, `description`, and `borderLabel`, listed by exported `PLAN_LOCALIZED_FIELDS`; missing translations fall back to `PLAN_FALLBACK_LOCALE` (`en`). `PlanModel` reads already return plans unlocked in that fallback locale |
46
- | `buildTenantPlanCatalog(planModel: PlanModel, featureModel: FeatureModel, plans: Plan[], locale: string): Promise<TenantPlanCatalog>` | Reads features, resolves plan inheritance, excludes unknown feature IDs and sorts plans/features by order; plan names and feature labels are read in `locale`; model read failures reject |
43
+ | `monthlyPrice(plan: Plan): number` | Returns the price as a monthly amount. A yearly price is divided by 12 |
44
+ | `isDowngrade(current: Plan \| null, target: Plan, seats?: number): boolean` | Compares the monthly cost. A per-seat plan is multiplied by `seats`, at least 1, and `seats` defaults to 1. A null `current` returns false, and an equal cost is not a downgrade |
45
+ | `localizeFeature(feature: Feature, locale: string): Feature` | Reads `displayName`, `description`, `tooltip` and `unit` in `locale`. `FEATURE_LOCALIZED_FIELDS` lists them. A missing translation falls back to `FEATURE_FALLBACK_LOCALE` (`en`, from `/db`) |
46
+ | `localizePlan(plan: Plan, locale: string): Plan` | Reads `name`, `description` and `borderLabel` in `locale`. `PLAN_LOCALIZED_FIELDS` (from `/db`) lists them. A missing translation falls back to `PLAN_FALLBACK_LOCALE` (`en`, from `/db`). Every `PlanModel` read already returns plans read in that fallback locale |
47
+ | `buildTenantPlanCatalog(planModel: PlanModel, featureModel: FeatureModel, plans: Plan[], locale: string): Promise<TenantPlanCatalog>` | Reads the features, resolves plan inheritance, drops unknown feature IDs and sorts plans and features by `order`. Plan names and feature labels are read in `locale`. A model read failure rejects |
47
48
 
48
49
  `TenantPlanCatalog` has `plans: TenantPlanView[]` and `features: TenantPlanFeature[]`.
49
50
 
50
- - `TenantPlanView`: `_id: string`, `name: string`, `price: number`, `currency: string`, `interval: PlanInterval` (`month` or `year`), `order: number`, `checkoutAvailable: boolean`, and `featureValues: Record<string, unknown>`. Checkout availability reflects a Stripe price reference, not an authorization decision.
51
- - `TenantPlanFeature`: `featureId: string`, `displayName: string`, `tooltip: string | null`, `unit: string | null`, `valueType: FeatureValueType` (`boolean`, `number`, or `string`), `isDetailRow: boolean`, and `order: number`.
51
+ - `TenantPlanView` has `_id: string`, `name: string`, `price: number`, `currency: string`, `interval: PlanInterval` (`month` or `year`), `order: number`, `checkoutAvailable: boolean`, and `featureValues: FeatureValues` (`Record<string, FeatureValue>`, from `/db`, where `FeatureValue` is `boolean | number | string | null`). `checkoutAvailable` is true when the plan has a Stripe price reference. It is not an authorization decision.
52
+ - `TenantPlanFeature` has `featureId: string`, `displayName: string`, `tooltip: string | null`, `unit: string | null`, `valueType: FeatureValueType` (`boolean`, `number`, or `string`), `isDetailRow: boolean`, and `order: number`.
52
53
 
53
- Keep caller-supplied plan/model scopes authorized. The catalogue builder does not filter an arbitrary plan list to what a user may buy. Write localized plan and feature texts using the canonical model's `localize("*")` convention, one value per locale (`{ en: "Pro", fr: "Pro" }`), never `$` i18n keys; see the [feature integration guide](/docs/modules/saas/extending#plan-feature-labels-and-values).
54
+ The catalogue builder does not filter an arbitrary plan list down to what a user may buy, so the caller authorizes the plans and models it passes. Localized plan and feature texts are written through the canonical model's `localize("*")` convention, with one value per locale (`{ en: "Pro", fr: "Pro" }`), never as `$` i18n keys. The [feature integration guide](/docs/modules/saas/extending#plan-feature-labels-and-values) shows the convention.
54
55
 
55
- ## HiddenStringFilter
56
+ ## `HiddenStringFilter`
56
57
 
57
- `HiddenStringFilter(): PropertyDecorator` is exported from `/data-api` and `/hidden-filter`. It registers string comparisons, including `is` for `TableView.routeParamFilters`, without a visible `@Column`. Apply it to the data controller prototype field, such as `_instance` or `userId`.
58
+ `HiddenStringFilter(): PropertyDecorator` is exported from `/data-api`, `/hidden-filter` and the root. It registers string comparisons, including the `is` mode that `TableView.routeParamFilters` uses, without a visible `@Column`. It decorates a field of the data controller prototype, such as `_instance` or `userId`.
58
59
 
59
- An unregistered filter can be silently dropped by the data API, so declaring a hidden route filter matters for scoping. The decorator itself does not authenticate a user or make a client-supplied tenant ID trustworthy; enforce the scope at the server authorization boundary.
60
+ The data API applies a filter only when its field is registered, and silently drops a route filter on any other field. Without the decorator, the table returns rows from every instance or user. The decorator does not authenticate a user or make a client-supplied tenant ID trustworthy. The server authorization boundary enforces the scope.
60
61
 
61
- ## Canonical database surface
62
+ ## Canonical database exports
62
63
 
63
- `/db` exports the table/model pairs for plans, features, subscriptions, billing info/state/settings, invoices, credit notes, refunds, legal documents, trial consumptions, segments, user segments, platform notes, plan migrations and Stripe webhook events. `/db/models` and `/db/tables` expose those groups separately. For example, `PlanModel` works with `Plan`, `FeatureModel` with `Feature`, and `TenantSubscriptionModel` with `TenantSubscription`; use their shipped TypeScript declarations for persistence fields and methods.
64
+ `/db` exports the table and model pairs for plans, features, subscriptions, billing info, billing state, billing settings, invoices, credit notes, refunds, legal documents, trial consumptions, segments, user segments, platform notes, plan migrations and Stripe webhook events. `/db/models` and `/db/tables` expose those groups separately. For example, `PlanModel` works with `Plan`, `FeatureModel` with `Feature`, and `TenantSubscriptionModel` with `TenantSubscription`. Their published TypeScript declarations list the persistence fields and methods.
64
65
 
65
- These are registered persistence objects, not copies to redeclare. Imports have registration side effects; prefer type-only imports for types. Direct model writes bypass runtime orchestration and require correct tenant scope. See the [database boundary](./1.index.md#database-imports-have-side-effects) before writing seeds or imports, and [recompute derived billing state](./2.billing.md#recomputetenantbillingstate) after writing relevant records.
66
+ These are registered persistence classes, not copies to redeclare. Importing them registers the tables, so a type-only import suits a type. Direct model writes skip the runtime's orchestration and need the correct tenant scope. The [database boundary](./1.index.md#database-imports-have-side-effects) covers seeds and imports, and [`RecomputeTenantBillingState`](./2.billing.md#recomputetenantbillingstate) refreshes the derived billing state after the writes.
@@ -2,10 +2,18 @@
2
2
  "extends": "../tsconfig.json",
3
3
  "compilerOptions": {
4
4
  "rootDir": "..",
5
+ "module": "esnext",
6
+ "moduleResolution": "bundler",
7
+ "noUnusedLocals": false,
8
+ "noUnusedParameters": false,
5
9
  "composite": false,
6
10
  "incremental": false,
7
11
  "declaration": false,
8
- "noEmit": true
12
+ "noEmit": true,
13
+ "paths": {
14
+ "@antelopejs/interface-dms-saas": ["../src/index.ts"],
15
+ "@antelopejs/interface-dms-saas/*": ["../src/*"]
16
+ }
9
17
  },
10
18
  "include": ["../src/**/*.ts", "./**/*.ts"]
11
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/interface-dms-saas",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "AntelopeJS interface for the DMS SaaS module: billing, plans, registration, workspace pages and lifecycle extension points.",
5
5
  "keywords": [
6
6
  "antelopejs",
@@ -59,29 +59,25 @@
59
59
  },
60
60
  "scripts": {
61
61
  "build": "rimraf dist && tsc",
62
- "lint": "oxlint && oxfmt --check .",
63
- "lint:fix": "oxlint --fix --max-warnings=1000000 && oxfmt .",
64
- "format": "oxfmt .",
65
62
  "typecheck": "tsc --noEmit",
66
63
  "check:exports": "node scripts/check-exports.mjs",
67
64
  "knip": "knip --dependencies",
68
65
  "knip:all": "knip",
69
- "release": "pnpm run lint && pnpm run build && release-it",
66
+ "release": "pnpm run build && release-it",
70
67
  "prepack": "pnpm run build"
71
68
  },
72
69
  "dependencies": {
73
- "@antelopejs/interface-data-api": ">=0.4.0 <1.0.0",
74
- "@antelopejs/interface-dms": ">=0.9.0 <1.0.0"
70
+ "@antelopejs/interface-data-api": ">=0.6.1 <1.0.0",
71
+ "@antelopejs/interface-dms": ">=0.12.0 <1.0.0"
75
72
  },
76
73
  "devDependencies": {
77
- "@antelopejs/interface-core": ">=0.2.4 <1.0.0",
78
- "@antelopejs/interface-database": ">=0.1.11 <1.0.0",
79
- "@antelopejs/interface-database-decorators": ">=0.1.10 <1.0.0",
74
+ "@antelopejs/interface-api": ">=0.3.0 <1.0.0",
75
+ "@antelopejs/interface-api-util": ">=0.3.0 <1.0.0",
76
+ "@antelopejs/interface-core": ">=0.4.0 <1.0.0",
77
+ "@antelopejs/interface-database": ">=0.3.0 <1.0.0",
78
+ "@antelopejs/interface-database-decorators": ">=0.2.0 <1.0.0",
80
79
  "@types/node": "^24.0.0",
81
80
  "knip": "^6.34.0",
82
- "oxfmt": "^0.66.0",
83
- "oxlint": "1.81.0",
84
- "oxlint-tsgolint": "^7.0.2001",
85
81
  "release-it": "^19.2.4",
86
82
  "release-it-changelogen": "^0.1.0",
87
83
  "rimraf": "^6.1.3",
@@ -1 +0,0 @@
1
- export declare function updatedRows(result: unknown): number;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.updatedRows = updatedRows;
4
- function updatedRows(result) {
5
- if (typeof result === "number")
6
- return result;
7
- const counts = result;
8
- return Number(counts?.replaced ??
9
- counts?.modifiedCount ??
10
- counts?.deleted ??
11
- counts?.deletedCount ??
12
- 0);
13
- }
14
- //# sourceMappingURL=revision.js.map