@fragment-dev/cli 2026.11.13-7 → 2026.11.14-1

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 (29) hide show
  1. package/dist/{chunk-3XCYMGE3.js → chunk-4AUNUT7Z.js} +4 -2
  2. package/dist/{chunk-2EZPMAOG.js → chunk-4KJOZZJJ.js} +1 -1
  3. package/dist/{chunk-5YXK5XSL.js → chunk-57YVQI74.js} +2 -2
  4. package/dist/{chunk-SBV53D6N.js → chunk-5Q5FY4NG.js} +2 -2
  5. package/dist/{chunk-FI2U3AB2.js → chunk-E72FRPF4.js} +8 -4
  6. package/dist/{chunk-GM4XMO7R.js → chunk-G5CBWM5A.js} +2 -2
  7. package/dist/{chunk-H34FQN7O.js → chunk-HHNGQYZB.js} +4 -4
  8. package/dist/{chunk-RBNP4MID.js → chunk-JVDAMJZJ.js} +2199 -2182
  9. package/dist/{chunk-P63ZOWQQ.js → chunk-K2KHRNPV.js} +9 -3
  10. package/dist/{chunk-BV3DJZN2.js → chunk-LGWOBHUY.js} +1 -1
  11. package/dist/{chunk-ZQ2XTJ24.js → chunk-QZ6NUJB5.js} +1 -1
  12. package/dist/{chunk-NUXJ4UQR.js → chunk-RG4CN74T.js} +162 -3
  13. package/dist/{chunk-TNZS3WJW.js → chunk-VY7NFMES.js} +2 -2
  14. package/dist/{chunk-CSP4CXUF.js → chunk-YV6J4BRT.js} +2 -2
  15. package/dist/commands/gen-graphql.js +4 -4
  16. package/dist/commands/print-schema.js +5 -5
  17. package/dist/commands/simulate-scenario.js +5 -5
  18. package/dist/commands/verify-schema.js +5 -5
  19. package/dist/commands.js +14 -14
  20. package/dist/graphql.js +2 -2
  21. package/dist/index.js +14 -14
  22. package/dist/utils/formatChartOfAccounts.js +3 -3
  23. package/dist/utils/formatEntries.js +3 -3
  24. package/dist/utils/formatScenarioAccountBalances.js +3 -3
  25. package/dist/utils/formatScenarioBalances.js +4 -4
  26. package/dist/utils/schemaBackCompat.js +4 -4
  27. package/dist/utils/schemaValidation.js +3 -3
  28. package/oclif.manifest.json +1 -1
  29. package/package.json +1 -1
@@ -7,7 +7,7 @@ import {
7
7
  generateSimulatingEntry,
8
8
  lil_id_default,
9
9
  makeLineKey
10
- } from "./chunk-2EZPMAOG.js";
10
+ } from "./chunk-4KJOZZJJ.js";
11
11
  import {
12
12
  formatBalance,
13
13
  getBalancePrecision
@@ -33,7 +33,7 @@ import {
33
33
  validateLedgerConsistencySettings,
34
34
  validatePaymentEntry,
35
35
  z as z2
36
- } from "./chunk-NUXJ4UQR.js";
36
+ } from "./chunk-RG4CN74T.js";
37
37
  import {
38
38
  BaseSchema,
39
39
  PaymentAccountingEventKey,
@@ -41,7 +41,7 @@ import {
41
41
  SystemLineParameterName,
42
42
  fillParams,
43
43
  getSchemaObjectParameters
44
- } from "./chunk-3XCYMGE3.js";
44
+ } from "./chunk-4AUNUT7Z.js";
45
45
  import {
46
46
  InternalError,
47
47
  assert_default
@@ -408,1908 +408,882 @@ var validateAndTransformEntryVersion = ({
408
408
 
409
409
  // ../../libs/liveblocks-commands/src/utils/paymentTypeValidation.ts
410
410
  init_cjs_shims();
411
- var convertLiveLine = (line) => ({
412
- key: line.key,
413
- account: line.account ? { path: line.account.path } : void 0,
414
- amount: line.amount ?? "",
415
- currency: line.currency ? {
416
- code: line.currency.code,
417
- customCurrencyId: line.currency.customCurrencyId
418
- } : void 0,
419
- description: line.description,
420
- system: line.system
421
- });
422
- var convertLiveEntry = (entry) => ({
423
- description: entry.description,
424
- lines: Array.from(entry.linesOrder.values()).map((lineId) => entry.lines.get(lineId)).filter((line) => line !== void 0).map(convertLiveLine)
425
- });
426
- var validateLivePaymentEntry = ({
427
- entryVersion,
428
- event,
429
- entryIdentity,
430
- accountPathToAccount
431
- }) => validatePaymentEntry({
432
- entry: convertLiveEntry(entryVersion),
433
- event,
434
- entryIdentity,
435
- accountPathToAccount,
436
- paymentAccountPath: findPaymentAccountPath(accountPathToAccount)
437
- });
438
411
 
439
- // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
412
+ // ../../libs/liveblocks-commands/src/utils/makeLivePaymentDetails.ts
440
413
  init_cjs_shims();
441
414
 
442
- // ../../libs/payment-commands/utils/amount.ts
415
+ // ../../node_modules/@liveblocks/client/dist/index.js
443
416
  init_cjs_shims();
444
417
 
445
- // ../../libs/types/payment.ts
418
+ // ../../node_modules/@liveblocks/core/dist/index.js
446
419
  init_cjs_shims();
447
- var MIN_PAYMENT_AMOUNT_CENTS = 100n;
448
- var MAX_PAYMENT_AMOUNT_CENTS = 10000000n;
449
- var formatUsd = (cents) => `$${(cents / 100n).toLocaleString("en-US")}.${(cents % 100n).toString().padStart(2, "0")}`;
450
- var PAYMENT_AMOUNT_RANGE_MESSAGE = `Amount must be between ${formatUsd(
451
- MIN_PAYMENT_AMOUNT_CENTS
452
- )} and ${formatUsd(MAX_PAYMENT_AMOUNT_CENTS)}`;
453
- var PaymentMode = /* @__PURE__ */ ((PaymentMode2) => {
454
- PaymentMode2["sandbox"] = "sandbox";
455
- PaymentMode2["glassbox"] = "glassbox";
456
- return PaymentMode2;
457
- })(PaymentMode || {});
458
- var PaymentModeSchema = z.nativeEnum(PaymentMode);
459
- var ApiPaymentMode = /* @__PURE__ */ ((ApiPaymentMode2) => {
460
- ApiPaymentMode2["sandbox"] = "sandbox";
461
- ApiPaymentMode2["production"] = "production";
462
- return ApiPaymentMode2;
463
- })(ApiPaymentMode || {});
464
- var ApiPaymentModeSchema = z.nativeEnum(ApiPaymentMode);
465
- var PaymentPersistenceEvent = {
466
- /** The Payment was created. */
467
- created: "created",
468
- /** The payer went through checkout; posted when the Payment enters `processing`. */
469
- checkout: "checkout",
470
- /** The Customer retried the Payment on a saved payment method; posted when the Payment enters `processing`. */
471
- retry: "retry",
472
- /** The card network captured the payment; it is guaranteed to settle. */
473
- card_captured: "card_captured",
474
- /** Stripe declined an attempt, or refused to create a PaymentIntent for it. */
475
- card_declined: "card_declined",
476
- /** The payer abandoned or failed an attempt's 3DS challenge. */
477
- card_3ds_canceled: "card_3ds_canceled",
478
- /** The payment was settled. */
479
- settled: "settled",
480
- /** A Fragment Payment refund record was created. */
481
- refund_initiated: "refund_initiated",
482
- /** A Fragment Payment refund cleared its in-transit account. */
483
- refund_settled: "refund_settled",
484
- /** Stripe declined a Fragment Payment refund. */
485
- refund_failed: "refund_failed"
486
- };
487
- var PaymentPersistenceEventSchema = z.nativeEnum(
488
- PaymentPersistenceEvent
489
- );
490
- var InternalPaymentAttemptStatus = {
491
- /** Payment attempt not yet sent to Stripe. */
492
- created: "created",
493
- /** Payment attempt has been sent to Stripe and is being processed. */
494
- processing: "processing",
495
- /** Payment attempt has been accepted. */
496
- accepted: "accepted",
497
- /** Payment attempt has been declined. */
498
- declined: "declined",
499
- /** Stripe refused to create a PaymentIntent for the attempt. */
500
- rejected: "rejected",
501
- /** The payer abandoned or failed the attempt's 3DS challenge. */
502
- canceled: "canceled",
503
- /** Payment attempt needs action from the payer. No stored shape yet. */
504
- needs_action: "needs_action"
505
- };
506
- var EXTERNAL_PAYMENT_ATTEMPT_STATUSES = {
507
- [InternalPaymentAttemptStatus.created]: "processing" /* processing */,
508
- [InternalPaymentAttemptStatus.processing]: "processing" /* processing */,
509
- [InternalPaymentAttemptStatus.needs_action]: "processing" /* processing */,
510
- [InternalPaymentAttemptStatus.accepted]: "succeeded" /* succeeded */,
511
- [InternalPaymentAttemptStatus.declined]: "failed" /* failed */,
512
- [InternalPaymentAttemptStatus.rejected]: "failed" /* failed */,
513
- [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 });
514
424
  };
515
- var paymentCurrencyCodes = [
516
- "USD"
517
- ];
518
- var PaymentCurrencyCodeSchema = z.enum(paymentCurrencyCodes);
519
- var ExternalAccountMatchInput = z.object({
520
- id: ParameterizedString.optional(),
521
- /** The External systems's ID of the account */
522
- externalId: ParameterizedString.optional(),
523
- /** The Fragment ID of the link */
524
- linkId: ParameterizedString.optional()
525
- });
526
-
527
- // ../../libs/payment-commands/utils/amount.ts
528
- var MAX_AMOUNT_CENTS = 2n ** 46n * 100n;
529
- var DEFAULT_FRAGMENT_FEE_SCHEDULE = {
530
- ["card_payin" /* card_payin */]: {
531
- rateBps: 290n,
532
- 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);
533
437
  }
534
- };
535
- var BPS_DENOMINATOR = 10000n;
536
- var calculateFragmentFeeCents = ({
537
- settledCents,
538
- schedule
539
- }) => {
540
- assert_default(settledCents >= 0n, InternalError, {
541
- info: { settledCents },
542
- message: `Expected a non-negative settled amount, got ${settledCents}`
543
- });
544
- return schedule.fixedCents + (settledCents * schedule.rateBps + BPS_DENOMINATOR / 2n) / BPS_DENOMINATOR;
545
- };
546
- var IntegerAmountSchema = z.string().regex(/^-?\d+$/).transform(BigInt);
547
-
548
- // ../../libs/shared-utils/parameterization.ts
549
- init_cjs_shims();
550
-
551
- // ../../libs/liveblocks-commands/src/utils/scenarioPayments.ts
552
- var SCENARIO_FRAGMENT_FEE_PERCENT = Number(DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].rateBps) / 100;
553
- var SCENARIO_FRAGMENT_FEE_FIXED_CENTS = Number(
554
- DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */].fixedCents
555
- );
556
- var evaluatePaymentAmount = (expression, parameters) => {
557
- const filled = fillParams(expression, parameters, {
558
- allowMissing: true,
559
- allowMissingInChildren: true
560
- }).trim();
561
- try {
562
- return { kind: "amount", amount: evaluateExpression(filled) };
563
- } catch {
564
- 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;
565
502
  }
566
- };
567
- var computeScenarioFee = (amount) => {
568
- const fee = calculateFragmentFeeCents({
569
- settledCents: amount < 0n ? -amount : amount,
570
- schedule: DEFAULT_FRAGMENT_FEE_SCHEDULE["card_payin" /* card_payin */]
571
- });
572
- return amount < 0n ? -fee : fee;
573
- };
574
-
575
- // ../../libs/liveblocks-commands/src/utils/sceneEventResolution.ts
576
- var PAYMENT_GONE_FROM_SCENARIO_REASON = "This payment is no longer in the scenario. Remove this row.";
577
- var PAYMENT_GONE_FROM_SCHEMA_REASON = "This payment is no longer in the schema. Remove this row.";
578
- var SETTLED_BEFORE_APPROVAL_REASON = "This payment settles before it is approved \u2014 move the settled row after its approved row.";
579
- 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.";
580
- var makeUnevaluatedAmountReason = (expression) => `Payment amount '${expression}' did not evaluate to a whole number. Check the parameters it references.`;
581
- var getLedgerSceneEventEntryId = (event) => ({
582
- flavor: "ledger",
583
- entryTypeId: event.entry.entryTypeId ?? "",
584
- entryTypeVersionId: event.entry.entryTypeVersionId ?? ""
585
- });
586
- var getPaymentVersionContext = (paymentTypes, payment) => {
587
- const paymentType = paymentTypes?.types.get(payment.paymentTypeId);
588
- const version = paymentType?.versions.get(payment.paymentTypeVersionId);
589
- if (!paymentType || !version)
590
- return null;
591
503
  return {
592
- paymentType: paymentType.type,
593
- amountExpression: version.payment.amount,
594
- lifecycleEvents: SCENE_PAYMENT_ACCOUNTING_EVENT_KEYS.filter(
595
- (event) => getPaymentEntryFromVersion(version, event) !== null
596
- )
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
+ }
597
519
  };
598
- };
599
- var withSystemParameters = (parameters, amountExpression, event) => {
600
- const evaluated = evaluatePaymentAmount(amountExpression, parameters);
601
- if (evaluated.kind !== "amount")
602
- return null;
603
- const amount = evaluated.amount.toString();
604
- const systemParameters = z2(event).with(PaymentAccountingEventKey.initiated, () => ({})).with(PaymentAccountingEventKey.settled, () => ({
605
- [SystemLineParameterName.payment_settlement_line]: amount,
606
- [SystemLineParameterName.payment_fee_line]: computeScenarioFee(
607
- evaluated.amount
608
- ).toString()
609
- })).with(
610
- PaymentAccountingEventKey.refund_initiated,
611
- PaymentAccountingEventKey.refund_failed,
612
- () => ({
613
- [SystemLineParameterName.payment_refund_line]: amount
614
- })
615
- ).exhaustive();
616
- return { ...parameters, ...systemParameters };
617
- };
618
- var getPaymentLifecycleFailure = ({
619
- lifecycleEvents,
620
- eventIndexByEvent
621
- }) => {
622
- const lifecycleSteps = lifecycleEvents.slice(1).map((event2, position) => {
623
- const previousEvent2 = lifecycleEvents[position];
624
- return {
625
- event: event2,
626
- previousEvent: previousEvent2,
627
- eventRowIndex: eventIndexByEvent.get(event2),
628
- previousEventRowIndex: eventIndexByEvent.get(previousEvent2)
629
- };
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
+ }
630
538
  });
631
- const invalidStep = lifecycleSteps.find(
632
- ({ eventRowIndex, previousEventRowIndex: previousEventRowIndex2 }) => eventRowIndex !== void 0 && (previousEventRowIndex2 === void 0 || previousEventRowIndex2 > eventRowIndex)
633
- );
634
- if (!invalidStep)
635
- return void 0;
636
- const { event, previousEvent, previousEventRowIndex } = invalidStep;
637
- if (event === PaymentAccountingEventKey.settled && previousEvent === PaymentAccountingEventKey.initiated) {
638
- 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);
639
563
  }
640
- 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.`;
641
- };
642
- var findInvalidPaymentEvents = (orderedEvents, lifecycleEventsByPaymentId) => {
643
- const eventIndexesByPaymentId = /* @__PURE__ */ new Map();
644
- orderedEvents.forEach((event, index) => {
645
- if (event.eventType !== "payment-entry")
646
- return;
647
- const eventIndexByEvent = eventIndexesByPaymentId.get(event.entry.paymentId) ?? /* @__PURE__ */ new Map();
648
- eventIndexByEvent.set(event.entry.event, index);
649
- eventIndexesByPaymentId.set(event.entry.paymentId, eventIndexByEvent);
650
- });
651
- const invalidReasonsById = /* @__PURE__ */ new Map();
652
- eventIndexesByPaymentId.forEach((eventIndexByEvent, paymentId) => {
653
- const lifecycleEvents = lifecycleEventsByPaymentId.get(paymentId);
654
- if (!lifecycleEvents)
655
- return;
656
- const failure = getPaymentLifecycleFailure({
657
- lifecycleEvents,
658
- eventIndexByEvent
659
- });
660
- if (failure === void 0)
661
- return;
662
- orderedEvents.forEach((event) => {
663
- if (event.eventType === "payment-entry" && event.entry.paymentId === paymentId) {
664
- 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;
665
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();
666
595
  });
667
- });
668
- return invalidReasonsById;
669
- };
670
- var resolvePaymentEvent = ({
671
- event,
672
- payments,
673
- paymentTypes,
674
- invalidPaymentReasonsById
675
- }) => {
676
- const payment = payments.get(event.entry.paymentId);
677
- if (!payment) {
678
- return {
679
- id: event.id,
680
- entryId: null,
681
- idKey: null,
682
- parameters: {},
683
- repeatedParameters: {},
684
- failure: {
685
- errorKind: "entry_invalid",
686
- reasons: [PAYMENT_GONE_FROM_SCENARIO_REASON]
687
- }
688
- };
596
+ return unsub;
689
597
  }
690
- const entryId = makePaymentEntryId(
691
- payment.paymentTypeId,
692
- payment.paymentTypeVersionId,
693
- event.entry.event
694
- );
695
- const context = getPaymentVersionContext(paymentTypes, payment);
696
- const instanceParameters = payment.parameters;
697
- const base = {
698
- id: event.id,
699
- entryId,
700
- idKey: getEntryIdKey(entryId),
701
- payment: {
702
- paymentType: context?.paymentType ?? "unknown",
703
- event: event.entry.event,
704
- ik: payment.ik
705
- },
706
- parameters: instanceParameters,
707
- repeatedParameters: {}
708
- };
709
- const fail = (errorKind, reason) => ({
710
- ...base,
711
- failure: { errorKind, reasons: [reason] }
712
- });
713
- if (!context)
714
- return fail("entry_invalid", PAYMENT_GONE_FROM_SCHEMA_REASON);
715
- const invalidPaymentReason = invalidPaymentReasonsById.get(event.id);
716
- if (invalidPaymentReason !== void 0) {
717
- return fail("entry_invalid", invalidPaymentReason);
598
+ waitUntil() {
599
+ throw new Error("waitUntil not supported on Signals");
718
600
  }
719
- const parameters = withSystemParameters(
720
- instanceParameters,
721
- context.amountExpression,
722
- event.entry.event
723
- );
724
- if (parameters === null) {
725
- return fail(
726
- "parameter_error",
727
- makeUnevaluatedAmountReason(context.amountExpression)
728
- );
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;
729
614
  }
730
- return { ...base, parameters };
731
615
  };
732
- var resolveSceneEvents = ({
733
- events,
734
- eventsOrder,
735
- payments,
736
- paymentTypes
737
- }) => {
738
- const eventsById = new Map(events.map((event) => [event.id, event]));
739
- const orderedEvents = eventsOrder.map((eventId) => eventsById.get(eventId)).filter((event) => event !== void 0);
740
- const lifecycleEventsByPaymentId = /* @__PURE__ */ new Map();
741
- payments.forEach((payment, paymentId) => {
742
- const context = getPaymentVersionContext(paymentTypes, payment);
743
- if (context) {
744
- lifecycleEventsByPaymentId.set(paymentId, context.lifecycleEvents);
745
- }
746
- });
747
- const invalidPaymentReasonsById = findInvalidPaymentEvents(
748
- orderedEvents,
749
- lifecycleEventsByPaymentId
750
- );
751
- return orderedEvents.map(
752
- (event) => z2(event).with({ eventType: "entry" }, (ledgerEvent) => {
753
- const entryId = getLedgerSceneEventEntryId(ledgerEvent);
754
- return {
755
- id: ledgerEvent.id,
756
- entryId,
757
- idKey: getEntryIdKey(entryId),
758
- parameters: ledgerEvent.entry.parameters,
759
- repeatedParameters: ledgerEvent.entry.repeatedParameters ?? {}
760
- };
761
- }).with(
762
- { eventType: "payment-entry" },
763
- (paymentEvent) => resolvePaymentEvent({
764
- event: paymentEvent,
765
- payments,
766
- paymentTypes,
767
- invalidPaymentReasonsById
768
- })
769
- ).exhaustive()
770
- );
771
- };
772
- var buildSceneEntriesByKey = ({
773
- resolvedEvents,
774
- root,
775
- accountPathToAccount,
776
- defaultConsistencyConfig
777
- }) => {
778
- const entriesByKey = /* @__PURE__ */ new Map();
779
- resolvedEvents.forEach(({ entryId, idKey }) => {
780
- if (!entryId || !idKey || entriesByKey.has(idKey))
781
- return;
782
- const entryType = getEntryTypeFromRoot(root, entryId);
783
- if (!entryType)
784
- return;
785
- const entryVersion = getEntryVersionFromRoot(root, entryId);
786
- if (!entryVersion)
787
- return;
788
- if (entryId.flavor === "ledger") {
789
- entriesByKey.set(
790
- idKey,
791
- validateAndTransformEntryVersion({
792
- entryType,
793
- entryVersion,
794
- accountPathToAccount,
795
- defaultConsistencyConfig
796
- })
797
- );
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) {
798
707
  return;
799
708
  }
800
- entriesByKey.set(
801
- idKey,
802
- transformEntryVersion({
803
- entryType,
804
- entryVersion,
805
- accountPathToAccount,
806
- errors: validateLivePaymentEntry({
807
- entryVersion,
808
- event: entryId.event,
809
- entryIdentity: entryType.type,
810
- accountPathToAccount
811
- })
812
- })
813
- );
814
- });
815
- return entriesByKey;
816
- };
817
-
818
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/EntryValidationUtils.ts
819
- init_cjs_shims();
820
- var buildAccountIdToAccountRecord = (chartOfAccounts) => {
821
- if (!chartOfAccounts)
822
- return {};
823
- const accountsMap = new Map(
824
- Array.from(chartOfAccounts.accounts.entries())
825
- );
826
- const accountIds = {};
827
- chartOfAccounts.accounts.forEach((account, accountId) => {
828
- const structuralPath = computeStructuralPath(
829
- accountId,
830
- accountsMap,
831
- account.parentId
832
- );
833
- accountIds[structuralPath] = accountId;
834
- });
835
- const filledIn = buildAndValidateChartOfAccounts(chartOfAccounts);
836
- const enhancedCoA = enhanceCoA(filledIn, { accountIds });
837
- return enhancedCoA.accountIdToAccount;
709
+ const updated = this.#recompute();
710
+ if (updated) {
711
+ super[kTrigger]();
712
+ }
713
+ }
838
714
  };
839
-
840
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
841
- init_cjs_shims();
842
-
843
- // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
844
- init_cjs_shims();
845
- import assert from "assert";
846
-
847
- // ../../libs/schema-validation/utils/transformers/schema.ts
848
- init_cjs_shims();
849
- var transformAndValidateSchema = (schema) => {
850
- const errors = [];
851
- const schemaKeyResult = SafeStringSchema.safeParse(schema.key);
852
- if (!schemaKeyResult.success || schemaKeyResult.data.includes("{{") || schemaKeyResult.data.includes("}}")) {
853
- errors.push({
854
- message: `Invalid key. Keys cannot contain '{{' or '}}' and must be non-empty`,
855
- path: ["key"]
856
- });
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
+ }
857
725
  }
858
- const res = transformAndValidateCoA({
859
- coa: schema.chartOfAccounts
860
- });
861
- const { errors: coaErrors } = res;
862
- const validatedChartOfAccounts = res.filledIn;
863
- errors.push(
864
- ...coaErrors.map((e) => ({ ...e, path: ["chartOfAccounts", ...e.path] }))
865
- );
866
- const { filledIn: ledgerEntries, errors: entryErrors } = transformAndValidateEntries({
867
- ledgerEntries: schema.ledgerEntries ?? { types: [] },
868
- validatedCoA: validatedChartOfAccounts
869
- });
870
- errors.push(
871
- ...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)
872
744
  );
873
- const { errors: paymentErrors } = transformAndValidatePayments({
874
- payments: schema.payments ?? { types: [] },
875
- validatedCoA: validatedChartOfAccounts
876
- });
877
- errors.push(
878
- ...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
+ )
879
758
  );
880
- const consistencyErrors = schema.consistencyConfig ? validateLedgerConsistencySettings(schema.consistencyConfig) : { errors: [] };
881
- errors.push(...consistencyErrors.errors);
882
- const groups = schema.groups ?? [];
883
- if (groups.length > 0) {
884
- groups.forEach((group, index) => {
885
- const groupErrors = validateGroup(
886
- group,
887
- validatedChartOfAccounts,
888
- ledgerEntries,
889
- index
890
- );
891
- errors.push(...groupErrors);
892
- });
893
- }
894
- return {
895
- errors,
896
- validatedSchema: {
897
- name: schema.name,
898
- key: schema.key,
899
- consistencyConfig: schema.consistencyConfig?.entries ? {
900
- entries: schema.consistencyConfig.entries
901
- } : {
902
- entries: "eventual"
903
- },
904
- ledgerEntries,
905
- chartOfAccounts: validatedChartOfAccounts,
906
- scenes: schema.scenes,
907
- groups,
908
- 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
+ () => {
909
772
  }
910
- };
911
- };
912
-
913
- // ../../libs/shared-utils/accounting/currency.ts
914
- init_cjs_shims();
915
-
916
- // ../../libs/shared-utils/accounting/doubleEntry.ts
917
- init_cjs_shims();
918
-
919
- // ../../fragment-compositions/visualizer/src/libs/FragmentBackendMock.ts
920
- var formatSchemaValidationError = (error3) => {
921
- const path = error3.path.length > 0 ? ` (Path: ${error3.path.join("/")})` : "";
922
- const code = error3.code ? ` [${error3.code}]` : "";
923
- return `${error3.message}${code}${path}`;
924
- };
925
- var getBaseEntryParameters = (entry, accountIdToAccount) => {
926
- const allParams = new Set(
927
- [
928
- ...getSchemaObjectParameters(entry, false),
929
- ...entry.lines.flatMap(
930
- ({ account }) => account?.id ? getSchemaObjectParameters(accountIdToAccount[account.id], false) : []
931
- )
932
- ].filter((param) => !entry.parameters[param])
933
773
  );
934
- return [...allParams];
935
- };
936
- var validateEntryConditions = ({
937
- filledEntry,
938
- sceneEvents,
939
- entryIndex
940
- }) => {
941
- filledEntry.conditions.forEach((condition) => {
942
- const { path } = condition.account;
943
- const { currency } = condition;
944
- assert(
945
- currency.code !== "MULTI",
946
- `Invalid Condition. Condition in Entry ${filledEntry.type} on multi-currency Ledger Account ${path} must have a currency set`
947
- );
948
- const matchesPath = {
949
- ownBalance: (linePath) => linePath === path,
950
- totalBalance: (linePath) => linePath === path || linePath.startsWith(`${path}/`)
951
- };
952
- const sumLines = (lines, scope) => lines.filter(
953
- (line) => matchesPath[scope](line.account.path) && line.currency.code === currency.code && line.currency.customCurrencyId === currency.customCurrencyId
954
- ).reduce(
955
- (sum, line) => sum + BigInt(evaluateExpression(line.amount)),
956
- 0n
957
- );
958
- const sumPriorLines = (scope) => sceneEvents.slice(0, entryIndex).reduce(
959
- (sum, { entry: balanceEntry }) => sum + (balanceEntry.isValid ? sumLines(balanceEntry.lines, scope) : 0n),
960
- 0n
961
- );
962
- const checkBoundary = (kind, scope, amount, bounds) => {
963
- if (!bounds)
964
- return;
965
- const label = kind === "precondition" ? "Precondition" : "Postcondition";
966
- const when = kind === "precondition" ? "before posting this entry" : "after posting this entry";
967
- const checks = [
968
- ["=", bounds.eq, (a, b) => a === b],
969
- [">=", bounds.gte, (a, b) => a >= b],
970
- ["<=", bounds.lte, (a, b) => a <= b]
971
- ];
972
- checks.forEach(([op, rhs, cmp]) => {
973
- if (rhs === void 0)
974
- return;
975
- assert(
976
- cmp(amount, BigInt(evaluateExpression(rhs))),
977
- `${label} not satisfied. Ledger Account ${path} must have ${scope} ${op} ${rhs} ${when}. Got: ${amount}`
978
- );
979
- });
980
- };
981
- const preOwn = sumPriorLines("ownBalance");
982
- const preTotal = sumPriorLines("totalBalance");
983
- checkBoundary(
984
- "precondition",
985
- "ownBalance",
986
- preOwn,
987
- condition.precondition?.ownBalance
988
- );
989
- checkBoundary(
990
- "precondition",
991
- "totalBalance",
992
- preTotal,
993
- condition.precondition?.totalBalance
994
- );
995
- const postOwn = preOwn + sumLines(filledEntry.lines, "ownBalance");
996
- const postTotal = preTotal + sumLines(filledEntry.lines, "totalBalance");
997
- checkBoundary(
998
- "postcondition",
999
- "ownBalance",
1000
- postOwn,
1001
- condition.postcondition?.ownBalance
1002
- );
1003
- checkBoundary(
1004
- "postcondition",
1005
- "totalBalance",
1006
- postTotal,
1007
- condition.postcondition?.totalBalance
1008
- );
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
+ }
1009
796
  });
1010
- };
1011
- var validateEntry2 = ({
1012
- accountIdToAccount,
1013
- baseEntry,
1014
- errors,
1015
- entry,
1016
- parameterValues
1017
- }) => {
1018
- try {
1019
- if (baseEntry) {
1020
- if (errors.length > 0) {
1021
- return {
1022
- errorKind: "entry_invalid",
1023
- reasons: errors.map(formatSchemaValidationError)
1024
- };
1025
- }
1026
- const parameters = getBaseEntryParameters(baseEntry, accountIdToAccount);
1027
- const missingParams = parameters.filter(
1028
- (param) => !parameterValues[param]
1029
- );
1030
- if (missingParams.length) {
1031
- 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);
1032
837
  }
838
+ } else {
839
+ return pos.substring(0, i + 1);
1033
840
  }
1034
- const lineValues = {};
1035
- entry.lines.forEach((line) => {
1036
- line.amountParameters.forEach((param) => {
1037
- assert(
1038
- !Number.isNaN(parseInt(parameterValues[param], 10)),
1039
- `Parameter ${param} must have numeric value`
1040
- );
1041
- });
1042
- });
1043
- const filledEntry = fillParams(entry, {
1044
- ...parameterValues,
1045
- ...entry.parameters
1046
- });
1047
- filledEntry.lines.forEach((line, lineNumber) => {
1048
- const key = makeLineKey(line, lineNumber);
1049
- const amount = line.amount && evaluateExpression(line.amount);
1050
- lineValues[key] = {
1051
- amount: Number(amount)
1052
- };
1053
- });
1054
- assert(
1055
- filledEntry.lines.every(
1056
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1057
- (line, lineNumber) => lineValues[makeLineKey(line, lineNumber)]
1058
- ),
1059
- "All amounts must be populated"
1060
- );
1061
- const accountsForBalancedPayload = {};
1062
- const linesForBalancedPayload = filledEntry.lines.map(
1063
- (line, lineNumber) => {
1064
- const lineKey = makeLineKey(line, lineNumber);
1065
- const fetchedAccount = accountIdToAccount[line.account.id];
1066
- const accountType = fetchedAccount.type;
1067
- if (accountType === void 0) {
1068
- throw new Error(
1069
- `Could not determine account type for path ${fetchedAccount.structuralPath}`
1070
- );
1071
- }
1072
- const account = {
1073
- currency: CurrencyCodeSchema.parse(line.currency.code),
1074
- customCurrencyId: line.currency.customCurrencyId,
1075
- type: accountType
1076
- };
1077
- const accountKey = `${fetchedAccount.structuralPath}:${serializeCurrency(account)}`;
1078
- accountsForBalancedPayload[accountKey] = account;
1079
- return {
1080
- currency: line.currency.code,
1081
- customCurrencyId: line.currency.customCurrencyId,
1082
- amount: BigInt(lineValues[lineKey].amount),
1083
- account: {
1084
- id: accountKey
1085
- }
1086
- };
1087
- }
1088
- );
1089
- assertBalancedLines({
1090
- // @ts-expect-error TODO: make visualizer support parameterized currencies after https://github.com/fragment-dev/workspaces/pull/3076/files is merged
1091
- lines: linesForBalancedPayload,
1092
- ledgerAccounts: accountsForBalancedPayload
1093
- });
1094
- return { lineValues, filledEntry };
1095
- } catch (err) {
1096
- if (err instanceof Error) {
1097
- 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;
1098
849
  }
1099
- throw err;
850
+ return pos.substring(0, i) + String.fromCharCode(code + 1);
1100
851
  }
1101
- };
1102
- var generatePostedEntry = ({
1103
- accountIdToAccount,
1104
- baseEntry,
1105
- errors,
1106
- entry,
1107
- postedEntryId,
1108
- parameterValues
1109
- }) => {
1110
- const entryId = postedEntryId || lil_id_default();
1111
- const validation = validateEntry2({
1112
- accountIdToAccount,
1113
- baseEntry,
1114
- errors,
1115
- entry,
1116
- parameterValues
1117
- });
1118
- if ("reasons" in validation) {
1119
- return {
1120
- isValid: false,
1121
- errorKind: validation.errorKind,
1122
- reasons: validation.reasons,
1123
- id: entryId,
1124
- type: entry.type,
1125
- typeVersion: entry.typeVersion,
1126
- baseEntryId: entry.id,
1127
- parameters: parameterValues
1128
- };
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");
1129
861
  }
1130
- const { filledEntry, lineValues } = validation;
1131
- return {
1132
- id: entryId,
1133
- typeVersion: filledEntry.typeVersion,
1134
- ik: lil_id_default(),
1135
- type: filledEntry.type,
1136
- parameters: parameterValues,
1137
- conditions: filledEntry.conditions,
1138
- lines: filledEntry.lines.map(
1139
- (line, lineNumber) => ({
1140
- ...line,
1141
- amount: String(lineValues[makeLineKey(line, lineNumber)].amount)
1142
- })
1143
- ),
1144
- tags: filledEntry.tags,
1145
- groups: filledEntry.groups,
1146
- baseEntryId: entry.id,
1147
- isValid: true,
1148
- status: filledEntry.status ?? "active"
1149
- };
1150
- };
1151
-
1152
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Entries/useEntryUtils.ts
1153
- init_cjs_shims();
1154
- var convertEntryResponseToEnhancedSchemaLedgerEntry = (entry, accountIdToAccount) => {
1155
- const baseEntry = {
1156
- type: entry.value.type,
1157
- typeVersion: entry.value.typeVersion,
1158
- description: entry.value.description,
1159
- postLinesAs: entry.value.postLinesAs,
1160
- status: entry.value.status,
1161
- parameters: convertStaticParametersToRecord(entry.value.parameters) ?? {},
1162
- groups: entry.value.groups?.map((group) => ({
1163
- key: safe`${group.key}`,
1164
- value: group.value
1165
- })) ?? [],
1166
- tags: entry.value.tags?.map((tag) => ({
1167
- key: tag.key,
1168
- value: tag.value
1169
- })) ?? [],
1170
- lines: entry.value.lines?.map((line) => ({
1171
- key: line.key,
1172
- account: line.account ? {
1173
- id: line.account.accountId ?? "",
1174
- path: line.account.path
1175
- } : void 0,
1176
- amount: line.amount,
1177
- currency: line.currency,
1178
- description: line.description,
1179
- tx: line.tx,
1180
- repeated: line.repeated ? { key: safe`${line.repeated.key}` } : void 0
1181
- })) ?? [],
1182
- conditions: entry.value.conditions?.map((condition) => ({
1183
- account: condition.account ? {
1184
- id: condition.account.accountId ?? "",
1185
- path: condition.account.path
1186
- } : void 0,
1187
- currency: condition.currency,
1188
- precondition: condition.precondition,
1189
- postcondition: condition.postcondition,
1190
- repeated: condition.repeated ? { key: safe`${condition.repeated.key}` } : void 0
1191
- })) ?? []
1192
- };
1193
- return enhanceLedgerEntry(
1194
- baseEntry,
1195
- accountIdToAccount,
1196
- safe`${entry.value.typeVersion && entry.value.typeVersion > 1 ? entry.value.versionId : entry.value.entryId}`
1197
- );
1198
- };
1199
-
1200
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/ScenarioValidationUtils.ts
1201
- var transformLiveblocksSceneEvents = (resolvedEvents, entriesByKey, accountIdToAccount) => {
1202
- const accountMap = new Map(Object.entries(accountIdToAccount));
1203
- const postedEntries = [];
1204
- resolvedEvents.forEach((event, entryIndex) => {
1205
- const { entryId, idKey, payment: paymentInfo } = event;
1206
- const baseEntryResponse = idKey === null ? void 0 : entriesByKey.get(idKey);
1207
- const baseEntryId = (entryId && (entryId.flavor === "payment" ? entryId.paymentTypeId : entryId.entryTypeId)) ?? "";
1208
- const repeatedParams = event.repeatedParameters;
1209
- const staticParams = event.parameters;
1210
- const pushSceneEvent = (entry, lineAccountTypes2) => {
1211
- postedEntries.push(
1212
- paymentInfo ? {
1213
- id: event.id,
1214
- eventType: "payment-entry",
1215
- entry,
1216
- payment: paymentInfo,
1217
- entryId,
1218
- lineAccountTypes: lineAccountTypes2
1219
- } : {
1220
- id: event.id,
1221
- eventType: "entry",
1222
- entry,
1223
- entryId,
1224
- lineAccountTypes: lineAccountTypes2
1225
- }
1226
- );
1227
- };
1228
- const pushInvalidSceneEvent = (errorKind, reasons) => {
1229
- pushSceneEvent(
1230
- {
1231
- id: event.id,
1232
- parameters: { ...staticParams, ...repeatedParams },
1233
- baseEntryId,
1234
- type: paymentInfo?.paymentType ?? "unknown",
1235
- isValid: false,
1236
- errorKind,
1237
- reasons
1238
- },
1239
- []
1240
- );
1241
- };
1242
- if (event.failure) {
1243
- pushInvalidSceneEvent(event.failure.errorKind, event.failure.reasons);
1244
- return;
1245
- }
1246
- if (!baseEntryResponse) {
1247
- pushInvalidSceneEvent("entry_invalid", [
1248
- entryId?.flavor === "payment" ? PAYMENT_GONE_FROM_SCHEMA_REASON : "Entry not found"
1249
- ]);
1250
- 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;
1251
873
  }
1252
- const lineAccountTypes = (baseEntryResponse.value.lines ?? []).map((line) => {
1253
- if (!line.account?.accountId) {
1254
- return void 0;
1255
- }
1256
- const account = accountMap.get(line.account.accountId);
1257
- if (!account) {
1258
- return void 0;
1259
- }
1260
- return account.type;
1261
- }).filter((type) => type !== void 0);
1262
- const enhancedEntry = convertEntryResponseToEnhancedSchemaLedgerEntry(
1263
- baseEntryResponse,
1264
- accountIdToAccount
1265
- );
1266
- const simulatingEntryErrors = [];
1267
- const simulatingEntry = generateSimulatingEntry({
1268
- entry: enhancedEntry,
1269
- accountIdToAccount,
1270
- onError: (error3) => {
1271
- if (error3 instanceof Error) {
1272
- simulatingEntryErrors.push(error3.message);
1273
- }
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);
1274
879
  }
1275
- });
1276
- if (!simulatingEntry) {
1277
- pushSceneEvent(
1278
- {
1279
- id: event.id,
1280
- parameters: { ...staticParams, ...repeatedParams },
1281
- baseEntryId,
1282
- type: "unknown",
1283
- isValid: false,
1284
- errorKind: "parameter_error",
1285
- reasons: [
1286
- "Failed to fill parameters on Entry. Reasons: ",
1287
- simulatingEntryErrors.join(", ")
1288
- ]
1289
- },
1290
- []
1291
- );
1292
- 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);
1293
885
  }
1294
- const mergedRepeatedParams = { ...staticParams, ...repeatedParams };
1295
- const preFilledEntry = {
1296
- ...simulatingEntry,
1297
- lines: simulatingEntry.lines.map(
1298
- (line) => fillParams(line, line.repeated ? mergedRepeatedParams : staticParams, {
1299
- allowMissing: true,
1300
- allowMissingInChildren: true
1301
- })
1302
- ),
1303
- conditions: simulatingEntry.conditions.map(
1304
- (condition) => fillParams(
1305
- condition,
1306
- condition.repeated ? mergedRepeatedParams : staticParams,
1307
- { allowMissing: true, allowMissingInChildren: true }
1308
- )
1309
- )
1310
- };
1311
- const postedEntry = generatePostedEntry({
1312
- accountIdToAccount,
1313
- baseEntry: enhancedEntry,
1314
- errors: baseEntryResponse.errors,
1315
- entry: preFilledEntry,
1316
- postedEntryId: event.id,
1317
- parameterValues: { ...staticParams, ...repeatedParams }
1318
- });
1319
- if (postedEntry.isValid) {
1320
- const lineAccounts = postedEntry.lines.map((line) => ({
1321
- acc: accountMap.get(line.account.id),
1322
- currency: line.currency
1323
- })).filter(
1324
- (la) => la.acc !== void 0
1325
- );
1326
- if (lineAccounts.length !== postedEntry.lines.length) {
1327
- pushSceneEvent(
1328
- {
1329
- ...postedEntry,
1330
- isValid: false,
1331
- errorKind: "entry_invalid",
1332
- reasons: ["Could not find account for some lines"]
1333
- },
1334
- []
1335
- );
1336
- return;
1337
- }
1338
- const resolveAccountType = (acc) => acc.type;
1339
- const lineAccountWithMissingType = lineAccounts.find(
1340
- ({ acc }) => resolveAccountType(acc) === void 0
1341
- );
1342
- if (lineAccountWithMissingType) {
1343
- pushSceneEvent(
1344
- {
1345
- ...postedEntry,
1346
- isValid: false,
1347
- errorKind: "entry_invalid",
1348
- reasons: [
1349
- `Could not determine account type for path ${lineAccountWithMissingType.acc.structuralPath}`
1350
- ]
1351
- },
1352
- []
1353
- );
1354
- return;
1355
- }
1356
- const conditionWithMissingType = postedEntry.conditions.map(
1357
- (condition) => condition.account.id ? accountMap.get(condition.account.id) : void 0
1358
- ).find(
1359
- (account) => account && resolveAccountType(account) === void 0
1360
- );
1361
- if (conditionWithMissingType) {
1362
- pushSceneEvent(
1363
- {
1364
- ...postedEntry,
1365
- isValid: false,
1366
- errorKind: "entry_invalid",
1367
- reasons: [
1368
- `Could not determine account type for path ${conditionWithMissingType.structuralPath}`
1369
- ]
1370
- },
1371
- []
1372
- );
1373
- return;
1374
- }
1375
- try {
1376
- validateEntryConditions({
1377
- filledEntry: postedEntry,
1378
- sceneEvents: postedEntries,
1379
- entryIndex
1380
- });
1381
- } catch (err) {
1382
- if (err instanceof Error) {
1383
- pushSceneEvent(
1384
- {
1385
- ...postedEntry,
1386
- isValid: false,
1387
- errorKind: "parameter_error",
1388
- reasons: [`Error in entry condition: ${err.message}`]
1389
- },
1390
- []
1391
- );
1392
- }
1393
- return;
1394
- }
1395
- }
1396
- pushSceneEvent(postedEntry, lineAccountTypes);
1397
- });
1398
- return postedEntries;
1399
- };
1400
-
1401
- // ../../fragment-compositions/visualizer/src/hooks/liveblocks/Scenarios/simulateScene.ts
1402
- var NO_SCENE_PAYMENTS = /* @__PURE__ */ new Map();
1403
- var simulateScene = ({
1404
- root,
1405
- sceneId
1406
- }) => {
1407
- const scene = root.schema.scenes.get(sceneId);
1408
- if (!scene)
1409
- return null;
1410
- const { chartOfAccounts } = root.schema;
1411
- const accountIdToAccount = buildAccountIdToAccountRecord(chartOfAccounts);
1412
- const { accountPathToAccount, defaultConsistencyConfig } = buildAccountPathToAccountMap(chartOfAccounts);
1413
- const resolvedEvents = resolveSceneEvents({
1414
- events: Array.from(scene.events.values()),
1415
- eventsOrder: Array.from(scene.eventsOrder.values()),
1416
- payments: scene.payments ?? NO_SCENE_PAYMENTS,
1417
- paymentTypes: root.schema.paymentTypes
1418
- });
1419
- const entriesByKey = buildSceneEntriesByKey({
1420
- resolvedEvents,
1421
- root,
1422
- accountPathToAccount,
1423
- defaultConsistencyConfig
1424
- });
1425
- const events = transformLiveblocksSceneEvents(
1426
- resolvedEvents,
1427
- entriesByKey,
1428
- accountIdToAccount
1429
- );
1430
- return {
1431
- id: scene.id,
1432
- name: scene.name ?? "",
1433
- events
1434
- };
1435
- };
1436
-
1437
- // ../../fragment-compositions/visualizer/src/utils/liveblocksUtils.ts
1438
- init_cjs_shims();
1439
- import assert3 from "assert";
1440
-
1441
- // ../../node_modules/@liveblocks/client/dist/index.js
1442
- init_cjs_shims();
1443
-
1444
- // ../../node_modules/@liveblocks/core/dist/index.js
1445
- init_cjs_shims();
1446
- var __defProp = Object.defineProperty;
1447
- var __export = (target, all) => {
1448
- for (var name in all)
1449
- __defProp(target, name, { get: all[name], enumerable: true });
1450
- };
1451
- var PKG_NAME = "@liveblocks/core";
1452
- var PKG_VERSION = "3.7.1";
1453
- var PKG_FORMAT = "esm";
1454
- var g = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
1455
- var crossLinkedDocs = "https://liveblocks.io/docs/errors/cross-linked";
1456
- var dupesDocs = "https://liveblocks.io/docs/errors/dupes";
1457
- var SPACE = " ";
1458
- function error(msg) {
1459
- if (process.env.NODE_ENV === "production") {
1460
- console.error(msg);
1461
- } else {
1462
- throw new Error(msg);
1463
886
  }
1464
887
  }
1465
- function detectDupes(pkgName, pkgVersion, pkgFormat) {
1466
- const pkgId = Symbol.for(pkgName);
1467
- const pkgBuildInfo = pkgFormat ? `${pkgVersion || "dev"} (${pkgFormat})` : pkgVersion || "dev";
1468
- if (!g[pkgId]) {
1469
- g[pkgId] = pkgBuildInfo;
1470
- } else if (g[pkgId] === pkgBuildInfo) {
1471
- } else {
1472
- const msg = [
1473
- `Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See ${dupesDocs + SPACE}`,
1474
- "",
1475
- "Conflicts:",
1476
- `- ${pkgName} ${g[pkgId]} (already loaded)`,
1477
- `- ${pkgName} ${pkgBuildInfo} (trying to load this now)`
1478
- ].join("\n");
1479
- error(msg);
1480
- }
1481
- if (pkgVersion && PKG_VERSION && pkgVersion !== PKG_VERSION) {
1482
- error(
1483
- [
1484
- `Cross-linked versions of Liveblocks found, which will cause issues! See ${crossLinkedDocs + SPACE}`,
1485
- "",
1486
- "Conflicts:",
1487
- `- ${PKG_NAME} is at ${PKG_VERSION}`,
1488
- `- ${pkgName} is at ${pkgVersion}`,
1489
- "",
1490
- "Always upgrade all Liveblocks packages to the same version number."
1491
- ].join("\n")
1492
- );
1493
- }
888
+ function takeN(pos, n) {
889
+ return n < pos.length ? pos.substring(0, n) : pos + ZERO.repeat(n - pos.length);
1494
890
  }
1495
- function makeEventSource() {
1496
- const _observers = /* @__PURE__ */ new Set();
1497
- function subscribe(callback) {
1498
- _observers.add(callback);
1499
- return () => _observers.delete(callback);
1500
- }
1501
- function subscribeOnce(callback) {
1502
- const unsub = subscribe((event) => {
1503
- unsub();
1504
- return callback(event);
1505
- });
1506
- return unsub;
891
+ var MIN_NON_ZERO_CODE = MIN_CODE + 1;
892
+ function isPos(str) {
893
+ if (str === "") {
894
+ return false;
1507
895
  }
1508
- async function waitUntil(predicate) {
1509
- let unsub;
1510
- return new Promise((res) => {
1511
- unsub = subscribe((event) => {
1512
- if (predicate === void 0 || predicate(event)) {
1513
- res(event);
1514
- }
1515
- });
1516
- }).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;
1517
900
  }
1518
- function notify(event) {
1519
- let called = false;
1520
- for (const callback of _observers) {
1521
- callback(event);
1522
- 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;
1523
905
  }
1524
- return called;
1525
906
  }
1526
- function count() {
1527
- 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);
1528
914
  }
1529
- return {
1530
- // Private/internal control over event emission
1531
- notify,
1532
- subscribe,
1533
- subscribeOnce,
1534
- count,
1535
- waitUntil,
1536
- dispose() {
1537
- _observers.clear();
1538
- },
1539
- // Publicly exposable subscription API
1540
- observable: {
1541
- subscribe,
1542
- subscribeOnce,
1543
- waitUntil
1544
- }
1545
- };
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
+ );
1546
922
  }
1547
- var freeze = process.env.NODE_ENV === "production" ? (
1548
- /* istanbul ignore next */
1549
- (x) => x
1550
- ) : Object.freeze;
1551
- function raise(msg) {
1552
- throw new Error(msg);
923
+ function asPos(str) {
924
+ return isPos(str) ? str : convertToPos(str);
1553
925
  }
1554
- function deepClone(value) {
1555
- return JSON.parse(JSON.stringify(value));
926
+ function crdtAsLiveNode(value) {
927
+ return value;
1556
928
  }
1557
- function compactObject(obj) {
1558
- const newObj = { ...obj };
1559
- Object.keys(obj).forEach((k) => {
1560
- const key = k;
1561
- if (newObj[key] === void 0) {
1562
- delete newObj[key];
1563
- }
1564
- });
1565
- return newObj;
929
+ function HasParent(node, key, pos = asPos(key)) {
930
+ return Object.freeze({ type: "HasParent", node, key, pos });
1566
931
  }
1567
- var kSinks = Symbol("kSinks");
1568
- var kTrigger = Symbol("kTrigger");
1569
- var signalsToTrigger = null;
1570
- var trackedReads = null;
1571
- function enqueueTrigger(signal) {
1572
- if (!signalsToTrigger)
1573
- raise("Expected to be in an active batch");
1574
- 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 });
1575
935
  }
1576
- var AbstractSignal = class {
1577
- /** @internal */
1578
- equals;
1579
- #eventSource;
936
+ var AbstractCrdt = class {
937
+ // ^^^^^^^^^^^^ TODO: Make this an interface
938
+ #pool;
939
+ #id;
940
+ #parent = NoParent;
1580
941
  /** @internal */
1581
- [kSinks];
1582
- constructor(equals) {
1583
- this.equals = equals ?? Object.is;
1584
- this.#eventSource = makeEventSource();
1585
- this[kSinks] = /* @__PURE__ */ new Set();
1586
- this.get = this.get.bind(this);
1587
- this.subscribe = this.subscribe.bind(this);
1588
- this.subscribeOnce = this.subscribeOnce.bind(this);
1589
- }
1590
- dispose() {
1591
- this.#eventSource.dispose();
1592
- this.#eventSource = "(disposed)";
1593
- this.equals = "(disposed)";
1594
- }
1595
- get hasWatchers() {
1596
- if (this.#eventSource.count() > 0)
1597
- return true;
1598
- for (const sink of this[kSinks]) {
1599
- if (sink.hasWatchers) {
1600
- return true;
1601
- }
1602
- }
1603
- return false;
1604
- }
1605
- [kTrigger]() {
1606
- this.#eventSource.notify();
1607
- for (const sink of this[kSinks]) {
1608
- 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");
1609
952
  }
1610
953
  }
1611
- subscribe(callback) {
1612
- if (this.#eventSource.count() === 0) {
1613
- 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");
1614
965
  }
1615
- return this.#eventSource.subscribe(callback);
1616
- }
1617
- subscribeOnce(callback) {
1618
- const unsub = this.subscribe(() => {
1619
- unsub();
1620
- return callback();
1621
- });
1622
- return unsub;
1623
- }
1624
- waitUntil() {
1625
- throw new Error("waitUntil not supported on Signals");
1626
966
  }
1627
- markSinksDirty() {
1628
- for (const sink of this[kSinks]) {
1629
- sink.markDirty();
1630
- }
967
+ /** @internal */
968
+ get _pool() {
969
+ return this.#pool;
1631
970
  }
1632
- addSink(sink) {
1633
- this[kSinks].add(sink);
971
+ get roomId() {
972
+ return this.#pool ? this.#pool.roomId : null;
1634
973
  }
1635
- removeSink(sink) {
1636
- this[kSinks].delete(sink);
974
+ /** @internal */
975
+ get _id() {
976
+ return this.#id;
1637
977
  }
1638
- asReadonly() {
1639
- return this;
978
+ /** @internal */
979
+ get parent() {
980
+ return this.#parent;
1640
981
  }
1641
- };
1642
- var INITIAL = Symbol();
1643
- var DerivedSignal = class _DerivedSignal extends AbstractSignal {
1644
- #prevValue;
1645
- #dirty;
1646
- // When true, the value in #value may not be up-to-date and needs re-checking
1647
- #sources;
1648
- #deps;
1649
- #transform;
1650
- // prettier-ignore
1651
- static from(...args) {
1652
- const last = args.pop();
1653
- if (typeof last !== "function")
1654
- raise("Invalid .from() call, last argument expected to be a function");
1655
- if (typeof args[args.length - 1] === "function") {
1656
- const equals = last;
1657
- const transform = args.pop();
1658
- return new _DerivedSignal(args, transform, equals);
1659
- } else {
1660
- const transform = last;
1661
- 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");
1662
993
  }
1663
994
  }
1664
- constructor(deps, transform, equals) {
1665
- super(equals);
1666
- this.#dirty = true;
1667
- this.#prevValue = INITIAL;
1668
- this.#deps = deps;
1669
- this.#sources = /* @__PURE__ */ new Set();
1670
- this.#transform = transform;
1671
- }
1672
- dispose() {
1673
- for (const src of this.#sources) {
1674
- 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
+ }
1675
1004
  }
1676
- this.#prevValue = "(disposed)";
1677
- this.#sources = "(disposed)";
1678
- this.#deps = "(disposed)";
1679
- this.#transform = "(disposed)";
1680
- }
1681
- get isDirty() {
1682
- return this.#dirty;
1005
+ return { modified: false };
1683
1006
  }
1684
- #recompute() {
1685
- const oldTrackedReads = trackedReads;
1686
- let derived;
1687
- trackedReads = /* @__PURE__ */ new Set();
1688
- try {
1689
- derived = this.#transform(...this.#deps.map((p) => p.get()));
1690
- } finally {
1691
- const oldSources = this.#sources;
1692
- this.#sources = /* @__PURE__ */ new Set();
1693
- for (const sig of trackedReads) {
1694
- this.#sources.add(sig);
1695
- oldSources.delete(sig);
1696
- }
1697
- for (const oldSource of oldSources) {
1698
- oldSource.removeSink(this);
1699
- }
1700
- for (const newSource of this.#sources) {
1701
- 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;
1702
1021
  }
1703
- trackedReads = oldTrackedReads;
1704
- }
1705
- this.#dirty = false;
1706
- if (!this.equals(this.#prevValue, derived)) {
1707
- this.#prevValue = derived;
1708
- return true;
1022
+ default:
1023
+ return assertNever(this.parent, "Unknown state");
1709
1024
  }
1710
- return false;
1711
1025
  }
1712
- markDirty() {
1713
- if (!this.#dirty) {
1714
- this.#dirty = true;
1715
- this.markSinksDirty();
1026
+ /** @internal */
1027
+ _attach(id, pool) {
1028
+ if (this.#id || this.#pool) {
1029
+ throw new Error("Cannot attach node: already attached");
1716
1030
  }
1031
+ pool.addNode(id, crdtAsLiveNode(this));
1032
+ this.#id = id;
1033
+ this.#pool = pool;
1717
1034
  }
1718
- get() {
1719
- if (this.#dirty) {
1720
- this.#recompute();
1035
+ /** @internal */
1036
+ _detach() {
1037
+ if (this.#pool && this.#id) {
1038
+ this.#pool.deleteNode(this.#id);
1721
1039
  }
1722
- trackedReads?.add(this);
1723
- return this.#prevValue;
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;
1724
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;
1725
1062
  /**
1726
- * Called by the Signal system if one or more of the dependent signals have
1727
- * changed. In the case of a DerivedSignal, we'll only want to re-evaluate
1728
- * the actual value if it's being watched, or any of their sinks are being
1729
- * 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.
1730
1068
  */
1731
- [kTrigger]() {
1732
- if (!this.hasWatchers) {
1733
- return;
1734
- }
1735
- const updated = this.#recompute();
1736
- if (updated) {
1737
- 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
+ }
1738
1076
  }
1739
1077
  }
1740
- };
1741
- function assertNever(_value, errmsg) {
1742
- throw new Error(errmsg);
1743
- }
1744
- function assert2(condition, errmsg) {
1745
- if (process.env.NODE_ENV !== "production") {
1746
- if (!condition) {
1747
- const err = new Error(errmsg);
1748
- err.name = "Assertion failure";
1749
- 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);
1750
1087
  }
1088
+ return this.#cachedTreeNode;
1751
1089
  }
1752
- }
1753
- function nn(value, errmsg = "Expected value to be non-nullable") {
1754
- assert2(value !== null && value !== void 0, errmsg);
1755
- return value;
1756
- }
1757
- var fancy_console_exports = {};
1758
- __export(fancy_console_exports, {
1759
- error: () => error2,
1760
- errorWithTitle: () => errorWithTitle,
1761
- warn: () => warn,
1762
- warnWithTitle: () => warnWithTitle
1763
- });
1764
- var badge = "background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;";
1765
- var bold = "font-weight:600";
1766
- function wrap(method) {
1767
- return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
1768
- /* istanbul ignore next */
1769
- (message, ...args) => console[method]("%cLiveblocks", badge, message, ...args)
1770
- );
1771
- }
1772
- var warn = wrap("warn");
1773
- var error2 = wrap("error");
1774
- function wrapWithTitle(method) {
1775
- return typeof window === "undefined" || process.env.NODE_ENV === "test" ? console[method] : (
1776
- /* istanbul ignore next */
1777
- (title, message, ...args) => console[method](
1778
- `%cLiveblocks%c ${title}`,
1779
- badge,
1780
- bold,
1781
- message,
1782
- ...args
1783
- )
1784
- );
1785
- }
1786
- var warnWithTitle = wrapWithTitle("warn");
1787
- var errorWithTitle = wrapWithTitle("error");
1788
- var nanoid = (t = 21) => crypto.getRandomValues(new Uint8Array(t)).reduce(
1789
- (t2, e) => t2 += (e &= 63) < 36 ? e.toString(36) : e < 62 ? (e - 26).toString(36).toUpperCase() : e < 63 ? "_" : "-",
1790
- ""
1791
- );
1792
- var BACKOFF_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4];
1793
- var RESET_DELAY = BACKOFF_DELAYS[0] - 1;
1794
- function log(level, message) {
1795
- const logger = level === 2 ? error2 : level === 1 ? warn : (
1796
- /* black hole */
1797
- () => {
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();
1798
1096
  }
1799
- );
1800
- return () => {
1801
- logger(message);
1802
- };
1097
+ return this.#cachedImmutable;
1098
+ }
1099
+ };
1100
+ function isRootCrdt(crdt) {
1101
+ return crdt.type === 0 && !isChildCrdt(crdt);
1803
1102
  }
1804
- var logPermanentClose = log(
1805
- 1,
1806
- "Connection to WebSocket closed permanently. Won't retry."
1807
- );
1808
- var kInternal = Symbol();
1809
- var EMPTY_OBJECT = Object.freeze({});
1810
- var NULL_KEYWORD_CHARS = Array.from(new Set("null"));
1811
- var TRUE_KEYWORD_CHARS = Array.from(new Set("true"));
1812
- var FALSE_KEYWORD_CHARS = Array.from(new Set("false"));
1813
- var ALL_KEYWORD_CHARS = Array.from(new Set("nulltruefalse"));
1814
- var kWILDCARD = Symbol("*");
1815
- var eventSource = makeEventSource();
1816
- if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
1817
- window.addEventListener("message", (event) => {
1818
- if (event.source === window && event.data?.source === "liveblocks-devtools-panel") {
1819
- eventSource.notify(event.data);
1820
- } else {
1821
- }
1822
- });
1103
+ function isChildCrdt(crdt) {
1104
+ return crdt.parentId !== void 0 && crdt.parentKey !== void 0;
1823
1105
  }
1824
- var onMessageFromPanel = eventSource.observable;
1825
- var loadedAt = Date.now();
1826
- var kPlain = Symbol("notification-settings-plain");
1827
- var MIN_CODE = 32;
1828
- var MAX_CODE = 126;
1829
- var NUM_DIGITS = MAX_CODE - MIN_CODE + 1;
1830
- var ZERO = nthDigit(0);
1831
- var ONE = nthDigit(1);
1832
- var ZERO_NINE = ZERO + nthDigit(-1);
1833
- function nthDigit(n) {
1834
- const code = MIN_CODE + (n < 0 ? NUM_DIGITS + n : n);
1835
- if (code < MIN_CODE || code > MAX_CODE) {
1836
- 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;
1837
1111
  }
1838
- return String.fromCharCode(code);
1839
- }
1840
- function makePosition(x, y) {
1841
- if (x !== void 0 && y !== void 0) {
1842
- return between(x, y);
1843
- } else if (x !== void 0) {
1844
- return after(x);
1845
- } else if (y !== void 0) {
1846
- return before(y);
1847
- } else {
1848
- return ONE;
1112
+ get data() {
1113
+ return this.#data;
1849
1114
  }
1850
- }
1851
- function before(pos) {
1852
- const lastIndex = pos.length - 1;
1853
- for (let i = 0; i <= lastIndex; i++) {
1854
- const code = pos.charCodeAt(i);
1855
- if (code <= MIN_CODE) {
1856
- 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
+ );
1857
1127
  }
1858
- if (i === lastIndex) {
1859
- if (code === MIN_CODE + 1) {
1860
- return pos.substring(0, i) + ZERO_NINE;
1861
- } else {
1862
- 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
1863
1136
  }
1864
- } else {
1865
- return pos.substring(0, i + 1);
1866
- }
1137
+ ];
1867
1138
  }
1868
- return ONE;
1869
- }
1870
- function after(pos) {
1871
- for (let i = 0; i <= pos.length - 1; i++) {
1872
- const code = pos.charCodeAt(i);
1873
- if (code >= MAX_CODE) {
1874
- continue;
1139
+ /** @internal */
1140
+ _serialize() {
1141
+ if (this.parent.type !== "HasParent") {
1142
+ throw new Error("Cannot serialize LiveRegister if parent is missing");
1875
1143
  }
1876
- 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
+ };
1877
1150
  }
1878
- return pos + ONE;
1879
- }
1880
- function between(lo, hi) {
1881
- if (lo < hi) {
1882
- return _between(lo, hi);
1883
- } else if (lo > hi) {
1884
- return _between(hi, lo);
1885
- } else {
1886
- throw new Error("Cannot compute value between two equal positions");
1151
+ /** @internal */
1152
+ _attachChild(_op) {
1153
+ throw new Error("Method not implemented.");
1887
1154
  }
1888
- }
1889
- function _between(lo, hi) {
1890
- let index = 0;
1891
- const loLen = lo.length;
1892
- const hiLen = hi.length;
1893
- while (true) {
1894
- const loCode = index < loLen ? lo.charCodeAt(index) : MIN_CODE;
1895
- const hiCode = index < hiLen ? hi.charCodeAt(index) : MAX_CODE;
1896
- if (loCode === hiCode) {
1897
- index++;
1898
- continue;
1899
- }
1900
- if (hiCode - loCode === 1) {
1901
- const size = index + 1;
1902
- let prefix = lo.substring(0, size);
1903
- if (prefix.length < size) {
1904
- prefix += ZERO.repeat(size - prefix.length);
1905
- }
1906
- const suffix = lo.substring(size);
1907
- const nines = "";
1908
- return prefix + _between(suffix, nines);
1909
- } else {
1910
- return takeN(lo, index) + String.fromCharCode(hiCode + loCode >> 1);
1911
- }
1912
- }
1913
- }
1914
- function takeN(pos, n) {
1915
- return n < pos.length ? pos.substring(0, n) : pos + ZERO.repeat(n - pos.length);
1916
- }
1917
- var MIN_NON_ZERO_CODE = MIN_CODE + 1;
1918
- function isPos(str) {
1919
- if (str === "") {
1920
- return false;
1921
- }
1922
- const lastIdx = str.length - 1;
1923
- const last = str.charCodeAt(lastIdx);
1924
- if (last < MIN_NON_ZERO_CODE || last > MAX_CODE) {
1925
- return false;
1926
- }
1927
- for (let i = 0; i < lastIdx; i++) {
1928
- const code = str.charCodeAt(i);
1929
- if (code < MIN_CODE || code > MAX_CODE) {
1930
- return false;
1931
- }
1932
- }
1933
- return true;
1934
- }
1935
- function convertToPos(str) {
1936
- const codes2 = [];
1937
- for (let i = 0; i < str.length; i++) {
1938
- const code = str.charCodeAt(i);
1939
- codes2.push(code < MIN_CODE ? MIN_CODE : code > MAX_CODE ? MAX_CODE : code);
1940
- }
1941
- while (codes2.length > 0 && codes2[codes2.length - 1] === MIN_CODE) {
1942
- codes2.length--;
1943
- }
1944
- return codes2.length > 0 ? String.fromCharCode(...codes2) : (
1945
- // Edge case: the str was a 0-only string, which is invalid. Default back to .1
1946
- ONE
1947
- );
1948
- }
1949
- function asPos(str) {
1950
- return isPos(str) ? str : convertToPos(str);
1951
- }
1952
- function crdtAsLiveNode(value) {
1953
- return value;
1954
- }
1955
- function HasParent(node, key, pos = asPos(key)) {
1956
- return Object.freeze({ type: "HasParent", node, key, pos });
1957
- }
1958
- var NoParent = Object.freeze({ type: "NoParent" });
1959
- function Orphaned(oldKey, oldPos = asPos(oldKey)) {
1960
- return Object.freeze({ type: "Orphaned", oldKey, oldPos });
1961
- }
1962
- var AbstractCrdt = class {
1963
- // ^^^^^^^^^^^^ TODO: Make this an interface
1964
- #pool;
1965
- #id;
1966
- #parent = NoParent;
1967
1155
  /** @internal */
1968
- _getParentKeyOrThrow() {
1969
- switch (this.parent.type) {
1970
- case "HasParent":
1971
- return this.parent.key;
1972
- case "NoParent":
1973
- throw new Error("Parent key is missing");
1974
- case "Orphaned":
1975
- return this.parent.oldKey;
1976
- default:
1977
- return assertNever(this.parent, "Unknown state");
1978
- }
1156
+ _detachChild(_crdt) {
1157
+ throw new Error("Method not implemented.");
1979
1158
  }
1980
1159
  /** @internal */
1981
- get _parentPos() {
1982
- switch (this.parent.type) {
1983
- case "HasParent":
1984
- return this.parent.pos;
1985
- case "NoParent":
1986
- throw new Error("Parent key is missing");
1987
- case "Orphaned":
1988
- return this.parent.oldPos;
1989
- default:
1990
- return assertNever(this.parent, "Unknown state");
1991
- }
1160
+ _apply(op, isLocal) {
1161
+ return super._apply(op, isLocal);
1992
1162
  }
1993
1163
  /** @internal */
1994
- get _pool() {
1995
- return this.#pool;
1996
- }
1997
- get roomId() {
1998
- 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
+ };
1999
1171
  }
2000
1172
  /** @internal */
2001
- get _id() {
2002
- return this.#id;
1173
+ _toImmutable() {
1174
+ return this.#data;
2003
1175
  }
2004
- /** @internal */
2005
- get parent() {
2006
- return this.#parent;
1176
+ clone() {
1177
+ return deepClone(this.data);
2007
1178
  }
2008
- /** @internal */
2009
- get _parentKey() {
2010
- switch (this.parent.type) {
2011
- case "HasParent":
2012
- return this.parent.key;
2013
- case "NoParent":
2014
- return null;
2015
- case "Orphaned":
2016
- return this.parent.oldKey;
2017
- default:
2018
- 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;
2019
1202
  }
2020
1203
  }
2021
1204
  /** @internal */
2022
- _apply(op, _isLocal) {
2023
- switch (op.type) {
2024
- case 5: {
2025
- if (this.parent.type === "HasParent") {
2026
- return this.parent.node._detachChild(crdtAsLiveNode(this));
2027
- }
2028
- return { modified: false };
2029
- }
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;
2030
1211
  }
2031
- 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;
2032
1218
  }
2033
- /** @internal */
2034
- _setParentLink(newParentNode, newParentKey) {
2035
- switch (this.parent.type) {
2036
- case "HasParent":
2037
- if (this.parent.node !== newParentNode) {
2038
- throw new Error("Cannot set parent: node already has a parent");
2039
- } else {
2040
- this.#parent = HasParent(newParentNode, newParentKey);
2041
- return;
2042
- }
2043
- case "Orphaned":
2044
- case "NoParent": {
2045
- this.#parent = HasParent(newParentNode, newParentKey);
2046
- 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);
2047
1250
  }
2048
- default:
2049
- return assertNever(this.parent, "Unknown state");
1251
+ ops.push(...childOps);
2050
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
+ );
2051
1274
  }
2052
1275
  /** @internal */
2053
1276
  _attach(id, pool) {
2054
- if (this.#id || this.#pool) {
2055
- 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);
2056
1280
  }
2057
- pool.addNode(id, crdtAsLiveNode(this));
2058
- this.#id = id;
2059
- this.#pool = pool;
2060
1281
  }
2061
1282
  /** @internal */
2062
1283
  _detach() {
2063
- if (this.#pool && this.#id) {
2064
- this.#pool.deleteNode(this.#id);
2065
- }
2066
- switch (this.parent.type) {
2067
- case "HasParent": {
2068
- this.#parent = Orphaned(this.parent.key, this.parent.pos);
2069
- break;
2070
- }
2071
- case "NoParent": {
2072
- this.#parent = NoParent;
2073
- break;
2074
- }
2075
- case "Orphaned": {
2076
- break;
2077
- }
2078
- default:
2079
- assertNever(this.parent, "Unknown state");
2080
- }
2081
- this.#pool = void 0;
2082
- }
2083
- /** This caches the result of the last .toImmutable() call for this Live node. */
2084
- #cachedImmutable;
2085
- #cachedTreeNodeKey;
2086
- /** This caches the result of the last .toTreeNode() call for this Live node. */
2087
- #cachedTreeNode;
2088
- /**
2089
- * @internal
2090
- *
2091
- * Clear the Immutable cache, so that the next call to `.toImmutable()` will
2092
- * recompute the equivalent Immutable value again. Call this after every
2093
- * mutation to the Live node.
2094
- */
2095
- invalidate() {
2096
- if (this.#cachedImmutable !== void 0 || this.#cachedTreeNode !== void 0) {
2097
- this.#cachedImmutable = void 0;
2098
- this.#cachedTreeNode = void 0;
2099
- if (this.parent.type === "HasParent") {
2100
- this.parent.node.invalidate();
2101
- }
2102
- }
2103
- }
2104
- /**
2105
- * @internal
2106
- *
2107
- * Return an snapshot of this Live tree for use in DevTools.
2108
- */
2109
- toTreeNode(key) {
2110
- if (this.#cachedTreeNode === void 0 || this.#cachedTreeNodeKey !== key) {
2111
- this.#cachedTreeNodeKey = key;
2112
- this.#cachedTreeNode = this._toTreeNode(key);
2113
- }
2114
- return this.#cachedTreeNode;
2115
- }
2116
- /**
2117
- * Return an immutable snapshot of this Live node and its children.
2118
- */
2119
- toImmutable() {
2120
- if (this.#cachedImmutable === void 0) {
2121
- this.#cachedImmutable = this._toImmutable();
2122
- }
2123
- return this.#cachedImmutable;
2124
- }
2125
- };
2126
- function isRootCrdt(crdt) {
2127
- return crdt.type === 0 && !isChildCrdt(crdt);
2128
- }
2129
- function isChildCrdt(crdt) {
2130
- return crdt.parentId !== void 0 && crdt.parentKey !== void 0;
2131
- }
2132
- var LiveRegister = class _LiveRegister extends AbstractCrdt {
2133
- #data;
2134
- constructor(data) {
2135
- super();
2136
- this.#data = data;
2137
- }
2138
- get data() {
2139
- return this.#data;
2140
- }
2141
- /** @internal */
2142
- static _deserialize([id, item], _parentToChildren, pool) {
2143
- const register = new _LiveRegister(item.data);
2144
- register._attach(id, pool);
2145
- return register;
2146
- }
2147
- /** @internal */
2148
- _toOps(parentId, parentKey, pool) {
2149
- if (this._id === void 0) {
2150
- throw new Error(
2151
- "Cannot serialize register if parentId or parentKey is undefined"
2152
- );
2153
- }
2154
- return [
2155
- {
2156
- type: 8,
2157
- opId: pool?.generateOpId(),
2158
- id: this._id,
2159
- parentId,
2160
- parentKey,
2161
- data: this.data
2162
- }
2163
- ];
2164
- }
2165
- /** @internal */
2166
- _serialize() {
2167
- if (this.parent.type !== "HasParent") {
2168
- throw new Error("Cannot serialize LiveRegister if parent is missing");
2169
- }
2170
- return {
2171
- type: 3,
2172
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
2173
- parentKey: this.parent.key,
2174
- data: this.data
2175
- };
2176
- }
2177
- /** @internal */
2178
- _attachChild(_op) {
2179
- throw new Error("Method not implemented.");
2180
- }
2181
- /** @internal */
2182
- _detachChild(_crdt) {
2183
- throw new Error("Method not implemented.");
2184
- }
2185
- /** @internal */
2186
- _apply(op, isLocal) {
2187
- return super._apply(op, isLocal);
2188
- }
2189
- /** @internal */
2190
- _toTreeNode(key) {
2191
- return {
2192
- type: "Json",
2193
- id: this._id ?? nanoid(),
2194
- key,
2195
- payload: this.#data
2196
- };
2197
- }
2198
- /** @internal */
2199
- _toImmutable() {
2200
- return this.#data;
2201
- }
2202
- clone() {
2203
- return deepClone(this.data);
2204
- }
2205
- };
2206
- function compareNodePosition(itemA, itemB) {
2207
- const posA = itemA._parentPos;
2208
- const posB = itemB._parentPos;
2209
- return posA === posB ? 0 : posA < posB ? -1 : 1;
2210
- }
2211
- var LiveList = class _LiveList extends AbstractCrdt {
2212
- // TODO: Naive array at first, find a better data structure. Maybe an Order statistics tree?
2213
- #items;
2214
- #implicitlyDeletedItems;
2215
- #unacknowledgedSets;
2216
- constructor(items) {
2217
- super();
2218
- this.#items = [];
2219
- this.#implicitlyDeletedItems = /* @__PURE__ */ new WeakSet();
2220
- this.#unacknowledgedSets = /* @__PURE__ */ new Map();
2221
- let position = void 0;
2222
- for (const item of items) {
2223
- const newPosition = makePosition(position);
2224
- const node = lsonToLiveNode(item);
2225
- node._setParentLink(this, newPosition);
2226
- this.#items.push(node);
2227
- position = newPosition;
2228
- }
2229
- }
2230
- /** @internal */
2231
- static _deserialize([id], parentToChildren, pool) {
2232
- const list = new _LiveList([]);
2233
- list._attach(id, pool);
2234
- const children = parentToChildren.get(id);
2235
- if (children === void 0) {
2236
- return list;
2237
- }
2238
- for (const [id2, crdt] of children) {
2239
- const child = deserialize([id2, crdt], parentToChildren, pool);
2240
- child._setParentLink(list, crdt.parentKey);
2241
- list._insertAndSort(child);
2242
- }
2243
- return list;
2244
- }
2245
- /**
2246
- * @internal
2247
- * This function assumes that the resulting ops will be sent to the server if they have an 'opId'
2248
- * so we mutate _unacknowledgedSets to avoid potential flickering
2249
- * https://github.com/liveblocks/liveblocks/pull/1177
2250
- *
2251
- * This is quite unintuitive and should disappear as soon as
2252
- * we introduce an explicit LiveList.Set operation
2253
- */
2254
- _toOps(parentId, parentKey, pool) {
2255
- if (this._id === void 0) {
2256
- throw new Error("Cannot serialize item is not attached");
2257
- }
2258
- const ops = [];
2259
- const op = {
2260
- id: this._id,
2261
- opId: pool?.generateOpId(),
2262
- type: 2,
2263
- parentId,
2264
- parentKey
2265
- };
2266
- ops.push(op);
2267
- for (const item of this.#items) {
2268
- const parentKey2 = item._getParentKeyOrThrow();
2269
- const childOps = HACK_addIntentAndDeletedIdToOperation(
2270
- item._toOps(this._id, parentKey2, pool),
2271
- void 0
2272
- );
2273
- const childOpId = childOps[0].opId;
2274
- if (childOpId !== void 0) {
2275
- this.#unacknowledgedSets.set(parentKey2, childOpId);
2276
- }
2277
- ops.push(...childOps);
2278
- }
2279
- return ops;
2280
- }
2281
- /**
2282
- * @internal
2283
- *
2284
- * Adds a new item into the sorted list, in the correct position.
2285
- */
2286
- _insertAndSort(item) {
2287
- this.#items.push(item);
2288
- this._sortItems();
2289
- }
2290
- /** @internal */
2291
- _sortItems() {
2292
- this.#items.sort(compareNodePosition);
2293
- this.invalidate();
2294
- }
2295
- /** @internal */
2296
- _indexOfPosition(position) {
2297
- return this.#items.findIndex(
2298
- (item) => item._getParentKeyOrThrow() === position
2299
- );
2300
- }
2301
- /** @internal */
2302
- _attach(id, pool) {
2303
- super._attach(id, pool);
2304
- for (const item of this.#items) {
2305
- item._attach(pool.generateId(), pool);
2306
- }
2307
- }
2308
- /** @internal */
2309
- _detach() {
2310
- super._detach();
2311
- for (const item of this.#items) {
2312
- item._detach();
1284
+ super._detach();
1285
+ for (const item of this.#items) {
1286
+ item._detach();
2313
1287
  }
2314
1288
  }
2315
1289
  #applySetRemote(op) {
@@ -3815,415 +2789,1461 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3815
2789
  if (isLiveNode(oldValue)) {
3816
2790
  oldValue._detach();
3817
2791
  }
3818
- isModified = true;
3819
- updateDelta[key] = { type: "update" };
3820
- this.#map.set(key, value);
3821
- this.invalidate();
3822
- }
3823
- if (Object.keys(reverseUpdate.data).length !== 0) {
3824
- reverse.unshift(reverseUpdate);
3825
- }
3826
- return isModified ? {
3827
- modified: {
3828
- node: this,
3829
- type: "LiveObject",
3830
- updates: updateDelta
3831
- },
3832
- reverse
3833
- } : { modified: false };
3834
- }
3835
- #applyDeleteObjectKey(op, isLocal) {
3836
- const key = op.key;
3837
- if (this.#map.has(key) === false) {
3838
- return { modified: false };
3839
- }
3840
- if (!isLocal && this.#propToLastUpdate.get(key) !== void 0) {
3841
- 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
+ }
3842
3840
  }
3843
- const oldValue = this.#map.get(key);
3844
- const id = nn(this._id);
3845
- let reverse = [];
3846
- if (isLiveNode(oldValue)) {
3847
- reverse = oldValue._toOps(id, op.key);
3848
- oldValue._detach();
3849
- } else if (oldValue !== void 0) {
3850
- reverse = [
3851
- {
3852
- type: 3,
3853
- id,
3854
- 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
+ );
3855
3878
  }
3856
- ];
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] };
3857
3905
  }
3858
- this.#map.delete(key);
3859
- 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) {
3860
3926
  return {
3861
- modified: {
3862
- node: this,
3863
- type: "LiveObject",
3864
- updates: { [op.key]: { type: "delete" } }
3865
- },
3866
- 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
3867
3935
  };
3868
3936
  }
3869
- /**
3870
- * Transform the LiveObject into a javascript object
3871
- */
3872
- toObject() {
3873
- return Object.fromEntries(this.#map);
3874
- }
3875
- /**
3876
- * Adds or updates a property with a specified key and a value.
3877
- * @param key The key of the property to add
3878
- * @param value The value of the property to add
3879
- */
3880
- set(key, value) {
3881
- this._pool?.assertStorageIsWritable();
3882
- this.update({ [key]: value });
3883
- }
3884
- /**
3885
- * Returns a specified property from the LiveObject.
3886
- * @param key The key of the property to get
3887
- */
3888
- get(key) {
3889
- return this.#map.get(key);
3890
- }
3891
- /**
3892
- * Deletes a key from the LiveObject
3893
- * @param key The key of the property to delete
3894
- */
3895
- delete(key) {
3896
- this._pool?.assertStorageIsWritable();
3897
- const keyAsString = key;
3898
- const oldValue = this.#map.get(keyAsString);
3899
- 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);
3900
4051
  return;
3901
4052
  }
3902
- if (this._pool === void 0 || this._id === void 0) {
3903
- if (isLiveNode(oldValue)) {
3904
- oldValue._detach();
3905
- }
3906
- this.#map.delete(keyAsString);
3907
- this.invalidate();
4053
+ if (!baseEntryResponse) {
4054
+ pushInvalidSceneEvent("entry_invalid", [
4055
+ entryId?.flavor === "payment" ? PAYMENT_GONE_FROM_SCHEMA_REASON : "Entry not found"
4056
+ ]);
3908
4057
  return;
3909
4058
  }
3910
- let reverse;
3911
- if (isLiveNode(oldValue)) {
3912
- oldValue._detach();
3913
- reverse = oldValue._toOps(this._id, keyAsString);
3914
- } else {
3915
- reverse = [
3916
- {
3917
- type: 3,
3918
- data: { [keyAsString]: oldValue },
3919
- id: this._id
3920
- }
3921
- ];
3922
- }
3923
- this.#map.delete(keyAsString);
3924
- this.invalidate();
3925
- const storageUpdates = /* @__PURE__ */ new Map();
3926
- storageUpdates.set(this._id, {
3927
- node: this,
3928
- type: "LiveObject",
3929
- updates: { [key]: { type: "delete" } }
3930
- });
3931
- this._pool.dispatch(
3932
- [
3933
- {
3934
- type: 6,
3935
- key: keyAsString,
3936
- id: this._id,
3937
- opId: this._pool.generateOpId()
3938
- }
3939
- ],
3940
- reverse,
3941
- storageUpdates
3942
- );
3943
- }
3944
- /**
3945
- * Adds or updates multiple properties at once with an object.
3946
- * @param patch The object used to overrides properties
3947
- */
3948
- update(patch) {
3949
- this._pool?.assertStorageIsWritable();
3950
- if (_LiveObject.detectLargeObjects) {
3951
- const data = {};
3952
- for (const [key, value] of this.#map) {
3953
- if (!isLiveNode(value)) {
3954
- data[key] = value;
3955
- }
3956
- }
3957
- for (const key of Object.keys(patch)) {
3958
- const value = patch[key];
3959
- if (value === void 0)
3960
- continue;
3961
- if (!isLiveNode(value)) {
3962
- data[key] = value;
3963
- }
4059
+ const lineAccountTypes = (baseEntryResponse.value.lines ?? []).map((line) => {
4060
+ if (!line.account?.accountId) {
4061
+ return void 0;
3964
4062
  }
3965
- const jsonString = JSON.stringify(data);
3966
- const upperBoundSize = jsonString.length * 4;
3967
- if (upperBoundSize > MAX_LIVE_OBJECT_SIZE) {
3968
- const preciseSize = new TextEncoder().encode(jsonString).length;
3969
- if (preciseSize > MAX_LIVE_OBJECT_SIZE) {
3970
- throw new Error(
3971
- `LiveObject size exceeded limit: ${preciseSize} bytes > ${MAX_LIVE_OBJECT_SIZE} bytes. See https://liveblocks.io/docs/platform/limits#Liveblocks-Storage-limits`
3972
- );
3973
- }
4063
+ const account = accountMap.get(line.account.accountId);
4064
+ if (!account) {
4065
+ return void 0;
3974
4066
  }
3975
- }
3976
- if (this._pool === void 0 || this._id === void 0) {
3977
- for (const key in patch) {
3978
- const newValue = patch[key];
3979
- if (newValue === void 0) {
3980
- continue;
3981
- }
3982
- const oldValue = this.#map.get(key);
3983
- if (isLiveNode(oldValue)) {
3984
- oldValue._detach();
3985
- }
3986
- if (isLiveNode(newValue)) {
3987
- 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);
3988
4080
  }
3989
- this.#map.set(key, newValue);
3990
- this.invalidate();
3991
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
+ );
3992
4099
  return;
3993
4100
  }
3994
- const ops = [];
3995
- const reverseOps = [];
3996
- const opId = this._pool.generateOpId();
3997
- const updatedProps = {};
3998
- const reverseUpdateOp = {
3999
- id: this._id,
4000
- type: 3,
4001
- 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
+ )
4002
4117
  };
4003
- const updateDelta = {};
4004
- for (const key in patch) {
4005
- const newValue = patch[key];
4006
- if (newValue === void 0) {
4007
- 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;
4008
4144
  }
4009
- const oldValue = this.#map.get(key);
4010
- if (isLiveNode(oldValue)) {
4011
- reverseOps.push(...oldValue._toOps(this._id, key));
4012
- oldValue._detach();
4013
- } else if (oldValue === void 0) {
4014
- reverseOps.push({ type: 6, id: this._id, key });
4015
- } else {
4016
- 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;
4017
4162
  }
4018
- if (isLiveNode(newValue)) {
4019
- newValue._setParentLink(this, key);
4020
- newValue._attach(this._pool.generateId(), this._pool);
4021
- const newAttachChildOps = newValue._toOps(this._id, key, this._pool);
4022
- const createCrdtOp = newAttachChildOps.find(
4023
- (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
+ []
4024
4179
  );
4025
- if (createCrdtOp) {
4026
- 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
+ );
4027
4199
  }
4028
- ops.push(...newAttachChildOps);
4029
- } else {
4030
- updatedProps[key] = newValue;
4031
- this.#propToLastUpdate.set(key, opId);
4200
+ return;
4032
4201
  }
4033
- this.#map.set(key, newValue);
4034
- this.invalidate();
4035
- updateDelta[key] = { type: "update" };
4036
- }
4037
- if (Object.keys(reverseUpdateOp.data).length !== 0) {
4038
- reverseOps.unshift(reverseUpdateOp);
4039
- }
4040
- if (Object.keys(updatedProps).length !== 0) {
4041
- ops.unshift({
4042
- opId,
4043
- id: this._id,
4044
- type: 3,
4045
- data: updatedProps
4046
- });
4047
- }
4048
- const storageUpdates = /* @__PURE__ */ new Map();
4049
- storageUpdates.set(this._id, {
4050
- node: this,
4051
- type: "LiveObject",
4052
- updates: updateDelta
4053
- });
4054
- this._pool.dispatch(ops, reverseOps, storageUpdates);
4055
- }
4056
- toImmutable() {
4057
- return super.toImmutable();
4058
- }
4059
- /** @internal */
4060
- toTreeNode(key) {
4061
- return super.toTreeNode(key);
4062
- }
4063
- /** @internal */
4064
- _toTreeNode(key) {
4065
- const nodeId = this._id ?? nanoid();
4066
- return {
4067
- type: "LiveObject",
4068
- id: nodeId,
4069
- key,
4070
- payload: Array.from(this.#map.entries()).map(
4071
- ([key2, value]) => isLiveNode(value) ? value.toTreeNode(key2) : { type: "Json", id: `${nodeId}:${key2}`, key: key2, payload: value }
4072
- )
4073
- };
4074
- }
4075
- /** @internal */
4076
- _toImmutable() {
4077
- const result = {};
4078
- for (const [key, val] of this.#map) {
4079
- result[key] = isLiveStructure(val) ? val.toImmutable() : val;
4080
- }
4081
- return process.env.NODE_ENV === "production" ? result : Object.freeze(result);
4082
- }
4083
- clone() {
4084
- return new _LiveObject(
4085
- Object.fromEntries(
4086
- Array.from(this.#map).map(([key, value]) => [
4087
- key,
4088
- isLiveStructure(value) ? value.clone() : deepClone(value)
4089
- ])
4090
- )
4091
- );
4092
- }
4093
- };
4094
- function creationOpToLiveNode(op) {
4095
- return lsonToLiveNode(creationOpToLson(op));
4096
- }
4097
- function creationOpToLson(op) {
4098
- switch (op.type) {
4099
- case 8:
4100
- return op.data;
4101
- case 4:
4102
- return new LiveObject(op.data);
4103
- case 7:
4104
- return new LiveMap();
4105
- case 2:
4106
- return new LiveList([]);
4107
- default:
4108
- return assertNever(op, "Unknown creation Op");
4109
- }
4110
- }
4111
- function deserialize([id, crdt], parentToChildren, pool) {
4112
- switch (crdt.type) {
4113
- case 0: {
4114
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4115
- }
4116
- case 1: {
4117
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4118
- }
4119
- case 2: {
4120
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4121
- }
4122
- case 3: {
4123
- return LiveRegister._deserialize([id, crdt], parentToChildren, pool);
4124
- }
4125
- default: {
4126
- throw new Error("Unexpected CRDT type");
4127
- }
4128
- }
4129
- }
4130
- function deserializeToLson([id, crdt], parentToChildren, pool) {
4131
- switch (crdt.type) {
4132
- case 0: {
4133
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4134
4202
  }
4135
- case 1: {
4136
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4137
- }
4138
- case 2: {
4139
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4140
- }
4141
- case 3: {
4142
- return crdt.data;
4143
- }
4144
- default: {
4145
- throw new Error("Unexpected CRDT type");
4146
- }
4147
- }
4148
- }
4149
- function isLiveStructure(value) {
4150
- return isLiveList(value) || isLiveMap(value) || isLiveObject(value);
4151
- }
4152
- function isLiveNode(value) {
4153
- return isLiveStructure(value) || isLiveRegister(value);
4154
- }
4155
- function isLiveList(value) {
4156
- return value instanceof LiveList;
4157
- }
4158
- function isLiveMap(value) {
4159
- return value instanceof LiveMap;
4160
- }
4161
- function isLiveObject(value) {
4162
- return value instanceof LiveObject;
4163
- }
4164
- function isLiveRegister(value) {
4165
- return value instanceof LiveRegister;
4166
- }
4167
- function liveNodeToLson(obj) {
4168
- if (obj instanceof LiveRegister) {
4169
- return obj.data;
4170
- } else if (obj instanceof LiveList || obj instanceof LiveMap || obj instanceof LiveObject) {
4171
- return obj;
4172
- } else {
4173
- return assertNever(obj, "Unknown AbstractCrdt");
4174
- }
4175
- }
4176
- function lsonToLiveNode(value) {
4177
- if (value instanceof LiveObject || value instanceof LiveMap || value instanceof LiveList) {
4178
- return value;
4179
- } else {
4180
- return new LiveRegister(value);
4181
- }
4182
- }
4183
- var MAX_SOCKET_MESSAGE_SIZE = 1024 * 1024 - 512;
4184
- var htmlEscapables = {
4185
- "&": "&amp;",
4186
- "<": "&lt;",
4187
- ">": "&gt;",
4188
- '"': "&quot;",
4189
- "'": "&#39;"
4190
- };
4191
- var htmlEscapablesRegex = new RegExp(
4192
- Object.keys(htmlEscapables).map((entity) => `\\${entity}`).join("|"),
4193
- "g"
4194
- );
4195
- var markdownEscapables = {
4196
- _: "\\_",
4197
- "*": "\\*",
4198
- "#": "\\#",
4199
- "`": "\\`",
4200
- "~": "\\~",
4201
- "!": "\\!",
4202
- "|": "\\|",
4203
- "(": "\\(",
4204
- ")": "\\)",
4205
- "{": "\\{",
4206
- "}": "\\}",
4207
- "[": "\\[",
4208
- "]": "\\]"
4203
+ pushSceneEvent(postedEntry, lineAccountTypes);
4204
+ });
4205
+ return postedEntries;
4209
4206
  };
4210
- var markdownEscapablesRegex = new RegExp(
4211
- Object.keys(markdownEscapables).map((entity) => `\\${entity}`).join("|"),
4212
- "g"
4213
- );
4214
- detectDupes(PKG_NAME, PKG_VERSION, PKG_FORMAT);
4215
4207
 
4216
- // ../../node_modules/@liveblocks/client/dist/index.js
4217
- var PKG_NAME2 = "@liveblocks/client";
4218
- var PKG_VERSION2 = "3.7.1";
4219
- var PKG_FORMAT2 = "esm";
4220
- 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
+ };
4221
4243
 
4222
- // ../../libs/liveblocks-commands/src/utils/liveObjectOf.ts
4244
+ // ../../fragment-compositions/visualizer/src/utils/liveblocksUtils.ts
4223
4245
  init_cjs_shims();
4224
- var liveObjectOf = (fields) => {
4225
- return new LiveObject(fields);
4226
- };
4246
+ import assert3 from "assert";
4227
4247
 
4228
4248
  // ../../libs/liveblocks-commands/src/utils/schemaConverters.ts
4229
4249
  init_cjs_shims();
@@ -4404,10 +4424,7 @@ var toLivePaymentAccounting = (accounting, accountIdByStructuralPath) => {
4404
4424
  };
4405
4425
  var toLivePaymentTypeVersion = (paymentType, versionId, accountIdByStructuralPath) => liveObjectOf({
4406
4426
  id: versionId,
4407
- payment: liveObjectOf({
4408
- amount: paymentType.payment.amount,
4409
- direction: paymentType.payment.direction
4410
- }),
4427
+ payment: makeLivePaymentDetails(paymentType.payment),
4411
4428
  status: paymentType.status,
4412
4429
  accounting: toLivePaymentAccounting(
4413
4430
  paymentType.accounting,