@reactor-team/js-sdk 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -317,16 +317,53 @@ function extractFileRefs(data) {
317
317
  let uploads;
318
318
  let scalars;
319
319
  for (const [key, value] of Object.entries(data)) {
320
- if (!isFileRef(value)) {
320
+ if (isFileRef(value)) {
321
+ uploads ??= {};
322
+ scalars ??= { ...data };
323
+ uploads[key] = toWireFileRef(value);
324
+ delete scalars[key];
321
325
  continue;
322
326
  }
323
- uploads ??= {};
324
- scalars ??= { ...data };
325
- uploads[key] = toWireFileRef(value);
326
- delete scalars[key];
327
+ const rewritten = rewriteNestedFileRefs(value);
328
+ if (rewritten !== value) {
329
+ scalars ??= { ...data };
330
+ scalars[key] = rewritten;
331
+ }
327
332
  }
328
333
  return { data: scalars ?? data, uploads };
329
334
  }
335
+ function rewriteNestedFileRefs(value) {
336
+ if (isFileRef(value)) {
337
+ return toWireFileRef(value);
338
+ }
339
+ if (Array.isArray(value)) {
340
+ const elements = value;
341
+ let copy;
342
+ elements.forEach((element, index) => {
343
+ const rewritten = rewriteNestedFileRefs(element);
344
+ if (rewritten !== element) {
345
+ copy ??= [...elements];
346
+ copy[index] = rewritten;
347
+ }
348
+ });
349
+ return copy ?? elements;
350
+ }
351
+ if (isSerializedAsObject(value)) {
352
+ let copy;
353
+ for (const [key, element] of Object.entries(value)) {
354
+ const rewritten = rewriteNestedFileRefs(element);
355
+ if (rewritten !== element) {
356
+ copy ??= { ...value };
357
+ copy[key] = rewritten;
358
+ }
359
+ }
360
+ return copy ?? value;
361
+ }
362
+ return value;
363
+ }
364
+ function isSerializedAsObject(value) {
365
+ return typeof value === "object" && value !== null && !ArrayBuffer.isView(value);
366
+ }
330
367
 
331
368
  // src/internal/recording.ts
332
369
  function toPublicClip(clip) {
@@ -448,7 +485,7 @@ async function importWasmModule() {
448
485
  // package.json
449
486
  var package_default = {
450
487
  name: "@reactor-team/js-sdk",
451
- version: "3.0.1",
488
+ version: "3.0.2",
452
489
  description: "Connect your JavaScript/TypeScript app to a live Reactor model in the browser.",
453
490
  license: "Apache-2.0",
454
491
  repository: {
@@ -941,6 +978,70 @@ var Reactor = class {
941
978
  * take ownership of Rust value while it was borrowed") or corrupt it
942
979
  * outright. */
943
980
  queue = new import_awaitqueue.AwaitQueue();
981
+ /** In-flight calls to `withReaderAccess()` — a "reply" `.catch(() => {})`
982
+ * copy of each, never the caller's own promise, so one rejecting can't
983
+ * make `Promise.all()` in `withWriterAccess()` reject and skip waiting
984
+ * for the rest. See `withReaderAccess()`/`withWriterAccess()`. */
985
+ activeReads = /* @__PURE__ */ new Set();
986
+ /** True for the span of a `withWriterAccess()` call — after it has waited
987
+ * out every read active when it started, before it releases the ones
988
+ * that arrived while it ran. */
989
+ writerActive = false;
990
+ /** Readers parked in `withReaderAccess()`'s wait loop, woken once
991
+ * `withWriterAccess()` finishes; each re-checks `writerActive` rather
992
+ * than assuming its turn, since another writer already queued behind the
993
+ * first one may have claimed it first. */
994
+ writerIdleWaiters = [];
995
+ /**
996
+ * Runs a read — sendCommand()/requestSchema()/requestClip()/
997
+ * requestRecording() — excluded from a lifecycle op (`withWriterAccess()`)
998
+ * but not from other reads: unlike `queue`, concurrent reads run
999
+ * concurrently. Queuing them the same way `queue` serializes writes would
1000
+ * head-of-line block an unrelated command, or even disconnect() itself,
1001
+ * behind one slow reply (the binding correlates replies independently, so
1002
+ * nothing requires this to be serial).
1003
+ *
1004
+ * Race-free the same way the wasm binding's own `readyState` check is: the
1005
+ * `writerActive` check and this call's registration in `activeReads` both
1006
+ * happen before the first `await` inside *fn*, so nothing can run between
1007
+ * them on a single-threaded JS event loop.
1008
+ */
1009
+ async withReaderAccess(fn) {
1010
+ while (this.writerActive) {
1011
+ await new Promise((resolve) => this.writerIdleWaiters.push(resolve));
1012
+ }
1013
+ const result = fn();
1014
+ const tracked = result.catch(() => void 0);
1015
+ this.activeReads.add(tracked);
1016
+ try {
1017
+ return await result;
1018
+ } finally {
1019
+ this.activeReads.delete(tracked);
1020
+ }
1021
+ }
1022
+ /**
1023
+ * Runs a lifecycle op's client-touching body exclusively: waits out every
1024
+ * read already in flight, then blocks new ones (`writerActive`) until it
1025
+ * finishes. Only ever called from inside a `queue`-serialized task, so at
1026
+ * most one writer runs this at a time — it doesn't serialize against
1027
+ * itself, only against `activeReads`.
1028
+ */
1029
+ async withWriterAccess(fn) {
1030
+ this.writerActive = true;
1031
+ if (this.activeReads.size > 0) {
1032
+ await Promise.all(this.activeReads);
1033
+ }
1034
+ try {
1035
+ return await fn();
1036
+ } finally {
1037
+ this.writerActive = false;
1038
+ const waiters = this.writerIdleWaiters;
1039
+ this.writerIdleWaiters = [];
1040
+ for (const wake of waiters) {
1041
+ wake();
1042
+ }
1043
+ }
1044
+ }
944
1045
  constructor(options) {
945
1046
  const { jwt, ...clientOptions } = options;
946
1047
  this.clientOptions = { sdkVersion: package_default.version, ...clientOptions };
@@ -964,10 +1065,13 @@ var Reactor = class {
964
1065
  this.jwt = jwt;
965
1066
  this.client?.setJwt(jwt);
966
1067
  }
967
- await this.queue.push(async () => {
968
- const client = await this.getOrCreateClient();
969
- await client.connect(options);
970
- }, "connect");
1068
+ await this.queue.push(
1069
+ () => this.withWriterAccess(async () => {
1070
+ const client = await this.getOrCreateClient();
1071
+ await client.connect(options);
1072
+ }),
1073
+ "connect"
1074
+ );
971
1075
  } catch (cause) {
972
1076
  throw this.captureError(cause);
973
1077
  }
@@ -990,15 +1094,18 @@ var Reactor = class {
990
1094
  async disconnect(recoverable = false) {
991
1095
  this.assertNotDisposed();
992
1096
  try {
993
- await this.queue.push(async () => {
994
- if (this.client) {
995
- await this.client.disconnect();
996
- }
997
- this.resetConnectionState();
998
- if (!recoverable) {
999
- this.freeClient();
1000
- }
1001
- }, "disconnect");
1097
+ await this.queue.push(
1098
+ () => this.withWriterAccess(async () => {
1099
+ if (this.client) {
1100
+ await this.client.disconnect();
1101
+ }
1102
+ this.resetConnectionState();
1103
+ if (!recoverable) {
1104
+ this.freeClient();
1105
+ }
1106
+ }),
1107
+ "disconnect"
1108
+ );
1002
1109
  } catch (cause) {
1003
1110
  throw this.captureError(cause);
1004
1111
  }
@@ -1012,10 +1119,13 @@ var Reactor = class {
1012
1119
  async reconnect(options) {
1013
1120
  this.assertNotDisposed();
1014
1121
  try {
1015
- await this.queue.push(async () => {
1016
- const client = await this.getOrCreateClient();
1017
- await client.reconnect(options);
1018
- }, "reconnect");
1122
+ await this.queue.push(
1123
+ () => this.withWriterAccess(async () => {
1124
+ const client = await this.getOrCreateClient();
1125
+ await client.reconnect(options);
1126
+ }),
1127
+ "reconnect"
1128
+ );
1019
1129
  } catch (cause) {
1020
1130
  throw this.captureError(cause);
1021
1131
  }
@@ -1030,9 +1140,11 @@ var Reactor = class {
1030
1140
  * mode) actually hands back `null` — normalized here so callers can rely
1031
1141
  * on the documented type instead of the binding's serialization quirk.
1032
1142
  *
1033
- * A `FileRef` (from `uploadFile`) may be passed as a top-level value in
1034
- * `data` alongside regular parameters — it is extracted and sent as a
1035
- * separate upload reference rather than embedded in the JSON payload.
1143
+ * A `FileRef` (from `uploadFile`) may be passed in `data` wherever the
1144
+ * model's schema declares a file. As a top-level value it is extracted and
1145
+ * sent as a separate upload reference rather than embedded in the JSON
1146
+ * payload; inside an array or object (a parameter that takes several files,
1147
+ * say) it is serialized as an upload reference in place.
1036
1148
  *
1037
1149
  * Unlike every other method here, this never rejects — a failure (the
1038
1150
  * session isn't `"ready"`, the send itself fails, …) is reported through
@@ -1054,9 +1166,11 @@ var Reactor = class {
1054
1166
  }
1055
1167
  try {
1056
1168
  this.assertNotDisposed();
1057
- const client = await this.getOrCreateClient();
1058
1169
  const extracted = extractFileRefs(data);
1059
- const reply = await client.sendCommand(command, extracted.data, extracted.uploads);
1170
+ const reply = await this.withReaderAccess(async () => {
1171
+ const client = await this.getOrCreateClient();
1172
+ return client.sendCommand(command, extracted.data, extracted.uploads);
1173
+ });
1060
1174
  return reply ?? void 0;
1061
1175
  } catch (cause) {
1062
1176
  this.emitError(cause);
@@ -1083,8 +1197,10 @@ var Reactor = class {
1083
1197
  switch (command) {
1084
1198
  case "requestSchema":
1085
1199
  try {
1086
- const client = await this.getOrCreateClient();
1087
- await this.refreshSchema(client);
1200
+ await this.withReaderAccess(async () => {
1201
+ const client = await this.getOrCreateClient();
1202
+ await this.refreshSchema(client);
1203
+ });
1088
1204
  } catch (cause) {
1089
1205
  this.emitError(cause);
1090
1206
  }
@@ -1106,8 +1222,10 @@ var Reactor = class {
1106
1222
  async requestSchema() {
1107
1223
  this.assertNotDisposed();
1108
1224
  try {
1109
- const client = await this.getOrCreateClient();
1110
- return this.normalizeSchema(await client.requestSchema());
1225
+ return await this.withReaderAccess(async () => {
1226
+ const client = await this.getOrCreateClient();
1227
+ return this.normalizeSchema(await client.requestSchema());
1228
+ });
1111
1229
  } catch (cause) {
1112
1230
  throw this.captureError(cause);
1113
1231
  }
@@ -1247,8 +1365,10 @@ var Reactor = class {
1247
1365
  async requestClip(durationSeconds) {
1248
1366
  this.assertNotDisposed();
1249
1367
  try {
1250
- const client = await this.getOrCreateClient();
1251
- return toPublicClip(await client.requestClip(durationSeconds));
1368
+ return await this.withReaderAccess(async () => {
1369
+ const client = await this.getOrCreateClient();
1370
+ return toPublicClip(await client.requestClip(durationSeconds));
1371
+ });
1252
1372
  } catch (cause) {
1253
1373
  throw this.captureError(cause);
1254
1374
  }
@@ -1257,8 +1377,10 @@ var Reactor = class {
1257
1377
  async requestRecording() {
1258
1378
  this.assertNotDisposed();
1259
1379
  try {
1260
- const client = await this.getOrCreateClient();
1261
- return toPublicClip(await client.requestRecording());
1380
+ return await this.withReaderAccess(async () => {
1381
+ const client = await this.getOrCreateClient();
1382
+ return toPublicClip(await client.requestRecording());
1383
+ });
1262
1384
  } catch (cause) {
1263
1385
  throw this.captureError(cause);
1264
1386
  }
@@ -1270,8 +1392,9 @@ var Reactor = class {
1270
1392
  // ── Uploads ─────────────────────────────────────────────────────────────
1271
1393
  /**
1272
1394
  * Uploads a file to the session's object store, resolving with a
1273
- * `FileRef` to pass as a top-level value in a `sendCommand()`'s `data`
1274
- * (see `extractFileRefs`). The binding itself takes `(file, name?)`
1395
+ * `FileRef` to pass in a `sendCommand()`'s `data`, at the top level or
1396
+ * inside an array or object (see `extractFileRefs`). The binding itself
1397
+ * takes `(file, name?)`
1275
1398
  * positionally and already applies the right defaulting — a bare
1276
1399
  * `Blob`'s name falls back to `"upload"`, and an empty/missing mime type
1277
1400
  * to `"application/octet-stream"` — so there's nothing to wrap here.
@@ -1345,7 +1468,7 @@ var Reactor = class {
1345
1468
  this.resetConnectionState();
1346
1469
  this.emitter.clear();
1347
1470
  if (client) {
1348
- void this.queue.push(() => client.free(), "dispose").catch(() => {
1471
+ void this.queue.push(() => this.withWriterAccess(() => Promise.resolve(client.free())), "dispose").catch(() => {
1349
1472
  });
1350
1473
  }
1351
1474
  }