@vscode/web-editors 0.0.2-15 → 0.0.2-151

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
@@ -2,6 +2,7 @@
2
2
  * Copyright (c) Microsoft Corporation. All rights reserved.
3
3
  * Licensed under the MIT License. See License.txt in the project root for license information.
4
4
  *--------------------------------------------------------------------------------------------*/
5
+ import { t as Emitter } from "./chunks/event-BrSLCUGr.js";
5
6
  import { HubRpcConnection, JsonRpcChannel, defineInterface, notificationType, requestType } from "@vscode/hubrpc";
6
7
  import { WindowMessageTransport, WindowMessageTransport as WindowMessageTransport$1 } from "@vscode/hubrpc/web";
7
8
  import { createManagedSigningChannel, findCoveringCapabilities, hubAccessInterface } from "@vscode/hubrpc/hub/common";
@@ -152,7 +153,7 @@ const allowsEval = /* @__PURE__*/ cached(() => {
152
153
  return false;
153
154
  }
154
155
  });
155
- function isPlainObject(o) {
156
+ function isPlainObject$1(o) {
156
157
  if (isObject(o) === false) return false;
157
158
  const ctor = o.constructor;
158
159
  if (ctor === void 0) return true;
@@ -163,7 +164,7 @@ function isPlainObject(o) {
163
164
  return true;
164
165
  }
165
166
  function shallowClone(o) {
166
- if (isPlainObject(o)) return { ...o };
167
+ if (isPlainObject$1(o)) return { ...o };
167
168
  if (Array.isArray(o)) return [...o];
168
169
  if (o instanceof Map) return new Map(o);
169
170
  if (o instanceof Set) return new Set(o);
@@ -246,7 +247,7 @@ function omit(schema, mask) {
246
247
  }));
247
248
  }
248
249
  function extend(schema, shape) {
249
- if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
250
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
250
251
  const checks = schema._zod.def.checks;
251
252
  if (checks && checks.length > 0) {
252
253
  const existingShape = schema._zod.def.shape;
@@ -262,7 +263,7 @@ function extend(schema, shape) {
262
263
  } }));
263
264
  }
264
265
  function safeExtend(schema, shape) {
265
- if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
266
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
266
267
  return clone(schema, mergeDefs(schema._zod.def, { get shape() {
267
268
  const _shape = {
268
269
  ...schema._zod.def.shape,
@@ -1853,7 +1854,7 @@ function mergeValues(a, b) {
1853
1854
  valid: true,
1854
1855
  data: a
1855
1856
  };
1856
- if (isPlainObject(a) && isPlainObject(b)) {
1857
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
1857
1858
  const bKeys = Object.keys(b);
1858
1859
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1859
1860
  const newObj = {
@@ -4118,14 +4119,33 @@ function superRefine(fn, params) {
4118
4119
  //#endregion
4119
4120
  //#region src/protocol.ts
4120
4121
  const zJsonValue = unknown();
4122
+ /**
4123
+ * The concurrency control both sides use when they announce it: concurrent
4124
+ * edits are transformed against each other instead of one side's being
4125
+ * dropped. See `OtPeer`.
4126
+ */
4127
+ const OT_EDIT_TRANSFORM = "ot/1";
4121
4128
  const zEditorCapabilities = object({
4122
4129
  supportsContentEdits: boolean().optional(),
4123
- supportsOptions: boolean().optional()
4130
+ supportsOptions: boolean().optional(),
4131
+ /** The editor implements `web-editor-presentation` (see {@link webEditorPresentationInterface}). */
4132
+ supportsPresentation: boolean().optional(),
4133
+ /**
4134
+ * Concurrency controls the editor implements, such as {@link OT_EDIT_TRANSFORM}.
4135
+ * Without one the host uses the client-authority policy, where
4136
+ * conflicting edits are dropped.
4137
+ */
4138
+ editTransforms: array(string()).optional()
4124
4139
  });
4125
4140
  const zHostCapabilities = object({
4126
4141
  supportsContentEdits: boolean().optional(),
4127
4142
  supportsOptions: boolean().optional(),
4128
- supportsForceUpdate: boolean().optional()
4143
+ supportsForceUpdate: boolean().optional(),
4144
+ supportsHostTransport: boolean().optional(),
4145
+ /** The host presents the editor inline and implements `web-editor-presentation-host`. */
4146
+ supportsPresentation: boolean().optional(),
4147
+ /** The concurrency control the host chose from the editor's `editTransforms`. */
4148
+ editTransform: string().optional()
4129
4149
  });
4130
4150
  const zTextEdit = object({
4131
4151
  offset: number().int().nonnegative(),
@@ -4147,18 +4167,56 @@ const zWebEditorUpdate = object({
4147
4167
  readOnly: boolean().optional(),
4148
4168
  serverRevision: number().int().nonnegative().optional(),
4149
4169
  acknowledgedClientRevision: number().int().nonnegative().optional(),
4150
- force: boolean().optional()
4170
+ force: boolean().optional(),
4171
+ /**
4172
+ * Sent with every `content` once the host chose a concurrency control, so
4173
+ * the editor knows it before `initialized` returns.
4174
+ */
4175
+ editTransform: string().optional()
4151
4176
  });
4177
+ /** How an embedding host currently presents the editor. */
4178
+ const zPresentationMode = _enum([
4179
+ "inline",
4180
+ "full-width",
4181
+ "full-view"
4182
+ ]);
4183
+ const zEditorHeight = number().positive().max(1e4);
4184
+ /**
4185
+ * Presentation controls the editor asks its embedding host for. The host's own
4186
+ * configuration takes precedence over these preferences.
4187
+ */
4188
+ const zPresentationPreferences = object({
4189
+ /** A height grip; dragging near the automatic (content) height snaps back to it. */
4190
+ resizable: boolean().optional(),
4191
+ /** A width grip that widens the editor up to the host's viewport. */
4192
+ fullWidth: boolean().optional(),
4193
+ /** A toolbar action that fills the host's viewport. */
4194
+ fullView: boolean().optional(),
4195
+ minHeight: zEditorHeight.optional(),
4196
+ /** Upper bound for the automatic height; users can still resize beyond it. */
4197
+ maxAutomaticHeight: zEditorHeight.optional()
4198
+ });
4199
+ const zContentType = _enum(["text", "json"]);
4152
4200
  const webEditorHostInterface = defineInterface({
4153
4201
  id: "web-editor-host",
4154
4202
  description: "Methods the host exposes to the editor (web-editor/0.12)."
4155
4203
  }, {
4204
+ /**
4205
+ * The editor's first message. The host picks the content type from
4206
+ * `contentTypes` (or `contentType`, from editors that do not send it)
4207
+ * and returns it; it fails the request if it can serve none of them.
4208
+ */
4156
4209
  initialized: requestType(object({
4157
4210
  protocolVersion: literal("web-editor/0.12"),
4158
- contentType: _enum(["text", "json"]),
4211
+ /** The editor's preferred content type. Hosts that predate `contentTypes` serve only this one. */
4212
+ contentType: zContentType,
4213
+ /** The content types the editor accepts, most preferred first. */
4214
+ contentTypes: array(zContentType).optional(),
4159
4215
  capabilities: zEditorCapabilities.optional()
4160
4216
  }), object({
4161
4217
  protocolVersion: literal("web-editor-host/0.12"),
4218
+ /** The content type the host serves. Hosts that predate it serve the request's `contentType`. */
4219
+ contentType: zContentType.optional(),
4162
4220
  capabilities: zHostCapabilities.optional()
4163
4221
  })),
4164
4222
  applyContentEdit: notificationType(object({
@@ -4167,9 +4225,18 @@ const webEditorHostInterface = defineInterface({
4167
4225
  basedOnServerRevision: number().int().nonnegative()
4168
4226
  })),
4169
4227
  /**
4170
- * The editor reports its laid-out content height (px). An embedding host
4171
- * that reserves block space (e.g. an iframe with no intrinsic height)
4172
- * uses this to size the frame once the guest has measured itself.
4228
+ * With an `editTransform`: the editor has integrated the host's edits up
4229
+ * to `serverRevision`. Lets the host forget them while the editor does
4230
+ * not edit; an `applyContentEdit` acknowledges them as well.
4231
+ */
4232
+ acknowledge: notificationType(object({ serverRevision: number().int().nonnegative() })),
4233
+ /**
4234
+ * The editor reports its preferred content height (px): the height it needs
4235
+ * to show its content without scrolling, independent of the frame's current
4236
+ * height. Measure the content, not the viewport or document, which follow
4237
+ * the frame. An embedding host that reserves block space (e.g. an iframe
4238
+ * with no intrinsic height) sizes the frame to it and uses it as the
4239
+ * automatic height that user resizing snaps back to.
4173
4240
  */
4174
4241
  reportSize: notificationType(object({ height: number().nonnegative() }))
4175
4242
  });
@@ -4185,6 +4252,31 @@ const webEditorInterface = defineInterface({
4185
4252
  })),
4186
4253
  getContentSchema: requestType(object({}), object({ schema: zJsonValue }))
4187
4254
  });
4255
+ const webEditorHostTransportInterface = defineInterface({
4256
+ id: "web-editor-host-transport",
4257
+ description: "Optional messages the web editor sends to its host."
4258
+ }, { message: notificationType(object({ message: zJsonValue })) });
4259
+ const webEditorClientTransportInterface = defineInterface({
4260
+ id: "web-editor-client-transport",
4261
+ description: "Optional messages the web editor host sends to the editor."
4262
+ }, { message: notificationType(object({ message: zJsonValue })) });
4263
+ /** Methods the editor exposes to a presenting host. */
4264
+ const webEditorPresentationInterface = defineInterface({
4265
+ id: "web-editor-presentation",
4266
+ description: "How the embedding host currently presents the editor."
4267
+ }, {
4268
+ /** Sent once the editor initialized, and whenever the mode changes. */
4269
+ changed: notificationType(object({ mode: zPresentationMode })) });
4270
+ /** Methods a presenting host exposes to the editor. */
4271
+ const webEditorPresentationHostInterface = defineInterface({
4272
+ id: "web-editor-presentation-host",
4273
+ description: "Presentation preferences and actions of an embedded editor."
4274
+ }, {
4275
+ /** Replaces the editor's previous preferences. */
4276
+ setPreferences: notificationType(zPresentationPreferences),
4277
+ /** Asks the host to leave full view, for example when the user presses Escape. */
4278
+ exitFullView: notificationType(object({}))
4279
+ });
4188
4280
  /** Per-scope registration: `registered` (toolbar button) and `isDefault` (auto-open). */
4189
4281
  const zScopeRegistration = object({
4190
4282
  registered: boolean(),
@@ -4202,7 +4294,12 @@ const vscodeAppHostInterface = defineInterface({
4202
4294
  description: "Methods an app `.vscode-app.html` exposes to the host (vscode-app-host/0.1)."
4203
4295
  }, {
4204
4296
  getContext: requestType(object({}), object({
4205
- dataDocument: object({ contentType: _enum(["text", "json"]) }).nullable(),
4297
+ /**
4298
+ * The document the app edits, or `null` when the app was opened
4299
+ * directly. `contentType` is the host's preference; the type the
4300
+ * host serves is agreed in `web-editor-host::initialized`.
4301
+ */
4302
+ dataDocument: object({ contentType: zContentType }).nullable(),
4206
4303
  embedding: zEmbeddingContext.nullable()
4207
4304
  })),
4208
4305
  /**
@@ -4260,7 +4357,21 @@ const vscodeAppHostInterface = defineInterface({
4260
4357
  workspace: zScopeRegistration,
4261
4358
  hasWorkspace: boolean(),
4262
4359
  changed: boolean()
4263
- }))
4360
+ })),
4361
+ /**
4362
+ * The view state of this editor tab, such as scroll positions or
4363
+ * selections, as last set by {@link setViewState}. `value` is omitted
4364
+ * when none is set. VS Code restores it when it restores the tab (for
4365
+ * example after a window reload), but a newly opened tab starts
4366
+ * without one. Only the top-level app of a tab has view state.
4367
+ */
4368
+ getViewState: requestType(object({}), object({ value: zJsonValue.optional() })),
4369
+ /**
4370
+ * Replace this editor tab's view state with a JSON value. The host
4371
+ * rejects values too large to persist with the tab, and calls from
4372
+ * embedded apps.
4373
+ */
4374
+ setViewState: requestType(object({ value: zJsonValue }), object({}))
4264
4375
  });
4265
4376
  /** Host-to-parent notifications for loaded child runtime changes. */
4266
4377
  const vscodeAppEmbeddingEventsInterface = defineInterface({
@@ -4283,7 +4394,7 @@ const vscodeAppEmbeddingEventsInterface = defineInterface({
4283
4394
  */
4284
4395
  function applyContentEdits(root, edits) {
4285
4396
  let current = root;
4286
- for (const edit of edits) if (edit.kind === "replace") current = setAtPath(current, edit.path, edit.newValue);
4397
+ for (const edit of edits) if (edit.kind === "replace") current = setAtPath(current, edit.path, cloneJson(edit.newValue));
4287
4398
  else {
4288
4399
  const existing = getAtPath(current, edit.path);
4289
4400
  if (typeof existing !== "string") throw new Error(`applyContentEdits: stringEdits at path [${edit.path.join(", ")}] requires a string, got ${typeof existing}`);
@@ -4297,6 +4408,9 @@ function applyTextEdits(text, edits) {
4297
4408
  for (const e of edits) result = result.slice(0, e.offset) + e.newText + result.slice(e.offset + e.length);
4298
4409
  return result;
4299
4410
  }
4411
+ function cloneJson(value) {
4412
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
4413
+ }
4300
4414
  function getAtPath(root, path) {
4301
4415
  let cur = root;
4302
4416
  for (const key of path) {
@@ -4352,76 +4466,667 @@ function decodeFromEditor(value, contentType, options = {}) {
4352
4466
  return JSON.stringify(value, void 0, indentation);
4353
4467
  }
4354
4468
  //#endregion
4355
- //#region src/utils/event.ts
4356
- var Emitter = class {
4357
- _listeners = /* @__PURE__ */ new Set();
4358
- event = (listener) => {
4359
- this._listeners.add(listener);
4360
- return { dispose: () => this._listeners.delete(listener) };
4361
- };
4362
- fire(value) {
4363
- for (const listener of this._listeners) try {
4364
- listener(value);
4365
- } catch (e) {
4366
- console.error("Emitter listener threw:", e);
4469
+ //#region src/sync/otPeer.ts
4470
+ /**
4471
+ * One of the two sides of a session that keeps a document in sync between
4472
+ * two parties who both edit it (the Jupiter algorithm behind most operational
4473
+ * transformation systems).
4474
+ *
4475
+ * Each side applies its own operations immediately and sends them along with
4476
+ * how many of the other side's operations it had applied. When an operation
4477
+ * from the other side arrives, it was made without the local operations the
4478
+ * other side had not seen yet. Those pending operations and the incoming one
4479
+ * are transformed against each other: the incoming one is then applied, and
4480
+ * the pending ones now describe how the local state differs from the other
4481
+ * side's. Once both sides have received everything, they hold the same
4482
+ * document, and no operation was dropped.
4483
+ *
4484
+ * The leader's operations take precedence in conflicts. Exactly one side must
4485
+ * be the leader. Messages must arrive in the order they were sent.
4486
+ *
4487
+ * The leader can also start over from a state it sends in full ({@link reset});
4488
+ * the follower's operations that were made before it received that state are
4489
+ * then discarded on both sides.
4490
+ */
4491
+ var OtPeer = class {
4492
+ _type;
4493
+ role;
4494
+ _localRevision = 0;
4495
+ _remoteRevision = 0;
4496
+ _pending = [];
4497
+ /** Remote operations made before the remote side saw this local revision are discarded. */
4498
+ _barrier = 0;
4499
+ constructor(_type, role) {
4500
+ this._type = _type;
4501
+ this.role = role;
4502
+ }
4503
+ /** Number of local operations, including resets. */
4504
+ get localRevision() {
4505
+ return this._localRevision;
4506
+ }
4507
+ /** Number of remote operations integrated, including discarded ones. */
4508
+ get remoteRevision() {
4509
+ return this._remoteRevision;
4510
+ }
4511
+ /** Local operations the remote side has not acknowledged yet, oldest first. */
4512
+ get pending() {
4513
+ return this._pending.map((p) => p.op);
4514
+ }
4515
+ /**
4516
+ * The local operations after `revision`, oldest first: how the local state
4517
+ * differs from the state the remote side had when it had integrated
4518
+ * `revision` and everything local before. `undefined` if they are no
4519
+ * longer known, because they were acknowledged since or a reset happened.
4520
+ */
4521
+ operationsAfter(revision) {
4522
+ if (revision < this._barrier || revision > this._localRevision) return;
4523
+ const firstPending = this._pending[0]?.revision ?? this._localRevision + 1;
4524
+ return revision + 1 < firstPending ? void 0 : this._pending.slice(revision + 1 - firstPending).map((p) => p.op);
4525
+ }
4526
+ /**
4527
+ * Records an operation already applied to the local state. Send it with
4528
+ * the returned revision and {@link remoteRevision} as the acknowledgement.
4529
+ */
4530
+ local(op) {
4531
+ const revision = ++this._localRevision;
4532
+ this._pending.push({
4533
+ revision,
4534
+ op
4535
+ });
4536
+ return revision;
4537
+ }
4538
+ /**
4539
+ * Integrates an operation from the remote side.
4540
+ *
4541
+ * @param revision The remote side's revision after `op`.
4542
+ * @param acknowledgedRevision How many local operations the remote side had integrated when it made `op`.
4543
+ * @returns The operation to apply to the local state, or `undefined` if
4544
+ * `op` was made before the remote side received the latest reset.
4545
+ */
4546
+ remote(op, revision, acknowledgedRevision) {
4547
+ if (revision !== this._remoteRevision + 1) throw new Error(`OtPeer: expected remote revision ${this._remoteRevision + 1}, got ${revision}`);
4548
+ if (acknowledgedRevision > this._localRevision) throw new Error(`OtPeer: remote acknowledged revision ${acknowledgedRevision}, but the latest local revision is ${this._localRevision}`);
4549
+ this._remoteRevision = revision;
4550
+ if (acknowledgedRevision < this._barrier) return;
4551
+ this.acknowledge(acknowledgedRevision);
4552
+ let incoming = op;
4553
+ this._pending = this._pending.map(({ revision, op: pending }) => {
4554
+ let pendingPrime;
4555
+ if (this.role === "leader") [pendingPrime, incoming] = this._type.transform(pending, incoming);
4556
+ else [incoming, pendingPrime] = this._type.transform(incoming, pending);
4557
+ return {
4558
+ revision,
4559
+ op: pendingPrime
4560
+ };
4561
+ });
4562
+ return incoming;
4563
+ }
4564
+ /** The remote side has integrated all local operations up to `revision`. */
4565
+ acknowledge(revision) {
4566
+ if (revision > this._localRevision) throw new Error(`OtPeer: remote acknowledged revision ${revision}, but the latest local revision is ${this._localRevision}`);
4567
+ let i = 0;
4568
+ while (i < this._pending.length && this._pending[i].revision <= revision) i++;
4569
+ if (i > 0) this._pending = this._pending.slice(i);
4570
+ }
4571
+ /**
4572
+ * Leader only: the local state is about to be sent in full and replaces
4573
+ * whatever the follower has. Returns the revision of the reset.
4574
+ *
4575
+ * @param remoteRevision Treat remote operations up to this revision as
4576
+ * integrated, to recover when the remote side's revisions got out of step.
4577
+ */
4578
+ reset(remoteRevision = this._remoteRevision) {
4579
+ if (this.role !== "leader") throw new Error("OtPeer.reset: only the leader can reset");
4580
+ this._remoteRevision = Math.max(this._remoteRevision, remoteRevision);
4581
+ this._pending = [];
4582
+ this._barrier = ++this._localRevision;
4583
+ return this._localRevision;
4584
+ }
4585
+ /**
4586
+ * Follower only: replaces the local state with the leader's full state at
4587
+ * `revision`. Pending local operations are discarded, as the leader
4588
+ * discards them too.
4589
+ */
4590
+ acceptReset(revision) {
4591
+ if (this.role !== "follower") throw new Error("OtPeer.acceptReset: only the follower accepts resets");
4592
+ if (revision !== this._remoteRevision + 1) throw new Error(`OtPeer: expected remote revision ${this._remoteRevision + 1}, got ${revision}`);
4593
+ this._remoteRevision = revision;
4594
+ this._pending = [];
4595
+ }
4596
+ };
4597
+ //#endregion
4598
+ //#region src/sync/textOperation.ts
4599
+ /** {@link OtType} for {@link TextOperation}s. */
4600
+ const textOperationOt = { transform: (winner, loser) => TextOperation.transform(winner, loser) };
4601
+ /**
4602
+ * A change to a string, as a sequence of components that walk the original
4603
+ * string from start to end: keep (`retain`), add (`insert`) or remove
4604
+ * (`delete`) text. Everything after the last component is kept.
4605
+ *
4606
+ * Operations are normalized (see {@link TextOperationBuilder}), so equal
4607
+ * changes have equal components. Their size depends on the number of edited
4608
+ * regions, not on the length of the string.
4609
+ */
4610
+ var TextOperation = class TextOperation {
4611
+ components;
4612
+ static get identity() {
4613
+ return identityOperation;
4614
+ }
4615
+ /** Converts edits that apply one after another, as on the wire, into one operation. */
4616
+ static fromTextEdits(edits) {
4617
+ let result = TextOperation.identity;
4618
+ for (const edit of edits) result = result.compose(new TextOperationBuilder().retain(edit.offset).insert(edit.newText).delete(edit.length).build());
4619
+ return result;
4620
+ }
4621
+ /** Use {@link TextOperationBuilder}, which normalizes the components. */
4622
+ constructor(token, components) {
4623
+ this.components = components;
4624
+ if (token !== normalizedToken) throw new Error("TextOperation: use TextOperationBuilder");
4625
+ }
4626
+ get isIdentity() {
4627
+ return this.components.length === 0;
4628
+ }
4629
+ /** Length of the shortest string this operation applies to. */
4630
+ get baseSpan() {
4631
+ let span = 0;
4632
+ for (const c of this.components) if (c.kind !== "insert") span += c.length;
4633
+ return span;
4634
+ }
4635
+ apply(text) {
4636
+ if (this.baseSpan > text.length) throw new Error(`TextOperation spans ${this.baseSpan} characters, but the text has ${text.length}`);
4637
+ const parts = [];
4638
+ let offset = 0;
4639
+ for (const c of this.components) if (c.kind === "retain") {
4640
+ parts.push(text.slice(offset, offset + c.length));
4641
+ offset += c.length;
4642
+ } else if (c.kind === "insert") parts.push(c.text);
4643
+ else offset += c.length;
4644
+ parts.push(text.slice(offset));
4645
+ return parts.join("");
4646
+ }
4647
+ /** Edits in ascending order that, applied one after another, have the effect of this operation. */
4648
+ toTextEdits() {
4649
+ const edits = [];
4650
+ let offset = 0;
4651
+ let pending;
4652
+ const flush = () => {
4653
+ if (pending) {
4654
+ edits.push(pending);
4655
+ offset += pending.newText.length;
4656
+ pending = void 0;
4657
+ }
4658
+ };
4659
+ for (const c of this.components) if (c.kind === "retain") {
4660
+ flush();
4661
+ offset += c.length;
4662
+ } else {
4663
+ pending ??= {
4664
+ offset,
4665
+ length: 0,
4666
+ newText: ""
4667
+ };
4668
+ if (c.kind === "insert") pending.newText += c.text;
4669
+ else pending.length += c.length;
4367
4670
  }
4671
+ flush();
4672
+ return edits;
4368
4673
  }
4369
- dispose() {
4370
- this._listeners.clear();
4674
+ /** The operation that has the effect of this operation followed by `next`. */
4675
+ compose(next) {
4676
+ const builder = new TextOperationBuilder();
4677
+ const first = new ComponentCursor(this.components);
4678
+ const second = new ComponentCursor(next.components);
4679
+ while (!first.done || !second.done) {
4680
+ const a = first.peek();
4681
+ const b = second.peek();
4682
+ if (a.kind === "delete") builder.delete(first.take(a.length));
4683
+ else if (b.kind === "insert") builder.insert(second.takeText());
4684
+ else {
4685
+ const length = Math.min(a.length, b.length);
4686
+ if (a.kind === "retain") if (b.kind === "retain") builder.retain(length);
4687
+ else builder.delete(length);
4688
+ else if (b.kind === "retain") builder.insert(a.text.slice(0, length));
4689
+ first.take(length);
4690
+ second.take(length);
4691
+ }
4692
+ }
4693
+ return builder.build();
4694
+ }
4695
+ /**
4696
+ * Transforms two operations on the same string so that each applies after
4697
+ * the other and both orders give the same result (`b'(a(s)) === a'(b(s))`).
4698
+ * Where both insert at the same position, `winner`'s text comes first.
4699
+ *
4700
+ * @returns `[winner', loser']`: `winner'` applies after `loser`, `loser'` after `winner`.
4701
+ */
4702
+ static transform(winner, loser) {
4703
+ const winnerPrime = new TextOperationBuilder();
4704
+ const loserPrime = new TextOperationBuilder();
4705
+ const w = new ComponentCursor(winner.components);
4706
+ const l = new ComponentCursor(loser.components);
4707
+ while (!w.done || !l.done) {
4708
+ const a = w.peek();
4709
+ const b = l.peek();
4710
+ if (a.kind === "insert") {
4711
+ const text = w.takeText();
4712
+ winnerPrime.insert(text);
4713
+ loserPrime.retain(text.length);
4714
+ } else if (b.kind === "insert") {
4715
+ const text = l.takeText();
4716
+ winnerPrime.retain(text.length);
4717
+ loserPrime.insert(text);
4718
+ } else {
4719
+ const length = Math.min(a.length, b.length);
4720
+ if (a.kind === "retain" && b.kind === "retain") {
4721
+ winnerPrime.retain(length);
4722
+ loserPrime.retain(length);
4723
+ } else if (a.kind === "delete" && b.kind === "retain") winnerPrime.delete(length);
4724
+ else if (a.kind === "retain" && b.kind === "delete") loserPrime.delete(length);
4725
+ w.take(length);
4726
+ l.take(length);
4727
+ }
4728
+ }
4729
+ return [winnerPrime.build(), loserPrime.build()];
4730
+ }
4731
+ /**
4732
+ * Where `offset` in the original string ends up after this operation.
4733
+ * An offset inside deleted text maps to where the deletion happened. Text
4734
+ * inserted exactly at `offset` ends up before the result for
4735
+ * `assoc === "after"` and after it for `assoc === "before"`.
4736
+ */
4737
+ mapOffset(offset, assoc = "after") {
4738
+ let original = 0;
4739
+ let mapped = 0;
4740
+ for (const c of this.components) {
4741
+ if (c.kind === "insert") {
4742
+ if (original < offset || original === offset && assoc === "after") mapped += c.text.length;
4743
+ continue;
4744
+ }
4745
+ if (original >= offset) break;
4746
+ const length = Math.min(c.length, offset - original);
4747
+ original += length;
4748
+ if (c.kind === "retain") mapped += length;
4749
+ if (length < c.length) break;
4750
+ }
4751
+ return mapped + offset - original;
4752
+ }
4753
+ equals(other) {
4754
+ return this.components.length === other.components.length && this.components.every((c, i) => componentsEqual(c, other.components[i]));
4755
+ }
4756
+ toString() {
4757
+ return this.components.map((c) => c.kind === "insert" ? JSON.stringify(c.text) : c.kind === "retain" ? `${c.length}` : `-${c.length}`).join(" ");
4758
+ }
4759
+ };
4760
+ const normalizedToken = Symbol("TextOperation.normalized");
4761
+ /**
4762
+ * Builds normalized {@link TextOperation}s: no empty components, adjacent
4763
+ * components of the same kind merged, an insert before a delete at the same
4764
+ * position, and no trailing retain.
4765
+ */
4766
+ var TextOperationBuilder = class {
4767
+ _components = [];
4768
+ retain(length) {
4769
+ assertLength(length);
4770
+ if (length === 0) return this;
4771
+ const last = this._components.at(-1);
4772
+ if (last?.kind === "retain") this._components[this._components.length - 1] = {
4773
+ kind: "retain",
4774
+ length: last.length + length
4775
+ };
4776
+ else this._components.push({
4777
+ kind: "retain",
4778
+ length
4779
+ });
4780
+ return this;
4781
+ }
4782
+ insert(text) {
4783
+ if (text === "") return this;
4784
+ const last = this._components.at(-1);
4785
+ if (last?.kind === "insert") this._components[this._components.length - 1] = {
4786
+ kind: "insert",
4787
+ text: last.text + text
4788
+ };
4789
+ else if (last?.kind === "delete") {
4790
+ const beforeDelete = this._components.at(-2);
4791
+ if (beforeDelete?.kind === "insert") this._components[this._components.length - 2] = {
4792
+ kind: "insert",
4793
+ text: beforeDelete.text + text
4794
+ };
4795
+ else this._components.splice(this._components.length - 1, 0, {
4796
+ kind: "insert",
4797
+ text
4798
+ });
4799
+ } else this._components.push({
4800
+ kind: "insert",
4801
+ text
4802
+ });
4803
+ return this;
4804
+ }
4805
+ delete(length) {
4806
+ assertLength(length);
4807
+ if (length === 0) return this;
4808
+ const last = this._components.at(-1);
4809
+ if (last?.kind === "delete") this._components[this._components.length - 1] = {
4810
+ kind: "delete",
4811
+ length: last.length + length
4812
+ };
4813
+ else this._components.push({
4814
+ kind: "delete",
4815
+ length
4816
+ });
4817
+ return this;
4818
+ }
4819
+ build() {
4820
+ const components = this._components.at(-1)?.kind === "retain" ? this._components.slice(0, -1) : [...this._components];
4821
+ return new TextOperation(normalizedToken, components);
4371
4822
  }
4372
4823
  };
4824
+ /** Walks components, splitting them as needed. Past the end it yields an endless retain. */
4825
+ var ComponentCursor = class {
4826
+ _components;
4827
+ _index = 0;
4828
+ _consumed = 0;
4829
+ constructor(_components) {
4830
+ this._components = _components;
4831
+ }
4832
+ get done() {
4833
+ return this._index >= this._components.length;
4834
+ }
4835
+ /** The rest of the current component. */
4836
+ peek() {
4837
+ const c = this._components[this._index];
4838
+ if (c === void 0) return {
4839
+ kind: "retain",
4840
+ length: Infinity
4841
+ };
4842
+ if (c.kind === "insert") {
4843
+ const text = c.text.slice(this._consumed);
4844
+ return {
4845
+ kind: "insert",
4846
+ text,
4847
+ length: text.length
4848
+ };
4849
+ }
4850
+ return {
4851
+ kind: c.kind,
4852
+ length: c.length - this._consumed
4853
+ };
4854
+ }
4855
+ /** Consumes up to `length` characters of the current component and returns how many it consumed. */
4856
+ take(length) {
4857
+ const c = this._components[this._index];
4858
+ if (c === void 0) return length;
4859
+ const available = (c.kind === "insert" ? c.text.length : c.length) - this._consumed;
4860
+ if (length >= available) {
4861
+ this._index++;
4862
+ this._consumed = 0;
4863
+ return available;
4864
+ }
4865
+ this._consumed += length;
4866
+ return length;
4867
+ }
4868
+ /** Consumes the rest of the current insert. */
4869
+ takeText() {
4870
+ const c = this._components[this._index];
4871
+ if (c?.kind !== "insert") throw new Error("ComponentCursor.takeText: not at an insert");
4872
+ const text = c.text.slice(this._consumed);
4873
+ this._index++;
4874
+ this._consumed = 0;
4875
+ return text;
4876
+ }
4877
+ };
4878
+ function componentsEqual(a, b) {
4879
+ if (a.kind === "insert" || b.kind === "insert") return a.kind === b.kind && a.text === b.text;
4880
+ return a.kind === b.kind && a.length === b.length;
4881
+ }
4882
+ function assertLength(length) {
4883
+ if (!Number.isInteger(length) || length < 0) throw new Error(`TextOperation: invalid length ${length}`);
4884
+ }
4885
+ const identityOperation = new TextOperationBuilder().build();
4886
+ //#endregion
4887
+ //#region src/sync/textDiff.ts
4888
+ /**
4889
+ * An operation that turns `oldText` into `newText` by replacing everything
4890
+ * between their common prefix and suffix. Linear time, so it stays fast for
4891
+ * large texts; separate changes become one replacement of the text between them.
4892
+ *
4893
+ * The replacement never starts or ends between `\r` and `\n`, so that text
4894
+ * inserted concurrently at its edges cannot split a `\r\n` line break.
4895
+ */
4896
+ function diffText(oldText, newText) {
4897
+ const shorter = Math.min(oldText.length, newText.length);
4898
+ let start = 0;
4899
+ while (start < shorter && oldText.charCodeAt(start) === newText.charCodeAt(start)) start++;
4900
+ if (start > 0 && oldText.charCodeAt(start - 1) === CR && (oldText.charCodeAt(start) === LF || newText.charCodeAt(start) === LF)) 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
+ if (oldEnd < oldText.length && oldText.charCodeAt(oldEnd) === LF && (oldText.charCodeAt(oldEnd - 1) === CR || newText.charCodeAt(newEnd - 1) === CR)) {
4908
+ oldEnd++;
4909
+ newEnd++;
4910
+ }
4911
+ return new TextOperationBuilder().retain(start).insert(newText.slice(start, newEnd)).delete(oldEnd - start).build();
4912
+ }
4913
+ const CR = 13;
4914
+ const LF = 10;
4915
+ //#endregion
4916
+ //#region src/sync/contentOperation.ts
4917
+ /** {@link OtType} for lists of {@link ContentEdit}s, as exchanged by web editors. */
4918
+ const contentEditsOt = { transform: (winner, loser) => transformContentEdits(winner, loser) };
4919
+ /**
4920
+ * Transforms two concurrent lists of {@link ContentEdit}s made on the same
4921
+ * content, so that each list applies after the other and both orders give the
4922
+ * same content.
4923
+ *
4924
+ * Edits at unrelated paths do not interact. String edits at the same path are
4925
+ * merged with {@link TextOperation.transform}. A `replace` overrides every
4926
+ * concurrent edit at or below its path; of two replacements at the same path,
4927
+ * `winner`'s is kept.
4928
+ *
4929
+ * @returns `[winner', loser']`: `winner'` applies after `loser`, `loser'` after `winner`.
4930
+ */
4931
+ function transformContentEdits(winner, loser) {
4932
+ const winnerPrime = [];
4933
+ let loserPrime = [...loser];
4934
+ for (const edit of winner) {
4935
+ let current = edit;
4936
+ const nextLoser = [];
4937
+ for (const other of loserPrime) {
4938
+ if (current === void 0) {
4939
+ nextLoser.push(other);
4940
+ continue;
4941
+ }
4942
+ const [w, l] = transformContentEdit(current, other);
4943
+ current = w;
4944
+ if (l !== void 0) nextLoser.push(l);
4945
+ }
4946
+ loserPrime = nextLoser;
4947
+ if (current !== void 0) winnerPrime.push(current);
4948
+ }
4949
+ return [winnerPrime, loserPrime];
4950
+ }
4951
+ /** `undefined` stands for an edit that has no effect anymore. */
4952
+ function transformContentEdit(winner, loser) {
4953
+ const relation = relatePaths(winner.path, loser.path);
4954
+ if (relation === "unrelated") return [winner, loser];
4955
+ if (winner.kind === "replace" && loser.kind === "replace") return relation === "descendant" ? [void 0, loser] : [winner, void 0];
4956
+ if (winner.kind === "replace") return [winner, void 0];
4957
+ if (loser.kind === "replace") return [void 0, loser];
4958
+ if (relation !== "equal") return [winner, loser];
4959
+ const [w, l] = TextOperation.transform(TextOperation.fromTextEdits(winner.stringEdits), TextOperation.fromTextEdits(loser.stringEdits));
4960
+ return [toStringEdits(winner.path, w), toStringEdits(loser.path, l)];
4961
+ }
4962
+ /** How path `a` relates to path `b`: `"ancestor"` means `a` is a proper prefix of `b`. */
4963
+ function relatePaths(a, b) {
4964
+ const length = Math.min(a.length, b.length);
4965
+ for (let i = 0; i < length; i++) if (a[i] !== b[i]) return "unrelated";
4966
+ return a.length === b.length ? "equal" : a.length < b.length ? "ancestor" : "descendant";
4967
+ }
4968
+ function toStringEdits(path, operation) {
4969
+ return operation.isIdentity ? void 0 : {
4970
+ kind: "stringEdits",
4971
+ path,
4972
+ stringEdits: operation.toTextEdits()
4973
+ };
4974
+ }
4975
+ /**
4976
+ * Where `offset` in the string at `path` ends up after `edits`, or `undefined`
4977
+ * if the string was replaced. See {@link TextOperation.mapOffset} for `assoc`.
4978
+ */
4979
+ function mapContentOffset(edits, path, offset, assoc = "after") {
4980
+ let result = offset;
4981
+ for (const edit of edits) {
4982
+ const relation = relatePaths(edit.path, path);
4983
+ if (relation === "unrelated" || relation === "descendant") continue;
4984
+ if (edit.kind === "replace") return;
4985
+ if (relation === "equal") result = TextOperation.fromTextEdits(edit.stringEdits).mapOffset(result, assoc);
4986
+ }
4987
+ return result;
4988
+ }
4989
+ /** Maps `offset` through each list of edits in turn; `undefined` if `operations` is `undefined` or the offset does not survive an edit. */
4990
+ function mapThrough(operations, path, offset, assoc) {
4991
+ if (!operations) return;
4992
+ let result = offset;
4993
+ for (const edits of operations) {
4994
+ result = mapContentOffset(edits, path, result, assoc);
4995
+ if (result === void 0) return;
4996
+ }
4997
+ return result;
4998
+ }
4999
+ /**
5000
+ * Edits that turn `oldValue` into `newValue`, as fine-grained as possible so
5001
+ * that they merge with concurrent edits: changed strings become string edits,
5002
+ * objects with the same keys and arrays with the same length are compared
5003
+ * member by member, and anything else is replaced.
5004
+ */
5005
+ function diffContent(oldValue, newValue, path = []) {
5006
+ if (typeof oldValue === "string" && typeof newValue === "string") {
5007
+ const operation = diffText(oldValue, newValue);
5008
+ return operation.isIdentity ? [] : [{
5009
+ kind: "stringEdits",
5010
+ path,
5011
+ stringEdits: operation.toTextEdits()
5012
+ }];
5013
+ }
5014
+ if (Array.isArray(oldValue) && Array.isArray(newValue) && oldValue.length === newValue.length) return oldValue.flatMap((item, i) => diffContent(item, newValue[i], [...path, String(i)]));
5015
+ if (isPlainObject(oldValue) && isPlainObject(newValue) && haveSameKeys(oldValue, newValue)) return Object.keys(oldValue).flatMap((key) => diffContent(oldValue[key], newValue[key], [...path, key]));
5016
+ return oldValue === newValue ? [] : [{
5017
+ kind: "replace",
5018
+ path,
5019
+ newValue
5020
+ }];
5021
+ }
5022
+ function isPlainObject(value) {
5023
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5024
+ }
5025
+ function haveSameKeys(a, b) {
5026
+ const keys = Object.keys(a);
5027
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key));
5028
+ }
4373
5029
  //#endregion
4374
5030
  //#region src/host/WebEditorHost.ts
4375
5031
  /**
4376
5032
  * Host-side façade for the web-editor v0.12 protocol.
4377
5033
  *
4378
5034
  * Owns the canonical text content. Translates between text/JSON form and the
4379
- * structural edits exchanged with the editor. Maintains the revision pair
4380
- * required by the client-authority conflict policy.
5035
+ * structural edits exchanged with the editor.
5036
+ *
5037
+ * Concurrent edits from both sides are merged with operational transformation
5038
+ * when the editor supports it ({@link OT_EDIT_TRANSFORM}). Otherwise the host
5039
+ * maintains the revision pair required by the client-authority conflict
5040
+ * policy, under which conflicting edits are dropped.
4381
5041
  */
4382
5042
  var WebEditorHost = class {
4383
5043
  _connection;
4384
5044
  _editor;
5045
+ _clientTransport;
5046
+ _presentation;
5047
+ _contentTypes;
5048
+ /** The type agreed with the editor; the host's preference until then. */
4385
5049
  _contentType;
4386
5050
  _jsonFormat;
4387
5051
  _onError;
4388
5052
  _capabilities;
5053
+ _hostTransportSubscription;
4389
5054
  _text;
4390
5055
  _readOnly;
5056
+ _presentationMode;
5057
+ /** Set while connected to an editor that merges concurrent edits. */
5058
+ _transform;
5059
+ /** Client-authority policy only. */
4391
5060
  _serverRevision = 0;
5061
+ /** Client-authority policy only. */
4392
5062
  _acknowledgedClientRevision = 0;
4393
5063
  _editorInitialized = false;
4394
5064
  _editorCapabilities;
5065
+ _pendingHostTransportMessages = [];
4395
5066
  _onDidChangeText = new Emitter();
5067
+ /** The editor changed the content. `edits` apply to the previous content, in the editor's form. */
4396
5068
  onDidChangeText = this._onDidChangeText.event;
4397
5069
  _onDidInitialize = new Emitter();
4398
5070
  onDidInitialize = this._onDidInitialize.event;
4399
5071
  _onDidReportSize = new Emitter();
4400
5072
  onDidReportSize = this._onDidReportSize.event;
5073
+ _onDidSetPresentationPreferences = new Emitter();
5074
+ /** The editor replaced its presentation preferences. Only fires with `supportsPresentation`. */
5075
+ onDidSetPresentationPreferences = this._onDidSetPresentationPreferences.event;
5076
+ _onDidRequestExitFullView = new Emitter();
5077
+ /** The editor asked to leave full view. Only fires with `supportsPresentation`. */
5078
+ onDidRequestExitFullView = this._onDidRequestExitFullView.event;
4401
5079
  constructor(options) {
4402
5080
  this._connection = options.connection;
4403
- this._contentType = options.contentType ?? "text";
5081
+ this._contentTypes = options.contentTypes ?? [options.contentType ?? "text"];
5082
+ if (this._contentTypes.length === 0) throw new Error("WebEditorHost: contentTypes must not be empty");
5083
+ this._contentType = this._contentTypes[0];
4404
5084
  this._text = options.initialText ?? "";
4405
5085
  this._readOnly = options.readOnly ?? false;
4406
5086
  this._jsonFormat = options.jsonFormat ?? {};
4407
5087
  this._onError = options.onError ?? ((m, d) => console.error("WebEditorHost:", m, d));
4408
- this._capabilities = options.capabilities ?? { supportsForceUpdate: true };
5088
+ this._capabilities = {
5089
+ ...options.capabilities ?? { supportsForceUpdate: true },
5090
+ supportsHostTransport: options.hostTransport ? true : void 0,
5091
+ supportsPresentation: options.supportsPresentation ? true : void 0
5092
+ };
4409
5093
  this._editor = this._connection.get(webEditorInterface);
5094
+ this._clientTransport = this._connection.get(webEditorClientTransportInterface);
5095
+ this._presentation = this._connection.get(webEditorPresentationInterface);
4410
5096
  this._connection.register(webEditorHostInterface, {
4411
5097
  initialized: (params) => {
4412
- if (params.contentType !== this._contentType) this._onError(`Editor contentType "${params.contentType}" does not match host "${this._contentType}"`);
5098
+ const accepted = params.contentTypes ?? [params.contentType];
5099
+ const contentType = accepted.find((type) => this._contentTypes.includes(type));
5100
+ if (contentType === void 0) {
5101
+ this._editorInitialized = false;
5102
+ const message = `The editor accepts ${accepted.join(", ")} content, but the host can only serve this document as ${this._contentTypes.join(", ")}.`;
5103
+ this._onError(message);
5104
+ throw new Error(message);
5105
+ }
5106
+ this._contentType = contentType;
4413
5107
  this._editorCapabilities = params.capabilities;
4414
5108
  this._editorInitialized = true;
4415
5109
  this._serverRevision = 0;
4416
5110
  this._acknowledgedClientRevision = 0;
5111
+ this._transform = params.capabilities?.editTransforms?.includes("ot/1") ? new OtPeer(contentEditsOt, "leader") : void 0;
4417
5112
  this._pushFullUpdate();
5113
+ for (const message of this._pendingHostTransportMessages.splice(0)) this._clientTransport.message({ message });
5114
+ this._pushPresentationMode();
4418
5115
  this._onDidInitialize.fire({ capabilities: params.capabilities });
4419
5116
  return {
4420
5117
  protocolVersion: "web-editor-host/0.12",
4421
- capabilities: this._capabilities
5118
+ contentType,
5119
+ capabilities: this._transform ? {
5120
+ ...this._capabilities,
5121
+ editTransform: OT_EDIT_TRANSFORM
5122
+ } : this._capabilities
4422
5123
  };
4423
5124
  },
4424
5125
  applyContentEdit: (params) => {
5126
+ if (this._transform) {
5127
+ this._applyTransformedEditorEdit(this._transform, params);
5128
+ return;
5129
+ }
4425
5130
  if (this._readOnly) {
4426
5131
  this._onError("Editor sent applyContentEdit while readOnly");
4427
5132
  this._acknowledgeAndRestore(params.clientRevision);
@@ -4432,46 +5137,95 @@ var WebEditorHost = class {
4432
5137
  this._acknowledgeAndRestore(params.clientRevision);
4433
5138
  return;
4434
5139
  }
4435
- let newValue;
4436
- try {
4437
- newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), params.edits);
4438
- } catch (e) {
4439
- this._onError("Failed to apply content edits from editor", e);
4440
- this._acknowledgeAndRestore(params.clientRevision);
4441
- return;
4442
- }
4443
- let newText;
4444
- try {
4445
- newText = decodeFromEditor(newValue, this._contentType, this._jsonFormat);
4446
- } catch (e) {
4447
- this._onError("Failed to decode editor content", e);
5140
+ const newText = this._applyEditorEdits(params.edits);
5141
+ if (newText === void 0) {
4448
5142
  this._acknowledgeAndRestore(params.clientRevision);
4449
5143
  return;
4450
5144
  }
4451
5145
  this._acknowledgedClientRevision = Math.max(this._acknowledgedClientRevision, params.clientRevision);
4452
5146
  if (newText !== this._text) {
4453
5147
  this._text = newText;
4454
- this._onDidChangeText.fire({ text: newText });
5148
+ this._onDidChangeText.fire({
5149
+ text: newText,
5150
+ edits: params.edits
5151
+ });
4455
5152
  }
4456
5153
  this._pushAcknowledgement();
4457
5154
  },
5155
+ acknowledge: (params) => {
5156
+ try {
5157
+ this._transform?.acknowledge(params.serverRevision);
5158
+ } catch (e) {
5159
+ this._onError("Editor acknowledged edits the host did not send", e);
5160
+ }
5161
+ },
4458
5162
  reportSize: (params) => {
4459
5163
  this._onDidReportSize.fire({ height: params.height });
4460
5164
  }
4461
5165
  });
5166
+ if (options.supportsPresentation) this._connection.register(webEditorPresentationHostInterface, {
5167
+ setPreferences: (preferences) => this._onDidSetPresentationPreferences.fire(preferences),
5168
+ exitFullView: () => this._onDidRequestExitFullView.fire()
5169
+ });
5170
+ if (options.hostTransport) {
5171
+ this._connection.register(webEditorHostTransportInterface, { message: ({ message }) => options.hostTransport.sendMessage(message) });
5172
+ this._hostTransportSubscription = options.hostTransport.onMessage((message) => {
5173
+ if (this._editorInitialized) this._clientTransport.message({ message });
5174
+ else this._pendingHostTransportMessages.push(message);
5175
+ });
5176
+ }
4462
5177
  }
4463
5178
  /** The text the host believes the document currently holds. */
4464
5179
  getText() {
4465
5180
  return this._text;
4466
5181
  }
4467
5182
  /**
4468
- * Push a new full text to the editor. Sent as a `replace` at the document
4469
- * root. If `force`, the editor must adopt it even with pending local edits.
5183
+ * The content type agreed with the editor, in which edits are exchanged.
5184
+ * `undefined` until the editor initialized.
5185
+ */
5186
+ get contentType() {
5187
+ return this._editorInitialized ? this._contentType : void 0;
5188
+ }
5189
+ /** The current content's version, to send along with offsets into it. */
5190
+ get version() {
5191
+ return this._transform ? {
5192
+ serverRevision: this._transform.localRevision,
5193
+ clientRevision: this._transform.remoteRevision
5194
+ } : {
5195
+ serverRevision: this._serverRevision,
5196
+ clientRevision: this._acknowledgedClientRevision
5197
+ };
5198
+ }
5199
+ /**
5200
+ * Maps an offset into the string at `path`, which the editor computed on
5201
+ * its content at `version`, into the current content. Call it when the
5202
+ * editor's message arrives: its earlier edits are integrated by then.
5203
+ *
5204
+ * @returns `undefined` if the offset cannot be mapped, for example because
5205
+ * the string was replaced or the content was reset since.
5206
+ */
5207
+ mapOffset(version, path, offset, assoc) {
5208
+ if (!this._transform) {
5209
+ const current = this.version;
5210
+ return version.serverRevision === current.serverRevision && version.clientRevision === current.clientRevision ? offset : void 0;
5211
+ }
5212
+ if (version.clientRevision !== this._transform.remoteRevision) return;
5213
+ return mapThrough(this._transform.operationsAfter(version.serverRevision), path, offset, assoc);
5214
+ }
5215
+ /**
5216
+ * Change the text the editor shows.
5217
+ *
5218
+ * When the editor merges concurrent edits, the change is sent as edits
5219
+ * that merge with the editor's unsent edits. Otherwise, and with `force`,
5220
+ * the full text is sent. If `force`, the editor must adopt it even with
5221
+ * pending local edits, which are then discarded.
4470
5222
  */
4471
5223
  setText(text, opts = {}) {
4472
5224
  if (text === this._text && !opts.force) return;
5225
+ const edits = this._transform && !opts.force ? this._diff(this._text, text) : void 0;
4473
5226
  this._text = text;
4474
- this._pushFullUpdate(opts.force);
5227
+ if (edits) this._sendHostEdits(edits);
5228
+ else this._pushFullUpdate(opts.force);
4475
5229
  }
4476
5230
  /**
4477
5231
  * Reassign this host/editor connection to another logical document.
@@ -4486,43 +5240,128 @@ var WebEditorHost = class {
4486
5240
  getReadOnly() {
4487
5241
  return this._readOnly;
4488
5242
  }
5243
+ /**
5244
+ * Tell the editor how the host presents it. Sent to editors that support
5245
+ * presentation once they initialized, and again after they reconnect.
5246
+ */
5247
+ setPresentationMode(mode) {
5248
+ if (this._presentationMode === mode) return;
5249
+ this._presentationMode = mode;
5250
+ this._pushPresentationMode();
5251
+ }
4489
5252
  setReadOnly(readOnly) {
4490
5253
  if (this._readOnly === readOnly) return;
4491
5254
  this._readOnly = readOnly;
4492
5255
  if (this._editorInitialized) this._editor.update({
4493
5256
  readOnly,
4494
- acknowledgedClientRevision: this._acknowledgedClientRevision
5257
+ acknowledgedClientRevision: this._transform?.remoteRevision ?? this._acknowledgedClientRevision
4495
5258
  });
4496
5259
  }
4497
5260
  /**
4498
- * Push fine-grained edits to the editor.
4499
- * The host is responsible for keeping its own `_text` consistent with these edits.
5261
+ * Change the text by fine-grained edits, which are pushed to the editor.
5262
+ * An editor that initializes later receives the changed text.
4500
5263
  */
4501
5264
  applyEdits(edits) {
4502
- if (edits.length === 0 || !this._editorInitialized) return;
4503
- let newValue;
5265
+ if (edits.length === 0) return;
4504
5266
  try {
4505
- newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), edits);
5267
+ const newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), edits);
4506
5268
  this._text = decodeFromEditor(newValue, this._contentType, this._jsonFormat);
4507
5269
  } catch (e) {
4508
5270
  this._onError("Failed to apply outgoing edits to local text", e);
4509
5271
  return;
4510
5272
  }
4511
- this._serverRevision++;
4512
- this._editor.applyContentEdits({
4513
- edits,
4514
- serverRevision: this._serverRevision,
4515
- acknowledgedClientRevision: this._acknowledgedClientRevision
4516
- });
5273
+ this._sendHostEdits(edits);
4517
5274
  }
4518
5275
  dispose() {
5276
+ this._hostTransportSubscription?.dispose();
4519
5277
  this._onDidChangeText.dispose();
4520
5278
  this._onDidInitialize.dispose();
4521
5279
  this._onDidReportSize.dispose();
5280
+ this._onDidSetPresentationPreferences.dispose();
5281
+ this._onDidRequestExitFullView.dispose();
5282
+ this._pendingHostTransportMessages.length = 0;
4522
5283
  this._connection.close();
4523
5284
  }
5285
+ _applyTransformedEditorEdit(transform, params) {
5286
+ let edits;
5287
+ try {
5288
+ edits = transform.remote(params.edits, params.clientRevision, params.basedOnServerRevision);
5289
+ } catch (e) {
5290
+ this._onError("Editor edit does not follow the edit transform protocol", e);
5291
+ this._resetEditor(transform, params.clientRevision);
5292
+ return;
5293
+ }
5294
+ if (edits === void 0) {
5295
+ this._pushAcknowledgement();
5296
+ return;
5297
+ }
5298
+ if (this._readOnly) {
5299
+ this._onError("Editor sent applyContentEdit while readOnly");
5300
+ this._resetEditor(transform);
5301
+ return;
5302
+ }
5303
+ const newText = this._applyEditorEdits(edits);
5304
+ if (newText === void 0) {
5305
+ this._resetEditor(transform);
5306
+ return;
5307
+ }
5308
+ if (newText !== this._text) {
5309
+ this._text = newText;
5310
+ this._onDidChangeText.fire({
5311
+ text: newText,
5312
+ edits
5313
+ });
5314
+ }
5315
+ this._pushAcknowledgement();
5316
+ }
5317
+ /** The text after the editor's `edits`, or `undefined` after reporting why they do not apply. */
5318
+ _applyEditorEdits(edits) {
5319
+ let newValue;
5320
+ try {
5321
+ newValue = applyContentEdits(encodeForEditor(this._text, this._contentType), edits);
5322
+ } catch (e) {
5323
+ this._onError("Failed to apply content edits from editor", e);
5324
+ return;
5325
+ }
5326
+ try {
5327
+ return decodeFromEditor(newValue, this._contentType, this._jsonFormat);
5328
+ } catch (e) {
5329
+ this._onError("Failed to decode editor content", e);
5330
+ return;
5331
+ }
5332
+ }
5333
+ /** Edits from `oldText` to `newText` in the editor's form, or `undefined` if either cannot be encoded. */
5334
+ _diff(oldText, newText) {
5335
+ try {
5336
+ return diffContent(encodeForEditor(oldText, this._contentType), encodeForEditor(newText, this._contentType));
5337
+ } catch {
5338
+ return;
5339
+ }
5340
+ }
5341
+ _sendHostEdits(edits) {
5342
+ if (edits.length === 0 || !this._editorInitialized) return;
5343
+ if (this._transform) {
5344
+ const serverRevision = this._transform.local(edits);
5345
+ this._editor.applyContentEdits({
5346
+ edits: [...edits],
5347
+ serverRevision,
5348
+ acknowledgedClientRevision: this._transform.remoteRevision
5349
+ });
5350
+ return;
5351
+ }
5352
+ this._serverRevision++;
5353
+ this._editor.applyContentEdits({
5354
+ edits,
5355
+ serverRevision: this._serverRevision,
5356
+ acknowledgedClientRevision: this._acknowledgedClientRevision
5357
+ });
5358
+ }
4524
5359
  _pushFullUpdate(force) {
4525
5360
  if (!this._editorInitialized) return;
5361
+ if (this._transform) {
5362
+ this._resetEditor(this._transform);
5363
+ return;
5364
+ }
4526
5365
  this._serverRevision++;
4527
5366
  let content;
4528
5367
  try {
@@ -4539,13 +5378,43 @@ var WebEditorHost = class {
4539
5378
  force
4540
5379
  });
4541
5380
  }
5381
+ /**
5382
+ * Sends the full content, which replaces the editor's. Editor edits made
5383
+ * before the editor receives it are discarded on both sides.
5384
+ */
5385
+ _resetEditor(transform, clientRevision) {
5386
+ let content;
5387
+ try {
5388
+ content = encodeForEditor(this._text, this._contentType);
5389
+ } catch (e) {
5390
+ this._onError("Failed to encode text for editor", e);
5391
+ return;
5392
+ }
5393
+ const serverRevision = transform.reset(clientRevision);
5394
+ this._editor.update({
5395
+ content,
5396
+ readOnly: this._readOnly,
5397
+ serverRevision,
5398
+ acknowledgedClientRevision: transform.remoteRevision,
5399
+ force: true,
5400
+ editTransform: OT_EDIT_TRANSFORM
5401
+ });
5402
+ }
4542
5403
  _pushAcknowledgement() {
4543
5404
  if (!this._editorInitialized) return;
5405
+ if (this._transform) {
5406
+ this._editor.update({ acknowledgedClientRevision: this._transform.remoteRevision });
5407
+ return;
5408
+ }
4544
5409
  this._editor.update({
4545
5410
  serverRevision: this._serverRevision,
4546
5411
  acknowledgedClientRevision: this._acknowledgedClientRevision
4547
5412
  });
4548
5413
  }
5414
+ _pushPresentationMode() {
5415
+ if (!this._editorInitialized || !this._capabilities.supportsPresentation || !this._editorCapabilities?.supportsPresentation || this._presentationMode === void 0) return;
5416
+ this._presentation.changed({ mode: this._presentationMode });
5417
+ }
4549
5418
  _acknowledgeAndRestore(clientRevision) {
4550
5419
  this._acknowledgedClientRevision = Math.max(this._acknowledgedClientRevision, clientRevision);
4551
5420
  this._pushFullUpdate(true);
@@ -4645,7 +5514,7 @@ var HostConnection = class HostConnection {
4645
5514
  const result = await signed.connection.get(hubAccessInterface).requestAccess({
4646
5515
  consumer: {
4647
5516
  ...req.consumer,
4648
- principal: signed.principal.identity.principal
5517
+ principal: signed.principal.identity.publicSigningIdentity.principal
4649
5518
  },
4650
5519
  permissions,
4651
5520
  duration: req.duration
@@ -4693,27 +5562,55 @@ var HostConnection = class HostConnection {
4693
5562
  * Calls `host.initialized` immediately, then exposes the current content and
4694
5563
  * read-only flag as observable events. Local edits made through {@link applyEdits}
4695
5564
  * are sent to the host with monotonically increasing client revisions.
5565
+ *
5566
+ * When the host supports it ({@link OT_EDIT_TRANSFORM}), host edits that
5567
+ * arrive while local edits are unacknowledged are transformed against them,
5568
+ * so neither side's edits are lost. Otherwise such host changes are dropped
5569
+ * (client-authority policy).
4696
5570
  */
4697
5571
  var WebEditorClient = class WebEditorClient {
4698
5572
  _connection;
4699
5573
  _host;
5574
+ _hostTransportProxy;
5575
+ _presentationHost;
4700
5576
  _onError;
5577
+ _hostTransport;
4701
5578
  _content = void 0;
4702
5579
  _readOnly = false;
4703
5580
  _options = void 0;
4704
5581
  _hostCapabilities;
4705
- _clientRevision = 0;
5582
+ _contentType;
5583
+ _connected = false;
5584
+ /** Host messages that arrived before the `initialized` response, which tells how to read them. */
5585
+ _messagesBeforeConnect = [];
5586
+ _presentationMode;
5587
+ _presentationPreferences;
5588
+ _pendingHostTransportMessages = [];
5589
+ _hostTransportActivated = false;
5590
+ /** Local edits and their revisions; its pending edits are those the host has not acknowledged. */
5591
+ _edits = new OtPeer(contentEditsOt, "follower");
5592
+ /** Whether the host transforms concurrent edits, as announced with its first content. */
5593
+ _transform = false;
5594
+ /** Client-authority policy only. */
4706
5595
  _basedOnServerRevision = 0;
4707
- /** Number of un-acked local revisions. While > 0 the editor has pending edits. */
4708
- _pendingLocalEdits = 0;
4709
5596
  _onDidChangeContent = new Emitter();
5597
+ /**
5598
+ * The content changed: by a local edit, by host edits (after
5599
+ * {@link onDidApplyHostEdits}) or replaced by the host. Listeners must
5600
+ * tolerate content they already show.
5601
+ */
4710
5602
  onDidChangeContent = this._onDidChangeContent.event;
4711
5603
  _onDidApplyHostEdits = new Emitter();
5604
+ /** Host edits were applied; `edits` are relative to the previous content, after transformation against local edits. */
4712
5605
  onDidApplyHostEdits = this._onDidApplyHostEdits.event;
4713
5606
  _onDidChangeReadOnly = new Emitter();
4714
5607
  onDidChangeReadOnly = this._onDidChangeReadOnly.event;
4715
5608
  _onDidChangeOptions = new Emitter();
4716
5609
  onDidChangeOptions = this._onDidChangeOptions.event;
5610
+ _onDidChangePresentationMode = new Emitter();
5611
+ /** The embedding host changed how it presents this editor. See {@link getPresentationMode}. */
5612
+ onDidChangePresentationMode = this._onDidChangePresentationMode.event;
5613
+ _onDidReceiveHostMessage = new Emitter();
4717
5614
  /** Resolves once the host has acknowledged `initialized`. */
4718
5615
  onDidConnect;
4719
5616
  static async connect(options) {
@@ -4725,23 +5622,74 @@ var WebEditorClient = class WebEditorClient {
4725
5622
  this._connection = resolveConnection(options.connection);
4726
5623
  this._onError = options.onError ?? ((m, d) => console.error("WebEditorClient:", m, d));
4727
5624
  this._host = this._connection.get(webEditorHostInterface);
5625
+ this._hostTransportProxy = this._connection.get(webEditorHostTransportInterface);
5626
+ this._presentationHost = this._connection.get(webEditorPresentationHostInterface);
4728
5627
  this._connection.register(webEditorInterface, {
4729
- update: (params) => this._handleUpdate(params),
4730
- applyContentEdits: (params) => this._handleApplyContentEdits(params),
5628
+ update: (params) => this._afterConnect(() => this._handleUpdate(params)),
5629
+ applyContentEdits: (params) => this._afterConnect(() => this._handleApplyContentEdits(params)),
4731
5630
  getContentSchema: async () => {
4732
5631
  return { schema: options.getContentSchema ? await options.getContentSchema() : null };
4733
5632
  }
4734
5633
  });
5634
+ this._connection.register(webEditorPresentationInterface, { changed: ({ mode }) => {
5635
+ if (mode === this._presentationMode) return;
5636
+ this._presentationMode = mode;
5637
+ this._onDidChangePresentationMode.fire({ mode });
5638
+ } });
5639
+ this._connection.register(webEditorClientTransportInterface, { message: ({ message }) => {
5640
+ if (this._hostTransportActivated) this._onDidReceiveHostMessage.fire(message);
5641
+ else this._pendingHostTransportMessages.push(message);
5642
+ } });
5643
+ const contentTypes = options.contentTypes ?? [options.contentType ?? "text"];
5644
+ if (contentTypes.length === 0) throw new Error("WebEditorClient: contentTypes must not be empty");
4735
5645
  this.onDidConnect = this._host.initialized({
4736
5646
  protocolVersion: "web-editor/0.12",
4737
- contentType: options.contentType ?? "text",
4738
- capabilities: options.capabilities
5647
+ contentType: contentTypes[0],
5648
+ contentTypes: [...contentTypes],
5649
+ capabilities: {
5650
+ editTransforms: [OT_EDIT_TRANSFORM],
5651
+ ...options.capabilities,
5652
+ supportsPresentation: true
5653
+ }
4739
5654
  }).then((r) => {
5655
+ const contentType = r.contentType ?? contentTypes[0];
5656
+ this._contentType = contentType;
4740
5657
  this._hostCapabilities = r.capabilities;
4741
- return { capabilities: r.capabilities };
5658
+ this._transform ||= r.capabilities?.editTransform === OT_EDIT_TRANSFORM;
5659
+ this._connected = true;
5660
+ for (const handle of this._messagesBeforeConnect?.splice(0) ?? []) handle();
5661
+ this._messagesBeforeConnect = void 0;
5662
+ if (this._presentationPreferences) this.setPresentationPreferences(this._presentationPreferences);
5663
+ if (r.capabilities?.supportsHostTransport) this._hostTransport = {
5664
+ onMessage: (listener) => {
5665
+ const disposable = this._onDidReceiveHostMessage.event(listener);
5666
+ if (!this._hostTransportActivated) {
5667
+ this._hostTransportActivated = true;
5668
+ for (const message of this._pendingHostTransportMessages.splice(0)) listener(message);
5669
+ }
5670
+ return disposable;
5671
+ },
5672
+ sendMessage: (message) => this._hostTransportProxy.message({ message })
5673
+ };
5674
+ else this._pendingHostTransportMessages.length = 0;
5675
+ return {
5676
+ capabilities: r.capabilities,
5677
+ contentType
5678
+ };
4742
5679
  });
4743
5680
  }
4744
5681
  /**
5682
+ * The content type the host serves, one of the accepted ones; `undefined`
5683
+ * until the host answered `initialized`. Content events fire only after it is set.
5684
+ */
5685
+ get contentType() {
5686
+ return this._contentType;
5687
+ }
5688
+ _afterConnect(handle) {
5689
+ if (this._messagesBeforeConnect) this._messagesBeforeConnect.push(handle);
5690
+ else handle();
5691
+ }
5692
+ /**
4745
5693
  * The underlying connection. Reuse it to talk to other host interfaces
4746
5694
  * (e.g. `vscode-app-host`) over the same transport instead of opening a
4747
5695
  * second one.
@@ -4749,9 +5697,36 @@ var WebEditorClient = class WebEditorClient {
4749
5697
  get connection() {
4750
5698
  return this._connection;
4751
5699
  }
5700
+ /** Optional notification transport supplied by the web editor host. */
5701
+ get hostTransport() {
5702
+ return this._hostTransport;
5703
+ }
4752
5704
  getContent() {
4753
5705
  return this._content;
4754
5706
  }
5707
+ /** The current content's version, to send along with offsets into it. */
5708
+ get version() {
5709
+ return {
5710
+ serverRevision: this._serverRevision,
5711
+ clientRevision: this._edits.localRevision
5712
+ };
5713
+ }
5714
+ /**
5715
+ * Maps an offset into the string at `path`, which the host computed on its
5716
+ * content at `version`, into the current content. Call it when the host's
5717
+ * message arrives.
5718
+ *
5719
+ * @returns `undefined` if the offset cannot be mapped, for example because
5720
+ * host edits arrived since or the string was replaced.
5721
+ */
5722
+ mapOffset(version, path, offset, assoc) {
5723
+ if (version.serverRevision !== this._serverRevision) return;
5724
+ return mapThrough(this._edits.operationsAfter(version.clientRevision), path, offset, assoc);
5725
+ }
5726
+ /** The host revision the content is based on. */
5727
+ get _serverRevision() {
5728
+ return this._transform ? this._edits.remoteRevision : this._basedOnServerRevision;
5729
+ }
4755
5730
  getReadOnly() {
4756
5731
  return this._readOnly;
4757
5732
  }
@@ -4773,35 +5748,59 @@ var WebEditorClient = class WebEditorClient {
4773
5748
  this._onError("Failed to apply local edits", e);
4774
5749
  return;
4775
5750
  }
4776
- this._clientRevision++;
4777
- this._pendingLocalEdits++;
5751
+ const clientRevision = this._edits.local(edits);
4778
5752
  this._onDidChangeContent.fire({
4779
5753
  content: this._content,
4780
5754
  force: false
4781
5755
  });
4782
5756
  this._host.applyContentEdit({
4783
- edits,
4784
- clientRevision: this._clientRevision,
4785
- basedOnServerRevision: this._basedOnServerRevision
5757
+ edits: [...edits],
5758
+ clientRevision,
5759
+ basedOnServerRevision: this._serverRevision
4786
5760
  });
4787
5761
  }
4788
5762
  /**
4789
- * Report the editor's current laid-out content height (px) to the host.
4790
- * A host embedding this editor in an iframe uses it to size the frame.
5763
+ * Report the editor's preferred content height (px): the height it needs to
5764
+ * show its content without scrolling, independent of the frame's current
5765
+ * height. A host embedding this editor in an iframe sizes the frame to it.
4791
5766
  */
4792
5767
  reportSize(height) {
4793
5768
  this._host.reportSize({ height });
4794
5769
  }
5770
+ /**
5771
+ * How an embedding host currently presents this editor, or `undefined` when
5772
+ * the host does not present it inline (for example a standalone editor).
5773
+ */
5774
+ getPresentationMode() {
5775
+ return this._presentationMode;
5776
+ }
5777
+ /**
5778
+ * Ask a presenting host for presentation controls (resize grips, full view).
5779
+ * Replaces earlier preferences; sent once connected, and ignored by hosts
5780
+ * that do not present the editor inline.
5781
+ */
5782
+ setPresentationPreferences(preferences) {
5783
+ this._presentationPreferences = preferences;
5784
+ if (this._connected && this._hostCapabilities?.supportsPresentation) this._presentationHost.setPreferences(preferences);
5785
+ }
5786
+ /** Ask a presenting host to leave full view. */
5787
+ exitFullView() {
5788
+ if (this._connected && this._hostCapabilities?.supportsPresentation) this._presentationHost.exitFullView({});
5789
+ }
4795
5790
  dispose() {
4796
5791
  this._onDidChangeContent.dispose();
4797
5792
  this._onDidApplyHostEdits.dispose();
4798
5793
  this._onDidChangeReadOnly.dispose();
4799
5794
  this._onDidChangeOptions.dispose();
5795
+ this._onDidChangePresentationMode.dispose();
5796
+ this._onDidReceiveHostMessage.dispose();
5797
+ this._pendingHostTransportMessages.length = 0;
4800
5798
  this._connection.close();
4801
5799
  }
4802
5800
  _handleUpdate(params) {
5801
+ if (params.editTransform === "ot/1") this._transform = true;
4803
5802
  if (params.acknowledgedClientRevision !== void 0) this._acknowledge(params.acknowledgedClientRevision);
4804
- if (params.serverRevision !== void 0) this._basedOnServerRevision = params.serverRevision;
5803
+ if (!this._transform && params.serverRevision !== void 0) this._basedOnServerRevision = params.serverRevision;
4805
5804
  if (params.readOnly !== void 0 && params.readOnly !== this._readOnly) {
4806
5805
  this._readOnly = params.readOnly;
4807
5806
  this._onDidChangeReadOnly.fire({ readOnly: params.readOnly });
@@ -4810,19 +5809,35 @@ var WebEditorClient = class WebEditorClient {
4810
5809
  this._options = params.options;
4811
5810
  this._onDidChangeOptions.fire({ options: params.options });
4812
5811
  }
4813
- if (params.content !== void 0) {
4814
- if (this._pendingLocalEdits > 0 && !params.force) return;
5812
+ if (params.content === void 0) return;
5813
+ if (this._transform) {
5814
+ try {
5815
+ this._edits.acceptReset(params.serverRevision ?? -1);
5816
+ } catch (e) {
5817
+ this._onError("Host content does not follow the edit transform protocol", e);
5818
+ }
4815
5819
  this._content = params.content;
4816
5820
  this._onDidChangeContent.fire({
4817
5821
  content: params.content,
4818
- force: params.force === true
5822
+ force: true
4819
5823
  });
5824
+ return;
4820
5825
  }
5826
+ if (this._edits.pending.length > 0 && !params.force) return;
5827
+ this._content = params.content;
5828
+ this._onDidChangeContent.fire({
5829
+ content: params.content,
5830
+ force: params.force === true
5831
+ });
4821
5832
  }
4822
5833
  _handleApplyContentEdits(params) {
5834
+ if (this._transform) {
5835
+ this._applyTransformedHostEdits(params);
5836
+ return;
5837
+ }
4823
5838
  this._acknowledge(params.acknowledgedClientRevision);
4824
5839
  this._basedOnServerRevision = params.serverRevision;
4825
- if (this._pendingLocalEdits > 0) return;
5840
+ if (this._edits.pending.length > 0) return;
4826
5841
  try {
4827
5842
  this._content = applyContentEdits(this._content, params.edits);
4828
5843
  } catch (e) {
@@ -4834,10 +5849,36 @@ var WebEditorClient = class WebEditorClient {
4834
5849
  content: this._content
4835
5850
  });
4836
5851
  }
4837
- _acknowledge(ackedClientRevision) {
4838
- const acked = Math.max(0, this._clientRevision - (this._clientRevision - ackedClientRevision));
4839
- const newPending = Math.max(0, this._clientRevision - acked);
4840
- this._pendingLocalEdits = newPending;
5852
+ _applyTransformedHostEdits(params) {
5853
+ let edits;
5854
+ try {
5855
+ edits = [...this._edits.remote(params.edits, params.serverRevision, params.acknowledgedClientRevision) ?? []];
5856
+ } catch (e) {
5857
+ this._onError("Host edits do not follow the edit transform protocol", e);
5858
+ return;
5859
+ }
5860
+ try {
5861
+ this._content = applyContentEdits(this._content, edits);
5862
+ } catch (e) {
5863
+ this._onError("Failed to apply host edits", e);
5864
+ return;
5865
+ }
5866
+ this._host.acknowledge({ serverRevision: params.serverRevision });
5867
+ this._onDidApplyHostEdits.fire({
5868
+ edits,
5869
+ content: this._content
5870
+ });
5871
+ this._onDidChangeContent.fire({
5872
+ content: this._content,
5873
+ force: false
5874
+ });
5875
+ }
5876
+ _acknowledge(clientRevision) {
5877
+ try {
5878
+ this._edits.acknowledge(clientRevision);
5879
+ } catch (e) {
5880
+ this._onError("Host acknowledged edits the editor did not send", e);
5881
+ }
4841
5882
  }
4842
5883
  };
4843
5884
  //#endregion
@@ -5045,8 +6086,287 @@ var VsCodeAppHostClient = class {
5045
6086
  dismissable: options?.dismissable
5046
6087
  });
5047
6088
  }
6089
+ /**
6090
+ * This editor tab's view state, or `undefined` when none is set. VS Code
6091
+ * restores it with the tab (for example after a window reload); a newly
6092
+ * opened tab starts without one. Validate it like any other persisted
6093
+ * input, since it may come from an older version of the app.
6094
+ */
6095
+ async getViewState() {
6096
+ return (await this._host.getViewState({})).value;
6097
+ }
6098
+ /**
6099
+ * Replace this editor tab's view state with a JSON value, for example
6100
+ * scroll positions or selections. Use per-app storage for state shared by
6101
+ * every tab. Rejects for values too large to persist and in embedded apps.
6102
+ */
6103
+ async setViewState(value) {
6104
+ await this._host.setViewState({ value });
6105
+ }
5048
6106
  };
5049
6107
  //#endregion
5050
- export { EmbeddedAppHandle, VsCodeAppHostClient, WebEditorClient, WebEditorHost, WindowMessageTransport, applyContentEdits, applyTextEdits, createWindowParentConnection, decodeFromEditor, encodeForEditor, vscodeAppEmbeddingEventsInterface, vscodeAppHostInterface, webEditorHostInterface, webEditorInterface };
6108
+ //#region src/documentSync/textDocumentSync.ts
6109
+ /**
6110
+ * Keeps a web editor's text and a {@link SyncedTextDocument} in sync while
6111
+ * both change.
6112
+ *
6113
+ * The editor text is the document text plus the editor's changes that are not
6114
+ * in the document yet. Editor changes are written one batch at a time. A
6115
+ * document change that is not such a write, for example an undo, a format on
6116
+ * save or another editor's edit, is transformed against the unwritten editor
6117
+ * changes and sent to the editor, so neither side's changes are lost. A write
6118
+ * the document rejects because it changed meanwhile is transformed the same
6119
+ * way and written again. If the document applies a write differently, for
6120
+ * example with its own line breaks, the editor receives the difference.
6121
+ *
6122
+ * Editors connect through a {@link WebEditorHost}, which merges the editor's
6123
+ * unsent edits with the changes sent to it (operational transformation).
6124
+ * Each (re)loaded editor connects anew.
6125
+ */
6126
+ var TextDocumentSync = class {
6127
+ _document;
6128
+ _onError;
6129
+ /** The document text as last seen. */
6130
+ _documentText;
6131
+ /** {@link _documentText} with {@link _writing} and {@link _unwritten} applied. */
6132
+ _text;
6133
+ _revision = 0;
6134
+ _writing;
6135
+ /**
6136
+ * Document changes seen while {@link _writing} is in flight. They are
6137
+ * settled when it completes: only then is it known whether the first one
6138
+ * is the write.
6139
+ */
6140
+ _changesDuringWrite = [];
6141
+ /** Editor changes after {@link _writing} that are not written yet. */
6142
+ _unwritten = TextOperation.identity;
6143
+ _host;
6144
+ _tracked = /* @__PURE__ */ new Set();
6145
+ _onDidChangeText = new Emitter();
6146
+ /** Fires after every change of {@link text}. */
6147
+ onDidChangeText = this._onDidChangeText.event;
6148
+ _onDidSettle = new Emitter();
6149
+ _subscription;
6150
+ _disposed = false;
6151
+ constructor(_document, options = {}) {
6152
+ this._document = _document;
6153
+ this._onError = options.onError ?? ((message, detail) => console.error("TextDocumentSync:", message, detail));
6154
+ this._documentText = _document.getText();
6155
+ this._text = this._documentText;
6156
+ this._subscription = _document.onDidChangeText((change) => this._acceptDocumentChange(change.edits));
6157
+ }
6158
+ /** The editor text: the document text with the editor changes that are not written yet. */
6159
+ get text() {
6160
+ return this._text;
6161
+ }
6162
+ /** Changes with every change of {@link text}. */
6163
+ get revision() {
6164
+ return this._revision;
6165
+ }
6166
+ /** The version to send along with offsets into {@link text}, while an editor is connected. */
6167
+ get version() {
6168
+ return this._host?.version;
6169
+ }
6170
+ /**
6171
+ * Connects a (re)loaded editor, which receives the current text. Replaces
6172
+ * the previous editor's host, which is disposed along with its connection.
6173
+ */
6174
+ connect(connection, options = {}) {
6175
+ this._host?.dispose();
6176
+ const host = new WebEditorHost({
6177
+ ...options,
6178
+ connection,
6179
+ initialText: this._text,
6180
+ onError: this._onError
6181
+ });
6182
+ this._host = host;
6183
+ host.onDidChangeText(({ text, edits }) => {
6184
+ if (this._host === host) this._acceptEditorChange(text, edits);
6185
+ });
6186
+ return host;
6187
+ }
6188
+ /**
6189
+ * Follows `offset` in {@link text} through later changes, until disposed.
6190
+ * With `"after"` (the default), text inserted exactly at the offset ends up
6191
+ * before it.
6192
+ */
6193
+ track(offset, assoc = "after") {
6194
+ const tracked = new TrackedOffsetImpl(offset, assoc, this._tracked);
6195
+ this._tracked.add(tracked);
6196
+ return tracked;
6197
+ }
6198
+ /**
6199
+ * Tracks an offset into the text that the editor sent along with
6200
+ * `version`; `undefined` if it cannot be mapped. Call it when the editor's
6201
+ * message arrives.
6202
+ */
6203
+ trackFromEditor(version, offset, assoc) {
6204
+ const mapped = offset < 0 ? void 0 : this._host?.mapOffset(version, [], offset, assoc);
6205
+ return mapped === void 0 || mapped > this._text.length ? void 0 : this.track(mapped, assoc);
6206
+ }
6207
+ /**
6208
+ * Resolves once every editor change is in the document, so that
6209
+ * {@link text} equals the document text. Rejects if the sync is disposed.
6210
+ */
6211
+ async drain() {
6212
+ while (!this._disposed && (this._writing || !this._unwritten.isIdentity)) await new Promise((resolve) => {
6213
+ const listener = this._onDidSettle.event(() => {
6214
+ listener.dispose();
6215
+ resolve();
6216
+ });
6217
+ });
6218
+ if (this._disposed) throw new Error("The document sync was disposed");
6219
+ }
6220
+ dispose() {
6221
+ this._disposed = true;
6222
+ this._subscription.dispose();
6223
+ this._host?.dispose();
6224
+ this._host = void 0;
6225
+ this._tracked.clear();
6226
+ this._onDidSettle.fire();
6227
+ this._onDidSettle.dispose();
6228
+ this._onDidChangeText.dispose();
6229
+ }
6230
+ _acceptEditorChange(text, edits) {
6231
+ const operation = this._host?.contentType === "text" && edits.length === 1 && edits[0].kind === "stringEdits" && edits[0].path.length === 0 ? TextOperation.fromTextEdits(edits[0].stringEdits) : diffText(this._text, text);
6232
+ this._applyToText(operation);
6233
+ this._unwritten = this._unwritten.compose(operation);
6234
+ this._write();
6235
+ }
6236
+ _acceptDocumentChange(edits) {
6237
+ const change = {
6238
+ text: this._document.getText(),
6239
+ edits
6240
+ };
6241
+ if (this._writing) {
6242
+ this._changesDuringWrite.push(change);
6243
+ return;
6244
+ }
6245
+ this._acceptExternalChange(change);
6246
+ this._write();
6247
+ }
6248
+ /** Someone else changed the document: merges the change with the editor changes that are not written yet. */
6249
+ _acceptExternalChange({ text: documentText, edits }) {
6250
+ if (documentText === this._documentText) return;
6251
+ const external = (edits && fromDocumentEdits(this._documentText, edits, documentText)) ?? diffText(this._documentText, documentText);
6252
+ const [externalPrime, unwrittenPrime] = TextOperation.transform(external, this._unwritten);
6253
+ this._documentText = documentText;
6254
+ this._unwritten = unwrittenPrime;
6255
+ this._applyFromDocument(externalPrime);
6256
+ }
6257
+ async _write() {
6258
+ if (this._disposed || this._writing) return;
6259
+ if (this._unwritten.isIdentity) {
6260
+ this._onDidSettle.fire();
6261
+ return;
6262
+ }
6263
+ if (this._document.getText() !== this._documentText) return;
6264
+ const operation = this._unwritten;
6265
+ const write = {
6266
+ operation,
6267
+ version: this._document.version,
6268
+ expected: operation.apply(this._documentText)
6269
+ };
6270
+ this._writing = write;
6271
+ this._unwritten = TextOperation.identity;
6272
+ let applied = false;
6273
+ try {
6274
+ applied = await this._document.applyEdits(write.version, toDocumentEdits(operation));
6275
+ } catch (error) {
6276
+ this._onError("Failed to write the editor's changes to the document", error);
6277
+ }
6278
+ if (this._disposed) return;
6279
+ this._writing = void 0;
6280
+ const changes = this._changesDuringWrite.splice(0);
6281
+ if (applied) {
6282
+ const written = changes.shift()?.text ?? this._document.getText();
6283
+ this._documentText = written;
6284
+ const [unwrittenPrime, adjustmentPrime] = TextOperation.transform(this._unwritten, diffText(write.expected, written));
6285
+ this._unwritten = unwrittenPrime;
6286
+ this._applyFromDocument(adjustmentPrime);
6287
+ } else if (changes.length === 0 && this._document.version === write.version) {
6288
+ this._onError("The document rejected the editor's changes");
6289
+ this._unwritten = TextOperation.identity;
6290
+ this._applyFromDocument(diffText(this._text, this._documentText));
6291
+ } else this._unwritten = operation.compose(this._unwritten);
6292
+ for (const change of changes) this._acceptExternalChange(change);
6293
+ this._write();
6294
+ }
6295
+ /** Applies a change that comes from the document to {@link text} and sends it to the editor. */
6296
+ _applyFromDocument(operation) {
6297
+ if (operation.isIdentity) return;
6298
+ this._applyToText(operation);
6299
+ if (this._host?.contentType === "text") this._host?.applyEdits([{
6300
+ kind: "stringEdits",
6301
+ path: [],
6302
+ stringEdits: operation.toTextEdits()
6303
+ }]);
6304
+ else this._host?.setText(this._text);
6305
+ }
6306
+ _applyToText(operation) {
6307
+ if (operation.isIdentity) return;
6308
+ this._text = operation.apply(this._text);
6309
+ this._revision++;
6310
+ for (const tracked of this._tracked) tracked.offset = operation.mapOffset(tracked.offset, tracked.assoc);
6311
+ this._onDidChangeText.fire();
6312
+ }
6313
+ };
6314
+ /**
6315
+ * The operation that applies `edits` (offsets into `oldText`, in any order) to
6316
+ * `oldText`, if they don't overlap and turn it into `newText`; `undefined`
6317
+ * otherwise, for example if a change was missed.
6318
+ */
6319
+ function fromDocumentEdits(oldText, edits, newText) {
6320
+ const builder = new TextOperationBuilder();
6321
+ let offset = 0;
6322
+ for (const edit of [...edits].sort((a, b) => a.offset - b.offset)) {
6323
+ if (edit.offset < offset || edit.length < 0 || edit.offset + edit.length > oldText.length) return;
6324
+ builder.retain(edit.offset - offset).insert(edit.newText).delete(edit.length);
6325
+ offset = edit.offset + edit.length;
6326
+ }
6327
+ const operation = builder.build();
6328
+ return operation.apply(oldText) === newText ? operation : void 0;
6329
+ }
6330
+ var TrackedOffsetImpl = class {
6331
+ offset;
6332
+ assoc;
6333
+ _owner;
6334
+ constructor(offset, assoc, _owner) {
6335
+ this.offset = offset;
6336
+ this.assoc = assoc;
6337
+ this._owner = _owner;
6338
+ }
6339
+ dispose() {
6340
+ this._owner.delete(this);
6341
+ }
6342
+ };
6343
+ /** The edits of `operation`, with offsets into the text before it. */
6344
+ function toDocumentEdits(operation) {
6345
+ const edits = [];
6346
+ let offset = 0;
6347
+ let pending;
6348
+ for (const component of operation.components) if (component.kind === "retain") {
6349
+ if (pending) {
6350
+ edits.push(pending);
6351
+ pending = void 0;
6352
+ }
6353
+ offset += component.length;
6354
+ } else {
6355
+ pending ??= {
6356
+ offset,
6357
+ length: 0,
6358
+ newText: ""
6359
+ };
6360
+ if (component.kind === "insert") pending.newText += component.text;
6361
+ else {
6362
+ pending.length += component.length;
6363
+ offset += component.length;
6364
+ }
6365
+ }
6366
+ if (pending) edits.push(pending);
6367
+ return edits;
6368
+ }
6369
+ //#endregion
6370
+ export { EmbeddedAppHandle, OT_EDIT_TRANSFORM, OtPeer, TextDocumentSync, 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 };
5051
6371
 
5052
6372
  //# sourceMappingURL=index.js.map