@playstack/audiences
Local-authoritative lists, consent evidence, subscriptions, signed preference flows, tags, and data-only segments.
Reference: @playstack/audiences@0.1.0-beta.5 · TypeScript
Pro. Covered by the Playstack Pro License. Registry access is required; check preview availability before installing. See package access.
@playstack/audiences owns the durable meaning of an audience: lists, subscribers, per-list subscription edges, append-only consent evidence, tags, and versioned segment definitions. It resolves recipients; it never composes or sends a campaign.
Install
npm install @playstack/audiences @playstack/delivery @playstack/eventsCompose and subscribe
import { createAudiences } from '@playstack/audiences'
const audiences = createAudiences({
persistence,
suppression: delivery,
tokens,
normalizer: { normalize: normalizeEmail },
abuse: signupAbuseGate,
segments,
events,
clock,
ids,
})
await audiences.createList({
key: 'release-notes',
name: 'Release notes',
topic: 'release-notes',
authority: 'local',
doubleOptIn: true,
})
const result = await audiences.subscribe('release-notes', {
email: form.email,
source: 'launch-page',
})The trusted server result contains the token required to send a confirmation. Public controllers must return only a uniform accepted state and must never echo confirmation, preference, or unsubscribe tokens.
Admit consent before issuing credentials
createAudienceAdmissions() is the narrower profile for applications that mint
bearer credentials during claimed worker preparation. It requires no token issuer
or segment adapter. Subscription admission returns state and opaque identifiers;
confirmation returns state without issuing preferences or unsubscribe tokens.
The existing createAudiences() convenience APIs retain their token results.
The required confirmation-intent sink joins subscriber state, consent evidence and an identifier-only durable intent on the same physical transaction. It runs again for every abuse-admitted pending retry, without duplicating consent evidence. The sink must enforce its durable cooldown, limits and original-key deduplication; failure rolls back the entire mutation. Acknowledging admission requires a durable intent for that enrollment, including when reusing an existing intent. No broker, provider send or independent root transaction belongs in this callback.
Both operations can join a caller transaction. The minimal persistence contract must assert that the original handle is live; a matching transaction-kind string alone is insufficient. Propagate failures so the caller rolls back, and expose results only after commit.
For affected Prisma/adapter combinations, retain the qualified Prisma dispatch fence. Handle checks and ordinary rollback tests do not qualify delayed SQL after an unfenced rollback; this profile does not repair that separate driver behavior.
Confirmation verifies the supplied credential and takes native contact/subscription
locks before running an optional current-proof authorization grant. This is where
a canonical application checks or consumes its original enrollment-bound proof
on the same transaction. Native consentRevision fences stale work; it is not a
replacement for the application's confirmation-incarnation authority. Removal
and rejoining must not let an older proof authorize the new enrollment.
A supported composition registers a native Delivery attempt with
contentBinding: 'per-submission' in the sink, under the host's enrollment and
admission-policy locks. Its immutable key and logical request hash contain opaque
authority references. An Events outbox wakeup can refer to that intent; workers
recover from the durable attempt even if the wakeup is lost. Only claimed worker
preparation rechecks current authority, mints the credential, renders and binds
the complete message. Preserve the original attempt budget and quarantine
uncertain outcomes without reminting.
Keep source and attempt lock ordering consistent. In this recipe, a pending retry observes its existing attempt without taking that attempt's lock and retains the current intent key. Only fresh, unexposed keys are registered while holding source locks. Re-registering an in-flight key there can invert the worker's attempt/source lock order; qualify competing admission and preparation.
Native Notifications queue/admission methods own root transactions, so they cannot be called as the audience write's transactional sink. An application using them hands off after its durable source intent commits. The encrypted confirmation producer below is a separate supported profile for credentials issued at admission.
Current state and paged consent evidence
Current subscriptions carry consentRevision, not an embedded lifetime history.
Native subscribe/confirm writes state, immutable evidence and transactional
handoffs together. The Prisma artifact stores evidence separately; canonical
application persistence can implement the same public appendConsent and
listConsent ports without copying its contact authority into another store.
Ordinary state mutations and subscriber listings do not load the history.
Authorized operators can use
audiences.listConsent(listKey, subscriberId, { limit, cursor }) for 1–100 rows.
The cursor binds the list, subscriber and initial revision ceiling; it is not
authorization. Later appends do not extend an in-progress history. The guarded
Nest management binding exposes the same bounded read. Reauthorize every page,
keep raw evidence private, and treat the host admin detail as a bounded preview.
When explicitly approved for export, consentProvenance contains
{ items, nextCursor? }, with at most 25 initial evidence rows per subscriber.
Continue its cursor with AudienceExports.consentPage(...); it independently
checks current export authority and records a same-transaction safe audit.
Neither contact pagination nor an initial provenance page implies complete export.
This storage change requires reviewed schema activation. Populated installations must preserve original consent facts, order and generation bindings through an explicit offline migration/import; no history is fabricated or automatically backfilled. The repository host migration refuses populated subscriptions before destructive DDL. Apply and qualify the reviewed transition before new runtimes start. Erasure counts evidence against its configured cleanup bound and fails closed rather than claiming that partial cleanup erased a subscriber.
Configuration reference
AudiencesOptions property | Required | Purpose |
|---|---|---|
persistence | Yes | Transactional lists, subscribers, subscriptions, tags, and segment queries. |
suppression | Yes | Topic suppression writer from @playstack/delivery; it must share the persistence transaction kind. |
tokens | Yes | Issues and verifies purpose-bound confirmation, preference, and unsubscribe tokens. |
normalizer | Yes | Applies the application's email normalization policy. |
abuse | Yes | Runs rate-limit, CAPTCHA, honeypot, or other signup policy before mutation. |
segments | Yes | Validates and compiles data-only segment definitions where subscriber data lives. |
remote | No | Queue and provider authority for remote-owned lists. |
confirmationDelivery | No | Persists encrypted confirmation admission using the actual consent transaction. |
operatorRemoval | No | Mandatory transaction-bound action authority when enabling soft subscription removal. |
events | Yes | Emits list, consent, subscription, and remote-operation lifecycle events. |
clock, ids | Yes | Application-owned time and identifiers. |
| token TTL properties | No | Override confirmation, preference, and unsubscribe token lifetimes. |
onTokenError | No | Observes token failures without exposing them to a public response. |
Bridge contracts
| Contract | Boundary |
|---|---|
AudiencePersistence | Transactional audience storage and database-side subscriber queries. |
AudienceTokenIssuer | Purpose-bound signed tokens; exposes its application-owned client. |
AudienceEmailNormalizer | Explicit normalization without provider-specific alias assumptions. |
AudienceAbuseGate | Pre-mutation public signup policy. |
AudienceSegmentCompiler | Validates and compiles versioned data-only segment trees. |
AudienceRemoteCommandQueue | Transactional, endpoint-free subscribe and unsubscribe intent. |
AudienceRemoteAuthority | Provider-specific segment validation, mutations, and recipient queries. |
AudienceConfirmationDelivery | Transaction-bound encrypted confirmation admission; never inline provider I/O. |
Durable confirmation mail
Use AudienceConfirmationOutbox from @playstack/audiences/confirmation and
PrismaAudienceConfirmationPersistence from @playstack/audiences/confirmation/prisma
to persist encrypted confirmation intents with consent. Explicitly select the
optional audiences.confirmations.prisma artifact and apply your reviewed
migration before enabling it. Compose native CryptoSuite, the same audience token
issuer, a fixed deployment namespace, globally unique IDs and current host
canDeliver policy. Cooldown, maximum unexpired intents, token TTL and lease
duration are required server configuration; the existing public abuse gate remains.
Schedule bounded recover(limit) and scrubExpired(limit) batches. Recovery
hands identifier-only references to native Notifications using stable logical
keys. Durable notification admission and the downstream queue must retain those
keys across consumed jobs and lost acknowledgments. A broker's short deduplication
TTL is insufficient. Recovery is not provider delivery or exactly-once email.
The private mail worker uses resolve(reference) to recheck current consent,
authority, recipient and proof bindings before rendering. Its transient email/token
result must never reach browser responses, ordinary jobs, admissions, logs or
events. Native Mail/Delivery suppression and encrypted/uncertain-attempt handling
remain required. No public key-ID resolver or identity/account provisioning is
installed. Nest's post-commit onSubscriptionResult is not an atomic mail handoff.
For native Delivery attempt preparation, resolveInTransaction(reference, tx)
joins those checks to the original caller handle without a nested transaction.
Its transient result is not a committed send grant. Provider I/O must await the
outer commit; native suppression, encrypted content, immutable request hashes,
compatible locks and the check-to-send race still require qualification.
Expired ciphertext is scrubbed in bounded batches; replay IDs remain as tombstones. This is not full subscriber erasure. Production Mail composition, erasure policy and actual application/provider qualification remain separate activation gates.
Compose the durable handoff
The portable playstack add audiences --adapter=confirmations --dry-run recipe
reports these obligations without choosing a provider or starting a scheduler:
- Select the native audience, confirmation, notification admission/queue, Delivery attempt and suppression artifacts that the application uses. Review and apply migrations first; configure native Crypto, purpose-bound tokens, immutable namespaces, IDs, limits and compatible transaction lock ordering.
- Join encrypted confirmation admission to the original consent write. Return uniform public acceptance only after commit. A post-commit callback alone can lose mail handoff on a crash and is not this composition.
- Recover the original opaque reference through durable Notifications admission
with the same logical key.
PrismaNotificationQueueand its optionalnotifications.queue.prismaartifact retain independent replay receipts after completed jobs are deleted. A bounded queue consumer joins Delivery registration, protected content and an outbox on its supplied transaction; no provider I/O,notifications.process()or nested root transaction belongs in that callback. - Resolve proof/consent/recipient authority and suppression using the original Delivery preparation handle. Bind the approved template, configured callback origin, recipient, proof and expiry to the immutable request hash. Keep secrets transient or protected, never in ordinary jobs, events or logs.
- Only a newly committed Delivery begin grants Mail I/O. Unknown outcomes stay quarantined; queue replay is not permission to resend. Schedule bounded recovery, proof scrubbing, cleanup and shutdown, and qualify actual driver fencing and provider cancellation.
Public GET inspection does not mutate consent. Native POST confirmation is not signup, session issuance or early-access admission. Welcome mail is a separate approved confirmed-event notification with its own stable key and current suppression. Preferences/unsubscribe have separate token purposes; do not use a marketing welcome's transactional label to evade consent. Invitation mail uses the distinct native invitation lifecycle.
The packaged README contains the maintained sequence and privacy activation checklist. Local capture-provider/PostgreSQL fixtures exercise the handoff, not live sender verification, templates, deployed queues, provider delivery or cross-store erasure. Optional webhooks must not become a signup/mail prerequisite.
The maintained PostgreSQL confirmation fixture additionally composes native Mail
with a capture provider and native Delivery attempts on Prisma 6.19.3/7.9.1.
Rollback/no-send-before-commit, duplicate refusal, changed recipients, current
policy/consent/expiry and suppression checks, and unknown-outcome quarantine pass.
Use checkSuppressionInTransaction with the original preparation handle and a
recomputed immutable request hash. This is local fixture evidence, not live email,
rendered templates, deployed queue/scheduler/driver safety or complete erasure.
Remote-authoritative lists use createAudienceRemoteQueue to register original
identifier-only intents in the queue admission transaction, and
createAudienceRemoteProcessor to claim a retained keyed target before provider
submission. Select/migrate optional audiences.remote.prisma and wire its journal,
exact backing persistence and qualified transaction fence where required. Native
Prisma 7 registration and workers refuse unfenced execution. Native Prisma 6
registration requires the backing Audience persistence runner for the outer
joined workflow; arbitrary foreign handles are not attested by a root's identity. Producer-only admission requires no
provider SDK, endpoint lookup or token issuance.
processRemote() returns completed, stale, quarantined or blocked.
Only trusted exact-command proof of no mutation permits retry. Unknown/partial
submission and lost acknowledgments keep permanent target barriers; age and
redelivery never grant a new send. Accepted receipts survive projection/event
rollback and replay without provider I/O. Changed endpoints or resolved provider
configuration cannot activate the wrong contact. Missing registration refuses;
unconfigured pending workers fail closed. Quiesce older workers and review prior
pending/uncertain work rather than inventing registration evidence.
Keep a stable keyed canonical endpoint hasher, provider-account identity and namespace across lists and erasure/re-enrollment, and retain journal barriers. Host complaint, new-intent authorization and retention remain explicit policy; provider work already in flight cannot be recalled. Remote reads stay with the provider and mirrored authority remains unsupported. See the package README for worker/producer wiring and the custom-adapter contract.
@playstack/audiences-resend implements the remote-authority boundary with Resend Contacts and Segments. Playstack retains consent, confirmation, suppression, and idempotent command state while Resend becomes the explicitly selected contact authority. Removing one subscription removes only that segment membership; fresh explicit consent may clear the contact's global unsubscribe state.
Early-access invitations
AudienceInvitations from @playstack/audiences/invitations supplies explicit
confirmed-subscriber batch preview/commit, authenticated recipient inspection and
acceptance, operator status/revoke/reissue, encrypted proof intents and stable
identifier-only recovery. Select/migrate audiences.invitations.prisma for the
native /invitations/prisma adapter. Consent and proof possession do not create an
identity, account or membership. New recipients first complete native Auth signup;
existing recipients need an authenticated active verified identity.
Operator authority, current recipient/activity, suppression/eligibility,
transaction-bound admission and native Events/Audit ports are mandatory. Native
Prisma uses Read Committed and subscriber-before-subscription locking; qualify
compatible host identity/attempt/suppression order. Private
resolveInTransaction(reference, tx) joins send preparation, not a send grant.
Await committed begin before external Mail I/O. Reissue invalidates the old proof;
expiry/revocation/acceptance clear ciphertext while replay tombstones remain.
The package installs no invitation routes, automatic signup, mail provider,
scheduler, product entitlement or complete erasure policy. Batches use explicit
IDs, not an automatic priority/segment policy. The explicit CLI
audiences --adapter=invitations plan reports those adoption gates.
Prisma and testing
@playstack/audiences/prisma exports PrismaAudiencePersistence and PrismaAudienceSegmentCompiler. Built-in segment nodes compile to parameterized SQL and application resolvers return predicates with separately supplied values. The managed audiences.prisma artifact remains application-migrated.
@playstack/audiences/testing supplies deterministic in-memory persistence, token, topic-suppression, segment, queue, and remote-authority fixtures. They are not production persistence or cryptography.
Operator reads
listSubscribers(listKey, { status, tag, segmentKey, cursor, limit }) remains
active-only by default; trusted management callers can explicitly query pending,
active, removed or all records. Tag filters intersect stored segments.
getSubscriber(listKey, subscriberId) returns list-bound subscription/consent/tag
detail or null, not a raw global subscriber lookup. These advanced reads are
local-authoritative; remote providers reject unsupported management filters.
Every read needs current server-side management authority. A deployment operator
waitlist is not customer account administration. Minimize provenance fields in
browser responses and route the identifier-only query/inspection events through
the host's audit composition. Cursors bind list and filters but are not credentials;
reset pagination when changing filters or adopting the current cursor format.
Native Nest management routes expose these reads under their required guard.
Read-only AudiencesSection, AudienceSubscribersTable and
AudienceSubscriberDetail are available from @playstack/admin-ui. The host
supplies authorized safe projections and immutable scope/list/query generations;
the section refuses mismatched page/detail responses and gates extension slots.
Fetch cancellation remains host-owned. Export, removal and all-list erasure have
separate opt-in contracts below; the read-only section installs none of them.
Operator administration and removal
Use native scoped management reads with Admin UI's AudiencesSection, subscriber
table/detail and AudienceInvitationsSection; the host supplies routes, safe
projections and trusted operator access. Customer account roles do not implicitly
grant deployment-list authority. UI permission hints never replace server checks.
Optional operatorRemoval authorizes
removeSubscription(listKey, subscriberId, { principal, source }) on the exact
write transaction, including missing-edge/replay calls. principal is the trusted
server identity and source is server-owned provenance. Local removal retains
consent history, applies topic suppression and emits the native removed event;
remote lists retain native unsubscribe/suppression commands until convergence.
This is soft removal, not subscriber erasure or proof issuance. Rejoining needs
fresh native consent, and old invitation consent bindings cannot revive.
Trusted authenticated workflows can instead call
withdrawSubscriptionInTransaction(listKey, subscriberId, { source, authorize }, transaction, context?)
without a temporary preferences token or deployment-operator configuration. The
host callback binds the current identity/workflow to the exact list/contact on
that handle, before mutation and after required suppression/event/queue writes.
IDs and tracing context grant no permission. Keep early host identity locks and
native contact/subscription locks in compatible order; propagate refusal so the
whole caller transaction rolls back. Return acceptance only after outer commit.
Withdrawal retains contact/consent history and uses the existing local removal or
remote identifier-only unsubscribe intent. It calls no token issuer, verifier or
provider, and adds no public route or remote-uncertainty guarantee. The existing
full-service constructor ports remain required. Custom AudiencePersistence
must implement the published assertTransaction contract; native joined writes
require a live ReadCommitted handle. No schema migration is needed.
Nest exposes the route only with explicit operatorRemoval callbacks:
POST /audiences/subscribers/:subscriberId/remove?list=... accepts an empty body.
Keep its management guard, per-action native authority, Origin/CSRF and rate policy.
Admin UI's standalone AudienceSubscriptionRemoval confirms the action and waits
for authoritative reload; aborting browser waiting does not roll back a server
commit. Export/download and all-list erasure remain separate contracts, not
direct-row deletion buttons.
Authorized export and all-list erasure
AudienceExports from @playstack/audiences/export returns bounded live keyset
JSON pages using native persistence and segment queries, without a second contact
store. Required operator/list/field authorization and safe action recording join
the original physical transaction; audit failure withholds the page. Cursors bind
the deployment, export, list, filters and approved fields, not authentication.
Remote lists refuse. The host owns private no-store downloads, whole-export
time/row/byte/rate budgets, output retention and CSV formula escaping if converting.
These pages are not an immutable snapshot and returned data cannot be recalled.
AudienceSubscriberLifecycle from @playstack/audiences/lifecycle and
PrismaAudienceLifecyclePersistence from /lifecycle/prisma supply explicit
all-list local-contact erasure, including remote-linked contacts. Every
erase input and accepted receipt carries target: 'local-contact'; provider
authority is unchanged and remote list queries can still return provider data. Review the nullable
email/tombstone migration and apply the exported /lifecycle/constraints.sql
resource; Prisma does not create that CHECK automatically. Configure every
installed confirmation/invitation producer namespace, current authority over
every affected list and mandatory same-handle before/after cleanup and Audit hooks.
A partial list selection is not erasure authority. Both inspect and erase
accept an optional caller transaction. Required assertTransaction guards the
handle before beforeLock host admission establishes GLOBAL then SUBJECT locks
ahead of native invitation/contact locking. That hook receives no early contact;
verify the stable keyed binding in beforeErase. Final same-handle authorization
follows cleanup/evidence, including missing/repeated requests. Propagate refusal
to roll back host/native writes together and disclose acceptance after commit.
Custom lifecycle adapters update the guard and explicit-target contract; no new
schema change is introduced beyond the existing contact/tombstone CHECK.
Native erasure clears contact/user links, consent evidence, tags and selected producer secrets while retaining opaque tombstones, removed edges, exact remote operation/command markers and replay/suppression evidence. Markers remain even on a now-local list and never acknowledge provider completion. Erasure sends no provider request, queues no remote unsubscribe and retries no uncertain operation. It is not account deletion, legal anonymity or automatic cleanup of survey stores, admissions/queues, protected payloads, exported files, providers, WAL or backups. External cleanup needs durable recovery because repeated native erasure does not rerun cleanup hooks. An active sender cannot be recalled. Qualify complaint/bounce policy and fresh enrollment separately: a new subscriber ID does not automatically inherit old subject-bound suppressions. Remote-linked hooks must retain host-owned uncertain-command journals and keyed complaint/ provider-suppression/cross-ID enrollment fences. Fresh consent must still consult those barriers; the native subject-only store supplies no cross-ID policy. Old-ID queued work becomes stale, while already-prepared provider I/O can still finish. The later native result cannot restore the erased contact; host drainage and durable remote-outcome handling remain separate qualification gates.
Expose AudienceExport or AudienceSubscriberErasure from Admin UI only after
their independently authorized workflows are qualified. UI hints, soft removal,
receipt deletion or a local accepted result do not establish complete erasure.
Boundary
Fresh consent removes only the exact list suppression retained by the removed subscription. It never clears channel-wide or unrelated list suppressions. Email equality also never links a subscriber to a user; verifiedUserId is accepted only through a trusted application call.
API entry points and requirements
Reference snapshot: @playstack/audiences@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.
| Public entry point | Declaration file |
|---|---|
@playstack/audiences | ./dist/index.d.ts |
@playstack/audiences/errors | ./dist/errors.d.ts |
@playstack/audiences/export | ./dist/export.d.ts |
@playstack/audiences/lifecycle | ./dist/lifecycle.d.ts |
@playstack/audiences/lifecycle/prisma | ./dist/lifecycle-prisma.d.ts |
@playstack/audiences/lifecycle/constraints.sql | No TypeScript declaration (asset or metadata export). |
@playstack/audiences/prisma | ./dist/prisma.d.ts |
@playstack/audiences/confirmation | ./dist/confirmation.d.ts |
@playstack/audiences/confirmation/prisma | ./dist/confirmation-prisma.d.ts |
@playstack/audiences/invitations | ./dist/invitations.d.ts |
@playstack/audiences/invitations/prisma | ./dist/invitations-prisma.d.ts |
@playstack/audiences/testing | ./dist/testing.d.ts |
@playstack/audiences/playstack.integration.json | No TypeScript declaration (asset or metadata export). |
@playstack/audiences/package.json | No TypeScript declaration (asset or metadata export). |
@playstack/audiences/remote/prisma | ./dist/remote-prisma.d.ts |
@playstack/audiences/remote/testing | ./dist/remote-testing.d.ts |
Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.
Peer dependencies
This package declares no peer dependencies. Its ordinary dependencies are resolved by the package manager.
For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.