@vscode/web-editors 0.0.2-112 → 0.0.2-114

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -152,7 +152,7 @@ const allowsEval = /* @__PURE__*/ cached(() => {
152
152
  return false;
153
153
  }
154
154
  });
155
- function isPlainObject(o) {
155
+ function isPlainObject$1(o) {
156
156
  if (isObject(o) === false) return false;
157
157
  const ctor = o.constructor;
158
158
  if (ctor === void 0) return true;
@@ -163,7 +163,7 @@ function isPlainObject(o) {
163
163
  return true;
164
164
  }
165
165
  function shallowClone(o) {
166
- if (isPlainObject(o)) return { ...o };
166
+ if (isPlainObject$1(o)) return { ...o };
167
167
  if (Array.isArray(o)) return [...o];
168
168
  if (o instanceof Map) return new Map(o);
169
169
  if (o instanceof Set) return new Set(o);
@@ -246,7 +246,7 @@ function omit(schema, mask) {
246
246
  }));
247
247
  }
248
248
  function extend(schema, shape) {
249
- if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
249
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
250
250
  const checks = schema._zod.def.checks;
251
251
  if (checks && checks.length > 0) {
252
252
  const existingShape = schema._zod.def.shape;
@@ -262,7 +262,7 @@ function extend(schema, shape) {
262
262
  } }));
263
263
  }
264
264
  function safeExtend(schema, shape) {
265
- if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
265
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
266
266
  return clone(schema, mergeDefs(schema._zod.def, { get shape() {
267
267
  const _shape = {
268
268
  ...schema._zod.def.shape,
@@ -1853,7 +1853,7 @@ function mergeValues(a, b) {
1853
1853
  valid: true,
1854
1854
  data: a
1855
1855
  };
1856
- if (isPlainObject(a) && isPlainObject(b)) {
1856
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
1857
1857
  const bKeys = Object.keys(b);
1858
1858
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1859
1859
  const newObj = {
@@ -4118,11 +4118,23 @@ function superRefine(fn, params) {
4118
4118
  //#endregion
4119
4119
  //#region src/protocol.ts
4120
4120
  const zJsonValue = unknown();
4121
+ /**
4122
+ * The concurrency control both sides use when they announce it: concurrent
4123
+ * edits are transformed against each other instead of one side's being
4124
+ * dropped. See `OtPeer`.
4125
+ */
4126
+ const OT_EDIT_TRANSFORM = "ot/1";
4121
4127
  const zEditorCapabilities = object({
4122
4128
  supportsContentEdits: boolean().optional(),
4123
4129
  supportsOptions: boolean().optional(),
4124
4130
  /** The editor implements `web-editor-presentation` (see {@link webEditorPresentationInterface}). */
4125
- supportsPresentation: boolean().optional()
4131
+ supportsPresentation: boolean().optional(),
4132
+ /**
4133
+ * Concurrency controls the editor implements, such as {@link OT_EDIT_TRANSFORM}.
4134
+ * Without one the host uses the client-authority policy, where
4135
+ * conflicting edits are dropped.
4136
+ */
4137
+ editTransforms: array(string()).optional()
4126
4138
  });
4127
4139
  const zHostCapabilities = object({
4128
4140
  supportsContentEdits: boolean().optional(),
@@ -4130,7 +4142,9 @@ const zHostCapabilities = object({
4130
4142
  supportsForceUpdate: boolean().optional(),
4131
4143
  supportsHostTransport: boolean().optional(),
4132
4144
  /** The host presents the editor inline and implements `web-editor-presentation-host`. */
4133
- supportsPresentation: boolean().optional()
4145
+ supportsPresentation: boolean().optional(),
4146
+ /** The concurrency control the host chose from the editor's `editTransforms`. */
4147
+ editTransform: string().optional()
4134
4148
  });
4135
4149
  const zTextEdit = object({
4136
4150
  offset: number().int().nonnegative(),
@@ -4152,7 +4166,12 @@ const zWebEditorUpdate = object({
4152
4166
  readOnly: boolean().optional(),
4153
4167
  serverRevision: number().int().nonnegative().optional(),
4154
4168
  acknowledgedClientRevision: number().int().nonnegative().optional(),
4155
- force: boolean().optional()
4169
+ force: boolean().optional(),
4170
+ /**
4171
+ * Sent with every `content` once the host chose a concurrency control, so
4172
+ * the editor knows it before `initialized` returns.
4173
+ */
4174
+ editTransform: string().optional()
4156
4175
  });
4157
4176
  /** How an embedding host currently presents the editor. */
4158
4177
  const zPresentationMode = _enum([
@@ -4194,6 +4213,12 @@ const webEditorHostInterface = defineInterface({
4194
4213
  basedOnServerRevision: number().int().nonnegative()
4195
4214
  })),
4196
4215
  /**
4216
+ * With an `editTransform`: the editor has integrated the host's edits up
4217
+ * to `serverRevision`. Lets the host forget them while the editor does
4218
+ * not edit; an `applyContentEdit` acknowledges them as well.
4219
+ */
4220
+ acknowledge: notificationType(object({ serverRevision: number().int().nonnegative() })),
4221
+ /**
4197
4222
  * The editor reports its preferred content height (px): the height it needs
4198
4223
  * to show its content without scrolling, independent of the frame's current
4199
4224
  * height. Measure the content, not the viewport or document, which follow
@@ -4352,7 +4377,7 @@ const vscodeAppEmbeddingEventsInterface = defineInterface({
4352
4377
  */
4353
4378
  function applyContentEdits(root, edits) {
4354
4379
  let current = root;
4355
- for (const edit of edits) if (edit.kind === "replace") current = setAtPath(current, edit.path, edit.newValue);
4380
+ for (const edit of edits) if (edit.kind === "replace") current = setAtPath(current, edit.path, cloneJson(edit.newValue));
4356
4381
  else {
4357
4382
  const existing = getAtPath(current, edit.path);
4358
4383
  if (typeof existing !== "string") throw new Error(`applyContentEdits: stringEdits at path [${edit.path.join(", ")}] requires a string, got ${typeof existing}`);
@@ -4366,6 +4391,9 @@ function applyTextEdits(text, edits) {
4366
4391
  for (const e of edits) result = result.slice(0, e.offset) + e.newText + result.slice(e.offset + e.length);
4367
4392
  return result;
4368
4393
  }
4394
+ function cloneJson(value) {
4395
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
4396
+ }
4369
4397
  function getAtPath(root, path) {
4370
4398
  let cur = root;
4371
4399
  for (const key of path) {
@@ -4440,13 +4468,638 @@ var Emitter = class {
4440
4468
  }
4441
4469
  };
4442
4470
  //#endregion
4471
+ //#region src/sync/otPeer.ts
4472
+ /**
4473
+ * One of the two sides of a session that keeps a document in sync between
4474
+ * two parties who both edit it (the Jupiter algorithm behind most operational
4475
+ * transformation systems).
4476
+ *
4477
+ * Each side applies its own operations immediately and sends them along with
4478
+ * how many of the other side's operations it had applied. When an operation
4479
+ * from the other side arrives, it was made without the local operations the
4480
+ * other side had not seen yet. Those pending operations and the incoming one
4481
+ * are transformed against each other: the incoming one is then applied, and
4482
+ * the pending ones now describe how the local state differs from the other
4483
+ * side's. Once both sides have received everything, they hold the same
4484
+ * document, and no operation was dropped.
4485
+ *
4486
+ * The leader's operations take precedence in conflicts. Exactly one side must
4487
+ * be the leader. Messages must arrive in the order they were sent.
4488
+ *
4489
+ * The leader can also start over from a state it sends in full ({@link reset});
4490
+ * the follower's operations that were made before it received that state are
4491
+ * then discarded on both sides.
4492
+ */
4493
+ var OtPeer = class {
4494
+ _type;
4495
+ role;
4496
+ _localRevision = 0;
4497
+ _remoteRevision = 0;
4498
+ _pending = [];
4499
+ /** Remote operations made before the remote side saw this local revision are discarded. */
4500
+ _barrier = 0;
4501
+ constructor(_type, role) {
4502
+ this._type = _type;
4503
+ this.role = role;
4504
+ }
4505
+ /** Number of local operations, including resets. */
4506
+ get localRevision() {
4507
+ return this._localRevision;
4508
+ }
4509
+ /** Number of remote operations integrated, including discarded ones. */
4510
+ get remoteRevision() {
4511
+ return this._remoteRevision;
4512
+ }
4513
+ /** Local operations the remote side has not acknowledged yet, oldest first. */
4514
+ get pending() {
4515
+ return this._pending.map((p) => p.op);
4516
+ }
4517
+ /**
4518
+ * The local operations after `revision`, oldest first: how the local state
4519
+ * differs from the state the remote side had when it had integrated
4520
+ * `revision` and everything local before. `undefined` if they are no
4521
+ * longer known, because they were acknowledged since or a reset happened.
4522
+ */
4523
+ operationsAfter(revision) {
4524
+ if (revision < this._barrier || revision > this._localRevision) return;
4525
+ const firstPending = this._pending[0]?.revision ?? this._localRevision + 1;
4526
+ return revision + 1 < firstPending ? void 0 : this._pending.slice(revision + 1 - firstPending).map((p) => p.op);
4527
+ }
4528
+ /**
4529
+ * Records an operation already applied to the local state. Send it with
4530
+ * the returned revision and {@link remoteRevision} as the acknowledgement.
4531
+ */
4532
+ local(op) {
4533
+ const revision = ++this._localRevision;
4534
+ this._pending.push({
4535
+ revision,
4536
+ op
4537
+ });
4538
+ return revision;
4539
+ }
4540
+ /**
4541
+ * Integrates an operation from the remote side.
4542
+ *
4543
+ * @param revision The remote side's revision after `op`.
4544
+ * @param acknowledgedRevision How many local operations the remote side had integrated when it made `op`.
4545
+ * @returns The operation to apply to the local state, or `undefined` if
4546
+ * `op` was made before the remote side received the latest reset.
4547
+ */
4548
+ remote(op, revision, acknowledgedRevision) {
4549
+ if (revision !== this._remoteRevision + 1) throw new Error(`OtPeer: expected remote revision ${this._remoteRevision + 1}, got ${revision}`);
4550
+ if (acknowledgedRevision > this._localRevision) throw new Error(`OtPeer: remote acknowledged revision ${acknowledgedRevision}, but the latest local revision is ${this._localRevision}`);
4551
+ this._remoteRevision = revision;
4552
+ if (acknowledgedRevision < this._barrier) return;
4553
+ this.acknowledge(acknowledgedRevision);
4554
+ let incoming = op;
4555
+ this._pending = this._pending.map(({ revision, op: pending }) => {
4556
+ let pendingPrime;
4557
+ if (this.role === "leader") [pendingPrime, incoming] = this._type.transform(pending, incoming);
4558
+ else [incoming, pendingPrime] = this._type.transform(incoming, pending);
4559
+ return {
4560
+ revision,
4561
+ op: pendingPrime
4562
+ };
4563
+ });
4564
+ return incoming;
4565
+ }
4566
+ /** The remote side has integrated all local operations up to `revision`. */
4567
+ acknowledge(revision) {
4568
+ if (revision > this._localRevision) throw new Error(`OtPeer: remote acknowledged revision ${revision}, but the latest local revision is ${this._localRevision}`);
4569
+ let i = 0;
4570
+ while (i < this._pending.length && this._pending[i].revision <= revision) i++;
4571
+ if (i > 0) this._pending = this._pending.slice(i);
4572
+ }
4573
+ /**
4574
+ * Leader only: the local state is about to be sent in full and replaces
4575
+ * whatever the follower has. Returns the revision of the reset.
4576
+ *
4577
+ * @param remoteRevision Treat remote operations up to this revision as
4578
+ * integrated, to recover when the remote side's revisions got out of step.
4579
+ */
4580
+ reset(remoteRevision = this._remoteRevision) {
4581
+ if (this.role !== "leader") throw new Error("OtPeer.reset: only the leader can reset");
4582
+ this._remoteRevision = Math.max(this._remoteRevision, remoteRevision);
4583
+ this._pending = [];
4584
+ this._barrier = ++this._localRevision;
4585
+ return this._localRevision;
4586
+ }
4587
+ /**
4588
+ * Follower only: replaces the local state with the leader's full state at
4589
+ * `revision`. Pending local operations are discarded, as the leader
4590
+ * discards them too.
4591
+ */
4592
+ acceptReset(revision) {
4593
+ if (this.role !== "follower") throw new Error("OtPeer.acceptReset: only the follower accepts resets");
4594
+ if (revision !== this._remoteRevision + 1) throw new Error(`OtPeer: expected remote revision ${this._remoteRevision + 1}, got ${revision}`);
4595
+ this._remoteRevision = revision;
4596
+ this._pending = [];
4597
+ }
4598
+ };
4599
+ //#endregion
4600
+ //#region src/sync/textOperation.ts
4601
+ /** {@link OtType} for {@link TextOperation}s. */
4602
+ const textOperationOt = { transform: (winner, loser) => TextOperation.transform(winner, loser) };
4603
+ /**
4604
+ * A change to a string, as a sequence of components that walk the original
4605
+ * string from start to end: keep (`retain`), add (`insert`) or remove
4606
+ * (`delete`) text. Everything after the last component is kept.
4607
+ *
4608
+ * Operations are normalized (see {@link TextOperationBuilder}), so equal
4609
+ * changes have equal components. Their size depends on the number of edited
4610
+ * regions, not on the length of the string.
4611
+ */
4612
+ var TextOperation = class TextOperation {
4613
+ components;
4614
+ static get identity() {
4615
+ return identityOperation;
4616
+ }
4617
+ /** Converts edits that apply one after another, as on the wire, into one operation. */
4618
+ static fromTextEdits(edits) {
4619
+ let result = TextOperation.identity;
4620
+ for (const edit of edits) result = result.compose(new TextOperationBuilder().retain(edit.offset).insert(edit.newText).delete(edit.length).build());
4621
+ return result;
4622
+ }
4623
+ /** Use {@link TextOperationBuilder}, which normalizes the components. */
4624
+ constructor(token, components) {
4625
+ this.components = components;
4626
+ if (token !== normalizedToken) throw new Error("TextOperation: use TextOperationBuilder");
4627
+ }
4628
+ get isIdentity() {
4629
+ return this.components.length === 0;
4630
+ }
4631
+ /** Length of the shortest string this operation applies to. */
4632
+ get baseSpan() {
4633
+ let span = 0;
4634
+ for (const c of this.components) if (c.kind !== "insert") span += c.length;
4635
+ return span;
4636
+ }
4637
+ apply(text) {
4638
+ if (this.baseSpan > text.length) throw new Error(`TextOperation spans ${this.baseSpan} characters, but the text has ${text.length}`);
4639
+ const parts = [];
4640
+ let offset = 0;
4641
+ for (const c of this.components) if (c.kind === "retain") {
4642
+ parts.push(text.slice(offset, offset + c.length));
4643
+ offset += c.length;
4644
+ } else if (c.kind === "insert") parts.push(c.text);
4645
+ else offset += c.length;
4646
+ parts.push(text.slice(offset));
4647
+ return parts.join("");
4648
+ }
4649
+ /** Edits in ascending order that, applied one after another, have the effect of this operation. */
4650
+ toTextEdits() {
4651
+ const edits = [];
4652
+ let offset = 0;
4653
+ let pending;
4654
+ const flush = () => {
4655
+ if (pending) {
4656
+ edits.push(pending);
4657
+ offset += pending.newText.length;
4658
+ pending = void 0;
4659
+ }
4660
+ };
4661
+ for (const c of this.components) if (c.kind === "retain") {
4662
+ flush();
4663
+ offset += c.length;
4664
+ } else {
4665
+ pending ??= {
4666
+ offset,
4667
+ length: 0,
4668
+ newText: ""
4669
+ };
4670
+ if (c.kind === "insert") pending.newText += c.text;
4671
+ else pending.length += c.length;
4672
+ }
4673
+ flush();
4674
+ return edits;
4675
+ }
4676
+ /** The operation that has the effect of this operation followed by `next`. */
4677
+ compose(next) {
4678
+ const builder = new TextOperationBuilder();
4679
+ const first = new ComponentCursor(this.components);
4680
+ const second = new ComponentCursor(next.components);
4681
+ while (!first.done || !second.done) {
4682
+ const a = first.peek();
4683
+ const b = second.peek();
4684
+ if (a.kind === "delete") builder.delete(first.take(a.length));
4685
+ else if (b.kind === "insert") builder.insert(second.takeText());
4686
+ else {
4687
+ const length = Math.min(a.length, b.length);
4688
+ if (a.kind === "retain") if (b.kind === "retain") builder.retain(length);
4689
+ else builder.delete(length);
4690
+ else if (b.kind === "retain") builder.insert(a.text.slice(0, length));
4691
+ first.take(length);
4692
+ second.take(length);
4693
+ }
4694
+ }
4695
+ return builder.build();
4696
+ }
4697
+ /**
4698
+ * Transforms two operations on the same string so that each applies after
4699
+ * the other and both orders give the same result (`b'(a(s)) === a'(b(s))`).
4700
+ * Where both insert at the same position, `winner`'s text comes first.
4701
+ *
4702
+ * @returns `[winner', loser']`: `winner'` applies after `loser`, `loser'` after `winner`.
4703
+ */
4704
+ static transform(winner, loser) {
4705
+ const winnerPrime = new TextOperationBuilder();
4706
+ const loserPrime = new TextOperationBuilder();
4707
+ const w = new ComponentCursor(winner.components);
4708
+ const l = new ComponentCursor(loser.components);
4709
+ while (!w.done || !l.done) {
4710
+ const a = w.peek();
4711
+ const b = l.peek();
4712
+ if (a.kind === "insert") {
4713
+ const text = w.takeText();
4714
+ winnerPrime.insert(text);
4715
+ loserPrime.retain(text.length);
4716
+ } else if (b.kind === "insert") {
4717
+ const text = l.takeText();
4718
+ winnerPrime.retain(text.length);
4719
+ loserPrime.insert(text);
4720
+ } else {
4721
+ const length = Math.min(a.length, b.length);
4722
+ if (a.kind === "retain" && b.kind === "retain") {
4723
+ winnerPrime.retain(length);
4724
+ loserPrime.retain(length);
4725
+ } else if (a.kind === "delete" && b.kind === "retain") winnerPrime.delete(length);
4726
+ else if (a.kind === "retain" && b.kind === "delete") loserPrime.delete(length);
4727
+ w.take(length);
4728
+ l.take(length);
4729
+ }
4730
+ }
4731
+ return [winnerPrime.build(), loserPrime.build()];
4732
+ }
4733
+ /**
4734
+ * Where `offset` in the original string ends up after this operation.
4735
+ * An offset inside deleted text maps to where the deletion happened. Text
4736
+ * inserted exactly at `offset` ends up before the result for
4737
+ * `assoc === "after"` and after it for `assoc === "before"`.
4738
+ */
4739
+ mapOffset(offset, assoc = "after") {
4740
+ let original = 0;
4741
+ let mapped = 0;
4742
+ for (const c of this.components) {
4743
+ if (c.kind === "insert") {
4744
+ if (original < offset || original === offset && assoc === "after") mapped += c.text.length;
4745
+ continue;
4746
+ }
4747
+ if (original >= offset) break;
4748
+ const length = Math.min(c.length, offset - original);
4749
+ original += length;
4750
+ if (c.kind === "retain") mapped += length;
4751
+ if (length < c.length) break;
4752
+ }
4753
+ return mapped + offset - original;
4754
+ }
4755
+ equals(other) {
4756
+ return this.components.length === other.components.length && this.components.every((c, i) => componentsEqual(c, other.components[i]));
4757
+ }
4758
+ toString() {
4759
+ return this.components.map((c) => c.kind === "insert" ? JSON.stringify(c.text) : c.kind === "retain" ? `${c.length}` : `-${c.length}`).join(" ");
4760
+ }
4761
+ };
4762
+ const normalizedToken = Symbol("TextOperation.normalized");
4763
+ /**
4764
+ * Builds normalized {@link TextOperation}s: no empty components, adjacent
4765
+ * components of the same kind merged, an insert before a delete at the same
4766
+ * position, and no trailing retain.
4767
+ */
4768
+ var TextOperationBuilder = class {
4769
+ _components = [];
4770
+ retain(length) {
4771
+ assertLength(length);
4772
+ if (length === 0) return this;
4773
+ const last = this._components.at(-1);
4774
+ if (last?.kind === "retain") this._components[this._components.length - 1] = {
4775
+ kind: "retain",
4776
+ length: last.length + length
4777
+ };
4778
+ else this._components.push({
4779
+ kind: "retain",
4780
+ length
4781
+ });
4782
+ return this;
4783
+ }
4784
+ insert(text) {
4785
+ if (text === "") return this;
4786
+ const last = this._components.at(-1);
4787
+ if (last?.kind === "insert") this._components[this._components.length - 1] = {
4788
+ kind: "insert",
4789
+ text: last.text + text
4790
+ };
4791
+ else if (last?.kind === "delete") {
4792
+ const beforeDelete = this._components.at(-2);
4793
+ if (beforeDelete?.kind === "insert") this._components[this._components.length - 2] = {
4794
+ kind: "insert",
4795
+ text: beforeDelete.text + text
4796
+ };
4797
+ else this._components.splice(this._components.length - 1, 0, {
4798
+ kind: "insert",
4799
+ text
4800
+ });
4801
+ } else this._components.push({
4802
+ kind: "insert",
4803
+ text
4804
+ });
4805
+ return this;
4806
+ }
4807
+ delete(length) {
4808
+ assertLength(length);
4809
+ if (length === 0) return this;
4810
+ const last = this._components.at(-1);
4811
+ if (last?.kind === "delete") this._components[this._components.length - 1] = {
4812
+ kind: "delete",
4813
+ length: last.length + length
4814
+ };
4815
+ else this._components.push({
4816
+ kind: "delete",
4817
+ length
4818
+ });
4819
+ return this;
4820
+ }
4821
+ build() {
4822
+ const components = this._components.at(-1)?.kind === "retain" ? this._components.slice(0, -1) : [...this._components];
4823
+ return new TextOperation(normalizedToken, components);
4824
+ }
4825
+ };
4826
+ /** Walks components, splitting them as needed. Past the end it yields an endless retain. */
4827
+ var ComponentCursor = class {
4828
+ _components;
4829
+ _index = 0;
4830
+ _consumed = 0;
4831
+ constructor(_components) {
4832
+ this._components = _components;
4833
+ }
4834
+ get done() {
4835
+ return this._index >= this._components.length;
4836
+ }
4837
+ /** The rest of the current component. */
4838
+ peek() {
4839
+ const c = this._components[this._index];
4840
+ if (c === void 0) return {
4841
+ kind: "retain",
4842
+ length: Infinity
4843
+ };
4844
+ if (c.kind === "insert") {
4845
+ const text = c.text.slice(this._consumed);
4846
+ return {
4847
+ kind: "insert",
4848
+ text,
4849
+ length: text.length
4850
+ };
4851
+ }
4852
+ return {
4853
+ kind: c.kind,
4854
+ length: c.length - this._consumed
4855
+ };
4856
+ }
4857
+ /** Consumes up to `length` characters of the current component and returns how many it consumed. */
4858
+ take(length) {
4859
+ const c = this._components[this._index];
4860
+ if (c === void 0) return length;
4861
+ const available = (c.kind === "insert" ? c.text.length : c.length) - this._consumed;
4862
+ if (length >= available) {
4863
+ this._index++;
4864
+ this._consumed = 0;
4865
+ return available;
4866
+ }
4867
+ this._consumed += length;
4868
+ return length;
4869
+ }
4870
+ /** Consumes the rest of the current insert. */
4871
+ takeText() {
4872
+ const c = this._components[this._index];
4873
+ if (c?.kind !== "insert") throw new Error("ComponentCursor.takeText: not at an insert");
4874
+ const text = c.text.slice(this._consumed);
4875
+ this._index++;
4876
+ this._consumed = 0;
4877
+ return text;
4878
+ }
4879
+ };
4880
+ function componentsEqual(a, b) {
4881
+ if (a.kind === "insert" || b.kind === "insert") return a.kind === b.kind && a.text === b.text;
4882
+ return a.kind === b.kind && a.length === b.length;
4883
+ }
4884
+ function assertLength(length) {
4885
+ if (!Number.isInteger(length) || length < 0) throw new Error(`TextOperation: invalid length ${length}`);
4886
+ }
4887
+ const identityOperation = new TextOperationBuilder().build();
4888
+ //#endregion
4889
+ //#region src/sync/textDiff.ts
4890
+ /**
4891
+ * A minimal operation that turns `oldText` into `newText`, so that unchanged
4892
+ * text in between separate changes is kept (and concurrent edits there keep
4893
+ * their place). Uses Myers' O(ND) algorithm on the part between the common
4894
+ * prefix and suffix; when the texts differ in more than `maxDistance`
4895
+ * characters, everything in between is replaced instead.
4896
+ */
4897
+ function diffText(oldText, newText, maxDistance = 256) {
4898
+ const shorter = Math.min(oldText.length, newText.length);
4899
+ let start = 0;
4900
+ while (start < shorter && oldText.charCodeAt(start) === newText.charCodeAt(start)) start++;
4901
+ let oldEnd = oldText.length;
4902
+ let newEnd = newText.length;
4903
+ while (oldEnd > start && newEnd > start && oldText.charCodeAt(oldEnd - 1) === newText.charCodeAt(newEnd - 1)) {
4904
+ oldEnd--;
4905
+ newEnd--;
4906
+ }
4907
+ const builder = new TextOperationBuilder().retain(start);
4908
+ const a = oldText.slice(start, oldEnd);
4909
+ const b = newText.slice(start, newEnd);
4910
+ const script = shortestEditScript(a, b, maxDistance);
4911
+ if (script) for (const step of script) if (step.kind === "keep") builder.retain(step.length);
4912
+ else if (step.kind === "insert") builder.insert(b.slice(step.newStart, step.newStart + step.length));
4913
+ else builder.delete(step.length);
4914
+ else builder.insert(b).delete(a.length);
4915
+ return builder.build();
4916
+ }
4917
+ /** Myers' shortest edit script from `a` to `b`, or `undefined` if it needs more than `maxDistance` steps. */
4918
+ function shortestEditScript(a, b, maxDistance) {
4919
+ const n = a.length;
4920
+ const m = b.length;
4921
+ const max = Math.min(n + m, maxDistance);
4922
+ const offset = max + 1;
4923
+ const v = new Int32Array(2 * max + 3);
4924
+ const trace = [];
4925
+ for (let d = 0; d <= max; d++) {
4926
+ trace.push(v.slice());
4927
+ for (let k = -d; k <= d; k += 2) {
4928
+ let x = k === -d || k !== d && v[offset + k - 1] < v[offset + k + 1] ? v[offset + k + 1] : v[offset + k - 1] + 1;
4929
+ let y = x - k;
4930
+ while (x < n && y < m && a.charCodeAt(x) === b.charCodeAt(y)) {
4931
+ x++;
4932
+ y++;
4933
+ }
4934
+ v[offset + k] = x;
4935
+ if (x >= n && y >= m) return backtrack(trace, d, n, m, offset);
4936
+ }
4937
+ }
4938
+ }
4939
+ function backtrack(trace, distance, n, m, offset) {
4940
+ const reversed = [];
4941
+ let x = n;
4942
+ let y = m;
4943
+ for (let d = distance; d > 0; d--) {
4944
+ const v = trace[d];
4945
+ const k = x - y;
4946
+ const previousK = k === -d || k !== d && v[offset + k - 1] < v[offset + k + 1] ? k + 1 : k - 1;
4947
+ const previousX = v[offset + previousK];
4948
+ const previousY = previousX - previousK;
4949
+ const snake = Math.min(x - previousX, y - previousY);
4950
+ if (snake > 0) reversed.push({
4951
+ kind: "keep",
4952
+ length: snake
4953
+ });
4954
+ x -= snake;
4955
+ y -= snake;
4956
+ if (x === previousX) {
4957
+ reversed.push({
4958
+ kind: "insert",
4959
+ newStart: previousY,
4960
+ length: 1
4961
+ });
4962
+ y--;
4963
+ } else {
4964
+ reversed.push({
4965
+ kind: "delete",
4966
+ length: 1
4967
+ });
4968
+ x--;
4969
+ }
4970
+ }
4971
+ if (x > 0) reversed.push({
4972
+ kind: "keep",
4973
+ length: x
4974
+ });
4975
+ return reversed.reverse();
4976
+ }
4977
+ //#endregion
4978
+ //#region src/sync/contentOperation.ts
4979
+ /** {@link OtType} for lists of {@link ContentEdit}s, as exchanged by web editors. */
4980
+ const contentEditsOt = { transform: (winner, loser) => transformContentEdits(winner, loser) };
4981
+ /**
4982
+ * Transforms two concurrent lists of {@link ContentEdit}s made on the same
4983
+ * content, so that each list applies after the other and both orders give the
4984
+ * same content.
4985
+ *
4986
+ * Edits at unrelated paths do not interact. String edits at the same path are
4987
+ * merged with {@link TextOperation.transform}. A `replace` overrides every
4988
+ * concurrent edit at or below its path; of two replacements at the same path,
4989
+ * `winner`'s is kept.
4990
+ *
4991
+ * @returns `[winner', loser']`: `winner'` applies after `loser`, `loser'` after `winner`.
4992
+ */
4993
+ function transformContentEdits(winner, loser) {
4994
+ const winnerPrime = [];
4995
+ let loserPrime = [...loser];
4996
+ for (const edit of winner) {
4997
+ let current = edit;
4998
+ const nextLoser = [];
4999
+ for (const other of loserPrime) {
5000
+ if (current === void 0) {
5001
+ nextLoser.push(other);
5002
+ continue;
5003
+ }
5004
+ const [w, l] = transformContentEdit(current, other);
5005
+ current = w;
5006
+ if (l !== void 0) nextLoser.push(l);
5007
+ }
5008
+ loserPrime = nextLoser;
5009
+ if (current !== void 0) winnerPrime.push(current);
5010
+ }
5011
+ return [winnerPrime, loserPrime];
5012
+ }
5013
+ /** `undefined` stands for an edit that has no effect anymore. */
5014
+ function transformContentEdit(winner, loser) {
5015
+ const relation = relatePaths(winner.path, loser.path);
5016
+ if (relation === "unrelated") return [winner, loser];
5017
+ if (winner.kind === "replace" && loser.kind === "replace") return relation === "descendant" ? [void 0, loser] : [winner, void 0];
5018
+ if (winner.kind === "replace") return [winner, void 0];
5019
+ if (loser.kind === "replace") return [void 0, loser];
5020
+ if (relation !== "equal") return [winner, loser];
5021
+ const [w, l] = TextOperation.transform(TextOperation.fromTextEdits(winner.stringEdits), TextOperation.fromTextEdits(loser.stringEdits));
5022
+ return [toStringEdits(winner.path, w), toStringEdits(loser.path, l)];
5023
+ }
5024
+ /** How path `a` relates to path `b`: `"ancestor"` means `a` is a proper prefix of `b`. */
5025
+ function relatePaths(a, b) {
5026
+ const length = Math.min(a.length, b.length);
5027
+ for (let i = 0; i < length; i++) if (a[i] !== b[i]) return "unrelated";
5028
+ return a.length === b.length ? "equal" : a.length < b.length ? "ancestor" : "descendant";
5029
+ }
5030
+ function toStringEdits(path, operation) {
5031
+ return operation.isIdentity ? void 0 : {
5032
+ kind: "stringEdits",
5033
+ path,
5034
+ stringEdits: operation.toTextEdits()
5035
+ };
5036
+ }
5037
+ /**
5038
+ * Where `offset` in the string at `path` ends up after `edits`, or `undefined`
5039
+ * if the string was replaced. See {@link TextOperation.mapOffset} for `assoc`.
5040
+ */
5041
+ function mapContentOffset(edits, path, offset, assoc = "after") {
5042
+ let result = offset;
5043
+ for (const edit of edits) {
5044
+ const relation = relatePaths(edit.path, path);
5045
+ if (relation === "unrelated" || relation === "descendant") continue;
5046
+ if (edit.kind === "replace") return;
5047
+ if (relation === "equal") result = TextOperation.fromTextEdits(edit.stringEdits).mapOffset(result, assoc);
5048
+ }
5049
+ return result;
5050
+ }
5051
+ /** Maps `offset` through each list of edits in turn; `undefined` if `operations` is `undefined` or the offset does not survive an edit. */
5052
+ function mapThrough(operations, path, offset, assoc) {
5053
+ if (!operations) return;
5054
+ let result = offset;
5055
+ for (const edits of operations) {
5056
+ result = mapContentOffset(edits, path, result, assoc);
5057
+ if (result === void 0) return;
5058
+ }
5059
+ return result;
5060
+ }
5061
+ /**
5062
+ * Edits that turn `oldValue` into `newValue`, as fine-grained as possible so
5063
+ * that they merge with concurrent edits: changed strings become string edits,
5064
+ * objects with the same keys and arrays with the same length are compared
5065
+ * member by member, and anything else is replaced.
5066
+ */
5067
+ function diffContent(oldValue, newValue, path = []) {
5068
+ if (typeof oldValue === "string" && typeof newValue === "string") {
5069
+ const operation = diffText(oldValue, newValue);
5070
+ return operation.isIdentity ? [] : [{
5071
+ kind: "stringEdits",
5072
+ path,
5073
+ stringEdits: operation.toTextEdits()
5074
+ }];
5075
+ }
5076
+ if (Array.isArray(oldValue) && Array.isArray(newValue) && oldValue.length === newValue.length) return oldValue.flatMap((item, i) => diffContent(item, newValue[i], [...path, String(i)]));
5077
+ if (isPlainObject(oldValue) && isPlainObject(newValue) && haveSameKeys(oldValue, newValue)) return Object.keys(oldValue).flatMap((key) => diffContent(oldValue[key], newValue[key], [...path, key]));
5078
+ return oldValue === newValue ? [] : [{
5079
+ kind: "replace",
5080
+ path,
5081
+ newValue
5082
+ }];
5083
+ }
5084
+ function isPlainObject(value) {
5085
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5086
+ }
5087
+ function haveSameKeys(a, b) {
5088
+ const keys = Object.keys(a);
5089
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key));
5090
+ }
5091
+ //#endregion
4443
5092
  //#region src/host/WebEditorHost.ts
4444
5093
  /**
4445
5094
  * Host-side façade for the web-editor v0.12 protocol.
4446
5095
  *
4447
5096
  * Owns the canonical text content. Translates between text/JSON form and the
4448
- * structural edits exchanged with the editor. Maintains the revision pair
4449
- * required by the client-authority conflict policy.
5097
+ * structural edits exchanged with the editor.
5098
+ *
5099
+ * Concurrent edits from both sides are merged with operational transformation
5100
+ * when the editor supports it ({@link OT_EDIT_TRANSFORM}). Otherwise the host
5101
+ * maintains the revision pair required by the client-authority conflict
5102
+ * policy, under which conflicting edits are dropped.
4450
5103
  */
4451
5104
  var WebEditorHost = class {
4452
5105
  _connection;
@@ -4461,12 +5114,17 @@ var WebEditorHost = class {
4461
5114
  _text;
4462
5115
  _readOnly;
4463
5116
  _presentationMode;
5117
+ /** Set while connected to an editor that merges concurrent edits. */
5118
+ _transform;
5119
+ /** Client-authority policy only. */
4464
5120
  _serverRevision = 0;
5121
+ /** Client-authority policy only. */
4465
5122
  _acknowledgedClientRevision = 0;
4466
5123
  _editorInitialized = false;
4467
5124
  _editorCapabilities;
4468
5125
  _pendingHostTransportMessages = [];
4469
5126
  _onDidChangeText = new Emitter();
5127
+ /** The editor changed the content. `edits` apply to the previous content, in the editor's form. */
4470
5128
  onDidChangeText = this._onDidChangeText.event;
4471
5129
  _onDidInitialize = new Emitter();
4472
5130
  onDidInitialize = this._onDidInitialize.event;
@@ -4500,16 +5158,24 @@ var WebEditorHost = class {
4500
5158
  this._editorInitialized = true;
4501
5159
  this._serverRevision = 0;
4502
5160
  this._acknowledgedClientRevision = 0;
5161
+ this._transform = params.capabilities?.editTransforms?.includes("ot/1") ? new OtPeer(contentEditsOt, "leader") : void 0;
4503
5162
  this._pushFullUpdate();
4504
5163
  for (const message of this._pendingHostTransportMessages.splice(0)) this._clientTransport.message({ message });
4505
5164
  this._pushPresentationMode();
4506
5165
  this._onDidInitialize.fire({ capabilities: params.capabilities });
4507
5166
  return {
4508
5167
  protocolVersion: "web-editor-host/0.12",
4509
- capabilities: this._capabilities
5168
+ capabilities: this._transform ? {
5169
+ ...this._capabilities,
5170
+ editTransform: OT_EDIT_TRANSFORM
5171
+ } : this._capabilities
4510
5172
  };
4511
5173
  },
4512
5174
  applyContentEdit: (params) => {
5175
+ if (this._transform) {
5176
+ this._applyTransformedEditorEdit(this._transform, params);
5177
+ return;
5178
+ }
4513
5179
  if (this._readOnly) {
4514
5180
  this._onError("Editor sent applyContentEdit while readOnly");
4515
5181
  this._acknowledgeAndRestore(params.clientRevision);
@@ -4520,29 +5186,28 @@ var WebEditorHost = class {
4520
5186
  this._acknowledgeAndRestore(params.clientRevision);
4521
5187
  return;
4522
5188
  }
4523
- let newValue;
4524
- try {
4525
- newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), params.edits);
4526
- } catch (e) {
4527
- this._onError("Failed to apply content edits from editor", e);
4528
- this._acknowledgeAndRestore(params.clientRevision);
4529
- return;
4530
- }
4531
- let newText;
4532
- try {
4533
- newText = decodeFromEditor(newValue, this._contentType, this._jsonFormat);
4534
- } catch (e) {
4535
- this._onError("Failed to decode editor content", e);
5189
+ const newText = this._applyEditorEdits(params.edits);
5190
+ if (newText === void 0) {
4536
5191
  this._acknowledgeAndRestore(params.clientRevision);
4537
5192
  return;
4538
5193
  }
4539
5194
  this._acknowledgedClientRevision = Math.max(this._acknowledgedClientRevision, params.clientRevision);
4540
5195
  if (newText !== this._text) {
4541
5196
  this._text = newText;
4542
- this._onDidChangeText.fire({ text: newText });
5197
+ this._onDidChangeText.fire({
5198
+ text: newText,
5199
+ edits: params.edits
5200
+ });
4543
5201
  }
4544
5202
  this._pushAcknowledgement();
4545
5203
  },
5204
+ acknowledge: (params) => {
5205
+ try {
5206
+ this._transform?.acknowledge(params.serverRevision);
5207
+ } catch (e) {
5208
+ this._onError("Editor acknowledged edits the host did not send", e);
5209
+ }
5210
+ },
4546
5211
  reportSize: (params) => {
4547
5212
  this._onDidReportSize.fire({ height: params.height });
4548
5213
  }
@@ -4563,14 +5228,46 @@ var WebEditorHost = class {
4563
5228
  getText() {
4564
5229
  return this._text;
4565
5230
  }
5231
+ /** The current content's version, to send along with offsets into it. */
5232
+ get version() {
5233
+ return this._transform ? {
5234
+ serverRevision: this._transform.localRevision,
5235
+ clientRevision: this._transform.remoteRevision
5236
+ } : {
5237
+ serverRevision: this._serverRevision,
5238
+ clientRevision: this._acknowledgedClientRevision
5239
+ };
5240
+ }
5241
+ /**
5242
+ * Maps an offset into the string at `path`, which the editor computed on
5243
+ * its content at `version`, into the current content. Call it when the
5244
+ * editor's message arrives: its earlier edits are integrated by then.
5245
+ *
5246
+ * @returns `undefined` if the offset cannot be mapped, for example because
5247
+ * the string was replaced or the content was reset since.
5248
+ */
5249
+ mapOffset(version, path, offset, assoc) {
5250
+ if (!this._transform) {
5251
+ const current = this.version;
5252
+ return version.serverRevision === current.serverRevision && version.clientRevision === current.clientRevision ? offset : void 0;
5253
+ }
5254
+ if (version.clientRevision !== this._transform.remoteRevision) return;
5255
+ return mapThrough(this._transform.operationsAfter(version.serverRevision), path, offset, assoc);
5256
+ }
4566
5257
  /**
4567
- * Push a new full text to the editor. Sent as a `replace` at the document
4568
- * root. If `force`, the editor must adopt it even with pending local edits.
5258
+ * Change the text the editor shows.
5259
+ *
5260
+ * When the editor merges concurrent edits, the change is sent as edits
5261
+ * that merge with the editor's unsent edits. Otherwise, and with `force`,
5262
+ * the full text is sent. If `force`, the editor must adopt it even with
5263
+ * pending local edits, which are then discarded.
4569
5264
  */
4570
5265
  setText(text, opts = {}) {
4571
5266
  if (text === this._text && !opts.force) return;
5267
+ const edits = this._transform && !opts.force ? this._diff(this._text, text) : void 0;
4572
5268
  this._text = text;
4573
- this._pushFullUpdate(opts.force);
5269
+ if (edits) this._sendHostEdits(edits);
5270
+ else this._pushFullUpdate(opts.force);
4574
5271
  }
4575
5272
  /**
4576
5273
  * Reassign this host/editor connection to another logical document.
@@ -4599,29 +5296,23 @@ var WebEditorHost = class {
4599
5296
  this._readOnly = readOnly;
4600
5297
  if (this._editorInitialized) this._editor.update({
4601
5298
  readOnly,
4602
- acknowledgedClientRevision: this._acknowledgedClientRevision
5299
+ acknowledgedClientRevision: this._transform?.remoteRevision ?? this._acknowledgedClientRevision
4603
5300
  });
4604
5301
  }
4605
5302
  /**
4606
- * Push fine-grained edits to the editor.
4607
- * The host is responsible for keeping its own `_text` consistent with these edits.
5303
+ * Change the text by fine-grained edits, which are pushed to the editor.
5304
+ * An editor that initializes later receives the changed text.
4608
5305
  */
4609
5306
  applyEdits(edits) {
4610
- if (edits.length === 0 || !this._editorInitialized) return;
4611
- let newValue;
5307
+ if (edits.length === 0) return;
4612
5308
  try {
4613
- newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), edits);
5309
+ const newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), edits);
4614
5310
  this._text = decodeFromEditor(newValue, this._contentType, this._jsonFormat);
4615
5311
  } catch (e) {
4616
5312
  this._onError("Failed to apply outgoing edits to local text", e);
4617
5313
  return;
4618
5314
  }
4619
- this._serverRevision++;
4620
- this._editor.applyContentEdits({
4621
- edits,
4622
- serverRevision: this._serverRevision,
4623
- acknowledgedClientRevision: this._acknowledgedClientRevision
4624
- });
5315
+ this._sendHostEdits(edits);
4625
5316
  }
4626
5317
  dispose() {
4627
5318
  this._hostTransportSubscription?.dispose();
@@ -4633,8 +5324,86 @@ var WebEditorHost = class {
4633
5324
  this._pendingHostTransportMessages.length = 0;
4634
5325
  this._connection.close();
4635
5326
  }
5327
+ _applyTransformedEditorEdit(transform, params) {
5328
+ let edits;
5329
+ try {
5330
+ edits = transform.remote(params.edits, params.clientRevision, params.basedOnServerRevision);
5331
+ } catch (e) {
5332
+ this._onError("Editor edit does not follow the edit transform protocol", e);
5333
+ this._resetEditor(transform, params.clientRevision);
5334
+ return;
5335
+ }
5336
+ if (edits === void 0) {
5337
+ this._pushAcknowledgement();
5338
+ return;
5339
+ }
5340
+ if (this._readOnly) {
5341
+ this._onError("Editor sent applyContentEdit while readOnly");
5342
+ this._resetEditor(transform);
5343
+ return;
5344
+ }
5345
+ const newText = this._applyEditorEdits(edits);
5346
+ if (newText === void 0) {
5347
+ this._resetEditor(transform);
5348
+ return;
5349
+ }
5350
+ if (newText !== this._text) {
5351
+ this._text = newText;
5352
+ this._onDidChangeText.fire({
5353
+ text: newText,
5354
+ edits
5355
+ });
5356
+ }
5357
+ this._pushAcknowledgement();
5358
+ }
5359
+ /** The text after the editor's `edits`, or `undefined` after reporting why they do not apply. */
5360
+ _applyEditorEdits(edits) {
5361
+ let newValue;
5362
+ try {
5363
+ newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), edits);
5364
+ } catch (e) {
5365
+ this._onError("Failed to apply content edits from editor", e);
5366
+ return;
5367
+ }
5368
+ try {
5369
+ return decodeFromEditor(newValue, this._contentType, this._jsonFormat);
5370
+ } catch (e) {
5371
+ this._onError("Failed to decode editor content", e);
5372
+ return;
5373
+ }
5374
+ }
5375
+ /** Edits from `oldText` to `newText` in the editor's form, or `undefined` if either cannot be encoded. */
5376
+ _diff(oldText, newText) {
5377
+ try {
5378
+ return diffContent(encodeForEditor(oldText, this._contentType), encodeForEditor(newText, this._contentType));
5379
+ } catch {
5380
+ return;
5381
+ }
5382
+ }
5383
+ _sendHostEdits(edits) {
5384
+ if (edits.length === 0 || !this._editorInitialized) return;
5385
+ if (this._transform) {
5386
+ const serverRevision = this._transform.local(edits);
5387
+ this._editor.applyContentEdits({
5388
+ edits: [...edits],
5389
+ serverRevision,
5390
+ acknowledgedClientRevision: this._transform.remoteRevision
5391
+ });
5392
+ return;
5393
+ }
5394
+ this._serverRevision++;
5395
+ this._editor.applyContentEdits({
5396
+ edits,
5397
+ serverRevision: this._serverRevision,
5398
+ acknowledgedClientRevision: this._acknowledgedClientRevision
5399
+ });
5400
+ }
4636
5401
  _pushFullUpdate(force) {
4637
5402
  if (!this._editorInitialized) return;
5403
+ if (this._transform) {
5404
+ this._resetEditor(this._transform);
5405
+ return;
5406
+ }
4638
5407
  this._serverRevision++;
4639
5408
  let content;
4640
5409
  try {
@@ -4651,8 +5420,34 @@ var WebEditorHost = class {
4651
5420
  force
4652
5421
  });
4653
5422
  }
5423
+ /**
5424
+ * Sends the full content, which replaces the editor's. Editor edits made
5425
+ * before the editor receives it are discarded on both sides.
5426
+ */
5427
+ _resetEditor(transform, clientRevision) {
5428
+ let content;
5429
+ try {
5430
+ content = encodeForEditor(this._text, this._contentType);
5431
+ } catch (e) {
5432
+ this._onError("Failed to encode text for editor", e);
5433
+ return;
5434
+ }
5435
+ const serverRevision = transform.reset(clientRevision);
5436
+ this._editor.update({
5437
+ content,
5438
+ readOnly: this._readOnly,
5439
+ serverRevision,
5440
+ acknowledgedClientRevision: transform.remoteRevision,
5441
+ force: true,
5442
+ editTransform: OT_EDIT_TRANSFORM
5443
+ });
5444
+ }
4654
5445
  _pushAcknowledgement() {
4655
5446
  if (!this._editorInitialized) return;
5447
+ if (this._transform) {
5448
+ this._editor.update({ acknowledgedClientRevision: this._transform.remoteRevision });
5449
+ return;
5450
+ }
4656
5451
  this._editor.update({
4657
5452
  serverRevision: this._serverRevision,
4658
5453
  acknowledgedClientRevision: this._acknowledgedClientRevision
@@ -4809,6 +5604,11 @@ var HostConnection = class HostConnection {
4809
5604
  * Calls `host.initialized` immediately, then exposes the current content and
4810
5605
  * read-only flag as observable events. Local edits made through {@link applyEdits}
4811
5606
  * are sent to the host with monotonically increasing client revisions.
5607
+ *
5608
+ * When the host supports it ({@link OT_EDIT_TRANSFORM}), host edits that
5609
+ * arrive while local edits are unacknowledged are transformed against them,
5610
+ * so neither side's edits are lost. Otherwise such host changes are dropped
5611
+ * (client-authority policy).
4812
5612
  */
4813
5613
  var WebEditorClient = class WebEditorClient {
4814
5614
  _connection;
@@ -4826,13 +5626,21 @@ var WebEditorClient = class WebEditorClient {
4826
5626
  _presentationPreferences;
4827
5627
  _pendingHostTransportMessages = [];
4828
5628
  _hostTransportActivated = false;
4829
- _clientRevision = 0;
5629
+ /** Local edits and their revisions; its pending edits are those the host has not acknowledged. */
5630
+ _edits = new OtPeer(contentEditsOt, "follower");
5631
+ /** Whether the host transforms concurrent edits, as announced with its first content. */
5632
+ _transform = false;
5633
+ /** Client-authority policy only. */
4830
5634
  _basedOnServerRevision = 0;
4831
- /** Number of un-acked local revisions. While > 0 the editor has pending edits. */
4832
- _pendingLocalEdits = 0;
4833
5635
  _onDidChangeContent = new Emitter();
5636
+ /**
5637
+ * The content changed: by a local edit, by host edits (after
5638
+ * {@link onDidApplyHostEdits}) or replaced by the host. Listeners must
5639
+ * tolerate content they already show.
5640
+ */
4834
5641
  onDidChangeContent = this._onDidChangeContent.event;
4835
5642
  _onDidApplyHostEdits = new Emitter();
5643
+ /** Host edits were applied; `edits` are relative to the previous content, after transformation against local edits. */
4836
5644
  onDidApplyHostEdits = this._onDidApplyHostEdits.event;
4837
5645
  _onDidChangeReadOnly = new Emitter();
4838
5646
  onDidChangeReadOnly = this._onDidChangeReadOnly.event;
@@ -4875,11 +5683,13 @@ var WebEditorClient = class WebEditorClient {
4875
5683
  protocolVersion: "web-editor/0.12",
4876
5684
  contentType: options.contentType ?? "text",
4877
5685
  capabilities: {
5686
+ editTransforms: [OT_EDIT_TRANSFORM],
4878
5687
  ...options.capabilities,
4879
5688
  supportsPresentation: true
4880
5689
  }
4881
5690
  }).then((r) => {
4882
5691
  this._hostCapabilities = r.capabilities;
5692
+ this._transform ||= r.capabilities?.editTransform === OT_EDIT_TRANSFORM;
4883
5693
  this._connected = true;
4884
5694
  if (this._presentationPreferences) this.setPresentationPreferences(this._presentationPreferences);
4885
5695
  if (r.capabilities?.supportsHostTransport) this._hostTransport = {
@@ -4912,6 +5722,29 @@ var WebEditorClient = class WebEditorClient {
4912
5722
  getContent() {
4913
5723
  return this._content;
4914
5724
  }
5725
+ /** The current content's version, to send along with offsets into it. */
5726
+ get version() {
5727
+ return {
5728
+ serverRevision: this._serverRevision,
5729
+ clientRevision: this._edits.localRevision
5730
+ };
5731
+ }
5732
+ /**
5733
+ * Maps an offset into the string at `path`, which the host computed on its
5734
+ * content at `version`, into the current content. Call it when the host's
5735
+ * message arrives.
5736
+ *
5737
+ * @returns `undefined` if the offset cannot be mapped, for example because
5738
+ * host edits arrived since or the string was replaced.
5739
+ */
5740
+ mapOffset(version, path, offset, assoc) {
5741
+ if (version.serverRevision !== this._serverRevision) return;
5742
+ return mapThrough(this._edits.operationsAfter(version.clientRevision), path, offset, assoc);
5743
+ }
5744
+ /** The host revision the content is based on. */
5745
+ get _serverRevision() {
5746
+ return this._transform ? this._edits.remoteRevision : this._basedOnServerRevision;
5747
+ }
4915
5748
  getReadOnly() {
4916
5749
  return this._readOnly;
4917
5750
  }
@@ -4933,16 +5766,15 @@ var WebEditorClient = class WebEditorClient {
4933
5766
  this._onError("Failed to apply local edits", e);
4934
5767
  return;
4935
5768
  }
4936
- this._clientRevision++;
4937
- this._pendingLocalEdits++;
5769
+ const clientRevision = this._edits.local(edits);
4938
5770
  this._onDidChangeContent.fire({
4939
5771
  content: this._content,
4940
5772
  force: false
4941
5773
  });
4942
5774
  this._host.applyContentEdit({
4943
- edits,
4944
- clientRevision: this._clientRevision,
4945
- basedOnServerRevision: this._basedOnServerRevision
5775
+ edits: [...edits],
5776
+ clientRevision,
5777
+ basedOnServerRevision: this._serverRevision
4946
5778
  });
4947
5779
  }
4948
5780
  /**
@@ -4984,8 +5816,9 @@ var WebEditorClient = class WebEditorClient {
4984
5816
  this._connection.close();
4985
5817
  }
4986
5818
  _handleUpdate(params) {
5819
+ if (params.editTransform === "ot/1") this._transform = true;
4987
5820
  if (params.acknowledgedClientRevision !== void 0) this._acknowledge(params.acknowledgedClientRevision);
4988
- if (params.serverRevision !== void 0) this._basedOnServerRevision = params.serverRevision;
5821
+ if (!this._transform && params.serverRevision !== void 0) this._basedOnServerRevision = params.serverRevision;
4989
5822
  if (params.readOnly !== void 0 && params.readOnly !== this._readOnly) {
4990
5823
  this._readOnly = params.readOnly;
4991
5824
  this._onDidChangeReadOnly.fire({ readOnly: params.readOnly });
@@ -4994,19 +5827,35 @@ var WebEditorClient = class WebEditorClient {
4994
5827
  this._options = params.options;
4995
5828
  this._onDidChangeOptions.fire({ options: params.options });
4996
5829
  }
4997
- if (params.content !== void 0) {
4998
- if (this._pendingLocalEdits > 0 && !params.force) return;
5830
+ if (params.content === void 0) return;
5831
+ if (this._transform) {
5832
+ try {
5833
+ this._edits.acceptReset(params.serverRevision ?? -1);
5834
+ } catch (e) {
5835
+ this._onError("Host content does not follow the edit transform protocol", e);
5836
+ }
4999
5837
  this._content = params.content;
5000
5838
  this._onDidChangeContent.fire({
5001
5839
  content: params.content,
5002
- force: params.force === true
5840
+ force: true
5003
5841
  });
5842
+ return;
5004
5843
  }
5844
+ if (this._edits.pending.length > 0 && !params.force) return;
5845
+ this._content = params.content;
5846
+ this._onDidChangeContent.fire({
5847
+ content: params.content,
5848
+ force: params.force === true
5849
+ });
5005
5850
  }
5006
5851
  _handleApplyContentEdits(params) {
5852
+ if (this._transform) {
5853
+ this._applyTransformedHostEdits(params);
5854
+ return;
5855
+ }
5007
5856
  this._acknowledge(params.acknowledgedClientRevision);
5008
5857
  this._basedOnServerRevision = params.serverRevision;
5009
- if (this._pendingLocalEdits > 0) return;
5858
+ if (this._edits.pending.length > 0) return;
5010
5859
  try {
5011
5860
  this._content = applyContentEdits(this._content, params.edits);
5012
5861
  } catch (e) {
@@ -5018,10 +5867,36 @@ var WebEditorClient = class WebEditorClient {
5018
5867
  content: this._content
5019
5868
  });
5020
5869
  }
5021
- _acknowledge(ackedClientRevision) {
5022
- const acked = Math.max(0, this._clientRevision - (this._clientRevision - ackedClientRevision));
5023
- const newPending = Math.max(0, this._clientRevision - acked);
5024
- this._pendingLocalEdits = newPending;
5870
+ _applyTransformedHostEdits(params) {
5871
+ let edits;
5872
+ try {
5873
+ edits = [...this._edits.remote(params.edits, params.serverRevision, params.acknowledgedClientRevision) ?? []];
5874
+ } catch (e) {
5875
+ this._onError("Host edits do not follow the edit transform protocol", e);
5876
+ return;
5877
+ }
5878
+ try {
5879
+ this._content = applyContentEdits(this._content, edits);
5880
+ } catch (e) {
5881
+ this._onError("Failed to apply host edits", e);
5882
+ return;
5883
+ }
5884
+ this._host.acknowledge({ serverRevision: params.serverRevision });
5885
+ this._onDidApplyHostEdits.fire({
5886
+ edits,
5887
+ content: this._content
5888
+ });
5889
+ this._onDidChangeContent.fire({
5890
+ content: this._content,
5891
+ force: false
5892
+ });
5893
+ }
5894
+ _acknowledge(clientRevision) {
5895
+ try {
5896
+ this._edits.acknowledge(clientRevision);
5897
+ } catch (e) {
5898
+ this._onError("Host acknowledged edits the editor did not send", e);
5899
+ }
5025
5900
  }
5026
5901
  };
5027
5902
  //#endregion
@@ -5248,6 +6123,6 @@ var VsCodeAppHostClient = class {
5248
6123
  }
5249
6124
  };
5250
6125
  //#endregion
5251
- export { EmbeddedAppHandle, VsCodeAppHostClient, WebEditorClient, WebEditorHost, WindowMessageTransport, applyContentEdits, applyTextEdits, createWindowParentConnection, decodeFromEditor, encodeForEditor, vscodeAppEmbeddingEventsInterface, vscodeAppHostInterface, webEditorClientTransportInterface, webEditorHostInterface, webEditorHostTransportInterface, webEditorInterface, webEditorPresentationHostInterface, webEditorPresentationInterface };
6126
+ export { EmbeddedAppHandle, OT_EDIT_TRANSFORM, OtPeer, TextOperation, TextOperationBuilder, VsCodeAppHostClient, WebEditorClient, WebEditorHost, WindowMessageTransport, applyContentEdits, applyTextEdits, contentEditsOt, createWindowParentConnection, decodeFromEditor, diffContent, diffText, encodeForEditor, mapContentOffset, mapThrough, textOperationOt, transformContentEdits, vscodeAppEmbeddingEventsInterface, vscodeAppHostInterface, webEditorClientTransportInterface, webEditorHostInterface, webEditorHostTransportInterface, webEditorInterface, webEditorPresentationHostInterface, webEditorPresentationInterface };
5252
6127
 
5253
6128
  //# sourceMappingURL=index.js.map