@palantir/pack.state.foundry-event 0.1.2 → 0.2.0

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.
@@ -1,55 +1,55 @@
1
1
 
2
- > @palantir/pack.state.foundry-event@0.1.2 lint /home/runner/work/pack/pack/packages/state/foundry-event
2
+ > @palantir/pack.state.foundry-event@0.2.0 lint /home/runner/work/pack/pack/packages/state/foundry-event
3
3
  > eslint ./src && dprint check --config $(find-up dprint.json) --allow-no-files
4
4
 
5
5
 
6
6
  /home/runner/work/pack/pack/packages/state/foundry-event/src/__tests__/EventServiceCometD.reconnection.test.ts
7
- 152:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
7
+ 166:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
8
8
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
9
9
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
10
- 208:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
10
+ 222:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
11
11
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
12
12
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
13
- 209:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
13
+ 223:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
14
14
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
15
15
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
16
- 245:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
16
+ 259:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
17
17
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
18
18
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
19
- 246:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
19
+ 260:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
20
20
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
21
21
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
22
- 250:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
22
+ 264:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
23
23
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
24
24
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
25
- 254:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
25
+ 268:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
26
26
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
27
27
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
28
- 292:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
28
+ 306:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
29
29
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
30
30
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
31
- 324:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
31
+ 338:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
32
32
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
33
33
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
34
- 325:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
34
+ 339:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
35
35
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
36
36
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
37
- 350:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
37
+ 364:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
38
38
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
39
39
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
40
- 351:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
40
+ 365:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
41
41
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
42
42
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
43
- 400:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
43
+ 414:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
44
44
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
45
45
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
46
- 431:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
46
+ 445:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
47
47
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
48
48
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
49
- 432:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
49
+ 446:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
50
50
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
51
51
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
52
- 433:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
52
+ 447:14 warning A method that is not declared with `this: void` may cause unintentional scoping of `this` when separated from its object.
53
53
  Consider using an arrow function or explicitly `.bind()`ing the method to avoid calling the method with an unintended `this` value.
54
54
  If a function does not access `this`, it can be annotated with `this: void` @typescript-eslint/unbound-method
55
55
 
@@ -1,5 +1,6 @@
1
1
 
2
- > @palantir/pack.state.foundry-event@0.1.2 transpileBrowser /home/runner/work/pack/pack/packages/state/foundry-event
2
+ > @palantir/pack.state.foundry-event@0.2.0 transpileBrowser /home/runner/work/pack/pack/packages/state/foundry-event
3
3
  > monorepo-transpile -f esm -m bundle -t browser
4
4
 
5
+ [baseline-browser-mapping] The data in this module is over two months old. To ensure accurate Baseline data, please update: `npm i baseline-browser-mapping@latest -D`
5
6
  👍
@@ -1,5 +1,6 @@
1
1
 
2
- > @palantir/pack.state.foundry-event@0.1.2 transpileCjs /home/runner/work/pack/pack/packages/state/foundry-event
2
+ > @palantir/pack.state.foundry-event@0.2.0 transpileCjs /home/runner/work/pack/pack/packages/state/foundry-event
3
3
  > monorepo-transpile -f cjs -m bundle -t node
4
4
 
5
+ [baseline-browser-mapping] The data in this module is over two months old. To ensure accurate Baseline data, please update: `npm i baseline-browser-mapping@latest -D`
5
6
  👍
@@ -1,5 +1,6 @@
1
1
 
2
- > @palantir/pack.state.foundry-event@0.1.2 transpileEsm /home/runner/work/pack/pack/packages/state/foundry-event
2
+ > @palantir/pack.state.foundry-event@0.2.0 transpileEsm /home/runner/work/pack/pack/packages/state/foundry-event
3
3
  > monorepo-transpile -f esm -m bundle -t node
4
4
 
5
+ [baseline-browser-mapping] The data in this module is over two months old. To ensure accurate Baseline data, please update: `npm i baseline-browser-mapping@latest -D`
5
6
  👍
@@ -1,5 +1,5 @@
1
1
 
2
- > @palantir/pack.state.foundry-event@0.1.2 transpileTypes /home/runner/work/pack/pack/packages/state/foundry-event
2
+ > @palantir/pack.state.foundry-event@0.2.0 transpileTypes /home/runner/work/pack/pack/packages/state/foundry-event
3
3
  > monorepo-transpile -f esm -m types -t node
4
4
 
5
5
  👍
@@ -1,4 +1,4 @@
1
1
 
2
- > @palantir/pack.state.foundry-event@0.1.2 typecheck /home/runner/work/pack/pack/packages/state/foundry-event
2
+ > @palantir/pack.state.foundry-event@0.2.0 typecheck /home/runner/work/pack/pack/packages/state/foundry-event
3
3
  > tsc --noEmit --emitDeclarationOnly false
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @palantir/pack.state.foundry-event
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 83e4a85: Replace local presence types with @osdk/foundry.pack types. Update presence events to use new type format.
8
+
9
+ ### Patch Changes
10
+
11
+ - b02d9b7: Lazy load cometd dep and declare side-effects
12
+ - 571578c: Add Booleans to pack.schema
13
+ - fcf8655: Fix AckExtension side-effect not referencing the proper cometD module
14
+ - 7ee55de: Bump dependencies
15
+ - 4a44875: Remove bun-specific scripts and dependency
16
+ - Updated dependencies [9f45b8e]
17
+ - Updated dependencies [571578c]
18
+ - Updated dependencies [862daf6]
19
+ - Updated dependencies [87f1e63]
20
+ - Updated dependencies [e6e40f7]
21
+ - Updated dependencies [15f7f90]
22
+ - Updated dependencies [7ee55de]
23
+ - Updated dependencies [4a44875]
24
+ - Updated dependencies [8057223]
25
+ - Updated dependencies [19b8f5b]
26
+ - @palantir/pack.document-schema.model-types@0.3.0
27
+ - @palantir/pack.state.core@0.3.0
28
+ - @palantir/pack.core@0.2.1
29
+ - @palantir/pack.auth@0.1.1
30
+
3
31
  ## 0.1.2
4
32
 
5
33
  ### Patch Changes
@@ -1,12 +1,24 @@
1
1
  import { getAuthModule } from '@palantir/pack.auth';
2
- import { CometD, AckExtension } from 'cometd';
3
- import 'cometd/AckExtension.js';
4
2
  import { justOnce, generateId } from '@palantir/pack.core';
5
3
  import { hasMetadata, getMetadata } from '@palantir/pack.document-schema.model-types';
6
4
  import { DocumentLoadStatus } from '@palantir/pack.state.core';
7
5
  import { Base64 } from 'js-base64';
8
6
  import * as y from 'yjs';
9
7
 
8
+ // src/FoundryEventService.ts
9
+
10
+ // src/cometd/lazyLoadCometD.ts
11
+ async function lazyLoadCometD() {
12
+ const cometdModule = await import('cometd');
13
+ const {
14
+ default: AckExtension
15
+ } = await import('cometd/AckExtension.js');
16
+ return {
17
+ ...cometdModule,
18
+ AckExtension
19
+ };
20
+ }
21
+
10
22
  // src/cometd/EventServiceCometD.ts
11
23
  var BEARER_TOKEN_FIELD = "bearer-token";
12
24
  var EXTENSION_ACK = "AckExtension";
@@ -18,66 +30,79 @@ var EventServiceCometD = class {
18
30
  subscriptionById = /* @__PURE__ */ new Map();
19
31
  tokenExtension = new TokenExtension();
20
32
  nextSubscriptionHandle = 0;
21
- constructor(app, cometd = new CometD()) {
33
+ cometd;
34
+ constructor(app, cometdLoader = lazyLoadCometD) {
22
35
  this.app = app;
23
- this.cometd = cometd;
36
+ this.cometdLoader = cometdLoader;
24
37
  this.logger = app.config.logger.child({}, {
25
38
  msgPrefix: "EventServiceCometD"
26
39
  });
27
- this.configureCometd();
28
- this.cometd.registerExtension(EXTENSION_ACK, new AckExtension());
29
- this.cometd.registerExtension(EXTENSION_HANDSHAKE_TOKEN, this.tokenExtension);
30
40
  getAuthModule(app).onTokenChange((token) => {
31
41
  this.tokenExtension.setToken(token);
32
42
  });
33
43
  }
34
- initialize() {
44
+ async initialize() {
35
45
  if (this.initializePromise != null) {
36
46
  return this.initializePromise;
37
47
  }
38
- this.initializePromise = new Promise((resolve) => {
39
- this.cometd.addListener(META_CHANNEL_HANDSHAKE, ({
40
- clientId,
41
- connectionType,
42
- error,
43
- successful
44
- }) => {
45
- if (successful) {
46
- this.logger.info("CometD handshake successful", {
47
- clientId,
48
- connectionType
49
- });
50
- resolve();
51
- this.cometd.batch(() => {
52
- this.subscriptionById.forEach((subscription, subscriptionId) => {
53
- this.logger.debug("Resubscribing to channel", {
54
- channel: subscription.eventChannel,
55
- subscriptionId
56
- });
57
- const subscribeProps = subscription.getSubscriptionRequest?.();
58
- subscription.handle = this.cometd.resubscribe(subscription.handle, {
59
- ext: subscribeProps
48
+ this.initializePromise = (async () => {
49
+ if (this.cometd == null) {
50
+ const {
51
+ AckExtension,
52
+ CometD
53
+ } = await this.cometdLoader();
54
+ this.cometd = new CometD();
55
+ this.configureCometd();
56
+ this.cometd.registerExtension(EXTENSION_ACK, new AckExtension());
57
+ this.cometd.registerExtension(EXTENSION_HANDSHAKE_TOKEN, this.tokenExtension);
58
+ }
59
+ await new Promise((resolve) => {
60
+ this.cometd.addListener(META_CHANNEL_HANDSHAKE, ({
61
+ clientId,
62
+ connectionType,
63
+ error,
64
+ successful
65
+ }) => {
66
+ if (successful) {
67
+ this.logger.info("CometD handshake successful", {
68
+ clientId,
69
+ connectionType
70
+ });
71
+ resolve();
72
+ this.cometd.batch(() => {
73
+ this.subscriptionById.forEach((subscription, subscriptionId) => {
74
+ this.logger.debug("Resubscribing to channel", {
75
+ channel: subscription.eventChannel,
76
+ subscriptionId
77
+ });
78
+ const subscribeProps = subscription.getSubscriptionRequest?.();
79
+ subscription.handle = this.cometd.resubscribe(subscription.handle, {
80
+ ext: subscribeProps
81
+ });
60
82
  });
61
83
  });
62
- });
63
- } else {
64
- this.logger.warn("CometD handshake failed", {
65
- clientId,
66
- error
67
- });
68
- }
69
- });
70
- const authModule = getAuthModule(this.app);
71
- void authModule.getToken().then((token) => {
72
- this.logger.info("Initializing CometD with token");
73
- this.tokenExtension.setToken(token);
74
- this.cometd.handshake();
84
+ } else {
85
+ this.logger.warn("CometD handshake failed", {
86
+ clientId,
87
+ error
88
+ });
89
+ }
90
+ });
91
+ const authModule = getAuthModule(this.app);
92
+ void authModule.getToken().then((token) => {
93
+ this.logger.info("Initializing CometD with token");
94
+ this.tokenExtension.setToken(token);
95
+ this.cometd.handshake();
96
+ });
75
97
  });
76
- });
98
+ })();
77
99
  return this.initializePromise;
78
100
  }
79
101
  async subscribe(channel, onMessage, getSubscriptionRequest) {
80
102
  await this.initialize();
103
+ if (this.cometd == null) {
104
+ throw new Error("CometD not initialized");
105
+ }
81
106
  const subscriptionId = (this.nextSubscriptionHandle++).toString(10);
82
107
  return new Promise((resolve, reject) => {
83
108
  const messageHandler = (receivedData) => {
@@ -138,6 +163,12 @@ var EventServiceCometD = class {
138
163
  eventChannel
139
164
  } = subscription;
140
165
  this.subscriptionById.delete(subscriptionId);
166
+ if (this.cometd == null) {
167
+ this.logger.warn("CometD not initialized, cannot unsubscribe", {
168
+ subscriptionId
169
+ });
170
+ return;
171
+ }
141
172
  this.cometd.unsubscribe(handle, (message) => {
142
173
  if (!message.successful) {
143
174
  this.logger.warn("Server unsubscribe confirmation failed", {
@@ -150,6 +181,9 @@ var EventServiceCometD = class {
150
181
  }
151
182
  async publish(channel, content) {
152
183
  await this.initialize();
184
+ if (this.cometd == null) {
185
+ throw new Error("CometD not initialized");
186
+ }
153
187
  return new Promise((resolve, reject) => {
154
188
  this.cometd.publish(channel, content, (message) => {
155
189
  if (message.successful) {
@@ -174,6 +208,9 @@ var EventServiceCometD = class {
174
208
  this.configureCometd(logLevel);
175
209
  }
176
210
  configureCometd(logLevel) {
211
+ if (this.cometd == null) {
212
+ return;
213
+ }
177
214
  const url = getCometDWebsocketUrl(this.app.config);
178
215
  this.logger.info("Configuring cometD ", {
179
216
  url
@@ -207,19 +244,21 @@ var TokenExtension = class {
207
244
  return message;
208
245
  };
209
246
  };
247
+
248
+ // src/FoundryEventService.ts
210
249
  var UPDATE_ORIGIN_REMOTE = "remote";
211
250
  var getDocumentUpdatesChannelId = (documentId) => `/document/${documentId}/updates`;
212
251
  var getDocumentPublishChannelId = (documentId) => `/document/${documentId}/publish`;
213
252
  var getDocumentActivityChannelId = (documentId) => `/document/${documentId}/activity`;
214
253
  var getDocumentPresenceChannelId = (documentId) => `/document/${documentId}/presence`;
215
254
  var getDocumentPresencePublishChannelId = (documentId) => `/document/${documentId}/presence-publish`;
216
- var FoundryEventService = class {
255
+ var FoundryEventServiceImpl = class {
217
256
  eventService;
218
257
  logger;
219
258
  sessions = /* @__PURE__ */ new Map();
220
- constructor(app, cometd) {
259
+ constructor(app, cometdLoader) {
221
260
  this.app = app;
222
- this.eventService = new EventServiceCometD(app, cometd);
261
+ this.eventService = new EventServiceCometD(app, cometdLoader);
223
262
  this.logger = app.config.logger.child({}, {
224
263
  level: "debug",
225
264
  msgPrefix: "FoundryEventService"
@@ -349,12 +388,12 @@ var FoundryEventService = class {
349
388
  if (ignoreSelfUpdates && localUserId != null) {
350
389
  switch (update.type) {
351
390
  case "presenceChangeEvent":
352
- if (update.presenceChangeEvent.userId === localUserId) {
391
+ if (update.userId === localUserId) {
353
392
  return;
354
393
  }
355
394
  break;
356
395
  case "customPresenceEvent":
357
- if (update.customPresenceEvent.userId === localUserId) {
396
+ if (update.userId === localUserId) {
358
397
  return;
359
398
  }
360
399
  break;
@@ -389,12 +428,10 @@ var FoundryEventService = class {
389
428
  throw new Error("Could not get current userId");
390
429
  }
391
430
  return this.eventService.publish(channelId, {
392
- custom: {
393
- clientId: session.clientId,
394
- eventData: messageData,
395
- // FIXME: why do we have to send this, we are authenticated
396
- userId
397
- },
431
+ clientId: session.clientId,
432
+ eventData: messageData,
433
+ // FIXME: why do we have to send this, we are authenticated
434
+ userId,
398
435
  type: "custom"
399
436
  }).catch((error) => {
400
437
  this.logger.error("Failed to publish custom presence", error, {
@@ -501,8 +538,8 @@ var FoundryEventService = class {
501
538
  return documentId;
502
539
  }
503
540
  };
504
- function createFoundryEventService(app, cometd) {
505
- return new FoundryEventService(app, cometd);
541
+ function createFoundryEventService(app, cometdLoader) {
542
+ return new FoundryEventServiceImpl(app, cometdLoader);
506
543
  }
507
544
  function isEditDescription(obj) {
508
545
  return obj != null && typeof obj === "object" && "data" in obj && "model" in obj && typeof obj.model === "object" && obj.model != null && hasMetadata(obj.model);
@@ -517,6 +554,6 @@ function createDocumentEditDescription(editDescription) {
517
554
  };
518
555
  }
519
556
 
520
- export { EventServiceCometD, FoundryEventService, createFoundryEventService };
557
+ export { createFoundryEventService };
521
558
  //# sourceMappingURL=index.js.map
522
559
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cometd/EventServiceCometD.ts","../../src/FoundryEventService.ts"],"names":["getAuthModule"],"mappings":";;;;;;;;;;AAoBA,IAAM,kBAAA,GAAqB,cAAA;AAC3B,IAAM,aAAA,GAAgB,cAAA;AACtB,IAAM,yBAAA,GAA4B,gBAAA;AAClC,IAAM,sBAAA,GAAyB,iBAAA;AACxB,IAAM,qBAAN,MAAyB;AAAA,EAC9B,MAAA;AAAA,EACA,iBAAA;AAAA,EACA,gBAAA,uBAAuB,GAAA,EAAI;AAAA,EAC3B,cAAA,GAAiB,IAAI,cAAA,EAAe;AAAA,EACpC,sBAAA,GAAyB,CAAA;AAAA,EACzB,WAAA,CAAY,GAAA,EAAK,MAAA,GAAS,IAAI,QAAO,EAAG;AACtC,IAAA,IAAA,CAAK,GAAA,GAAM,GAAA;AACX,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,SAAS,GAAA,CAAI,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,EAAC,EAAG;AAAA,MACxC,SAAA,EAAW;AAAA,KACZ,CAAA;AACD,IAAA,IAAA,CAAK,eAAA,EAAgB;AACrB,IAAA,IAAA,CAAK,MAAA,CAAO,iBAAA,CAAkB,aAAA,EAAe,IAAI,cAAc,CAAA;AAC/D,IAAA,IAAA,CAAK,MAAA,CAAO,iBAAA,CAAkB,yBAAA,EAA2B,IAAA,CAAK,cAAc,CAAA;AAO5E,IAAA,aAAA,CAAc,GAAG,CAAA,CAAE,aAAA,CAAc,CAAA,KAAA,KAAS;AACxC,MAAA,IAAA,CAAK,cAAA,CAAe,SAAS,KAAK,CAAA;AAAA,IACpC,CAAC,CAAA;AAAA,EACH;AAAA,EACA,UAAA,GAAa;AACX,IAAA,IAAI,IAAA,CAAK,qBAAqB,IAAA,EAAM;A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eAAA,CAAgB,IAAA;AAAA,MACtB,OAAA,EAAS;AAAA,KACX;AAAA,IACA,SAAA,EAAW,WAAA,CAAY,eAAA,CAAgB,KAAK,CAAA,CAAE;AAAA,GAChD;AACF","file":"index.js","sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getAuthModule } from \"@palantir/pack.auth\";\nimport { AckExtension, CometD } from \"cometd\";\n// side-effect shenanigans imports the class impl to cometd module\nimport \"cometd/AckExtension.js\";\nconst BEARER_TOKEN_FIELD = \"bearer-token\";\nconst EXTENSION_ACK = \"AckExtension\";\nconst EXTENSION_HANDSHAKE_TOKEN = \"handshakeToken\";\nconst META_CHANNEL_HANDSHAKE = \"/meta/handshake\";\nexport class EventServiceCometD {\n logger;\n initializePromise;\n subscriptionById = new Map();\n tokenExtension = new TokenExtension();\n nextSubscriptionHandle = 0;\n constructor(app, cometd = new CometD()) {\n this.app = app;\n this.cometd = cometd;\n this.logger = app.config.logger.child({}, {\n msgPrefix: \"EventServiceCometD\"\n });\n this.configureCometd();\n this.cometd.registerExtension(EXTENSION_ACK, new AckExtension());\n this.cometd.registerExtension(EXTENSION_HANDSHAKE_TOKEN, this.tokenExtension);\n\n // TODO: Support binary messages\n // this.cometd.registerExtension(BINARY_EXTENSION_NAME, new BinaryExtension());\n\n // Any time the token changes, update the extension so reconnection requests use the new token.\n // This will also be called on initial token set when the auth module is initialized.\n getAuthModule(app).onTokenChange(token => {\n this.tokenExtension.setToken(token);\n });\n }\n initialize() {\n if (this.initializePromise != null) {\n return this.initializePromise;\n }\n this.initializePromise = new Promise(resolve => {\n this.cometd.addListener(META_CHANNEL_HANDSHAKE, ({\n clientId,\n connectionType,\n error,\n successful\n }) => {\n if (successful) {\n this.logger.info(\"CometD handshake successful\", {\n clientId,\n connectionType\n });\n resolve();\n this.cometd.batch(() => {\n this.subscriptionById.forEach((subscription, subscriptionId) => {\n this.logger.debug(\"Resubscribing to channel\", {\n channel: subscription.eventChannel,\n subscriptionId\n });\n const subscribeProps = subscription.getSubscriptionRequest?.();\n subscription.handle = this.cometd.resubscribe(subscription.handle, {\n ext: subscribeProps\n });\n });\n });\n } else {\n this.logger.warn(\"CometD handshake failed\", {\n clientId,\n error\n });\n }\n });\n const authModule = getAuthModule(this.app);\n void authModule.getToken().then(token => {\n this.logger.info(\"Initializing CometD with token\");\n this.tokenExtension.setToken(token);\n this.cometd.handshake();\n });\n });\n return this.initializePromise;\n }\n async subscribe(channel, onMessage, getSubscriptionRequest) {\n await this.initialize();\n const subscriptionId = (this.nextSubscriptionHandle++).toString(10);\n return new Promise((resolve, reject) => {\n const messageHandler = receivedData => {\n if (!this.subscriptionById.has(subscriptionId)) {\n this.logger.info(\"Dropping message for unsubscribing channel\", {\n channel,\n subscriptionId\n });\n return;\n }\n this.logger.debug(\"Received message on channel\", {\n channel,\n subscriptionId,\n hasData: receivedData.data != null\n });\n onMessage(receivedData.data);\n };\n const subscribeCallback = message => {\n if (message.successful) {\n this.logger.debug(\"Successfully subscribed to channel\", {\n channel,\n subscriptionId\n });\n resolve(subscriptionId);\n } else {\n this.subscriptionById.delete(subscriptionId);\n // TODO: Is failure really expected? It's not on the type...\n const maybeFailureReason = \"failure\" in message && typeof message.failure === \"object\" && message.failure && \"reason\" in message.failure && typeof message.failure.reason === \"string\" ? message.failure.reason : undefined;\n this.logger.error(\"Failed to subscribe to channel \", {\n channel,\n error: message.error,\n maybeFailureReason\n });\n const errorMessage = message.error ?? (maybeFailureReason != null ? `(no error message provided by server, a guess: ${maybeFailureReason})` : \"(no error message provided by server)\");\n reject(new Error(`Failed to subscribe to channel ${channel}: ${errorMessage}`));\n }\n };\n const ext = getSubscriptionRequest?.();\n const subscriptionHandle = ext != null ? this.cometd.subscribe(channel, messageHandler, {\n ext\n }, subscribeCallback) : this.cometd.subscribe(channel, messageHandler, subscribeCallback);\n this.subscriptionById.set(subscriptionId, {\n handle: subscriptionHandle,\n getSubscriptionRequest,\n eventChannel: channel\n });\n });\n }\n unsubscribe(subscriptionId) {\n const subscription = this.subscriptionById.get(subscriptionId);\n if (subscription == null) {\n this.logger.warn(\"Attempted to unsubscribe from unknown subscriptionId\", {\n subscriptionId\n });\n return;\n }\n const {\n handle,\n eventChannel\n } = subscription;\n this.subscriptionById.delete(subscriptionId);\n this.cometd.unsubscribe(handle, message => {\n if (!message.successful) {\n this.logger.warn(\"Server unsubscribe confirmation failed\", {\n eventChannel,\n subscriptionId,\n error: message.error\n });\n }\n });\n }\n async publish(channel, content) {\n await this.initialize();\n return new Promise((resolve, reject) => {\n this.cometd.publish(channel, content, message => {\n if (message.successful) {\n this.logger.debug(\"Successfully published message\", channel, {\n content\n });\n resolve();\n } else {\n const error = new Error(`Failed to publish to ${channel}`, {\n cause: message.error\n });\n this.logger.error(\"Failed to publish\", {\n channel,\n error\n });\n reject(error);\n }\n });\n });\n }\n setLogLevel(logLevel) {\n this.configureCometd(logLevel);\n }\n configureCometd(logLevel) {\n const url = getCometDWebsocketUrl(this.app.config);\n this.logger.info(\"Configuring cometD \", {\n url\n });\n this.cometd.configure({\n url,\n // NOTE : Allow higher latency on busy networks to avoid retry loops when servers or networks fall behind.\n maxNetworkDelay: 30_000,\n logLevel,\n autoBatch: true\n });\n }\n}\nfunction getCometDWebsocketUrl(appConfig) {\n const httpUrl = new URL(`${appConfig.remote.packWsPath}/cometd`, appConfig.remote.baseUrl);\n httpUrl.protocol.replace(/https?/, \"ws\");\n // TODO: likely need a specific port for ingest - all of this should be in in appConfig\n return httpUrl.href;\n}\nclass TokenExtension {\n currentToken;\n setToken(token) {\n this.currentToken = token;\n }\n outgoing = message => {\n // Always use the latest token when doing a handshake (handles reconnects)\n if (message.channel === META_CHANNEL_HANDSHAKE) {\n if (this.currentToken) {\n message.ext ??= {};\n message.ext[BEARER_TOKEN_FIELD] = this.currentToken;\n }\n }\n return message;\n };\n}","/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getAuthModule } from \"@palantir/pack.auth\";\nimport { generateId, justOnce } from \"@palantir/pack.core\";\nimport { getMetadata, hasMetadata } from \"@palantir/pack.document-schema.model-types\";\nimport { DocumentLoadStatus } from \"@palantir/pack.state.core\";\nimport { Base64 } from \"js-base64\";\nimport * as y from \"yjs\";\nimport { EventServiceCometD } from \"./cometd/EventServiceCometD.js\";\n\n// TODO: replace with @osdk/foundry.pack types when they land.\n\n// TODO: presence api should have an eventType so we don't need extra wrapper here.\n\nconst UPDATE_ORIGIN_REMOTE = \"remote\";\nconst getDocumentUpdatesChannelId = documentId => `/document/${documentId}/updates`;\nconst getDocumentPublishChannelId = documentId => `/document/${documentId}/publish`;\nconst getDocumentActivityChannelId = documentId => `/document/${documentId}/activity`;\nconst getDocumentPresenceChannelId = documentId => `/document/${documentId}/presence`;\nconst getDocumentPresencePublishChannelId = documentId => `/document/${documentId}/presence-publish`;\n/**\n * This manages event subscriptions and publishing of document related events via\n * our PACK Foundry backend's cometd service.\n */\nexport class FoundryEventService {\n eventService;\n logger;\n sessions = new Map();\n constructor(app, cometd) {\n this.app = app;\n this.eventService = new EventServiceCometD(app, cometd);\n this.logger = app.config.logger.child({}, {\n level: \"debug\",\n msgPrefix: \"FoundryEventService\"\n });\n }\n getOrCreateSession(documentId, yDoc) {\n const sessionId = this.getSessionId(documentId);\n let session = this.sessions.get(sessionId);\n if (!session) {\n session = {\n activitySubscriptionId: undefined,\n clientId: crypto.randomUUID(),\n documentId,\n documentSubscriptionId: undefined,\n lastRevisionId: undefined,\n localYDocUpdateHandler: undefined,\n presenceSubscriptionId: undefined,\n yDoc\n };\n this.sessions.set(sessionId, session);\n }\n return session;\n }\n startDocumentSync(documentId, yDoc, onStatusChange) {\n const session = this.getOrCreateSession(documentId, yDoc);\n if (session.documentSubscriptionId != null) {\n throw new Error(`Document data sync already active for document ${documentId}`);\n }\n const localYDocUpdateHandler = (update, origin) => {\n if (origin === UPDATE_ORIGIN_REMOTE) {\n return;\n }\n const lastRevisionId = session.lastRevisionId;\n if (lastRevisionId == null) {\n this.logger.error(\"Cannot publish document update before initial load is complete. The local state will remain inconsistent.\", {\n docId: documentId\n });\n return;\n }\n const publishChannelId = getDocumentPublishChannelId(documentId);\n const editId = generateId();\n const description = isEditDescription(origin) ? createDocumentEditDescription(origin) : undefined;\n void this.eventService.publish(publishChannelId, {\n clientId: session.clientId,\n description,\n editId,\n yjsUpdate: {\n data: Base64.fromUint8Array(update)\n }\n }).catch(error => {\n this.logger.error(\"Failed to publish document update\", error, {\n docId: documentId\n });\n });\n };\n session.localYDocUpdateHandler = localYDocUpdateHandler;\n yDoc.on(\"update\", localYDocUpdateHandler);\n onStatusChange({\n load: DocumentLoadStatus.LOADING\n });\n const channelId = getDocumentUpdatesChannelId(documentId);\n this.eventService.subscribe(channelId, message => {\n if (session.localYDocUpdateHandler !== localYDocUpdateHandler) {\n return;\n }\n this.handleDocumentUpdateMessage(session, message, yDoc, onStatusChange);\n }, () => ({\n clientId: session.clientId,\n lastRevisionId: session.lastRevisionId?.toString()\n })).then(subscriptionId => {\n if (session.localYDocUpdateHandler === localYDocUpdateHandler) {\n session.documentSubscriptionId = subscriptionId;\n } else {\n this.eventService.unsubscribe(subscriptionId);\n this.sessions.delete(this.getSessionId(documentId));\n }\n }).catch(e => {\n if (session.localYDocUpdateHandler === localYDocUpdateHandler) {\n const error = new Error(\"Failed to setup document data subscription\", {\n cause: e\n });\n onStatusChange({\n error,\n load: DocumentLoadStatus.ERROR\n });\n } else {\n this.logger.warn(\"Document data subscription error after subscription was closed\", {\n docId: documentId,\n error: e\n });\n }\n });\n return {\n clientId: session.clientId,\n documentId: session.documentId\n };\n }\n subscribeToActivityUpdates(documentId, callback) {\n const session = this.getOrCreateSession(documentId);\n const channelId = getDocumentActivityChannelId(documentId);\n return this.eventService.subscribe(channelId, event => {\n this.logger.debug(\"Received activity event\", {\n docId: documentId,\n event\n });\n callback(event);\n }).then(subscriptionId => {\n session.activitySubscriptionId = subscriptionId;\n return subscriptionId;\n }).catch(e => {\n this.logger.error(\"Failed to subscribe to activity updates\", e, {\n docId: documentId\n });\n throw new Error(\"Failed to subscribe to activity updates\", {\n cause: e\n });\n });\n }\n subscribeToPresenceUpdates(documentId, callback, options = {}) {\n const {\n ignoreSelfUpdates = true\n } = options;\n const session = this.getOrCreateSession(documentId);\n const channelId = getDocumentPresenceChannelId(documentId);\n return this.eventService.subscribe(channelId, update => {\n // TODO: api should provide clientId so we filter on our presence messages only,\n // but allow apps to decide what they do with same-user-different-client messages ie\n // from different tabs or devices.\n const localUserId = getAuthModule(this.app).getCurrentUser(true)?.userId;\n if (ignoreSelfUpdates && localUserId != null) {\n switch (update.type) {\n case \"presenceChangeEvent\":\n if (update.presenceChangeEvent.userId === localUserId) {\n return;\n }\n break;\n case \"customPresenceEvent\":\n if (update.customPresenceEvent.userId === localUserId) {\n return;\n }\n break;\n default:\n update;\n break;\n }\n }\n this.logger.debug(\"Received presence update\", {\n docId: documentId,\n updateType: update.type\n });\n callback(update);\n }).then(subscriptionId => {\n session.presenceSubscriptionId = subscriptionId;\n return subscriptionId;\n }).catch(e => {\n this.logger.error(\"Failed to subscribe to presence updates\", e, {\n docId: documentId\n });\n throw new Error(\"Failed to subscribe to presence updates\", {\n cause: e\n });\n });\n }\n publishCustomPresence(documentId, eventType, eventData) {\n const session = this.getOrCreateSession(documentId);\n const channelId = getDocumentPresencePublishChannelId(documentId);\n const messageData = {\n eventData,\n eventType\n };\n // TODO: maybe the session should hold userId\n // Though would need better reconnection handling to ensure userId doesn't change.\n const userId = getAuthModule(this.app).getCurrentUser(true)?.userId;\n if (userId == null) {\n throw new Error(\"Could not get current userId\");\n }\n return this.eventService.publish(channelId, {\n custom: {\n clientId: session.clientId,\n eventData: messageData,\n // FIXME: why do we have to send this, we are authenticated\n userId\n },\n type: \"custom\"\n }).catch(error => {\n this.logger.error(\"Failed to publish custom presence\", error, {\n docId: documentId\n });\n throw error;\n });\n }\n stopDocumentSync(session) {\n const sessionId = this.getSessionId(session.documentId);\n const internalSession = this.sessions.get(sessionId);\n if (internalSession == null) {\n this.logger.warn(\"Attempted to stop sync for unknown session\", {\n documentId: session.documentId,\n clientId: session.clientId\n });\n return;\n }\n if (internalSession.localYDocUpdateHandler != null) {\n internalSession.yDoc?.off(\"update\", internalSession.localYDocUpdateHandler);\n internalSession.localYDocUpdateHandler = undefined;\n }\n if (internalSession.activitySubscriptionId) {\n this.eventService.unsubscribe(internalSession.activitySubscriptionId);\n }\n if (internalSession.presenceSubscriptionId) {\n this.eventService.unsubscribe(internalSession.presenceSubscriptionId);\n }\n if (internalSession.documentSubscriptionId) {\n this.eventService.unsubscribe(internalSession.documentSubscriptionId);\n this.sessions.delete(sessionId);\n }\n }\n handleDocumentUpdateMessage(session, message, yDoc, onStatusChange) {\n switch (message.type) {\n case \"error\":\n const {\n args,\n code,\n errorInstanceId\n } = message;\n this.logger.error(\"Received document update error message\", {\n docId: session.documentId,\n code,\n errorInstanceId,\n args\n });\n onStatusChange({\n error: new Error(`Subscription in error state [${errorInstanceId}]`, {\n cause: message\n }),\n load: DocumentLoadStatus.ERROR\n });\n break;\n case \"update\":\n const {\n baseRevisionId,\n clientId,\n revisionId,\n update\n } = message;\n const data = update != null && typeof update.data === \"string\" ? Base64.toUint8Array(update.data) : undefined;\n const messageDetail = {\n baseRevisionId,\n clientId,\n revisionId,\n updateSize: data?.byteLength ?? 0\n };\n\n // FIXME: the typescript generators for api types come out as string, hard to be clear that they are numbers.\n if (session.lastRevisionId != null && Number(baseRevisionId) !== session.lastRevisionId) {\n this.logger.error(\"Got unexpected update for baseRevisionId\", {\n docId: session.documentId,\n lastRevisionId: session.lastRevisionId,\n message: messageDetail\n });\n return;\n }\n this.logger.debug(\"Applying remote Y.js update\", {\n docId: session.documentId,\n lastRevisionId: session.lastRevisionId,\n message: messageDetail\n });\n session.lastRevisionId = Number(revisionId);\n if (data != null) {\n y.applyUpdate(yDoc, data, UPDATE_ORIGIN_REMOTE);\n }\n onStatusChange({\n load: DocumentLoadStatus.LOADED\n });\n break;\n default:\n message;\n const {\n type\n } = message;\n justOnce(`unknown-collab-update-type:${type}`, () => {\n this.logger.warn(\"Received unknown DocumentUpdateMessage type. This is only warned the first occurrence.\", {\n docId: session.documentId,\n updateType: type\n });\n });\n break;\n }\n }\n getSessionId(documentId) {\n return documentId;\n }\n}\nexport function createFoundryEventService(app, cometd) {\n return new FoundryEventService(app, cometd);\n}\nfunction isEditDescription(obj) {\n return obj != null && typeof obj === \"object\" && \"data\" in obj && \"model\" in obj && typeof obj.model === \"object\" && obj.model != null && hasMetadata(obj.model);\n}\nfunction createDocumentEditDescription(editDescription) {\n return {\n eventData: {\n data: editDescription.data,\n version: 1\n },\n eventType: getMetadata(editDescription.model).name\n };\n}"]}
1
+ {"version":3,"sources":["../../src/cometd/lazyLoadCometD.ts","../../src/cometd/EventServiceCometD.ts","../../src/FoundryEventService.ts"],"names":["getAuthModule"],"mappings":";;;;;;;;;;AAgBA,eAAsB,cAAA,GAAiB;AACrC,EAAA,MAAM,YAAA,GAAe,MAAM,OAAO,QAAQ,CAAA;AAW1C,EAAA,MAAM;AAAA,IACJ,OAAA,EAAS;AAAA,GACX,GAAI,MAAM,OAAO,wBAAwB,CAAA;AACz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;AAAA,EACA,aAAa,UAAA,EAAY;AACvB,IAAA,OAAO,UAAA;AAAA,EACT;AACF,CAAA;AACO,SAAS,yBAAA,CAA0B,KAC1C,YAAA,EAAc;AACZ,EAAA,OAAO,IAAI,uBAAA,CAAwB,GAAA,EAAK,YAAY,CAAA;AACtD;AACA,SAAS,kBAAkB,GAAA,EAAK;AAC9B,EAAA,OAAO,OAAO,IAAA,IAAQ,OAAO,QAAQ,QAAA,IAAY,MAAA,IAAU,OAAO,OAAA,IAAW,GAAA,IAAO,OAAO,GAAA,CAAI,UAAU,QAAA,IAAY,GAAA,CAAI,SAAS,IAAA,IAAQ,WAAA,CAAY,IAAI,KAAK,CAAA;AACjK;AACA,SAAS,8BAA8B,eAAA,EAAiB;AACtD,EAAA,OAAO;AAAA,IACL,SAAA,EAAW;AAAA,MACT,MAAM,eAAA,CAAgB,IAAA;AAAA,MACtB,OAAA,EAAS;AAAA,KACX;AAAA,IACA,SAAA,EAAW,WAAA,CAAY,eAAA,CAAgB,KAAK,CAAA,CAAE;AAAA,GAChD;AACF","file":"index.js","sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport async function lazyLoadCometD() {\n const cometdModule = await import(\"cometd\");\n // cometd module does declare the extensions, however they are added to the module as side-effects\n // by importing the submodule extension files. So for any we use we'll need to import them explicitly.\n // Note that this file should be included in package.json \"sideEffects\" to avoid tree-shaking.\n\n // TODO: switch back to dynamic import with side-effect loading when supported by new cometD version. Requires\n // backend version upgrade first.\n // AckExtension.js modifies the cometd module as a side-effect to add AckExtension.\n // We need to capture the returned constructor because with ESM bundlers, the module reference\n // may not reflect the mutation.\n // @ts-expect-error TS2307: No type declarations for cometd/AckExtension.js, but its default export is the AckExtension constructor\n const {\n default: AckExtension\n } = await import(\"cometd/AckExtension.js\");\n return {\n ...cometdModule,\n AckExtension\n };\n}","/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getAuthModule } from \"@palantir/pack.auth\";\nimport { lazyLoadCometD } from \"./lazyLoadCometD.js\";\nconst BEARER_TOKEN_FIELD = \"bearer-token\";\nconst EXTENSION_ACK = \"AckExtension\";\nconst EXTENSION_HANDSHAKE_TOKEN = \"handshakeToken\";\nconst META_CHANNEL_HANDSHAKE = \"/meta/handshake\";\nexport class EventServiceCometD {\n logger;\n initializePromise;\n subscriptionById = new Map();\n tokenExtension = new TokenExtension();\n nextSubscriptionHandle = 0;\n cometd;\n constructor(app, cometdLoader = lazyLoadCometD) {\n this.app = app;\n this.cometdLoader = cometdLoader;\n this.logger = app.config.logger.child({}, {\n msgPrefix: \"EventServiceCometD\"\n });\n\n // Any time the token changes, update the extension so reconnection requests use the new token.\n // This will also be called on initial token set when the auth module is initialized.\n getAuthModule(app).onTokenChange(token => {\n this.tokenExtension.setToken(token);\n });\n }\n async initialize() {\n if (this.initializePromise != null) {\n return this.initializePromise;\n }\n this.initializePromise = (async () => {\n if (this.cometd == null) {\n const {\n AckExtension,\n CometD\n } = await this.cometdLoader();\n this.cometd = new CometD();\n this.configureCometd();\n this.cometd.registerExtension(EXTENSION_ACK, new AckExtension());\n this.cometd.registerExtension(EXTENSION_HANDSHAKE_TOKEN, this.tokenExtension);\n\n // TODO: Support binary messages\n // this.cometd.registerExtension(BINARY_EXTENSION_NAME, new BinaryExtension());\n }\n await new Promise(resolve => {\n this.cometd.addListener(META_CHANNEL_HANDSHAKE, ({\n clientId,\n connectionType,\n error,\n successful\n }) => {\n if (successful) {\n this.logger.info(\"CometD handshake successful\", {\n clientId,\n connectionType\n });\n resolve();\n this.cometd.batch(() => {\n this.subscriptionById.forEach((subscription, subscriptionId) => {\n this.logger.debug(\"Resubscribing to channel\", {\n channel: subscription.eventChannel,\n subscriptionId\n });\n const subscribeProps = subscription.getSubscriptionRequest?.();\n subscription.handle = this.cometd.resubscribe(subscription.handle, {\n ext: subscribeProps\n });\n });\n });\n } else {\n this.logger.warn(\"CometD handshake failed\", {\n clientId,\n error\n });\n }\n });\n const authModule = getAuthModule(this.app);\n void authModule.getToken().then(token => {\n this.logger.info(\"Initializing CometD with token\");\n this.tokenExtension.setToken(token);\n this.cometd.handshake();\n });\n });\n })();\n return this.initializePromise;\n }\n async subscribe(channel, onMessage, getSubscriptionRequest) {\n await this.initialize();\n if (this.cometd == null) {\n throw new Error(\"CometD not initialized\");\n }\n const subscriptionId = (this.nextSubscriptionHandle++).toString(10);\n return new Promise((resolve, reject) => {\n const messageHandler = receivedData => {\n if (!this.subscriptionById.has(subscriptionId)) {\n this.logger.info(\"Dropping message for unsubscribing channel\", {\n channel,\n subscriptionId\n });\n return;\n }\n this.logger.debug(\"Received message on channel\", {\n channel,\n subscriptionId,\n hasData: receivedData.data != null\n });\n onMessage(receivedData.data);\n };\n const subscribeCallback = message => {\n if (message.successful) {\n this.logger.debug(\"Successfully subscribed to channel\", {\n channel,\n subscriptionId\n });\n resolve(subscriptionId);\n } else {\n this.subscriptionById.delete(subscriptionId);\n // TODO: Is failure really expected? It's not on the type...\n const maybeFailureReason = \"failure\" in message && typeof message.failure === \"object\" && message.failure && \"reason\" in message.failure && typeof message.failure.reason === \"string\" ? message.failure.reason : undefined;\n this.logger.error(\"Failed to subscribe to channel \", {\n channel,\n error: message.error,\n maybeFailureReason\n });\n const errorMessage = message.error ?? (maybeFailureReason != null ? `(no error message provided by server, a guess: ${maybeFailureReason})` : \"(no error message provided by server)\");\n reject(new Error(`Failed to subscribe to channel ${channel}: ${errorMessage}`));\n }\n };\n const ext = getSubscriptionRequest?.();\n const subscriptionHandle = ext != null ? this.cometd.subscribe(channel, messageHandler, {\n ext\n }, subscribeCallback) : this.cometd.subscribe(channel, messageHandler, subscribeCallback);\n this.subscriptionById.set(subscriptionId, {\n handle: subscriptionHandle,\n getSubscriptionRequest,\n eventChannel: channel\n });\n });\n }\n unsubscribe(subscriptionId) {\n const subscription = this.subscriptionById.get(subscriptionId);\n if (subscription == null) {\n this.logger.warn(\"Attempted to unsubscribe from unknown subscriptionId\", {\n subscriptionId\n });\n return;\n }\n const {\n handle,\n eventChannel\n } = subscription;\n this.subscriptionById.delete(subscriptionId);\n if (this.cometd == null) {\n this.logger.warn(\"CometD not initialized, cannot unsubscribe\", {\n subscriptionId\n });\n return;\n }\n this.cometd.unsubscribe(handle, message => {\n if (!message.successful) {\n this.logger.warn(\"Server unsubscribe confirmation failed\", {\n eventChannel,\n subscriptionId,\n error: message.error\n });\n }\n });\n }\n async publish(channel, content) {\n await this.initialize();\n if (this.cometd == null) {\n throw new Error(\"CometD not initialized\");\n }\n return new Promise((resolve, reject) => {\n this.cometd.publish(channel, content, message => {\n if (message.successful) {\n this.logger.debug(\"Successfully published message\", channel, {\n content\n });\n resolve();\n } else {\n const error = new Error(`Failed to publish to ${channel}`, {\n cause: message.error\n });\n this.logger.error(\"Failed to publish\", {\n channel,\n error\n });\n reject(error);\n }\n });\n });\n }\n setLogLevel(logLevel) {\n this.configureCometd(logLevel);\n }\n configureCometd(logLevel) {\n if (this.cometd == null) {\n return;\n }\n const url = getCometDWebsocketUrl(this.app.config);\n this.logger.info(\"Configuring cometD \", {\n url\n });\n this.cometd.configure({\n url,\n // NOTE : Allow higher latency on busy networks to avoid retry loops when servers or networks fall behind.\n maxNetworkDelay: 30_000,\n logLevel,\n autoBatch: true\n });\n }\n}\nfunction getCometDWebsocketUrl(appConfig) {\n const httpUrl = new URL(`${appConfig.remote.packWsPath}/cometd`, appConfig.remote.baseUrl);\n httpUrl.protocol.replace(/https?/, \"ws\");\n // TODO: likely need a specific port for ingest - all of this should be in in appConfig\n return httpUrl.href;\n}\nclass TokenExtension {\n currentToken;\n setToken(token) {\n this.currentToken = token;\n }\n outgoing = message => {\n // Always use the latest token when doing a handshake (handles reconnects)\n if (message.channel === META_CHANNEL_HANDSHAKE) {\n if (this.currentToken) {\n message.ext ??= {};\n message.ext[BEARER_TOKEN_FIELD] = this.currentToken;\n }\n }\n return message;\n };\n}","/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getAuthModule } from \"@palantir/pack.auth\";\nimport { generateId, justOnce } from \"@palantir/pack.core\";\nimport { getMetadata, hasMetadata } from \"@palantir/pack.document-schema.model-types\";\nimport { DocumentLoadStatus } from \"@palantir/pack.state.core\";\nimport { Base64 } from \"js-base64\";\nimport * as y from \"yjs\";\nimport { EventServiceCometD } from \"./cometd/EventServiceCometD.js\";\n\n// TODO: replace with @osdk/foundry.pack types when they land.\n\n// TODO: presence api should have an eventType so we don't need extra wrapper here.\n\nconst UPDATE_ORIGIN_REMOTE = \"remote\";\nconst getDocumentUpdatesChannelId = documentId => `/document/${documentId}/updates`;\nconst getDocumentPublishChannelId = documentId => `/document/${documentId}/publish`;\nconst getDocumentActivityChannelId = documentId => `/document/${documentId}/activity`;\nconst getDocumentPresenceChannelId = documentId => `/document/${documentId}/presence`;\nconst getDocumentPresencePublishChannelId = documentId => `/document/${documentId}/presence-publish`;\n\n/**\n * This manages event subscriptions and publishing of document related events via\n * our PACK Foundry backend's cometd service.\n */\n\nclass FoundryEventServiceImpl {\n eventService;\n logger;\n sessions = new Map();\n constructor(app, cometdLoader) {\n this.app = app;\n this.eventService = new EventServiceCometD(app, cometdLoader);\n this.logger = app.config.logger.child({}, {\n level: \"debug\",\n msgPrefix: \"FoundryEventService\"\n });\n }\n getOrCreateSession(documentId, yDoc) {\n const sessionId = this.getSessionId(documentId);\n let session = this.sessions.get(sessionId);\n if (!session) {\n session = {\n activitySubscriptionId: undefined,\n clientId: crypto.randomUUID(),\n documentId,\n documentSubscriptionId: undefined,\n lastRevisionId: undefined,\n localYDocUpdateHandler: undefined,\n presenceSubscriptionId: undefined,\n yDoc\n };\n this.sessions.set(sessionId, session);\n }\n return session;\n }\n startDocumentSync(documentId, yDoc, onStatusChange) {\n const session = this.getOrCreateSession(documentId, yDoc);\n if (session.documentSubscriptionId != null) {\n throw new Error(`Document data sync already active for document ${documentId}`);\n }\n const localYDocUpdateHandler = (update, origin) => {\n if (origin === UPDATE_ORIGIN_REMOTE) {\n return;\n }\n const lastRevisionId = session.lastRevisionId;\n if (lastRevisionId == null) {\n this.logger.error(\"Cannot publish document update before initial load is complete. The local state will remain inconsistent.\", {\n docId: documentId\n });\n return;\n }\n const publishChannelId = getDocumentPublishChannelId(documentId);\n const editId = generateId();\n const description = isEditDescription(origin) ? createDocumentEditDescription(origin) : undefined;\n void this.eventService.publish(publishChannelId, {\n clientId: session.clientId,\n description,\n editId,\n yjsUpdate: {\n data: Base64.fromUint8Array(update)\n }\n }).catch(error => {\n this.logger.error(\"Failed to publish document update\", error, {\n docId: documentId\n });\n });\n };\n session.localYDocUpdateHandler = localYDocUpdateHandler;\n yDoc.on(\"update\", localYDocUpdateHandler);\n onStatusChange({\n load: DocumentLoadStatus.LOADING\n });\n const channelId = getDocumentUpdatesChannelId(documentId);\n this.eventService.subscribe(channelId, message => {\n if (session.localYDocUpdateHandler !== localYDocUpdateHandler) {\n return;\n }\n this.handleDocumentUpdateMessage(session, message, yDoc, onStatusChange);\n }, () => ({\n clientId: session.clientId,\n lastRevisionId: session.lastRevisionId?.toString()\n })).then(subscriptionId => {\n if (session.localYDocUpdateHandler === localYDocUpdateHandler) {\n session.documentSubscriptionId = subscriptionId;\n } else {\n this.eventService.unsubscribe(subscriptionId);\n this.sessions.delete(this.getSessionId(documentId));\n }\n }).catch(e => {\n if (session.localYDocUpdateHandler === localYDocUpdateHandler) {\n const error = new Error(\"Failed to setup document data subscription\", {\n cause: e\n });\n onStatusChange({\n error,\n load: DocumentLoadStatus.ERROR\n });\n } else {\n this.logger.warn(\"Document data subscription error after subscription was closed\", {\n docId: documentId,\n error: e\n });\n }\n });\n return {\n clientId: session.clientId,\n documentId: session.documentId\n };\n }\n subscribeToActivityUpdates(documentId, callback) {\n const session = this.getOrCreateSession(documentId);\n const channelId = getDocumentActivityChannelId(documentId);\n return this.eventService.subscribe(channelId, event => {\n this.logger.debug(\"Received activity event\", {\n docId: documentId,\n event\n });\n callback(event);\n }).then(subscriptionId => {\n session.activitySubscriptionId = subscriptionId;\n return subscriptionId;\n }).catch(e => {\n this.logger.error(\"Failed to subscribe to activity updates\", e, {\n docId: documentId\n });\n throw new Error(\"Failed to subscribe to activity updates\", {\n cause: e\n });\n });\n }\n subscribeToPresenceUpdates(documentId, callback, options = {}) {\n const {\n ignoreSelfUpdates = true\n } = options;\n const session = this.getOrCreateSession(documentId);\n const channelId = getDocumentPresenceChannelId(documentId);\n return this.eventService.subscribe(channelId, update => {\n // TODO: api should provide clientId so we filter on our presence messages only,\n // but allow apps to decide what they do with same-user-different-client messages ie\n // from different tabs or devices.\n const localUserId = getAuthModule(this.app).getCurrentUser(true)?.userId;\n if (ignoreSelfUpdates && localUserId != null) {\n switch (update.type) {\n case \"presenceChangeEvent\":\n if (update.userId === localUserId) {\n return;\n }\n break;\n case \"customPresenceEvent\":\n if (update.userId === localUserId) {\n return;\n }\n break;\n default:\n update;\n break;\n }\n }\n this.logger.debug(\"Received presence update\", {\n docId: documentId,\n updateType: update.type\n });\n callback(update);\n }).then(subscriptionId => {\n session.presenceSubscriptionId = subscriptionId;\n return subscriptionId;\n }).catch(e => {\n this.logger.error(\"Failed to subscribe to presence updates\", e, {\n docId: documentId\n });\n throw new Error(\"Failed to subscribe to presence updates\", {\n cause: e\n });\n });\n }\n publishCustomPresence(documentId, eventType, eventData) {\n const session = this.getOrCreateSession(documentId);\n const channelId = getDocumentPresencePublishChannelId(documentId);\n const messageData = {\n eventData,\n eventType\n };\n // TODO: maybe the session should hold userId\n // Though would need better reconnection handling to ensure userId doesn't change.\n const userId = getAuthModule(this.app).getCurrentUser(true)?.userId;\n if (userId == null) {\n throw new Error(\"Could not get current userId\");\n }\n return this.eventService.publish(channelId, {\n clientId: session.clientId,\n eventData: messageData,\n // FIXME: why do we have to send this, we are authenticated\n userId,\n type: \"custom\"\n }).catch(error => {\n this.logger.error(\"Failed to publish custom presence\", error, {\n docId: documentId\n });\n throw error;\n });\n }\n stopDocumentSync(session) {\n const sessionId = this.getSessionId(session.documentId);\n const internalSession = this.sessions.get(sessionId);\n if (internalSession == null) {\n this.logger.warn(\"Attempted to stop sync for unknown session\", {\n documentId: session.documentId,\n clientId: session.clientId\n });\n return;\n }\n if (internalSession.localYDocUpdateHandler != null) {\n internalSession.yDoc?.off(\"update\", internalSession.localYDocUpdateHandler);\n internalSession.localYDocUpdateHandler = undefined;\n }\n if (internalSession.activitySubscriptionId) {\n this.eventService.unsubscribe(internalSession.activitySubscriptionId);\n }\n if (internalSession.presenceSubscriptionId) {\n this.eventService.unsubscribe(internalSession.presenceSubscriptionId);\n }\n if (internalSession.documentSubscriptionId) {\n this.eventService.unsubscribe(internalSession.documentSubscriptionId);\n this.sessions.delete(sessionId);\n }\n }\n handleDocumentUpdateMessage(session, message, yDoc, onStatusChange) {\n switch (message.type) {\n case \"error\":\n const {\n args,\n code,\n errorInstanceId\n } = message;\n this.logger.error(\"Received document update error message\", {\n docId: session.documentId,\n code,\n errorInstanceId,\n args\n });\n onStatusChange({\n error: new Error(`Subscription in error state [${errorInstanceId}]`, {\n cause: message\n }),\n load: DocumentLoadStatus.ERROR\n });\n break;\n case \"update\":\n const {\n baseRevisionId,\n clientId,\n revisionId,\n update\n } = message;\n const data = update != null && typeof update.data === \"string\" ? Base64.toUint8Array(update.data) : undefined;\n const messageDetail = {\n baseRevisionId,\n clientId,\n revisionId,\n updateSize: data?.byteLength ?? 0\n };\n\n // FIXME: the typescript generators for api types come out as string, hard to be clear that they are numbers.\n if (session.lastRevisionId != null && Number(baseRevisionId) !== session.lastRevisionId) {\n this.logger.error(\"Got unexpected update for baseRevisionId\", {\n docId: session.documentId,\n lastRevisionId: session.lastRevisionId,\n message: messageDetail\n });\n return;\n }\n this.logger.debug(\"Applying remote Y.js update\", {\n docId: session.documentId,\n lastRevisionId: session.lastRevisionId,\n message: messageDetail\n });\n session.lastRevisionId = Number(revisionId);\n if (data != null) {\n y.applyUpdate(yDoc, data, UPDATE_ORIGIN_REMOTE);\n }\n onStatusChange({\n load: DocumentLoadStatus.LOADED\n });\n break;\n default:\n message;\n const {\n type\n } = message;\n justOnce(`unknown-collab-update-type:${type}`, () => {\n this.logger.warn(\"Received unknown DocumentUpdateMessage type. This is only warned the first occurrence.\", {\n docId: session.documentId,\n updateType: type\n });\n });\n break;\n }\n }\n getSessionId(documentId) {\n return documentId;\n }\n}\nexport function createFoundryEventService(app, /** @internal */\ncometdLoader) {\n return new FoundryEventServiceImpl(app, cometdLoader);\n}\nfunction isEditDescription(obj) {\n return obj != null && typeof obj === \"object\" && \"data\" in obj && \"model\" in obj && typeof obj.model === \"object\" && obj.model != null && hasMetadata(obj.model);\n}\nfunction createDocumentEditDescription(editDescription) {\n return {\n eventData: {\n data: editDescription.data,\n version: 1\n },\n eventType: getMetadata(editDescription.model).name\n };\n}"]}