castle-web-cli 0.4.227 → 0.4.229

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.
Files changed (42) hide show
  1. package/dist/agent-prompts.d.ts +9 -3
  2. package/dist/agent-prompts.js +140 -48
  3. package/dist/agent.js +127 -14
  4. package/dist/api.d.ts +37 -0
  5. package/dist/api.js +29 -0
  6. package/dist/castle-host/host.d.ts +6 -0
  7. package/dist/castle-host/host.js +42 -3
  8. package/dist/castleJson.d.ts +15 -0
  9. package/dist/castleJson.js +136 -3
  10. package/dist/cloudGit.d.ts +27 -1
  11. package/dist/cloudGit.js +359 -24
  12. package/dist/cloudGitServe.js +9 -5
  13. package/dist/gitCollaborators.d.ts +16 -0
  14. package/dist/gitCollaborators.js +42 -0
  15. package/dist/gitIncoming.d.ts +17 -0
  16. package/dist/gitIncoming.js +113 -0
  17. package/dist/gitRemote.js +2 -2
  18. package/dist/imports.js +4 -2
  19. package/dist/index.js +5 -0
  20. package/dist/init.js +1 -1
  21. package/dist/native/playtest-browser.js +13 -1
  22. package/dist/platformDoc.js +1 -1
  23. package/dist/save-deck.js +3 -0
  24. package/dist/serve.js +17 -0
  25. package/dist/shell/assets/index-Cf61cNfT.css +1 -0
  26. package/dist/shell/assets/{index-D006JHww.js → index-D2tWM896.js} +71 -71
  27. package/dist/shell/index.html +2 -2
  28. package/dist/sourceLineage.d.ts +42 -0
  29. package/dist/sourceLineage.js +380 -0
  30. package/dist/webSourceSync.d.ts +9 -0
  31. package/dist/webSourceSync.js +24 -9
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/sdk/README.md +81 -0
  34. package/kits/base/sdk/castle.d.ts +1 -1
  35. package/kits/base/sdk/commands.d.ts +6 -0
  36. package/kits/base/sdk/multiplayer.d.ts +44 -6
  37. package/kits/base/sdk/multiplayer.js +62 -1
  38. package/kits/base/sdk/server/platformHandle.d.ts +9 -1
  39. package/kits/base/sdk/server/wrapper.d.ts +111 -4
  40. package/kits/base/sdk/server/wrapper.js +650 -24
  41. package/package.json +10 -2
  42. package/dist/shell/assets/index-BxDYy_-C.css +0 -1
@@ -1,5 +1,5 @@
1
1
  import { isBinaryPayload, toUint8Array, } from "../multiplayerProtocol";
2
- import { encodeStorageValue } from "../storageJson";
2
+ import { encodeStorageValue, storageError } from "../storageJson";
3
3
  import { createServerStorage } from "./storage";
4
4
  // The publish bundler binds the author's default callbacks export once and
5
5
  // exports the returned one-argument function as `__castleBootSession`.
@@ -23,8 +23,9 @@ async function bootSession(platformHandle, callbacks) {
23
23
  platformHandle.on("leave", async (connId) => {
24
24
  const player = players.get(connId);
25
25
  players.delete(connId);
26
- if (player)
26
+ if (player) {
27
27
  await callbacks.onPlayerLeave?.(session, player);
28
+ }
28
29
  });
29
30
  platformHandle.on("message", async (connId, text) => {
30
31
  const player = players.get(connId);
@@ -53,12 +54,12 @@ async function bootSession(platformHandle, callbacks) {
53
54
  const turn = Object.freeze({
54
55
  requestId: request.requestId,
55
56
  operationId: request.operationId,
56
- speaker: Object.freeze({ ...request.speaker }),
57
+ speaker: Object.freeze(joinedPlayer(request.speaker.playerId, request.speaker)),
57
58
  characterId: request.characterId,
58
59
  input: request.input,
59
60
  audience: Object.freeze({
60
61
  disclosure: request.audience.disclosure,
61
- players: Object.freeze(request.audience.players.map((player) => Object.freeze({ ...player }))),
62
+ players: Object.freeze(request.audience.players.map((player) => Object.freeze(joinedPlayer(player.playerId, player)))),
62
63
  characterIds: Object.freeze([...request.audience.characterIds]),
63
64
  }),
64
65
  async send() {
@@ -102,9 +103,10 @@ async function bootSession(platformHandle, callbacks) {
102
103
  let settled = false;
103
104
  const brokerFailure = { rejection: null };
104
105
  const command = Object.freeze({
106
+ type: request.command.type,
105
107
  requestId: request.requestId,
106
108
  operationId: request.operationId,
107
- speaker: Object.freeze({ ...request.speaker }),
109
+ speaker: Object.freeze(joinedPlayer(request.speaker.playerId, request.speaker)),
108
110
  command: deepFreezeJsonObject(request.command),
109
111
  async apply() {
110
112
  if (settled)
@@ -148,7 +150,7 @@ async function bootSession(platformHandle, callbacks) {
148
150
  const brokerFailure = { rejection: null };
149
151
  const read = Object.freeze({
150
152
  requestId: request.requestId,
151
- speaker: Object.freeze({ ...request.speaker }),
153
+ speaker: Object.freeze(joinedPlayer(request.speaker.playerId, request.speaker)),
152
154
  query: deepFreezeJsonObject(request.query),
153
155
  async read() {
154
156
  if (settled)
@@ -252,6 +254,26 @@ function createAuthorSession(platformHandle, players) {
252
254
  const WORLD_OPERATION_ID_MAX_BYTES = 128;
253
255
  const WORLD_OPERATION_ID_MAX_CHARACTERS = 120;
254
256
  const WORLD_CHECKPOINT_VERSION_MAX = 2_147_483_647;
257
+ const WORLD_JOURNAL_MAX_ENTRIES = 16;
258
+ const WORLD_JOURNAL_MAX_KIND_CHARACTERS = 64;
259
+ const WORLD_JOURNAL_MAX_PARTICIPANT_BYTES = 128;
260
+ const WORLD_JOURNAL_MAX_PARTICIPANTS_PER_ENTRY = 16;
261
+ const WORLD_JOURNAL_MAX_PARTICIPANT_FILTERS = 64;
262
+ const WORLD_JOURNAL_MAX_DATA_BYTES = 2_048;
263
+ const WORLD_JOURNAL_MAX_REQUEST_BYTES = 16 * 1_024;
264
+ const WORLD_JOURNAL_MAX_READ_LIMIT = 128;
265
+ const WORLD_PARTICIPANTS_MAX_READ_LIMIT = 256;
266
+ const WORLD_JOURNAL_MAX_SEQUENCE = "9223372036854775807";
267
+ const SAFE_WORLD_JOURNAL_KIND = /^[A-Za-z0-9_.:-]+$/;
268
+ const WORLD_NOTIFICATIONS_MAX_PARTICIPANTS = 16;
269
+ const WORLD_NOTIFICATIONS_MAX_SLOTS = 4;
270
+ const WORLD_NOTIFICATIONS_MAX_SLOT_CHARACTERS = 40;
271
+ const WORLD_NOTIFICATIONS_MAX_SCHEDULE_MS = 30 * 24 * 60 * 60 * 1_000;
272
+ const WORLD_NOTIFICATIONS_PAST_TOLERANCE_MS = 60 * 1_000;
273
+ const WORLD_CATCH_UP_DEFAULT_MAX_ELAPSED_MS = 7 * 24 * 60 * 60 * 1_000;
274
+ const SAFE_WORLD_NOTIFICATION_KEY = /^[A-Za-z0-9_-]+$/;
275
+ const CANONICAL_WORLD_NOTIFICATION_TIME = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/;
276
+ const URL_IN_WORLD_NOTIFICATION_TEXT = /(?:https?:\/\/|www\.|\b[a-z0-9-]+\.(?:app|com|dev|gg|io|net|org|xyz)\b)/i;
255
277
  function createServerWorld(platformHandle) {
256
278
  if (!platformHandle.config.world)
257
279
  return null;
@@ -260,34 +282,632 @@ function createServerWorld(platformHandle) {
260
282
  throw worldError("The persistent-world checkpoint broker is unavailable.", "read");
261
283
  }
262
284
  const initial = parseWorldSnapshot(platformHandle.config.world, "read");
285
+ const read = async () => {
286
+ const result = await platformHandle.worldCheckpointRead();
287
+ return parseWorldSnapshot(parsePlatformJson(result, "read"), "read");
288
+ };
289
+ const commit = async (input) => {
290
+ const expectedRevision = assertWorldRevision(input?.expectedRevision);
291
+ const operationId = assertWorldOperationId(input?.operationId);
292
+ const checkpoint = assertWorldCheckpoint(input?.checkpoint);
293
+ const raw = await platformHandle.worldCheckpointCommit(JSON.stringify({
294
+ expectedRevision,
295
+ operationId,
296
+ checkpoint,
297
+ }));
298
+ const result = parsePlatformJson(raw, "commit");
299
+ if (typeof result.replayed !== "boolean") {
300
+ throw worldError("The platform returned an invalid commit receipt.", "commit");
301
+ }
302
+ return Object.freeze({
303
+ revision: assertWorldRevision(result.revision),
304
+ replayed: result.replayed,
305
+ operationId,
306
+ });
307
+ };
263
308
  return Object.freeze({
264
309
  snapshot: initial,
310
+ journal: createServerWorldJournal(platformHandle),
311
+ participants: createServerWorldParticipants(platformHandle),
312
+ notifications: createServerWorldNotifications(platformHandle),
265
313
  characters: createServerWorldCharacters(platformHandle),
266
- async read() {
267
- const result = await platformHandle.worldCheckpointRead();
268
- return parseWorldSnapshot(parsePlatformJson(result, "read"), "read");
314
+ read,
315
+ commit,
316
+ async catchUp(options) {
317
+ return catchUpWorld(platformHandle.config.world?.worldTime, read, commit, options);
269
318
  },
270
- async commit(input) {
271
- const expectedRevision = assertWorldRevision(input?.expectedRevision);
272
- const operationId = assertWorldOperationId(input?.operationId);
273
- const checkpoint = assertWorldCheckpoint(input?.checkpoint);
274
- const raw = await platformHandle.worldCheckpointCommit(JSON.stringify({
275
- expectedRevision,
276
- operationId,
319
+ });
320
+ }
321
+ async function catchUpWorld(worldTime, read, commit, options) {
322
+ const operation = "session.world.catchUp";
323
+ if (worldTime?.advance !== "wallClock") {
324
+ throw worldJournalArgumentError('The destination must opt in with worldTime.advance set to "wallClock".', operation);
325
+ }
326
+ assertOnlyKeys(options, ["key", "maxElapsedMs", "apply"], operation, "options");
327
+ const key = options.key === undefined
328
+ ? "advancedThroughMs"
329
+ : assertWorldCatchUpKey(options.key, operation);
330
+ const maxElapsedMs = options.maxElapsedMs === undefined
331
+ ? WORLD_CATCH_UP_DEFAULT_MAX_ELAPSED_MS
332
+ : assertBoundedInteger(options.maxElapsedMs, 0, Number.MAX_SAFE_INTEGER, "maxElapsedMs", operation);
333
+ if (typeof options.apply !== "function") {
334
+ throw worldJournalArgumentError("apply must be a function.", operation);
335
+ }
336
+ const now = Date.now();
337
+ let snapshot = await read();
338
+ for (let attempt = 0; attempt < 2; attempt += 1) {
339
+ const state = worldCatchUpState(snapshot.checkpoint, key, now, maxElapsedMs, operation);
340
+ if (state.markerExists && state.elapsedMs === 0) {
341
+ if (state.markerMs >= now) {
342
+ return Object.freeze({ applied: false, elapsedMs: 0, revision: snapshot.revision });
343
+ }
344
+ const checkpoint = checkpointWithCatchUpMarker(snapshot.checkpoint, key, state.markerMs, now, operation);
345
+ try {
346
+ const receipt = await commit({
347
+ expectedRevision: snapshot.revision,
348
+ operationId: `catchUp:${snapshot.revision}`,
349
+ checkpoint,
350
+ });
351
+ return Object.freeze({ applied: false, elapsedMs: 0, revision: receipt.revision });
352
+ }
353
+ catch (error) {
354
+ if (attempt !== 0 || !isWorldRevisionConflict(error))
355
+ throw error;
356
+ snapshot = await read();
357
+ continue;
358
+ }
359
+ }
360
+ const returned = await options.apply(Object.freeze({
361
+ elapsedMs: state.elapsedMs,
362
+ now,
363
+ checkpoint: snapshot.checkpoint,
364
+ }));
365
+ const normalized = assertWorldCheckpoint(returned, "commit");
366
+ if (!isRecord(normalized.value)) {
367
+ throw worldJournalArgumentError("apply must return a checkpoint whose value is an object.", operation);
368
+ }
369
+ const checkpoint = checkpointWithCatchUpMarker(normalized, key, state.markerMs, now, operation);
370
+ try {
371
+ const receipt = await commit({
372
+ expectedRevision: snapshot.revision,
373
+ operationId: `catchUp:${snapshot.revision}`,
277
374
  checkpoint,
278
- }));
279
- const result = parsePlatformJson(raw, "commit");
280
- if (typeof result.replayed !== "boolean") {
281
- throw worldError("The platform returned an invalid commit receipt.", "commit");
375
+ });
376
+ return Object.freeze({
377
+ applied: !receipt.replayed,
378
+ elapsedMs: state.elapsedMs,
379
+ revision: receipt.revision,
380
+ });
381
+ }
382
+ catch (error) {
383
+ if (attempt !== 0 || !isWorldRevisionConflict(error))
384
+ throw error;
385
+ snapshot = await read();
386
+ }
387
+ }
388
+ throw new TypeError(`${operation}: unreachable catch-up state.`);
389
+ }
390
+ function assertWorldCatchUpKey(value, operation) {
391
+ if (typeof value !== "string") {
392
+ throw worldJournalArgumentError("key must be a string.", operation);
393
+ }
394
+ return value;
395
+ }
396
+ function worldCatchUpState(checkpoint, key, now, maxElapsedMs, operation) {
397
+ if (!checkpoint ||
398
+ !isRecord(checkpoint.value) ||
399
+ !Object.prototype.hasOwnProperty.call(checkpoint.value, key)) {
400
+ return { markerExists: false, markerMs: now, elapsedMs: 0 };
401
+ }
402
+ const advancedThroughMs = checkpoint.value[key];
403
+ if (!Number.isSafeInteger(advancedThroughMs) || advancedThroughMs < 0) {
404
+ throw worldJournalArgumentError(`checkpoint.value.${key} must be a non-negative integer timestamp in milliseconds.`, operation);
405
+ }
406
+ const markerMs = advancedThroughMs;
407
+ return {
408
+ markerExists: true,
409
+ markerMs,
410
+ elapsedMs: Math.min(maxElapsedMs, Math.max(0, now - markerMs)),
411
+ };
412
+ }
413
+ function checkpointWithCatchUpMarker(checkpoint, key, existingMarkerMs, now, operation) {
414
+ if (!isRecord(checkpoint.value)) {
415
+ throw worldJournalArgumentError("apply must return a checkpoint whose value is an object.", operation);
416
+ }
417
+ return Object.freeze({
418
+ version: checkpoint.version,
419
+ value: Object.freeze({
420
+ ...checkpoint.value,
421
+ [key]: Math.max(existingMarkerMs, now),
422
+ }),
423
+ });
424
+ }
425
+ function isWorldRevisionConflict(error) {
426
+ return isRecord(error) && error.code === "CAULDRON_WORLD_REVISION_CONFLICT";
427
+ }
428
+ function createServerWorldJournal(platformHandle) {
429
+ return Object.freeze({
430
+ async append(input) {
431
+ const operation = "session.world.journal.append";
432
+ assertOnlyKeys(input, ["operationId", "entries"], operation, "input");
433
+ const operationId = assertWorldJournalOperationId(input?.operationId, operation);
434
+ if (!Array.isArray(input?.entries) ||
435
+ input.entries.length < 1 ||
436
+ input.entries.length > WORLD_JOURNAL_MAX_ENTRIES) {
437
+ throw worldJournalArgumentError(`entries must contain from 1 through ${WORLD_JOURNAL_MAX_ENTRIES} entries.`, operation);
438
+ }
439
+ const entries = input.entries.map((entry, index) => normalizeWorldJournalAppendEntry(entry, index, operation));
440
+ const args = { operationId, entries };
441
+ if (utf8Length(JSON.stringify(args)) > WORLD_JOURNAL_MAX_REQUEST_BYTES) {
442
+ throw worldJournalArgumentError(`The serialized request may be at most ${WORLD_JOURNAL_MAX_REQUEST_BYTES} bytes.`, operation);
443
+ }
444
+ const result = parseWorldJournalJson(await callWorldJournalStorage(platformHandle, "worldJournalAppend", args, operation), operation);
445
+ if (!isRecord(result) || result.operationId !== operationId ||
446
+ typeof result.replayed !== "boolean") {
447
+ throw invalidWorldJournalResponse(operation);
282
448
  }
283
449
  return Object.freeze({
284
- revision: assertWorldRevision(result.revision),
285
- replayed: result.replayed,
286
450
  operationId,
451
+ replayed: result.replayed,
452
+ firstSeq: parseWorldJournalSequence(result.firstSeq, operation, true),
453
+ lastSeq: parseWorldJournalSequence(result.lastSeq, operation, true),
454
+ });
455
+ },
456
+ async read(options = {}) {
457
+ const operation = "session.world.journal.read";
458
+ assertOnlyKeys(options, ["afterSeq", "limit", "participantId"], operation, "options");
459
+ const args = {};
460
+ if (options.afterSeq !== undefined) {
461
+ args.afterSeq = assertWorldJournalSequence(options.afterSeq, operation, "afterSeq");
462
+ }
463
+ if (options.limit !== undefined) {
464
+ args.limit = assertBoundedInteger(options.limit, 1, WORLD_JOURNAL_MAX_READ_LIMIT, "limit", operation);
465
+ }
466
+ if (options.participantId !== undefined) {
467
+ args.participantId = assertWorldParticipantId(options.participantId, "participantId", operation);
468
+ }
469
+ const result = parseWorldJournalJson(await callWorldJournalStorage(platformHandle, "worldJournalRead", args, operation), operation);
470
+ if (!isRecord(result) || !Array.isArray(result.entries) ||
471
+ result.entries.length > WORLD_JOURNAL_MAX_READ_LIMIT) {
472
+ throw invalidWorldJournalResponse(operation);
473
+ }
474
+ const entries = result.entries.map((entry) => parseWorldJournalEntry(entry, operation));
475
+ return Object.freeze({
476
+ entries: Object.freeze(entries),
477
+ nextSeq: parseWorldJournalSequence(result.nextSeq, operation),
478
+ oldestRetainedSeq: result.oldestRetainedSeq === null
479
+ ? null
480
+ : parseWorldJournalSequence(result.oldestRetainedSeq, operation, true),
481
+ });
482
+ },
483
+ });
484
+ }
485
+ function createServerWorldParticipants(platformHandle) {
486
+ return Object.freeze({
487
+ async read(options = {}) {
488
+ const operation = "session.world.participants.read";
489
+ assertOnlyKeys(options, ["participantIds", "limit"], operation, "options");
490
+ const args = {};
491
+ if (options.participantIds !== undefined) {
492
+ args.participantIds = normalizeParticipantIds(options.participantIds, WORLD_JOURNAL_MAX_PARTICIPANT_FILTERS, "participantIds", operation);
493
+ }
494
+ if (options.limit !== undefined) {
495
+ args.limit = assertBoundedInteger(options.limit, 1, WORLD_PARTICIPANTS_MAX_READ_LIMIT, "limit", operation);
496
+ }
497
+ const result = parseWorldJournalJson(await callWorldJournalStorage(platformHandle, "worldParticipantsRead", args, operation), operation);
498
+ if (!isRecord(result) || !Array.isArray(result.participants) ||
499
+ result.participants.length > WORLD_PARTICIPANTS_MAX_READ_LIMIT) {
500
+ throw invalidWorldJournalResponse(operation);
501
+ }
502
+ return Object.freeze({
503
+ participants: Object.freeze(result.participants.map((participant) => parseWorldParticipant(participant, operation))),
504
+ });
505
+ },
506
+ });
507
+ }
508
+ function createServerWorldNotifications(platformHandle) {
509
+ return Object.freeze({
510
+ async notify(input) {
511
+ const operation = "session.world.notifications.notify";
512
+ assertOnlyKeys(input, ["key", "participantIds", "templateId", "slots", "at", "expiresAt"], operation, "input");
513
+ const now = Date.now();
514
+ const key = assertWorldNotificationSafeKey(input.key, "key", operation);
515
+ const participantIds = normalizeParticipantIds(input.participantIds, WORLD_NOTIFICATIONS_MAX_PARTICIPANTS, "participantIds", operation);
516
+ const templateId = assertWorldNotificationSafeKey(input.templateId, "templateId", operation);
517
+ const slots = input.slots === undefined
518
+ ? undefined
519
+ : normalizeWorldNotificationSlots(input.slots, operation);
520
+ const at = input.at === undefined
521
+ ? undefined
522
+ : assertWorldNotificationTime(input.at, "at", operation);
523
+ const atMs = at?.milliseconds ?? now;
524
+ if (atMs < now - WORLD_NOTIFICATIONS_PAST_TOLERANCE_MS ||
525
+ atMs > now + WORLD_NOTIFICATIONS_MAX_SCHEDULE_MS) {
526
+ throw worldJournalArgumentError("at must be no more than 60 seconds in the past and at most 30 days ahead.", operation);
527
+ }
528
+ // Ghost clamps a tolerated past `at` to its own now, so expiry is judged
529
+ // against that effective time, not the original timestamp.
530
+ const effectiveAtMs = Math.max(atMs, now);
531
+ const expiresAt = input.expiresAt === undefined
532
+ ? undefined
533
+ : assertWorldNotificationTime(input.expiresAt, "expiresAt", operation);
534
+ if (expiresAt &&
535
+ (expiresAt.milliseconds <= effectiveAtMs ||
536
+ expiresAt.milliseconds > effectiveAtMs + WORLD_NOTIFICATIONS_MAX_SCHEDULE_MS)) {
537
+ throw worldJournalArgumentError("expiresAt must be after at and at most 30 days after it.", operation);
538
+ }
539
+ const args = {
540
+ key,
541
+ participantIds,
542
+ templateId,
543
+ ...(slots === undefined ? {} : { slots }),
544
+ ...(at === undefined ? {} : { at: at.value }),
545
+ ...(expiresAt === undefined ? {} : { expiresAt: expiresAt.value }),
546
+ };
547
+ const result = parseWorldNotificationResult(await callWorldNotificationStorage(platformHandle, "worldNotify", args, operation), operation);
548
+ if (result.key !== key)
549
+ throw invalidWorldNotificationResponse(operation);
550
+ return Object.freeze({
551
+ key,
552
+ accepted: parseWorldNotificationCount(result.accepted, operation),
553
+ skipped: parseWorldNotificationCount(result.skipped, operation),
554
+ limited: parseWorldNotificationCount(result.limited, operation),
555
+ });
556
+ },
557
+ async cancel(input) {
558
+ const operation = "session.world.notifications.cancel";
559
+ assertOnlyKeys(input, ["key", "participantIds"], operation, "input");
560
+ const key = assertWorldNotificationSafeKey(input.key, "key", operation);
561
+ const participantIds = input.participantIds === undefined
562
+ ? undefined
563
+ : normalizeParticipantIds(input.participantIds, WORLD_NOTIFICATIONS_MAX_PARTICIPANTS, "participantIds", operation);
564
+ const args = {
565
+ key,
566
+ ...(participantIds === undefined ? {} : { participantIds }),
567
+ };
568
+ const result = parseWorldNotificationResult(await callWorldNotificationStorage(platformHandle, "worldNotifyCancel", args, operation), operation);
569
+ return Object.freeze({
570
+ cancelled: parseWorldNotificationCount(result.cancelled, operation),
287
571
  });
288
572
  },
289
573
  });
290
574
  }
575
+ function assertWorldNotificationSafeKey(value, field, operation) {
576
+ if (typeof value !== "string" ||
577
+ worldNotificationCharacters(value) < 1 ||
578
+ worldNotificationCharacters(value) > 64 ||
579
+ !SAFE_WORLD_NOTIFICATION_KEY.test(value)) {
580
+ throw worldJournalArgumentError(`${field} must be a safe key of at most 64 characters.`, operation);
581
+ }
582
+ return value;
583
+ }
584
+ function normalizeWorldNotificationSlots(value, operation) {
585
+ if (!isRecord(value)) {
586
+ throw worldJournalArgumentError("slots must be an object.", operation);
587
+ }
588
+ const entries = Object.entries(value);
589
+ if (entries.length > WORLD_NOTIFICATIONS_MAX_SLOTS) {
590
+ throw worldJournalArgumentError(`slots may contain at most ${WORLD_NOTIFICATIONS_MAX_SLOTS} values.`, operation);
591
+ }
592
+ const normalized = {};
593
+ for (const [key, slotValue] of entries.sort(([left], [right]) => left.localeCompare(right))) {
594
+ assertWorldNotificationSafeKey(key, `slots.${key}`, operation);
595
+ if (typeof slotValue !== "string" ||
596
+ worldNotificationCharacters(slotValue) < 1 ||
597
+ worldNotificationCharacters(slotValue) > WORLD_NOTIFICATIONS_MAX_SLOT_CHARACTERS ||
598
+ slotValue.includes("\0") ||
599
+ hasUnpairedSurrogate(slotValue) ||
600
+ slotValue.includes("\n") ||
601
+ slotValue.includes("\r") ||
602
+ URL_IN_WORLD_NOTIFICATION_TEXT.test(slotValue)) {
603
+ throw worldJournalArgumentError(`slots.${key} must be 1 through ${WORLD_NOTIFICATIONS_MAX_SLOT_CHARACTERS} ` +
604
+ "characters of single-line text without a URL.", operation);
605
+ }
606
+ normalized[key] = slotValue;
607
+ }
608
+ return Object.freeze(normalized);
609
+ }
610
+ function worldNotificationCharacters(value) {
611
+ return Array.from(value).length;
612
+ }
613
+ function assertWorldNotificationTime(value, field, operation) {
614
+ if (typeof value !== "string") {
615
+ throw worldJournalArgumentError(`${field} must be a canonical ISO 8601 time with at most millisecond precision.`, operation);
616
+ }
617
+ const match = CANONICAL_WORLD_NOTIFICATION_TIME.exec(value);
618
+ const milliseconds = Date.parse(value);
619
+ if (!match || !Number.isFinite(milliseconds)) {
620
+ throw worldJournalArgumentError(`${field} must be a canonical ISO 8601 time with at most millisecond precision.`, operation);
621
+ }
622
+ const normalized = new Date(milliseconds).toISOString();
623
+ const normalizedFraction = normalized.slice(20, 23);
624
+ if (normalized.slice(0, 19) !== match[1] ||
625
+ (match[2] === undefined
626
+ ? normalizedFraction !== "000"
627
+ : normalizedFraction !== match[2].padEnd(3, "0"))) {
628
+ throw worldJournalArgumentError(`${field} must be a canonical ISO 8601 time with at most millisecond precision.`, operation);
629
+ }
630
+ return { value, milliseconds };
631
+ }
632
+ async function callWorldNotificationStorage(platformHandle, op, args, operation) {
633
+ if (typeof platformHandle.storage !== "function" || platformHandle.storageEnabled === false) {
634
+ throw worldNotificationsUnavailable(operation);
635
+ }
636
+ try {
637
+ return await platformHandle.storage(op, JSON.stringify(args));
638
+ }
639
+ catch (error) {
640
+ if (isUnknownStorageOperation(error))
641
+ throw worldNotificationsUnavailable(operation);
642
+ throw error;
643
+ }
644
+ }
645
+ function worldNotificationsUnavailable(operation) {
646
+ return storageError("CAULDRON_WORLD_NOTIFICATIONS_UNAVAILABLE", "This Castle host does not support persistent-world notifications.", operation);
647
+ }
648
+ function parseWorldNotificationResult(value, operation) {
649
+ let result;
650
+ try {
651
+ result = JSON.parse(value);
652
+ }
653
+ catch {
654
+ throw invalidWorldNotificationResponse(operation);
655
+ }
656
+ if (!isRecord(result))
657
+ throw invalidWorldNotificationResponse(operation);
658
+ return result;
659
+ }
660
+ function parseWorldNotificationCount(value, operation) {
661
+ if (!Number.isSafeInteger(value) || value < 0) {
662
+ throw invalidWorldNotificationResponse(operation);
663
+ }
664
+ return value;
665
+ }
666
+ function invalidWorldNotificationResponse(operation) {
667
+ return new TypeError(`${operation}: The platform returned an invalid response.`);
668
+ }
669
+ function normalizeWorldJournalAppendEntry(value, index, operation) {
670
+ const field = `entries[${index}]`;
671
+ assertOnlyKeys(value, ["kind", "disclosure", "participantIds", "data"], operation, field);
672
+ const entry = value;
673
+ if (typeof entry.kind !== "string" ||
674
+ entry.kind.length < 1 ||
675
+ entry.kind.length > WORLD_JOURNAL_MAX_KIND_CHARACTERS ||
676
+ !SAFE_WORLD_JOURNAL_KIND.test(entry.kind)) {
677
+ throw worldJournalArgumentError(`${field}.kind must be a safe key of at most ${WORLD_JOURNAL_MAX_KIND_CHARACTERS} characters.`, operation);
678
+ }
679
+ if (entry.disclosure !== "world" && entry.disclosure !== "participants") {
680
+ throw worldJournalArgumentError(`${field}.disclosure must be "world" or "participants".`, operation);
681
+ }
682
+ let participantIds;
683
+ if (entry.disclosure === "participants") {
684
+ participantIds = normalizeParticipantIds(entry.participantIds, WORLD_JOURNAL_MAX_PARTICIPANTS_PER_ENTRY, `${field}.participantIds`, operation);
685
+ }
686
+ else if (Object.prototype.hasOwnProperty.call(entry, "participantIds")) {
687
+ throw worldJournalArgumentError(`${field}.participantIds must be absent when disclosure is "world".`, operation);
688
+ }
689
+ let data;
690
+ if (Object.prototype.hasOwnProperty.call(entry, "data")) {
691
+ data = normalizeWorldJournalData(entry.data, field, operation);
692
+ }
693
+ return Object.freeze({
694
+ kind: entry.kind,
695
+ disclosure: entry.disclosure,
696
+ ...(participantIds === undefined ? {} : { participantIds }),
697
+ ...(data === undefined ? {} : { data }),
698
+ });
699
+ }
700
+ function normalizeWorldJournalData(value, field, operation) {
701
+ let encoded;
702
+ try {
703
+ encoded = encodeStorageValue(value, operation);
704
+ }
705
+ catch {
706
+ throw worldJournalArgumentError(`${field}.data must be JSON.`, operation);
707
+ }
708
+ const normalized = canonicalizeJson(JSON.parse(encoded));
709
+ assertWorldJournalDataText(normalized, `${field}.data`, operation);
710
+ if (utf8Length(JSON.stringify(normalized)) > WORLD_JOURNAL_MAX_DATA_BYTES) {
711
+ throw worldJournalArgumentError(`${field}.data may be at most ${WORLD_JOURNAL_MAX_DATA_BYTES} bytes when serialized.`, operation);
712
+ }
713
+ return normalized;
714
+ }
715
+ function assertWorldJournalDataText(value, field, operation) {
716
+ if (typeof value === "string") {
717
+ if (value.includes("\0") || hasUnpairedSurrogate(value)) {
718
+ throw worldJournalArgumentError(`${field} must contain valid text.`, operation);
719
+ }
720
+ return;
721
+ }
722
+ if (Array.isArray(value)) {
723
+ value.forEach((item, index) => assertWorldJournalDataText(item, `${field}[${index}]`, operation));
724
+ return;
725
+ }
726
+ if (value !== null && typeof value === "object") {
727
+ for (const [key, item] of Object.entries(value)) {
728
+ if (key.includes("\0") || hasUnpairedSurrogate(key)) {
729
+ throw worldJournalArgumentError(`${field} must contain valid text.`, operation);
730
+ }
731
+ assertWorldJournalDataText(item, `${field}.${key}`, operation);
732
+ }
733
+ }
734
+ }
735
+ function canonicalizeJson(value) {
736
+ if (Array.isArray(value))
737
+ return value.map(canonicalizeJson);
738
+ if (value !== null && typeof value === "object") {
739
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalizeJson(value[key])]));
740
+ }
741
+ return value;
742
+ }
743
+ function normalizeParticipantIds(value, max, field, operation) {
744
+ if (!Array.isArray(value) || value.length < 1 || value.length > max) {
745
+ throw worldJournalArgumentError(`${field} must contain from 1 through ${max} ids.`, operation);
746
+ }
747
+ const ids = [...new Set(value.map((id, index) => assertWorldParticipantId(id, `${field}[${index}]`, operation)))].sort();
748
+ if (ids.length > max) {
749
+ throw worldJournalArgumentError(`${field} must contain from 1 through ${max} ids.`, operation);
750
+ }
751
+ return Object.freeze(ids);
752
+ }
753
+ function assertWorldParticipantId(value, field, operation) {
754
+ if (typeof value !== "string" || value.length === 0 ||
755
+ value.includes("\0") || hasUnpairedSurrogate(value) ||
756
+ utf8Length(value) > WORLD_JOURNAL_MAX_PARTICIPANT_BYTES) {
757
+ throw worldJournalArgumentError(`${field} must be valid non-empty text of at most ${WORLD_JOURNAL_MAX_PARTICIPANT_BYTES} bytes.`, operation);
758
+ }
759
+ return value;
760
+ }
761
+ function assertWorldJournalOperationId(value, operation) {
762
+ if (typeof value !== "string" ||
763
+ value.length < 1 ||
764
+ value.length > WORLD_OPERATION_ID_MAX_CHARACTERS ||
765
+ value.includes("\0") ||
766
+ hasUnpairedSurrogate(value) ||
767
+ utf8Length(value) > WORLD_OPERATION_ID_MAX_BYTES) {
768
+ throw worldJournalArgumentError(`operationId must be valid text of at most ${WORLD_OPERATION_ID_MAX_CHARACTERS} characters and ${WORLD_OPERATION_ID_MAX_BYTES} bytes.`, operation);
769
+ }
770
+ return value;
771
+ }
772
+ function assertWorldJournalSequence(value, operation, field, positive = false) {
773
+ if (!isWorldJournalSequence(value, positive)) {
774
+ throw worldJournalArgumentError(`${field} must be a canonical decimal string no greater than ${WORLD_JOURNAL_MAX_SEQUENCE}.`, operation);
775
+ }
776
+ return value;
777
+ }
778
+ function assertBoundedInteger(value, min, max, field, operation) {
779
+ if (!Number.isSafeInteger(value) || value < min || value > max) {
780
+ throw worldJournalArgumentError(`${field} must be an integer from ${min} through ${max}.`, operation);
781
+ }
782
+ return value;
783
+ }
784
+ async function callWorldJournalStorage(platformHandle, op, args, operation) {
785
+ if (typeof platformHandle.storage !== "function" || platformHandle.storageEnabled === false) {
786
+ throw worldJournalUnavailable(operation);
787
+ }
788
+ try {
789
+ return await platformHandle.storage(op, JSON.stringify(args));
790
+ }
791
+ catch (error) {
792
+ if (isUnknownStorageOperation(error))
793
+ throw worldJournalUnavailable(operation);
794
+ throw error;
795
+ }
796
+ }
797
+ function isUnknownStorageOperation(error) {
798
+ if (!isRecord(error) ||
799
+ (error.code !== "CAULDRON_STORAGE_INVALID_ARGUMENT" &&
800
+ error.code !== "CAULDRON_STORAGE_BAD_REQUEST"))
801
+ return false;
802
+ const message = error.message;
803
+ return typeof message === "string" && /unknown (?:storage )?operation/i.test(message);
804
+ }
805
+ function worldJournalUnavailable(operation) {
806
+ return storageError("CAULDRON_WORLD_JOURNAL_UNAVAILABLE", "This Castle host does not support persistent-world journals.", operation);
807
+ }
808
+ function worldJournalArgumentError(message, operation) {
809
+ return storageError("INVALID_ARGUMENT", message, operation);
810
+ }
811
+ function parseWorldJournalJson(value, operation) {
812
+ try {
813
+ return JSON.parse(value);
814
+ }
815
+ catch {
816
+ throw invalidWorldJournalResponse(operation);
817
+ }
818
+ }
819
+ function invalidWorldJournalResponse(operation) {
820
+ return new TypeError(`${operation}: The platform returned an invalid response.`);
821
+ }
822
+ function parseWorldJournalEntry(value, operation) {
823
+ if (!isRecord(value) ||
824
+ (value.disclosure !== "world" && value.disclosure !== "participants") ||
825
+ !Array.isArray(value.participantIds) ||
826
+ typeof value.kind !== "string" ||
827
+ typeof value.createdAt !== "string") {
828
+ throw invalidWorldJournalResponse(operation);
829
+ }
830
+ const participantIds = value.participantIds.map((id) => {
831
+ if (typeof id !== "string")
832
+ throw invalidWorldJournalResponse(operation);
833
+ return id;
834
+ });
835
+ if ((value.disclosure === "world" && participantIds.length !== 0) ||
836
+ (value.disclosure === "participants" && participantIds.length < 1)) {
837
+ throw invalidWorldJournalResponse(operation);
838
+ }
839
+ let data;
840
+ try {
841
+ data = JSON.parse(encodeStorageValue(value.data, operation));
842
+ }
843
+ catch {
844
+ throw invalidWorldJournalResponse(operation);
845
+ }
846
+ return Object.freeze({
847
+ seq: parseWorldJournalSequence(value.seq, operation, true),
848
+ kind: value.kind,
849
+ disclosure: value.disclosure,
850
+ participantIds: Object.freeze(participantIds),
851
+ data,
852
+ createdAt: value.createdAt,
853
+ });
854
+ }
855
+ function parseWorldJournalSequence(value, operation, positive = false) {
856
+ if (!isWorldJournalSequence(value, positive)) {
857
+ throw invalidWorldJournalResponse(operation);
858
+ }
859
+ return value;
860
+ }
861
+ function isWorldJournalSequence(value, positive) {
862
+ if (typeof value !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(value))
863
+ return false;
864
+ if (positive && value === "0")
865
+ return false;
866
+ return value.length < WORLD_JOURNAL_MAX_SEQUENCE.length ||
867
+ (value.length === WORLD_JOURNAL_MAX_SEQUENCE.length &&
868
+ value <= WORLD_JOURNAL_MAX_SEQUENCE);
869
+ }
870
+ function parseWorldParticipant(value, operation) {
871
+ if (!isRecord(value) || typeof value.participantId !== "string" ||
872
+ typeof value.firstSeenAt !== "string" || typeof value.lastSeenAt !== "string" ||
873
+ (value.lastLeftAt !== null && typeof value.lastLeftAt !== "string") ||
874
+ !Number.isSafeInteger(value.visitCount) || value.visitCount < 0) {
875
+ throw invalidWorldJournalResponse(operation);
876
+ }
877
+ return Object.freeze({
878
+ participantId: value.participantId,
879
+ firstSeenAt: value.firstSeenAt,
880
+ lastSeenAt: value.lastSeenAt,
881
+ lastLeftAt: value.lastLeftAt,
882
+ visitCount: value.visitCount,
883
+ });
884
+ }
885
+ function assertOnlyKeys(value, allowed, operation, field) {
886
+ if (!isRecord(value) || Object.keys(value).some((key) => !allowed.includes(key))) {
887
+ throw worldJournalArgumentError(`${field} contains an unsupported field.`, operation);
888
+ }
889
+ }
890
+ function isRecord(value) {
891
+ return value !== null && typeof value === "object" && !Array.isArray(value);
892
+ }
893
+ function hasUnpairedSurrogate(value) {
894
+ for (let index = 0; index < value.length; index += 1) {
895
+ const code = value.charCodeAt(index);
896
+ if (code >= 0xd800 && code <= 0xdbff) {
897
+ const next = value.charCodeAt(index + 1);
898
+ if (!(next >= 0xdc00 && next <= 0xdfff))
899
+ return true;
900
+ index += 1;
901
+ }
902
+ else if (code >= 0xdc00 && code <= 0xdfff) {
903
+ return true;
904
+ }
905
+ }
906
+ return false;
907
+ }
908
+ function utf8Length(value) {
909
+ return new TextEncoder().encode(value).byteLength;
910
+ }
291
911
  function createServerWorldCharacters(platformHandle) {
292
912
  return Object.freeze({
293
913
  async create(input) {
@@ -638,14 +1258,20 @@ function unsupportedBinaryRuntime() {
638
1258
  throw new TypeError("This Castle runtime does not support binary multiplayer messages yet.");
639
1259
  }
640
1260
  function joinedPlayer(connId, identity) {
641
- if (typeof connId === "string")
642
- return { ...identity, playerId: connId };
1261
+ if (typeof connId === "string") {
1262
+ return {
1263
+ ...identity,
1264
+ playerId: connId,
1265
+ participantId: identity.scopedUserId ?? identity.userId,
1266
+ };
1267
+ }
643
1268
  const legacy = connId;
644
1269
  return {
645
1270
  playerId: legacy.playerId,
646
1271
  userId: legacy.userId,
647
1272
  username: legacy.username,
648
1273
  isAnonymous: legacy.isAnonymous,
1274
+ participantId: legacy.scopedUserId ?? legacy.userId,
649
1275
  ...(legacy.scopedUserId ? { scopedUserId: legacy.scopedUserId } : {}),
650
1276
  };
651
1277
  }