@memberjunction/communication-ms-graph 6.2.0-edge.5 → 6.2.0-edge.7

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,4 +1,4 @@
1
- import { BaseCommunicationProvider, MessageRetrievalCapabilities, CreateDraftParams, CreateDraftResult, ForwardMessageParams, ForwardMessageResult, GetEventsParams, GetEventsResult, GetFreeBusyParams, GetFreeBusyResult, FindMeetingTimesParams, FindMeetingTimesResult, CreateCalendarEventParams, CreateCalendarEventResult, UpdateCalendarEventParams, UpdateCalendarEventResult, RespondToCalendarEventParams, RespondToCalendarEventResult, CancelCalendarEventParams, CancelCalendarEventResult, VerifyMailboxAccessParams, VerifyMailboxAccessResult, GetMessagesParams, GetMessagesResult, GetSingleMessageParams, GetSingleMessageResult, DeleteMessageParams, DeleteMessageResult, MoveMessageParams, MoveMessageResult, ListFoldersParams, ListFoldersResult, MarkAsReadParams, MarkAsReadResult, ArchiveMessageParams, ArchiveMessageResult, SearchMessagesParams, SearchMessagesResult, ListAttachmentsParams, ListAttachmentsResult, DownloadAttachmentParams, DownloadAttachmentResult, ProviderOperation, MessageResult, ProcessedMessage, ProviderCredentialsBase, ReplyToMessageParams, ReplyToMessageResult, CreateSubscriptionParams, RenewSubscriptionParams, DeleteSubscriptionParams, SubscriptionResult, SubscriptionCapabilities, WebhookNotificationInput, ParseNotificationResult, BaseMessageResult } from "@memberjunction/communication-types";
1
+ import { BaseCommunicationProvider, MessageRetrievalCapabilities, CreateDraftParams, CreateDraftResult, ForwardMessageParams, ForwardMessageResult, GetEventsParams, GetEventsResult, GetFreeBusyParams, GetFreeBusyResult, FindMeetingTimesParams, FindMeetingTimesResult, CreateCalendarEventParams, CreateCalendarEventResult, UpdateCalendarEventParams, UpdateCalendarEventResult, RespondToCalendarEventParams, RespondToCalendarEventResult, CancelCalendarEventParams, CancelCalendarEventResult, VerifyMailboxAccessParams, VerifyMailboxAccessResult, GetMessagesParams, GetMessagesResult, GetSingleMessageParams, GetSingleMessageResult, DeleteMessageParams, DeleteMessageResult, MoveMessageParams, MoveMessageResult, ListFoldersParams, ListFoldersResult, MarkAsReadParams, MarkAsReadResult, ArchiveMessageParams, ArchiveMessageResult, SearchMessagesParams, SearchMessagesResult, ListAttachmentsParams, ListAttachmentsResult, DownloadAttachmentParams, DownloadAttachmentResult, ProviderOperation, MessageResult, ProcessedMessage, ProviderCredentialsBase, ReplyToMessageParams, ReplyToMessageResult, CreateSubscriptionParams, RenewSubscriptionParams, DeleteSubscriptionParams, SubscriptionResult, SubscriptionCapabilities, WebhookNotificationInput, ParseNotificationResult, BaseMessageResult, CalendarEventResult, CancelEventParams, CreateEventParams, GetEventParams, SyncEventsParams, SyncEventsResult, UpdateEventParams } from "@memberjunction/communication-types";
2
2
  import { Client } from '@microsoft/microsoft-graph-client';
3
3
  import { Message } from "@microsoft/microsoft-graph-types";
4
4
  /**
@@ -51,6 +51,13 @@ export interface MSGraphCredentials extends ProviderCredentialsBase {
51
51
  * Can also be overridden via message.From.
52
52
  */
53
53
  accountEmail?: string;
54
+ /**
55
+ * A bearer token the caller already holds: a delegated user token, or an app token from
56
+ * another registration (the realtime bridge passes its Teams bot token). When set it is used
57
+ * as is and tenantId/clientId/clientSecret are not needed. It is never cached here, so the
58
+ * caller refreshes it. Graph checks its scopes per call: calendar writes need Calendars.ReadWrite.
59
+ */
60
+ accessToken?: string;
54
61
  }
55
62
  /**
56
63
  * Implementation of the MS Graph provider for sending and receiving messages.
@@ -257,8 +264,6 @@ export declare class MSGraphProvider extends BaseCommunicationProvider {
257
264
  * marker genuinely has no instant here, and inventing one would file a meeting at the wrong time.
258
265
  */
259
266
  private toGetEventsEvent;
260
- /** A Graph date slot as an instant, or null when it does not determine one. */
261
- private static graphInstant;
262
267
  /**
263
268
  * Queries free/busy schedule intervals for one or more users via Microsoft Graph
264
269
  * `POST /users/{id}/calendar/getSchedule`.
@@ -313,6 +318,56 @@ export declare class MSGraphProvider extends BaseCommunicationProvider {
313
318
  * MS Graph supports all mailbox and calendar operations.
314
319
  */
315
320
  getSupportedOperations(): ProviderOperation[];
321
+ /**
322
+ * Creates an event. With attendees, Graph sends the invitations from the target mailbox, which
323
+ * becomes the organizer. `IsOnlineMeeting` attaches a Teams meeting.
324
+ */
325
+ CreateEvent(params: CreateEventParams, credentials?: MSGraphCredentials): Promise<CalendarEventResult>;
326
+ /** Patches the given fields. Graph sends updates to attendees when the organizer changes a meeting. */
327
+ UpdateEvent(params: UpdateEventParams, credentials?: MSGraphCredentials): Promise<CalendarEventResult>;
328
+ /**
329
+ * Cancels an event.
330
+ *
331
+ * THE ORGANIZER CANCELS, ANYONE ELSE DELETES. Graph's `cancel` sends attendees a cancellation
332
+ * (with the comment) but refuses a non-organizer with a 400. So the event's `isOrganizer` is read
333
+ * first: the organizer's mailbox cancels, an attendee's mailbox deletes its own copy, which removes
334
+ * it from that calendar only and tells nobody. An event that is already gone (404) counts as
335
+ * cancelled, so a retry after a lost reply does not fail. A 404 for the MAILBOX does not: Graph
336
+ * answers an unknown or mailbox-less user with 404 too, and that cancelled nothing.
337
+ */
338
+ CancelEvent(params: CancelEventParams, credentials?: MSGraphCredentials): Promise<BaseMessageResult>;
339
+ /** Reads one event with each attendee's response. */
340
+ GetEvent(params: GetEventParams, credentials?: MSGraphCredentials): Promise<CalendarEventResult>;
341
+ /**
342
+ * Reads changes through `calendarView/delta`.
343
+ *
344
+ * A full sync needs the window (Graph's delta over a calendar view is always bounded); the delta
345
+ * link Graph returns at the end carries that window, so later syncs need only the token. Pages are
346
+ * followed through `@odata.nextLink` until the `@odata.deltaLink`, which is the next token. Graph
347
+ * answers an expired or unknown token with 410 Gone: that comes back as `ResyncRequired`.
348
+ */
349
+ SyncEvents(params: SyncEventsParams, credentials?: MSGraphCredentials): Promise<SyncEventsResult>;
350
+ /**
351
+ * Graph lists under `@removed` both an event that was deleted and one added, moved or changed
352
+ * OUTSIDE the delta's window (see Graph's event: delta). A caller that took every tombstone as a
353
+ * deletion would cancel a meeting that was only rescheduled past the window. So each one is read:
354
+ * a 404 is a real removal, anything found comes back as an upsert of the event as it is now.
355
+ *
356
+ * ponytail: one GET per tombstone; batch them (Graph $batch, 20 per call) if a calendar's syncs
357
+ * ever carry many.
358
+ */
359
+ private confirmRemoval;
360
+ /** The first page of a full delta read. Throws when there is no window, which the caller reports. */
361
+ private firstDeltaUrl;
362
+ /** True when a Graph 404 is about the mailbox (no such user, or no Exchange mailbox), not the item. */
363
+ private isMailboxNotFound;
364
+ /** True when Graph refused a delta token as expired or unknown, so the caller must start over. */
365
+ private isResyncError;
366
+ /**
367
+ * The shared shape of every calendar call: refuse a missing target before any I/O, build the
368
+ * client and the mailbox path from the target alone, and turn a thrown error into a result.
369
+ */
370
+ private calendarCall;
316
371
  /**
317
372
  * Builds the base URL for Graph subscription resources. Subscriptions live at the
318
373
  * Graph service root (`/v1.0/subscriptions`), NOT under the users-rooted
@@ -1 +1 @@
1
- {"version":3,"file":"MSGraphProvider.d.ts","sourceRoot":"","sources":["../src/MSGraphProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,yBAAyB,EAEzB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,eAAe,EACf,eAAe,EAEf,iBAAiB,EACjB,iBAAiB,EAEjB,sBAAsB,EACtB,sBAAsB,EAEtB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,4BAA4B,EAC5B,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,EACjB,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB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AE,kBAAkB,GACjC,OAAO,CAAC,wBAAwB,CAAC;IAyCpC;;;;;OAKG;YACW,gBAAgB;IA2B9B;;;;;OAKG;YACW,gBAAgB;IAe9B;;OAEG;IACH,OAAO,CAAC,cAAc;IAQtB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAY3B;;;;;;OAMG;IACH,OAAO,CAAC,sBAAsB;IAe9B;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;IAQ1B;;;;;OAKG;IACH,OAAO,CAAC,2BAA2B;IAQnC;;;OAGG;IACH,OAAO,CAAC,aAAa;IAOrB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAOzB;;;;OAIG;IACH,OAAO,CAAC,eAAe;CAK1B"}
1
+ {"version":3,"file":"MSGraphProvider.d.ts","sourceRoot":"","sources":["../src/MSGraphProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,yBAAyB,EAEzB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,eAAe,EACf,eAAe,EAEf,iBAAiB,EACjB,iBAAiB,EAEjB,sBAAsB,EACtB,sBAAsB,EAEtB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,4BAA4B,EAC5B,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,EACjB,sBAAsB,EACtB,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,EACrB,wBAAwB,EACxB,wBAAwB,EAGxB,iBAAiB,EACjB,aAAa,EACb,gBAAgB,EAChB,uBAAuB,EACvB,oBAAoB,EACpB,oBAAoB,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decorate) || function (decorators, target, key,
7
7
  var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
- var MSGraphProvider_1;
11
- import { BaseCommunicationProvider, CombineFilterClauses, resolveCredentialValue, validateRequiredCredentials } from "@memberjunction/communication-types";
10
+ import { BaseCommunicationProvider, CombineFilterClauses, resolveCredentialValue, validateRequiredCredentials, CalendarTargetError, CalendarUpdateError } from "@memberjunction/communication-types";
12
11
  import { Client } from '@microsoft/microsoft-graph-client';
13
12
  import { ClientSecretCredential } from '@azure/identity';
14
13
  import { TokenCredentialAuthenticationProvider } from "@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials/index.js";
@@ -17,6 +16,7 @@ import { LogError, LogStatus } from "@memberjunction/core";
17
16
  import { compile } from 'html-to-text';
18
17
  import * as Auth from "./auth.js";
19
18
  import * as Config from "./config.js";
19
+ import { BuildGraphEventBody, GraphInstant, ToCalendarChange, ToCalendarEvent } from "./calendar.js";
20
20
  /**
21
21
  * The maximum lifetime, in minutes, that Microsoft Graph allows for a mail-resource
22
22
  * change-notification subscription (~3 days). Requested expirations are clamped to this.
@@ -32,6 +32,8 @@ function ODataInstant(when) {
32
32
  return when.toISOString();
33
33
  }
34
34
  const MSGRAPH_MAX_SUBSCRIPTION_MINUTES = 4230;
35
+ /** A guard against a misbehaving delta stream, not a real limit: a calendar view rarely spans more than a few pages. */
36
+ const MSGRAPH_MAX_DELTA_PAGES = 1000;
35
37
  /**
36
38
  * Implementation of the MS Graph provider for sending and receiving messages.
37
39
  *
@@ -57,7 +59,7 @@ const MSGRAPH_MAX_SUBSCRIPTION_MINUTES = 4230;
57
59
  * });
58
60
  * ```
59
61
  */
60
- let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseCommunicationProvider {
62
+ let MSGraphProvider = class MSGraphProvider extends BaseCommunicationProvider {
61
63
  /**
62
64
  * Graph filters both of these server-side, so neither is emulated here — `receivedDateTime`
63
65
  * comparisons and `isRead` are ordinary `$filter` clauses.
@@ -85,6 +87,11 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
85
87
  */
86
88
  resolveCredentials(credentials) {
87
89
  const disableFallback = credentials?.disableEnvironmentFallback ?? false;
90
+ const accessToken = credentials?.accessToken?.trim();
91
+ if (accessToken) {
92
+ const accountEmail = resolveCredentialValue(credentials?.accountEmail, Config.AZURE_ACCOUNT_EMAIL, disableFallback);
93
+ return { tenantId: '', clientId: '', clientSecret: '', accountEmail, accessToken };
94
+ }
88
95
  const tenantId = resolveCredentialValue(credentials?.tenantId, Config.AZURE_TENANT_ID, disableFallback);
89
96
  const clientId = resolveCredentialValue(credentials?.clientId, Config.AZURE_CLIENT_ID, disableFallback);
90
97
  const clientSecret = resolveCredentialValue(credentials?.clientSecret, Config.AZURE_CLIENT_SECRET, disableFallback);
@@ -126,6 +133,12 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
126
133
  * Uses cached client if credentials match environment (default case).
127
134
  */
128
135
  getGraphClient(creds) {
136
+ // A caller-supplied token wins, and is checked first so it can never fall into the env branch
137
+ // below. Not cached: the token expires and the caller refreshes it, and a client is cheap.
138
+ if (creds.accessToken) {
139
+ const token = creds.accessToken;
140
+ return Client.initWithMiddleware({ authProvider: { getAccessToken: async () => token } });
141
+ }
129
142
  // Check if using environment credentials (can use shared client)
130
143
  const isEnvCredentials = creds.tenantId === Config.AZURE_TENANT_ID &&
131
144
  creds.clientId === Config.AZURE_CLIENT_ID &&
@@ -682,7 +695,7 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
682
695
  // Ask for UTC explicitly rather than relying on it. Graph returns start/end in UTC when no
683
696
  // `Prefer: outlook.timezone` is sent, so this changes nothing today — but the default is
684
697
  // Microsoft's to change, and every other value would need a tz database to resolve. Saying
685
- // it makes the mapper's UTC assumption a request rather than a bet. `graphInstant` keeps
698
+ // it makes the mapper's UTC assumption a request rather than a bet. `GraphInstant` keeps
686
699
  // its null fallback for the case where a non-UTC zone comes back anyway.
687
700
  request = request.header('Prefer', 'outlook.timezone="UTC"');
688
701
  // Applied server-side so the $top cap counts only events the caller asked for. Filtering
@@ -738,30 +751,14 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
738
751
  SeriesID: event.seriesMasterId ?? null,
739
752
  Subject: event.subject ?? '',
740
753
  Body: event.bodyPreview ?? '',
741
- StartTime: MSGraphProvider_1.graphInstant(event.start),
742
- EndTime: MSGraphProvider_1.graphInstant(event.end),
754
+ StartTime: GraphInstant(event.start),
755
+ EndTime: GraphInstant(event.end),
743
756
  Location: event.location?.displayName ?? null,
744
757
  Organizer: organizer,
745
758
  Attendees: [...new Set(attendees)],
746
759
  IsCancelled: event.isCancelled === true
747
760
  };
748
761
  }
749
- /** A Graph date slot as an instant, or null when it does not determine one. */
750
- static graphInstant(slot) {
751
- const raw = slot?.dateTime?.trim();
752
- if (!raw)
753
- return null;
754
- // Both alternatives anchored. Unanchored, the `[Zz]` matched a "z" ANYWHERE in the string, so
755
- // a value that merely contained one counted as carrying an offset and skipped the UTC check.
756
- const hasOffset = /(?:[Zz]|[+-]\d{2}:?\d{2})$/.test(raw);
757
- const zone = (slot?.timeZone ?? 'UTC').trim().toUpperCase();
758
- // Only UTC is safe to assume. Any other named zone would need a tz database to resolve, and
759
- // guessing puts the meeting hours away from when it happened.
760
- if (!hasOffset && zone !== 'UTC')
761
- return null;
762
- const parsed = new Date(hasOffset ? raw : `${raw}Z`);
763
- return Number.isNaN(parsed.getTime()) ? null : parsed;
764
- }
765
762
  /**
766
763
  * Queries free/busy schedule intervals for one or more users via Microsoft Graph
767
764
  * `POST /users/{id}/calendar/getSchedule`.
@@ -804,8 +801,8 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
804
801
  const rawItems = raw.scheduleItems ?? [];
805
802
  const slots = [];
806
803
  for (const item of rawItems) {
807
- const start = MSGraphProvider_1.graphInstant(item.start);
808
- const end = MSGraphProvider_1.graphInstant(item.end);
804
+ const start = GraphInstant(item.start);
805
+ const end = GraphInstant(item.end);
809
806
  if (!start || !end)
810
807
  continue;
811
808
  slots.push({
@@ -895,8 +892,8 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
895
892
  const suggestions = [];
896
893
  for (const raw of rawSuggestions) {
897
894
  const slot = raw.meetingTimeSlot;
898
- const start = MSGraphProvider_1.graphInstant(slot?.start);
899
- const end = MSGraphProvider_1.graphInstant(slot?.end);
895
+ const start = GraphInstant(slot?.start);
896
+ const end = GraphInstant(slot?.end);
900
897
  if (!start || !end)
901
898
  continue;
902
899
  const rawAvailability = raw.attendeeAvailability ?? [];
@@ -1250,6 +1247,11 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
1250
1247
  'DeleteSubscription',
1251
1248
  'ParseNotification',
1252
1249
  'GetEvents',
1250
+ 'CreateEvent',
1251
+ 'UpdateEvent',
1252
+ 'CancelEvent',
1253
+ 'GetEvent',
1254
+ 'SyncEvents',
1253
1255
  'GetFreeBusy',
1254
1256
  'FindMeetingTimes',
1255
1257
  'CreateCalendarEvent',
@@ -1260,6 +1262,166 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
1260
1262
  ];
1261
1263
  }
1262
1264
  // ========================================================================
1265
+ // CALENDAR EVENTS
1266
+ // Every call names its mailbox through params.Target; there is no fallback to accountEmail or
1267
+ // AZURE_ACCOUNT_EMAIL here, so a meeting never lands in the deployment's service mailbox by
1268
+ // accident. Times are requested in UTC (`Prefer: outlook.timezone`), which GraphInstant relies on.
1269
+ //
1270
+ // Permissions: with the app's own client secret, Graph needs the APPLICATION permission
1271
+ // Calendars.ReadWrite (admin-consented; an application access policy can narrow it to some
1272
+ // mailboxes). With a caller-supplied accessToken, the token's own scopes apply: Calendars.ReadWrite
1273
+ // delegated for a user's token, Calendars.Read for a token that only syncs.
1274
+ // ========================================================================
1275
+ /**
1276
+ * Creates an event. With attendees, Graph sends the invitations from the target mailbox, which
1277
+ * becomes the organizer. `IsOnlineMeeting` attaches a Teams meeting.
1278
+ */
1279
+ async CreateEvent(params, credentials) {
1280
+ return this.calendarCall('CreateEvent', params.Target, credentials, (message) => ({ Success: false, ErrorMessage: message }), async (client, mailbox) => {
1281
+ const calendar = params.Target.CalendarID?.trim();
1282
+ const path = calendar ? `${mailbox}/calendars/${encodeURIComponent(calendar)}/events` : `${mailbox}/events`;
1283
+ const created = await client.api(path).header('Prefer', 'outlook.timezone="UTC"').post(BuildGraphEventBody(params.Event));
1284
+ return { Success: true, Event: ToCalendarEvent(created) };
1285
+ });
1286
+ }
1287
+ /** Patches the given fields. Graph sends updates to attendees when the organizer changes a meeting. */
1288
+ async UpdateEvent(params, credentials) {
1289
+ const changeError = CalendarUpdateError(params.Changes);
1290
+ if (changeError)
1291
+ return { Success: false, ErrorMessage: changeError };
1292
+ return this.calendarCall('UpdateEvent', params.Target, credentials, (message) => ({ Success: false, ErrorMessage: message }), async (client, mailbox) => {
1293
+ const path = `${mailbox}/events/${encodeURIComponent(params.ExternalEventID)}`;
1294
+ const updated = await client.api(path).header('Prefer', 'outlook.timezone="UTC"').patch(BuildGraphEventBody(params.Changes));
1295
+ return { Success: true, Event: ToCalendarEvent(updated) };
1296
+ });
1297
+ }
1298
+ /**
1299
+ * Cancels an event.
1300
+ *
1301
+ * THE ORGANIZER CANCELS, ANYONE ELSE DELETES. Graph's `cancel` sends attendees a cancellation
1302
+ * (with the comment) but refuses a non-organizer with a 400. So the event's `isOrganizer` is read
1303
+ * first: the organizer's mailbox cancels, an attendee's mailbox deletes its own copy, which removes
1304
+ * it from that calendar only and tells nobody. An event that is already gone (404) counts as
1305
+ * cancelled, so a retry after a lost reply does not fail. A 404 for the MAILBOX does not: Graph
1306
+ * answers an unknown or mailbox-less user with 404 too, and that cancelled nothing.
1307
+ */
1308
+ async CancelEvent(params, credentials) {
1309
+ const failure = (message, err) => this.getGraphStatusCode(err) === 404 && !this.isMailboxNotFound(err) ? { Success: true } : { Success: false, ErrorMessage: message };
1310
+ return this.calendarCall('CancelEvent', params.Target, credentials, failure, async (client, mailbox) => {
1311
+ const path = `${mailbox}/events/${encodeURIComponent(params.ExternalEventID)}`;
1312
+ const current = await client.api(path).select('isOrganizer').get();
1313
+ if (current?.isOrganizer === false) {
1314
+ await client.api(path).delete();
1315
+ }
1316
+ else {
1317
+ await client.api(`${path}/cancel`).post({ Comment: params.Comment ?? '' });
1318
+ }
1319
+ return { Success: true };
1320
+ });
1321
+ }
1322
+ /** Reads one event with each attendee's response. */
1323
+ async GetEvent(params, credentials) {
1324
+ return this.calendarCall('GetEvent', params.Target, credentials, (message) => ({ Success: false, ErrorMessage: message }), async (client, mailbox) => {
1325
+ const path = `${mailbox}/events/${encodeURIComponent(params.ExternalEventID)}`;
1326
+ const event = await client.api(path).header('Prefer', 'outlook.timezone="UTC"').get();
1327
+ return { Success: true, Event: ToCalendarEvent(event) };
1328
+ });
1329
+ }
1330
+ /**
1331
+ * Reads changes through `calendarView/delta`.
1332
+ *
1333
+ * A full sync needs the window (Graph's delta over a calendar view is always bounded); the delta
1334
+ * link Graph returns at the end carries that window, so later syncs need only the token. Pages are
1335
+ * followed through `@odata.nextLink` until the `@odata.deltaLink`, which is the next token. Graph
1336
+ * answers an expired or unknown token with 410 Gone: that comes back as `ResyncRequired`.
1337
+ */
1338
+ async SyncEvents(params, credentials) {
1339
+ const failure = (message, err) => ({
1340
+ Success: false,
1341
+ Changes: [],
1342
+ ErrorMessage: message,
1343
+ ResyncRequired: !!params.SyncToken && this.isResyncError(err)
1344
+ });
1345
+ return this.calendarCall('SyncEvents', params.Target, credentials, failure, async (client, mailbox) => {
1346
+ const result = { Success: true, Changes: [] };
1347
+ let url = params.SyncToken || this.firstDeltaUrl(mailbox, params);
1348
+ for (let page = 0; url && page < MSGRAPH_MAX_DELTA_PAGES; page++) {
1349
+ const response = await client.api(url).header('Prefer', 'outlook.timezone="UTC"').get();
1350
+ result.Changes.push(...(response?.value ?? []).map(ToCalendarChange));
1351
+ result.NextSyncToken = response?.['@odata.deltaLink'];
1352
+ url = result.NextSyncToken ? undefined : response?.['@odata.nextLink'];
1353
+ }
1354
+ if (!result.NextSyncToken)
1355
+ return failure('Graph delta read ended without a deltaLink; nothing was applied.');
1356
+ for (let i = 0; i < result.Changes.length; i++) {
1357
+ if (result.Changes[i].Kind === 'Removed')
1358
+ result.Changes[i] = await this.confirmRemoval(client, mailbox, result.Changes[i]);
1359
+ }
1360
+ return result;
1361
+ });
1362
+ }
1363
+ /**
1364
+ * Graph lists under `@removed` both an event that was deleted and one added, moved or changed
1365
+ * OUTSIDE the delta's window (see Graph's event: delta). A caller that took every tombstone as a
1366
+ * deletion would cancel a meeting that was only rescheduled past the window. So each one is read:
1367
+ * a 404 is a real removal, anything found comes back as an upsert of the event as it is now.
1368
+ *
1369
+ * ponytail: one GET per tombstone; batch them (Graph $batch, 20 per call) if a calendar's syncs
1370
+ * ever carry many.
1371
+ */
1372
+ async confirmRemoval(client, mailbox, change) {
1373
+ try {
1374
+ const path = `${mailbox}/events/${encodeURIComponent(change.ExternalEventID)}`;
1375
+ const event = await client.api(path).header('Prefer', 'outlook.timezone="UTC"').get();
1376
+ return { Kind: 'Upserted', ExternalEventID: change.ExternalEventID, Event: ToCalendarEvent(event) };
1377
+ }
1378
+ catch (err) {
1379
+ if (this.getGraphStatusCode(err) === 404)
1380
+ return change;
1381
+ throw err;
1382
+ }
1383
+ }
1384
+ /** The first page of a full delta read. Throws when there is no window, which the caller reports. */
1385
+ firstDeltaUrl(mailbox, params) {
1386
+ if (!params.WindowStart || !params.WindowEnd) {
1387
+ throw new Error('a full sync (no SyncToken) needs WindowStart and WindowEnd: Graph only syncs a bounded calendar view');
1388
+ }
1389
+ const calendar = params.Target.CalendarID?.trim();
1390
+ const view = calendar ? `${mailbox}/calendars/${encodeURIComponent(calendar)}/calendarView/delta` : `${mailbox}/calendarView/delta`;
1391
+ const start = encodeURIComponent(params.WindowStart.toISOString());
1392
+ const end = encodeURIComponent(params.WindowEnd.toISOString());
1393
+ return `${view}?startDateTime=${start}&endDateTime=${end}`;
1394
+ }
1395
+ /** True when a Graph 404 is about the mailbox (no such user, or no Exchange mailbox), not the item. */
1396
+ isMailboxNotFound(err) {
1397
+ const code = err && typeof err === 'object' && 'code' in err ? String(err.code) : '';
1398
+ return code === 'ErrorInvalidUser' || code === 'MailboxNotEnabledForRESTAPI';
1399
+ }
1400
+ /** True when Graph refused a delta token as expired or unknown, so the caller must start over. */
1401
+ isResyncError(err) {
1402
+ if (this.getGraphStatusCode(err) === 410)
1403
+ return true;
1404
+ const code = err && typeof err === 'object' && 'code' in err ? String(err.code) : '';
1405
+ return /syncState|resyncRequired/i.test(code);
1406
+ }
1407
+ /**
1408
+ * The shared shape of every calendar call: refuse a missing target before any I/O, build the
1409
+ * client and the mailbox path from the target alone, and turn a thrown error into a result.
1410
+ */
1411
+ async calendarCall(operation, target, credentials, failure, work) {
1412
+ const refusal = CalendarTargetError(operation, target);
1413
+ if (refusal || !target)
1414
+ return failure(refusal ?? `${operation} needs a Target.`);
1415
+ const identifier = target.Identifier.trim();
1416
+ try {
1417
+ const client = this.getGraphClient(this.resolveCredentials(credentials));
1418
+ return await work(client, `${this.getApiUri()}/${encodeURIComponent(identifier)}`);
1419
+ }
1420
+ catch (err) {
1421
+ return failure(`Microsoft Graph ${operation} failed for ${identifier}: ${err instanceof Error ? err.message : String(err)}`, err);
1422
+ }
1423
+ }
1424
+ // ========================================================================
1263
1425
  // PUSH-NOTIFICATION SUBSCRIPTIONS
1264
1426
  // Graph change-notification subscriptions. CRUD rides the existing authenticated
1265
1427
  // client; ParseNotification is pure (no client, no network). The provider is
@@ -2061,7 +2223,7 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
2061
2223
  return effective.toISOString();
2062
2224
  }
2063
2225
  };
2064
- MSGraphProvider = MSGraphProvider_1 = __decorate([
2226
+ MSGraphProvider = __decorate([
2065
2227
  RegisterClass(BaseCommunicationProvider, 'Microsoft Graph'),
2066
2228
  __metadata("design:paramtypes", [])
2067
2229
  ], MSGraphProvider);