@fragment-dev/cli 2026.11.12 → 2026.11.13-10

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 (87) hide show
  1. package/README.md +43 -1
  2. package/dist/{chunk-6H5VEWMH.js → chunk-2EMLJCCB.js} +1 -1
  3. package/dist/{chunk-V3LLFTBC.js → chunk-2YTWJRNP.js} +1 -1
  4. package/dist/{chunk-JTGVX5GX.js → chunk-4AUNUT7Z.js} +52 -9
  5. package/dist/{chunk-D46OZVDM.js → chunk-4EBR67QU.js} +2 -2
  6. package/dist/{chunk-CTS34CX4.js → chunk-4GSTQ6O4.js} +2 -2
  7. package/dist/{chunk-UYGNB7UR.js → chunk-4KJOZZJJ.js} +1 -1
  8. package/dist/{chunk-5F2PJ2LT.js → chunk-57YVQI74.js} +2 -2
  9. package/dist/{chunk-RHL6MOZS.js → chunk-5Q5FY4NG.js} +3 -3
  10. package/dist/{chunk-6MYCJAJL.js → chunk-67N5LE4N.js} +2 -2
  11. package/dist/{chunk-3ZBETKSW.js → chunk-6T66IJCY.js} +5 -0
  12. package/dist/{chunk-ECRNMUZY.js → chunk-AEIRSM6M.js} +1 -1
  13. package/dist/{chunk-IGBICJSY.js → chunk-B7254H5E.js} +1 -1
  14. package/dist/{chunk-R266LOJY.js → chunk-E72FRPF4.js} +15 -3
  15. package/dist/{chunk-S6EUZBEH.js → chunk-FMDJEY4R.js} +1 -1
  16. package/dist/{chunk-NHBFVBGA.js → chunk-G5CBWM5A.js} +3 -3
  17. package/dist/{chunk-WABMYMTO.js → chunk-GR3GGYJY.js} +2 -2
  18. package/dist/{chunk-VETXOSAQ.js → chunk-HGJQFG33.js} +2 -2
  19. package/dist/{chunk-D47P74VC.js → chunk-HHNGQYZB.js} +27 -27
  20. package/dist/{chunk-GJZISVDV.js → chunk-IWY22QAC.js} +2 -2
  21. package/dist/{chunk-DNAQPTVA.js → chunk-JVDAMJZJ.js} +2205 -2184
  22. package/dist/{chunk-77SONGBG.js → chunk-K2KHRNPV.js} +13 -4
  23. package/dist/{chunk-DFBITJLK.js → chunk-LGWOBHUY.js} +1 -1
  24. package/dist/{chunk-ZYFQDN2K.js → chunk-MB3FR4WL.js} +28 -4
  25. package/dist/{chunk-PBOTSYWN.js → chunk-MHNH7UHD.js} +1 -1
  26. package/dist/chunk-NEW2NRYM.js +46 -0
  27. package/dist/{chunk-AY5LBONU.js → chunk-PYG6AFYU.js} +2 -2
  28. package/dist/{chunk-EUEC2RGK.js → chunk-QZ6NUJB5.js} +2 -2
  29. package/dist/{chunk-6QJ3ZC6M.js → chunk-RG4CN74T.js} +225 -8
  30. package/dist/{chunk-OPMMPSLX.js → chunk-RQFQK7WV.js} +2 -2
  31. package/dist/{chunk-5WAZAXOW.js → chunk-SACWMZFU.js} +2 -2
  32. package/dist/{chunk-HII7DWWZ.js → chunk-SL4IWVLO.js} +2 -2
  33. package/dist/{chunk-EO6QNP4N.js → chunk-VEM4AZAI.js} +3 -3
  34. package/dist/{chunk-GNPKIMSW.js → chunk-VN2DVYGG.js} +3 -3
  35. package/dist/{chunk-H2RK3NKQ.js → chunk-VXYOFJKR.js} +2 -2
  36. package/dist/{chunk-IUDVJMWC.js → chunk-VY7NFMES.js} +2 -2
  37. package/dist/{chunk-DYLKAHKE.js → chunk-WAU6SFQ5.js} +7 -1
  38. package/dist/{chunk-35PT2VZ6.js → chunk-WQQ3DSJH.js} +2 -2
  39. package/dist/{chunk-77TG73N3.js → chunk-XJS4FFUC.js} +2 -2
  40. package/dist/{chunk-PWOJYW62.js → chunk-XTEERZ7T.js} +2 -2
  41. package/dist/{chunk-Q2E43BUP.js → chunk-YV6J4BRT.js} +3 -3
  42. package/dist/{chunk-G3IDF3GN.js → chunk-YWITUQIX.js} +1 -1
  43. package/dist/{chunk-SLD5GAXB.js → chunk-Z5SFM3A5.js} +1 -1
  44. package/dist/{chunk-CI336LA7.js → chunk-ZPU5TX3B.js} +1 -1
  45. package/dist/commands/add-ledger-entry.js +6 -5
  46. package/dist/commands/api-client/create.js +4 -3
  47. package/dist/commands/create-custom-link.js +6 -5
  48. package/dist/commands/create-ledger.js +6 -5
  49. package/dist/commands/delete-custom-txs.js +6 -5
  50. package/dist/commands/delete-ledger.js +6 -5
  51. package/dist/commands/delete-schema.js +6 -5
  52. package/dist/commands/gen-graphql.js +7 -6
  53. package/dist/commands/get-schema.js +7 -6
  54. package/dist/commands/init.js +4 -3
  55. package/dist/commands/login.js +5 -4
  56. package/dist/commands/migrate-ledger-entry.js +6 -5
  57. package/dist/commands/print-schema.js +8 -7
  58. package/dist/commands/query/ledgerAccounts.js +6 -5
  59. package/dist/commands/query/ledgers.js +6 -5
  60. package/dist/commands/query/schema.js +6 -5
  61. package/dist/commands/query/schemas.js +6 -5
  62. package/dist/commands/reverse-ledger-entry.js +6 -5
  63. package/dist/commands/simulate-scenario.js +8 -7
  64. package/dist/commands/start.js +4 -3
  65. package/dist/commands/store-schema.js +6 -5
  66. package/dist/commands/token.js +6 -5
  67. package/dist/commands/update-ledger-account.js +6 -5
  68. package/dist/commands/update.js +5 -4
  69. package/dist/commands/verify-schema.js +8 -7
  70. package/dist/commands/version.js +4 -3
  71. package/dist/commands/workspace.js +6 -5
  72. package/dist/commands.js +43 -42
  73. package/dist/graphql.js +2 -2
  74. package/dist/index.js +43 -42
  75. package/dist/lib/authenticatedCommand.js +5 -4
  76. package/dist/lib/baseCommand.js +3 -2
  77. package/dist/lib/curl.js +13 -0
  78. package/dist/lib/sdk.js +1 -1
  79. package/dist/lib/version.js +2 -1
  80. package/dist/utils/formatChartOfAccounts.js +3 -3
  81. package/dist/utils/formatEntries.js +3 -3
  82. package/dist/utils/formatScenarioAccountBalances.js +3 -3
  83. package/dist/utils/formatScenarioBalances.js +4 -4
  84. package/dist/utils/schemaBackCompat.js +4 -4
  85. package/dist/utils/schemaValidation.js +3 -3
  86. package/oclif.manifest.json +2 -2
  87. package/package.json +1 -1
@@ -7,7 +7,7 @@ import {
7
7
  generateSimulatingEntry,
8
8
  lil_id_default,
9
9
  makeLineKey
10
- } from "./chunk-UYGNB7UR.js";
10
+ } from "./chunk-4KJOZZJJ.js";
11
11
  import {
12
12
  formatBalance,
13
13
  getBalancePrecision
@@ -33,14 +33,15 @@ import {
33
33
  validateLedgerConsistencySettings,
34
34
  validatePaymentEntry,
35
35
  z as z2
36
- } from "./chunk-6QJ3ZC6M.js";
36
+ } from "./chunk-RG4CN74T.js";
37
37
  import {
38
38
  BaseSchema,
39
39
  PaymentAccountingEventKey,
40
+ SCENE_PAYMENT_ACCOUNTING_EVENT_KEYS,
40
41
  SystemLineParameterName,
41
42
  fillParams,
42
43
  getSchemaObjectParameters
43
- } from "./chunk-JTGVX5GX.js";
44
+ } from "./chunk-4AUNUT7Z.js";
44
45
  import {
45
46
  InternalError,
46
47
  assert_default
@@ -407,1908 +408,882 @@ var validateAndTransformEntryVersion = ({
407
408
 
408
409
  // ../../libs/liveblocks-commands/src/utils/paymentTypeValidation.ts
409
410
  init_cjs_shims();
410
- var convertLiveLine = (line) => ({
411
- key: line.key,
412
- account: line.account ? { path: line.account.path } : void 0,
413
- amount: line.amount ?? "",
414
- currency: line.currency ? {
415
- code: line.currency.code,
416
- customCurrencyId: line.currency.customCurrencyId
417
- } : void 0,
418
- description: line.description,
419
- system: line.system
420
- });
421
- var convertLiveEntry = (entry) => ({
422
- description: entry.description,
423
- lines: Array.from(entry.linesOrder.values()).map((lineId) => entry.lines.get(lineId)).filter((line) => line !== void 0).map(convertLiveLine)
424
- });
425
- var validateLivePaymentEntry = ({
426
- entryVersion,
427
- event,
428
- entryIdentity,
429
- accountPathToAccount
430
- }) => validatePaymentEntry({
431
- entry: convertLiveEntry(entryVersion),
432
- event,
433
- entryIdentity,
434
- accountPathToAccount,
435
- paymentAccountPath: findPaymentAccountPath(accountPathToAccount)
436
- });
437
411
 
438
- // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
412
+ // ../../libs/liveblocks-commands/src/utils/makeLivePaymentDetails.ts
439
413
  init_cjs_shims();
440
414
 
441
- // ../../libs/payment-commands/utils/amount.ts
415
+ // ../../node_modules/@liveblocks/client/dist/index.js
442
416
  init_cjs_shims();
443
417
 
444
- // ../../libs/types/payment.ts
418
+ // ../../node_modules/@liveblocks/core/dist/index.js
445
419
  init_cjs_shims();
446
- var MIN_PAYMENT_AMOUNT_CENTS = 100n;
447
- var MAX_PAYMENT_AMOUNT_CENTS = 10000000n;
448
- var formatUsd = (cents) => `$${(cents / 100n).toLocaleString("en-US")}.${(cents % 100n).toString().padStart(2, "0")}`;
449
- var PAYMENT_AMOUNT_RANGE_MESSAGE = `Amount must be between ${formatUsd(
450
- MIN_PAYMENT_AMOUNT_CENTS
451
- )} and ${formatUsd(MAX_PAYMENT_AMOUNT_CENTS)}`;
452
- var PaymentMode = /* @__PURE__ */ ((PaymentMode2) => {
453
- PaymentMode2["sandbox"] = "sandbox";
454
- PaymentMode2["glassbox"] = "glassbox";
455
- return PaymentMode2;
456
- })(PaymentMode || {});
457
- var PaymentModeSchema = z.nativeEnum(PaymentMode);
458
- var ApiPaymentMode = /* @__PURE__ */ ((ApiPaymentMode2) => {
459
- ApiPaymentMode2["sandbox"] = "sandbox";
460
- ApiPaymentMode2["production"] = "production";
461
- return ApiPaymentMode2;
462
- })(ApiPaymentMode || {});
463
- var ApiPaymentModeSchema = z.nativeEnum(ApiPaymentMode);
464
- var PaymentPersistenceEvent = {
465
- /** The Payment was created. */
466
- created: "created",
467
- /** The payer went through checkout; posted when the Payment enters `processing`. */
468
- checkout: "checkout",
469
- /** The Customer retried the Payment on a saved payment method; posted when the Payment enters `processing`. */
470
- retry: "retry",
471
- /** The card network captured the payment; it is guaranteed to settle. */
472
- card_captured: "card_captured",
473
- /** Stripe declined an attempt, or refused to create a PaymentIntent for it. */
474
- card_declined: "card_declined",
475
- /** The payer abandoned or failed an attempt's 3DS challenge. */
476
- card_3ds_canceled: "card_3ds_canceled",
477
- /** The payment was settled. */
478
- settled: "settled",
479
- /** A Fragment Payment refund record was created. */
480
- refund_initiated: "refund_initiated",
481
- /** A Fragment Payment refund cleared its in-transit account. */
482
- refund_settled: "refund_settled",
483
- /** Stripe declined a Fragment Payment refund. */
484
- refund_failed: "refund_failed"
485
- };
486
- var PaymentPersistenceEventSchema = z.nativeEnum(
487
- PaymentPersistenceEvent
488
- );
489
- var InternalPaymentAttemptStatus = {
490
- /** Payment attempt not yet sent to Stripe. */
491
- created: "created",
492
- /** Payment attempt has been sent to Stripe and is being processed. */
493
- processing: "processing",
494
- /** Payment attempt has been accepted. */
495
- accepted: "accepted",
496
- /** Payment attempt has been declined. */
497
- declined: "declined",
498
- /** Stripe refused to create a PaymentIntent for the attempt. */
499
- rejected: "rejected",
500
- /** The payer abandoned or failed the attempt's 3DS challenge. */
501
- canceled: "canceled",
502
- /** Payment attempt needs action from the payer. No stored shape yet. */
503
- needs_action: "needs_action"
504
- };
505
- var EXTERNAL_PAYMENT_ATTEMPT_STATUSES = {
506
- [InternalPaymentAttemptStatus.created]: "processing" /* processing */,
507
- [InternalPaymentAttemptStatus.processing]: "processing" /* processing */,
508
- [InternalPaymentAttemptStatus.needs_action]: "processing" /* processing */,
509
- [InternalPaymentAttemptStatus.accepted]: "succeeded" /* succeeded */,
510
- [InternalPaymentAttemptStatus.declined]: "failed" /* failed */,
511
- [InternalPaymentAttemptStatus.rejected]: "failed" /* failed */,
512
- [InternalPaymentAttemptStatus.canceled]: "failed" /* failed */
420
+ var __defProp = Object.defineProperty;
421
+ var __export = (target, all) => {
422
+ for (var name in all)
423
+ __defProp(target, name, { get: all[name], enumerable: true });
513
424
  };
514
- var paymentCurrencyCodes = [
515
- "USD"
516
- ];
517
- var PaymentCurrencyCodeSchema = z.enum(paymentCurrencyCodes);
518
- var ExternalAccountMatchInput = z.object({
519
- id: ParameterizedString.optional(),
520
- /** The External systems's ID of the account */
521
- externalId: ParameterizedString.optional(),
522
- /** The Fragment ID of the link */
523
- linkId: ParameterizedString.optional()
524
- });
525
-
526
- // ../../libs/payment-commands/utils/amount.ts
527
- var MAX_AMOUNT_CENTS = 2n ** 46n * 100n;
528
- var DEFAULT_FRAGMENT_FEE_SCHEDULE = {
529
- ["card_payin" /* card_payin */]: {
530
- rateBps: 290n,
531
- fixedCents: 30n
425
+ var PKG_NAME = "@liveblocks/core";
426
+ var PKG_VERSION = "3.7.1";
427
+ var PKG_FORMAT = "esm";
428
+ var g = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
429
+ var crossLinkedDocs = "https://liveblocks.io/docs/errors/cross-linked";
430
+ var dupesDocs = "https://liveblocks.io/docs/errors/dupes";
431
+ var SPACE = " ";
432
+ function error(msg) {
433
+ if (process.env.NODE_ENV === "production") {
434
+ console.error(msg);
435
+ } else {
436
+ throw new Error(msg);
532
437
  }
533
- };
534
- var BPS_DENOMINATOR = 10000n;
535
- var calculateFragmentFeeCents = ({
536
- settledCents,
537
- schedule
538
- }) => {
539
- assert_default(settledCents >= 0n, InternalError, {
540
- info: { settledCents },
541
- message: `Expected a non-negative settled amount, got ${settledCents}`
542
- });
543
- return schedule.fixedCents + (settledCents * schedule.rateBps + BPS_DENOMINATOR / 2n) / BPS_DENOMINATOR;
544
- };
545
- var IntegerAmountSchema = z.string().regex(/^-?\d+$/).transform(BigInt);
546
-
547
- // ../../libs/shared-utils/parameterization.ts
548
- init_cjs_shims();
549
-
550
- // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
551
- var SCENARIO_FRAGMENT_FEE_PERCENT = Number(DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].rateBps) / 100;
552
- var SCENARIO_FRAGMENT_FEE_FIXED_CENTS = Number(
553
- DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].fixedCents
554
- );
555
- var evaluatePaymentAmount = (expression, parameters) => {
556
- const filled = fillParams(expression, parameters, {
557
- allowMissing: true,
558
- allowMissingInChildren: true
559
- }).trim();
560
- try {
561
- return { kind: "amount", amount: evaluateExpression(filled) };
562
- } catch {
563
- return { kind: "unevaluated", expression };
438
+ }
439
+ function detectDupes(pkgName, pkgVersion, pkgFormat) {
440
+ const pkgId = Symbol.for(pkgName);
441
+ const pkgBuildInfo = pkgFormat ? `${pkgVersion || "dev"} (${pkgFormat})` : pkgVersion || "dev";
442
+ if (!g[pkgId]) {
443
+ g[pkgId] = pkgBuildInfo;
444
+ } else if (g[pkgId] === pkgBuildInfo) {
445
+ } else {
446
+ const msg = [
447
+ `Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See ${dupesDocs + SPACE}`,
448
+ "",
449
+ "Conflicts:",
450
+ `- ${pkgName} ${g[pkgId]} (already loaded)`,
451
+ `- ${pkgName} ${pkgBuildInfo} (trying to load this now)`
452
+ ].join("\n");
453
+ error(msg);
454
+ }
455
+ if (pkgVersion && PKG_VERSION && pkgVersion !== PKG_VERSION) {
456
+ error(
457
+ [
458
+ `Cross-linked versions of Liveblocks found, which will cause issues! See ${crossLinkedDocs + SPACE}`,
459
+ "",
460
+ "Conflicts:",
461
+ `- ${PKG_NAME} is at ${PKG_VERSION}`,
462
+ `- ${pkgName} is at ${pkgVersion}`,
463
+ "",
464
+ "Always upgrade all Liveblocks packages to the same version number."
465
+ ].join("\n")
466
+ );
467
+ }
468
+ }
469
+ function makeEventSource() {
470
+ const _observers = /* @__PURE__ */ new Set();
471
+ function subscribe(callback) {
472
+ _observers.add(callback);
473
+ return () => _observers.delete(callback);
474
+ }
475
+ function subscribeOnce(callback) {
476
+ const unsub = subscribe((event) => {
477
+ unsub();
478
+ return callback(event);
479
+ });
480
+ return unsub;
481
+ }
482
+ async function waitUntil(predicate) {
483
+ let unsub;
484
+ return new Promise((res) => {
485
+ unsub = subscribe((event) => {
486
+ if (predicate === void 0 || predicate(event)) {
487
+ res(event);
488
+ }
489
+ });
490
+ }).finally(() => unsub?.());
491
+ }
492
+ function notify(event) {
493
+ let called = false;
494
+ for (const callback of _observers) {
495
+ callback(event);
496
+ called = true;
497
+ }
498
+ return called;
499
+ }
500
+ function count() {
501
+ return _observers.size;
564
502
  }
565
- };
566
- var computeScenarioFee = (amount) => {
567
- const fee = calculateFragmentFeeCents({
568
- settledCents: amount < 0n ? -amount : amount,
569
- schedule: DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */]
570
- });
571
- return amount < 0n ? -fee : fee;
572
- };
573
-
574
- // ../../libs/liveblocks-commands/src/utils/sceneEventResolution.ts
575
- var PAYMENT_GONE_FROM_SCENARIO_REASON = "This payment is no longer in the scenario. Remove this row.";
576
- var PAYMENT_GONE_FROM_SCHEMA_REASON = "This payment is no longer in the schema. Remove this row.";
577
- var SETTLED_BEFORE_APPROVAL_REASON = "This payment settles before it is approved \u2014 move the settled row after its approved row.";
578
- var SETTLED_WITHOUT_APPROVAL_REASON = "This payment settles without being approved \u2014 its approved row is missing. Delete the settled row and re-add the payment.";
579
- var makeUnevaluatedAmountReason = (expression) => `Payment amount '${expression}' did not evaluate to a whole number. Check the parameters it references.`;
580
- var getLedgerSceneEventEntryId = (event) => ({
581
- flavor: "ledger",
582
- entryTypeId: event.entry.entryTypeId ?? "",
583
- entryTypeVersionId: event.entry.entryTypeVersionId ?? ""
584
- });
585
- var getPaymentVersionContext = (paymentTypes, payment) => {
586
- const paymentType = paymentTypes?.types.get(payment.paymentTypeId);
587
- const version = paymentType?.versions.get(payment.paymentTypeVersionId);
588
- if (!paymentType || !version)
589
- return null;
590
503
  return {
591
- paymentType: paymentType.type,
592
- amountExpression: version.payment.amount,
593
- lifecycleEvents: Object.values(PaymentAccountingEventKey).filter(
594
- (event) => getPaymentEntryFromVersion(version, event) !== null
595
- )
504
+ // Private/internal control over event emission
505
+ notify,
506
+ subscribe,
507
+ subscribeOnce,
508
+ count,
509
+ waitUntil,
510
+ dispose() {
511
+ _observers.clear();
512
+ },
513
+ // Publicly exposable subscription API
514
+ observable: {
515
+ subscribe,
516
+ subscribeOnce,
517
+ waitUntil
518
+ }
596
519
  };
597
- };
598
- var withSystemParameters = (parameters, amountExpression, event) => {
599
- const evaluated = evaluatePaymentAmount(amountExpression, parameters);
600
- if (evaluated.kind !== "amount")
601
- return null;
602
- const amount = evaluated.amount.toString();
603
- const systemParameters = z2(event).with(PaymentAccountingEventKey.initiated, () => ({})).with(PaymentAccountingEventKey.settled, () => ({
604
- [SystemLineParameterName.payment_settlement_line]: amount,
605
- [SystemLineParameterName.payment_fee_line]: computeScenarioFee(
606
- evaluated.amount
607
- ).toString()
608
- })).with(
609
- PaymentAccountingEventKey.refund_initiated,
610
- PaymentAccountingEventKey.refund_failed,
611
- () => ({
612
- [SystemLineParameterName.payment_refund_line]: amount
613
- })
614
- ).exhaustive();
615
- return { ...parameters, ...systemParameters };
616
- };
617
- var getPaymentLifecycleFailure = ({
618
- lifecycleEvents,
619
- eventIndexByEvent
620
- }) => {
621
- const lifecycleSteps = lifecycleEvents.slice(1).map((event2, position) => {
622
- const previousEvent2 = lifecycleEvents[position];
623
- return {
624
- event: event2,
625
- previousEvent: previousEvent2,
626
- eventRowIndex: eventIndexByEvent.get(event2),
627
- previousEventRowIndex: eventIndexByEvent.get(previousEvent2)
628
- };
520
+ }
521
+ var freeze = process.env.NODE_ENV === "production" ? (
522
+ /* istanbul ignore next */
523
+ (x) => x
524
+ ) : Object.freeze;
525
+ function raise(msg) {
526
+ throw new Error(msg);
527
+ }
528
+ function deepClone(value) {
529
+ return JSON.parse(JSON.stringify(value));
530
+ }
531
+ function compactObject(obj) {
532
+ const newObj = { ...obj };
533
+ Object.keys(obj).forEach((k) => {
534
+ const key = k;
535
+ if (newObj[key] === void 0) {
536
+ delete newObj[key];
537
+ }
629
538
  });
630
- const invalidStep = lifecycleSteps.find(
631
- ({ eventRowIndex, previousEventRowIndex: previousEventRowIndex2 }) => eventRowIndex !== void 0 && (previousEventRowIndex2 === void 0 || previousEventRowIndex2 > eventRowIndex)
632
- );
633
- if (!invalidStep)
634
- return void 0;
635
- const { event, previousEvent, previousEventRowIndex } = invalidStep;
636
- if (event === PaymentAccountingEventKey.settled && previousEvent === PaymentAccountingEventKey.initiated) {
637
- return previousEventRowIndex === void 0 ? SETTLED_WITHOUT_APPROVAL_REASON : SETTLED_BEFORE_APPROVAL_REASON;
539
+ return newObj;
540
+ }
541
+ var kSinks = Symbol("kSinks");
542
+ var kTrigger = Symbol("kTrigger");
543
+ var signalsToTrigger = null;
544
+ var trackedReads = null;
545
+ function enqueueTrigger(signal) {
546
+ if (!signalsToTrigger)
547
+ raise("Expected to be in an active batch");
548
+ signalsToTrigger.add(signal);
549
+ }
550
+ var AbstractSignal = class {
551
+ /** @internal */
552
+ equals;
553
+ #eventSource;
554
+ /** @internal */
555
+ [kSinks];
556
+ constructor(equals) {
557
+ this.equals = equals ?? Object.is;
558
+ this.#eventSource = makeEventSource();
559
+ this[kSinks] = /* @__PURE__ */ new Set();
560
+ this.get = this.get.bind(this);
561
+ this.subscribe = this.subscribe.bind(this);
562
+ this.subscribeOnce = this.subscribeOnce.bind(this);
638
563
  }
639
- return previousEventRowIndex === void 0 ? `This ${event} row has no preceding ${previousEvent} row. Delete the ${event} row and re-add the payment.` : `This ${event} row occurs before its ${previousEvent} row. Move the ${event} row after its ${previousEvent} row.`;
640
- };
641
- var findInvalidPaymentEvents = (orderedEvents, lifecycleEventsByPaymentId) => {
642
- const eventIndexesByPaymentId = /* @__PURE__ */ new Map();
643
- orderedEvents.forEach((event, index) => {
644
- if (event.eventType !== "payment-entry")
645
- return;
646
- const eventIndexByEvent = eventIndexesByPaymentId.get(event.entry.paymentId) ?? /* @__PURE__ */ new Map();
647
- eventIndexByEvent.set(event.entry.event, index);
648
- eventIndexesByPaymentId.set(event.entry.paymentId, eventIndexByEvent);
649
- });
650
- const invalidReasonsById = /* @__PURE__ */ new Map();
651
- eventIndexesByPaymentId.forEach((eventIndexByEvent, paymentId) => {
652
- const lifecycleEvents = lifecycleEventsByPaymentId.get(paymentId);
653
- if (!lifecycleEvents)
654
- return;
655
- const failure = getPaymentLifecycleFailure({
656
- lifecycleEvents,
657
- eventIndexByEvent
658
- });
659
- if (failure === void 0)
660
- return;
661
- orderedEvents.forEach((event) => {
662
- if (event.eventType === "payment-entry" && event.entry.paymentId === paymentId) {
663
- invalidReasonsById.set(event.id, failure);
564
+ dispose() {
565
+ this.#eventSource.dispose();
566
+ this.#eventSource = "(disposed)";
567
+ this.equals = "(disposed)";
568
+ }
569
+ get hasWatchers() {
570
+ if (this.#eventSource.count() > 0)
571
+ return true;
572
+ for (const sink of this[kSinks]) {
573
+ if (sink.hasWatchers) {
574
+ return true;
664
575
  }
576
+ }
577
+ return false;
578
+ }
579
+ [kTrigger]() {
580
+ this.#eventSource.notify();
581
+ for (const sink of this[kSinks]) {
582
+ enqueueTrigger(sink);
583
+ }
584
+ }
585
+ subscribe(callback) {
586
+ if (this.#eventSource.count() === 0) {
587
+ this.get();
588
+ }
589
+ return this.#eventSource.subscribe(callback);
590
+ }
591
+ subscribeOnce(callback) {
592
+ const unsub = this.subscribe(() => {
593
+ unsub();
594
+ return callback();
665
595
  });
666
- });
667
- return invalidReasonsById;
668
- };
669
- var resolvePaymentEvent = ({
670
- event,
671
- payments,
672
- paymentTypes,
673
- invalidPaymentReasonsById
674
- }) => {
675
- const payment = payments.get(event.entry.paymentId);
676
- if (!payment) {
677
- return {
678
- id: event.id,
679
- entryId: null,
680
- idKey: null,
681
- parameters: {},
682
- repeatedParameters: {},
683
- failure: {
684
- errorKind: "entry_invalid",
685
- reasons: [PAYMENT_GONE_FROM_SCENARIO_REASON]
686
- }
687
- };
596
+ return unsub;
688
597
  }
689
- const entryId = makePaymentEntryId(
690
- payment.paymentTypeId,
691
- payment.paymentTypeVersionId,
692
- event.entry.event
693
- );
694
- const context = getPaymentVersionContext(paymentTypes, payment);
695
- const instanceParameters = payment.parameters;
696
- const base = {
697
- id: event.id,
698
- entryId,
699
- idKey: getEntryIdKey(entryId),
700
- payment: {
701
- paymentType: context?.paymentType ?? "unknown",
702
- event: event.entry.event,
703
- ik: payment.ik
704
- },
705
- parameters: instanceParameters,
706
- repeatedParameters: {}
707
- };
708
- const fail = (errorKind, reason) => ({
709
- ...base,
710
- failure: { errorKind, reasons: [reason] }
711
- });
712
- if (!context)
713
- return fail("entry_invalid", PAYMENT_GONE_FROM_SCHEMA_REASON);
714
- const invalidPaymentReason = invalidPaymentReasonsById.get(event.id);
715
- if (invalidPaymentReason !== void 0) {
716
- return fail("entry_invalid", invalidPaymentReason);
598
+ waitUntil() {
599
+ throw new Error("waitUntil not supported on Signals");
717
600
  }
718
- const parameters = withSystemParameters(
719
- instanceParameters,
720
- context.amountExpression,
721
- event.entry.event
722
- );
723
- if (parameters === null) {
724
- return fail(
725
- "parameter_error",
726
- makeUnevaluatedAmountReason(context.amountExpression)
727
- );
601
+ markSinksDirty() {
602
+ for (const sink of this[kSinks]) {
603
+ sink.markDirty();
604
+ }
605
+ }
606
+ addSink(sink) {
607
+ this[kSinks].add(sink);
608
+ }
609
+ removeSink(sink) {
610
+ this[kSinks].delete(sink);
611
+ }
612
+ asReadonly() {
613
+ return this;
728
614
  }
729
- return { ...base, parameters };
730
615
  };
731
- var resolveSceneEvents = ({
732
- events,
733
- eventsOrder,
734
- payments,
735
- paymentTypes
736
- }) => {
737
- const eventsById = new Map(events.map((event) => [event.id, event]));
738
- const orderedEvents = eventsOrder.map((eventId) => eventsById.get(eventId)).filter((event) => event !== void 0);
739
- const lifecycleEventsByPaymentId = /* @__PURE__ */ new Map();
740
- payments.forEach((payment, paymentId) => {
741
- const context = getPaymentVersionContext(paymentTypes, payment);
742
- if (context) {
743
- lifecycleEventsByPaymentId.set(paymentId, context.lifecycleEvents);
744
- }
745
- });
746
- const invalidPaymentReasonsById = findInvalidPaymentEvents(
747
- orderedEvents,
748
- lifecycleEventsByPaymentId
749
- );
750
- return orderedEvents.map(
751
- (event) => z2(event).with({ eventType: "entry" }, (ledgerEvent) => {
752
- const entryId = getLedgerSceneEventEntryId(ledgerEvent);
753
- return {
754
- id: ledgerEvent.id,
755
- entryId,
756
- idKey: getEntryIdKey(entryId),
757
- parameters: ledgerEvent.entry.parameters,
758
- repeatedParameters: ledgerEvent.entry.repeatedParameters ?? {}
759
- };
760
- }).with(
761
- { eventType: "payment-entry" },
762
- (paymentEvent) => resolvePaymentEvent({
763
- event: paymentEvent,
764
- payments,
765
- paymentTypes,
766
- invalidPaymentReasonsById
767
- })
768
- ).exhaustive()
769
- );
770
- };
771
- var buildSceneEntriesByKey = ({
772
- resolvedEvents,
773
- root,
774
- accountPathToAccount,
775
- defaultConsistencyConfig
776
- }) => {
777
- const entriesByKey = /* @__PURE__ */ new Map();
778
- resolvedEvents.forEach(({ entryId, idKey }) => {
779
- if (!entryId || !idKey || entriesByKey.has(idKey))
780
- return;
781
- const entryType = getEntryTypeFromRoot(root, entryId);
782
- if (!entryType)
783
- return;
784
- const entryVersion = getEntryVersionFromRoot(root, entryId);
785
- if (!entryVersion)
786
- return;
787
- if (entryId.flavor === "ledger") {
788
- entriesByKey.set(
789
- idKey,
790
- validateAndTransformEntryVersion({
791
- entryType,
792
- entryVersion,
793
- accountPathToAccount,
794
- defaultConsistencyConfig
795
- })
796
- );
616
+ var INITIAL = Symbol();
617
+ var DerivedSignal = class _DerivedSignal extends AbstractSignal {
618
+ #prevValue;
619
+ #dirty;
620
+ // When true, the value in #value may not be up-to-date and needs re-checking
621
+ #sources;
622
+ #deps;
623
+ #transform;
624
+ // prettier-ignore
625
+ static from(...args) {
626
+ const last = args.pop();
627
+ if (typeof last !== "function")
628
+ raise("Invalid .from() call, last argument expected to be a function");
629
+ if (typeof args[args.length - 1] === "function") {
630
+ const equals = last;
631
+ const transform = args.pop();
632
+ return new _DerivedSignal(args, transform, equals);
633
+ } else {
634
+ const transform = last;
635
+ return new _DerivedSignal(args, transform);
636
+ }
637
+ }
638
+ constructor(deps, transform, equals) {
639
+ super(equals);
640
+ this.#dirty = true;
641
+ this.#prevValue = INITIAL;
642
+ this.#deps = deps;
643
+ this.#sources = /* @__PURE__ */ new Set();
644
+ this.#transform = transform;
645
+ }
646
+ dispose() {
647
+ for (const src of this.#sources) {
648
+ src.removeSink(this);
649
+ }
650
+ this.#prevValue = "(disposed)";
651
+ this.#sources = "(disposed)";
652
+ this.#deps = "(disposed)";
653
+ this.#transform = "(disposed)";
654
+ }
655
+ get isDirty() {
656
+ return this.#dirty;
657
+ }
658
+ #recompute() {
659
+ const oldTrackedReads = trackedReads;
660
+ let derived;
661
+ trackedReads = /* @__PURE__ */ new Set();
662
+ try {
663
+ derived = this.#transform(...this.#deps.map((p) => p.get()));
664
+ } finally {
665
+ const oldSources = this.#sources;
666
+ this.#sources = /* @__PURE__ */ new Set();
667
+ for (const sig of trackedReads) {
668
+ this.#sources.add(sig);
669
+ oldSources.delete(sig);
670
+ }
671
+ for (const oldSource of oldSources) {
672
+ oldSource.removeSink(this);
673
+ }
674
+ for (const newSource of this.#sources) {
675
+ newSource.addSink(this);
676
+ }
677
+ trackedReads = oldTrackedReads;
678
+ }
679
+ this.#dirty = false;
680
+ if (!this.equals(this.#prevValue, derived)) {
681
+ this.#prevValue = derived;
682
+ return true;
683
+ }
684
+ return false;
685
+ }
686
+ markDirty() {
687
+ if (!this.#dirty) {
688
+ this.#dirty = true;
689
+ this.markSinksDirty();
690
+ }
691
+ }
692
+ get() {
693
+ if (this.#dirty) {
694
+ this.#recompute();
695
+ }
696
+ trackedReads?.add(this);
697
+ return this.#prevValue;
698
+ }
699
+ /**
700
+ * Called by the Signal system if one or more of the dependent signals have
701
+ * changed. In the case of a DerivedSignal, we'll only want to re-evaluate
702
+ * the actual value if it's being watched, or any of their sinks are being
703
+ * watched actively.
704
+ */
705
+ [kTrigger]() {
706
+ if (!this.hasWatchers) {
797
707
  return;
798
708
  }
799
- entriesByKey.set(
800
- idKey,
801
- transformEntryVersion({
802
- entryType,
803
- entryVersion,
804
- accountPathToAccount,
805
- errors: validateLivePaymentEntry({
806
- entryVersion,
807
- event: entryId.event,
808
- entryIdentity: entryType.type,
809
- accountPathToAccount
810
- })
811
- })
812
- );
813
- });
814
- return entriesByKey;
815
- };
816
-
817
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/EntryValidationUtils.ts
818
- init_cjs_shims();
819
- var buildAccountIdToAccountRecord = (chartOfAccounts) => {
820
- if (!chartOfAccounts)
821
- return {};
822
- const accountsMap = new Map(
823
- Array.from(chartOfAccounts.accounts.entries())
824
- );
825
- const accountIds = {};
826
- chartOfAccounts.accounts.forEach((account, accountId) => {
827
- const structuralPath = computeStructuralPath(
828
- accountId,
829
- accountsMap,
830
- account.parentId
831
- );
832
- accountIds[structuralPath] = accountId;
833
- });
834
- const filledIn = buildAndValidateChartOfAccounts(chartOfAccounts);
835
- const enhancedCoA = enhanceCoA(filledIn, { accountIds });
836
- return enhancedCoA.accountIdToAccount;
709
+ const updated = this.#recompute();
710
+ if (updated) {
711
+ super[kTrigger]();
712
+ }
713
+ }
837
714
  };
838
-
839
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
840
- init_cjs_shims();
841
-
842
- // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
843
- init_cjs_shims();
844
- import assert from "assert";
845
-
846
- // ../../libs/schema-validation/utils/transformers/schema.ts
847
- init_cjs_shims();
848
- var transformAndValidateSchema = (schema) => {
849
- const errors = [];
850
- const schemaKeyResult = SafeStringSchema.safeParse(schema.key);
851
- if (!schemaKeyResult.success || schemaKeyResult.data.includes("{{") || schemaKeyResult.data.includes("}}")) {
852
- errors.push({
853
- message: `Invalid key. Keys cannot contain '{{' or '}}' and must be non-empty`,
854
- path: ["key"]
855
- });
715
+ function assertNever(_value, errmsg) {
716
+ throw new Error(errmsg);
717
+ }
718
+ function assert(condition, errmsg) {
719
+ if (process.env.NODE_ENV !== "production") {
720
+ if (!condition) {
721
+ const err = new Error(errmsg);
722
+ err.name = "Assertion failure";
723
+ throw err;
724
+ }
856
725
  }
857
- const res = transformAndValidateCoA({
858
- coa: schema.chartOfAccounts
859
- });
860
- const { errors: coaErrors } = res;
861
- const validatedChartOfAccounts = res.filledIn;
862
- errors.push(
863
- ...coaErrors.map((e) => ({ ...e, path: ["chartOfAccounts", ...e.path] }))
864
- );
865
- const { filledIn: ledgerEntries, errors: entryErrors } = transformAndValidateEntries({
866
- ledgerEntries: schema.ledgerEntries ?? { types: [] },
867
- validatedCoA: validatedChartOfAccounts
868
- });
869
- errors.push(
870
- ...entryErrors.map((e) => ({ ...e, path: ["ledgerEntries", ...e.path] }))
726
+ }
727
+ function nn(value, errmsg = "Expected value to be non-nullable") {
728
+ assert(value !== null && value !== void 0, errmsg);
729
+ return value;
730
+ }
731
+ var fancy_console_exports = {};
732
+ __export(fancy_console_exports, {
733
+ error: () => error2,
734
+ errorWithTitle: () => errorWithTitle,
735
+ warn: () => warn,
736
+ warnWithTitle: () => warnWithTitle
737
+ });
738
+ var badge = "background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;";
739
+ var bold = "font-weight:600";
740
+ function wrap(method) {
741
+ return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
742
+ /* istanbul ignore next */
743
+ (message, ...args) => console[method]("%cLiveblocks", badge, message, ...args)
871
744
  );
872
- const { errors: paymentErrors } = transformAndValidatePayments({
873
- payments: schema.payments ?? { types: [] },
874
- validatedCoA: validatedChartOfAccounts
875
- });
876
- errors.push(
877
- ...paymentErrors.map((e) => ({ ...e, path: ["payments", ...e.path] }))
745
+ }
746
+ var warn = wrap("warn");
747
+ var error2 = wrap("error");
748
+ function wrapWithTitle(method) {
749
+ return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
750
+ /* istanbul ignore next */
751
+ (title, message, ...args) => console[method](
752
+ `%cLiveblocks%c ${title}`,
753
+ badge,
754
+ bold,
755
+ message,
756
+ ...args
757
+ )
878
758
  );
879
- const consistencyErrors = schema.consistencyConfig ? validateLedgerConsistencySettings(schema.consistencyConfig) : { errors: [] };
880
- errors.push(...consistencyErrors.errors);
881
- const groups = schema.groups ?? [];
882
- if (groups.length > 0) {
883
- groups.forEach((group, index) => {
884
- const groupErrors = validateGroup(
885
- group,
886
- validatedChartOfAccounts,
887
- ledgerEntries,
888
- index
889
- );
890
- errors.push(...groupErrors);
891
- });
892
- }
893
- return {
894
- errors,
895
- validatedSchema: {
896
- name: schema.name,
897
- key: schema.key,
898
- consistencyConfig: schema.consistencyConfig?.entries ? {
899
- entries: schema.consistencyConfig.entries
900
- } : {
901
- entries: "eventual"
902
- },
903
- ledgerEntries,
904
- chartOfAccounts: validatedChartOfAccounts,
905
- scenes: schema.scenes,
906
- groups,
907
- payments: schema.payments
759
+ }
760
+ var warnWithTitle = wrapWithTitle("warn");
761
+ var errorWithTitle = wrapWithTitle("error");
762
+ var nanoid = (t = 21) => crypto.getRandomValues(new Uint8Array(t)).reduce(
763
+ (t2, e) => t2 += (e &= 63) < 36 ? e.toString(36) : e < 62 ? (e - 26).toString(36).toUpperCase() : e < 63 ? "_" : "-",
764
+ ""
765
+ );
766
+ var BACKOFF_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4];
767
+ var RESET_DELAY = BACKOFF_DELAYS[0] - 1;
768
+ function log(level, message) {
769
+ const logger = level === 2 ? error2 : level === 1 ? warn : (
770
+ /* black hole */
771
+ () => {
908
772
  }
909
- };
910
- };
911
-
912
- // ../../libs/shared-utils/accounting/currency.ts
913
- init_cjs_shims();
914
-
915
- // ../../libs/shared-utils/accounting/doubleEntry.ts
916
- init_cjs_shims();
917
-
918
- // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
919
- var formatSchemaValidationError = (error3) => {
920
- const path = error3.path.length > 0 ? ` (Path: ${error3.path.join("/")})` : "";
921
- const code = error3.code ? ` [${error3.code}]` : "";
922
- return `${error3.message}${code}${path}`;
923
- };
924
- var getBaseEntryParameters = (entry, accountIdToAccount) => {
925
- const allParams = new Set(
926
- [
927
- ...getSchemaObjectParameters(entry, false),
928
- ...entry.lines.flatMap(
929
- ({ account }) => account?.id ? getSchemaObjectParameters(accountIdToAccount[account.id], false) : []
930
- )
931
- ].filter((param) => !entry.parameters[param])
932
773
  );
933
- return [...allParams];
934
- };
935
- var validateEntryConditions = ({
936
- filledEntry,
937
- sceneEvents,
938
- entryIndex
939
- }) => {
940
- filledEntry.conditions.forEach((condition) => {
941
- const { path } = condition.account;
942
- const { currency } = condition;
943
- assert(
944
- currency.code !== "MULTI",
945
- `Invalid Condition. Condition in Entry ${filledEntry.type} on multi-currency Ledger Account ${path} must have a currency set`
946
- );
947
- const matchesPath = {
948
- ownBalance: (linePath) => linePath === path,
949
- totalBalance: (linePath) => linePath === path || linePath.startsWith(`${path}/`)
950
- };
951
- const sumLines = (lines, scope) => lines.filter(
952
- (line) => matchesPath[scope](line.account.path) && line.currency.code === currency.code && line.currency.customCurrencyId === currency.customCurrencyId
953
- ).reduce(
954
- (sum, line) => sum + BigInt(evaluateExpression(line.amount)),
955
- 0n
956
- );
957
- const sumPriorLines = (scope) => sceneEvents.slice(0, entryIndex).reduce(
958
- (sum, { entry: balanceEntry }) => sum + (balanceEntry.isValid ? sumLines(balanceEntry.lines, scope) : 0n),
959
- 0n
960
- );
961
- const checkBoundary = (kind, scope, amount, bounds) => {
962
- if (!bounds)
963
- return;
964
- const label = kind === "precondition" ? "Precondition" : "Postcondition";
965
- const when = kind === "precondition" ? "before posting this entry" : "after posting this entry";
966
- const checks = [
967
- ["=", bounds.eq, (a, b) => a === b],
968
- [">=", bounds.gte, (a, b) => a >= b],
969
- ["<=", bounds.lte, (a, b) => a <= b]
970
- ];
971
- checks.forEach(([op, rhs, cmp]) => {
972
- if (rhs === void 0)
973
- return;
974
- assert(
975
- cmp(amount, BigInt(evaluateExpression(rhs))),
976
- `${label} not satisfied. Ledger Account ${path} must have ${scope} ${op} ${rhs} ${when}. Got: ${amount}`
977
- );
978
- });
979
- };
980
- const preOwn = sumPriorLines("ownBalance");
981
- const preTotal = sumPriorLines("totalBalance");
982
- checkBoundary(
983
- "precondition",
984
- "ownBalance",
985
- preOwn,
986
- condition.precondition?.ownBalance
987
- );
988
- checkBoundary(
989
- "precondition",
990
- "totalBalance",
991
- preTotal,
992
- condition.precondition?.totalBalance
993
- );
994
- const postOwn = preOwn + sumLines(filledEntry.lines, "ownBalance");
995
- const postTotal = preTotal + sumLines(filledEntry.lines, "totalBalance");
996
- checkBoundary(
997
- "postcondition",
998
- "ownBalance",
999
- postOwn,
1000
- condition.postcondition?.ownBalance
1001
- );
1002
- checkBoundary(
1003
- "postcondition",
1004
- "totalBalance",
1005
- postTotal,
1006
- condition.postcondition?.totalBalance
1007
- );
774
+ return () => {
775
+ logger(message);
776
+ };
777
+ }
778
+ var logPermanentClose = log(
779
+ 1,
780
+ "Connection to WebSocket closed permanently. Won't retry."
781
+ );
782
+ var kInternal = Symbol();
783
+ var EMPTY_OBJECT = Object.freeze({});
784
+ var NULL_KEYWORD_CHARS = Array.from(new Set("null"));
785
+ var TRUE_KEYWORD_CHARS = Array.from(new Set("true"));
786
+ var FALSE_KEYWORD_CHARS = Array.from(new Set("false"));
787
+ var ALL_KEYWORD_CHARS = Array.from(new Set("nulltruefalse"));
788
+ var kWILDCARD = Symbol("*");
789
+ var eventSource = makeEventSource();
790
+ if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
791
+ window.addEventListener("message", (event) => {
792
+ if (event.source === window && event.data?.source === "liveblocks-devtools-panel") {
793
+ eventSource.notify(event.data);
794
+ } else {
795
+ }
1008
796
  });
1009
- };
1010
- var validateEntry2 = ({
1011
- accountIdToAccount,
1012
- baseEntry,
1013
- errors,
1014
- entry,
1015
- parameterValues
1016
- }) => {
1017
- try {
1018
- if (baseEntry) {
1019
- if (errors.length > 0) {
1020
- return {
1021
- errorKind: "entry_invalid",
1022
- reasons: errors.map(formatSchemaValidationError)
1023
- };
1024
- }
1025
- const parameters = getBaseEntryParameters(baseEntry, accountIdToAccount);
1026
- const missingParams = parameters.filter(
1027
- (param) => !parameterValues[param]
1028
- );
1029
- if (missingParams.length) {
1030
- throw new Error("All parameters must be filled in");
797
+ }
798
+ var onMessageFromPanel = eventSource.observable;
799
+ var loadedAt = Date.now();
800
+ var kPlain = Symbol("notification-settings-plain");
801
+ var MIN_CODE = 32;
802
+ var MAX_CODE = 126;
803
+ var NUM_DIGITS = MAX_CODE - MIN_CODE + 1;
804
+ var ZERO = nthDigit(0);
805
+ var ONE = nthDigit(1);
806
+ var ZERO_NINE = ZERO + nthDigit(-1);
807
+ function nthDigit(n) {
808
+ const code = MIN_CODE + (n < 0 ? NUM_DIGITS + n : n);
809
+ if (code < MIN_CODE || code > MAX_CODE) {
810
+ throw new Error(`Invalid n value: ${n}`);
811
+ }
812
+ return String.fromCharCode(code);
813
+ }
814
+ function makePosition(x, y) {
815
+ if (x !== void 0 && y !== void 0) {
816
+ return between(x, y);
817
+ } else if (x !== void 0) {
818
+ return after(x);
819
+ } else if (y !== void 0) {
820
+ return before(y);
821
+ } else {
822
+ return ONE;
823
+ }
824
+ }
825
+ function before(pos) {
826
+ const lastIndex = pos.length - 1;
827
+ for (let i = 0; i <= lastIndex; i++) {
828
+ const code = pos.charCodeAt(i);
829
+ if (code <= MIN_CODE) {
830
+ continue;
831
+ }
832
+ if (i === lastIndex) {
833
+ if (code === MIN_CODE + 1) {
834
+ return pos.substring(0, i) + ZERO_NINE;
835
+ } else {
836
+ return pos.substring(0, i) + String.fromCharCode(code - 1);
1031
837
  }
838
+ } else {
839
+ return pos.substring(0, i + 1);
1032
840
  }
1033
- const lineValues = {};
1034
- entry.lines.forEach((line) => {
1035
- line.amountParameters.forEach((param) => {
1036
- assert(
1037
- !Number.isNaN(parseInt(parameterValues[param], 10)),
1038
- `Parameter ${param} must have numeric value`
1039
- );
1040
- });
1041
- });
1042
- const filledEntry = fillParams(entry, {
1043
- ...parameterValues,
1044
- ...entry.parameters
1045
- });
1046
- filledEntry.lines.forEach((line, lineNumber) => {
1047
- const key = makeLineKey(line, lineNumber);
1048
- const amount = line.amount && evaluateExpression(line.amount);
1049
- lineValues[key] = {
1050
- amount: Number(amount)
1051
- };
1052
- });
1053
- assert(
1054
- filledEntry.lines.every(
1055
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1056
- (line, lineNumber) => lineValues[makeLineKey(line, lineNumber)]
1057
- ),
1058
- "All amounts must be populated"
1059
- );
1060
- const accountsForBalancedPayload = {};
1061
- const linesForBalancedPayload = filledEntry.lines.map(
1062
- (line, lineNumber) => {
1063
- const lineKey = makeLineKey(line, lineNumber);
1064
- const fetchedAccount = accountIdToAccount[line.account.id];
1065
- const accountType = fetchedAccount.type;
1066
- if (accountType === void 0) {
1067
- throw new Error(
1068
- `Could not determine account type for path ${fetchedAccount.structuralPath}`
1069
- );
1070
- }
1071
- const account = {
1072
- currency: CurrencyCodeSchema.parse(line.currency.code),
1073
- customCurrencyId: line.currency.customCurrencyId,
1074
- type: accountType
1075
- };
1076
- const accountKey = `${fetchedAccount.structuralPath}:${serializeCurrency(account)}`;
1077
- accountsForBalancedPayload[accountKey] = account;
1078
- return {
1079
- currency: line.currency.code,
1080
- customCurrencyId: line.currency.customCurrencyId,
1081
- amount: BigInt(lineValues[lineKey].amount),
1082
- account: {
1083
- id: accountKey
1084
- }
1085
- };
1086
- }
1087
- );
1088
- assertBalancedLines({
1089
- // @ts-expect-error TODO: make visualizer support parameterized currencies after https://github.com/fragment-dev/workspaces/pull/3076/files is merged
1090
- lines: linesForBalancedPayload,
1091
- ledgerAccounts: accountsForBalancedPayload
1092
- });
1093
- return { lineValues, filledEntry };
1094
- } catch (err) {
1095
- if (err instanceof Error) {
1096
- return { errorKind: "parameter_error", reasons: [err.message] };
841
+ }
842
+ return ONE;
843
+ }
844
+ function after(pos) {
845
+ for (let i = 0; i <= pos.length - 1; i++) {
846
+ const code = pos.charCodeAt(i);
847
+ if (code >= MAX_CODE) {
848
+ continue;
1097
849
  }
1098
- throw err;
850
+ return pos.substring(0, i) + String.fromCharCode(code + 1);
1099
851
  }
1100
- };
1101
- var generatePostedEntry = ({
1102
- accountIdToAccount,
1103
- baseEntry,
1104
- errors,
1105
- entry,
1106
- postedEntryId,
1107
- parameterValues
1108
- }) => {
1109
- const entryId = postedEntryId || lil_id_default();
1110
- const validation = validateEntry2({
1111
- accountIdToAccount,
1112
- baseEntry,
1113
- errors,
1114
- entry,
1115
- parameterValues
1116
- });
1117
- if ("reasons" in validation) {
1118
- return {
1119
- isValid: false,
1120
- errorKind: validation.errorKind,
1121
- reasons: validation.reasons,
1122
- id: entryId,
1123
- type: entry.type,
1124
- typeVersion: entry.typeVersion,
1125
- baseEntryId: entry.id,
1126
- parameters: parameterValues
1127
- };
852
+ return pos + ONE;
853
+ }
854
+ function between(lo, hi) {
855
+ if (lo < hi) {
856
+ return _between(lo, hi);
857
+ } else if (lo > hi) {
858
+ return _between(hi, lo);
859
+ } else {
860
+ throw new Error("Cannot compute value between two equal positions");
1128
861
  }
1129
- const { filledEntry, lineValues } = validation;
1130
- return {
1131
- id: entryId,
1132
- typeVersion: filledEntry.typeVersion,
1133
- ik: lil_id_default(),
1134
- type: filledEntry.type,
1135
- parameters: parameterValues,
1136
- conditions: filledEntry.conditions,
1137
- lines: filledEntry.lines.map(
1138
- (line, lineNumber) => ({
1139
- ...line,
1140
- amount: String(lineValues[makeLineKey(line, lineNumber)].amount)
1141
- })
1142
- ),
1143
- tags: filledEntry.tags,
1144
- groups: filledEntry.groups,
1145
- baseEntryId: entry.id,
1146
- isValid: true,
1147
- status: filledEntry.status ?? "active"
1148
- };
1149
- };
1150
-
1151
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/useEntryUtils.ts
1152
- init_cjs_shims();
1153
- var convertEntryResponseToEnhancedSchemaLedgerEntry = (entry, accountIdToAccount) => {
1154
- const baseEntry = {
1155
- type: entry.value.type,
1156
- typeVersion: entry.value.typeVersion,
1157
- description: entry.value.description,
1158
- postLinesAs: entry.value.postLinesAs,
1159
- status: entry.value.status,
1160
- parameters: convertStaticParametersToRecord(entry.value.parameters) ?? {},
1161
- groups: entry.value.groups?.map((group) => ({
1162
- key: safe`${group.key}`,
1163
- value: group.value
1164
- })) ?? [],
1165
- tags: entry.value.tags?.map((tag) => ({
1166
- key: tag.key,
1167
- value: tag.value
1168
- })) ?? [],
1169
- lines: entry.value.lines?.map((line) => ({
1170
- key: line.key,
1171
- account: line.account ? {
1172
- id: line.account.accountId ?? "",
1173
- path: line.account.path
1174
- } : void 0,
1175
- amount: line.amount,
1176
- currency: line.currency,
1177
- description: line.description,
1178
- tx: line.tx,
1179
- repeated: line.repeated ? { key: safe`${line.repeated.key}` } : void 0
1180
- })) ?? [],
1181
- conditions: entry.value.conditions?.map((condition) => ({
1182
- account: condition.account ? {
1183
- id: condition.account.accountId ?? "",
1184
- path: condition.account.path
1185
- } : void 0,
1186
- currency: condition.currency,
1187
- precondition: condition.precondition,
1188
- postcondition: condition.postcondition,
1189
- repeated: condition.repeated ? { key: safe`${condition.repeated.key}` } : void 0
1190
- })) ?? []
1191
- };
1192
- return enhanceLedgerEntry(
1193
- baseEntry,
1194
- accountIdToAccount,
1195
- safe`${entry.value.typeVersion && entry.value.typeVersion > 1 ? entry.value.versionId : entry.value.entryId}`
1196
- );
1197
- };
1198
-
1199
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
1200
- var transformLiveblocksSceneEvents = (resolvedEvents, entriesByKey, accountIdToAccount) => {
1201
- const accountMap = new Map(Object.entries(accountIdToAccount));
1202
- const postedEntries = [];
1203
- resolvedEvents.forEach((event, entryIndex) => {
1204
- const { entryId, idKey, payment: paymentInfo } = event;
1205
- const baseEntryResponse = idKey === null ? void 0 : entriesByKey.get(idKey);
1206
- const baseEntryId = (entryId && (entryId.flavor === "payment" ? entryId.paymentTypeId : entryId.entryTypeId)) ?? "";
1207
- const repeatedParams = event.repeatedParameters;
1208
- const staticParams = event.parameters;
1209
- const pushSceneEvent = (entry, lineAccountTypes2) => {
1210
- postedEntries.push(
1211
- paymentInfo ? {
1212
- id: event.id,
1213
- eventType: "payment-entry",
1214
- entry,
1215
- payment: paymentInfo,
1216
- entryId,
1217
- lineAccountTypes: lineAccountTypes2
1218
- } : {
1219
- id: event.id,
1220
- eventType: "entry",
1221
- entry,
1222
- entryId,
1223
- lineAccountTypes: lineAccountTypes2
1224
- }
1225
- );
1226
- };
1227
- const pushInvalidSceneEvent = (errorKind, reasons) => {
1228
- pushSceneEvent(
1229
- {
1230
- id: event.id,
1231
- parameters: { ...staticParams, ...repeatedParams },
1232
- baseEntryId,
1233
- type: paymentInfo?.paymentType ?? "unknown",
1234
- isValid: false,
1235
- errorKind,
1236
- reasons
1237
- },
1238
- []
1239
- );
1240
- };
1241
- if (event.failure) {
1242
- pushInvalidSceneEvent(event.failure.errorKind, event.failure.reasons);
1243
- return;
1244
- }
1245
- if (!baseEntryResponse) {
1246
- pushInvalidSceneEvent("entry_invalid", [
1247
- entryId?.flavor === "payment" ? PAYMENT_GONE_FROM_SCHEMA_REASON : "Entry not found"
1248
- ]);
1249
- return;
862
+ }
863
+ function _between(lo, hi) {
864
+ let index = 0;
865
+ const loLen = lo.length;
866
+ const hiLen = hi.length;
867
+ while (true) {
868
+ const loCode = index < loLen ? lo.charCodeAt(index) : MIN_CODE;
869
+ const hiCode = index < hiLen ? hi.charCodeAt(index) : MAX_CODE;
870
+ if (loCode === hiCode) {
871
+ index++;
872
+ continue;
1250
873
  }
1251
- const lineAccountTypes = (baseEntryResponse.value.lines ?? []).map((line) => {
1252
- if (!line.account?.accountId) {
1253
- return void 0;
1254
- }
1255
- const account = accountMap.get(line.account.accountId);
1256
- if (!account) {
1257
- return void 0;
1258
- }
1259
- return account.type;
1260
- }).filter((type) => type !== void 0);
1261
- const enhancedEntry = convertEntryResponseToEnhancedSchemaLedgerEntry(
1262
- baseEntryResponse,
1263
- accountIdToAccount
1264
- );
1265
- const simulatingEntryErrors = [];
1266
- const simulatingEntry = generateSimulatingEntry({
1267
- entry: enhancedEntry,
1268
- accountIdToAccount,
1269
- onError: (error3) => {
1270
- if (error3 instanceof Error) {
1271
- simulatingEntryErrors.push(error3.message);
1272
- }
874
+ if (hiCode - loCode === 1) {
875
+ const size = index + 1;
876
+ let prefix = lo.substring(0, size);
877
+ if (prefix.length < size) {
878
+ prefix += ZERO.repeat(size - prefix.length);
1273
879
  }
1274
- });
1275
- if (!simulatingEntry) {
1276
- pushSceneEvent(
1277
- {
1278
- id: event.id,
1279
- parameters: { ...staticParams, ...repeatedParams },
1280
- baseEntryId,
1281
- type: "unknown",
1282
- isValid: false,
1283
- errorKind: "parameter_error",
1284
- reasons: [
1285
- "Failed to fill parameters on Entry. Reasons: ",
1286
- simulatingEntryErrors.join(", ")
1287
- ]
1288
- },
1289
- []
1290
- );
1291
- return;
880
+ const suffix = lo.substring(size);
881
+ const nines = "";
882
+ return prefix + _between(suffix, nines);
883
+ } else {
884
+ return takeN(lo, index) + String.fromCharCode(hiCode + loCode >> 1);
1292
885
  }
1293
- const mergedRepeatedParams = { ...staticParams, ...repeatedParams };
1294
- const preFilledEntry = {
1295
- ...simulatingEntry,
1296
- lines: simulatingEntry.lines.map(
1297
- (line) => fillParams(line, line.repeated ? mergedRepeatedParams : staticParams, {
1298
- allowMissing: true,
1299
- allowMissingInChildren: true
1300
- })
1301
- ),
1302
- conditions: simulatingEntry.conditions.map(
1303
- (condition) => fillParams(
1304
- condition,
1305
- condition.repeated ? mergedRepeatedParams : staticParams,
1306
- { allowMissing: true, allowMissingInChildren: true }
1307
- )
1308
- )
1309
- };
1310
- const postedEntry = generatePostedEntry({
1311
- accountIdToAccount,
1312
- baseEntry: enhancedEntry,
1313
- errors: baseEntryResponse.errors,
1314
- entry: preFilledEntry,
1315
- postedEntryId: event.id,
1316
- parameterValues: { ...staticParams, ...repeatedParams }
1317
- });
1318
- if (postedEntry.isValid) {
1319
- const lineAccounts = postedEntry.lines.map((line) => ({
1320
- acc: accountMap.get(line.account.id),
1321
- currency: line.currency
1322
- })).filter(
1323
- (la) => la.acc !== void 0
1324
- );
1325
- if (lineAccounts.length !== postedEntry.lines.length) {
1326
- pushSceneEvent(
1327
- {
1328
- ...postedEntry,
1329
- isValid: false,
1330
- errorKind: "entry_invalid",
1331
- reasons: ["Could not find account for some lines"]
1332
- },
1333
- []
1334
- );
1335
- return;
1336
- }
1337
- const resolveAccountType = (acc) => acc.type;
1338
- const lineAccountWithMissingType = lineAccounts.find(
1339
- ({ acc }) => resolveAccountType(acc) === void 0
1340
- );
1341
- if (lineAccountWithMissingType) {
1342
- pushSceneEvent(
1343
- {
1344
- ...postedEntry,
1345
- isValid: false,
1346
- errorKind: "entry_invalid",
1347
- reasons: [
1348
- `Could not determine account type for path ${lineAccountWithMissingType.acc.structuralPath}`
1349
- ]
1350
- },
1351
- []
1352
- );
1353
- return;
1354
- }
1355
- const conditionWithMissingType = postedEntry.conditions.map(
1356
- (condition) => condition.account.id ? accountMap.get(condition.account.id) : void 0
1357
- ).find(
1358
- (account) => account && resolveAccountType(account) === void 0
1359
- );
1360
- if (conditionWithMissingType) {
1361
- pushSceneEvent(
1362
- {
1363
- ...postedEntry,
1364
- isValid: false,
1365
- errorKind: "entry_invalid",
1366
- reasons: [
1367
- `Could not determine account type for path ${conditionWithMissingType.structuralPath}`
1368
- ]
1369
- },
1370
- []
1371
- );
1372
- return;
1373
- }
1374
- try {
1375
- validateEntryConditions({
1376
- filledEntry: postedEntry,
1377
- sceneEvents: postedEntries,
1378
- entryIndex
1379
- });
1380
- } catch (err) {
1381
- if (err instanceof Error) {
1382
- pushSceneEvent(
1383
- {
1384
- ...postedEntry,
1385
- isValid: false,
1386
- errorKind: "parameter_error",
1387
- reasons: [`Error in entry condition: ${err.message}`]
1388
- },
1389
- []
1390
- );
1391
- }
1392
- return;
1393
- }
1394
- }
1395
- pushSceneEvent(postedEntry, lineAccountTypes);
1396
- });
1397
- return postedEntries;
1398
- };
1399
-
1400
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/simulateScene.ts
1401
- var NO_SCENE_PAYMENTS = /* @__PURE__ */ new Map();
1402
- var simulateScene = ({
1403
- root,
1404
- sceneId
1405
- }) => {
1406
- const scene = root.schema.scenes.get(sceneId);
1407
- if (!scene)
1408
- return null;
1409
- const { chartOfAccounts } = root.schema;
1410
- const accountIdToAccount = buildAccountIdToAccountRecord(chartOfAccounts);
1411
- const { accountPathToAccount, defaultConsistencyConfig } = buildAccountPathToAccountMap(chartOfAccounts);
1412
- const resolvedEvents = resolveSceneEvents({
1413
- events: Array.from(scene.events.values()),
1414
- eventsOrder: Array.from(scene.eventsOrder.values()),
1415
- payments: scene.payments ?? NO_SCENE_PAYMENTS,
1416
- paymentTypes: root.schema.paymentTypes
1417
- });
1418
- const entriesByKey = buildSceneEntriesByKey({
1419
- resolvedEvents,
1420
- root,
1421
- accountPathToAccount,
1422
- defaultConsistencyConfig
1423
- });
1424
- const events = transformLiveblocksSceneEvents(
1425
- resolvedEvents,
1426
- entriesByKey,
1427
- accountIdToAccount
1428
- );
1429
- return {
1430
- id: scene.id,
1431
- name: scene.name ?? "",
1432
- events
1433
- };
1434
- };
1435
-
1436
- // ../../fragment-compositions/visualizer/src/utils/liveblocksUtils.ts
1437
- init_cjs_shims();
1438
- import assert3 from "assert";
1439
-
1440
- // ../../node_modules/@liveblocks/client/dist/index.js
1441
- init_cjs_shims();
1442
-
1443
- // ../../node_modules/@liveblocks/core/dist/index.js
1444
- init_cjs_shims();
1445
- var __defProp = Object.defineProperty;
1446
- var __export = (target, all) => {
1447
- for (var name in all)
1448
- __defProp(target, name, { get: all[name], enumerable: true });
1449
- };
1450
- var PKG_NAME = "@liveblocks/core";
1451
- var PKG_VERSION = "3.7.1";
1452
- var PKG_FORMAT = "esm";
1453
- var g = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
1454
- var crossLinkedDocs = "https://liveblocks.io/docs/errors/cross-linked";
1455
- var dupesDocs = "https://liveblocks.io/docs/errors/dupes";
1456
- var SPACE = " ";
1457
- function error(msg) {
1458
- if (process.env.NODE_ENV === "production") {
1459
- console.error(msg);
1460
- } else {
1461
- throw new Error(msg);
1462
886
  }
1463
887
  }
1464
- function detectDupes(pkgName, pkgVersion, pkgFormat) {
1465
- const pkgId = Symbol.for(pkgName);
1466
- const pkgBuildInfo = pkgFormat ? `${pkgVersion || "dev"} (${pkgFormat})` : pkgVersion || "dev";
1467
- if (!g[pkgId]) {
1468
- g[pkgId] = pkgBuildInfo;
1469
- } else if (g[pkgId] === pkgBuildInfo) {
1470
- } else {
1471
- const msg = [
1472
- `Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See ${dupesDocs + SPACE}`,
1473
- "",
1474
- "Conflicts:",
1475
- `- ${pkgName} ${g[pkgId]} (already loaded)`,
1476
- `- ${pkgName} ${pkgBuildInfo} (trying to load this now)`
1477
- ].join("\n");
1478
- error(msg);
1479
- }
1480
- if (pkgVersion && PKG_VERSION && pkgVersion !== PKG_VERSION) {
1481
- error(
1482
- [
1483
- `Cross-linked versions of Liveblocks found, which will cause issues! See ${crossLinkedDocs + SPACE}`,
1484
- "",
1485
- "Conflicts:",
1486
- `- ${PKG_NAME} is at ${PKG_VERSION}`,
1487
- `- ${pkgName} is at ${pkgVersion}`,
1488
- "",
1489
- "Always upgrade all Liveblocks packages to the same version number."
1490
- ].join("\n")
1491
- );
1492
- }
888
+ function takeN(pos, n) {
889
+ return n < pos.length ? pos.substring(0, n) : pos + ZERO.repeat(n - pos.length);
1493
890
  }
1494
- function makeEventSource() {
1495
- const _observers = /* @__PURE__ */ new Set();
1496
- function subscribe(callback) {
1497
- _observers.add(callback);
1498
- return () => _observers.delete(callback);
1499
- }
1500
- function subscribeOnce(callback) {
1501
- const unsub = subscribe((event) => {
1502
- unsub();
1503
- return callback(event);
1504
- });
1505
- return unsub;
891
+ var MIN_NON_ZERO_CODE = MIN_CODE + 1;
892
+ function isPos(str) {
893
+ if (str === "") {
894
+ return false;
1506
895
  }
1507
- async function waitUntil(predicate) {
1508
- let unsub;
1509
- return new Promise((res) => {
1510
- unsub = subscribe((event) => {
1511
- if (predicate === void 0 || predicate(event)) {
1512
- res(event);
1513
- }
1514
- });
1515
- }).finally(() => unsub?.());
896
+ const lastIdx = str.length - 1;
897
+ const last = str.charCodeAt(lastIdx);
898
+ if (last < MIN_NON_ZERO_CODE || last > MAX_CODE) {
899
+ return false;
1516
900
  }
1517
- function notify(event) {
1518
- let called = false;
1519
- for (const callback of _observers) {
1520
- callback(event);
1521
- called = true;
901
+ for (let i = 0; i < lastIdx; i++) {
902
+ const code = str.charCodeAt(i);
903
+ if (code < MIN_CODE || code > MAX_CODE) {
904
+ return false;
1522
905
  }
1523
- return called;
1524
906
  }
1525
- function count() {
1526
- return _observers.size;
907
+ return true;
908
+ }
909
+ function convertToPos(str) {
910
+ const codes2 = [];
911
+ for (let i = 0; i < str.length; i++) {
912
+ const code = str.charCodeAt(i);
913
+ codes2.push(code < MIN_CODE ? MIN_CODE : code > MAX_CODE ? MAX_CODE : code);
1527
914
  }
1528
- return {
1529
- // Private/internal control over event emission
1530
- notify,
1531
- subscribe,
1532
- subscribeOnce,
1533
- count,
1534
- waitUntil,
1535
- dispose() {
1536
- _observers.clear();
1537
- },
1538
- // Publicly exposable subscription API
1539
- observable: {
1540
- subscribe,
1541
- subscribeOnce,
1542
- waitUntil
1543
- }
1544
- };
915
+ while (codes2.length > 0 && codes2[codes2.length - 1] === MIN_CODE) {
916
+ codes2.length--;
917
+ }
918
+ return codes2.length > 0 ? String.fromCharCode(...codes2) : (
919
+ // Edge case: the str was a 0-only string, which is invalid. Default back to .1
920
+ ONE
921
+ );
1545
922
  }
1546
- var freeze = process.env.NODE_ENV === "production" ? (
1547
- /* istanbul ignore next */
1548
- (x) => x
1549
- ) : Object.freeze;
1550
- function raise(msg) {
1551
- throw new Error(msg);
923
+ function asPos(str) {
924
+ return isPos(str) ? str : convertToPos(str);
1552
925
  }
1553
- function deepClone(value) {
1554
- return JSON.parse(JSON.stringify(value));
926
+ function crdtAsLiveNode(value) {
927
+ return value;
1555
928
  }
1556
- function compactObject(obj) {
1557
- const newObj = { ...obj };
1558
- Object.keys(obj).forEach((k) => {
1559
- const key = k;
1560
- if (newObj[key] === void 0) {
1561
- delete newObj[key];
1562
- }
1563
- });
1564
- return newObj;
929
+ function HasParent(node, key, pos = asPos(key)) {
930
+ return Object.freeze({ type: "HasParent", node, key, pos });
1565
931
  }
1566
- var kSinks = Symbol("kSinks");
1567
- var kTrigger = Symbol("kTrigger");
1568
- var signalsToTrigger = null;
1569
- var trackedReads = null;
1570
- function enqueueTrigger(signal) {
1571
- if (!signalsToTrigger)
1572
- raise("Expected to be in an active batch");
1573
- signalsToTrigger.add(signal);
932
+ var NoParent = Object.freeze({ type: "NoParent" });
933
+ function Orphaned(oldKey, oldPos = asPos(oldKey)) {
934
+ return Object.freeze({ type: "Orphaned", oldKey, oldPos });
1574
935
  }
1575
- var AbstractSignal = class {
1576
- /** @internal */
1577
- equals;
1578
- #eventSource;
936
+ var AbstractCrdt = class {
937
+ // ^^^^^^^^^^^^ TODO: Make this an interface
938
+ #pool;
939
+ #id;
940
+ #parent = NoParent;
1579
941
  /** @internal */
1580
- [kSinks];
1581
- constructor(equals) {
1582
- this.equals = equals ?? Object.is;
1583
- this.#eventSource = makeEventSource();
1584
- this[kSinks] = /* @__PURE__ */ new Set();
1585
- this.get = this.get.bind(this);
1586
- this.subscribe = this.subscribe.bind(this);
1587
- this.subscribeOnce = this.subscribeOnce.bind(this);
1588
- }
1589
- dispose() {
1590
- this.#eventSource.dispose();
1591
- this.#eventSource = "(disposed)";
1592
- this.equals = "(disposed)";
1593
- }
1594
- get hasWatchers() {
1595
- if (this.#eventSource.count() > 0)
1596
- return true;
1597
- for (const sink of this[kSinks]) {
1598
- if (sink.hasWatchers) {
1599
- return true;
1600
- }
1601
- }
1602
- return false;
1603
- }
1604
- [kTrigger]() {
1605
- this.#eventSource.notify();
1606
- for (const sink of this[kSinks]) {
1607
- enqueueTrigger(sink);
942
+ _getParentKeyOrThrow() {
943
+ switch (this.parent.type) {
944
+ case "HasParent":
945
+ return this.parent.key;
946
+ case "NoParent":
947
+ throw new Error("Parent key is missing");
948
+ case "Orphaned":
949
+ return this.parent.oldKey;
950
+ default:
951
+ return assertNever(this.parent, "Unknown state");
1608
952
  }
1609
953
  }
1610
- subscribe(callback) {
1611
- if (this.#eventSource.count() === 0) {
1612
- this.get();
954
+ /** @internal */
955
+ get _parentPos() {
956
+ switch (this.parent.type) {
957
+ case "HasParent":
958
+ return this.parent.pos;
959
+ case "NoParent":
960
+ throw new Error("Parent key is missing");
961
+ case "Orphaned":
962
+ return this.parent.oldPos;
963
+ default:
964
+ return assertNever(this.parent, "Unknown state");
1613
965
  }
1614
- return this.#eventSource.subscribe(callback);
1615
- }
1616
- subscribeOnce(callback) {
1617
- const unsub = this.subscribe(() => {
1618
- unsub();
1619
- return callback();
1620
- });
1621
- return unsub;
1622
966
  }
1623
- waitUntil() {
1624
- throw new Error("waitUntil not supported on Signals");
1625
- }
1626
- markSinksDirty() {
1627
- for (const sink of this[kSinks]) {
1628
- sink.markDirty();
1629
- }
967
+ /** @internal */
968
+ get _pool() {
969
+ return this.#pool;
1630
970
  }
1631
- addSink(sink) {
1632
- this[kSinks].add(sink);
971
+ get roomId() {
972
+ return this.#pool ? this.#pool.roomId : null;
1633
973
  }
1634
- removeSink(sink) {
1635
- this[kSinks].delete(sink);
974
+ /** @internal */
975
+ get _id() {
976
+ return this.#id;
1636
977
  }
1637
- asReadonly() {
1638
- return this;
978
+ /** @internal */
979
+ get parent() {
980
+ return this.#parent;
1639
981
  }
1640
- };
1641
- var INITIAL = Symbol();
1642
- var DerivedSignal = class _DerivedSignal extends AbstractSignal {
1643
- #prevValue;
1644
- #dirty;
1645
- // When true, the value in #value may not be up-to-date and needs re-checking
1646
- #sources;
1647
- #deps;
1648
- #transform;
1649
- // prettier-ignore
1650
- static from(...args) {
1651
- const last = args.pop();
1652
- if (typeof last !== "function")
1653
- raise("Invalid .from() call, last argument expected to be a function");
1654
- if (typeof args[args.length - 1] === "function") {
1655
- const equals = last;
1656
- const transform = args.pop();
1657
- return new _DerivedSignal(args, transform, equals);
1658
- } else {
1659
- const transform = last;
1660
- return new _DerivedSignal(args, transform);
982
+ /** @internal */
983
+ get _parentKey() {
984
+ switch (this.parent.type) {
985
+ case "HasParent":
986
+ return this.parent.key;
987
+ case "NoParent":
988
+ return null;
989
+ case "Orphaned":
990
+ return this.parent.oldKey;
991
+ default:
992
+ return assertNever(this.parent, "Unknown state");
1661
993
  }
1662
994
  }
1663
- constructor(deps, transform, equals) {
1664
- super(equals);
1665
- this.#dirty = true;
1666
- this.#prevValue = INITIAL;
1667
- this.#deps = deps;
1668
- this.#sources = /* @__PURE__ */ new Set();
1669
- this.#transform = transform;
1670
- }
1671
- dispose() {
1672
- for (const src of this.#sources) {
1673
- src.removeSink(this);
995
+ /** @internal */
996
+ _apply(op, _isLocal) {
997
+ switch (op.type) {
998
+ case 5: {
999
+ if (this.parent.type === "HasParent") {
1000
+ return this.parent.node._detachChild(crdtAsLiveNode(this));
1001
+ }
1002
+ return { modified: false };
1003
+ }
1674
1004
  }
1675
- this.#prevValue = "(disposed)";
1676
- this.#sources = "(disposed)";
1677
- this.#deps = "(disposed)";
1678
- this.#transform = "(disposed)";
1679
- }
1680
- get isDirty() {
1681
- return this.#dirty;
1005
+ return { modified: false };
1682
1006
  }
1683
- #recompute() {
1684
- const oldTrackedReads = trackedReads;
1685
- let derived;
1686
- trackedReads = /* @__PURE__ */ new Set();
1687
- try {
1688
- derived = this.#transform(...this.#deps.map((p) => p.get()));
1689
- } finally {
1690
- const oldSources = this.#sources;
1691
- this.#sources = /* @__PURE__ */ new Set();
1692
- for (const sig of trackedReads) {
1693
- this.#sources.add(sig);
1694
- oldSources.delete(sig);
1695
- }
1696
- for (const oldSource of oldSources) {
1697
- oldSource.removeSink(this);
1698
- }
1699
- for (const newSource of this.#sources) {
1700
- newSource.addSink(this);
1007
+ /** @internal */
1008
+ _setParentLink(newParentNode, newParentKey) {
1009
+ switch (this.parent.type) {
1010
+ case "HasParent":
1011
+ if (this.parent.node !== newParentNode) {
1012
+ throw new Error("Cannot set parent: node already has a parent");
1013
+ } else {
1014
+ this.#parent = HasParent(newParentNode, newParentKey);
1015
+ return;
1016
+ }
1017
+ case "Orphaned":
1018
+ case "NoParent": {
1019
+ this.#parent = HasParent(newParentNode, newParentKey);
1020
+ return;
1701
1021
  }
1702
- trackedReads = oldTrackedReads;
1703
- }
1704
- this.#dirty = false;
1705
- if (!this.equals(this.#prevValue, derived)) {
1706
- this.#prevValue = derived;
1707
- return true;
1022
+ default:
1023
+ return assertNever(this.parent, "Unknown state");
1708
1024
  }
1709
- return false;
1710
1025
  }
1711
- markDirty() {
1712
- if (!this.#dirty) {
1713
- this.#dirty = true;
1714
- this.markSinksDirty();
1026
+ /** @internal */
1027
+ _attach(id, pool) {
1028
+ if (this.#id || this.#pool) {
1029
+ throw new Error("Cannot attach node: already attached");
1715
1030
  }
1031
+ pool.addNode(id, crdtAsLiveNode(this));
1032
+ this.#id = id;
1033
+ this.#pool = pool;
1716
1034
  }
1717
- get() {
1718
- if (this.#dirty) {
1719
- this.#recompute();
1720
- }
1721
- trackedReads?.add(this);
1722
- return this.#prevValue;
1035
+ /** @internal */
1036
+ _detach() {
1037
+ if (this.#pool && this.#id) {
1038
+ this.#pool.deleteNode(this.#id);
1039
+ }
1040
+ switch (this.parent.type) {
1041
+ case "HasParent": {
1042
+ this.#parent = Orphaned(this.parent.key, this.parent.pos);
1043
+ break;
1044
+ }
1045
+ case "NoParent": {
1046
+ this.#parent = NoParent;
1047
+ break;
1048
+ }
1049
+ case "Orphaned": {
1050
+ break;
1051
+ }
1052
+ default:
1053
+ assertNever(this.parent, "Unknown state");
1054
+ }
1055
+ this.#pool = void 0;
1723
1056
  }
1057
+ /** This caches the result of the last .toImmutable() call for this Live node. */
1058
+ #cachedImmutable;
1059
+ #cachedTreeNodeKey;
1060
+ /** This caches the result of the last .toTreeNode() call for this Live node. */
1061
+ #cachedTreeNode;
1724
1062
  /**
1725
- * Called by the Signal system if one or more of the dependent signals have
1726
- * changed. In the case of a DerivedSignal, we'll only want to re-evaluate
1727
- * the actual value if it's being watched, or any of their sinks are being
1728
- * watched actively.
1063
+ * @internal
1064
+ *
1065
+ * Clear the Immutable cache, so that the next call to `.toImmutable()` will
1066
+ * recompute the equivalent Immutable value again. Call this after every
1067
+ * mutation to the Live node.
1729
1068
  */
1730
- [kTrigger]() {
1731
- if (!this.hasWatchers) {
1732
- return;
1733
- }
1734
- const updated = this.#recompute();
1735
- if (updated) {
1736
- super[kTrigger]();
1069
+ invalidate() {
1070
+ if (this.#cachedImmutable !== void 0 || this.#cachedTreeNode !== void 0) {
1071
+ this.#cachedImmutable = void 0;
1072
+ this.#cachedTreeNode = void 0;
1073
+ if (this.parent.type === "HasParent") {
1074
+ this.parent.node.invalidate();
1075
+ }
1737
1076
  }
1738
1077
  }
1739
- };
1740
- function assertNever(_value, errmsg) {
1741
- throw new Error(errmsg);
1742
- }
1743
- function assert2(condition, errmsg) {
1744
- if (process.env.NODE_ENV !== "production") {
1745
- if (!condition) {
1746
- const err = new Error(errmsg);
1747
- err.name = "Assertion failure";
1748
- throw err;
1078
+ /**
1079
+ * @internal
1080
+ *
1081
+ * Return an snapshot of this Live tree for use in DevTools.
1082
+ */
1083
+ toTreeNode(key) {
1084
+ if (this.#cachedTreeNode === void 0 || this.#cachedTreeNodeKey !== key) {
1085
+ this.#cachedTreeNodeKey = key;
1086
+ this.#cachedTreeNode = this._toTreeNode(key);
1749
1087
  }
1088
+ return this.#cachedTreeNode;
1750
1089
  }
1751
- }
1752
- function nn(value, errmsg = "Expected value to be non-nullable") {
1753
- assert2(value !== null && value !== void 0, errmsg);
1754
- return value;
1755
- }
1756
- var fancy_console_exports = {};
1757
- __export(fancy_console_exports, {
1758
- error: () => error2,
1759
- errorWithTitle: () => errorWithTitle,
1760
- warn: () => warn,
1761
- warnWithTitle: () => warnWithTitle
1762
- });
1763
- var badge = "background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;";
1764
- var bold = "font-weight:600";
1765
- function wrap(method) {
1766
- return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
1767
- /* istanbul ignore next */
1768
- (message, ...args) => console[method]("%cLiveblocks", badge, message, ...args)
1769
- );
1770
- }
1771
- var warn = wrap("warn");
1772
- var error2 = wrap("error");
1773
- function wrapWithTitle(method) {
1774
- return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
1775
- /* istanbul ignore next */
1776
- (title, message, ...args) => console[method](
1777
- `%cLiveblocks%c ${title}`,
1778
- badge,
1779
- bold,
1780
- message,
1781
- ...args
1782
- )
1783
- );
1784
- }
1785
- var warnWithTitle = wrapWithTitle("warn");
1786
- var errorWithTitle = wrapWithTitle("error");
1787
- var nanoid = (t = 21) => crypto.getRandomValues(new Uint8Array(t)).reduce(
1788
- (t2, e) => t2 += (e &= 63) < 36 ? e.toString(36) : e < 62 ? (e - 26).toString(36).toUpperCase() : e < 63 ? "_" : "-",
1789
- ""
1790
- );
1791
- var BACKOFF_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4];
1792
- var RESET_DELAY = BACKOFF_DELAYS[0] - 1;
1793
- function log(level, message) {
1794
- const logger = level === 2 ? error2 : level === 1 ? warn : (
1795
- /* black hole */
1796
- () => {
1090
+ /**
1091
+ * Return an immutable snapshot of this Live node and its children.
1092
+ */
1093
+ toImmutable() {
1094
+ if (this.#cachedImmutable === void 0) {
1095
+ this.#cachedImmutable = this._toImmutable();
1797
1096
  }
1798
- );
1799
- return () => {
1800
- logger(message);
1801
- };
1097
+ return this.#cachedImmutable;
1098
+ }
1099
+ };
1100
+ function isRootCrdt(crdt) {
1101
+ return crdt.type === 0 && !isChildCrdt(crdt);
1802
1102
  }
1803
- var logPermanentClose = log(
1804
- 1,
1805
- "Connection to WebSocket closed permanently. Won't retry."
1806
- );
1807
- var kInternal = Symbol();
1808
- var EMPTY_OBJECT = Object.freeze({});
1809
- var NULL_KEYWORD_CHARS = Array.from(new Set("null"));
1810
- var TRUE_KEYWORD_CHARS = Array.from(new Set("true"));
1811
- var FALSE_KEYWORD_CHARS = Array.from(new Set("false"));
1812
- var ALL_KEYWORD_CHARS = Array.from(new Set("nulltruefalse"));
1813
- var kWILDCARD = Symbol("*");
1814
- var eventSource = makeEventSource();
1815
- if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
1816
- window.addEventListener("message", (event) => {
1817
- if (event.source === window && event.data?.source === "liveblocks-devtools-panel") {
1818
- eventSource.notify(event.data);
1819
- } else {
1820
- }
1821
- });
1103
+ function isChildCrdt(crdt) {
1104
+ return crdt.parentId !== void 0 && crdt.parentKey !== void 0;
1822
1105
  }
1823
- var onMessageFromPanel = eventSource.observable;
1824
- var loadedAt = Date.now();
1825
- var kPlain = Symbol("notification-settings-plain");
1826
- var MIN_CODE = 32;
1827
- var MAX_CODE = 126;
1828
- var NUM_DIGITS = MAX_CODE - MIN_CODE + 1;
1829
- var ZERO = nthDigit(0);
1830
- var ONE = nthDigit(1);
1831
- var ZERO_NINE = ZERO + nthDigit(-1);
1832
- function nthDigit(n) {
1833
- const code = MIN_CODE + (n < 0 ? NUM_DIGITS + n : n);
1834
- if (code < MIN_CODE || code > MAX_CODE) {
1835
- throw new Error(`Invalid n value: ${n}`);
1106
+ var LiveRegister = class _LiveRegister extends AbstractCrdt {
1107
+ #data;
1108
+ constructor(data) {
1109
+ super();
1110
+ this.#data = data;
1836
1111
  }
1837
- return String.fromCharCode(code);
1838
- }
1839
- function makePosition(x, y) {
1840
- if (x !== void 0 && y !== void 0) {
1841
- return between(x, y);
1842
- } else if (x !== void 0) {
1843
- return after(x);
1844
- } else if (y !== void 0) {
1845
- return before(y);
1846
- } else {
1847
- return ONE;
1112
+ get data() {
1113
+ return this.#data;
1848
1114
  }
1849
- }
1850
- function before(pos) {
1851
- const lastIndex = pos.length - 1;
1852
- for (let i = 0; i <= lastIndex; i++) {
1853
- const code = pos.charCodeAt(i);
1854
- if (code <= MIN_CODE) {
1855
- continue;
1115
+ /** @internal */
1116
+ static _deserialize([id, item], _parentToChildren, pool) {
1117
+ const register = new _LiveRegister(item.data);
1118
+ register._attach(id, pool);
1119
+ return register;
1120
+ }
1121
+ /** @internal */
1122
+ _toOps(parentId, parentKey, pool) {
1123
+ if (this._id === void 0) {
1124
+ throw new Error(
1125
+ "Cannot serialize register if parentId or parentKey is undefined"
1126
+ );
1856
1127
  }
1857
- if (i === lastIndex) {
1858
- if (code === MIN_CODE + 1) {
1859
- return pos.substring(0, i) + ZERO_NINE;
1860
- } else {
1861
- return pos.substring(0, i) + String.fromCharCode(code - 1);
1128
+ return [
1129
+ {
1130
+ type: 8,
1131
+ opId: pool?.generateOpId(),
1132
+ id: this._id,
1133
+ parentId,
1134
+ parentKey,
1135
+ data: this.data
1862
1136
  }
1863
- } else {
1864
- return pos.substring(0, i + 1);
1865
- }
1137
+ ];
1866
1138
  }
1867
- return ONE;
1868
- }
1869
- function after(pos) {
1870
- for (let i = 0; i <= pos.length - 1; i++) {
1871
- const code = pos.charCodeAt(i);
1872
- if (code >= MAX_CODE) {
1873
- continue;
1139
+ /** @internal */
1140
+ _serialize() {
1141
+ if (this.parent.type !== "HasParent") {
1142
+ throw new Error("Cannot serialize LiveRegister if parent is missing");
1874
1143
  }
1875
- return pos.substring(0, i) + String.fromCharCode(code + 1);
1144
+ return {
1145
+ type: 3,
1146
+ parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
1147
+ parentKey: this.parent.key,
1148
+ data: this.data
1149
+ };
1876
1150
  }
1877
- return pos + ONE;
1878
- }
1879
- function between(lo, hi) {
1880
- if (lo < hi) {
1881
- return _between(lo, hi);
1882
- } else if (lo > hi) {
1883
- return _between(hi, lo);
1884
- } else {
1885
- throw new Error("Cannot compute value between two equal positions");
1151
+ /** @internal */
1152
+ _attachChild(_op) {
1153
+ throw new Error("Method not implemented.");
1886
1154
  }
1887
- }
1888
- function _between(lo, hi) {
1889
- let index = 0;
1890
- const loLen = lo.length;
1891
- const hiLen = hi.length;
1892
- while (true) {
1893
- const loCode = index < loLen ? lo.charCodeAt(index) : MIN_CODE;
1894
- const hiCode = index < hiLen ? hi.charCodeAt(index) : MAX_CODE;
1895
- if (loCode === hiCode) {
1896
- index++;
1897
- continue;
1898
- }
1899
- if (hiCode - loCode === 1) {
1900
- const size = index + 1;
1901
- let prefix = lo.substring(0, size);
1902
- if (prefix.length < size) {
1903
- prefix += ZERO.repeat(size - prefix.length);
1904
- }
1905
- const suffix = lo.substring(size);
1906
- const nines = "";
1907
- return prefix + _between(suffix, nines);
1908
- } else {
1909
- return takeN(lo, index) + String.fromCharCode(hiCode + loCode >> 1);
1910
- }
1911
- }
1912
- }
1913
- function takeN(pos, n) {
1914
- return n < pos.length ? pos.substring(0, n) : pos + ZERO.repeat(n - pos.length);
1915
- }
1916
- var MIN_NON_ZERO_CODE = MIN_CODE + 1;
1917
- function isPos(str) {
1918
- if (str === "") {
1919
- return false;
1920
- }
1921
- const lastIdx = str.length - 1;
1922
- const last = str.charCodeAt(lastIdx);
1923
- if (last < MIN_NON_ZERO_CODE || last > MAX_CODE) {
1924
- return false;
1925
- }
1926
- for (let i = 0; i < lastIdx; i++) {
1927
- const code = str.charCodeAt(i);
1928
- if (code < MIN_CODE || code > MAX_CODE) {
1929
- return false;
1930
- }
1931
- }
1932
- return true;
1933
- }
1934
- function convertToPos(str) {
1935
- const codes2 = [];
1936
- for (let i = 0; i < str.length; i++) {
1937
- const code = str.charCodeAt(i);
1938
- codes2.push(code < MIN_CODE ? MIN_CODE : code > MAX_CODE ? MAX_CODE : code);
1939
- }
1940
- while (codes2.length > 0 && codes2[codes2.length - 1] === MIN_CODE) {
1941
- codes2.length--;
1942
- }
1943
- return codes2.length > 0 ? String.fromCharCode(...codes2) : (
1944
- // Edge case: the str was a 0-only string, which is invalid. Default back to .1
1945
- ONE
1946
- );
1947
- }
1948
- function asPos(str) {
1949
- return isPos(str) ? str : convertToPos(str);
1950
- }
1951
- function crdtAsLiveNode(value) {
1952
- return value;
1953
- }
1954
- function HasParent(node, key, pos = asPos(key)) {
1955
- return Object.freeze({ type: "HasParent", node, key, pos });
1956
- }
1957
- var NoParent = Object.freeze({ type: "NoParent" });
1958
- function Orphaned(oldKey, oldPos = asPos(oldKey)) {
1959
- return Object.freeze({ type: "Orphaned", oldKey, oldPos });
1960
- }
1961
- var AbstractCrdt = class {
1962
- // ^^^^^^^^^^^^ TODO: Make this an interface
1963
- #pool;
1964
- #id;
1965
- #parent = NoParent;
1966
1155
  /** @internal */
1967
- _getParentKeyOrThrow() {
1968
- switch (this.parent.type) {
1969
- case "HasParent":
1970
- return this.parent.key;
1971
- case "NoParent":
1972
- throw new Error("Parent key is missing");
1973
- case "Orphaned":
1974
- return this.parent.oldKey;
1975
- default:
1976
- return assertNever(this.parent, "Unknown state");
1977
- }
1156
+ _detachChild(_crdt) {
1157
+ throw new Error("Method not implemented.");
1978
1158
  }
1979
1159
  /** @internal */
1980
- get _parentPos() {
1981
- switch (this.parent.type) {
1982
- case "HasParent":
1983
- return this.parent.pos;
1984
- case "NoParent":
1985
- throw new Error("Parent key is missing");
1986
- case "Orphaned":
1987
- return this.parent.oldPos;
1988
- default:
1989
- return assertNever(this.parent, "Unknown state");
1990
- }
1160
+ _apply(op, isLocal) {
1161
+ return super._apply(op, isLocal);
1991
1162
  }
1992
1163
  /** @internal */
1993
- get _pool() {
1994
- return this.#pool;
1995
- }
1996
- get roomId() {
1997
- return this.#pool ? this.#pool.roomId : null;
1164
+ _toTreeNode(key) {
1165
+ return {
1166
+ type: "Json",
1167
+ id: this._id ?? nanoid(),
1168
+ key,
1169
+ payload: this.#data
1170
+ };
1998
1171
  }
1999
1172
  /** @internal */
2000
- get _id() {
2001
- return this.#id;
1173
+ _toImmutable() {
1174
+ return this.#data;
2002
1175
  }
2003
- /** @internal */
2004
- get parent() {
2005
- return this.#parent;
1176
+ clone() {
1177
+ return deepClone(this.data);
2006
1178
  }
2007
- /** @internal */
2008
- get _parentKey() {
2009
- switch (this.parent.type) {
2010
- case "HasParent":
2011
- return this.parent.key;
2012
- case "NoParent":
2013
- return null;
2014
- case "Orphaned":
2015
- return this.parent.oldKey;
2016
- default:
2017
- return assertNever(this.parent, "Unknown state");
1179
+ };
1180
+ function compareNodePosition(itemA, itemB) {
1181
+ const posA = itemA._parentPos;
1182
+ const posB = itemB._parentPos;
1183
+ return posA === posB ? 0 : posA < posB ? -1 : 1;
1184
+ }
1185
+ var LiveList = class _LiveList extends AbstractCrdt {
1186
+ // TODO: Naive array at first, find a better data structure. Maybe an Order statistics tree?
1187
+ #items;
1188
+ #implicitlyDeletedItems;
1189
+ #unacknowledgedSets;
1190
+ constructor(items) {
1191
+ super();
1192
+ this.#items = [];
1193
+ this.#implicitlyDeletedItems = /* @__PURE__ */ new WeakSet();
1194
+ this.#unacknowledgedSets = /* @__PURE__ */ new Map();
1195
+ let position = void 0;
1196
+ for (const item of items) {
1197
+ const newPosition = makePosition(position);
1198
+ const node = lsonToLiveNode(item);
1199
+ node._setParentLink(this, newPosition);
1200
+ this.#items.push(node);
1201
+ position = newPosition;
2018
1202
  }
2019
1203
  }
2020
1204
  /** @internal */
2021
- _apply(op, _isLocal) {
2022
- switch (op.type) {
2023
- case 5: {
2024
- if (this.parent.type === "HasParent") {
2025
- return this.parent.node._detachChild(crdtAsLiveNode(this));
2026
- }
2027
- return { modified: false };
2028
- }
1205
+ static _deserialize([id], parentToChildren, pool) {
1206
+ const list = new _LiveList([]);
1207
+ list._attach(id, pool);
1208
+ const children = parentToChildren.get(id);
1209
+ if (children === void 0) {
1210
+ return list;
2029
1211
  }
2030
- return { modified: false };
1212
+ for (const [id2, crdt] of children) {
1213
+ const child = deserialize([id2, crdt], parentToChildren, pool);
1214
+ child._setParentLink(list, crdt.parentKey);
1215
+ list._insertAndSort(child);
1216
+ }
1217
+ return list;
2031
1218
  }
2032
- /** @internal */
2033
- _setParentLink(newParentNode, newParentKey) {
2034
- switch (this.parent.type) {
2035
- case "HasParent":
2036
- if (this.parent.node !== newParentNode) {
2037
- throw new Error("Cannot set parent: node already has a parent");
2038
- } else {
2039
- this.#parent = HasParent(newParentNode, newParentKey);
2040
- return;
2041
- }
2042
- case "Orphaned":
2043
- case "NoParent": {
2044
- this.#parent = HasParent(newParentNode, newParentKey);
2045
- return;
1219
+ /**
1220
+ * @internal
1221
+ * This function assumes that the resulting ops will be sent to the server if they have an 'opId'
1222
+ * so we mutate _unacknowledgedSets to avoid potential flickering
1223
+ * https://github.com/liveblocks/liveblocks/pull/1177
1224
+ *
1225
+ * This is quite unintuitive and should disappear as soon as
1226
+ * we introduce an explicit LiveList.Set operation
1227
+ */
1228
+ _toOps(parentId, parentKey, pool) {
1229
+ if (this._id === void 0) {
1230
+ throw new Error("Cannot serialize item is not attached");
1231
+ }
1232
+ const ops = [];
1233
+ const op = {
1234
+ id: this._id,
1235
+ opId: pool?.generateOpId(),
1236
+ type: 2,
1237
+ parentId,
1238
+ parentKey
1239
+ };
1240
+ ops.push(op);
1241
+ for (const item of this.#items) {
1242
+ const parentKey2 = item._getParentKeyOrThrow();
1243
+ const childOps = HACK_addIntentAndDeletedIdToOperation(
1244
+ item._toOps(this._id, parentKey2, pool),
1245
+ void 0
1246
+ );
1247
+ const childOpId = childOps[0].opId;
1248
+ if (childOpId !== void 0) {
1249
+ this.#unacknowledgedSets.set(parentKey2, childOpId);
2046
1250
  }
2047
- default:
2048
- return assertNever(this.parent, "Unknown state");
1251
+ ops.push(...childOps);
2049
1252
  }
1253
+ return ops;
1254
+ }
1255
+ /**
1256
+ * @internal
1257
+ *
1258
+ * Adds a new item into the sorted list, in the correct position.
1259
+ */
1260
+ _insertAndSort(item) {
1261
+ this.#items.push(item);
1262
+ this._sortItems();
1263
+ }
1264
+ /** @internal */
1265
+ _sortItems() {
1266
+ this.#items.sort(compareNodePosition);
1267
+ this.invalidate();
1268
+ }
1269
+ /** @internal */
1270
+ _indexOfPosition(position) {
1271
+ return this.#items.findIndex(
1272
+ (item) => item._getParentKeyOrThrow() === position
1273
+ );
2050
1274
  }
2051
1275
  /** @internal */
2052
1276
  _attach(id, pool) {
2053
- if (this.#id || this.#pool) {
2054
- throw new Error("Cannot attach node: already attached");
1277
+ super._attach(id, pool);
1278
+ for (const item of this.#items) {
1279
+ item._attach(pool.generateId(), pool);
2055
1280
  }
2056
- pool.addNode(id, crdtAsLiveNode(this));
2057
- this.#id = id;
2058
- this.#pool = pool;
2059
1281
  }
2060
1282
  /** @internal */
2061
1283
  _detach() {
2062
- if (this.#pool && this.#id) {
2063
- this.#pool.deleteNode(this.#id);
2064
- }
2065
- switch (this.parent.type) {
2066
- case "HasParent": {
2067
- this.#parent = Orphaned(this.parent.key, this.parent.pos);
2068
- break;
2069
- }
2070
- case "NoParent": {
2071
- this.#parent = NoParent;
2072
- break;
2073
- }
2074
- case "Orphaned": {
2075
- break;
2076
- }
2077
- default:
2078
- assertNever(this.parent, "Unknown state");
2079
- }
2080
- this.#pool = void 0;
2081
- }
2082
- /** This caches the result of the last .toImmutable() call for this Live node. */
2083
- #cachedImmutable;
2084
- #cachedTreeNodeKey;
2085
- /** This caches the result of the last .toTreeNode() call for this Live node. */
2086
- #cachedTreeNode;
2087
- /**
2088
- * @internal
2089
- *
2090
- * Clear the Immutable cache, so that the next call to `.toImmutable()` will
2091
- * recompute the equivalent Immutable value again. Call this after every
2092
- * mutation to the Live node.
2093
- */
2094
- invalidate() {
2095
- if (this.#cachedImmutable !== void 0 || this.#cachedTreeNode !== void 0) {
2096
- this.#cachedImmutable = void 0;
2097
- this.#cachedTreeNode = void 0;
2098
- if (this.parent.type === "HasParent") {
2099
- this.parent.node.invalidate();
2100
- }
2101
- }
2102
- }
2103
- /**
2104
- * @internal
2105
- *
2106
- * Return an snapshot of this Live tree for use in DevTools.
2107
- */
2108
- toTreeNode(key) {
2109
- if (this.#cachedTreeNode === void 0 || this.#cachedTreeNodeKey !== key) {
2110
- this.#cachedTreeNodeKey = key;
2111
- this.#cachedTreeNode = this._toTreeNode(key);
2112
- }
2113
- return this.#cachedTreeNode;
2114
- }
2115
- /**
2116
- * Return an immutable snapshot of this Live node and its children.
2117
- */
2118
- toImmutable() {
2119
- if (this.#cachedImmutable === void 0) {
2120
- this.#cachedImmutable = this._toImmutable();
2121
- }
2122
- return this.#cachedImmutable;
2123
- }
2124
- };
2125
- function isRootCrdt(crdt) {
2126
- return crdt.type === 0 && !isChildCrdt(crdt);
2127
- }
2128
- function isChildCrdt(crdt) {
2129
- return crdt.parentId !== void 0 && crdt.parentKey !== void 0;
2130
- }
2131
- var LiveRegister = class _LiveRegister extends AbstractCrdt {
2132
- #data;
2133
- constructor(data) {
2134
- super();
2135
- this.#data = data;
2136
- }
2137
- get data() {
2138
- return this.#data;
2139
- }
2140
- /** @internal */
2141
- static _deserialize([id, item], _parentToChildren, pool) {
2142
- const register = new _LiveRegister(item.data);
2143
- register._attach(id, pool);
2144
- return register;
2145
- }
2146
- /** @internal */
2147
- _toOps(parentId, parentKey, pool) {
2148
- if (this._id === void 0) {
2149
- throw new Error(
2150
- "Cannot serialize register if parentId or parentKey is undefined"
2151
- );
2152
- }
2153
- return [
2154
- {
2155
- type: 8,
2156
- opId: pool?.generateOpId(),
2157
- id: this._id,
2158
- parentId,
2159
- parentKey,
2160
- data: this.data
2161
- }
2162
- ];
2163
- }
2164
- /** @internal */
2165
- _serialize() {
2166
- if (this.parent.type !== "HasParent") {
2167
- throw new Error("Cannot serialize LiveRegister if parent is missing");
2168
- }
2169
- return {
2170
- type: 3,
2171
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
2172
- parentKey: this.parent.key,
2173
- data: this.data
2174
- };
2175
- }
2176
- /** @internal */
2177
- _attachChild(_op) {
2178
- throw new Error("Method not implemented.");
2179
- }
2180
- /** @internal */
2181
- _detachChild(_crdt) {
2182
- throw new Error("Method not implemented.");
2183
- }
2184
- /** @internal */
2185
- _apply(op, isLocal) {
2186
- return super._apply(op, isLocal);
2187
- }
2188
- /** @internal */
2189
- _toTreeNode(key) {
2190
- return {
2191
- type: "Json",
2192
- id: this._id ?? nanoid(),
2193
- key,
2194
- payload: this.#data
2195
- };
2196
- }
2197
- /** @internal */
2198
- _toImmutable() {
2199
- return this.#data;
2200
- }
2201
- clone() {
2202
- return deepClone(this.data);
2203
- }
2204
- };
2205
- function compareNodePosition(itemA, itemB) {
2206
- const posA = itemA._parentPos;
2207
- const posB = itemB._parentPos;
2208
- return posA === posB ? 0 : posA < posB ? -1 : 1;
2209
- }
2210
- var LiveList = class _LiveList extends AbstractCrdt {
2211
- // TODO: Naive array at first, find a better data structure. Maybe an Order statistics tree?
2212
- #items;
2213
- #implicitlyDeletedItems;
2214
- #unacknowledgedSets;
2215
- constructor(items) {
2216
- super();
2217
- this.#items = [];
2218
- this.#implicitlyDeletedItems = /* @__PURE__ */ new WeakSet();
2219
- this.#unacknowledgedSets = /* @__PURE__ */ new Map();
2220
- let position = void 0;
2221
- for (const item of items) {
2222
- const newPosition = makePosition(position);
2223
- const node = lsonToLiveNode(item);
2224
- node._setParentLink(this, newPosition);
2225
- this.#items.push(node);
2226
- position = newPosition;
2227
- }
2228
- }
2229
- /** @internal */
2230
- static _deserialize([id], parentToChildren, pool) {
2231
- const list = new _LiveList([]);
2232
- list._attach(id, pool);
2233
- const children = parentToChildren.get(id);
2234
- if (children === void 0) {
2235
- return list;
2236
- }
2237
- for (const [id2, crdt] of children) {
2238
- const child = deserialize([id2, crdt], parentToChildren, pool);
2239
- child._setParentLink(list, crdt.parentKey);
2240
- list._insertAndSort(child);
2241
- }
2242
- return list;
2243
- }
2244
- /**
2245
- * @internal
2246
- * This function assumes that the resulting ops will be sent to the server if they have an 'opId'
2247
- * so we mutate _unacknowledgedSets to avoid potential flickering
2248
- * https://github.com/liveblocks/liveblocks/pull/1177
2249
- *
2250
- * This is quite unintuitive and should disappear as soon as
2251
- * we introduce an explicit LiveList.Set operation
2252
- */
2253
- _toOps(parentId, parentKey, pool) {
2254
- if (this._id === void 0) {
2255
- throw new Error("Cannot serialize item is not attached");
2256
- }
2257
- const ops = [];
2258
- const op = {
2259
- id: this._id,
2260
- opId: pool?.generateOpId(),
2261
- type: 2,
2262
- parentId,
2263
- parentKey
2264
- };
2265
- ops.push(op);
2266
- for (const item of this.#items) {
2267
- const parentKey2 = item._getParentKeyOrThrow();
2268
- const childOps = HACK_addIntentAndDeletedIdToOperation(
2269
- item._toOps(this._id, parentKey2, pool),
2270
- void 0
2271
- );
2272
- const childOpId = childOps[0].opId;
2273
- if (childOpId !== void 0) {
2274
- this.#unacknowledgedSets.set(parentKey2, childOpId);
2275
- }
2276
- ops.push(...childOps);
2277
- }
2278
- return ops;
2279
- }
2280
- /**
2281
- * @internal
2282
- *
2283
- * Adds a new item into the sorted list, in the correct position.
2284
- */
2285
- _insertAndSort(item) {
2286
- this.#items.push(item);
2287
- this._sortItems();
2288
- }
2289
- /** @internal */
2290
- _sortItems() {
2291
- this.#items.sort(compareNodePosition);
2292
- this.invalidate();
2293
- }
2294
- /** @internal */
2295
- _indexOfPosition(position) {
2296
- return this.#items.findIndex(
2297
- (item) => item._getParentKeyOrThrow() === position
2298
- );
2299
- }
2300
- /** @internal */
2301
- _attach(id, pool) {
2302
- super._attach(id, pool);
2303
- for (const item of this.#items) {
2304
- item._attach(pool.generateId(), pool);
2305
- }
2306
- }
2307
- /** @internal */
2308
- _detach() {
2309
- super._detach();
2310
- for (const item of this.#items) {
2311
- item._detach();
1284
+ super._detach();
1285
+ for (const item of this.#items) {
1286
+ item._detach();
2312
1287
  }
2313
1288
  }
2314
1289
  #applySetRemote(op) {
@@ -3814,415 +2789,1461 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3814
2789
  if (isLiveNode(oldValue)) {
3815
2790
  oldValue._detach();
3816
2791
  }
3817
- isModified = true;
3818
- updateDelta[key] = { type: "update" };
3819
- this.#map.set(key, value);
3820
- this.invalidate();
3821
- }
3822
- if (Object.keys(reverseUpdate.data).length !== 0) {
3823
- reverse.unshift(reverseUpdate);
3824
- }
3825
- return isModified ? {
3826
- modified: {
3827
- node: this,
3828
- type: "LiveObject",
3829
- updates: updateDelta
3830
- },
3831
- reverse
3832
- } : { modified: false };
3833
- }
3834
- #applyDeleteObjectKey(op, isLocal) {
3835
- const key = op.key;
3836
- if (this.#map.has(key) === false) {
3837
- return { modified: false };
3838
- }
3839
- if (!isLocal && this.#propToLastUpdate.get(key) !== void 0) {
3840
- return { modified: false };
2792
+ isModified = true;
2793
+ updateDelta[key] = { type: "update" };
2794
+ this.#map.set(key, value);
2795
+ this.invalidate();
2796
+ }
2797
+ if (Object.keys(reverseUpdate.data).length !== 0) {
2798
+ reverse.unshift(reverseUpdate);
2799
+ }
2800
+ return isModified ? {
2801
+ modified: {
2802
+ node: this,
2803
+ type: "LiveObject",
2804
+ updates: updateDelta
2805
+ },
2806
+ reverse
2807
+ } : { modified: false };
2808
+ }
2809
+ #applyDeleteObjectKey(op, isLocal) {
2810
+ const key = op.key;
2811
+ if (this.#map.has(key) === false) {
2812
+ return { modified: false };
2813
+ }
2814
+ if (!isLocal && this.#propToLastUpdate.get(key) !== void 0) {
2815
+ return { modified: false };
2816
+ }
2817
+ const oldValue = this.#map.get(key);
2818
+ const id = nn(this._id);
2819
+ let reverse = [];
2820
+ if (isLiveNode(oldValue)) {
2821
+ reverse = oldValue._toOps(id, op.key);
2822
+ oldValue._detach();
2823
+ } else if (oldValue !== void 0) {
2824
+ reverse = [
2825
+ {
2826
+ type: 3,
2827
+ id,
2828
+ data: { [key]: oldValue }
2829
+ }
2830
+ ];
2831
+ }
2832
+ this.#map.delete(key);
2833
+ this.invalidate();
2834
+ return {
2835
+ modified: {
2836
+ node: this,
2837
+ type: "LiveObject",
2838
+ updates: { [op.key]: { type: "delete" } }
2839
+ },
2840
+ reverse
2841
+ };
2842
+ }
2843
+ /**
2844
+ * Transform the LiveObject into a javascript object
2845
+ */
2846
+ toObject() {
2847
+ return Object.fromEntries(this.#map);
2848
+ }
2849
+ /**
2850
+ * Adds or updates a property with a specified key and a value.
2851
+ * @param key The key of the property to add
2852
+ * @param value The value of the property to add
2853
+ */
2854
+ set(key, value) {
2855
+ this._pool?.assertStorageIsWritable();
2856
+ this.update({ [key]: value });
2857
+ }
2858
+ /**
2859
+ * Returns a specified property from the LiveObject.
2860
+ * @param key The key of the property to get
2861
+ */
2862
+ get(key) {
2863
+ return this.#map.get(key);
2864
+ }
2865
+ /**
2866
+ * Deletes a key from the LiveObject
2867
+ * @param key The key of the property to delete
2868
+ */
2869
+ delete(key) {
2870
+ this._pool?.assertStorageIsWritable();
2871
+ const keyAsString = key;
2872
+ const oldValue = this.#map.get(keyAsString);
2873
+ if (oldValue === void 0) {
2874
+ return;
2875
+ }
2876
+ if (this._pool === void 0 || this._id === void 0) {
2877
+ if (isLiveNode(oldValue)) {
2878
+ oldValue._detach();
2879
+ }
2880
+ this.#map.delete(keyAsString);
2881
+ this.invalidate();
2882
+ return;
2883
+ }
2884
+ let reverse;
2885
+ if (isLiveNode(oldValue)) {
2886
+ oldValue._detach();
2887
+ reverse = oldValue._toOps(this._id, keyAsString);
2888
+ } else {
2889
+ reverse = [
2890
+ {
2891
+ type: 3,
2892
+ data: { [keyAsString]: oldValue },
2893
+ id: this._id
2894
+ }
2895
+ ];
2896
+ }
2897
+ this.#map.delete(keyAsString);
2898
+ this.invalidate();
2899
+ const storageUpdates = /* @__PURE__ */ new Map();
2900
+ storageUpdates.set(this._id, {
2901
+ node: this,
2902
+ type: "LiveObject",
2903
+ updates: { [key]: { type: "delete" } }
2904
+ });
2905
+ this._pool.dispatch(
2906
+ [
2907
+ {
2908
+ type: 6,
2909
+ key: keyAsString,
2910
+ id: this._id,
2911
+ opId: this._pool.generateOpId()
2912
+ }
2913
+ ],
2914
+ reverse,
2915
+ storageUpdates
2916
+ );
2917
+ }
2918
+ /**
2919
+ * Adds or updates multiple properties at once with an object.
2920
+ * @param patch The object used to overrides properties
2921
+ */
2922
+ update(patch) {
2923
+ this._pool?.assertStorageIsWritable();
2924
+ if (_LiveObject.detectLargeObjects) {
2925
+ const data = {};
2926
+ for (const [key, value] of this.#map) {
2927
+ if (!isLiveNode(value)) {
2928
+ data[key] = value;
2929
+ }
2930
+ }
2931
+ for (const key of Object.keys(patch)) {
2932
+ const value = patch[key];
2933
+ if (value === void 0)
2934
+ continue;
2935
+ if (!isLiveNode(value)) {
2936
+ data[key] = value;
2937
+ }
2938
+ }
2939
+ const jsonString = JSON.stringify(data);
2940
+ const upperBoundSize = jsonString.length * 4;
2941
+ if (upperBoundSize > MAX_LIVE_OBJECT_SIZE) {
2942
+ const preciseSize = new TextEncoder().encode(jsonString).length;
2943
+ if (preciseSize > MAX_LIVE_OBJECT_SIZE) {
2944
+ throw new Error(
2945
+ `LiveObject size exceeded limit: ${preciseSize} bytes > ${MAX_LIVE_OBJECT_SIZE} bytes. See https://liveblocks.io/docs/platform/limits#Liveblocks-Storage-limits`
2946
+ );
2947
+ }
2948
+ }
2949
+ }
2950
+ if (this._pool === void 0 || this._id === void 0) {
2951
+ for (const key in patch) {
2952
+ const newValue = patch[key];
2953
+ if (newValue === void 0) {
2954
+ continue;
2955
+ }
2956
+ const oldValue = this.#map.get(key);
2957
+ if (isLiveNode(oldValue)) {
2958
+ oldValue._detach();
2959
+ }
2960
+ if (isLiveNode(newValue)) {
2961
+ newValue._setParentLink(this, key);
2962
+ }
2963
+ this.#map.set(key, newValue);
2964
+ this.invalidate();
2965
+ }
2966
+ return;
2967
+ }
2968
+ const ops = [];
2969
+ const reverseOps = [];
2970
+ const opId = this._pool.generateOpId();
2971
+ const updatedProps = {};
2972
+ const reverseUpdateOp = {
2973
+ id: this._id,
2974
+ type: 3,
2975
+ data: {}
2976
+ };
2977
+ const updateDelta = {};
2978
+ for (const key in patch) {
2979
+ const newValue = patch[key];
2980
+ if (newValue === void 0) {
2981
+ continue;
2982
+ }
2983
+ const oldValue = this.#map.get(key);
2984
+ if (isLiveNode(oldValue)) {
2985
+ reverseOps.push(...oldValue._toOps(this._id, key));
2986
+ oldValue._detach();
2987
+ } else if (oldValue === void 0) {
2988
+ reverseOps.push({ type: 6, id: this._id, key });
2989
+ } else {
2990
+ reverseUpdateOp.data[key] = oldValue;
2991
+ }
2992
+ if (isLiveNode(newValue)) {
2993
+ newValue._setParentLink(this, key);
2994
+ newValue._attach(this._pool.generateId(), this._pool);
2995
+ const newAttachChildOps = newValue._toOps(this._id, key, this._pool);
2996
+ const createCrdtOp = newAttachChildOps.find(
2997
+ (op) => op.parentId === this._id
2998
+ );
2999
+ if (createCrdtOp) {
3000
+ this.#propToLastUpdate.set(key, nn(createCrdtOp.opId));
3001
+ }
3002
+ ops.push(...newAttachChildOps);
3003
+ } else {
3004
+ updatedProps[key] = newValue;
3005
+ this.#propToLastUpdate.set(key, opId);
3006
+ }
3007
+ this.#map.set(key, newValue);
3008
+ this.invalidate();
3009
+ updateDelta[key] = { type: "update" };
3010
+ }
3011
+ if (Object.keys(reverseUpdateOp.data).length !== 0) {
3012
+ reverseOps.unshift(reverseUpdateOp);
3013
+ }
3014
+ if (Object.keys(updatedProps).length !== 0) {
3015
+ ops.unshift({
3016
+ opId,
3017
+ id: this._id,
3018
+ type: 3,
3019
+ data: updatedProps
3020
+ });
3021
+ }
3022
+ const storageUpdates = /* @__PURE__ */ new Map();
3023
+ storageUpdates.set(this._id, {
3024
+ node: this,
3025
+ type: "LiveObject",
3026
+ updates: updateDelta
3027
+ });
3028
+ this._pool.dispatch(ops, reverseOps, storageUpdates);
3029
+ }
3030
+ toImmutable() {
3031
+ return super.toImmutable();
3032
+ }
3033
+ /** @internal */
3034
+ toTreeNode(key) {
3035
+ return super.toTreeNode(key);
3036
+ }
3037
+ /** @internal */
3038
+ _toTreeNode(key) {
3039
+ const nodeId = this._id ?? nanoid();
3040
+ return {
3041
+ type: "LiveObject",
3042
+ id: nodeId,
3043
+ key,
3044
+ payload: Array.from(this.#map.entries()).map(
3045
+ ([key2, value]) => isLiveNode(value) ? value.toTreeNode(key2) : { type: "Json", id: `${nodeId}:${key2}`, key: key2, payload: value }
3046
+ )
3047
+ };
3048
+ }
3049
+ /** @internal */
3050
+ _toImmutable() {
3051
+ const result = {};
3052
+ for (const [key, val] of this.#map) {
3053
+ result[key] = isLiveStructure(val) ? val.toImmutable() : val;
3054
+ }
3055
+ return process.env.NODE_ENV === "production" ? result : Object.freeze(result);
3056
+ }
3057
+ clone() {
3058
+ return new _LiveObject(
3059
+ Object.fromEntries(
3060
+ Array.from(this.#map).map(([key, value]) => [
3061
+ key,
3062
+ isLiveStructure(value) ? value.clone() : deepClone(value)
3063
+ ])
3064
+ )
3065
+ );
3066
+ }
3067
+ };
3068
+ function creationOpToLiveNode(op) {
3069
+ return lsonToLiveNode(creationOpToLson(op));
3070
+ }
3071
+ function creationOpToLson(op) {
3072
+ switch (op.type) {
3073
+ case 8:
3074
+ return op.data;
3075
+ case 4:
3076
+ return new LiveObject(op.data);
3077
+ case 7:
3078
+ return new LiveMap();
3079
+ case 2:
3080
+ return new LiveList([]);
3081
+ default:
3082
+ return assertNever(op, "Unknown creation Op");
3083
+ }
3084
+ }
3085
+ function deserialize([id, crdt], parentToChildren, pool) {
3086
+ switch (crdt.type) {
3087
+ case 0: {
3088
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool);
3089
+ }
3090
+ case 1: {
3091
+ return LiveList._deserialize([id, crdt], parentToChildren, pool);
3092
+ }
3093
+ case 2: {
3094
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool);
3095
+ }
3096
+ case 3: {
3097
+ return LiveRegister._deserialize([id, crdt], parentToChildren, pool);
3098
+ }
3099
+ default: {
3100
+ throw new Error("Unexpected CRDT type");
3101
+ }
3102
+ }
3103
+ }
3104
+ function deserializeToLson([id, crdt], parentToChildren, pool) {
3105
+ switch (crdt.type) {
3106
+ case 0: {
3107
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool);
3108
+ }
3109
+ case 1: {
3110
+ return LiveList._deserialize([id, crdt], parentToChildren, pool);
3111
+ }
3112
+ case 2: {
3113
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool);
3114
+ }
3115
+ case 3: {
3116
+ return crdt.data;
3117
+ }
3118
+ default: {
3119
+ throw new Error("Unexpected CRDT type");
3120
+ }
3121
+ }
3122
+ }
3123
+ function isLiveStructure(value) {
3124
+ return isLiveList(value) || isLiveMap(value) || isLiveObject(value);
3125
+ }
3126
+ function isLiveNode(value) {
3127
+ return isLiveStructure(value) || isLiveRegister(value);
3128
+ }
3129
+ function isLiveList(value) {
3130
+ return value instanceof LiveList;
3131
+ }
3132
+ function isLiveMap(value) {
3133
+ return value instanceof LiveMap;
3134
+ }
3135
+ function isLiveObject(value) {
3136
+ return value instanceof LiveObject;
3137
+ }
3138
+ function isLiveRegister(value) {
3139
+ return value instanceof LiveRegister;
3140
+ }
3141
+ function liveNodeToLson(obj) {
3142
+ if (obj instanceof LiveRegister) {
3143
+ return obj.data;
3144
+ } else if (obj instanceof LiveList || obj instanceof LiveMap || obj instanceof LiveObject) {
3145
+ return obj;
3146
+ } else {
3147
+ return assertNever(obj, "Unknown AbstractCrdt");
3148
+ }
3149
+ }
3150
+ function lsonToLiveNode(value) {
3151
+ if (value instanceof LiveObject || value instanceof LiveMap || value instanceof LiveList) {
3152
+ return value;
3153
+ } else {
3154
+ return new LiveRegister(value);
3155
+ }
3156
+ }
3157
+ var MAX_SOCKET_MESSAGE_SIZE = 1024 * 1024 - 512;
3158
+ var htmlEscapables = {
3159
+ "&": "&amp;",
3160
+ "<": "&lt;",
3161
+ ">": "&gt;",
3162
+ '"': "&quot;",
3163
+ "'": "&#39;"
3164
+ };
3165
+ var htmlEscapablesRegex = new RegExp(
3166
+ Object.keys(htmlEscapables).map((entity) => `\\${entity}`).join("|"),
3167
+ "g"
3168
+ );
3169
+ var markdownEscapables = {
3170
+ _: "\\_",
3171
+ "*": "\\*",
3172
+ "#": "\\#",
3173
+ "`": "\\`",
3174
+ "~": "\\~",
3175
+ "!": "\\!",
3176
+ "|": "\\|",
3177
+ "(": "\\(",
3178
+ ")": "\\)",
3179
+ "{": "\\{",
3180
+ "}": "\\}",
3181
+ "[": "\\[",
3182
+ "]": "\\]"
3183
+ };
3184
+ var markdownEscapablesRegex = new RegExp(
3185
+ Object.keys(markdownEscapables).map((entity) => `\\${entity}`).join("|"),
3186
+ "g"
3187
+ );
3188
+ detectDupes(PKG_NAME, PKG_VERSION, PKG_FORMAT);
3189
+
3190
+ // ../../node_modules/@liveblocks/client/dist/index.js
3191
+ var PKG_NAME2 = "@liveblocks/client";
3192
+ var PKG_VERSION2 = "3.7.1";
3193
+ var PKG_FORMAT2 = "esm";
3194
+ detectDupes(PKG_NAME2, PKG_VERSION2, PKG_FORMAT2);
3195
+
3196
+ // ../../libs/liveblocks-commands/src/utils/liveObjectOf.ts
3197
+ init_cjs_shims();
3198
+ var liveObjectOf = (fields) => {
3199
+ return new LiveObject(fields);
3200
+ };
3201
+
3202
+ // ../../libs/liveblocks-commands/src/utils/makeLivePaymentDetails.ts
3203
+ var makeLivePaymentDetails = ({
3204
+ amount,
3205
+ direction,
3206
+ tags
3207
+ }) => liveObjectOf({
3208
+ amount,
3209
+ direction,
3210
+ tags: new LiveList(
3211
+ (tags ?? []).map(
3212
+ ({ key, value }) => new LiveObject({ id: lil_id_default(), key, value })
3213
+ )
3214
+ )
3215
+ });
3216
+
3217
+ // ../../libs/liveblocks-commands/src/utils/paymentTypeValidation.ts
3218
+ var convertLiveLine = (line) => ({
3219
+ key: line.key,
3220
+ account: line.account ? { path: line.account.path } : void 0,
3221
+ amount: line.amount ?? "",
3222
+ currency: line.currency ? {
3223
+ code: line.currency.code,
3224
+ customCurrencyId: line.currency.customCurrencyId
3225
+ } : void 0,
3226
+ description: line.description,
3227
+ system: line.system
3228
+ });
3229
+ var convertLiveEntry = (entry) => ({
3230
+ description: entry.description,
3231
+ lines: Array.from(entry.linesOrder.values()).map((lineId) => entry.lines.get(lineId)).filter((line) => line !== void 0).map(convertLiveLine)
3232
+ });
3233
+ var validateLivePaymentEntry = ({
3234
+ entryVersion,
3235
+ event,
3236
+ entryIdentity,
3237
+ accountPathToAccount
3238
+ }) => validatePaymentEntry({
3239
+ entry: convertLiveEntry(entryVersion),
3240
+ event,
3241
+ entryIdentity,
3242
+ accountPathToAccount,
3243
+ paymentAccountPath: findPaymentAccountPath(accountPathToAccount)
3244
+ });
3245
+
3246
+ // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
3247
+ init_cjs_shims();
3248
+
3249
+ // ../../libs/payment-commands/utils/amount.ts
3250
+ init_cjs_shims();
3251
+
3252
+ // ../../libs/types/payment.ts
3253
+ init_cjs_shims();
3254
+ var MIN_PAYMENT_AMOUNT_CENTS = 100n;
3255
+ var MAX_PAYMENT_AMOUNT_CENTS = 10000000n;
3256
+ var formatUsd = (cents) => `$${(cents / 100n).toLocaleString("en-US")}.${(cents % 100n).toString().padStart(2, "0")}`;
3257
+ var PAYMENT_AMOUNT_RANGE_MESSAGE = `Amount must be between ${formatUsd(
3258
+ MIN_PAYMENT_AMOUNT_CENTS
3259
+ )} and ${formatUsd(MAX_PAYMENT_AMOUNT_CENTS)}`;
3260
+ var PaymentMode = /* @__PURE__ */ ((PaymentMode2) => {
3261
+ PaymentMode2["sandbox"] = "sandbox";
3262
+ PaymentMode2["glassbox"] = "glassbox";
3263
+ return PaymentMode2;
3264
+ })(PaymentMode || {});
3265
+ var PaymentModeSchema = z.nativeEnum(PaymentMode);
3266
+ var ApiPaymentMode = /* @__PURE__ */ ((ApiPaymentMode2) => {
3267
+ ApiPaymentMode2["sandbox"] = "sandbox";
3268
+ ApiPaymentMode2["production"] = "production";
3269
+ return ApiPaymentMode2;
3270
+ })(ApiPaymentMode || {});
3271
+ var ApiPaymentModeSchema = z.nativeEnum(ApiPaymentMode);
3272
+ var PaymentPersistenceEvent = {
3273
+ /** The Payment was created. */
3274
+ created: "created",
3275
+ /** The payer went through checkout; posted when the Payment enters `processing`. */
3276
+ checkout: "checkout",
3277
+ /** The Customer retried the Payment on a saved payment method; posted when the Payment enters `processing`. */
3278
+ retry: "retry",
3279
+ /** The card network captured the payment; it is guaranteed to settle. */
3280
+ card_captured: "card_captured",
3281
+ /** Stripe declined an attempt, or refused to create a PaymentIntent for it. */
3282
+ card_declined: "card_declined",
3283
+ /** The payer abandoned or failed an attempt's 3DS challenge. */
3284
+ card_3ds_canceled: "card_3ds_canceled",
3285
+ /** The payment was settled. */
3286
+ settled: "settled",
3287
+ /** A Fragment Payment refund record was created. */
3288
+ refund_initiated: "refund_initiated",
3289
+ /** A Fragment Payment refund cleared its in-transit account. */
3290
+ refund_settled: "refund_settled",
3291
+ /** Stripe declined a Fragment Payment refund. */
3292
+ refund_failed: "refund_failed"
3293
+ };
3294
+ var PaymentPersistenceEventSchema = z.nativeEnum(
3295
+ PaymentPersistenceEvent
3296
+ );
3297
+ var InternalPaymentAttemptStatus = {
3298
+ /** Payment attempt not yet sent to Stripe. */
3299
+ created: "created",
3300
+ /** Payment attempt has been sent to Stripe and is being processed. */
3301
+ processing: "processing",
3302
+ /** Payment attempt has been accepted. */
3303
+ accepted: "accepted",
3304
+ /** Payment attempt has been declined. */
3305
+ declined: "declined",
3306
+ /** Stripe refused to create a PaymentIntent for the attempt. */
3307
+ rejected: "rejected",
3308
+ /** The payer abandoned or failed the attempt's 3DS challenge. */
3309
+ canceled: "canceled",
3310
+ /** Payment attempt needs action from the payer. No stored shape yet. */
3311
+ needs_action: "needs_action"
3312
+ };
3313
+ var EXTERNAL_PAYMENT_ATTEMPT_STATUSES = {
3314
+ [InternalPaymentAttemptStatus.created]: "processing" /* processing */,
3315
+ [InternalPaymentAttemptStatus.processing]: "processing" /* processing */,
3316
+ [InternalPaymentAttemptStatus.needs_action]: "processing" /* processing */,
3317
+ [InternalPaymentAttemptStatus.accepted]: "succeeded" /* succeeded */,
3318
+ [InternalPaymentAttemptStatus.declined]: "failed" /* failed */,
3319
+ [InternalPaymentAttemptStatus.rejected]: "failed" /* failed */,
3320
+ [InternalPaymentAttemptStatus.canceled]: "failed" /* failed */
3321
+ };
3322
+ var paymentCurrencyCodes = [
3323
+ "USD"
3324
+ ];
3325
+ var PaymentCurrencyCodeSchema = z.enum(paymentCurrencyCodes);
3326
+ var ExternalAccountMatchInput = z.object({
3327
+ id: ParameterizedString.optional(),
3328
+ /** The External systems's ID of the account */
3329
+ externalId: ParameterizedString.optional(),
3330
+ /** The Fragment ID of the link */
3331
+ linkId: ParameterizedString.optional()
3332
+ });
3333
+
3334
+ // ../../libs/payment-commands/utils/amount.ts
3335
+ var MAX_AMOUNT_CENTS = 2n ** 46n * 100n;
3336
+ var DEFAULT_FRAGMENT_FEE_SCHEDULE = {
3337
+ ["card_payin" /* card_payin */]: {
3338
+ rateBps: 290n,
3339
+ fixedCents: 30n
3340
+ }
3341
+ };
3342
+ var BPS_DENOMINATOR = 10000n;
3343
+ var calculateFragmentFeeCents = ({
3344
+ settledCents,
3345
+ schedule
3346
+ }) => {
3347
+ assert_default(settledCents >= 0n, InternalError, {
3348
+ info: { settledCents },
3349
+ message: `Expected a non-negative settled amount, got ${settledCents}`
3350
+ });
3351
+ return schedule.fixedCents + (settledCents * schedule.rateBps + BPS_DENOMINATOR / 2n) / BPS_DENOMINATOR;
3352
+ };
3353
+ var IntegerAmountSchema = z.string().regex(/^-?\d+$/).transform(BigInt);
3354
+
3355
+ // ../../libs/shared-utils/parameterization.ts
3356
+ init_cjs_shims();
3357
+
3358
+ // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
3359
+ var SCENARIO_FRAGMENT_FEE_PERCENT = Number(DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].rateBps) / 100;
3360
+ var SCENARIO_FRAGMENT_FEE_FIXED_CENTS = Number(
3361
+ DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].fixedCents
3362
+ );
3363
+ var evaluatePaymentAmount = (expression, parameters) => {
3364
+ const filled = fillParams(expression, parameters, {
3365
+ allowMissing: true,
3366
+ allowMissingInChildren: true
3367
+ }).trim();
3368
+ try {
3369
+ return { kind: "amount", amount: evaluateExpression(filled) };
3370
+ } catch {
3371
+ return { kind: "unevaluated", expression };
3372
+ }
3373
+ };
3374
+ var computeScenarioFee = (amount) => {
3375
+ const fee = calculateFragmentFeeCents({
3376
+ settledCents: amount < 0n ? -amount : amount,
3377
+ schedule: DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */]
3378
+ });
3379
+ return amount < 0n ? -fee : fee;
3380
+ };
3381
+
3382
+ // ../../libs/liveblocks-commands/src/utils/sceneEventResolution.ts
3383
+ var PAYMENT_GONE_FROM_SCENARIO_REASON = "This payment is no longer in the scenario. Remove this row.";
3384
+ var PAYMENT_GONE_FROM_SCHEMA_REASON = "This payment is no longer in the schema. Remove this row.";
3385
+ var SETTLED_BEFORE_APPROVAL_REASON = "This payment settles before it is approved \u2014 move the settled row after its approved row.";
3386
+ var SETTLED_WITHOUT_APPROVAL_REASON = "This payment settles without being approved \u2014 its approved row is missing. Delete the settled row and re-add the payment.";
3387
+ var makeUnevaluatedAmountReason = (expression) => `Payment amount '${expression}' did not evaluate to a whole number. Check the parameters it references.`;
3388
+ var getLedgerSceneEventEntryId = (event) => ({
3389
+ flavor: "ledger",
3390
+ entryTypeId: event.entry.entryTypeId ?? "",
3391
+ entryTypeVersionId: event.entry.entryTypeVersionId ?? ""
3392
+ });
3393
+ var getPaymentVersionContext = (paymentTypes, payment) => {
3394
+ const paymentType = paymentTypes?.types.get(payment.paymentTypeId);
3395
+ const version = paymentType?.versions.get(payment.paymentTypeVersionId);
3396
+ if (!paymentType || !version)
3397
+ return null;
3398
+ return {
3399
+ paymentType: paymentType.type,
3400
+ amountExpression: version.payment.amount,
3401
+ lifecycleEvents: SCENE_PAYMENT_ACCOUNTING_EVENT_KEYS.filter(
3402
+ (event) => getPaymentEntryFromVersion(version, event) !== null
3403
+ )
3404
+ };
3405
+ };
3406
+ var withSystemParameters = (parameters, amountExpression, event) => {
3407
+ const evaluated = evaluatePaymentAmount(amountExpression, parameters);
3408
+ if (evaluated.kind !== "amount")
3409
+ return null;
3410
+ const amount = evaluated.amount.toString();
3411
+ const systemParameters = z2(event).with(PaymentAccountingEventKey.initiated, () => ({})).with(PaymentAccountingEventKey.settled, () => ({
3412
+ [SystemLineParameterName.payment_settlement_line]: amount,
3413
+ [SystemLineParameterName.payment_fee_line]: computeScenarioFee(
3414
+ evaluated.amount
3415
+ ).toString()
3416
+ })).with(
3417
+ PaymentAccountingEventKey.refund_initiated,
3418
+ PaymentAccountingEventKey.refund_failed,
3419
+ () => ({
3420
+ [SystemLineParameterName.payment_refund_line]: amount
3421
+ })
3422
+ ).exhaustive();
3423
+ return { ...parameters, ...systemParameters };
3424
+ };
3425
+ var getPaymentLifecycleFailure = ({
3426
+ lifecycleEvents,
3427
+ eventIndexByEvent
3428
+ }) => {
3429
+ const lifecycleSteps = lifecycleEvents.slice(1).map((event2, position) => {
3430
+ const previousEvent2 = lifecycleEvents[position];
3431
+ return {
3432
+ event: event2,
3433
+ previousEvent: previousEvent2,
3434
+ eventRowIndex: eventIndexByEvent.get(event2),
3435
+ previousEventRowIndex: eventIndexByEvent.get(previousEvent2)
3436
+ };
3437
+ });
3438
+ const invalidStep = lifecycleSteps.find(
3439
+ ({ eventRowIndex, previousEventRowIndex: previousEventRowIndex2 }) => eventRowIndex !== void 0 && (previousEventRowIndex2 === void 0 || previousEventRowIndex2 > eventRowIndex)
3440
+ );
3441
+ if (!invalidStep)
3442
+ return void 0;
3443
+ const { event, previousEvent, previousEventRowIndex } = invalidStep;
3444
+ if (event === PaymentAccountingEventKey.settled && previousEvent === PaymentAccountingEventKey.initiated) {
3445
+ return previousEventRowIndex === void 0 ? SETTLED_WITHOUT_APPROVAL_REASON : SETTLED_BEFORE_APPROVAL_REASON;
3446
+ }
3447
+ return previousEventRowIndex === void 0 ? `This ${event} row has no preceding ${previousEvent} row. Delete the ${event} row and re-add the payment.` : `This ${event} row occurs before its ${previousEvent} row. Move the ${event} row after its ${previousEvent} row.`;
3448
+ };
3449
+ var findInvalidPaymentEvents = (orderedEvents, lifecycleEventsByPaymentId) => {
3450
+ const eventIndexesByPaymentId = /* @__PURE__ */ new Map();
3451
+ orderedEvents.forEach((event, index) => {
3452
+ if (event.eventType !== "payment-entry")
3453
+ return;
3454
+ const eventIndexByEvent = eventIndexesByPaymentId.get(event.entry.paymentId) ?? /* @__PURE__ */ new Map();
3455
+ eventIndexByEvent.set(event.entry.event, index);
3456
+ eventIndexesByPaymentId.set(event.entry.paymentId, eventIndexByEvent);
3457
+ });
3458
+ const invalidReasonsById = /* @__PURE__ */ new Map();
3459
+ eventIndexesByPaymentId.forEach((eventIndexByEvent, paymentId) => {
3460
+ const lifecycleEvents = lifecycleEventsByPaymentId.get(paymentId);
3461
+ if (!lifecycleEvents)
3462
+ return;
3463
+ const failure = getPaymentLifecycleFailure({
3464
+ lifecycleEvents,
3465
+ eventIndexByEvent
3466
+ });
3467
+ if (failure === void 0)
3468
+ return;
3469
+ orderedEvents.forEach((event) => {
3470
+ if (event.eventType === "payment-entry" && event.entry.paymentId === paymentId) {
3471
+ invalidReasonsById.set(event.id, failure);
3472
+ }
3473
+ });
3474
+ });
3475
+ return invalidReasonsById;
3476
+ };
3477
+ var resolvePaymentEvent = ({
3478
+ event,
3479
+ payments,
3480
+ paymentTypes,
3481
+ invalidPaymentReasonsById
3482
+ }) => {
3483
+ const payment = payments.get(event.entry.paymentId);
3484
+ if (!payment) {
3485
+ return {
3486
+ id: event.id,
3487
+ entryId: null,
3488
+ idKey: null,
3489
+ parameters: {},
3490
+ repeatedParameters: {},
3491
+ failure: {
3492
+ errorKind: "entry_invalid",
3493
+ reasons: [PAYMENT_GONE_FROM_SCENARIO_REASON]
3494
+ }
3495
+ };
3496
+ }
3497
+ const entryId = makePaymentEntryId(
3498
+ payment.paymentTypeId,
3499
+ payment.paymentTypeVersionId,
3500
+ event.entry.event
3501
+ );
3502
+ const context = getPaymentVersionContext(paymentTypes, payment);
3503
+ const instanceParameters = payment.parameters;
3504
+ const base = {
3505
+ id: event.id,
3506
+ entryId,
3507
+ idKey: getEntryIdKey(entryId),
3508
+ payment: {
3509
+ paymentType: context?.paymentType ?? "unknown",
3510
+ event: event.entry.event,
3511
+ ik: payment.ik
3512
+ },
3513
+ parameters: instanceParameters,
3514
+ repeatedParameters: {}
3515
+ };
3516
+ const fail = (errorKind, reason) => ({
3517
+ ...base,
3518
+ failure: { errorKind, reasons: [reason] }
3519
+ });
3520
+ if (!context)
3521
+ return fail("entry_invalid", PAYMENT_GONE_FROM_SCHEMA_REASON);
3522
+ const invalidPaymentReason = invalidPaymentReasonsById.get(event.id);
3523
+ if (invalidPaymentReason !== void 0) {
3524
+ return fail("entry_invalid", invalidPaymentReason);
3525
+ }
3526
+ const parameters = withSystemParameters(
3527
+ instanceParameters,
3528
+ context.amountExpression,
3529
+ event.entry.event
3530
+ );
3531
+ if (parameters === null) {
3532
+ return fail(
3533
+ "parameter_error",
3534
+ makeUnevaluatedAmountReason(context.amountExpression)
3535
+ );
3536
+ }
3537
+ return { ...base, parameters };
3538
+ };
3539
+ var resolveSceneEvents = ({
3540
+ events,
3541
+ eventsOrder,
3542
+ payments,
3543
+ paymentTypes
3544
+ }) => {
3545
+ const eventsById = new Map(events.map((event) => [event.id, event]));
3546
+ const orderedEvents = eventsOrder.map((eventId) => eventsById.get(eventId)).filter((event) => event !== void 0);
3547
+ const lifecycleEventsByPaymentId = /* @__PURE__ */ new Map();
3548
+ payments.forEach((payment, paymentId) => {
3549
+ const context = getPaymentVersionContext(paymentTypes, payment);
3550
+ if (context) {
3551
+ lifecycleEventsByPaymentId.set(paymentId, context.lifecycleEvents);
3552
+ }
3553
+ });
3554
+ const invalidPaymentReasonsById = findInvalidPaymentEvents(
3555
+ orderedEvents,
3556
+ lifecycleEventsByPaymentId
3557
+ );
3558
+ return orderedEvents.map(
3559
+ (event) => z2(event).with({ eventType: "entry" }, (ledgerEvent) => {
3560
+ const entryId = getLedgerSceneEventEntryId(ledgerEvent);
3561
+ return {
3562
+ id: ledgerEvent.id,
3563
+ entryId,
3564
+ idKey: getEntryIdKey(entryId),
3565
+ parameters: ledgerEvent.entry.parameters,
3566
+ repeatedParameters: ledgerEvent.entry.repeatedParameters ?? {}
3567
+ };
3568
+ }).with(
3569
+ { eventType: "payment-entry" },
3570
+ (paymentEvent) => resolvePaymentEvent({
3571
+ event: paymentEvent,
3572
+ payments,
3573
+ paymentTypes,
3574
+ invalidPaymentReasonsById
3575
+ })
3576
+ ).exhaustive()
3577
+ );
3578
+ };
3579
+ var buildSceneEntriesByKey = ({
3580
+ resolvedEvents,
3581
+ root,
3582
+ accountPathToAccount,
3583
+ defaultConsistencyConfig
3584
+ }) => {
3585
+ const entriesByKey = /* @__PURE__ */ new Map();
3586
+ resolvedEvents.forEach(({ entryId, idKey }) => {
3587
+ if (!entryId || !idKey || entriesByKey.has(idKey))
3588
+ return;
3589
+ const entryType = getEntryTypeFromRoot(root, entryId);
3590
+ if (!entryType)
3591
+ return;
3592
+ const entryVersion = getEntryVersionFromRoot(root, entryId);
3593
+ if (!entryVersion)
3594
+ return;
3595
+ if (entryId.flavor === "ledger") {
3596
+ entriesByKey.set(
3597
+ idKey,
3598
+ validateAndTransformEntryVersion({
3599
+ entryType,
3600
+ entryVersion,
3601
+ accountPathToAccount,
3602
+ defaultConsistencyConfig
3603
+ })
3604
+ );
3605
+ return;
3606
+ }
3607
+ entriesByKey.set(
3608
+ idKey,
3609
+ transformEntryVersion({
3610
+ entryType,
3611
+ entryVersion,
3612
+ accountPathToAccount,
3613
+ errors: validateLivePaymentEntry({
3614
+ entryVersion,
3615
+ event: entryId.event,
3616
+ entryIdentity: entryType.type,
3617
+ accountPathToAccount
3618
+ })
3619
+ })
3620
+ );
3621
+ });
3622
+ return entriesByKey;
3623
+ };
3624
+
3625
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/EntryValidationUtils.ts
3626
+ init_cjs_shims();
3627
+ var buildAccountIdToAccountRecord = (chartOfAccounts) => {
3628
+ if (!chartOfAccounts)
3629
+ return {};
3630
+ const accountsMap = new Map(
3631
+ Array.from(chartOfAccounts.accounts.entries())
3632
+ );
3633
+ const accountIds = {};
3634
+ chartOfAccounts.accounts.forEach((account, accountId) => {
3635
+ const structuralPath = computeStructuralPath(
3636
+ accountId,
3637
+ accountsMap,
3638
+ account.parentId
3639
+ );
3640
+ accountIds[structuralPath] = accountId;
3641
+ });
3642
+ const filledIn = buildAndValidateChartOfAccounts(chartOfAccounts);
3643
+ const enhancedCoA = enhanceCoA(filledIn, { accountIds });
3644
+ return enhancedCoA.accountIdToAccount;
3645
+ };
3646
+
3647
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
3648
+ init_cjs_shims();
3649
+
3650
+ // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
3651
+ init_cjs_shims();
3652
+ import assert2 from "assert";
3653
+
3654
+ // ../../libs/schema-validation/utils/transformers/schema.ts
3655
+ init_cjs_shims();
3656
+ var transformAndValidateSchema = (schema) => {
3657
+ const errors = [];
3658
+ const schemaKeyResult = SafeStringSchema.safeParse(schema.key);
3659
+ if (!schemaKeyResult.success || schemaKeyResult.data.includes("{{") || schemaKeyResult.data.includes("}}")) {
3660
+ errors.push({
3661
+ message: `Invalid key. Keys cannot contain '{{' or '}}' and must be non-empty`,
3662
+ path: ["key"]
3663
+ });
3664
+ }
3665
+ const res = transformAndValidateCoA({
3666
+ coa: schema.chartOfAccounts
3667
+ });
3668
+ const { errors: coaErrors } = res;
3669
+ const validatedChartOfAccounts = res.filledIn;
3670
+ errors.push(
3671
+ ...coaErrors.map((e) => ({ ...e, path: ["chartOfAccounts", ...e.path] }))
3672
+ );
3673
+ const { filledIn: ledgerEntries, errors: entryErrors } = transformAndValidateEntries({
3674
+ ledgerEntries: schema.ledgerEntries ?? { types: [] },
3675
+ validatedCoA: validatedChartOfAccounts
3676
+ });
3677
+ errors.push(
3678
+ ...entryErrors.map((e) => ({ ...e, path: ["ledgerEntries", ...e.path] }))
3679
+ );
3680
+ const { errors: paymentErrors } = transformAndValidatePayments({
3681
+ payments: schema.payments ?? { types: [] },
3682
+ validatedCoA: validatedChartOfAccounts
3683
+ });
3684
+ errors.push(
3685
+ ...paymentErrors.map((e) => ({ ...e, path: ["payments", ...e.path] }))
3686
+ );
3687
+ const consistencyErrors = schema.consistencyConfig ? validateLedgerConsistencySettings(schema.consistencyConfig) : { errors: [] };
3688
+ errors.push(...consistencyErrors.errors);
3689
+ const groups = schema.groups ?? [];
3690
+ if (groups.length > 0) {
3691
+ groups.forEach((group, index) => {
3692
+ const groupErrors = validateGroup(
3693
+ group,
3694
+ validatedChartOfAccounts,
3695
+ ledgerEntries,
3696
+ index
3697
+ );
3698
+ errors.push(...groupErrors);
3699
+ });
3700
+ }
3701
+ return {
3702
+ errors,
3703
+ validatedSchema: {
3704
+ name: schema.name,
3705
+ key: schema.key,
3706
+ consistencyConfig: schema.consistencyConfig?.entries ? {
3707
+ entries: schema.consistencyConfig.entries
3708
+ } : {
3709
+ entries: "eventual"
3710
+ },
3711
+ ledgerEntries,
3712
+ chartOfAccounts: validatedChartOfAccounts,
3713
+ scenes: schema.scenes,
3714
+ groups,
3715
+ payments: schema.payments
3716
+ }
3717
+ };
3718
+ };
3719
+
3720
+ // ../../libs/shared-utils/accounting/currency.ts
3721
+ init_cjs_shims();
3722
+
3723
+ // ../../libs/shared-utils/accounting/doubleEntry.ts
3724
+ init_cjs_shims();
3725
+
3726
+ // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
3727
+ var formatSchemaValidationError = (error3) => {
3728
+ const path = error3.path.length > 0 ? ` (Path: ${error3.path.join("/")})` : "";
3729
+ const code = error3.code ? ` [${error3.code}]` : "";
3730
+ return `${error3.message}${code}${path}`;
3731
+ };
3732
+ var getBaseEntryParameters = (entry, accountIdToAccount) => {
3733
+ const allParams = new Set(
3734
+ [
3735
+ ...getSchemaObjectParameters(entry, false),
3736
+ ...entry.lines.flatMap(
3737
+ ({ account }) => account?.id ? getSchemaObjectParameters(accountIdToAccount[account.id], false) : []
3738
+ )
3739
+ ].filter((param) => !entry.parameters[param])
3740
+ );
3741
+ return [...allParams];
3742
+ };
3743
+ var validateEntryConditions = ({
3744
+ filledEntry,
3745
+ sceneEvents,
3746
+ entryIndex
3747
+ }) => {
3748
+ filledEntry.conditions.forEach((condition) => {
3749
+ const { path } = condition.account;
3750
+ const { currency } = condition;
3751
+ assert2(
3752
+ currency.code !== "MULTI",
3753
+ `Invalid Condition. Condition in Entry ${filledEntry.type} on multi-currency Ledger Account ${path} must have a currency set`
3754
+ );
3755
+ const matchesPath = {
3756
+ ownBalance: (linePath) => linePath === path,
3757
+ totalBalance: (linePath) => linePath === path || linePath.startsWith(`${path}/`)
3758
+ };
3759
+ const sumLines = (lines, scope) => lines.filter(
3760
+ (line) => matchesPath[scope](line.account.path) && line.currency.code === currency.code && line.currency.customCurrencyId === currency.customCurrencyId
3761
+ ).reduce(
3762
+ (sum, line) => sum + BigInt(evaluateExpression(line.amount)),
3763
+ 0n
3764
+ );
3765
+ const sumPriorLines = (scope) => sceneEvents.slice(0, entryIndex).reduce(
3766
+ (sum, { entry: balanceEntry }) => sum + (balanceEntry.isValid ? sumLines(balanceEntry.lines, scope) : 0n),
3767
+ 0n
3768
+ );
3769
+ const checkBoundary = (kind, scope, amount, bounds) => {
3770
+ if (!bounds)
3771
+ return;
3772
+ const label = kind === "precondition" ? "Precondition" : "Postcondition";
3773
+ const when = kind === "precondition" ? "before posting this entry" : "after posting this entry";
3774
+ const checks = [
3775
+ ["=", bounds.eq, (a, b) => a === b],
3776
+ [">=", bounds.gte, (a, b) => a >= b],
3777
+ ["<=", bounds.lte, (a, b) => a <= b]
3778
+ ];
3779
+ checks.forEach(([op, rhs, cmp]) => {
3780
+ if (rhs === void 0)
3781
+ return;
3782
+ assert2(
3783
+ cmp(amount, BigInt(evaluateExpression(rhs))),
3784
+ `${label} not satisfied. Ledger Account ${path} must have ${scope} ${op} ${rhs} ${when}. Got: ${amount}`
3785
+ );
3786
+ });
3787
+ };
3788
+ const preOwn = sumPriorLines("ownBalance");
3789
+ const preTotal = sumPriorLines("totalBalance");
3790
+ checkBoundary(
3791
+ "precondition",
3792
+ "ownBalance",
3793
+ preOwn,
3794
+ condition.precondition?.ownBalance
3795
+ );
3796
+ checkBoundary(
3797
+ "precondition",
3798
+ "totalBalance",
3799
+ preTotal,
3800
+ condition.precondition?.totalBalance
3801
+ );
3802
+ const postOwn = preOwn + sumLines(filledEntry.lines, "ownBalance");
3803
+ const postTotal = preTotal + sumLines(filledEntry.lines, "totalBalance");
3804
+ checkBoundary(
3805
+ "postcondition",
3806
+ "ownBalance",
3807
+ postOwn,
3808
+ condition.postcondition?.ownBalance
3809
+ );
3810
+ checkBoundary(
3811
+ "postcondition",
3812
+ "totalBalance",
3813
+ postTotal,
3814
+ condition.postcondition?.totalBalance
3815
+ );
3816
+ });
3817
+ };
3818
+ var validateEntry2 = ({
3819
+ accountIdToAccount,
3820
+ baseEntry,
3821
+ errors,
3822
+ entry,
3823
+ parameterValues
3824
+ }) => {
3825
+ try {
3826
+ if (baseEntry) {
3827
+ if (errors.length > 0) {
3828
+ return {
3829
+ errorKind: "entry_invalid",
3830
+ reasons: errors.map(formatSchemaValidationError)
3831
+ };
3832
+ }
3833
+ const parameters = getBaseEntryParameters(baseEntry, accountIdToAccount);
3834
+ const missingParams = parameters.filter(
3835
+ (param) => !parameterValues[param]
3836
+ );
3837
+ if (missingParams.length) {
3838
+ throw new Error("All parameters must be filled in");
3839
+ }
3841
3840
  }
3842
- const oldValue = this.#map.get(key);
3843
- const id = nn(this._id);
3844
- let reverse = [];
3845
- if (isLiveNode(oldValue)) {
3846
- reverse = oldValue._toOps(id, op.key);
3847
- oldValue._detach();
3848
- } else if (oldValue !== void 0) {
3849
- reverse = [
3850
- {
3851
- type: 3,
3852
- id,
3853
- data: { [key]: oldValue }
3841
+ const lineValues = {};
3842
+ entry.lines.forEach((line) => {
3843
+ line.amountParameters.forEach((param) => {
3844
+ assert2(
3845
+ !Number.isNaN(parseInt(parameterValues[param], 10)),
3846
+ `Parameter ${param} must have numeric value`
3847
+ );
3848
+ });
3849
+ });
3850
+ const filledEntry = fillParams(entry, {
3851
+ ...parameterValues,
3852
+ ...entry.parameters
3853
+ });
3854
+ filledEntry.lines.forEach((line, lineNumber) => {
3855
+ const key = makeLineKey(line, lineNumber);
3856
+ const amount = line.amount && evaluateExpression(line.amount);
3857
+ lineValues[key] = {
3858
+ amount: Number(amount)
3859
+ };
3860
+ });
3861
+ assert2(
3862
+ filledEntry.lines.every(
3863
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3864
+ (line, lineNumber) => lineValues[makeLineKey(line, lineNumber)]
3865
+ ),
3866
+ "All amounts must be populated"
3867
+ );
3868
+ const accountsForBalancedPayload = {};
3869
+ const linesForBalancedPayload = filledEntry.lines.map(
3870
+ (line, lineNumber) => {
3871
+ const lineKey = makeLineKey(line, lineNumber);
3872
+ const fetchedAccount = accountIdToAccount[line.account.id];
3873
+ const accountType = fetchedAccount.type;
3874
+ if (accountType === void 0) {
3875
+ throw new Error(
3876
+ `Could not determine account type for path ${fetchedAccount.structuralPath}`
3877
+ );
3854
3878
  }
3855
- ];
3879
+ const account = {
3880
+ currency: CurrencyCodeSchema.parse(line.currency.code),
3881
+ customCurrencyId: line.currency.customCurrencyId,
3882
+ type: accountType
3883
+ };
3884
+ const accountKey = `${fetchedAccount.structuralPath}:${serializeCurrency(account)}`;
3885
+ accountsForBalancedPayload[accountKey] = account;
3886
+ return {
3887
+ currency: line.currency.code,
3888
+ customCurrencyId: line.currency.customCurrencyId,
3889
+ amount: BigInt(lineValues[lineKey].amount),
3890
+ account: {
3891
+ id: accountKey
3892
+ }
3893
+ };
3894
+ }
3895
+ );
3896
+ assertBalancedLines({
3897
+ // @ts-expect-error TODO: make visualizer support parameterized currencies after https://github.com/fragment-dev/workspaces/pull/3076/files is merged
3898
+ lines: linesForBalancedPayload,
3899
+ ledgerAccounts: accountsForBalancedPayload
3900
+ });
3901
+ return { lineValues, filledEntry };
3902
+ } catch (err) {
3903
+ if (err instanceof Error) {
3904
+ return { errorKind: "parameter_error", reasons: [err.message] };
3856
3905
  }
3857
- this.#map.delete(key);
3858
- this.invalidate();
3906
+ throw err;
3907
+ }
3908
+ };
3909
+ var generatePostedEntry = ({
3910
+ accountIdToAccount,
3911
+ baseEntry,
3912
+ errors,
3913
+ entry,
3914
+ postedEntryId,
3915
+ parameterValues
3916
+ }) => {
3917
+ const entryId = postedEntryId || lil_id_default();
3918
+ const validation = validateEntry2({
3919
+ accountIdToAccount,
3920
+ baseEntry,
3921
+ errors,
3922
+ entry,
3923
+ parameterValues
3924
+ });
3925
+ if ("reasons" in validation) {
3859
3926
  return {
3860
- modified: {
3861
- node: this,
3862
- type: "LiveObject",
3863
- updates: { [op.key]: { type: "delete" } }
3864
- },
3865
- reverse
3927
+ isValid: false,
3928
+ errorKind: validation.errorKind,
3929
+ reasons: validation.reasons,
3930
+ id: entryId,
3931
+ type: entry.type,
3932
+ typeVersion: entry.typeVersion,
3933
+ baseEntryId: entry.id,
3934
+ parameters: parameterValues
3866
3935
  };
3867
3936
  }
3868
- /**
3869
- * Transform the LiveObject into a javascript object
3870
- */
3871
- toObject() {
3872
- return Object.fromEntries(this.#map);
3873
- }
3874
- /**
3875
- * Adds or updates a property with a specified key and a value.
3876
- * @param key The key of the property to add
3877
- * @param value The value of the property to add
3878
- */
3879
- set(key, value) {
3880
- this._pool?.assertStorageIsWritable();
3881
- this.update({ [key]: value });
3882
- }
3883
- /**
3884
- * Returns a specified property from the LiveObject.
3885
- * @param key The key of the property to get
3886
- */
3887
- get(key) {
3888
- return this.#map.get(key);
3889
- }
3890
- /**
3891
- * Deletes a key from the LiveObject
3892
- * @param key The key of the property to delete
3893
- */
3894
- delete(key) {
3895
- this._pool?.assertStorageIsWritable();
3896
- const keyAsString = key;
3897
- const oldValue = this.#map.get(keyAsString);
3898
- if (oldValue === void 0) {
3937
+ const { filledEntry, lineValues } = validation;
3938
+ return {
3939
+ id: entryId,
3940
+ typeVersion: filledEntry.typeVersion,
3941
+ ik: lil_id_default(),
3942
+ type: filledEntry.type,
3943
+ parameters: parameterValues,
3944
+ conditions: filledEntry.conditions,
3945
+ lines: filledEntry.lines.map(
3946
+ (line, lineNumber) => ({
3947
+ ...line,
3948
+ amount: String(lineValues[makeLineKey(line, lineNumber)].amount)
3949
+ })
3950
+ ),
3951
+ tags: filledEntry.tags,
3952
+ groups: filledEntry.groups,
3953
+ baseEntryId: entry.id,
3954
+ isValid: true,
3955
+ status: filledEntry.status ?? "active"
3956
+ };
3957
+ };
3958
+
3959
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/useEntryUtils.ts
3960
+ init_cjs_shims();
3961
+ var convertEntryResponseToEnhancedSchemaLedgerEntry = (entry, accountIdToAccount) => {
3962
+ const baseEntry = {
3963
+ type: entry.value.type,
3964
+ typeVersion: entry.value.typeVersion,
3965
+ description: entry.value.description,
3966
+ postLinesAs: entry.value.postLinesAs,
3967
+ status: entry.value.status,
3968
+ parameters: convertStaticParametersToRecord(entry.value.parameters) ?? {},
3969
+ groups: entry.value.groups?.map((group) => ({
3970
+ key: safe`${group.key}`,
3971
+ value: group.value
3972
+ })) ?? [],
3973
+ tags: entry.value.tags?.map((tag) => ({
3974
+ key: tag.key,
3975
+ value: tag.value
3976
+ })) ?? [],
3977
+ lines: entry.value.lines?.map((line) => ({
3978
+ key: line.key,
3979
+ account: line.account ? {
3980
+ id: line.account.accountId ?? "",
3981
+ path: line.account.path
3982
+ } : void 0,
3983
+ amount: line.amount,
3984
+ currency: line.currency,
3985
+ description: line.description,
3986
+ tx: line.tx,
3987
+ repeated: line.repeated ? { key: safe`${line.repeated.key}` } : void 0
3988
+ })) ?? [],
3989
+ conditions: entry.value.conditions?.map((condition) => ({
3990
+ account: condition.account ? {
3991
+ id: condition.account.accountId ?? "",
3992
+ path: condition.account.path
3993
+ } : void 0,
3994
+ currency: condition.currency,
3995
+ precondition: condition.precondition,
3996
+ postcondition: condition.postcondition,
3997
+ repeated: condition.repeated ? { key: safe`${condition.repeated.key}` } : void 0
3998
+ })) ?? []
3999
+ };
4000
+ return enhanceLedgerEntry(
4001
+ baseEntry,
4002
+ accountIdToAccount,
4003
+ safe`${entry.value.typeVersion && entry.value.typeVersion > 1 ? entry.value.versionId : entry.value.entryId}`
4004
+ );
4005
+ };
4006
+
4007
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
4008
+ var transformLiveblocksSceneEvents = (resolvedEvents, entriesByKey, accountIdToAccount) => {
4009
+ const accountMap = new Map(Object.entries(accountIdToAccount));
4010
+ const postedEntries = [];
4011
+ resolvedEvents.forEach((event, entryIndex) => {
4012
+ const { entryId, idKey, payment: paymentInfo } = event;
4013
+ const baseEntryResponse = idKey === null ? void 0 : entriesByKey.get(idKey);
4014
+ const baseEntryId = (entryId && (entryId.flavor === "payment" ? entryId.paymentTypeId : entryId.entryTypeId)) ?? "";
4015
+ const repeatedParams = event.repeatedParameters;
4016
+ const staticParams = event.parameters;
4017
+ const pushSceneEvent = (entry, lineAccountTypes2) => {
4018
+ postedEntries.push(
4019
+ paymentInfo ? {
4020
+ id: event.id,
4021
+ eventType: "payment-entry",
4022
+ entry,
4023
+ payment: paymentInfo,
4024
+ entryId,
4025
+ lineAccountTypes: lineAccountTypes2
4026
+ } : {
4027
+ id: event.id,
4028
+ eventType: "entry",
4029
+ entry,
4030
+ entryId,
4031
+ lineAccountTypes: lineAccountTypes2
4032
+ }
4033
+ );
4034
+ };
4035
+ const pushInvalidSceneEvent = (errorKind, reasons) => {
4036
+ pushSceneEvent(
4037
+ {
4038
+ id: event.id,
4039
+ parameters: { ...staticParams, ...repeatedParams },
4040
+ baseEntryId,
4041
+ type: paymentInfo?.paymentType ?? "unknown",
4042
+ isValid: false,
4043
+ errorKind,
4044
+ reasons
4045
+ },
4046
+ []
4047
+ );
4048
+ };
4049
+ if (event.failure) {
4050
+ pushInvalidSceneEvent(event.failure.errorKind, event.failure.reasons);
3899
4051
  return;
3900
4052
  }
3901
- if (this._pool === void 0 || this._id === void 0) {
3902
- if (isLiveNode(oldValue)) {
3903
- oldValue._detach();
3904
- }
3905
- this.#map.delete(keyAsString);
3906
- this.invalidate();
4053
+ if (!baseEntryResponse) {
4054
+ pushInvalidSceneEvent("entry_invalid", [
4055
+ entryId?.flavor === "payment" ? PAYMENT_GONE_FROM_SCHEMA_REASON : "Entry not found"
4056
+ ]);
3907
4057
  return;
3908
4058
  }
3909
- let reverse;
3910
- if (isLiveNode(oldValue)) {
3911
- oldValue._detach();
3912
- reverse = oldValue._toOps(this._id, keyAsString);
3913
- } else {
3914
- reverse = [
3915
- {
3916
- type: 3,
3917
- data: { [keyAsString]: oldValue },
3918
- id: this._id
3919
- }
3920
- ];
3921
- }
3922
- this.#map.delete(keyAsString);
3923
- this.invalidate();
3924
- const storageUpdates = /* @__PURE__ */ new Map();
3925
- storageUpdates.set(this._id, {
3926
- node: this,
3927
- type: "LiveObject",
3928
- updates: { [key]: { type: "delete" } }
3929
- });
3930
- this._pool.dispatch(
3931
- [
3932
- {
3933
- type: 6,
3934
- key: keyAsString,
3935
- id: this._id,
3936
- opId: this._pool.generateOpId()
3937
- }
3938
- ],
3939
- reverse,
3940
- storageUpdates
3941
- );
3942
- }
3943
- /**
3944
- * Adds or updates multiple properties at once with an object.
3945
- * @param patch The object used to overrides properties
3946
- */
3947
- update(patch) {
3948
- this._pool?.assertStorageIsWritable();
3949
- if (_LiveObject.detectLargeObjects) {
3950
- const data = {};
3951
- for (const [key, value] of this.#map) {
3952
- if (!isLiveNode(value)) {
3953
- data[key] = value;
3954
- }
3955
- }
3956
- for (const key of Object.keys(patch)) {
3957
- const value = patch[key];
3958
- if (value === void 0)
3959
- continue;
3960
- if (!isLiveNode(value)) {
3961
- data[key] = value;
3962
- }
4059
+ const lineAccountTypes = (baseEntryResponse.value.lines ?? []).map((line) => {
4060
+ if (!line.account?.accountId) {
4061
+ return void 0;
3963
4062
  }
3964
- const jsonString = JSON.stringify(data);
3965
- const upperBoundSize = jsonString.length * 4;
3966
- if (upperBoundSize > MAX_LIVE_OBJECT_SIZE) {
3967
- const preciseSize = new TextEncoder().encode(jsonString).length;
3968
- if (preciseSize > MAX_LIVE_OBJECT_SIZE) {
3969
- throw new Error(
3970
- `LiveObject size exceeded limit: ${preciseSize} bytes > ${MAX_LIVE_OBJECT_SIZE} bytes. See https://liveblocks.io/docs/platform/limits#Liveblocks-Storage-limits`
3971
- );
3972
- }
4063
+ const account = accountMap.get(line.account.accountId);
4064
+ if (!account) {
4065
+ return void 0;
3973
4066
  }
3974
- }
3975
- if (this._pool === void 0 || this._id === void 0) {
3976
- for (const key in patch) {
3977
- const newValue = patch[key];
3978
- if (newValue === void 0) {
3979
- continue;
3980
- }
3981
- const oldValue = this.#map.get(key);
3982
- if (isLiveNode(oldValue)) {
3983
- oldValue._detach();
3984
- }
3985
- if (isLiveNode(newValue)) {
3986
- newValue._setParentLink(this, key);
4067
+ return account.type;
4068
+ }).filter((type) => type !== void 0);
4069
+ const enhancedEntry = convertEntryResponseToEnhancedSchemaLedgerEntry(
4070
+ baseEntryResponse,
4071
+ accountIdToAccount
4072
+ );
4073
+ const simulatingEntryErrors = [];
4074
+ const simulatingEntry = generateSimulatingEntry({
4075
+ entry: enhancedEntry,
4076
+ accountIdToAccount,
4077
+ onError: (error3) => {
4078
+ if (error3 instanceof Error) {
4079
+ simulatingEntryErrors.push(error3.message);
3987
4080
  }
3988
- this.#map.set(key, newValue);
3989
- this.invalidate();
3990
4081
  }
4082
+ });
4083
+ if (!simulatingEntry) {
4084
+ pushSceneEvent(
4085
+ {
4086
+ id: event.id,
4087
+ parameters: { ...staticParams, ...repeatedParams },
4088
+ baseEntryId,
4089
+ type: "unknown",
4090
+ isValid: false,
4091
+ errorKind: "parameter_error",
4092
+ reasons: [
4093
+ "Failed to fill parameters on Entry. Reasons: ",
4094
+ simulatingEntryErrors.join(", ")
4095
+ ]
4096
+ },
4097
+ []
4098
+ );
3991
4099
  return;
3992
4100
  }
3993
- const ops = [];
3994
- const reverseOps = [];
3995
- const opId = this._pool.generateOpId();
3996
- const updatedProps = {};
3997
- const reverseUpdateOp = {
3998
- id: this._id,
3999
- type: 3,
4000
- data: {}
4101
+ const mergedRepeatedParams = { ...staticParams, ...repeatedParams };
4102
+ const preFilledEntry = {
4103
+ ...simulatingEntry,
4104
+ lines: simulatingEntry.lines.map(
4105
+ (line) => fillParams(line, line.repeated ? mergedRepeatedParams : staticParams, {
4106
+ allowMissing: true,
4107
+ allowMissingInChildren: true
4108
+ })
4109
+ ),
4110
+ conditions: simulatingEntry.conditions.map(
4111
+ (condition) => fillParams(
4112
+ condition,
4113
+ condition.repeated ? mergedRepeatedParams : staticParams,
4114
+ { allowMissing: true, allowMissingInChildren: true }
4115
+ )
4116
+ )
4001
4117
  };
4002
- const updateDelta = {};
4003
- for (const key in patch) {
4004
- const newValue = patch[key];
4005
- if (newValue === void 0) {
4006
- continue;
4118
+ const postedEntry = generatePostedEntry({
4119
+ accountIdToAccount,
4120
+ baseEntry: enhancedEntry,
4121
+ errors: baseEntryResponse.errors,
4122
+ entry: preFilledEntry,
4123
+ postedEntryId: event.id,
4124
+ parameterValues: { ...staticParams, ...repeatedParams }
4125
+ });
4126
+ if (postedEntry.isValid) {
4127
+ const lineAccounts = postedEntry.lines.map((line) => ({
4128
+ acc: accountMap.get(line.account.id),
4129
+ currency: line.currency
4130
+ })).filter(
4131
+ (la) => la.acc !== void 0
4132
+ );
4133
+ if (lineAccounts.length !== postedEntry.lines.length) {
4134
+ pushSceneEvent(
4135
+ {
4136
+ ...postedEntry,
4137
+ isValid: false,
4138
+ errorKind: "entry_invalid",
4139
+ reasons: ["Could not find account for some lines"]
4140
+ },
4141
+ []
4142
+ );
4143
+ return;
4007
4144
  }
4008
- const oldValue = this.#map.get(key);
4009
- if (isLiveNode(oldValue)) {
4010
- reverseOps.push(...oldValue._toOps(this._id, key));
4011
- oldValue._detach();
4012
- } else if (oldValue === void 0) {
4013
- reverseOps.push({ type: 6, id: this._id, key });
4014
- } else {
4015
- reverseUpdateOp.data[key] = oldValue;
4145
+ const resolveAccountType = (acc) => acc.type;
4146
+ const lineAccountWithMissingType = lineAccounts.find(
4147
+ ({ acc }) => resolveAccountType(acc) === void 0
4148
+ );
4149
+ if (lineAccountWithMissingType) {
4150
+ pushSceneEvent(
4151
+ {
4152
+ ...postedEntry,
4153
+ isValid: false,
4154
+ errorKind: "entry_invalid",
4155
+ reasons: [
4156
+ `Could not determine account type for path ${lineAccountWithMissingType.acc.structuralPath}`
4157
+ ]
4158
+ },
4159
+ []
4160
+ );
4161
+ return;
4016
4162
  }
4017
- if (isLiveNode(newValue)) {
4018
- newValue._setParentLink(this, key);
4019
- newValue._attach(this._pool.generateId(), this._pool);
4020
- const newAttachChildOps = newValue._toOps(this._id, key, this._pool);
4021
- const createCrdtOp = newAttachChildOps.find(
4022
- (op) => op.parentId === this._id
4163
+ const conditionWithMissingType = postedEntry.conditions.map(
4164
+ (condition) => condition.account.id ? accountMap.get(condition.account.id) : void 0
4165
+ ).find(
4166
+ (account) => account && resolveAccountType(account) === void 0
4167
+ );
4168
+ if (conditionWithMissingType) {
4169
+ pushSceneEvent(
4170
+ {
4171
+ ...postedEntry,
4172
+ isValid: false,
4173
+ errorKind: "entry_invalid",
4174
+ reasons: [
4175
+ `Could not determine account type for path ${conditionWithMissingType.structuralPath}`
4176
+ ]
4177
+ },
4178
+ []
4023
4179
  );
4024
- if (createCrdtOp) {
4025
- this.#propToLastUpdate.set(key, nn(createCrdtOp.opId));
4180
+ return;
4181
+ }
4182
+ try {
4183
+ validateEntryConditions({
4184
+ filledEntry: postedEntry,
4185
+ sceneEvents: postedEntries,
4186
+ entryIndex
4187
+ });
4188
+ } catch (err) {
4189
+ if (err instanceof Error) {
4190
+ pushSceneEvent(
4191
+ {
4192
+ ...postedEntry,
4193
+ isValid: false,
4194
+ errorKind: "parameter_error",
4195
+ reasons: [`Error in entry condition: ${err.message}`]
4196
+ },
4197
+ []
4198
+ );
4026
4199
  }
4027
- ops.push(...newAttachChildOps);
4028
- } else {
4029
- updatedProps[key] = newValue;
4030
- this.#propToLastUpdate.set(key, opId);
4200
+ return;
4031
4201
  }
4032
- this.#map.set(key, newValue);
4033
- this.invalidate();
4034
- updateDelta[key] = { type: "update" };
4035
- }
4036
- if (Object.keys(reverseUpdateOp.data).length !== 0) {
4037
- reverseOps.unshift(reverseUpdateOp);
4038
- }
4039
- if (Object.keys(updatedProps).length !== 0) {
4040
- ops.unshift({
4041
- opId,
4042
- id: this._id,
4043
- type: 3,
4044
- data: updatedProps
4045
- });
4046
- }
4047
- const storageUpdates = /* @__PURE__ */ new Map();
4048
- storageUpdates.set(this._id, {
4049
- node: this,
4050
- type: "LiveObject",
4051
- updates: updateDelta
4052
- });
4053
- this._pool.dispatch(ops, reverseOps, storageUpdates);
4054
- }
4055
- toImmutable() {
4056
- return super.toImmutable();
4057
- }
4058
- /** @internal */
4059
- toTreeNode(key) {
4060
- return super.toTreeNode(key);
4061
- }
4062
- /** @internal */
4063
- _toTreeNode(key) {
4064
- const nodeId = this._id ?? nanoid();
4065
- return {
4066
- type: "LiveObject",
4067
- id: nodeId,
4068
- key,
4069
- payload: Array.from(this.#map.entries()).map(
4070
- ([key2, value]) => isLiveNode(value) ? value.toTreeNode(key2) : { type: "Json", id: `${nodeId}:${key2}`, key: key2, payload: value }
4071
- )
4072
- };
4073
- }
4074
- /** @internal */
4075
- _toImmutable() {
4076
- const result = {};
4077
- for (const [key, val] of this.#map) {
4078
- result[key] = isLiveStructure(val) ? val.toImmutable() : val;
4079
- }
4080
- return process.env.NODE_ENV === "production" ? result : Object.freeze(result);
4081
- }
4082
- clone() {
4083
- return new _LiveObject(
4084
- Object.fromEntries(
4085
- Array.from(this.#map).map(([key, value]) => [
4086
- key,
4087
- isLiveStructure(value) ? value.clone() : deepClone(value)
4088
- ])
4089
- )
4090
- );
4091
- }
4092
- };
4093
- function creationOpToLiveNode(op) {
4094
- return lsonToLiveNode(creationOpToLson(op));
4095
- }
4096
- function creationOpToLson(op) {
4097
- switch (op.type) {
4098
- case 8:
4099
- return op.data;
4100
- case 4:
4101
- return new LiveObject(op.data);
4102
- case 7:
4103
- return new LiveMap();
4104
- case 2:
4105
- return new LiveList([]);
4106
- default:
4107
- return assertNever(op, "Unknown creation Op");
4108
- }
4109
- }
4110
- function deserialize([id, crdt], parentToChildren, pool) {
4111
- switch (crdt.type) {
4112
- case 0: {
4113
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4114
- }
4115
- case 1: {
4116
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4117
- }
4118
- case 2: {
4119
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4120
- }
4121
- case 3: {
4122
- return LiveRegister._deserialize([id, crdt], parentToChildren, pool);
4123
- }
4124
- default: {
4125
- throw new Error("Unexpected CRDT type");
4126
- }
4127
- }
4128
- }
4129
- function deserializeToLson([id, crdt], parentToChildren, pool) {
4130
- switch (crdt.type) {
4131
- case 0: {
4132
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4133
4202
  }
4134
- case 1: {
4135
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4136
- }
4137
- case 2: {
4138
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4139
- }
4140
- case 3: {
4141
- return crdt.data;
4142
- }
4143
- default: {
4144
- throw new Error("Unexpected CRDT type");
4145
- }
4146
- }
4147
- }
4148
- function isLiveStructure(value) {
4149
- return isLiveList(value) || isLiveMap(value) || isLiveObject(value);
4150
- }
4151
- function isLiveNode(value) {
4152
- return isLiveStructure(value) || isLiveRegister(value);
4153
- }
4154
- function isLiveList(value) {
4155
- return value instanceof LiveList;
4156
- }
4157
- function isLiveMap(value) {
4158
- return value instanceof LiveMap;
4159
- }
4160
- function isLiveObject(value) {
4161
- return value instanceof LiveObject;
4162
- }
4163
- function isLiveRegister(value) {
4164
- return value instanceof LiveRegister;
4165
- }
4166
- function liveNodeToLson(obj) {
4167
- if (obj instanceof LiveRegister) {
4168
- return obj.data;
4169
- } else if (obj instanceof LiveList || obj instanceof LiveMap || obj instanceof LiveObject) {
4170
- return obj;
4171
- } else {
4172
- return assertNever(obj, "Unknown AbstractCrdt");
4173
- }
4174
- }
4175
- function lsonToLiveNode(value) {
4176
- if (value instanceof LiveObject || value instanceof LiveMap || value instanceof LiveList) {
4177
- return value;
4178
- } else {
4179
- return new LiveRegister(value);
4180
- }
4181
- }
4182
- var MAX_SOCKET_MESSAGE_SIZE = 1024 * 1024 - 512;
4183
- var htmlEscapables = {
4184
- "&": "&amp;",
4185
- "<": "&lt;",
4186
- ">": "&gt;",
4187
- '"': "&quot;",
4188
- "'": "&#39;"
4189
- };
4190
- var htmlEscapablesRegex = new RegExp(
4191
- Object.keys(htmlEscapables).map((entity) => `\\${entity}`).join("|"),
4192
- "g"
4193
- );
4194
- var markdownEscapables = {
4195
- _: "\\_",
4196
- "*": "\\*",
4197
- "#": "\\#",
4198
- "`": "\\`",
4199
- "~": "\\~",
4200
- "!": "\\!",
4201
- "|": "\\|",
4202
- "(": "\\(",
4203
- ")": "\\)",
4204
- "{": "\\{",
4205
- "}": "\\}",
4206
- "[": "\\[",
4207
- "]": "\\]"
4203
+ pushSceneEvent(postedEntry, lineAccountTypes);
4204
+ });
4205
+ return postedEntries;
4208
4206
  };
4209
- var markdownEscapablesRegex = new RegExp(
4210
- Object.keys(markdownEscapables).map((entity) => `\\${entity}`).join("|"),
4211
- "g"
4212
- );
4213
- detectDupes(PKG_NAME, PKG_VERSION, PKG_FORMAT);
4214
4207
 
4215
- // ../../node_modules/@liveblocks/client/dist/index.js
4216
- var PKG_NAME2 = "@liveblocks/client";
4217
- var PKG_VERSION2 = "3.7.1";
4218
- var PKG_FORMAT2 = "esm";
4219
- detectDupes(PKG_NAME2, PKG_VERSION2, PKG_FORMAT2);
4208
+ // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/simulateScene.ts
4209
+ var NO_SCENE_PAYMENTS = /* @__PURE__ */ new Map();
4210
+ var simulateScene = ({
4211
+ root,
4212
+ sceneId
4213
+ }) => {
4214
+ const scene = root.schema.scenes.get(sceneId);
4215
+ if (!scene)
4216
+ return null;
4217
+ const { chartOfAccounts } = root.schema;
4218
+ const accountIdToAccount = buildAccountIdToAccountRecord(chartOfAccounts);
4219
+ const { accountPathToAccount, defaultConsistencyConfig } = buildAccountPathToAccountMap(chartOfAccounts);
4220
+ const resolvedEvents = resolveSceneEvents({
4221
+ events: Array.from(scene.events.values()),
4222
+ eventsOrder: Array.from(scene.eventsOrder.values()),
4223
+ payments: scene.payments ?? NO_SCENE_PAYMENTS,
4224
+ paymentTypes: root.schema.paymentTypes
4225
+ });
4226
+ const entriesByKey = buildSceneEntriesByKey({
4227
+ resolvedEvents,
4228
+ root,
4229
+ accountPathToAccount,
4230
+ defaultConsistencyConfig
4231
+ });
4232
+ const events = transformLiveblocksSceneEvents(
4233
+ resolvedEvents,
4234
+ entriesByKey,
4235
+ accountIdToAccount
4236
+ );
4237
+ return {
4238
+ id: scene.id,
4239
+ name: scene.name ?? "",
4240
+ events
4241
+ };
4242
+ };
4220
4243
 
4221
- // ../../libs/liveblocks-commands/src/utils/liveObjectOf.ts
4244
+ // ../../fragment-compositions/visualizer/src/utils/liveblocksUtils.ts
4222
4245
  init_cjs_shims();
4223
- var liveObjectOf = (fields) => {
4224
- return new LiveObject(fields);
4225
- };
4246
+ import assert3 from "assert";
4226
4247
 
4227
4248
  // ../../libs/liveblocks-commands/src/utils/schemaConverters.ts
4228
4249
  init_cjs_shims();
@@ -4395,15 +4416,15 @@ var toLivePaymentAccounting = (accounting, accountIdByStructuralPath) => {
4395
4416
  settled: toLivePaymentEntry(accounting.settled, accountIdByStructuralPath),
4396
4417
  initiated: toOptionalEntry(accounting.initiated),
4397
4418
  refund_initiated: toOptionalEntry(accounting.refund_initiated),
4398
- refund_failed: toOptionalEntry(accounting.refund_failed)
4419
+ refund_failed: toOptionalEntry(accounting.refund_failed),
4420
+ chargeback_settled: toOptionalEntry(accounting.chargeback_settled),
4421
+ chargeback_countered: toOptionalEntry(accounting.chargeback_countered),
4422
+ chargeback_reversed: toOptionalEntry(accounting.chargeback_reversed)
4399
4423
  });
4400
4424
  };
4401
4425
  var toLivePaymentTypeVersion = (paymentType, versionId, accountIdByStructuralPath) => liveObjectOf({
4402
4426
  id: versionId,
4403
- payment: liveObjectOf({
4404
- amount: paymentType.payment.amount,
4405
- direction: paymentType.payment.direction
4406
- }),
4427
+ payment: makeLivePaymentDetails(paymentType.payment),
4407
4428
  status: paymentType.status,
4408
4429
  accounting: toLivePaymentAccounting(
4409
4430
  paymentType.accounting,