@dereekb/firebase-server 13.31.0 → 13.33.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.
Files changed (80) hide show
  1. package/calcom/index.cjs.default.js +1 -0
  2. package/calcom/index.cjs.js +1451 -0
  3. package/calcom/index.cjs.mjs +2 -0
  4. package/calcom/index.d.ts +1 -0
  5. package/calcom/index.esm.js +1437 -0
  6. package/calcom/package.json +29 -0
  7. package/calcom/src/index.d.ts +1 -0
  8. package/calcom/src/lib/calcom.oauth.connection.cache.d.ts +49 -0
  9. package/calcom/src/lib/calcom.oauth.connection.config.d.ts +75 -0
  10. package/calcom/src/lib/calcom.oauth.connection.context.d.ts +84 -0
  11. package/calcom/src/lib/calcom.oauth.connection.controller.d.ts +18 -0
  12. package/calcom/src/lib/calcom.oauth.connection.module.d.ts +55 -0
  13. package/calcom/src/lib/calcom.oauth.connection.service.d.ts +33 -0
  14. package/calcom/src/lib/index.d.ts +6 -0
  15. package/discord/index.cjs.default.js +1 -0
  16. package/discord/index.cjs.js +761 -0
  17. package/discord/index.cjs.mjs +2 -0
  18. package/discord/index.d.ts +1 -0
  19. package/discord/index.esm.js +753 -0
  20. package/discord/package.json +29 -0
  21. package/discord/src/index.d.ts +1 -0
  22. package/discord/src/lib/discord.oauth.connection.config.d.ts +69 -0
  23. package/discord/src/lib/discord.oauth.connection.controller.d.ts +18 -0
  24. package/discord/src/lib/discord.oauth.connection.module.d.ts +39 -0
  25. package/discord/src/lib/discord.oauth.connection.service.d.ts +43 -0
  26. package/discord/src/lib/index.d.ts +4 -0
  27. package/index.cjs.js +14 -3
  28. package/index.esm.js +14 -3
  29. package/mailgun/package.json +9 -9
  30. package/mcp/package.json +11 -11
  31. package/model/index.cjs.js +11077 -6072
  32. package/model/index.esm.js +11020 -6081
  33. package/model/package.json +10 -9
  34. package/model/src/lib/index.d.ts +1 -0
  35. package/model/src/lib/mailgun/index.d.ts +1 -0
  36. package/model/src/lib/mailgun/notification.healthcheck.mailgun.d.ts +115 -0
  37. package/model/src/lib/notification/index.d.ts +2 -0
  38. package/model/src/lib/notification/notification.action.server.d.ts +42 -3
  39. package/model/src/lib/notification/notification.error.d.ts +31 -0
  40. package/model/src/lib/notification/notification.healthcheck.d.ts +39 -0
  41. package/model/src/lib/notification/notification.healthcheck.service.d.ts +118 -0
  42. package/model/src/lib/notification/notification.send.service.d.ts +22 -0
  43. package/model/src/lib/userexternalconnection/index.d.ts +8 -0
  44. package/model/src/lib/userexternalconnection/oauth/index.d.ts +7 -0
  45. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.config.d.ts +110 -0
  46. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.controller.d.ts +68 -0
  47. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.error.d.ts +29 -0
  48. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.refresh.d.ts +24 -0
  49. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.registry.d.ts +54 -0
  50. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.service.d.ts +216 -0
  51. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.state.d.ts +114 -0
  52. package/model/src/lib/userexternalconnection/userexternalconnection.accessor.service.d.ts +111 -0
  53. package/model/src/lib/userexternalconnection/userexternalconnection.action.server.d.ts +172 -0
  54. package/model/src/lib/userexternalconnection/userexternalconnection.error.d.ts +44 -0
  55. package/model/src/lib/userexternalconnection/userexternalconnection.module.d.ts +129 -0
  56. package/model/src/lib/userexternalconnection/userexternalconnection.private.d.ts +192 -0
  57. package/model/src/lib/userexternalconnection/userexternalconnection.reader.service.d.ts +157 -0
  58. package/model/src/lib/userexternalconnection/userexternalconnection.refresh.service.d.ts +46 -0
  59. package/oidc/index.cjs.js +104 -78
  60. package/oidc/index.esm.js +104 -78
  61. package/oidc/package.json +10 -10
  62. package/package.json +24 -10
  63. package/src/lib/env/env.config.d.ts +15 -0
  64. package/src/lib/env/env.service.d.ts +7 -0
  65. package/src/lib/nest/env/env.service.d.ts +1 -0
  66. package/test/index.cjs.js +14 -2
  67. package/test/index.esm.js +15 -3
  68. package/test/package.json +11 -11
  69. package/test/src/lib/firebase/firebase.admin.auth.d.ts +1 -1
  70. package/twilio/package.json +8 -8
  71. package/zoho/README.md +8 -0
  72. package/zoho/index.cjs.js +1223 -33
  73. package/zoho/index.esm.js +1212 -36
  74. package/zoho/package.json +12 -9
  75. package/zoho/src/lib/index.d.ts +5 -0
  76. package/zoho/src/lib/zoho.oauth.connection.cache.d.ts +45 -0
  77. package/zoho/src/lib/zoho.oauth.connection.config.d.ts +80 -0
  78. package/zoho/src/lib/zoho.oauth.connection.controller.d.ts +18 -0
  79. package/zoho/src/lib/zoho.oauth.connection.module.d.ts +43 -0
  80. package/zoho/src/lib/zoho.oauth.connection.service.d.ts +107 -0
@@ -0,0 +1,1437 @@
1
+ import { calcomOAuthAuthorizeUrlFactory, CALCOM_OAUTH_SCOPE_DELIMITER, calcomAccessTokenFromTokenResponse, refreshAccessToken, CalcomOAuthAccessTokenError, CalcomOAuthAuthFailureError, CalcomServerFetchResponseError } from '@dereekb/calcom';
2
+ import { CALCOM_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE } from '@dereekb/firebase';
3
+ import { userExternalConnectionOAuthControllerPath, userExternalConnectionOAuthRoutesForGlobalRouteExclude, userExternalConnectionOAuthServiceConfigFactory, UserExternalConnectionOAuthServiceConfig, UserExternalConnectionStateCoder, UserExternalConnectionServerActions, UserExternalConnectionAccessor, AbstractUserExternalConnectionOAuthService, mergeRefreshedUserExternalConnectionCredentials, DEFAULT_USER_EXTERNAL_CONNECTION_REFRESH_FAILURE_ERROR_CODE, userExternalConnectionProviderNotConnectedError, userExternalConnectionCredentialsExpiredError, AbstractUserExternalConnectionOAuthController } from '@dereekb/firebase-server/model';
4
+ import { MS_IN_SECOND, HTTP_UNAUTHORIZED_STATUS_CODE } from '@dereekb/util';
5
+ import { safeToJsDate } from '@dereekb/date';
6
+ import { Injectable, Inject, Logger, Controller } from '@nestjs/common';
7
+ import { CalcomOAuthApi, CalcomApi } from '@dereekb/calcom/nestjs';
8
+ import { FetchResponseError, fetchJsonFunction, returnNullHandleFetchJsonParseErrorFunction } from '@dereekb/util/fetch';
9
+ import { ConfigModule } from '@nestjs/config';
10
+ import { FirebaseServerEnvService } from '@dereekb/firebase-server';
11
+
12
+ function _type_of$3(obj) {
13
+ "@swc/helpers - typeof";
14
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
15
+ }
16
+ function __decorate(decorators, target, key, desc) {
17
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
18
+ if ((typeof Reflect === "undefined" ? "undefined" : _type_of$3(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
19
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
20
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
21
+ }
22
+ function __param(paramIndex, decorator) {
23
+ return function(target, key) {
24
+ decorator(target, key, paramIndex);
25
+ };
26
+ }
27
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
28
+ var e = new Error(message);
29
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
30
+ };
31
+
32
+ function _assert_this_initialized$2(self) {
33
+ if (self === void 0) {
34
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
35
+ }
36
+ return self;
37
+ }
38
+ function _call_super$2(_this, derived, args) {
39
+ derived = _get_prototype_of$2(derived);
40
+ return _possible_constructor_return$2(_this, _is_native_reflect_construct$2() ? Reflect.construct(derived, args || [], _get_prototype_of$2(_this).constructor) : derived.apply(_this, args));
41
+ }
42
+ function _class_call_check$3(instance, Constructor) {
43
+ if (!(instance instanceof Constructor)) {
44
+ throw new TypeError("Cannot call a class as a function");
45
+ }
46
+ }
47
+ function _define_property$3(obj, key, value) {
48
+ if (key in obj) {
49
+ Object.defineProperty(obj, key, {
50
+ value: value,
51
+ enumerable: true,
52
+ configurable: true,
53
+ writable: true
54
+ });
55
+ } else {
56
+ obj[key] = value;
57
+ }
58
+ return obj;
59
+ }
60
+ function _get_prototype_of$2(o) {
61
+ _get_prototype_of$2 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
62
+ return o.__proto__ || Object.getPrototypeOf(o);
63
+ };
64
+ return _get_prototype_of$2(o);
65
+ }
66
+ function _inherits$2(subClass, superClass) {
67
+ if (typeof superClass !== "function" && superClass !== null) {
68
+ throw new TypeError("Super expression must either be null or a function");
69
+ }
70
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
71
+ constructor: {
72
+ value: subClass,
73
+ writable: true,
74
+ configurable: true
75
+ }
76
+ });
77
+ if (superClass) _set_prototype_of$2(subClass, superClass);
78
+ }
79
+ function _object_spread$1(target) {
80
+ for(var i = 1; i < arguments.length; i++){
81
+ var source = arguments[i] != null ? arguments[i] : {};
82
+ var ownKeys = Object.keys(source);
83
+ if (typeof Object.getOwnPropertySymbols === "function") {
84
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
85
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
86
+ }));
87
+ }
88
+ ownKeys.forEach(function(key) {
89
+ _define_property$3(target, key, source[key]);
90
+ });
91
+ }
92
+ return target;
93
+ }
94
+ function ownKeys$1(object, enumerableOnly) {
95
+ var keys = Object.keys(object);
96
+ if (Object.getOwnPropertySymbols) {
97
+ var symbols = Object.getOwnPropertySymbols(object);
98
+ keys.push.apply(keys, symbols);
99
+ }
100
+ return keys;
101
+ }
102
+ function _object_spread_props$1(target, source) {
103
+ source = source != null ? source : {};
104
+ if (Object.getOwnPropertyDescriptors) {
105
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
106
+ } else {
107
+ ownKeys$1(Object(source)).forEach(function(key) {
108
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
109
+ });
110
+ }
111
+ return target;
112
+ }
113
+ function _possible_constructor_return$2(self, call) {
114
+ if (call && (_type_of$2(call) === "object" || typeof call === "function")) {
115
+ return call;
116
+ }
117
+ return _assert_this_initialized$2(self);
118
+ }
119
+ function _set_prototype_of$2(o, p) {
120
+ _set_prototype_of$2 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
121
+ o.__proto__ = p;
122
+ return o;
123
+ };
124
+ return _set_prototype_of$2(o, p);
125
+ }
126
+ function _type_of$2(obj) {
127
+ "@swc/helpers - typeof";
128
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
129
+ }
130
+ function _is_native_reflect_construct$2() {
131
+ try {
132
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
133
+ } catch (_) {}
134
+ return (_is_native_reflect_construct$2 = function() {
135
+ return !!result;
136
+ })();
137
+ }
138
+ /**
139
+ * Controller path the Cal.com external-connection OAuth endpoints are mounted at.
140
+ *
141
+ * Derived from the framework's path factory, the same expression the redirect URI and the
142
+ * global-prefix exclusion are built from, so the three cannot drift apart.
143
+ */ var CALCOM_USER_EXTERNAL_CONNECTION_OAUTH_CONTROLLER_PATH = userExternalConnectionOAuthControllerPath(CALCOM_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE);
144
+ /**
145
+ * Routes to exclude from an app's global API route prefix so the Cal.com callback controller stays
146
+ * mounted at `/oauth/calcom/*`.
147
+ *
148
+ * Spread this into the `exclude` list of the app's `globalApiRoutePrefix` config, alongside
149
+ * `FIREBASE_SERVER_OIDC_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE`.
150
+ */ var CALCOM_USER_EXTERNAL_CONNECTION_OAUTH_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE = userExternalConnectionOAuthRoutesForGlobalRouteExclude(CALCOM_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE);
151
+ /**
152
+ * The scopes requested when an app does not declare its own.
153
+ *
154
+ * Declared in code, deliberately NOT read from the environment: the set to request follows from what
155
+ * the integration actually does, so it is a property of the code rather than of a deployment.
156
+ * Requesting less than the code uses does not make it work — it moves the failure from the consent
157
+ * screen to the first API call.
158
+ *
159
+ * Least privilege for a per-user calendar connect: read which meeting types exist, read the user's
160
+ * availability, and read/write bookings. Excludes `EVENT_TYPE_WRITE` and `SCHEDULE_WRITE` —
161
+ * connecting a calendar does not involve editing the user's meeting types or availability — and
162
+ * `PROFILE_READ`, which is only needed to label the connection with the Cal.com account it belongs
163
+ * to.
164
+ *
165
+ * Cal.com refuses the authorize request outright when the requested set exceeds what the OAuth
166
+ * client is registered for ("Requested scope exceeds the client's registered scopes"). That is a
167
+ * registration problem: register the scopes the code needs, rather than narrowing the request to fit.
168
+ * An app whose integration genuinely does less can declare its own set on the module metadata, in
169
+ * code where it is reviewable.
170
+ */ var DEFAULT_CALCOM_OAUTH_SCOPES = [
171
+ 'EVENT_TYPE_READ',
172
+ 'SCHEDULE_READ',
173
+ 'BOOKING_READ',
174
+ 'BOOKING_WRITE'
175
+ ];
176
+ /**
177
+ * Configuration for the {@link CalcomUserExternalConnectionOAuthService}.
178
+ *
179
+ * Extends the framework config with the one thing that is Cal.com's own — which scopes to request.
180
+ */ var CalcomUserExternalConnectionOAuthServiceConfig = /*#__PURE__*/ function(UserExternalConnectionOAuthServiceConfig) {
181
+ _inherits$2(CalcomUserExternalConnectionOAuthServiceConfig, UserExternalConnectionOAuthServiceConfig);
182
+ function CalcomUserExternalConnectionOAuthServiceConfig() {
183
+ _class_call_check$3(this, CalcomUserExternalConnectionOAuthServiceConfig);
184
+ var _this;
185
+ _this = _call_super$2(this, CalcomUserExternalConnectionOAuthServiceConfig, arguments), _define_property$3(_this, "scopes", void 0);
186
+ return _this;
187
+ }
188
+ return CalcomUserExternalConnectionOAuthServiceConfig;
189
+ }(UserExternalConnectionOAuthServiceConfig);
190
+ /**
191
+ * Builds the Cal.com connect flow's configuration from the app's configured origins.
192
+ *
193
+ * Nothing here is read from the environment as a value: the redirect URI is derived from the app's
194
+ * OAuth origin plus the mounted controller path, and the return URLs from the app URL plus
195
+ * code-declared paths. Registering Cal.com therefore adds no deployment configuration beyond the
196
+ * client credentials themselves.
197
+ *
198
+ * @param config - The env service, the return paths, and the optional scope override.
199
+ * @returns The validated service configuration.
200
+ */ function calcomUserExternalConnectionOAuthServiceConfigFactory(config) {
201
+ var envService = config.envService, successPath = config.successPath, failurePath = config.failurePath, scopes = config.scopes;
202
+ var baseConfig = userExternalConnectionOAuthServiceConfigFactory({
203
+ envService: envService,
204
+ providerType: CALCOM_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE,
205
+ successPath: successPath,
206
+ failurePath: failurePath
207
+ });
208
+ return _object_spread_props$1(_object_spread$1({}, baseConfig), {
209
+ scopes: scopes !== null && scopes !== void 0 ? scopes : DEFAULT_CALCOM_OAUTH_SCOPES
210
+ });
211
+ }
212
+
213
+ function _assert_this_initialized$1(self) {
214
+ if (self === void 0) {
215
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
216
+ }
217
+ return self;
218
+ }
219
+ function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
220
+ try {
221
+ var info = gen[key](arg);
222
+ var value = info.value;
223
+ } catch (error) {
224
+ reject(error);
225
+ return;
226
+ }
227
+ if (info.done) {
228
+ resolve(value);
229
+ } else {
230
+ Promise.resolve(value).then(_next, _throw);
231
+ }
232
+ }
233
+ function _async_to_generator$2(fn) {
234
+ return function() {
235
+ var self = this, args = arguments;
236
+ return new Promise(function(resolve, reject) {
237
+ var gen = fn.apply(self, args);
238
+ function _next(value) {
239
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
240
+ }
241
+ function _throw(err) {
242
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
243
+ }
244
+ _next(undefined);
245
+ });
246
+ };
247
+ }
248
+ function _call_super$1(_this, derived, args) {
249
+ derived = _get_prototype_of$1(derived);
250
+ return _possible_constructor_return$1(_this, _is_native_reflect_construct$1() ? Reflect.construct(derived, [], _get_prototype_of$1(_this).constructor) : derived.apply(_this, args));
251
+ }
252
+ function _class_call_check$2(instance, Constructor) {
253
+ if (!(instance instanceof Constructor)) {
254
+ throw new TypeError("Cannot call a class as a function");
255
+ }
256
+ }
257
+ function _defineProperties(target, props) {
258
+ for(var i = 0; i < props.length; i++){
259
+ var descriptor = props[i];
260
+ descriptor.enumerable = descriptor.enumerable || false;
261
+ descriptor.configurable = true;
262
+ if ("value" in descriptor) descriptor.writable = true;
263
+ Object.defineProperty(target, descriptor.key, descriptor);
264
+ }
265
+ }
266
+ function _create_class(Constructor, protoProps, staticProps) {
267
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
268
+ return Constructor;
269
+ }
270
+ function _define_property$2(obj, key, value) {
271
+ if (key in obj) {
272
+ Object.defineProperty(obj, key, {
273
+ value: value,
274
+ enumerable: true,
275
+ configurable: true,
276
+ writable: true
277
+ });
278
+ } else {
279
+ obj[key] = value;
280
+ }
281
+ return obj;
282
+ }
283
+ function _get_prototype_of$1(o) {
284
+ _get_prototype_of$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
285
+ return o.__proto__ || Object.getPrototypeOf(o);
286
+ };
287
+ return _get_prototype_of$1(o);
288
+ }
289
+ function _inherits$1(subClass, superClass) {
290
+ if (typeof superClass !== "function" && superClass !== null) {
291
+ throw new TypeError("Super expression must either be null or a function");
292
+ }
293
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
294
+ constructor: {
295
+ value: subClass,
296
+ writable: true,
297
+ configurable: true
298
+ }
299
+ });
300
+ if (superClass) _set_prototype_of$1(subClass, superClass);
301
+ }
302
+ function _possible_constructor_return$1(self, call) {
303
+ if (call && (_type_of$1(call) === "object" || typeof call === "function")) {
304
+ return call;
305
+ }
306
+ return _assert_this_initialized$1(self);
307
+ }
308
+ function _set_prototype_of$1(o, p) {
309
+ _set_prototype_of$1 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
310
+ o.__proto__ = p;
311
+ return o;
312
+ };
313
+ return _set_prototype_of$1(o, p);
314
+ }
315
+ function _type_of$1(obj) {
316
+ "@swc/helpers - typeof";
317
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
318
+ }
319
+ function _is_native_reflect_construct$1() {
320
+ try {
321
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
322
+ } catch (_) {}
323
+ return (_is_native_reflect_construct$1 = function() {
324
+ return !!result;
325
+ })();
326
+ }
327
+ function _ts_generator$2(thisArg, body) {
328
+ var f, y, t, _ = {
329
+ label: 0,
330
+ sent: function() {
331
+ if (t[0] & 1) throw t[1];
332
+ return t[1];
333
+ },
334
+ trys: [],
335
+ ops: []
336
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
337
+ return d(g, "next", {
338
+ value: verb(0)
339
+ }), d(g, "throw", {
340
+ value: verb(1)
341
+ }), d(g, "return", {
342
+ value: verb(2)
343
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
344
+ value: function() {
345
+ return this;
346
+ }
347
+ }), g;
348
+ function verb(n) {
349
+ return function(v) {
350
+ return step([
351
+ n,
352
+ v
353
+ ]);
354
+ };
355
+ }
356
+ function step(op) {
357
+ if (f) throw new TypeError("Generator is already executing.");
358
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
359
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
360
+ if (y = 0, t) op = [
361
+ op[0] & 2,
362
+ t.value
363
+ ];
364
+ switch(op[0]){
365
+ case 0:
366
+ case 1:
367
+ t = op;
368
+ break;
369
+ case 4:
370
+ _.label++;
371
+ return {
372
+ value: op[1],
373
+ done: false
374
+ };
375
+ case 5:
376
+ _.label++;
377
+ y = op[1];
378
+ op = [
379
+ 0
380
+ ];
381
+ continue;
382
+ case 7:
383
+ op = _.ops.pop();
384
+ _.trys.pop();
385
+ continue;
386
+ default:
387
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
388
+ _ = 0;
389
+ continue;
390
+ }
391
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
392
+ _.label = op[1];
393
+ break;
394
+ }
395
+ if (op[0] === 6 && _.label < t[1]) {
396
+ _.label = t[1];
397
+ t = op;
398
+ break;
399
+ }
400
+ if (t && _.label < t[2]) {
401
+ _.label = t[2];
402
+ _.ops.push(op);
403
+ break;
404
+ }
405
+ if (t[2]) _.ops.pop();
406
+ _.trys.pop();
407
+ continue;
408
+ }
409
+ op = body.call(thisArg, _);
410
+ } catch (e) {
411
+ op = [
412
+ 6,
413
+ e
414
+ ];
415
+ y = 0;
416
+ } finally{
417
+ f = t = 0;
418
+ }
419
+ if (op[0] & 5) throw op[1];
420
+ return {
421
+ value: op[0] ? op[1] : void 0,
422
+ done: true
423
+ };
424
+ }
425
+ }
426
+ /**
427
+ * Maps an exchanged Cal.com token to the credentials stored on the private connection document.
428
+ *
429
+ * The `refreshToken` written here is the rotated one from the exchange — Cal.com invalidates the
430
+ * token each use, so persisting the one we sent would break the next refresh.
431
+ *
432
+ * @param accessToken - The exchanged Cal.com access token.
433
+ * @returns The credentials to store.
434
+ */ function calcomUserExternalConnectionCredentials(accessToken) {
435
+ var token = accessToken.accessToken, refreshToken = accessToken.refreshToken, expiresAt = accessToken.expiresAt, scope = accessToken.scope;
436
+ // split on the same delimiter the authorize request joins with, so the round trip stays symmetric
437
+ var scopes = scope ? scope.split(CALCOM_OAUTH_SCOPE_DELIMITER).filter(function(x) {
438
+ return x.length > 0;
439
+ }) : undefined;
440
+ return {
441
+ accessToken: token,
442
+ refreshToken: refreshToken,
443
+ tokenType: 'Bearer',
444
+ issuedAt: new Date().toISOString(),
445
+ expiresAt: expiresAt.toISOString(),
446
+ scopes: scopes
447
+ };
448
+ }
449
+ /**
450
+ * Cal.com's half of the external-connection authorization-code handoff.
451
+ *
452
+ * Everything else — resolving who is connecting, surfacing a refusal, persisting the credentials,
453
+ * choosing the redirect — is the framework's.
454
+ */ var CalcomUserExternalConnectionOAuthService = /*#__PURE__*/ function(AbstractUserExternalConnectionOAuthService) {
455
+ _inherits$1(CalcomUserExternalConnectionOAuthService, AbstractUserExternalConnectionOAuthService);
456
+ function CalcomUserExternalConnectionOAuthService(config, stateCoder, userExternalConnectionActions, userExternalConnectionAccessor, oauthApi) {
457
+ _class_call_check$2(this, CalcomUserExternalConnectionOAuthService);
458
+ var _this;
459
+ _this = _call_super$1(this, CalcomUserExternalConnectionOAuthService), _define_property$2(_this, "config", void 0), _define_property$2(_this, "stateCoder", void 0), _define_property$2(_this, "userExternalConnectionActions", void 0), _define_property$2(_this, "userExternalConnectionAccessor", void 0), _define_property$2(_this, "oauthApi", void 0), _define_property$2(_this, "authorizeUrlFactory", void 0);
460
+ _this.config = config;
461
+ _this.stateCoder = stateCoder;
462
+ _this.userExternalConnectionActions = userExternalConnectionActions;
463
+ _this.userExternalConnectionAccessor = userExternalConnectionAccessor;
464
+ _this.oauthApi = oauthApi;
465
+ var scopes = config.scopes, userExternalConnectionOAuth = config.userExternalConnectionOAuth;
466
+ // read through the api rather than injecting CalcomOAuthServiceConfig directly, which the OAuth
467
+ // module does not export to its dependents
468
+ var clientId = oauthApi.config.calcomOAuth.clientId;
469
+ // CalcomOAuthServiceConfig accepts an api-key-only configuration, which has no client id — that
470
+ // would otherwise compose an authorize URL carrying `client_id=undefined` and fail at the
471
+ // consent screen rather than at startup
472
+ if (!clientId) {
473
+ throw new Error('CalcomUserExternalConnectionOAuthService requires a Cal.com OAuth clientId (CALCOM_CLIENT_ID). An api-key-only Cal.com configuration cannot run the per-user connect flow.');
474
+ }
475
+ _this.authorizeUrlFactory = calcomOAuthAuthorizeUrlFactory({
476
+ clientId: clientId,
477
+ redirectUri: userExternalConnectionOAuth.redirectUri,
478
+ scopes: scopes
479
+ });
480
+ return _this;
481
+ }
482
+ _create_class(CalcomUserExternalConnectionOAuthService, [
483
+ {
484
+ key: "authorizeUrlForState",
485
+ value: function authorizeUrlForState(state) {
486
+ return this.authorizeUrlFactory({
487
+ state: state
488
+ });
489
+ }
490
+ },
491
+ {
492
+ key: "credentialsForAuthorizationCode",
493
+ value: function credentialsForAuthorizationCode(input) {
494
+ return _async_to_generator$2(function() {
495
+ var accessToken;
496
+ return _ts_generator$2(this, function(_state) {
497
+ switch(_state.label){
498
+ case 0:
499
+ return [
500
+ 4,
501
+ this.oauthApi.exchangeAuthorizationCodeToAccessToken({
502
+ code: input.code,
503
+ redirectUri: input.redirectUri
504
+ })
505
+ ];
506
+ case 1:
507
+ accessToken = _state.sent();
508
+ return [
509
+ 2,
510
+ calcomUserExternalConnectionCredentials(accessToken)
511
+ ];
512
+ }
513
+ });
514
+ }).call(this);
515
+ }
516
+ },
517
+ {
518
+ key: "refreshCredentials",
519
+ value: function refreshCredentials(input) {
520
+ return _async_to_generator$2(function() {
521
+ var refreshToken, response;
522
+ return _ts_generator$2(this, function(_state) {
523
+ switch(_state.label){
524
+ case 0:
525
+ refreshToken = input.credentials.refreshToken;
526
+ if (!refreshToken) {
527
+ throw new Error('CalcomUserExternalConnectionOAuthService.refreshCredentials: the stored credentials carry no refresh token.');
528
+ }
529
+ return [
530
+ 4,
531
+ refreshAccessToken(this.oauthApi.oauthContext)({
532
+ refreshToken: refreshToken
533
+ })
534
+ ];
535
+ case 1:
536
+ response = _state.sent();
537
+ return [
538
+ 2,
539
+ calcomUserExternalConnectionCredentials(calcomAccessTokenFromTokenResponse(response))
540
+ ];
541
+ }
542
+ });
543
+ }).call(this);
544
+ }
545
+ }
546
+ ]);
547
+ return CalcomUserExternalConnectionOAuthService;
548
+ }(AbstractUserExternalConnectionOAuthService);
549
+ CalcomUserExternalConnectionOAuthService = __decorate([
550
+ Injectable(),
551
+ __param(0, Inject(CalcomUserExternalConnectionOAuthServiceConfig)),
552
+ __param(1, Inject(UserExternalConnectionStateCoder)),
553
+ __param(2, Inject(UserExternalConnectionServerActions)),
554
+ __param(3, Inject(UserExternalConnectionAccessor)),
555
+ __param(4, Inject(CalcomOAuthApi))
556
+ ], CalcomUserExternalConnectionOAuthService);
557
+
558
+ function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
559
+ try {
560
+ var info = gen[key](arg);
561
+ var value = info.value;
562
+ } catch (error) {
563
+ reject(error);
564
+ return;
565
+ }
566
+ if (info.done) {
567
+ resolve(value);
568
+ } else {
569
+ Promise.resolve(value).then(_next, _throw);
570
+ }
571
+ }
572
+ function _async_to_generator$1(fn) {
573
+ return function() {
574
+ var self = this, args = arguments;
575
+ return new Promise(function(resolve, reject) {
576
+ var gen = fn.apply(self, args);
577
+ function _next(value) {
578
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
579
+ }
580
+ function _throw(err) {
581
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
582
+ }
583
+ _next(undefined);
584
+ });
585
+ };
586
+ }
587
+ function _ts_generator$1(thisArg, body) {
588
+ var f, y, t, _ = {
589
+ label: 0,
590
+ sent: function() {
591
+ if (t[0] & 1) throw t[1];
592
+ return t[1];
593
+ },
594
+ trys: [],
595
+ ops: []
596
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
597
+ return d(g, "next", {
598
+ value: verb(0)
599
+ }), d(g, "throw", {
600
+ value: verb(1)
601
+ }), d(g, "return", {
602
+ value: verb(2)
603
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
604
+ value: function() {
605
+ return this;
606
+ }
607
+ }), g;
608
+ function verb(n) {
609
+ return function(v) {
610
+ return step([
611
+ n,
612
+ v
613
+ ]);
614
+ };
615
+ }
616
+ function step(op) {
617
+ if (f) throw new TypeError("Generator is already executing.");
618
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
619
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
620
+ if (y = 0, t) op = [
621
+ op[0] & 2,
622
+ t.value
623
+ ];
624
+ switch(op[0]){
625
+ case 0:
626
+ case 1:
627
+ t = op;
628
+ break;
629
+ case 4:
630
+ _.label++;
631
+ return {
632
+ value: op[1],
633
+ done: false
634
+ };
635
+ case 5:
636
+ _.label++;
637
+ y = op[1];
638
+ op = [
639
+ 0
640
+ ];
641
+ continue;
642
+ case 7:
643
+ op = _.ops.pop();
644
+ _.trys.pop();
645
+ continue;
646
+ default:
647
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
648
+ _ = 0;
649
+ continue;
650
+ }
651
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
652
+ _.label = op[1];
653
+ break;
654
+ }
655
+ if (op[0] === 6 && _.label < t[1]) {
656
+ _.label = t[1];
657
+ t = op;
658
+ break;
659
+ }
660
+ if (t && _.label < t[2]) {
661
+ _.label = t[2];
662
+ _.ops.push(op);
663
+ break;
664
+ }
665
+ if (t[2]) _.ops.pop();
666
+ _.trys.pop();
667
+ continue;
668
+ }
669
+ op = body.call(thisArg, _);
670
+ } catch (e) {
671
+ op = [
672
+ 6,
673
+ e
674
+ ];
675
+ y = 0;
676
+ } finally{
677
+ f = t = 0;
678
+ }
679
+ if (op[0] & 5) throw op[1];
680
+ return {
681
+ value: op[0] ? op[1] : void 0,
682
+ done: true
683
+ };
684
+ }
685
+ }
686
+ /**
687
+ * Maps stored connection credentials to a {@link CalcomAccessToken}.
688
+ *
689
+ * @param credentials - The credentials stored for the `calcom` provider.
690
+ * @returns The equivalent Cal.com access token, or null when the credentials cannot form one.
691
+ */ function calcomAccessTokenFromUserExternalConnectionCredentials(credentials) {
692
+ var expiresAt = safeToJsDate(credentials === null || credentials === void 0 ? void 0 : credentials.expiresAt);
693
+ var result;
694
+ // Cal.com's token type requires all four, and its factory reads `expiresAt` to decide whether to
695
+ // refresh — a token synthesized without one would be treated as valid forever
696
+ if ((credentials === null || credentials === void 0 ? void 0 : credentials.refreshToken) && expiresAt != null) {
697
+ var _ref, _credentials_scopes;
698
+ var issuedAt = safeToJsDate(credentials.issuedAt);
699
+ var expiresIn = Math.round((expiresAt.getTime() - ((_ref = issuedAt === null || issuedAt === void 0 ? void 0 : issuedAt.getTime()) !== null && _ref !== void 0 ? _ref : Date.now())) / MS_IN_SECOND);
700
+ result = {
701
+ accessToken: credentials.accessToken,
702
+ refreshToken: credentials.refreshToken,
703
+ // re-joined on the delimiter the authorize request splits on, so the round trip stays symmetric
704
+ scope: ((_credentials_scopes = credentials.scopes) !== null && _credentials_scopes !== void 0 ? _credentials_scopes : []).join(CALCOM_OAUTH_SCOPE_DELIMITER),
705
+ expiresIn: expiresIn,
706
+ expiresAt: expiresAt
707
+ };
708
+ }
709
+ return result;
710
+ }
711
+ /**
712
+ * Creates a {@link CalcomAccessTokenCache} backed by a user's UserExternalConnection pair.
713
+ *
714
+ * This is what keeps a Cal.com connection working past its first refresh. Cal.com invalidates a
715
+ * refresh token on every use and returns a rotated one, but it hands that rotated token to its
716
+ * `CalcomAccessTokenCache` — not back to us. With the default in-memory or file cache, the token
717
+ * stored on `uecp` is spent the first time it is used: nothing looks wrong, the entry stays
718
+ * `connected`, and the next process that starts with a cold cache replays a dead token.
719
+ *
720
+ * Pointing the cache at the connection pair makes the pair the single store of record, so a rotation
721
+ * is durable the moment it happens.
722
+ *
723
+ * Deliberately NOT registered as a `CalcomOAuthAccessTokenCacheService`: that service's `cacheForKey`
724
+ * is keyed by an opaque string, whereas this cache is per-user and needs a uid. Build one per user at
725
+ * the call site and pass it in explicitly.
726
+ *
727
+ * @param config - The accessor, the actions, and the user the cache is for.
728
+ * @returns A CalcomAccessTokenCache reading and writing the user's connection pair.
729
+ */ function userExternalConnectionCalcomAccessTokenCache(config) {
730
+ var accessor = config.accessor, actions = config.actions, uid = config.uid;
731
+ var providerType = CALCOM_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE;
732
+ var connection = accessor.accessorForUser({
733
+ uid: uid
734
+ })(providerType);
735
+ function loadCachedToken() {
736
+ return _async_to_generator$1(function() {
737
+ var credentials;
738
+ return _ts_generator$1(this, function(_state) {
739
+ switch(_state.label){
740
+ case 0:
741
+ return [
742
+ 4,
743
+ connection.readUserExternalConnectionCredentials()
744
+ ];
745
+ case 1:
746
+ credentials = _state.sent();
747
+ return [
748
+ 2,
749
+ calcomAccessTokenFromUserExternalConnectionCredentials(credentials)
750
+ ];
751
+ }
752
+ });
753
+ })();
754
+ }
755
+ function updateCachedToken(accessToken) {
756
+ return _async_to_generator$1(function() {
757
+ var previous, refreshed, credentials;
758
+ return _ts_generator$1(this, function(_state) {
759
+ switch(_state.label){
760
+ case 0:
761
+ return [
762
+ 4,
763
+ connection.readUserExternalConnectionCredentials()
764
+ ];
765
+ case 1:
766
+ previous = _state.sent();
767
+ refreshed = calcomUserExternalConnectionCredentials(accessToken);
768
+ // merged rather than written verbatim, because the paired write replaces the provider's credentials
769
+ // wholesale and Cal.com's token carries no account id or label
770
+ credentials = previous == null ? refreshed : mergeRefreshedUserExternalConnectionCredentials({
771
+ previous: previous,
772
+ refreshed: refreshed
773
+ });
774
+ return [
775
+ 4,
776
+ actions.refreshUserExternalConnectionCredentials({
777
+ uid: uid,
778
+ providerType: providerType,
779
+ credentials: credentials
780
+ })
781
+ ];
782
+ case 2:
783
+ _state.sent();
784
+ return [
785
+ 2
786
+ ];
787
+ }
788
+ });
789
+ })();
790
+ }
791
+ return {
792
+ loadCachedToken: loadCachedToken,
793
+ updateCachedToken: updateCachedToken
794
+ };
795
+ }
796
+
797
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
798
+ try {
799
+ var info = gen[key](arg);
800
+ var value = info.value;
801
+ } catch (error) {
802
+ reject(error);
803
+ return;
804
+ }
805
+ if (info.done) {
806
+ resolve(value);
807
+ } else {
808
+ Promise.resolve(value).then(_next, _throw);
809
+ }
810
+ }
811
+ function _async_to_generator(fn) {
812
+ return function() {
813
+ var self = this, args = arguments;
814
+ return new Promise(function(resolve, reject) {
815
+ var gen = fn.apply(self, args);
816
+ function _next(value) {
817
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
818
+ }
819
+ function _throw(err) {
820
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
821
+ }
822
+ _next(undefined);
823
+ });
824
+ };
825
+ }
826
+ function _class_call_check$1(instance, Constructor) {
827
+ if (!(instance instanceof Constructor)) {
828
+ throw new TypeError("Cannot call a class as a function");
829
+ }
830
+ }
831
+ function _define_property$1(obj, key, value) {
832
+ if (key in obj) {
833
+ Object.defineProperty(obj, key, {
834
+ value: value,
835
+ enumerable: true,
836
+ configurable: true,
837
+ writable: true
838
+ });
839
+ } else {
840
+ obj[key] = value;
841
+ }
842
+ return obj;
843
+ }
844
+ function _instanceof(left, right) {
845
+ "@swc/helpers - instanceof";
846
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
847
+ return !!right[Symbol.hasInstance](left);
848
+ } else {
849
+ return left instanceof right;
850
+ }
851
+ }
852
+ function _object_spread(target) {
853
+ for(var i = 1; i < arguments.length; i++){
854
+ var source = arguments[i] != null ? arguments[i] : {};
855
+ var ownKeys = Object.keys(source);
856
+ if (typeof Object.getOwnPropertySymbols === "function") {
857
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
858
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
859
+ }));
860
+ }
861
+ ownKeys.forEach(function(key) {
862
+ _define_property$1(target, key, source[key]);
863
+ });
864
+ }
865
+ return target;
866
+ }
867
+ function ownKeys(object, enumerableOnly) {
868
+ var keys = Object.keys(object);
869
+ if (Object.getOwnPropertySymbols) {
870
+ var symbols = Object.getOwnPropertySymbols(object);
871
+ keys.push.apply(keys, symbols);
872
+ }
873
+ return keys;
874
+ }
875
+ function _object_spread_props(target, source) {
876
+ source = source != null ? source : {};
877
+ if (Object.getOwnPropertyDescriptors) {
878
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
879
+ } else {
880
+ ownKeys(Object(source)).forEach(function(key) {
881
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
882
+ });
883
+ }
884
+ return target;
885
+ }
886
+ function _ts_generator(thisArg, body) {
887
+ var f, y, t, _ = {
888
+ label: 0,
889
+ sent: function() {
890
+ if (t[0] & 1) throw t[1];
891
+ return t[1];
892
+ },
893
+ trys: [],
894
+ ops: []
895
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
896
+ return d(g, "next", {
897
+ value: verb(0)
898
+ }), d(g, "throw", {
899
+ value: verb(1)
900
+ }), d(g, "return", {
901
+ value: verb(2)
902
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
903
+ value: function() {
904
+ return this;
905
+ }
906
+ }), g;
907
+ function verb(n) {
908
+ return function(v) {
909
+ return step([
910
+ n,
911
+ v
912
+ ]);
913
+ };
914
+ }
915
+ function step(op) {
916
+ if (f) throw new TypeError("Generator is already executing.");
917
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
918
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
919
+ if (y = 0, t) op = [
920
+ op[0] & 2,
921
+ t.value
922
+ ];
923
+ switch(op[0]){
924
+ case 0:
925
+ case 1:
926
+ t = op;
927
+ break;
928
+ case 4:
929
+ _.label++;
930
+ return {
931
+ value: op[1],
932
+ done: false
933
+ };
934
+ case 5:
935
+ _.label++;
936
+ y = op[1];
937
+ op = [
938
+ 0
939
+ ];
940
+ continue;
941
+ case 7:
942
+ op = _.ops.pop();
943
+ _.trys.pop();
944
+ continue;
945
+ default:
946
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
947
+ _ = 0;
948
+ continue;
949
+ }
950
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
951
+ _.label = op[1];
952
+ break;
953
+ }
954
+ if (op[0] === 6 && _.label < t[1]) {
955
+ _.label = t[1];
956
+ t = op;
957
+ break;
958
+ }
959
+ if (t && _.label < t[2]) {
960
+ _.label = t[2];
961
+ _.ops.push(op);
962
+ break;
963
+ }
964
+ if (t[2]) _.ops.pop();
965
+ _.trys.pop();
966
+ continue;
967
+ }
968
+ op = body.call(thisArg, _);
969
+ } catch (e) {
970
+ op = [
971
+ 6,
972
+ e
973
+ ];
974
+ y = 0;
975
+ } finally{
976
+ f = t = 0;
977
+ }
978
+ if (op[0] & 5) throw op[1];
979
+ return {
980
+ value: op[0] ? op[1] : void 0,
981
+ done: true
982
+ };
983
+ }
984
+ }
985
+ /**
986
+ * Maps an error thrown while calling Cal.com as a user to the code to record on their connection.
987
+ *
988
+ * Returns null for anything that is not the grant being refused — a rate limit, a validation error, a
989
+ * network failure, or a 403 all leave the connection itself intact, and marking it `error` for those
990
+ * would send the user to a reconnect that fixes nothing.
991
+ *
992
+ * @param error - The error thrown by a Cal.com call.
993
+ * @returns The error code to record, or null when the connection is not at fault.
994
+ *
995
+ * @__NO_SIDE_EFFECTS__
996
+ */ function userExternalConnectionErrorCodeFromCalcomError(error) {
997
+ var result;
998
+ if (_instanceof(error, CalcomOAuthAccessTokenError)) {
999
+ // `invalid_grant`, the only code this error carries. Recorded as `expired` rather than `revoked`
1000
+ // for the same reason the reader does: the code cannot distinguish a revoked grant from a refresh
1001
+ // token that was already spent, and telling the user they revoked access when they did not would
1002
+ // send the UI down the wrong path
1003
+ result = DEFAULT_USER_EXTERNAL_CONNECTION_REFRESH_FAILURE_ERROR_CODE;
1004
+ } else if (_instanceof(error, CalcomOAuthAuthFailureError)) {
1005
+ // no usable access token could be produced from the stored refresh token
1006
+ result = 'unauthorized';
1007
+ } else if (_instanceof(error, CalcomServerFetchResponseError)) {
1008
+ result = error.responseError.response.status === HTTP_UNAUTHORIZED_STATUS_CODE ? 'unauthorized' : undefined;
1009
+ } else if (_instanceof(error, FetchResponseError)) {
1010
+ // the same rejection, for a response whose body Cal.com's error parser could not read
1011
+ result = error.response.status === HTTP_UNAUTHORIZED_STATUS_CODE ? 'unauthorized' : undefined;
1012
+ }
1013
+ return result;
1014
+ }
1015
+ /**
1016
+ * Turns a uid into a Cal.com API instance that acts as that user.
1017
+ *
1018
+ * The provider-specific sibling of `UserExternalConnectionReader.readerForUser`, and the only correct
1019
+ * way to make per-user Cal.com calls in an app that stores connections on the pair:
1020
+ *
1021
+ * ```ts
1022
+ * const calcom = await calcomUserContextService.calcomUserContextForUser({ uid });
1023
+ * const me = await calcom.getMe();
1024
+ * ```
1025
+ *
1026
+ * Do NOT assemble this by hand from `readUsableUserExternalConnectionCredentials()`. Cal.com runs its
1027
+ * own refresh loop through the access token cache, so a reader refresh followed by a library refresh
1028
+ * spends a rotated refresh token twice and destroys one of two valid grants.
1029
+ */ var UserExternalConnectionCalcomUserContextService = function UserExternalConnectionCalcomUserContextService() {
1030
+ _class_call_check$1(this, UserExternalConnectionCalcomUserContextService);
1031
+ };
1032
+ /**
1033
+ * Creates a {@link UserExternalConnectionCalcomUserContextService}.
1034
+ *
1035
+ * Instances are NOT cached per user. Each call builds a fresh token factory, so the in-memory token
1036
+ * tier lives only as long as the returned instance and one request's tokens are never visible to the
1037
+ * next. The pair-backed cache means the cost of that is a document read, not a token refresh.
1038
+ *
1039
+ * @param config - The Cal.com API, the accessor, and the write surface.
1040
+ * @returns A concrete UserExternalConnectionCalcomUserContextService implementation.
1041
+ */ function userExternalConnectionCalcomUserContextService(config) {
1042
+ var calcomApi = config.calcomApi, accessor = config.accessor, actions = config.actions;
1043
+ var providerType = CALCOM_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE;
1044
+ var logger = new Logger('UserExternalConnectionCalcomUserContextService');
1045
+ /**
1046
+ * Records that Cal.com refused the user's grant.
1047
+ *
1048
+ * Never throws: the caller is already handling the provider's error, and losing that error to a
1049
+ * failed write would be worse than not recording it.
1050
+ *
1051
+ * @param uid - The user whose grant was refused.
1052
+ * @param error - The code to record.
1053
+ */ function reportRefusedGrant(uid, error) {
1054
+ return _async_to_generator(function() {
1055
+ var entry, e;
1056
+ return _ts_generator(this, function(_state) {
1057
+ switch(_state.label){
1058
+ case 0:
1059
+ _state.trys.push([
1060
+ 0,
1061
+ 4,
1062
+ ,
1063
+ 5
1064
+ ]);
1065
+ return [
1066
+ 4,
1067
+ accessor.accessorForUser({
1068
+ uid: uid
1069
+ })(providerType).readUserExternalConnectionForProvider()
1070
+ ];
1071
+ case 1:
1072
+ entry = _state.sent().entry;
1073
+ if (!((entry === null || entry === void 0 ? void 0 : entry.st) !== 'error' || entry.er !== error)) return [
1074
+ 3,
1075
+ 3
1076
+ ];
1077
+ return [
1078
+ 4,
1079
+ actions.markUserExternalConnectionError({
1080
+ uid: uid,
1081
+ providerType: providerType,
1082
+ error: error
1083
+ })
1084
+ ];
1085
+ case 2:
1086
+ _state.sent();
1087
+ _state.label = 3;
1088
+ case 3:
1089
+ return [
1090
+ 3,
1091
+ 5
1092
+ ];
1093
+ case 4:
1094
+ e = _state.sent();
1095
+ logger.error('Failed marking the "'.concat(providerType, '" connection error for uid "').concat(uid, '": '), e);
1096
+ return [
1097
+ 3,
1098
+ 5
1099
+ ];
1100
+ case 5:
1101
+ return [
1102
+ 2
1103
+ ];
1104
+ }
1105
+ });
1106
+ })();
1107
+ }
1108
+ /**
1109
+ * Wraps a Cal.com fetch so a refused grant is always recorded on the connection.
1110
+ *
1111
+ * Wrapping the fetch rather than asking callers to report is what makes this impossible to forget,
1112
+ * and it is the only layer that sees both failures: Cal.com resolves the access token inside the
1113
+ * request's header factory, so a dead refresh token surfaces here exactly like a 401 response does.
1114
+ *
1115
+ * @param uid - The user the fetch acts as.
1116
+ * @param fetch - The user context's fetch.
1117
+ * @returns An equivalent fetch that records a refused grant before rethrowing.
1118
+ */ function reportingFetch(uid, fetch) {
1119
+ return function(input, init) {
1120
+ return _async_to_generator(function() {
1121
+ var result, e, error;
1122
+ return _ts_generator(this, function(_state) {
1123
+ switch(_state.label){
1124
+ case 0:
1125
+ _state.trys.push([
1126
+ 0,
1127
+ 2,
1128
+ ,
1129
+ 5
1130
+ ]);
1131
+ return [
1132
+ 4,
1133
+ fetch(input, init)
1134
+ ];
1135
+ case 1:
1136
+ result = _state.sent(); // awaited so a thrown error is caught here
1137
+ return [
1138
+ 3,
1139
+ 5
1140
+ ];
1141
+ case 2:
1142
+ e = _state.sent();
1143
+ error = userExternalConnectionErrorCodeFromCalcomError(e);
1144
+ if (!(error != null)) return [
1145
+ 3,
1146
+ 4
1147
+ ];
1148
+ return [
1149
+ 4,
1150
+ reportRefusedGrant(uid, error)
1151
+ ];
1152
+ case 3:
1153
+ _state.sent();
1154
+ _state.label = 4;
1155
+ case 4:
1156
+ throw e;
1157
+ case 5:
1158
+ return [
1159
+ 2,
1160
+ result
1161
+ ];
1162
+ }
1163
+ });
1164
+ })();
1165
+ };
1166
+ }
1167
+ function calcomUserContextForUser(input) {
1168
+ return _async_to_generator(function() {
1169
+ var uid, _ref, entry, credentials, refreshToken, accessTokenCache, userContext, fetch, fetchJson, reportingContext;
1170
+ return _ts_generator(this, function(_state) {
1171
+ switch(_state.label){
1172
+ case 0:
1173
+ uid = input.uid;
1174
+ return [
1175
+ 4,
1176
+ accessor.accessorForUser({
1177
+ uid: uid
1178
+ })(providerType).readUserExternalConnectionForProvider()
1179
+ ];
1180
+ case 1:
1181
+ _ref = _state.sent(), entry = _ref.entry, credentials = _ref.credentials;
1182
+ // an absent entry, absent credentials, or an explicit disconnect all mean the same thing: there is
1183
+ // nothing here to act as, and the remedy is for the user to connect. An `error` entry is NOT
1184
+ // refused — it keeps its credentials precisely so a refresh can repair it, and the refresh Cal.com
1185
+ // runs through the cache writes back as `connected`, so a working grant heals the entry on first use
1186
+ if (entry == null || credentials == null || entry.st === 'disconnected') {
1187
+ throw userExternalConnectionProviderNotConnectedError(providerType);
1188
+ }
1189
+ refreshToken = credentials.refreshToken;
1190
+ // Cal.com issues an access token only in exchange for a refresh token, so without one there is
1191
+ // nothing to act with and no way to renew — a reconnect is the only remedy
1192
+ if (!refreshToken) {
1193
+ throw userExternalConnectionCredentialsExpiredError(providerType);
1194
+ }
1195
+ // the pair-backed cache, never the default: Cal.com invalidates a refresh token on every use and
1196
+ // hands the replacement to its cache, so any other cache leaves the stored token spent after one
1197
+ // use while the entry still reads `connected`
1198
+ accessTokenCache = userExternalConnectionCalcomAccessTokenCache({
1199
+ accessor: accessor,
1200
+ actions: actions,
1201
+ uid: uid
1202
+ });
1203
+ userContext = calcomApi.makeUserContext({
1204
+ refreshToken: refreshToken,
1205
+ accessTokenCache: accessTokenCache
1206
+ });
1207
+ fetch = reportingFetch(uid, userContext.userFetch);
1208
+ // rebuilt over the wrapped fetch rather than wrapped itself, so the reporting cannot be bypassed
1209
+ // by whichever of the two an API function reaches for. The parse handling matches the Cal.com
1210
+ // factory's, which is what the unwrapped `userFetchJson` was built with
1211
+ fetchJson = fetchJsonFunction(fetch, {
1212
+ handleFetchJsonParseErrorFunction: returnNullHandleFetchJsonParseErrorFunction
1213
+ });
1214
+ reportingContext = _object_spread_props(_object_spread({}, userContext), {
1215
+ fetch: fetch,
1216
+ fetchJson: fetchJson,
1217
+ userFetch: fetch,
1218
+ userFetchJson: fetchJson
1219
+ });
1220
+ return [
1221
+ 2,
1222
+ calcomApi.makeContextInstance(reportingContext)
1223
+ ];
1224
+ }
1225
+ });
1226
+ })();
1227
+ }
1228
+ return {
1229
+ calcomUserContextForUser: calcomUserContextForUser
1230
+ };
1231
+ }
1232
+
1233
+ function _assert_this_initialized(self) {
1234
+ if (self === void 0) {
1235
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1236
+ }
1237
+ return self;
1238
+ }
1239
+ function _call_super(_this, derived, args) {
1240
+ derived = _get_prototype_of(derived);
1241
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
1242
+ }
1243
+ function _class_call_check(instance, Constructor) {
1244
+ if (!(instance instanceof Constructor)) {
1245
+ throw new TypeError("Cannot call a class as a function");
1246
+ }
1247
+ }
1248
+ function _define_property(obj, key, value) {
1249
+ if (key in obj) {
1250
+ Object.defineProperty(obj, key, {
1251
+ value: value,
1252
+ enumerable: true,
1253
+ configurable: true,
1254
+ writable: true
1255
+ });
1256
+ } else {
1257
+ obj[key] = value;
1258
+ }
1259
+ return obj;
1260
+ }
1261
+ function _get_prototype_of(o) {
1262
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
1263
+ return o.__proto__ || Object.getPrototypeOf(o);
1264
+ };
1265
+ return _get_prototype_of(o);
1266
+ }
1267
+ function _inherits(subClass, superClass) {
1268
+ if (typeof superClass !== "function" && superClass !== null) {
1269
+ throw new TypeError("Super expression must either be null or a function");
1270
+ }
1271
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
1272
+ constructor: {
1273
+ value: subClass,
1274
+ writable: true,
1275
+ configurable: true
1276
+ }
1277
+ });
1278
+ if (superClass) _set_prototype_of(subClass, superClass);
1279
+ }
1280
+ function _possible_constructor_return(self, call) {
1281
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
1282
+ return call;
1283
+ }
1284
+ return _assert_this_initialized(self);
1285
+ }
1286
+ function _set_prototype_of(o, p) {
1287
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
1288
+ o.__proto__ = p;
1289
+ return o;
1290
+ };
1291
+ return _set_prototype_of(o, p);
1292
+ }
1293
+ function _type_of(obj) {
1294
+ "@swc/helpers - typeof";
1295
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1296
+ }
1297
+ function _is_native_reflect_construct() {
1298
+ try {
1299
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1300
+ } catch (_) {}
1301
+ return (_is_native_reflect_construct = function() {
1302
+ return !!result;
1303
+ })();
1304
+ }
1305
+ /**
1306
+ * Endpoints for the Cal.com external-connection authorization-code handoff.
1307
+ *
1308
+ * Mounted at `/oauth/calcom`, matching the Angular registry's default authorize path of
1309
+ * `/oauth/<providerType>/authorize`. Hosting rewrites do not strip the path, so this prefix is the
1310
+ * public path — but an app with a global API route prefix must ALSO exclude these routes from it via
1311
+ * {@link CALCOM_USER_EXTERNAL_CONNECTION_OAUTH_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE}, or they land under
1312
+ * that prefix instead and no longer match the redirect URI registered with Cal.com.
1313
+ *
1314
+ * The `authorize` and `callback` routes come from the base class, so this declares only where they
1315
+ * mount and which service serves them.
1316
+ */ var CalcomUserExternalConnectionOAuthController = /*#__PURE__*/ function(AbstractUserExternalConnectionOAuthController) {
1317
+ _inherits(CalcomUserExternalConnectionOAuthController, AbstractUserExternalConnectionOAuthController);
1318
+ function CalcomUserExternalConnectionOAuthController(oauthService) {
1319
+ _class_call_check(this, CalcomUserExternalConnectionOAuthController);
1320
+ var _this;
1321
+ _this = _call_super(this, CalcomUserExternalConnectionOAuthController), _define_property(_this, "oauthService", void 0);
1322
+ _this.oauthService = oauthService;
1323
+ return _this;
1324
+ }
1325
+ return CalcomUserExternalConnectionOAuthController;
1326
+ }(AbstractUserExternalConnectionOAuthController);
1327
+ CalcomUserExternalConnectionOAuthController = __decorate([
1328
+ Controller(CALCOM_USER_EXTERNAL_CONNECTION_OAUTH_CONTROLLER_PATH),
1329
+ __param(0, Inject(CalcomUserExternalConnectionOAuthService))
1330
+ ], CalcomUserExternalConnectionOAuthController);
1331
+
1332
+ function _array_like_to_array(arr, len) {
1333
+ if (len == null || len > arr.length) len = arr.length;
1334
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1335
+ return arr2;
1336
+ }
1337
+ function _array_without_holes(arr) {
1338
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
1339
+ }
1340
+ function _iterable_to_array(iter) {
1341
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1342
+ }
1343
+ function _non_iterable_spread() {
1344
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1345
+ }
1346
+ function _to_consumable_array(arr) {
1347
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1348
+ }
1349
+ function _unsupported_iterable_to_array(o, minLen) {
1350
+ if (!o) return;
1351
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
1352
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1353
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1354
+ if (n === "Map" || n === "Set") return Array.from(n);
1355
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1356
+ }
1357
+ /**
1358
+ * Convenience function used to generate ModuleMetadata for an app's Cal.com external-connection
1359
+ * OAuth module.
1360
+ *
1361
+ * Opt-in, like the webhook module: importing the Cal.com OAuth module alone never mounts HTTP
1362
+ * routes, so an app that only makes outbound Cal.com calls exposes no endpoints.
1363
+ *
1364
+ * The importing module must also supply `UserExternalConnectionServerActions` and
1365
+ * `UserExternalConnectionStateCoder` — both exported by `appUserExternalConnectionModuleMetadata`,
1366
+ * so pass that module in `imports`.
1367
+ *
1368
+ * @param config - The module metadata configuration.
1369
+ * @returns NestJS ModuleMetadata mounting the Cal.com connect endpoints.
1370
+ */ function appCalcomUserExternalConnectionOAuthModuleMetadata(config) {
1371
+ var dependencyModule = config.dependencyModule, successPath = config.successPath, failurePath = config.failurePath, scopes = config.scopes, imports = config.imports, exports = config.exports, providers = config.providers;
1372
+ var dependencyModuleImport = dependencyModule ? [
1373
+ dependencyModule
1374
+ ] : [];
1375
+ return {
1376
+ imports: [
1377
+ ConfigModule
1378
+ ].concat(_to_consumable_array(dependencyModuleImport), _to_consumable_array(imports !== null && imports !== void 0 ? imports : [])),
1379
+ controllers: [
1380
+ CalcomUserExternalConnectionOAuthController
1381
+ ],
1382
+ exports: [
1383
+ CalcomUserExternalConnectionOAuthService
1384
+ ].concat(_to_consumable_array(exports !== null && exports !== void 0 ? exports : [])),
1385
+ providers: [
1386
+ {
1387
+ provide: CalcomUserExternalConnectionOAuthServiceConfig,
1388
+ inject: [
1389
+ FirebaseServerEnvService
1390
+ ],
1391
+ useFactory: function useFactory(envService) {
1392
+ return calcomUserExternalConnectionOAuthServiceConfigFactory({
1393
+ envService: envService,
1394
+ successPath: successPath,
1395
+ failurePath: failurePath,
1396
+ scopes: scopes
1397
+ });
1398
+ }
1399
+ },
1400
+ CalcomUserExternalConnectionOAuthService
1401
+ ].concat(_to_consumable_array(providers !== null && providers !== void 0 ? providers : []))
1402
+ };
1403
+ }
1404
+ // MARK: Calcom User Context Service
1405
+ /**
1406
+ * Creates the NestJS provider for the {@link UserExternalConnectionCalcomUserContextService}.
1407
+ *
1408
+ * A provider rather than a module, because the three tokens it needs are never declared together:
1409
+ * `CalcomApi` comes from the app's Cal.com module and the accessor and actions from its
1410
+ * UserExternalConnection module. Declare this in a module that imports both.
1411
+ *
1412
+ * Separate from {@link appCalcomUserExternalConnectionOAuthModuleMetadata} on purpose — that module
1413
+ * needs only `CalcomOAuthApi`, and folding this in would force every app running the connect flow to
1414
+ * also provide `CalcomApi` whether it makes outbound Cal.com calls or not.
1415
+ *
1416
+ * @returns The NestJS provider.
1417
+ *
1418
+ * @__NO_SIDE_EFFECTS__
1419
+ */ function userExternalConnectionCalcomUserContextServiceProvider() {
1420
+ return {
1421
+ provide: UserExternalConnectionCalcomUserContextService,
1422
+ useFactory: function useFactory(calcomApi, accessor, actions) {
1423
+ return userExternalConnectionCalcomUserContextService({
1424
+ calcomApi: calcomApi,
1425
+ accessor: accessor,
1426
+ actions: actions
1427
+ });
1428
+ },
1429
+ inject: [
1430
+ CalcomApi,
1431
+ UserExternalConnectionAccessor,
1432
+ UserExternalConnectionServerActions
1433
+ ]
1434
+ };
1435
+ }
1436
+
1437
+ export { CALCOM_USER_EXTERNAL_CONNECTION_OAUTH_CONTROLLER_PATH, CALCOM_USER_EXTERNAL_CONNECTION_OAUTH_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE, CalcomUserExternalConnectionOAuthController, CalcomUserExternalConnectionOAuthService, CalcomUserExternalConnectionOAuthServiceConfig, DEFAULT_CALCOM_OAUTH_SCOPES, UserExternalConnectionCalcomUserContextService, appCalcomUserExternalConnectionOAuthModuleMetadata, calcomAccessTokenFromUserExternalConnectionCredentials, calcomUserExternalConnectionCredentials, calcomUserExternalConnectionOAuthServiceConfigFactory, userExternalConnectionCalcomAccessTokenCache, userExternalConnectionCalcomUserContextService, userExternalConnectionCalcomUserContextServiceProvider, userExternalConnectionErrorCodeFromCalcomError };