@edclass/ivs-providers
v1.3.24
Published
React providers and a publication-centric core for Amazon IVS Real-Time stages. **One API** — the old v1/v2/v3 layering is gone (1.0.0).
Keywords
Readme
@edclass/ivs-providers
React providers and a publication-centric core for Amazon IVS Real-Time stages. One API — the old v1/v2/v3 layering is gone (1.0.0).
Architecture
┌───────────────────────────────────────────────────────────┐
│ SURFACE PROVIDERS (src/providers.tsx) │
│ OwnStreamProvider · viewer hooks · CallStreamProvider │
└──────────────┬────────────────────────────┬───────────────┘
│ publish via │ join/state via
┌──────────────▼──────────────┐ ┌──────────▼───────────────┐
│ PUBLICATION (src/publication)│ │ STAGE ENGINE (src/stage) │
│ PublicationManager │ │ registry (refcounted │
│ PublisherPlane (single- │ │ acquire/release, token │
│ destination per source) │ │ rotation), engine hook, │
│ driver → stage registry │ │ EDIvsStage/Strategy │
└──────────────────────────────┘ └──────────────────────────┘
┌───────────────────────────────────────────────────────────┐
│ DEVICE (src/device, src/hooks) — capture + controls ONLY │
│ EDDeviceManagerProvider · useEDUserMedia/useEDDisplayMedia│
│ NEVER publishes. No stage pointers. │
└───────────────────────────────────────────────────────────┘Core rules:
- A capture source is published to AT MOST ONE stage (
PublisherPlane, keyed bysourceOwnerId). Moving it is end-before-publish — a camera can never be live on two stages, and ending a call can never leave the camera on the callee's stage. - The device layer never publishes. It captures (
userMedia.mediaStreamsingleton — tracks swapped in place, so gate onuserMedia.cameraOn, never on stream truthiness) and controls (mute/switch/screen-share prompt). - One stage ARN hosts BOTH participant groups (
user+displaytokens). Legacy rosters remain group-filtered. New purpose policies make private ingress publish-only and allow an authorised personal-stage viewer to see the replicated User camera plus only the private Display needed for the monitor card.
The three surfaces
OwnStreamProvider — resident broadcast (student uplink, teacher on-duty)
<OwnStreamProvider
joinData={joinData} // room + per-group stage configs
cameraStream={userMedia.cameraOn ? userMedia.mediaStream : null}
screenStream={screenStream} // gesture-provided; null = not sharing
shouldPublish={policy} // e.g. in-slot latch, on-duty, call-active
subscribe={false} // optional publish-only uplink; default true
screenSubscriptionFilter={fn} // optional display-roster policy; MUST be
// identity-stable (useCallback)
autoJoin={Boolean(joinData)}
sourceOwnerId={localUser.id} // ALWAYS the local user, never the room host
>Both subscription knobs COMPOSE across every surface holding the
registry-shared stage: the stage subscribes only while no holder passes
subscribe={false}, and a remote participant must pass every registered
screenSubscriptionFilter. Most-restrictive wins — a publish-only surface
denies subscriptions for all co-holders of that room's stages, so don't mount
one on a room another surface needs to watch.
useOwnStream() → { camera, screen, cameraPlane, screenPlane, onCall }.
camera/screen are stage values (connectState, publishState,
getParticipants, on/off, mute toggles, updateStreamsToPublish).
useViewerStage — subscribe-only
const user = useViewerStage(joinData, 'user')
const display = useViewerStage(joinData, 'display')Joins on data, auto-rejoins on disconnect, releases on unmount. No manual join/leave — never rebuild one (that's the flap class the rewrite killed).
Private monitor stages — purpose-bound
usePersonalStageViewer(personalJoinData) joins one subscribe-only personal
stage credential. It exposes the replicated camera and private monitor screen;
the strategy cannot publish and excludes a public classroom Display.
useMonitorIngressStage({ joinData, publication, publicationEpoch }) joins one
learner/teacher private-ingress credential. publication accepts only the
successful result type returned by displayMedia.startMonitorShare(...); a
rejected or stale capture cannot be published, replace a newer stream, or stop
one. Both hooks are route-agnostic and never open the browser picker.
CallStreamProvider — on-demand staff call
<CallStreamProvider
callData={callData ?? null} // the STUDENT's room while a call runs
cameraStream={userMedia.cameraOn ? userMedia.mediaStream : null}
screenStream={callScreenStream}
audioOnly={voiceOnly}
sourceId={staffUser.id} // bare owner id; same id as OwnStream for a
> // teacher = call auto-cuts/restores broadcastuseCallStream() → { call, screen, cameraPlane, screenPlane, active }.
Setting callData joins + publishes; clearing it stops the planes and leaves.
Unmount always stops the planes (no publication is ever left behind in the
singleton PublicationManager).
Device layer
<EDDeviceManagerProvider>
const { userMedia, displayMedia, stopDevices } = useEDDeviceManager()
await userMedia.startUserMedia() // capture camera+mic
const s = await displayMedia.startScreenShare() // gesture-driven prompt
const monitor = await displayMedia.startMonitorShare({
epoch,
isCurrentEpoch,
onHealth,
}) // gesture-driven; accepts only displaySurface === 'monitor' by default
// Trusted teacher surfaces may explicitly allow the browser's other choices.
await displayMedia.startMonitorShare({
epoch,
allowedDisplaySurfaces: ['monitor', 'window', 'browser'],
})Media failure diagnostics
Every capture, stage and publish failure the package can observe is reported
as one closed EDMediaDiagnosticKind and handed to the host in batches —
the package never owns a network connection. Pass a sink to the device
provider (an inline arrow is fine; the latest one is always used):
<EDDeviceManagerProvider
onMediaDiagnostics={(batch) => {
// batch.reason: 'interval' | 'pagehide' | 'uninstall'
// batch.events: [{ kind, count, firstAt, lastAt, errorName, errorCode,
// visibilityStateAtFirst, onlineAtFirst, ... }]
// batch.dropped: reports cut by the batch/session caps
// batch.environment: secureContext, getUserMedia/getDisplayMedia support,
// visibility/online AT SEND TIME
send(batch) // on 'pagehide' prefer navigator.sendBeacon
}}
>| Kind | When |
| --- | --- |
| screen.capture-failed | getDisplayMedia refused or errored (incl. unsupported device, insecure origin) |
| screen.capture-cancelled | Chromium Permission denied: picker closed or blocked by policy — elapsedMs separates them |
| screen.capture-busy | a share request ignored because a picker was still open |
| camera.permission-denied | the camera/microphone permission probe failed |
| camera.permission-partial | the combined probe failed; continued with the granted kind only |
| camera.capture-retrying | recoverable getUserMedia error, retrying once (retryReason) |
| camera.capture-failed | getUserMedia failed after any retry |
| stage.join-failed | a stage join settled with an error category |
| stage.error | the SDK raised an ERROR event |
| stage.left-unexpectedly | the SDK left a stage nobody asked to leave, including a drop the lifecycle stream attributes to an earlier leave that never took effect (a leave the app requested and that happened is not reported, whatever its cause) |
| publish.retrying | a PUBLISH_ERROR scheduled the paced publish retry |
| publish.failed | a publication's publish/replication threw, including re-arming an active one (source: camera/screen) |
| publish.simulcast-rollback | a simulcast re-publish failed and was rolled back |
| transcription.init-failed | the live-caption audio pipeline could not start |
Batching keeps the backend safe from 429s: at most one batch per
mediaDiagnosticsFlushIntervalMs (default 10 s; raised to 1 s, and a
non-finite value falls back to the default) plus an immediate flush when the
page is hidden or the active reporter changes; identical reports collapse into
one entry with a count. A batch holds at most 50 distinct entries, and a page
reports at most 500 distinct failure identities over its whole life — a
recurring failure is charged once, and reinstalling the reporter does not
refill the budget; the excess is counted in dropped.
Diagnostics are report-only: they never change media handling, and they only
read the stage lifecycle stream, never change what it decides or attributes.
Stage and publish reports carry only the closed lifecycle category, the SDK's
numeric StageErrorCode (errorCode, e.g. 2 TOKEN_EXPIRED, 6
STAGE_AT_CAPACITY) and, on publish.failed, the error's class name (at most
64 characters) — raw SDK errors and their messages never leave the package. Lifecycle events carry the same optional errorCode when they hold
an SDK stage error. Each entry records visibilityStateAtFirst / onlineAtFirst from
when the failure happened; batch.environment describes the send.
Hosts without the device provider can call
setMediaDiagnosticsReporter(fn, options). Reporters stack: the most recently
installed one receives batches, and its uninstall function hands them back to
the one below. Install order is mount order, not nesting depth — a nested
provider reached by navigation installs last and wins, but providers mounted
in the same commit (a direct load or refresh) install child-first, so the
outer one wins. If nested providers pass different sinks, make them
interchangeable.
Join data shape
const joinData: EDIvsJoinData = {
roomId: 'your-room-id', // room identity (not necessarily a stage ARN)
ownerId: 'room-owner-id', // whose room this is (isOwner filters)
stageConfigs: {
user: { token, participantId, userId, participantGroup: 'user', purpose: 'legacyRoom' },
display: { token, participantId, userId, participantGroup: 'display', purpose: 'legacyRoom' },
},
}Extras
usePatrolSlot(wanted)— hard cap (12) on concurrent patrol/grid stage connections; a card only fetches join data while it holds a slot.PublicationManager.publicationsForStage(key)— the safeguarding "who is publishing to this stage" query.AudienceViewController(src/publication/audience.ts) — warm-standby primary/secondary presence rotation (shared teacher stages).
Testing
pnpm vitest run — pure unit tests, no mock frameworks (hand-rolled fakes).
pnpm build (= tsc -b && vite build) is the type gate; plain
tsc --noEmit does NOT check the referenced project.
