simcapture-sdk
v1.0.0
Published
Opinionated, strongly-typed SimCapture SDK — entity handles, fluent builders, and value objects over the SimCapture REST API.
Readme
simcapture-sdk
SDK tipado para la API REST de SimCapture. Entidades navegables, builders fluidos y
value objects; auth, cache de token y reintento ante 401 resueltos por dentro.
Instalación
npm install simcapture-sdk
pnpm add simcapture-sdk
bun add simcapture-sdkNode ≥ 18. axios es la única dependencia.
Quick start
import { SimCapture, TimeWindow, Location, Reservation } from "simcapture-sdk";
const sc = new SimCapture({
apiUrl: process.env.SIMCAPTURE_API!, // https://api.simcapture.com
inventoryUrl: process.env.SIMCAPTURE_INVENTORY_API!,
credentials: {
username: process.env.SIMCAPTURE_USER!,
password: process.env.SIMCAPTURE_PASSWORD!,
clientSubdomain: process.env.SIMCAPTURE_SUBDOMAIN!, // tu tenant
},
});
const org = await sc.Organization.named("Facultad de Medicina");
const room = new Location({ name: "P3-H1" }); // referencia, sin red
const date = new TimeWindow("2026-06-05").start().at("23:00").end().at("23:10");
const reserva = await new Reservation()
.titled("Reserva de prueba")
.inOrganization(org) // handle, UUID o nombre
.at(room)
.when(date)
.save();
await reserva.organization(); // navegación: fetch bajo demanda
reserva.date.durationMinutes();Namespaces
| Namespace | Métodos |
|---|---|
| sc.Course | named · get · all · page · create · build |
| sc.Scenario | get · build(course) |
| sc.Reservation | get · between · isAvailable · build |
| sc.Organization | named · get · all · create · build · replace |
| sc.Location | named · get · all |
| sc.User | named · get · all · page · groups · create · build |
| sc.Simulator | named · get · all · configs |
| sc.InventoryItem | named · get · all |
| sc.Live | locations |
| sc.Notification | send({ recipients, subject?, body? }) |
| sc.Profile | get |
named() matchea exacto, sin distinguir mayúsculas: sin match lanza NotFoundError;
con varios, AmbiguousMatchError con los ids para desambiguar vía get(id).
Listados
all() significa todo: recorre las páginas por dentro y concatena. Corta solo con
página vacía; si el servidor nunca la devuelve, lanza en vez de entregar media lista.
await sc.Course.all(); // todas las páginas
await sc.Course.page(0); // → { items, total }
await sc.User.all({ search: "jdoe" });/organizations, /locations, /simulators, /items, /simulator-configs y
/userGroups no paginan: ahí all() es una sola request.
Builders: draft → save()
Encadenás setters; save() valida local (todos los faltantes en un solo
ValidationError) y hace el POST. Después, la misma instancia es la entidad cargada.
const course = await new Course()
.titled("CURSO DEMO").inOrganization(org) // requeridos
.withPublicTitle("Demo").passingPercentage(70)
.save();
const esc = await new Scenario()
.forCourse(course).titled("ESC 1") // requeridos
.withSimulators([simulator]).selfRecorded()
.save();
await new User()
.withUserName("jdoe").withPassword("s3cret").withEmail("[email protected]")
.inOrganizations([org]).inGroup((await sc.User.groups())[0]!)
.save();
await sc.Organization.build({ name: "Enfermería" }).save();El contexto del cliente se infiere del primer handle que adjuntás. Si solo usás strings,
pre-vinculá con las fábricas (sc.Course.build(...), sc.Reservation.build(...), …).
Los getters lanzan error claro sobre un draft sin guardar.
Reservas
await reserva.reschedule(date);
await reserva.rename("Nuevo título");
await reserva.recolor("#07f");
await reserva.setSetupTime(60); // preserva endTs/participantes como la web app
await reserva.setTakedownTime(15);
await reserva.setPublicNotes("visible");
await reserva.setPrivateNotes("interna");
await reserva.updateDetails({ privateNotes: "..." });
await reserva.delete();
await sc.Reservation.between(date); // solapan la ventana
await sc.Reservation.isAvailable(date, { locations: [room] }); // ¿libre?Opcionales del builder: .setupTime · .takedownTime · .withPublicNotes ·
.withPrivateNotes · .withColor · .withExpectedParticipants · .selfEnroll ·
.consumeInventory · .withSimulators · .withInventory.
Evaluaciones y adjuntos
const tpl = await new EvaluationTemplate()
.forScenario(esc).titled("Evaluación").duringSession() // o .beforeSession() / .afterSession()
.withQuestions([
{ text: "¿Correcto?", answers: [{ text: "SI", points: 1 }, { text: "NO", points: 0 }] },
])
.save();
const results = await esc.evaluations(tpl); // los métodos aceptan el handle
await course.assignEvaluation({ template: tpl, when: date, scenario: esc, students: [student] });
await esc.attach(new Attachment("invite.ics", await readFile("invite.ics")));
const bytes = await esc.downloadAttachment("invite.ics");Detalles que importan
TimeWindow:"HH:mm"sin offset se interpreta en UTC (SimCapture guarda ISO-Z). Para hora local pasá unDateo un string con offset.overlapses half-open.isAvailable: el servidor solo filtra por ventana; salas, cursos y organizaciones se filtran client-side (AND entre categorías).attach(): el registro bulk reemplaza la lista completa, así que relee los adjuntos actuales y los reenvía junto con los nuevos..addCourse()no viaja en el payload: el endpoint de creación no acepta courseIds (el curso entra por el escenario). Queda para vincular contexto..rawen cada entidad expone el registro completo de la API, incluso lo que el SDK no modela.
Errores
Todos extienden SimCaptureError, así que instanceof SimCaptureError alcanza como red.
| Error | Cuándo | status |
|---|---|---|
| NotFoundError | lookup sin match | 0 |
| AmbiguousMatchError | lookup con >1 match (err.matches trae ids) | 0 |
| ValidationError | builder incompleto, VO inválido, draft sin guardar | 0 |
| SimCaptureError | fallo HTTP upstream, o listado que supera PAGE_SCAN_CAP | real / 0 |
Auth
- Token cacheado hasta vencer su TTL suave (
tokenTtlMs, default 30 min). - Un
401limpia la cache, re-loguea una vez y reintenta. - Llamadas concurrentes comparten un único
/authen vuelo.
Migración desde 0.x
Cambia la superficie, no el motor (auth, transporte y retry son los mismos).
| 0.x | 1.x |
|---|---|
| new SimCaptureClient(...) | new SimCapture(...) |
| sc.organizations.findAll() | sc.Organization.all() |
| sc.courses.find(query) | sc.Course.page(n) (una página) · sc.Course.all() (todas) |
| sc.courses.create(input) | new Course().titled(...).inOrganization(org).save() |
| sc.courses.createScenario(id, i) | (await sc.Course.get(id)).addScenario(i) |
| sc.reservations.create(input) | sc.Reservation.build({...}).save() |
| sc.reservations.findAll({start,end}) | sc.Reservation.between(date) |
| sc.users.find({search}) | sc.User.all({ search }) · sc.User.named(term) |
| sc.scenarios.uploadAttachment + setAttachments | scenario.attach(new Attachment(...)) |
| sc.scenarios.delete(id) | (await sc.Scenario.get(id)).delete() |
| sc.simulators.getConfigs() | sc.Simulator.configs() |
| sc.profile() | sc.Profile.get() |
| start/end como strings | new TimeWindow(día).start().at(hh).end().at(hh) |
Los tipos wire (ReservationRecord, CourseRow, EvaluationResult, …) siguen exportados.
Arquitectura
domain/ value objects, errors, ports (HttpClient, TokenStore)
application/ entities + services (los namespaces sc.X), Authenticator, recursos
infrastructure/ axios transport + in-memory token store
config/ SimCaptureConfig + validación
simcapture.ts composition rootLas dependencias apuntan hacia adentro: entidades y servicios solo conocen los puertos, testeables con fakes. Podés inyectar transporte o token store propios en el 2º argumento.
Desarrollo
bun install
bun run typecheck # tsc --noEmit (strict)
bun test # contra los puertos, sin red
bun run build # bun build → ESM+CJS + tsc → .d.tsLicencia
MIT
