gesso-framework 0.6.6 → 0.6.7

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.
@@ -1,4 +1,4 @@
1
- import { a as agentSurface, i as serveAgentPort } from "./remote-xxij8zXe.js";
1
+ import { A as structurallyEqual } from "./serveChannels-Cs22-p8X.js";
2
2
  import { BehaviorSubject, Observable, Subject, Subscription, combineLatest, debounceTime, distinctUntilChanged, map, of, skip, tap, throttleTime } from "rxjs";
3
3
  //#region src/Input.ts
4
4
  /**
@@ -120,7 +120,7 @@ function warnStaleRead(tag, label, from, to) {
120
120
  * about what actually moved.
121
121
  */
122
122
  function describeChange(from, to) {
123
- if (isPlainObject$2(from) && isPlainObject$2(to)) {
123
+ if (isPlainObject(from) && isPlainObject(to)) {
124
124
  for (const key of /* @__PURE__ */ new Set([...Object.keys(from), ...Object.keys(to)])) {
125
125
  const before = from[key];
126
126
  const after = to[key];
@@ -130,7 +130,7 @@ function describeChange(from, to) {
130
130
  }
131
131
  return `from ${describe(from)} to ${describe(to)}`;
132
132
  }
133
- function isPlainObject$2(value) {
133
+ function isPlainObject(value) {
134
134
  return typeof value === "object" && value !== null && !Array.isArray(value);
135
135
  }
136
136
  function safeJson(value) {
@@ -250,61 +250,6 @@ function internalState(initialValue, label) {
250
250
  return state;
251
251
  }
252
252
  //#endregion
253
- //#region src/channel/structuralEquals.ts
254
- /**
255
- * Deep comparison for store read models.
256
- *
257
- * Projections and selectors allocate a fresh value on every
258
- * evaluation, so reference equality reports a change on every
259
- * unrelated state emission. That invalidates bindings and dirties
260
- * nodes across the whole tree for state the view never read.
261
- *
262
- * Scope is deliberately narrow: primitives, arrays, and plain objects
263
- * — what a projection is allowed to return. Anything else (class
264
- * instances, Date, Map, Set, functions) compares by reference, which
265
- * is conservative: it reports a change, so the UI updates when it did
266
- * not need to rather than failing to update when it did.
267
- *
268
- * The same comparison becomes the equality half of the patch differ
269
- * in Phase E, so a store behaves identically local or remote.
270
- */
271
- const MAX_DEPTH$1 = 100;
272
- function structurallyEqual(a, b) {
273
- return compare(a, b, 0);
274
- }
275
- function compare(a, b, depth) {
276
- if (Object.is(a, b)) return true;
277
- if (depth > MAX_DEPTH$1) return false;
278
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
279
- const aIsArray = Array.isArray(a);
280
- if (aIsArray !== Array.isArray(b)) return false;
281
- if (aIsArray) {
282
- const left = a;
283
- const right = b;
284
- if (left.length !== right.length) return false;
285
- for (let i = 0; i < left.length; i++) if (!compare(left[i], right[i], depth + 1)) return false;
286
- return true;
287
- }
288
- if (!isPlainObject$1(a) || !isPlainObject$1(b)) return false;
289
- const left = a;
290
- const right = b;
291
- const leftKeys = Object.keys(left);
292
- if (leftKeys.length !== Object.keys(right).length) return false;
293
- for (const key of leftKeys) {
294
- if (!Object.prototype.hasOwnProperty.call(right, key)) return false;
295
- if (!compare(left[key], right[key], depth + 1)) return false;
296
- }
297
- return true;
298
- }
299
- /**
300
- * Objects created from an object literal or a null prototype. Class
301
- * instances are excluded so they keep reference semantics.
302
- */
303
- function isPlainObject$1(value) {
304
- const prototype = Object.getPrototypeOf(value);
305
- return prototype === Object.prototype || prototype === null;
306
- }
307
- //#endregion
308
253
  //#region src/derive.ts
309
254
  /**
310
255
  * One value from several, kept equal to `project` of the latest of each
@@ -989,898 +934,6 @@ function throttled(source, ms) {
989
934
  }));
990
935
  }
991
936
  //#endregion
992
- //#region src/channel/ChannelToken.ts
993
- /**
994
- * Declares a channel.
995
- *
996
- * The name identifies it across the thread boundary and must be
997
- * stable; unlike a class name it survives minification, which is why
998
- * it is written out rather than derived.
999
- */
1000
- function channel(name, initial) {
1001
- if (name.length === 0) throw new Error("A channel needs a name: it is how the two threads agree on which one this is.");
1002
- return {
1003
- name,
1004
- initial
1005
- };
1006
- }
1007
- /**
1008
- * Declares a channel from one object.
1009
- *
1010
- * export const Catalog = defineChannel('catalog', {
1011
- * view: {
1012
- * products: [] as readonly ProductRow[],
1013
- * status: 'loading' as ShelfStatus
1014
- * },
1015
- * commands: {} as {
1016
- * addToCart(id: string, quantity: number): void;
1017
- * move(from: number, to: number): void;
1018
- * }
1019
- * });
1020
- *
1021
- * export type CatalogView = ViewOf<typeof Catalog>;
1022
- *
1023
- * The same token `channel()` returns, declared once instead of three
1024
- * times. `channel<View, Commands>(name, initial)` wrote the view as an
1025
- * interface, then as an initial literal that had to agree with it, and
1026
- * a key added to one and forgotten in the other was a type error in a
1027
- * third file. Here the object is the type.
1028
- *
1029
- * A field whose initial value is narrower than the type it holds is
1030
- * given the type it holds: `[]` is `never[]` and `'loading'` is
1031
- * `string` unless it is said, which is what the `as` clauses above are
1032
- * for. `ViewOf` and `CommandsOf` name the resulting types wherever the
1033
- * application used to name its own interface.
1034
- *
1035
- * `channel()` is not deprecated and keeps working exactly as it did.
1036
- * An application with interfaces it wants to keep, because they are
1037
- * shared with something else or because the initial values are built
1038
- * elsewhere, has nothing to migrate.
1039
- */
1040
- function defineChannel(name, spec) {
1041
- return channel(name, spec.view);
1042
- }
1043
- /**
1044
- * The keys a channel publishes.
1045
- *
1046
- * Structural in its parameter rather than generic over the token, so
1047
- * it does not have to agree with any particular command type to read
1048
- * what is only ever the initial value's shape.
1049
- */
1050
- function viewKeys(token) {
1051
- return Object.keys(token.initial);
1052
- }
1053
- //#endregion
1054
- //#region src/channel/ChannelProtocol.ts
1055
- function isChannelClientMessage(value) {
1056
- const type = value?.type;
1057
- return type === "channel:sync" || type === "channel:command";
1058
- }
1059
- function isChannelHostMessage(value) {
1060
- const type = value?.type;
1061
- return type === "channel:patch" || type === "channel:error";
1062
- }
1063
- //#endregion
1064
- //#region src/channel/StorePatch.ts
1065
- /**
1066
- * Describes how to turn `previous` into `current` for one projection.
1067
- *
1068
- * Returns an empty list when nothing changed, which is the common case
1069
- * and the reason this exists: the point of a projection is that most
1070
- * state changes do not alter it, and the ones that do usually alter a
1071
- * small part.
1072
- */
1073
- function diffProjection(projection, previous, current) {
1074
- const patches = [];
1075
- diff(projection, [], previous, current, patches);
1076
- return patches;
1077
- }
1078
- function diff(projection, path, previous, current, out) {
1079
- if (structurallyEqual(previous, current)) return;
1080
- if (Array.isArray(previous) && Array.isArray(current)) {
1081
- diffArray(projection, path, previous, current, out);
1082
- return;
1083
- }
1084
- if (isPlainObject(previous) && isPlainObject(current)) {
1085
- for (const key of Object.keys(current)) if (Object.prototype.hasOwnProperty.call(previous, key)) diff(projection, [...path, key], previous[key], current[key], out);
1086
- else out.push({
1087
- op: "set",
1088
- projection,
1089
- path: [...path, key],
1090
- value: current[key]
1091
- });
1092
- for (const key of Object.keys(previous)) if (!Object.prototype.hasOwnProperty.call(current, key)) out.push({
1093
- op: "delete",
1094
- projection,
1095
- path: [...path, key]
1096
- });
1097
- return;
1098
- }
1099
- out.push({
1100
- op: "set",
1101
- projection,
1102
- path,
1103
- value: current
1104
- });
1105
- }
1106
- /**
1107
- * Diffs two arrays by trimming the common prefix and suffix.
1108
- *
1109
- * This is not a minimal edit script — a shuffle degrades to replacing
1110
- * the middle wholesale. It is chosen because the operations lists
1111
- * actually undergo (append, prepend, remove one, edit in place) all
1112
- * reduce to a single small patch, and computing a true LCS on every
1113
- * store change would cost more than it saves.
1114
- */
1115
- function diffArray(projection, path, previous, current, out) {
1116
- let start = 0;
1117
- while (start < previous.length && start < current.length && structurallyEqual(previous[start], current[start])) start++;
1118
- let previousEnd = previous.length - 1;
1119
- let currentEnd = current.length - 1;
1120
- while (previousEnd >= start && currentEnd >= start && structurallyEqual(previous[previousEnd], current[currentEnd])) {
1121
- previousEnd--;
1122
- currentEnd--;
1123
- }
1124
- const previousCount = previousEnd - start + 1;
1125
- const currentCount = currentEnd - start + 1;
1126
- if (previousCount === 0 && currentCount === 0) return;
1127
- if (previousCount === currentCount) {
1128
- for (let offset = 0; offset < previousCount; offset++) {
1129
- const index = start + offset;
1130
- diff(projection, [...path, index], previous[index], current[index], out);
1131
- }
1132
- return;
1133
- }
1134
- out.push({
1135
- op: "splice",
1136
- projection,
1137
- path,
1138
- index: start,
1139
- deleteCount: previousCount,
1140
- items: current.slice(start, currentEnd + 1)
1141
- });
1142
- }
1143
- /**
1144
- * Applies patches to a projection value, sharing structure with the
1145
- * original everywhere the patch did not reach.
1146
- *
1147
- * Nothing handed in is mutated: bindings hold onto emitted values, so a
1148
- * replica that edited in place would change data a component already
1149
- * rendered.
1150
- *
1151
- * **Each container on a patched path is copied once per batch, not once
1152
- * per patch.** A batch of N patches into one K-key object used to cost
1153
- * N × K: every patch spread the whole object again to change one key.
1154
- * A snapshot keyed by id is exactly that shape — gessologic published
1155
- * `Record<netId, 0 | 1>` for ten thousand nets, about nine hundred
1156
- * patches a publish, and the render worker's patch phase fell minutes
1157
- * behind a 60 Hz stream it could never catch. So the batch remembers
1158
- * the containers it has copied, and writes into those in place: they
1159
- * are its own, made during this call and seen by nobody yet. Values
1160
- * that arrived inside a patch are never written into, because they are
1161
- * the patch's — a devtools log replays the same patch objects again.
1162
- */
1163
- function applyPatches(root, patches) {
1164
- const owned = /* @__PURE__ */ new Set();
1165
- let next = root;
1166
- for (const patch of patches) next = applyOne(next, patch, owned);
1167
- return next;
1168
- }
1169
- function applyPatch(root, patch) {
1170
- return applyOne(root, patch, /* @__PURE__ */ new Set());
1171
- }
1172
- function applyOne(root, patch, owned) {
1173
- switch (patch.op) {
1174
- case "set": return setIn(root, patch.path, 0, patch.value, owned);
1175
- case "delete":
1176
- if (patch.path.length === 0) return;
1177
- return deleteIn(root, patch.path, 0, owned);
1178
- case "splice": return updateIn(root, patch.path, 0, owned, (node) => {
1179
- const array = Array.isArray(node) ? node : [];
1180
- const spliced = array.slice(0, patch.index).concat(patch.items, array.slice(patch.index + patch.deleteCount));
1181
- owned.add(spliced);
1182
- return spliced;
1183
- });
1184
- }
1185
- }
1186
- function setIn(node, path, index, value, owned) {
1187
- if (index === path.length) return value;
1188
- const key = path[index];
1189
- const copy = cloneContainer(node, key, owned);
1190
- setKey(copy, key, setIn(readKey(node, key), path, index + 1, value, owned));
1191
- return copy;
1192
- }
1193
- function deleteIn(node, path, index, owned) {
1194
- const key = path[index];
1195
- const copy = cloneContainer(node, key, owned);
1196
- if (index === path.length - 1) {
1197
- if (Array.isArray(copy)) copy.splice(Number(key), 1);
1198
- else delete copy[String(key)];
1199
- return copy;
1200
- }
1201
- setKey(copy, key, deleteIn(readKey(node, key), path, index + 1, owned));
1202
- return copy;
1203
- }
1204
- function updateIn(node, path, index, owned, update) {
1205
- if (index === path.length) return update(node);
1206
- const key = path[index];
1207
- const copy = cloneContainer(node, key, owned);
1208
- setKey(copy, key, updateIn(readKey(node, key), path, index + 1, owned, update));
1209
- return copy;
1210
- }
1211
- /**
1212
- * The container to write `key` into: `node` itself when this batch
1213
- * already copied it, and a fresh copy, remembered, when it did not.
1214
- */
1215
- function cloneContainer(node, key, owned) {
1216
- if (typeof node === "object" && node !== null && owned.has(node)) return node;
1217
- let copy;
1218
- if (Array.isArray(node)) copy = node.slice();
1219
- else if (isPlainObject(node)) copy = { ...node };
1220
- else copy = typeof key === "number" ? [] : {};
1221
- owned.add(copy);
1222
- return copy;
1223
- }
1224
- function readKey(node, key) {
1225
- if (node === null || node === void 0) return;
1226
- return node[key];
1227
- }
1228
- function setKey(container, key, value) {
1229
- container[key] = value;
1230
- }
1231
- function isPlainObject(value) {
1232
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1233
- const prototype = Object.getPrototypeOf(value);
1234
- return prototype === Object.prototype || prototype === null;
1235
- }
1236
- //#endregion
1237
- //#region src/channel/plainData.ts
1238
- /**
1239
- * Checks that a value can cross the barrier.
1240
- *
1241
- * `structurallyEqual` understands primitives, arrays and plain
1242
- * objects, and falls back to reference equality for everything else —
1243
- * which for a freshly built value reports "changed" every single time.
1244
- * A view key holding a `Date`, a `Map` or a domain object therefore
1245
- * re-emits on every unrelated update and dirties the subtree bound to
1246
- * it, forever, while looking perfectly correct.
1247
- *
1248
- * That failure is invisible in a test and shows up as a vague slowness
1249
- * much later, so `provide` checks each key's first emission and throws
1250
- * naming the path. The view-model layer is where rich objects become
1251
- * flat data; this is what makes that a rule rather than a convention.
1252
- *
1253
- * The check runs once per key, on the first value only. It is a
1254
- * development guard against a design mistake, not a validator on the
1255
- * hot path.
1256
- */
1257
- const MAX_DEPTH = 100;
1258
- /**
1259
- * Returns the path to the first value that cannot cross, or null when
1260
- * the whole tree is plain data.
1261
- */
1262
- function findUnplainPath(value, path = []) {
1263
- if (path.length > MAX_DEPTH) return format(path);
1264
- if (value === null) return null;
1265
- const type = typeof value;
1266
- if (type === "string" || type === "number" || type === "boolean" || type === "undefined") return null;
1267
- if (type === "function" || type === "symbol" || type === "bigint") return format(path);
1268
- if (Array.isArray(value)) {
1269
- for (let index = 0; index < value.length; index++) {
1270
- const found = findUnplainPath(value[index], [...path, index]);
1271
- if (found !== null) return found;
1272
- }
1273
- return null;
1274
- }
1275
- const prototype = Object.getPrototypeOf(value);
1276
- if (prototype !== Object.prototype && prototype !== null) return format(path);
1277
- for (const [key, member] of Object.entries(value)) {
1278
- const found = findUnplainPath(member, [...path, key]);
1279
- if (found !== null) return found;
1280
- }
1281
- return null;
1282
- }
1283
- /**
1284
- * Throws when `value` cannot cross the barrier, naming the channel,
1285
- * the key and the path within it.
1286
- */
1287
- function requirePlainData(channelName, key, value) {
1288
- const path = findUnplainPath(value);
1289
- if (path === null) return;
1290
- const where = path === "" ? `'${key}'` : `'${key}'${path}`;
1291
- throw new Error(`Channel '${channelName}' published ${where}, which is not plain data. Only primitives, arrays and plain objects cross the barrier: a Date, Map, Set, class instance or function compares by reference, so it would report a change on every update and rebuild the subtree bound to it. Flatten it in the view model.`);
1292
- }
1293
- function format(path) {
1294
- return path.map((step) => typeof step === "number" ? `[${step}]` : `.${step}`).join("");
1295
- }
1296
- //#endregion
1297
- //#region src/channel/provide.ts
1298
- /**
1299
- * Publishes a channel from the thread that owns its data.
1300
- *
1301
- * Each view key is subscribed, diffed against what the other side last
1302
- * saw, and sent as patches. Whatever produced the observable — a bare
1303
- * subject or a stack of layers — stays here; only plain data crosses.
1304
- *
1305
- * Keys are subscribed on the first sync request, so a channel nobody
1306
- * is watching costs nothing.
1307
- */
1308
- function provide(token, source, port) {
1309
- return new ProvidedChannel(token, source, port);
1310
- }
1311
- var ProvidedChannel = class {
1312
- token;
1313
- source;
1314
- port;
1315
- subscriptions = new Subscription();
1316
- /**
1317
- * What the other side is known to hold, seeded from the token's
1318
- * initial value — which the replica also starts from, so an app
1319
- * whose first emission equals the initial sends nothing at all.
1320
- */
1321
- previous = /* @__PURE__ */ new Map();
1322
- checked = /* @__PURE__ */ new Set();
1323
- synced = false;
1324
- constructor(token, source, port) {
1325
- this.token = token;
1326
- this.source = source;
1327
- this.port = port;
1328
- for (const key of viewKeys(token)) this.previous.set(key, token.initial[key]);
1329
- this.port.onmessage = (event) => this.receive(event.data);
1330
- }
1331
- receive(data) {
1332
- if (!isChannelClientMessage(data)) return;
1333
- try {
1334
- if (data.type === "channel:sync") {
1335
- this.sync();
1336
- return;
1337
- }
1338
- this.runCommand(data.command, data.payload, data.rest);
1339
- } catch (error) {
1340
- this.post({
1341
- type: "channel:error",
1342
- message: error instanceof Error ? error.message : String(error),
1343
- stack: error instanceof Error ? error.stack : void 0
1344
- });
1345
- }
1346
- }
1347
- runCommand(name, payload, rest) {
1348
- const handler = this.source.commands?.[name];
1349
- if (handler === void 0) {
1350
- const names = Object.keys(this.source.commands ?? {}).sort().join(", ");
1351
- throw new Error(`Channel '${this.token.name}' has no command '${name}'. Declared commands: ${names.length > 0 ? names : "(none)"}.`);
1352
- }
1353
- handler(payload, ...rest ?? []);
1354
- }
1355
- sync() {
1356
- if (this.synced) {
1357
- this.resend();
1358
- return;
1359
- }
1360
- this.synced = true;
1361
- for (const key of viewKeys(this.token)) {
1362
- const observable = this.source.view[key];
1363
- if (observable === void 0) {
1364
- this.post({
1365
- type: "channel:error",
1366
- message: `Channel '${this.token.name}' declares view key '${key}' but nothing was provided for it.`
1367
- });
1368
- continue;
1369
- }
1370
- this.subscriptions.add(observable.subscribe({
1371
- next: (value) => this.publish(key, value),
1372
- error: (error) => this.post({
1373
- type: "channel:error",
1374
- message: `Channel '${this.token.name}' view key '${key}' errored: ${error instanceof Error ? error.message : String(error)}`,
1375
- stack: error instanceof Error ? error.stack : void 0
1376
- })
1377
- }));
1378
- }
1379
- }
1380
- publish(key, value) {
1381
- if (!this.checked.has(key)) {
1382
- this.checked.add(key);
1383
- try {
1384
- requirePlainData(this.token.name, key, value);
1385
- } catch (error) {
1386
- this.post({
1387
- type: "channel:error",
1388
- message: error instanceof Error ? error.message : String(error),
1389
- stack: error instanceof Error ? error.stack : void 0
1390
- });
1391
- return;
1392
- }
1393
- }
1394
- const patches = diffProjection(key, this.previous.get(key), value);
1395
- this.previous.set(key, value);
1396
- if (patches.length > 0) this.post({
1397
- type: "channel:patch",
1398
- patches
1399
- });
1400
- }
1401
- /** Re-sends every key in full, for a client that reattached. */
1402
- resend() {
1403
- const patches = [];
1404
- for (const [key, value] of this.previous) patches.push({
1405
- op: "set",
1406
- projection: key,
1407
- path: [],
1408
- value
1409
- });
1410
- if (patches.length > 0) this.post({
1411
- type: "channel:patch",
1412
- patches
1413
- });
1414
- }
1415
- post(message) {
1416
- this.port.postMessage(message);
1417
- }
1418
- dispose() {
1419
- this.subscriptions.unsubscribe();
1420
- this.port.onmessage = null;
1421
- }
1422
- };
1423
- //#endregion
1424
- //#region src/app/NodeReport.ts
1425
- /**
1426
- * A node as a path somebody can read: `App > TrackScreen > ActionRow >
1427
- * Button "Like"`.
1428
- *
1429
- * Written for error messages rather than for the inspector, and the
1430
- * difference decides the shape. A report is read beside the tree it
1431
- * came from, so an id is a handle; an error is read in a console or an
1432
- * overlay with no tree beside it, and `node-4821` there is a fact
1433
- * about nothing. The owner chain is what a person recognises, because
1434
- * it is the components they wrote.
1435
- *
1436
- * Owners arrive nearest-first, as `UiNodeReport.owners` computes them,
1437
- * and read outermost-first, as a path does. The accessible name is the
1438
- * leaf when there is one: two `Button`s in the same row are only told
1439
- * apart by what they say.
1440
- */
1441
- function formatNodePath(owners, node) {
1442
- const names = owners.map((owner) => owner.name).reverse();
1443
- if (names.length === 0) return node.label === void 0 || node.label === "" ? `${node.type} ${node.id}` : `${node.type} "${node.label}"`;
1444
- const path = names.join(" > ");
1445
- return node.label === void 0 || node.label === "" ? path : `${path} "${node.label}"`;
1446
- }
1447
- /**
1448
- * Describes the stream driving a property.
1449
- *
1450
- * `timeOrigin` turns the binding's own reading into an epoch stamp:
1451
- * `performance.timeOrigin` on a thread that has one, and zero where
1452
- * the reading is already an epoch.
1453
- */
1454
- function describeStream(binding, timeOrigin) {
1455
- const label = binding.observable?.label;
1456
- const labelled = typeof label === "string" && label !== "";
1457
- const emittedAt = binding.emittedAt();
1458
- return {
1459
- source: labelled ? label : `observable #${binding.id}`,
1460
- kind: labelled ? "cell" : "observable",
1461
- value: printPropValue(binding.value()),
1462
- emissions: binding.emissionCount(),
1463
- emittedAt: emittedAt === null ? null : timeOrigin + emittedAt,
1464
- connected: binding.connected()
1465
- };
1466
- }
1467
- /** A stream as one line: what feeds the prop, and how long ago it said so. */
1468
- function formatStream(stream, now = Date.now()) {
1469
- const when = stream.emittedAt === null ? "no value yet" : `${formatAge(Math.max(0, now - stream.emittedAt))} ago`;
1470
- const emissions = `${stream.emissions} emission${stream.emissions === 1 ? "" : "s"}`;
1471
- return `${stream.source} · ${emissions} · ${when}${stream.connected ? "" : " · disconnected"}`;
1472
- }
1473
- /** An age in the largest unit that stays readable. */
1474
- function formatAge(ms) {
1475
- if (ms < 1e3) return `${Math.round(ms)}ms`;
1476
- if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
1477
- return `${Math.round(ms / 6e4)}m`;
1478
- }
1479
- /**
1480
- * A value as one line a person can read.
1481
- *
1482
- * `JSON.stringify` alone is not enough: the two values a canvas UI
1483
- * puts in a property that it cannot handle are a `Set` (a node's
1484
- * visual states) and a function (an event handler), and it prints both
1485
- * as `{}`, which in an inspector reads as a bug in the application
1486
- * rather than one in the inspector.
1487
- */
1488
- function printPropValue(value) {
1489
- if (value === void 0) return "undefined";
1490
- if (value === null) return "null";
1491
- if (typeof value === "function") return `ƒ ${value.name === "" ? "(anonymous)" : value.name}`;
1492
- if (typeof value === "symbol") return value.toString();
1493
- if (typeof value === "string") return value;
1494
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
1495
- if (value instanceof Set) return `Set { ${[...value].map(printPropValue).join(", ")} }`;
1496
- if (value instanceof Map) return `Map { ${[...value].map(([key, entry]) => `${printPropValue(key)}: ${printPropValue(entry)}`).join(", ")} }`;
1497
- if (Array.isArray(value)) return `[${value.map(printPropValue).join(", ")}]`;
1498
- try {
1499
- return JSON.stringify(value) ?? String(value);
1500
- } catch {
1501
- return String(value);
1502
- }
1503
- }
1504
- /** The report as text, for a console or a test failure. */
1505
- function formatNodeReport(report) {
1506
- const lines = [`${report.type} '${report.id}'`];
1507
- if (report.owners.length > 0) lines.push(`rendered by ${report.owners.map((owner) => owner.name).join(" inside ")}`);
1508
- if (report.modifiers.length > 0) lines.push(`modifiers: ${report.modifiers.join(", ")}`);
1509
- if (report.listens.length > 0) lines.push(`listens: ${report.listens.join(", ")}`);
1510
- if (report.beneath.length > 0) {
1511
- lines.push("beneath, at the pointer:");
1512
- for (const under of report.beneath) {
1513
- const owner = under.owner === void 0 ? "" : ` (${under.owner})`;
1514
- const listens = under.listens.length === 0 ? "" : `, listens: ${under.listens.join(", ")}`;
1515
- lines.push(` ${under.type} ${under.id}${owner}${listens}`);
1516
- }
1517
- }
1518
- if (report.props.length > 0) {
1519
- lines.push("props:");
1520
- for (const prop of report.props) {
1521
- lines.push(` ${prop.name} = ${prop.value}${prop.source === void 0 ? "" : ` (${prop.source})`}`);
1522
- if (prop.stream !== void 0) lines.push(` ${formatStream(prop.stream)}`);
1523
- }
1524
- }
1525
- if (report.environment.length > 0) {
1526
- lines.push("environment:");
1527
- for (const entry of report.environment) lines.push(` ${entry.key} = ${entry.value}${entry.provided ? " (provided here)" : ""}`);
1528
- }
1529
- if (report.semantics !== void 0) {
1530
- const parts = [
1531
- report.semantics.role === void 0 ? void 0 : `role ${report.semantics.role}`,
1532
- report.semantics.label === void 0 ? void 0 : `label ${report.semantics.label}`,
1533
- report.semantics.value === void 0 ? void 0 : `value ${report.semantics.value}`,
1534
- report.semantics.states === void 0 || report.semantics.states.length === 0 ? void 0 : `states ${report.semantics.states.join(", ")}`
1535
- ].filter((part) => part !== void 0);
1536
- if (parts.length > 0) lines.push(`semantics: ${parts.join(" · ")}`);
1537
- }
1538
- lines.push(report.explanation);
1539
- return lines.join("\n");
1540
- }
1541
- //#endregion
1542
- //#region src/worker/captureConsole.ts
1543
- const LEVELS = [
1544
- "log",
1545
- "info",
1546
- "warn",
1547
- "error",
1548
- "debug"
1549
- ];
1550
- /**
1551
- * Copies every `console.*` call on `target` (the worker global's
1552
- * console by default) to `sink`. Returns a function that restores the
1553
- * original methods.
1554
- *
1555
- * Idempotent per target: a second capture on the same console replaces
1556
- * the first's sink rather than nesting, so toggling a panel on twice
1557
- * does not log twice.
1558
- */
1559
- function captureConsole(sink, target = console) {
1560
- const installed = target[CAPTURED];
1561
- if (installed !== void 0) {
1562
- installed.sink = sink;
1563
- return installed.restore;
1564
- }
1565
- const originals = /* @__PURE__ */ new Map();
1566
- const state = {
1567
- sink,
1568
- restore: () => {
1569
- for (const [level, original] of originals) target[level] = original;
1570
- delete target[CAPTURED];
1571
- }
1572
- };
1573
- for (const level of LEVELS) {
1574
- const original = target[level];
1575
- originals.set(level, original);
1576
- target[level] = (...args) => {
1577
- original.apply(target, args);
1578
- try {
1579
- state.sink({
1580
- level,
1581
- args: args.map(formatConsoleArg),
1582
- at: Date.now()
1583
- });
1584
- } catch {}
1585
- };
1586
- }
1587
- target[CAPTURED] = state;
1588
- return state.restore;
1589
- }
1590
- const CAPTURED = Symbol.for("gesso:console-captured");
1591
- /**
1592
- * One console argument as the panel prints it.
1593
- *
1594
- * `printPropValue` already prints the values a canvas UI is likely to
1595
- * log; an Error is the one thing it prints badly (`{}`), and the one
1596
- * thing a developer most wants to read whole.
1597
- */
1598
- function formatConsoleArg(value) {
1599
- if (value instanceof Error) return value.stack !== void 0 && value.stack !== "" ? value.stack : `${value.name}: ${value.message}`;
1600
- return printPropValue(value);
1601
- }
1602
- function isConsoleForwardingMessage(value) {
1603
- const message = value;
1604
- return message?.type === "gesso:console" && typeof message.enabled === "boolean";
1605
- }
1606
- function isConsoleEntryMessage(value) {
1607
- const message = value;
1608
- return message?.type === "gesso:console" && typeof message.entry === "object" && message.entry !== null;
1609
- }
1610
- //#endregion
1611
- //#region src/worker/WorkerPorts.ts
1612
- /**
1613
- * Named `MessagePort`s into a worker.
1614
- *
1615
- * A worker's global `onmessage` is a single channel, so a worker that
1616
- * receives messages on it can host exactly one conversation. That is
1617
- * why a store in a data worker used to mean a worker per store: the
1618
- * client claimed the `Worker` object itself, and a second one had
1619
- * nowhere to go.
1620
- *
1621
- * A handshake fixes it. The client opens a `MessageChannel`, keeps one
1622
- * end and transfers the other with a name; the worker serves that name
1623
- * and the two ends talk privately from then on. The global channel is
1624
- * used once per conversation and carries nothing else.
1625
- *
1626
- * Nothing here knows what travels over a port. It is the transport the
1627
- * store replication in `../store/worker` runs on today and the barrier
1628
- * contract will run on next.
1629
- */
1630
- function isPortHandshake(value) {
1631
- const message = value;
1632
- return message?.type === "gesso:port" && typeof message.key === "string";
1633
- }
1634
- /**
1635
- * Stands for "whichever worker the shell spawned for the application".
1636
- *
1637
- * A registration inside the render worker cannot name that worker: it
1638
- * is created by the shell and its port only arrives with `init`, long
1639
- * after `useChannel` and `useService` have run. This sentinel is what a
1640
- * registration puts there instead, and the render worker swaps it for
1641
- * the real handle once the port shows up.
1642
- *
1643
- * Opening a port on it before then is a bug rather than a race, so it
1644
- * says so.
1645
- */
1646
- const APPLICATION_WORKER = {
1647
- open() {
1648
- throw new Error("APPLICATION_WORKER was used directly. It is a placeholder the render worker replaces with the shell's port; reaching it means no application-logic worker was supplied. Pass appLogicWorker to createApp.");
1649
- },
1650
- spawned: false,
1651
- terminate() {}
1652
- };
1653
- /**
1654
- * A handle over an endpoint someone else owns.
1655
- *
1656
- * The shell spawns the application worker and hands the render worker
1657
- * one end of a channel to it; this is what the render worker opens
1658
- * named ports over. `terminate` is a no-op — the lifetime belongs to
1659
- * whoever created the endpoint, and a handle that could kill a worker
1660
- * it did not spawn would be a surprising thing to hand out.
1661
- */
1662
- function portHandle(endpoint) {
1663
- return {
1664
- open(key) {
1665
- const channel = new MessageChannel();
1666
- endpoint.postMessage({
1667
- type: "gesso:port",
1668
- key
1669
- }, [channel.port2]);
1670
- return channel.port1;
1671
- },
1672
- get spawned() {
1673
- return true;
1674
- },
1675
- terminate() {}
1676
- };
1677
- }
1678
- function isHubMessage(value) {
1679
- return value?.type === "gesso:hub";
1680
- }
1681
- const BASE_INSTALLED = Symbol.for("gesso:port-base-installed");
1682
- const CONSOLE_RESTORE = Symbol.for("gesso:port-console-restore");
1683
- /**
1684
- * Starts or stops copying this worker's console to whoever posts to
1685
- * it, as `ConsoleEntryMessage`s. A host with no `postMessage` (a test's
1686
- * bare object) has nowhere to send them and forwards nothing.
1687
- */
1688
- function setConsoleForwarding(host, enabled) {
1689
- host[CONSOLE_RESTORE]?.();
1690
- delete host[CONSOLE_RESTORE];
1691
- const post = host.postMessage;
1692
- if (!enabled || typeof post !== "function") return;
1693
- host[CONSOLE_RESTORE] = captureConsole((entry) => {
1694
- const message = {
1695
- type: "gesso:console",
1696
- entry
1697
- };
1698
- post.call(host, message);
1699
- });
1700
- }
1701
- /**
1702
- * The handler every `servePorts` chain sits on top of.
1703
- *
1704
- * It owns the two things no individual server can: routing a hub port
1705
- * through the whole chain, and answering a handshake that nobody
1706
- * accepted. Both have to be innermost — the first because the chain is
1707
- * only complete once every server has wrapped `onmessage`, the second
1708
- * because "nobody accepted" is only known after every server has
1709
- * declined.
1710
- */
1711
- function installBase(host) {
1712
- if (host[BASE_INSTALLED] === true) return;
1713
- host[BASE_INSTALLED] = true;
1714
- const previous = host.onmessage;
1715
- const registered = host[SERVED_NAMES] ?? [];
1716
- host.onmessage = (event) => {
1717
- if (isConsoleForwardingMessage(event.data)) {
1718
- setConsoleForwarding(host, event.data.enabled);
1719
- return;
1720
- }
1721
- if (isHubMessage(event.data)) {
1722
- const port = event.ports?.[0];
1723
- if (port === void 0) throw new Error("A hub message arrived with no port attached.");
1724
- port.onmessage = host.onmessage;
1725
- return;
1726
- }
1727
- if (!isPortHandshake(event.data)) {
1728
- previous?.(event);
1729
- return;
1730
- }
1731
- const port = event.ports?.[0];
1732
- if (port === void 0) throw new Error(`Port handshake for '${event.data.key}' arrived with no port attached.`);
1733
- const served = registered.flatMap((get) => [...get()]).sort();
1734
- const error = {
1735
- type: "port:error",
1736
- message: `Nothing is served under '${event.data.key}'. This worker serves: ${served.length > 0 ? served.join(", ") : "(nothing)"}.`
1737
- };
1738
- port.postMessage(error);
1739
- };
1740
- }
1741
- /**
1742
- * Wraps a worker factory so the worker is created once and shared.
1743
- *
1744
- * A factory rather than a URL for the same reason the render worker
1745
- * takes one: a bundler only emits a chunk for a worker it can see
1746
- * constructed literally in the calling module.
1747
- *
1748
- * const data = workerHandle(
1749
- * () => new Worker(new URL('./data.worker.ts', import.meta.url), { type: 'module' })
1750
- * );
1751
- */
1752
- function workerHandle(factory) {
1753
- let worker;
1754
- return {
1755
- open(key) {
1756
- worker ??= factory();
1757
- const channel = new MessageChannel();
1758
- worker.postMessage({
1759
- type: "gesso:port",
1760
- key
1761
- }, [channel.port2]);
1762
- return channel.port1;
1763
- },
1764
- get spawned() {
1765
- return worker !== void 0;
1766
- },
1767
- terminate() {
1768
- worker?.terminate();
1769
- worker = void 0;
1770
- }
1771
- };
1772
- }
1773
- function isPortErrorMessage(value) {
1774
- const message = value;
1775
- return message?.type === "port:error" && typeof message.message === "string";
1776
- }
1777
- /** Every name served on a host, across all `servePorts` calls on it. */
1778
- const SERVED_NAMES = Symbol.for("gesso:served-port-names");
1779
- /**
1780
- * Serves named ports inside a worker.
1781
- *
1782
- * Call it synchronously at the top level of the worker module, before
1783
- * any await, so no handshake is missed.
1784
- *
1785
- * `onPort` returns whether it took the port. Returning false passes
1786
- * the handshake to whatever was serving before, which is what lets two
1787
- * kinds of thing — stores and channels, during the migration — share
1788
- * one worker: each answers for its own names and declines the rest.
1789
- * When nobody accepts, the port is answered with an error naming
1790
- * everything the worker does serve, because a handshake that silently
1791
- * matched nothing leaves the client waiting forever with nothing said.
1792
- *
1793
- * `names` is only read to build that message.
1794
- *
1795
- * Returns a function that stops serving.
1796
- */
1797
- function servePorts(onPort, names, host = self) {
1798
- const withNames = host;
1799
- const registered = withNames[SERVED_NAMES] ??= [];
1800
- registered.push(names);
1801
- installBase(host);
1802
- const previous = host.onmessage;
1803
- host.onmessage = (event) => {
1804
- if (!isPortHandshake(event.data)) {
1805
- previous?.(event);
1806
- return;
1807
- }
1808
- const port = event.ports?.[0];
1809
- if (port === void 0) throw new Error(`Port handshake for '${event.data.key}' arrived with no port attached.`);
1810
- if (onPort(event.data.key, port)) return;
1811
- previous?.(event);
1812
- };
1813
- return () => {
1814
- host.onmessage = previous;
1815
- const index = registered.indexOf(names);
1816
- if (index >= 0) registered.splice(index, 1);
1817
- };
1818
- }
1819
- //#endregion
1820
- //#region src/channel/serveChannels.ts
1821
- /**
1822
- * One served channel, with its source checked against its token.
1823
- *
1824
- * `ServedChannel` is erased on purpose, so one list can hold channels
1825
- * of every shape; the cost is that a view key the token declares and
1826
- * the source forgets is found at startup, by the error `provide`
1827
- * reports, rather than by the compiler. This is the typed seam: the
1828
- * source must hold an Observable for every key of the token's view and
1829
- * a handler for every command, and each handler takes the arguments
1830
- * the token declares, so none of them needs an annotation.
1831
- *
1832
- * serveChannels([
1833
- * serve(Catalog, { view: catalog, commands: { add: name => catalog.add(name) } })
1834
- * ]);
1835
- *
1836
- * The view may be any object with the right observables on it, which
1837
- * is often the domain object itself when its properties are named
1838
- * after the keys. Only the declared keys are read from it.
1839
- */
1840
- function serve(token, source) {
1841
- return {
1842
- token,
1843
- source
1844
- };
1845
- }
1846
- /**
1847
- * Publishes channels from an application worker.
1848
- *
1849
- * Call it synchronously at the top level of the worker module, before
1850
- * any await, so no handshake is missed:
1851
- *
1852
- * const catalog = new CatalogViewModel(new CatalogDomain(new OpfsStore()));
1853
- * serveChannels([
1854
- * serve(Catalog, { view: { products: catalog.products$ }, commands: { … } })
1855
- * ]);
1856
- *
1857
- * Everything above this call is the application's own — plain classes,
1858
- * plain observables, no framework import. This function is the entire
1859
- * seam between it and the view.
1860
- *
1861
- * Returns a function that stops serving and disposes what it provided.
1862
- */
1863
- function serveChannels(channels, host) {
1864
- const byName = /* @__PURE__ */ new Map();
1865
- for (const served of channels) byName.set(served.token.name, served);
1866
- const provided = [];
1867
- const stop = servePorts((key, port) => {
1868
- if (key === "gesso:agent") {
1869
- serveAgentPort(port, (confirm) => agentSurface(channels, { confirm }));
1870
- return true;
1871
- }
1872
- const served = byName.get(key);
1873
- if (served === void 0) return false;
1874
- provided.push(provide(served.token, served.source, port));
1875
- return true;
1876
- }, () => [...byName.keys()], host);
1877
- return () => {
1878
- stop();
1879
- for (const channel of provided) channel.dispose();
1880
- provided.length = 0;
1881
- };
1882
- }
1883
- //#endregion
1884
937
  //#region src/channel/pick.ts
1885
938
  /**
1886
939
  * One key of a view model, as its own Observable, emitting only when
@@ -2675,6 +1728,6 @@ function persisted(adapter, key, options) {
2675
1728
  return new PersistedState(adapter, key, options);
2676
1729
  }
2677
1730
  //#endregion
2678
- export { structurallyEqual as $, printPropValue as A, channel as B, captureConsole as C, formatNodePath as D, formatAge as E, applyPatch as F, mutate as G, viewKeys as H, applyPatches as I, select as J, Resource as K, diffProjection as L, provide as M, findUnplainPath as N, formatNodeReport as O, requirePlainData as P, equalityOf as Q, isChannelClientMessage as R, workerHandle as S, describeStream as T, debounced as U, defineChannel as V, throttled as W, computed as X, ComputedCell as Y, derive as Z, isHubMessage as _, undoable as a, isOutputTarget as at, portHandle as b, classifyStorageError as c, trackRead as ct, storageReadValue as d, InternalState as et, pick as f, APPLICATION_WORKER as g, serveChannels as h, OpfsStorage as i, into as it, ProvidedChannel as j, formatStream as k, storageErrorMessage as l, withBodyOf as lt, serve as m, persisted as n, InputCell as nt, UndoStack as o, output as ot, pickKeys as p, resource as q, IndexedDbStorage as r, input as rt, MemoryStorage as s, outputTargetOf as st, PersistedState as t, internalState as tt, storageReadFailure as u, isPortErrorMessage as v, isConsoleEntryMessage as w, servePorts as x, isPortHandshake as y, isChannelHostMessage as z };
1731
+ export { output as A, equalityOf as C, input as D, InputCell as E, trackRead as M, withBodyOf as N, into as O, derive as S, internalState as T, Resource as _, undoable as a, ComputedCell as b, classifyStorageError as c, storageReadValue as d, pick as f, mutate as g, throttled as h, OpfsStorage as i, outputTargetOf as j, isOutputTarget as k, storageErrorMessage as l, debounced as m, persisted as n, UndoStack as o, pickKeys as p, IndexedDbStorage as r, MemoryStorage as s, PersistedState as t, storageReadFailure as u, resource as v, InternalState as w, computed as x, select as y };
2679
1732
 
2680
- //# sourceMappingURL=persisted-pix1fS1D.js.map
1733
+ //# sourceMappingURL=persisted-i6TIWX8R.js.map