@memberjunction/communication-ms-graph 6.2.0-edge.4 → 6.2.0-edge.6

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.
@@ -7,8 +7,7 @@ var __decorate = (this && this.__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,33 +751,480 @@ 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;
762
+ /**
763
+ * Queries free/busy schedule intervals for one or more users via Microsoft Graph
764
+ * `POST /users/{id}/calendar/getSchedule`.
765
+ *
766
+ * @requires MS Graph Scope: Calendars.Read (Application or Delegated)
767
+ */
768
+ async GetFreeBusy(params, credentials) {
769
+ try {
770
+ const creds = this.resolveCredentials(credentials);
771
+ const client = this.getGraphClient(creds);
772
+ const mailbox = this.resolveMailbox('GetFreeBusy', creds, params.Identifier, params.ContextData?.Email, params.Schedules[0]);
773
+ if (!params.Schedules || params.Schedules.length === 0) {
774
+ return {
775
+ Success: false,
776
+ Schedules: [],
777
+ ErrorMessage: 'GetFreeBusy requires at least one email address in Schedules.'
778
+ };
779
+ }
780
+ const path = `${this.getApiUri()}/${encodeURIComponent(mailbox)}/calendar/getSchedule`;
781
+ const body = {
782
+ schedules: params.Schedules,
783
+ startTime: {
784
+ dateTime: params.StartDateTime.toISOString(),
785
+ timeZone: 'UTC'
786
+ },
787
+ endTime: {
788
+ dateTime: params.EndDateTime.toISOString(),
789
+ timeZone: 'UTC'
790
+ },
791
+ availabilityViewInterval: params.AvailabilityViewIntervalMinutes ?? 30
792
+ };
793
+ const response = await client
794
+ .api(path)
795
+ .header('Prefer', 'outlook.timezone="UTC"')
796
+ .post(body);
797
+ const rawSchedules = response?.value ?? [];
798
+ const schedules = rawSchedules.map((raw) => {
799
+ const scheduleId = String(raw.scheduleId ?? '');
800
+ const errorObj = raw.error;
801
+ const rawItems = raw.scheduleItems ?? [];
802
+ const slots = [];
803
+ for (const item of rawItems) {
804
+ const start = GraphInstant(item.start);
805
+ const end = GraphInstant(item.end);
806
+ if (!start || !end)
807
+ continue;
808
+ slots.push({
809
+ StartTime: start,
810
+ EndTime: end,
811
+ Status: this.mapGraphFreeBusyStatus(String(item.status ?? 'busy')),
812
+ Subject: typeof item.subject === 'string' ? item.subject : undefined
813
+ });
814
+ }
815
+ return {
816
+ ScheduleID: scheduleId,
817
+ AvailabilityView: typeof raw.availabilityView === 'string' ? raw.availabilityView : undefined,
818
+ Slots: slots,
819
+ Error: errorObj?.message
820
+ };
821
+ });
822
+ return {
823
+ Success: true,
824
+ Schedules: schedules,
825
+ SourceData: rawSchedules
826
+ };
827
+ }
828
+ catch (ex) {
829
+ LogError('Error getting free/busy schedule via MS Graph', undefined, ex);
830
+ return {
831
+ Success: false,
832
+ Schedules: [],
833
+ ErrorMessage: `Error getting free/busy schedule: ${ex instanceof Error ? ex.message : String(ex)}`
834
+ };
835
+ }
836
+ }
837
+ mapGraphFreeBusyStatus(status) {
838
+ const normalized = status.trim().toLowerCase();
839
+ if (normalized === 'free')
840
+ return 'Free';
841
+ if (normalized === 'tentative')
842
+ return 'Tentative';
843
+ if (normalized === 'oof')
844
+ return 'OutOfOffice';
845
+ if (normalized === 'workingelsewhere')
846
+ return 'WorkingElsewhere';
847
+ if (normalized === 'busy')
848
+ return 'Busy';
849
+ return 'Unknown';
850
+ }
851
+ /**
852
+ * Finds candidate meeting times across attendees via Microsoft Graph
853
+ * `POST /users/{id}/findMeetingTimes`.
854
+ *
855
+ * @requires MS Graph Scope: Calendars.Read.Shared (Delegated) or Calendars.Read (Application where supported)
856
+ */
857
+ async FindMeetingTimes(params, credentials) {
858
+ try {
859
+ const creds = this.resolveCredentials(credentials);
860
+ const client = this.getGraphClient(creds);
861
+ const mailbox = this.resolveMailbox('FindMeetingTimes', creds, params.Identifier, params.ContextData?.Email);
862
+ const path = `${this.getApiUri()}/${encodeURIComponent(mailbox)}/findMeetingTimes`;
863
+ const body = {
864
+ attendees: params.Attendees.map((a) => ({
865
+ type: a.Required === false ? 'optional' : 'required',
866
+ emailAddress: { address: a.Email }
867
+ })),
868
+ timeConstraint: {
869
+ activityDomain: 'work',
870
+ timeSlots: [
871
+ {
872
+ start: {
873
+ dateTime: params.StartDateTime.toISOString(),
874
+ timeZone: 'UTC'
875
+ },
876
+ end: {
877
+ dateTime: params.EndDateTime.toISOString(),
878
+ timeZone: 'UTC'
879
+ }
880
+ }
881
+ ]
882
+ },
883
+ meetingDuration: `PT${Math.max(5, Math.round(params.DurationMinutes))}M`,
884
+ maxCandidates: params.MaxCandidates ?? 5,
885
+ minimumAttendeePercentage: params.MinimumAttendeePercentage ?? 100
886
+ };
887
+ const response = await client
888
+ .api(path)
889
+ .header('Prefer', 'outlook.timezone="UTC"')
890
+ .post(body);
891
+ const rawSuggestions = response?.meetingTimeSuggestions ?? [];
892
+ const suggestions = [];
893
+ for (const raw of rawSuggestions) {
894
+ const slot = raw.meetingTimeSlot;
895
+ const start = GraphInstant(slot?.start);
896
+ const end = GraphInstant(slot?.end);
897
+ if (!start || !end)
898
+ continue;
899
+ const rawAvailability = raw.attendeeAvailability ?? [];
900
+ suggestions.push({
901
+ StartTime: start,
902
+ EndTime: end,
903
+ Confidence: typeof raw.confidence === 'number' ? raw.confidence : 0,
904
+ OrganizerAvailability: typeof raw.organizerAvailability === 'string' ? raw.organizerAvailability : undefined,
905
+ SuggestionReason: typeof raw.suggestionReason === 'string' ? raw.suggestionReason : undefined,
906
+ AttendeeAvailability: rawAvailability.map((a) => {
907
+ const att = a.attendee;
908
+ return {
909
+ Email: att?.emailAddress?.address ?? '',
910
+ Availability: this.mapGraphFreeBusyStatus(String(a.availability ?? 'unknown'))
911
+ };
912
+ })
913
+ });
914
+ }
915
+ return {
916
+ Success: true,
917
+ Suggestions: suggestions,
918
+ EmptySuggestionsReason: typeof response?.emptySuggestionsReason === 'string'
919
+ ? response.emptySuggestionsReason
920
+ : undefined,
921
+ SourceData: response
922
+ };
923
+ }
924
+ catch (ex) {
925
+ LogError('Error finding meeting times via MS Graph', undefined, ex);
926
+ return {
927
+ Success: false,
928
+ Suggestions: [],
929
+ ErrorMessage: `Error finding meeting times: ${ex instanceof Error ? ex.message : String(ex)}`
930
+ };
931
+ }
932
+ }
933
+ /**
934
+ * Creates a calendar event (and optionally sends invitations / creates an online meeting)
935
+ * via Microsoft Graph `POST /users/{id}/events`.
936
+ *
937
+ * @requires MS Graph Scope: Calendars.ReadWrite (Application)
938
+ */
939
+ async CreateCalendarEvent(params, credentials) {
940
+ try {
941
+ const creds = this.resolveCredentials(credentials);
942
+ const client = this.getGraphClient(creds);
943
+ const mailbox = this.resolveMailbox('CreateCalendarEvent', creds, params.Identifier, params.ContextData?.Email);
944
+ const body = {
945
+ subject: params.Subject,
946
+ start: {
947
+ dateTime: params.StartTime.toISOString(),
948
+ timeZone: params.TimeZone ?? 'UTC'
949
+ },
950
+ end: {
951
+ dateTime: params.EndTime.toISOString(),
952
+ timeZone: params.TimeZone ?? 'UTC'
953
+ }
954
+ };
955
+ if (params.Body !== undefined) {
956
+ body.body = {
957
+ contentType: params.IsHTML ? 'HTML' : 'Text',
958
+ content: params.Body
959
+ };
960
+ }
961
+ if (params.Location) {
962
+ body.location = { displayName: params.Location };
963
+ }
964
+ if (params.Attendees && params.Attendees.length > 0) {
965
+ body.attendees = params.Attendees.map((a) => ({
966
+ type: a.Required === false ? 'optional' : 'required',
967
+ emailAddress: {
968
+ address: a.Email,
969
+ name: a.Name
970
+ }
971
+ }));
972
+ }
973
+ if (params.IsOnlineMeeting) {
974
+ body.isOnlineMeeting = true;
975
+ body.onlineMeetingProvider = 'teamsForBusiness';
976
+ }
977
+ if (params.DryRun) {
978
+ LogStatus(`[DryRun] Microsoft Graph: CreateCalendarEvent '${params.Subject}' for ${mailbox} — external call skipped`);
979
+ return {
980
+ Success: true,
981
+ DryRun: true,
982
+ Event: {
983
+ ExternalSystemRecordID: 'DRY_RUN_EVENT_ID',
984
+ SeriesID: null,
985
+ Subject: params.Subject,
986
+ Body: params.Body ?? '',
987
+ StartTime: params.StartTime,
988
+ EndTime: params.EndTime,
989
+ Location: params.Location ?? null,
990
+ Organizer: mailbox.toLowerCase(),
991
+ Attendees: (params.Attendees ?? []).map((a) => a.Email.toLowerCase()),
992
+ IsCancelled: false
993
+ },
994
+ SourceData: body
995
+ };
996
+ }
997
+ const path = `${this.getApiUri()}/${encodeURIComponent(mailbox)}/events`;
998
+ const response = await client
999
+ .api(path)
1000
+ .header('Prefer', 'outlook.timezone="UTC"')
1001
+ .post(body);
1002
+ return {
1003
+ Success: true,
1004
+ Event: response ? this.toGetEventsEvent(response) : undefined,
1005
+ OnlineMeetingUrl: response?.onlineMeeting?.joinUrl ?? response?.onlineMeetingUrl ?? null,
1006
+ SourceData: response
1007
+ };
1008
+ }
1009
+ catch (ex) {
1010
+ LogError('Error creating calendar event via MS Graph', undefined, ex);
1011
+ return {
1012
+ Success: false,
1013
+ ErrorMessage: `Error creating calendar event: ${ex instanceof Error ? ex.message : String(ex)}`
1014
+ };
1015
+ }
1016
+ }
1017
+ /**
1018
+ * Updates an existing calendar event via Microsoft Graph `PATCH /users/{id}/events/{eventId}`.
1019
+ *
1020
+ * @requires MS Graph Scope: Calendars.ReadWrite (Application)
1021
+ */
1022
+ async UpdateCalendarEvent(params, credentials) {
1023
+ try {
1024
+ const creds = this.resolveCredentials(credentials);
1025
+ const client = this.getGraphClient(creds);
1026
+ const mailbox = this.resolveMailbox('UpdateCalendarEvent', creds, params.Identifier, params.ContextData?.Email);
1027
+ const body = {};
1028
+ if (params.Subject !== undefined) {
1029
+ body.subject = params.Subject;
1030
+ }
1031
+ if (params.Body !== undefined) {
1032
+ body.body = {
1033
+ contentType: params.IsHTML ? 'HTML' : 'Text',
1034
+ content: params.Body
1035
+ };
1036
+ }
1037
+ if (params.StartTime) {
1038
+ body.start = {
1039
+ dateTime: params.StartTime.toISOString(),
1040
+ timeZone: params.TimeZone ?? 'UTC'
1041
+ };
1042
+ }
1043
+ if (params.EndTime) {
1044
+ body.end = {
1045
+ dateTime: params.EndTime.toISOString(),
1046
+ timeZone: params.TimeZone ?? 'UTC'
1047
+ };
1048
+ }
1049
+ if (params.Location !== undefined) {
1050
+ body.location = { displayName: params.Location };
1051
+ }
1052
+ if (params.Attendees) {
1053
+ body.attendees = params.Attendees.map((a) => ({
1054
+ type: a.Required === false ? 'optional' : 'required',
1055
+ emailAddress: {
1056
+ address: a.Email,
1057
+ name: a.Name
1058
+ }
1059
+ }));
1060
+ }
1061
+ if (params.DryRun) {
1062
+ LogStatus(`[DryRun] Microsoft Graph: UpdateCalendarEvent '${params.EventID}' for ${mailbox} — external call skipped`);
1063
+ return {
1064
+ Success: true,
1065
+ DryRun: true,
1066
+ SourceData: body
1067
+ };
1068
+ }
1069
+ const path = `${this.getApiUri()}/${encodeURIComponent(mailbox)}/events/${encodeURIComponent(params.EventID)}`;
1070
+ const response = await client
1071
+ .api(path)
1072
+ .header('Prefer', 'outlook.timezone="UTC"')
1073
+ .patch(body);
1074
+ return {
1075
+ Success: true,
1076
+ Event: response ? this.toGetEventsEvent(response) : undefined,
1077
+ SourceData: response
1078
+ };
1079
+ }
1080
+ catch (ex) {
1081
+ LogError('Error updating calendar event via MS Graph', undefined, ex);
1082
+ return {
1083
+ Success: false,
1084
+ ErrorMessage: `Error updating calendar event: ${ex instanceof Error ? ex.message : String(ex)}`
1085
+ };
1086
+ }
1087
+ }
1088
+ /**
1089
+ * Responds to a calendar event invitation (`accept`, `tentativelyAccept`, or `decline`)
1090
+ * via Microsoft Graph `POST /users/{id}/events/{eventId}/{accept|tentativelyAccept|decline}`.
1091
+ *
1092
+ * @requires MS Graph Scope: Calendars.ReadWrite (Application)
1093
+ */
1094
+ async RespondToCalendarEvent(params, credentials) {
1095
+ try {
1096
+ const creds = this.resolveCredentials(credentials);
1097
+ const client = this.getGraphClient(creds);
1098
+ const mailbox = this.resolveMailbox('RespondToCalendarEvent', creds, params.Identifier, params.ContextData?.Email);
1099
+ const actionSegment = params.Response === 'Accept'
1100
+ ? 'accept'
1101
+ : params.Response === 'TentativelyAccept'
1102
+ ? 'tentativelyAccept'
1103
+ : 'decline';
1104
+ const body = {
1105
+ comment: params.Comment ?? '',
1106
+ sendResponse: params.SendResponse ?? true
1107
+ };
1108
+ if (params.DryRun) {
1109
+ LogStatus(`[DryRun] Microsoft Graph: RespondToCalendarEvent (${actionSegment}) '${params.EventID}' for ${mailbox} — external call skipped`);
1110
+ return { Success: true, DryRun: true };
1111
+ }
1112
+ const path = `${this.getApiUri()}/${encodeURIComponent(mailbox)}/events/${encodeURIComponent(params.EventID)}/${actionSegment}`;
1113
+ await client.api(path).post(body);
1114
+ return { Success: true };
1115
+ }
1116
+ catch (ex) {
1117
+ LogError('Error responding to calendar event via MS Graph', undefined, ex);
1118
+ return {
1119
+ Success: false,
1120
+ ErrorMessage: `Error responding to calendar event: ${ex instanceof Error ? ex.message : String(ex)}`
1121
+ };
1122
+ }
1123
+ }
1124
+ /**
1125
+ * Cancels a calendar event organized by the mailbox owner via Microsoft Graph
1126
+ * `POST /users/{id}/events/{eventId}/cancel`.
1127
+ *
1128
+ * @requires MS Graph Scope: Calendars.ReadWrite (Application)
1129
+ */
1130
+ async CancelCalendarEvent(params, credentials) {
1131
+ try {
1132
+ const creds = this.resolveCredentials(credentials);
1133
+ const client = this.getGraphClient(creds);
1134
+ const mailbox = this.resolveMailbox('CancelCalendarEvent', creds, params.Identifier, params.ContextData?.Email);
1135
+ const body = {
1136
+ comment: params.Comment ?? ''
1137
+ };
1138
+ if (params.DryRun) {
1139
+ LogStatus(`[DryRun] Microsoft Graph: CancelCalendarEvent '${params.EventID}' for ${mailbox} — external call skipped`);
1140
+ return { Success: true, DryRun: true };
1141
+ }
1142
+ const path = `${this.getApiUri()}/${encodeURIComponent(mailbox)}/events/${encodeURIComponent(params.EventID)}/cancel`;
1143
+ await client.api(path).post(body);
1144
+ return { Success: true };
1145
+ }
1146
+ catch (ex) {
1147
+ LogError('Error cancelling calendar event via MS Graph', undefined, ex);
1148
+ return {
1149
+ Success: false,
1150
+ ErrorMessage: `Error cancelling calendar event: ${ex instanceof Error ? ex.message : String(ex)}`
1151
+ };
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Performs a lightweight preflight check to verify whether the active Microsoft Graph
1156
+ * enterprise credential is authorized to read mail and/or calendar for the specified mailbox.
1157
+ * Used by enterprise security gates to detect Exchange Application Access Policy restrictions
1158
+ * (`ErrorAccessDenied` / 403) before offering personal mailbox or calendar operations.
1159
+ */
1160
+ async VerifyMailboxAccess(params, credentials) {
1161
+ const identifier = params.Identifier?.trim();
1162
+ if (!identifier) {
1163
+ return {
1164
+ Success: false,
1165
+ Identifier: '',
1166
+ CanReadMail: false,
1167
+ CanReadCalendar: false,
1168
+ ErrorMessage: 'VerifyMailboxAccess requires a non-empty Identifier (mailbox email).'
1169
+ };
1170
+ }
1171
+ try {
1172
+ const creds = this.resolveCredentials(credentials);
1173
+ const client = this.getGraphClient(creds);
1174
+ const checkMail = params.CheckMailRead ?? true;
1175
+ const checkCalendar = params.CheckCalendarRead ?? true;
1176
+ let canReadMail = false;
1177
+ let canReadCalendar = false;
1178
+ let mailErrorMessage;
1179
+ let calendarErrorMessage;
1180
+ if (checkMail) {
1181
+ try {
1182
+ const mailPath = `${this.getApiUri()}/${encodeURIComponent(identifier)}/mailFolders/inbox`;
1183
+ await client.api(mailPath).select('id').get();
1184
+ canReadMail = true;
1185
+ }
1186
+ catch (mailEx) {
1187
+ mailErrorMessage = mailEx instanceof Error ? mailEx.message : String(mailEx);
1188
+ }
1189
+ }
1190
+ if (checkCalendar) {
1191
+ try {
1192
+ const calPath = `${this.getApiUri()}/${encodeURIComponent(identifier)}/calendar`;
1193
+ await client.api(calPath).select('id').get();
1194
+ canReadCalendar = true;
1195
+ }
1196
+ catch (calEx) {
1197
+ calendarErrorMessage = calEx instanceof Error ? calEx.message : String(calEx);
1198
+ }
1199
+ }
1200
+ const overallSuccess = (!checkMail || canReadMail) &&
1201
+ (!checkCalendar || canReadCalendar);
1202
+ return {
1203
+ Success: overallSuccess,
1204
+ Identifier: identifier,
1205
+ CanReadMail: canReadMail,
1206
+ CanReadCalendar: canReadCalendar,
1207
+ MailErrorMessage: mailErrorMessage,
1208
+ CalendarErrorMessage: calendarErrorMessage,
1209
+ ErrorMessage: overallSuccess
1210
+ ? undefined
1211
+ : [mailErrorMessage, calendarErrorMessage].filter(Boolean).join('; ')
1212
+ };
1213
+ }
1214
+ catch (ex) {
1215
+ const msg = ex instanceof Error ? ex.message : String(ex);
1216
+ return {
1217
+ Success: false,
1218
+ Identifier: identifier,
1219
+ CanReadMail: false,
1220
+ CanReadCalendar: false,
1221
+ ErrorMessage: `Error verifying mailbox access for ${identifier}: ${msg}`
1222
+ };
1223
+ }
764
1224
  }
765
1225
  /**
766
1226
  * Returns the list of operations supported by MS Graph provider.
767
- * MS Graph supports all mailbox operations.
1227
+ * MS Graph supports all mailbox and calendar operations.
768
1228
  */
769
1229
  getSupportedOperations() {
770
1230
  return [
@@ -786,10 +1246,182 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
786
1246
  'RenewSubscription',
787
1247
  'DeleteSubscription',
788
1248
  'ParseNotification',
789
- 'GetEvents'
1249
+ 'GetEvents',
1250
+ 'CreateEvent',
1251
+ 'UpdateEvent',
1252
+ 'CancelEvent',
1253
+ 'GetEvent',
1254
+ 'SyncEvents',
1255
+ 'GetFreeBusy',
1256
+ 'FindMeetingTimes',
1257
+ 'CreateCalendarEvent',
1258
+ 'UpdateCalendarEvent',
1259
+ 'RespondToCalendarEvent',
1260
+ 'CancelCalendarEvent',
1261
+ 'VerifyMailboxAccess'
790
1262
  ];
791
1263
  }
792
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
+ // ========================================================================
793
1425
  // PUSH-NOTIFICATION SUBSCRIPTIONS
794
1426
  // Graph change-notification subscriptions. CRUD rides the existing authenticated
795
1427
  // client; ParseNotification is pure (no client, no network). The provider is
@@ -1591,7 +2223,7 @@ let MSGraphProvider = MSGraphProvider_1 = class MSGraphProvider extends BaseComm
1591
2223
  return effective.toISOString();
1592
2224
  }
1593
2225
  };
1594
- MSGraphProvider = MSGraphProvider_1 = __decorate([
2226
+ MSGraphProvider = __decorate([
1595
2227
  RegisterClass(BaseCommunicationProvider, 'Microsoft Graph'),
1596
2228
  __metadata("design:paramtypes", [])
1597
2229
  ], MSGraphProvider);