@corsair-dev/cli 0.1.16 → 0.1.17

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 (105) hide show
  1. package/dist/index.js +747 -732
  2. package/dist/src/auth.d.ts.map +1 -0
  3. package/dist/src/commands/auth.command.d.ts +9 -0
  4. package/dist/src/commands/auth.command.d.ts.map +1 -0
  5. package/dist/src/commands/base.command.d.ts +14 -0
  6. package/dist/src/commands/base.command.d.ts.map +1 -0
  7. package/dist/src/commands/list.command.d.ts +9 -0
  8. package/dist/src/commands/list.command.d.ts.map +1 -0
  9. package/dist/src/commands/onedrive-subscribe.command.d.ts +6 -0
  10. package/dist/src/commands/onedrive-subscribe.command.d.ts.map +1 -0
  11. package/dist/src/commands/schema.command.d.ts +9 -0
  12. package/dist/src/commands/schema.command.d.ts.map +1 -0
  13. package/dist/src/commands/script.command.d.ts +10 -0
  14. package/dist/src/commands/script.command.d.ts.map +1 -0
  15. package/dist/src/commands/setup.command.d.ts +11 -0
  16. package/dist/src/commands/setup.command.d.ts.map +1 -0
  17. package/dist/src/commands/sharepoint-subscribe.command.d.ts +6 -0
  18. package/dist/src/commands/sharepoint-subscribe.command.d.ts.map +1 -0
  19. package/dist/src/commands/studio.command.d.ts +10 -0
  20. package/dist/src/commands/studio.command.d.ts.map +1 -0
  21. package/dist/src/commands/subscribe/onedrive.command.d.ts +8 -0
  22. package/dist/src/commands/subscribe/onedrive.command.d.ts.map +1 -0
  23. package/dist/src/commands/subscribe/outlook.command.d.ts +8 -0
  24. package/dist/src/commands/subscribe/outlook.command.d.ts.map +1 -0
  25. package/dist/src/commands/subscribe/sharepoint.command.d.ts +8 -0
  26. package/dist/src/commands/subscribe/sharepoint.command.d.ts.map +1 -0
  27. package/dist/src/commands/subscribe/teams.command.d.ts +8 -0
  28. package/dist/src/commands/subscribe/teams.command.d.ts.map +1 -0
  29. package/dist/src/commands/subscribe.command.d.ts +10 -0
  30. package/dist/src/commands/subscribe.command.d.ts.map +1 -0
  31. package/dist/src/commands/teams-subscribe.command.d.ts +6 -0
  32. package/dist/src/commands/teams-subscribe.command.d.ts.map +1 -0
  33. package/dist/src/commands/watch-renew.command.d.ts +8 -0
  34. package/dist/src/commands/watch-renew.command.d.ts.map +1 -0
  35. package/dist/src/get-tsconfig-info.d.ts.map +1 -0
  36. package/dist/src/index.d.ts +5 -0
  37. package/dist/src/index.d.ts.map +1 -0
  38. package/dist/src/index.types.d.ts +16 -0
  39. package/dist/src/index.types.d.ts.map +1 -0
  40. package/dist/src/lib/google/calendar.d.ts.map +1 -0
  41. package/dist/src/lib/google/drive.d.ts.map +1 -0
  42. package/dist/src/lib/google/gmail.d.ts.map +1 -0
  43. package/dist/src/lib/google/index.d.ts.map +1 -0
  44. package/dist/src/lib/google/shared.d.ts.map +1 -0
  45. package/dist/src/lib/google/sheets.d.ts.map +1 -0
  46. package/dist/src/lib/google/subscribe-google.d.ts +2 -0
  47. package/dist/src/lib/google/subscribe-google.d.ts.map +1 -0
  48. package/dist/src/lib/microsoft/credentials.d.ts.map +1 -0
  49. package/dist/src/lib/microsoft/graph.d.ts.map +1 -0
  50. package/dist/src/lib/microsoft/onedrive.d.ts.map +1 -0
  51. package/dist/src/lib/microsoft/outlook.d.ts.map +1 -0
  52. package/dist/src/lib/microsoft/sharepoint.d.ts.map +1 -0
  53. package/dist/src/lib/microsoft/subscribe-microsoft.d.ts +5 -0
  54. package/dist/src/lib/microsoft/subscribe-microsoft.d.ts.map +1 -0
  55. package/dist/src/lib/microsoft/teams.d.ts.map +1 -0
  56. package/dist/src/utils/corsair-instance.d.ts +8 -0
  57. package/dist/src/utils/corsair-instance.d.ts.map +1 -0
  58. package/dist/src/utils/corsair.d.ts.map +1 -0
  59. package/dist/src/utils/load-config.d.ts.map +1 -0
  60. package/dist/src/utils/prompts.d.ts.map +1 -0
  61. package/dist/src/utils/subscription.d.ts +2 -0
  62. package/dist/src/utils/subscription.d.ts.map +1 -0
  63. package/package.json +5 -4
  64. package/dist/auth.d.ts.map +0 -1
  65. package/dist/get-tsconfig-info.d.ts.map +0 -1
  66. package/dist/google/calendar.d.ts.map +0 -1
  67. package/dist/google/drive.d.ts.map +0 -1
  68. package/dist/google/gmail.d.ts.map +0 -1
  69. package/dist/google/index.d.ts.map +0 -1
  70. package/dist/google/shared.d.ts.map +0 -1
  71. package/dist/google/sheets.d.ts.map +0 -1
  72. package/dist/index.d.ts +0 -33
  73. package/dist/index.d.ts.map +0 -1
  74. package/dist/microsoft/credentials.d.ts.map +0 -1
  75. package/dist/microsoft/graph.d.ts.map +0 -1
  76. package/dist/microsoft/onedrive.d.ts.map +0 -1
  77. package/dist/microsoft/outlook.d.ts.map +0 -1
  78. package/dist/microsoft/sharepoint.d.ts.map +0 -1
  79. package/dist/microsoft/teams.d.ts.map +0 -1
  80. package/dist/subscribe-google.d.ts +0 -2
  81. package/dist/subscribe-google.d.ts.map +0 -1
  82. package/dist/subscribe-microsoft.d.ts +0 -5
  83. package/dist/subscribe-microsoft.d.ts.map +0 -1
  84. package/dist/tsup.config.d.ts +0 -3
  85. package/dist/tsup.config.d.ts.map +0 -1
  86. package/dist/utils/corsair.d.ts.map +0 -1
  87. package/dist/utils/load-config.d.ts.map +0 -1
  88. package/dist/utils/prompts.d.ts.map +0 -1
  89. /package/dist/{auth.d.ts → src/auth.d.ts} +0 -0
  90. /package/dist/{get-tsconfig-info.d.ts → src/get-tsconfig-info.d.ts} +0 -0
  91. /package/dist/{google → src/lib/google}/calendar.d.ts +0 -0
  92. /package/dist/{google → src/lib/google}/drive.d.ts +0 -0
  93. /package/dist/{google → src/lib/google}/gmail.d.ts +0 -0
  94. /package/dist/{google → src/lib/google}/index.d.ts +0 -0
  95. /package/dist/{google → src/lib/google}/shared.d.ts +0 -0
  96. /package/dist/{google → src/lib/google}/sheets.d.ts +0 -0
  97. /package/dist/{microsoft → src/lib/microsoft}/credentials.d.ts +0 -0
  98. /package/dist/{microsoft → src/lib/microsoft}/graph.d.ts +0 -0
  99. /package/dist/{microsoft → src/lib/microsoft}/onedrive.d.ts +0 -0
  100. /package/dist/{microsoft → src/lib/microsoft}/outlook.d.ts +0 -0
  101. /package/dist/{microsoft → src/lib/microsoft}/sharepoint.d.ts +0 -0
  102. /package/dist/{microsoft → src/lib/microsoft}/teams.d.ts +0 -0
  103. /package/dist/{utils → src/utils}/corsair.d.ts +0 -0
  104. /package/dist/{utils → src/utils}/load-config.d.ts +0 -0
  105. /package/dist/{utils → src/utils}/prompts.d.ts +0 -0
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ var __export = (target, all) => {
9
9
  __defProp(target, name, { get: all[name], enumerable: true });
10
10
  };
11
11
 
12
- // get-tsconfig-info.ts
12
+ // src/get-tsconfig-info.ts
13
13
  import fs from "fs";
14
14
  import path from "path";
15
15
  function stripJsonComments(jsonString) {
@@ -33,12 +33,192 @@ function getTsconfigInfo(cwd, flatPath) {
33
33
  }
34
34
  }
35
35
  var init_get_tsconfig_info = __esm({
36
- "get-tsconfig-info.ts"() {
36
+ "src/get-tsconfig-info.ts"() {
37
37
  "use strict";
38
38
  }
39
39
  });
40
40
 
41
- // utils/corsair.ts
41
+ // src/utils/corsair-instance.ts
42
+ import fs2, { existsSync } from "fs";
43
+ import path2 from "path";
44
+ import babelPresetReact from "@babel/preset-react";
45
+ import babelPresetTypeScript from "@babel/preset-typescript";
46
+ import { loadConfig } from "c12";
47
+ function isCorsairInstance(value) {
48
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
49
+ return false;
50
+ }
51
+ if ("withTenant" in value && typeof value.withTenant === "function") {
52
+ return true;
53
+ }
54
+ return Object.keys(value).length > 0;
55
+ }
56
+ function resolveReferencePath(configDir, refPath) {
57
+ const resolvedPath = path2.resolve(configDir, refPath);
58
+ if (refPath.endsWith(".json")) return resolvedPath;
59
+ if (existsSync(resolvedPath)) {
60
+ const stats = fs2.statSync(resolvedPath);
61
+ if (stats.isFile()) return resolvedPath;
62
+ }
63
+ return path2.resolve(configDir, refPath, "tsconfig.json");
64
+ }
65
+ function getPathAliasesRecursive(tsconfigPath, visited = /* @__PURE__ */ new Set()) {
66
+ if (visited.has(tsconfigPath)) return {};
67
+ visited.add(tsconfigPath);
68
+ if (!existsSync(tsconfigPath)) return {};
69
+ const tsConfig = getTsconfigInfo(void 0, tsconfigPath);
70
+ const { paths = {}, baseUrl = "." } = tsConfig.compilerOptions || {};
71
+ const configDir = path2.dirname(tsconfigPath);
72
+ const resolvedBaseUrl = path2.resolve(configDir, baseUrl);
73
+ const aliases = {};
74
+ for (const [alias, aliasPaths] of Object.entries(paths)) {
75
+ for (const aliasPath of aliasPaths) {
76
+ const aliasKey = alias.endsWith("*") ? alias.slice(0, -1) : alias;
77
+ const aliasValue = aliasPath.endsWith("*") ? aliasPath.slice(0, -1) : aliasPath;
78
+ aliases[aliasKey] = path2.join(resolvedBaseUrl, aliasValue);
79
+ }
80
+ }
81
+ for (const ref of tsConfig.references || []) {
82
+ const refPath = resolveReferencePath(configDir, ref.path);
83
+ const refAliases = getPathAliasesRecursive(refPath, visited);
84
+ for (const [alias, aliasPath] of Object.entries(refAliases)) {
85
+ if (!(alias in aliases)) aliases[alias] = aliasPath;
86
+ }
87
+ }
88
+ return aliases;
89
+ }
90
+ function getPathAliases(cwd) {
91
+ const tsConfigPath = path2.join(cwd, "tsconfig.json");
92
+ return existsSync(tsConfigPath) ? getPathAliasesRecursive(tsConfigPath) : {};
93
+ }
94
+ function jitiOptions(cwd) {
95
+ return {
96
+ transformOptions: {
97
+ babel: {
98
+ presets: [
99
+ [babelPresetTypeScript, { isTSX: true, allExtensions: true }],
100
+ [babelPresetReact, { runtime: "automatic" }]
101
+ ]
102
+ }
103
+ },
104
+ extensions: [".ts", ".tsx", ".js", ".jsx"],
105
+ alias: getPathAliases(cwd)
106
+ };
107
+ }
108
+ function fail(message, shouldThrowOnError) {
109
+ if (shouldThrowOnError) throw new Error(message);
110
+ console.error(`[#corsair]: ${message}`);
111
+ process.exit(1);
112
+ }
113
+ function parseLoadError(error) {
114
+ const msg = error instanceof Error ? error.message : String(error);
115
+ if (msg.includes(
116
+ "This module cannot be imported from a Client Component module"
117
+ )) {
118
+ return "Please remove import 'server-only' from your corsair.ts file temporarily.";
119
+ }
120
+ if (msg.includes("Could not locate the bindings file") || msg.includes("NODE_MODULE_VERSION") || msg.includes(".node")) {
121
+ return "Native module binding not found. Run `npm rebuild` or reinstall dependencies.";
122
+ }
123
+ return msg;
124
+ }
125
+ function findCorsairConfigPath(cwd) {
126
+ for (const possiblePath of POSSIBLE_PATHS) {
127
+ const fullPath = path2.join(cwd, possiblePath);
128
+ if (existsSync(fullPath)) return fullPath;
129
+ }
130
+ return null;
131
+ }
132
+ async function getCorsairInstance({
133
+ cwd,
134
+ configPath,
135
+ shouldThrowOnError = false
136
+ }) {
137
+ const candidatePaths = configPath ? [existsSync(configPath) ? configPath : path2.join(cwd, configPath)] : [...POSSIBLE_PATHS];
138
+ for (const candidatePath of candidatePaths) {
139
+ try {
140
+ const { config } = await loadConfig({
141
+ configFile: candidatePath,
142
+ dotenv: true,
143
+ jitiOptions: jitiOptions(cwd),
144
+ cwd
145
+ });
146
+ if ("corsair" in config && isCorsairInstance(config.corsair)) {
147
+ return config.corsair;
148
+ }
149
+ if ("default" in config && isCorsairInstance(config.default)) {
150
+ return config.default;
151
+ }
152
+ if (Object.keys(config).length > 0) {
153
+ fail(
154
+ `Couldn't read your Corsair instance in ${candidatePath}. Export it as 'corsair' or default.`,
155
+ shouldThrowOnError
156
+ );
157
+ }
158
+ } catch (error) {
159
+ fail(
160
+ `Error loading ${candidatePath}: ${parseLoadError(error)}`,
161
+ shouldThrowOnError
162
+ );
163
+ }
164
+ }
165
+ fail(
166
+ "Couldn't find corsair.ts in your project. Add it in root or src/lib/server/app.",
167
+ shouldThrowOnError
168
+ );
169
+ }
170
+ function resolveClient(instance, tenant) {
171
+ const obj = instance;
172
+ if ("withTenant" in obj && typeof obj.withTenant === "function") {
173
+ if (!tenant) {
174
+ console.error(
175
+ "[#corsair]: This is a multi-tenant instance. Pass --tenant=<id>."
176
+ );
177
+ process.exit(1);
178
+ }
179
+ return obj.withTenant(tenant);
180
+ }
181
+ return obj;
182
+ }
183
+ var POSSIBLE_PATHS;
184
+ var init_corsair_instance = __esm({
185
+ "src/utils/corsair-instance.ts"() {
186
+ "use strict";
187
+ init_get_tsconfig_info();
188
+ POSSIBLE_PATHS = [
189
+ "corsair.ts",
190
+ "corsair.tsx",
191
+ "corsair.js",
192
+ "corsair.jsx",
193
+ "src/corsair.ts",
194
+ "src/corsair.tsx",
195
+ "src/corsair.js",
196
+ "src/corsair.jsx",
197
+ "lib/corsair.ts",
198
+ "lib/corsair.tsx",
199
+ "lib/corsair.js",
200
+ "lib/corsair.jsx",
201
+ "server/corsair.ts",
202
+ "server/corsair.tsx",
203
+ "server/corsair.js",
204
+ "server/corsair.jsx",
205
+ "src/server/corsair.ts",
206
+ "src/server/corsair.tsx",
207
+ "src/server/corsair.js",
208
+ "src/server/corsair.jsx",
209
+ "app/corsair.ts",
210
+ "app/corsair.tsx",
211
+ "app/corsair.js",
212
+ "app/corsair.jsx",
213
+ "corsair/index.ts",
214
+ "corsair/index.tsx",
215
+ "corsair/index.js",
216
+ "corsair/index.jsx"
217
+ ];
218
+ }
219
+ });
220
+
221
+ // src/utils/corsair.ts
42
222
  import { CORSAIR_INTERNAL } from "corsair/core";
43
223
  async function extractInternalConfig(cwd) {
44
224
  const instance = await getCorsairInstance({ cwd, shouldThrowOnError: true });
@@ -51,13 +231,13 @@ async function extractInternalConfig(cwd) {
51
231
  return internal;
52
232
  }
53
233
  var init_corsair = __esm({
54
- "utils/corsair.ts"() {
234
+ "src/utils/corsair.ts"() {
55
235
  "use strict";
56
- init_index();
236
+ init_corsair_instance();
57
237
  }
58
238
  });
59
239
 
60
- // utils/load-config.ts
240
+ // src/utils/load-config.ts
61
241
  import * as p from "@clack/prompts";
62
242
  async function loadInternalConfig(cwd, title, pluginId, pluginLabel) {
63
243
  p.intro(title);
@@ -90,13 +270,13 @@ async function loadInternalConfig(cwd, title, pluginId, pluginLabel) {
90
270
  return { internal, plugin };
91
271
  }
92
272
  var init_load_config = __esm({
93
- "utils/load-config.ts"() {
273
+ "src/utils/load-config.ts"() {
94
274
  "use strict";
95
275
  init_corsair();
96
276
  }
97
277
  });
98
278
 
99
- // utils/prompts.ts
279
+ // src/utils/prompts.ts
100
280
  import * as crypto from "crypto";
101
281
  import * as p2 from "@clack/prompts";
102
282
  async function promptTenantId() {
@@ -141,12 +321,12 @@ async function promptClientState() {
141
321
  return clientState;
142
322
  }
143
323
  var init_prompts = __esm({
144
- "utils/prompts.ts"() {
324
+ "src/utils/prompts.ts"() {
145
325
  "use strict";
146
326
  }
147
327
  });
148
328
 
149
- // microsoft/credentials.ts
329
+ // src/lib/microsoft/credentials.ts
150
330
  import * as p3 from "@clack/prompts";
151
331
  import {
152
332
  createAccountKeyManager,
@@ -258,13 +438,13 @@ async function saveWebhookSignature(accountKm, clientState) {
258
438
  }
259
439
  var MICROSOFT_TOKEN_URL;
260
440
  var init_credentials = __esm({
261
- "microsoft/credentials.ts"() {
441
+ "src/lib/microsoft/credentials.ts"() {
262
442
  "use strict";
263
443
  MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
264
444
  }
265
445
  });
266
446
 
267
- // microsoft/graph.ts
447
+ // src/lib/microsoft/graph.ts
268
448
  async function createGraphSubscription(accessToken, notificationUrl, resource, changeType, clientState, expiryMinutes) {
269
449
  const expirationDateTime = new Date(
270
450
  Date.now() + expiryMinutes * 60 * 1e3
@@ -291,13 +471,13 @@ async function createGraphSubscription(accessToken, notificationUrl, resource, c
291
471
  }
292
472
  var GRAPH_API_BASE;
293
473
  var init_graph = __esm({
294
- "microsoft/graph.ts"() {
474
+ "src/lib/microsoft/graph.ts"() {
295
475
  "use strict";
296
476
  GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";
297
477
  }
298
478
  });
299
479
 
300
- // microsoft/onedrive.ts
480
+ // src/lib/microsoft/onedrive.ts
301
481
  import * as p4 from "@clack/prompts";
302
482
  function buildOnedriveResource(resourceType, ids) {
303
483
  switch (resourceType) {
@@ -415,7 +595,7 @@ Note: OneDrive subscriptions expire. Re-run this command to renew.`,
415
595
  }
416
596
  var ONEDRIVE_MAX_EXPIRY_MINUTES, ONEDRIVE_RESOURCE_OPTIONS;
417
597
  var init_onedrive = __esm({
418
- "microsoft/onedrive.ts"() {
598
+ "src/lib/microsoft/onedrive.ts"() {
419
599
  "use strict";
420
600
  init_load_config();
421
601
  init_prompts();
@@ -442,7 +622,7 @@ var init_onedrive = __esm({
442
622
  }
443
623
  });
444
624
 
445
- // microsoft/outlook.ts
625
+ // src/lib/microsoft/outlook.ts
446
626
  import * as p5 from "@clack/prompts";
447
627
  async function runOutlookSubscribe({
448
628
  cwd
@@ -521,7 +701,7 @@ Note: Outlook subscriptions expire. Re-run this command to renew.`,
521
701
  }
522
702
  var OUTLOOK_RESOURCES;
523
703
  var init_outlook = __esm({
524
- "microsoft/outlook.ts"() {
704
+ "src/lib/microsoft/outlook.ts"() {
525
705
  "use strict";
526
706
  init_load_config();
527
707
  init_prompts();
@@ -565,7 +745,7 @@ var init_outlook = __esm({
565
745
  }
566
746
  });
567
747
 
568
- // microsoft/sharepoint.ts
748
+ // src/lib/microsoft/sharepoint.ts
569
749
  import * as p6 from "@clack/prompts";
570
750
  function buildSiteUrl(siteId, subpath) {
571
751
  const isHostnamePath = siteId.includes(":") && !siteId.includes(",");
@@ -716,7 +896,7 @@ Note: SharePoint subscriptions expire after ${SHAREPOINT_MAX_EXPIRY_DAYS} days m
716
896
  }
717
897
  var SHAREPOINT_MAX_EXPIRY_DAYS;
718
898
  var init_sharepoint = __esm({
719
- "microsoft/sharepoint.ts"() {
899
+ "src/lib/microsoft/sharepoint.ts"() {
720
900
  "use strict";
721
901
  init_load_config();
722
902
  init_prompts();
@@ -726,7 +906,7 @@ var init_sharepoint = __esm({
726
906
  }
727
907
  });
728
908
 
729
- // microsoft/teams.ts
909
+ // src/lib/microsoft/teams.ts
730
910
  import * as p7 from "@clack/prompts";
731
911
  async function fetchJoinedTeams(accessToken) {
732
912
  const response = await fetch(`${GRAPH_API_BASE}/me/joinedTeams`, {
@@ -1006,7 +1186,7 @@ Note: Teams subscriptions expire. Re-run this command to renew.`,
1006
1186
  }
1007
1187
  var TEAMS_MAX_EXPIRY_MINUTES;
1008
1188
  var init_teams = __esm({
1009
- "microsoft/teams.ts"() {
1189
+ "src/lib/microsoft/teams.ts"() {
1010
1190
  "use strict";
1011
1191
  init_load_config();
1012
1192
  init_prompts();
@@ -1021,7 +1201,7 @@ var init_teams = __esm({
1021
1201
  }
1022
1202
  });
1023
1203
 
1024
- // subscribe-microsoft.ts
1204
+ // src/lib/microsoft/subscribe-microsoft.ts
1025
1205
  var subscribe_microsoft_exports = {};
1026
1206
  __export(subscribe_microsoft_exports, {
1027
1207
  runOnedriveSubscribe: () => runOnedriveSubscribe,
@@ -1030,7 +1210,7 @@ __export(subscribe_microsoft_exports, {
1030
1210
  runTeamsSubscribe: () => runTeamsSubscribe
1031
1211
  });
1032
1212
  var init_subscribe_microsoft = __esm({
1033
- "subscribe-microsoft.ts"() {
1213
+ "src/lib/microsoft/subscribe-microsoft.ts"() {
1034
1214
  "use strict";
1035
1215
  init_onedrive();
1036
1216
  init_outlook();
@@ -1039,7 +1219,7 @@ var init_subscribe_microsoft = __esm({
1039
1219
  }
1040
1220
  });
1041
1221
 
1042
- // google/calendar.ts
1222
+ // src/lib/google/calendar.ts
1043
1223
  import * as crypto2 from "crypto";
1044
1224
  import * as p8 from "@clack/prompts";
1045
1225
  async function setupCalendarWatch(accessToken, webhookUrl, calendarId) {
@@ -1079,13 +1259,13 @@ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
1079
1259
  }
1080
1260
  var CALENDAR_API_BASE;
1081
1261
  var init_calendar = __esm({
1082
- "google/calendar.ts"() {
1262
+ "src/lib/google/calendar.ts"() {
1083
1263
  "use strict";
1084
1264
  CALENDAR_API_BASE = "https://www.googleapis.com/calendar/v3";
1085
1265
  }
1086
1266
  });
1087
1267
 
1088
- // google/drive.ts
1268
+ // src/lib/google/drive.ts
1089
1269
  import * as crypto3 from "crypto";
1090
1270
  import * as p9 from "@clack/prompts";
1091
1271
  async function setupDriveWatch(accessToken, webhookUrl) {
@@ -1141,13 +1321,13 @@ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
1141
1321
  }
1142
1322
  var DRIVE_API_BASE;
1143
1323
  var init_drive = __esm({
1144
- "google/drive.ts"() {
1324
+ "src/lib/google/drive.ts"() {
1145
1325
  "use strict";
1146
1326
  DRIVE_API_BASE = "https://www.googleapis.com/drive/v3";
1147
1327
  }
1148
1328
  });
1149
1329
 
1150
- // google/gmail.ts
1330
+ // src/lib/google/gmail.ts
1151
1331
  import * as p10 from "@clack/prompts";
1152
1332
  async function setupGmailWatch(accessToken, topicName) {
1153
1333
  const watchSpin = p10.spinner();
@@ -1180,13 +1360,13 @@ Expiration: ${new Date(Number(data.expiration)).toISOString()}`,
1180
1360
  }
1181
1361
  var GMAIL_API_BASE;
1182
1362
  var init_gmail = __esm({
1183
- "google/gmail.ts"() {
1363
+ "src/lib/google/gmail.ts"() {
1184
1364
  "use strict";
1185
1365
  GMAIL_API_BASE = "https://gmail.googleapis.com/gmail/v1";
1186
1366
  }
1187
1367
  });
1188
1368
 
1189
- // google/shared.ts
1369
+ // src/lib/google/shared.ts
1190
1370
  import { execSync } from "child_process";
1191
1371
  async function refreshGoogleAccessToken(clientId, clientSecret, refreshToken) {
1192
1372
  const response = await fetch("https://oauth2.googleapis.com/token", {
@@ -1234,12 +1414,12 @@ function copyToClipboard(text6) {
1234
1414
  }
1235
1415
  }
1236
1416
  var init_shared = __esm({
1237
- "google/shared.ts"() {
1417
+ "src/lib/google/shared.ts"() {
1238
1418
  "use strict";
1239
1419
  }
1240
1420
  });
1241
1421
 
1242
- // google/sheets.ts
1422
+ // src/lib/google/sheets.ts
1243
1423
  import * as p11 from "@clack/prompts";
1244
1424
  async function setupSheetsWatch(webhookUrl) {
1245
1425
  const appsScriptCode = APPS_SCRIPT_TEMPLATE(webhookUrl);
@@ -1286,7 +1466,7 @@ The Apps Script code ${copied ? "has been copied to your clipboard" : "is displa
1286
1466
  }
1287
1467
  var APPS_SCRIPT_TEMPLATE;
1288
1468
  var init_sheets = __esm({
1289
- "google/sheets.ts"() {
1469
+ "src/lib/google/sheets.ts"() {
1290
1470
  "use strict";
1291
1471
  init_shared();
1292
1472
  APPS_SCRIPT_TEMPLATE = (webhookUrl) => `var WEBHOOK_URL = "${webhookUrl}";
@@ -1357,7 +1537,7 @@ function removeTriggers() {
1357
1537
  }
1358
1538
  });
1359
1539
 
1360
- // google/index.ts
1540
+ // src/lib/google/index.ts
1361
1541
  import * as p12 from "@clack/prompts";
1362
1542
  import {
1363
1543
  CORSAIR_INTERNAL as CORSAIR_INTERNAL2,
@@ -1542,9 +1722,9 @@ async function runGoogleSubscribe({
1542
1722
  }
1543
1723
  var GOOGLE_PLUGINS;
1544
1724
  var init_google = __esm({
1545
- "google/index.ts"() {
1725
+ "src/lib/google/index.ts"() {
1546
1726
  "use strict";
1547
- init_index();
1727
+ init_corsair_instance();
1548
1728
  init_prompts();
1549
1729
  init_calendar();
1550
1730
  init_drive();
@@ -1560,31 +1740,31 @@ var init_google = __esm({
1560
1740
  }
1561
1741
  });
1562
1742
 
1563
- // subscribe-google.ts
1743
+ // src/lib/google/subscribe-google.ts
1564
1744
  var subscribe_google_exports = {};
1565
1745
  __export(subscribe_google_exports, {
1566
1746
  runGoogleSubscribe: () => runGoogleSubscribe
1567
1747
  });
1568
1748
  var init_subscribe_google = __esm({
1569
- "subscribe-google.ts"() {
1749
+ "src/lib/google/subscribe-google.ts"() {
1570
1750
  "use strict";
1571
1751
  init_google();
1572
1752
  }
1573
1753
  });
1574
1754
 
1575
- // auth.ts
1755
+ // src/auth.ts
1576
1756
  var auth_exports = {};
1577
1757
  __export(auth_exports, {
1578
1758
  runAuth: () => runAuth
1579
1759
  });
1580
1760
  import { spawn } from "child_process";
1581
1761
  import * as crypto4 from "crypto";
1582
- import * as fs2 from "fs";
1762
+ import * as fs3 from "fs";
1583
1763
  import * as http from "http";
1584
1764
  import * as https from "https";
1585
1765
  import * as net from "net";
1586
1766
  import * as os from "os";
1587
- import * as path2 from "path";
1767
+ import * as path3 from "path";
1588
1768
  import * as querystring from "querystring";
1589
1769
  import {
1590
1770
  CORSAIR_INTERNAL as CORSAIR_INTERNAL3,
@@ -1599,10 +1779,10 @@ function out(data) {
1599
1779
  console.log(JSON.stringify(data));
1600
1780
  }
1601
1781
  function authStateFile(sessionId) {
1602
- return path2.join(os.tmpdir(), `corsair-auth-${sessionId}.json`);
1782
+ return path3.join(os.tmpdir(), `corsair-auth-${sessionId}.json`);
1603
1783
  }
1604
1784
  function writeAuthState(sessionId, state) {
1605
- fs2.writeFileSync(authStateFile(sessionId), JSON.stringify(state));
1785
+ fs3.writeFileSync(authStateFile(sessionId), JSON.stringify(state));
1606
1786
  }
1607
1787
  function pollAuthState(sessionId, timeoutMs) {
1608
1788
  return new Promise((resolve, reject) => {
@@ -1610,7 +1790,7 @@ function pollAuthState(sessionId, timeoutMs) {
1610
1790
  const start = Date.now();
1611
1791
  const interval = setInterval(() => {
1612
1792
  try {
1613
- const state = JSON.parse(fs2.readFileSync(file, "utf8"));
1793
+ const state = JSON.parse(fs3.readFileSync(file, "utf8"));
1614
1794
  clearInterval(interval);
1615
1795
  resolve(state);
1616
1796
  } catch {
@@ -1702,7 +1882,6 @@ async function ensureIntegration(database, pluginId, kek) {
1702
1882
  const encryptedDek = await encryptDEK(dek, kek);
1703
1883
  const row = await orm.integrations.create({
1704
1884
  name: pluginId,
1705
- config: {},
1706
1885
  dek: encryptedDek
1707
1886
  });
1708
1887
  return { id: row.id };
@@ -1719,7 +1898,6 @@ async function ensureAccount(database, integrationId, tenantId, kek) {
1719
1898
  await orm.accounts.create({
1720
1899
  tenant_id: tenantId,
1721
1900
  integration_id: integrationId,
1722
- config: {},
1723
1901
  dek: encryptedDek
1724
1902
  });
1725
1903
  }
@@ -1925,7 +2103,7 @@ async function oauthCollect(database, plugin, kek, tenantId, sessionId) {
1925
2103
  const accessToken = await accountKm.get_access_token();
1926
2104
  if (accessToken) {
1927
2105
  try {
1928
- fs2.unlinkSync(authStateFile(sessionId));
2106
+ fs3.unlinkSync(authStateFile(sessionId));
1929
2107
  } catch {
1930
2108
  }
1931
2109
  out({ status: "success", plugin: plugin.id, tenant: tenantId });
@@ -1933,7 +2111,7 @@ async function oauthCollect(database, plugin, kek, tenantId, sessionId) {
1933
2111
  }
1934
2112
  try {
1935
2113
  const state = JSON.parse(
1936
- fs2.readFileSync(authStateFile(sessionId), "utf8")
2114
+ fs3.readFileSync(authStateFile(sessionId), "utf8")
1937
2115
  );
1938
2116
  if (state.status === "error") {
1939
2117
  out({ status: "error", error: state.error });
@@ -2164,646 +2342,375 @@ Authorize ${plugin.id}
2164
2342
  `);
2165
2343
  }
2166
2344
  var init_auth = __esm({
2167
- "auth.ts"() {
2345
+ "src/auth.ts"() {
2168
2346
  "use strict";
2169
- init_index();
2347
+ init_corsair_instance();
2170
2348
  }
2171
2349
  });
2172
2350
 
2173
- // index.ts
2174
- import fs3, { existsSync, realpathSync } from "fs";
2175
- import path3 from "path";
2351
+ // src/index.ts
2352
+ import { realpathSync } from "fs";
2176
2353
  import { fileURLToPath } from "url";
2177
- import babelPresetReact from "@babel/preset-react";
2178
- import babelPresetTypeScript from "@babel/preset-typescript";
2179
- import { loadConfig } from "c12";
2180
- import { getSchema, listOperations } from "corsair";
2181
- function resolveReferencePath(configDir, refPath) {
2182
- const resolvedPath = path3.resolve(configDir, refPath);
2183
- if (refPath.endsWith(".json")) {
2184
- return resolvedPath;
2185
- }
2186
- if (fs3.existsSync(resolvedPath)) {
2187
- try {
2188
- const stats = fs3.statSync(resolvedPath);
2189
- if (stats.isFile()) {
2190
- return resolvedPath;
2191
- }
2192
- } catch {
2193
- }
2194
- }
2195
- return path3.resolve(configDir, refPath, "tsconfig.json");
2196
- }
2197
- function getPathAliasesRecursive(tsconfigPath, visited = /* @__PURE__ */ new Set()) {
2198
- if (visited.has(tsconfigPath)) {
2199
- return {};
2200
- }
2201
- visited.add(tsconfigPath);
2202
- if (!fs3.existsSync(tsconfigPath)) {
2203
- console.warn(`Referenced tsconfig not found: ${tsconfigPath}`);
2204
- return {};
2205
- }
2206
- try {
2207
- const tsConfig = getTsconfigInfo(void 0, tsconfigPath);
2208
- const { paths = {}, baseUrl = "." } = tsConfig.compilerOptions || {};
2209
- const result = {};
2210
- const configDir = path3.dirname(tsconfigPath);
2211
- const obj = Object.entries(paths);
2212
- for (const [alias, aliasPaths] of obj) {
2213
- for (const aliasedPath of aliasPaths) {
2214
- const resolvedBaseUrl = path3.resolve(configDir, baseUrl);
2215
- const finalAlias = alias.slice(-1) === "*" ? alias.slice(0, -1) : alias;
2216
- const finalAliasedPath = aliasedPath.slice(-1) === "*" ? aliasedPath.slice(0, -1) : aliasedPath;
2217
- result[finalAlias || ""] = path3.join(resolvedBaseUrl, finalAliasedPath);
2218
- }
2219
- }
2220
- if (tsConfig.references) {
2221
- for (const ref of tsConfig.references) {
2222
- const refPath = resolveReferencePath(configDir, ref.path);
2223
- const refAliases = getPathAliasesRecursive(refPath, visited);
2224
- for (const [alias, aliasPath] of Object.entries(refAliases)) {
2225
- if (!(alias in result)) {
2226
- result[alias] = aliasPath;
2227
- }
2228
- }
2229
- }
2354
+ import { Command } from "commander";
2355
+
2356
+ // package.json
2357
+ var version = "0.1.17";
2358
+
2359
+ // src/utils/subscription.ts
2360
+ async function runWebhookSubscription(cwd, pluginId) {
2361
+ const microsoftPluginRunner = {
2362
+ outlook: "runOutlookSubscribe",
2363
+ sharepoint: "runSharepointSubscribe",
2364
+ teams: "runTeamsSubscribe",
2365
+ onedrive: "runOnedriveSubscribe"
2366
+ };
2367
+ if (pluginId in microsoftPluginRunner) {
2368
+ const mod = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2369
+ const fn = mod[microsoftPluginRunner[pluginId]];
2370
+ if (typeof fn === "function") {
2371
+ await fn({ cwd });
2372
+ return;
2230
2373
  }
2231
- return result;
2232
- } catch (error) {
2233
- console.warn(`Error parsing tsconfig at ${tsconfigPath}: ${error}`);
2234
- return {};
2235
- }
2236
- }
2237
- function getPathAliases(cwd) {
2238
- const tsConfigPath = path3.join(cwd, "tsconfig.json");
2239
- if (!fs3.existsSync(tsConfigPath)) {
2240
- return null;
2241
2374
  }
2242
- try {
2243
- const result = getPathAliasesRecursive(tsConfigPath);
2244
- return result;
2245
- } catch (error) {
2246
- console.error(error);
2247
- throw new Error("Error parsing tsconfig.json");
2248
- }
2249
- }
2250
- function findCorsairConfigPath(cwd) {
2251
- for (const possiblePath of possiblePaths) {
2252
- const fullPath = path3.join(cwd, possiblePath);
2253
- if (existsSync(fullPath)) {
2254
- return fullPath;
2255
- }
2375
+ if (["gmail", "googledrive", "googlecalendar", "googlesheets"].includes(
2376
+ pluginId
2377
+ )) {
2378
+ const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2379
+ await runGoogleSubscribe2({ cwd, pluginId });
2380
+ return;
2256
2381
  }
2257
- return null;
2382
+ console.error(
2383
+ `[#corsair]: Webhook subscription not supported for plugin '${pluginId}'.`
2384
+ );
2385
+ process.exit(1);
2258
2386
  }
2259
- async function getCorsairInstance({
2260
- cwd,
2261
- configPath,
2262
- shouldThrowOnError = false
2263
- }) {
2264
- try {
2265
- let corsairInstance = null;
2266
- if (configPath) {
2267
- let resolvedPath = path3.join(cwd, configPath);
2268
- if (existsSync(configPath)) {
2269
- resolvedPath = configPath;
2387
+
2388
+ // src/commands/base.command.ts
2389
+ import { Option } from "commander";
2390
+ var BaseCommand = class {
2391
+ action({}) {
2392
+ }
2393
+ getAliases() {
2394
+ return [];
2395
+ }
2396
+ getArguments() {
2397
+ return [];
2398
+ }
2399
+ getOptions() {
2400
+ return [];
2401
+ }
2402
+ getUsage() {
2403
+ return "";
2404
+ }
2405
+ getSubCommands() {
2406
+ return [];
2407
+ }
2408
+ prepare = (program) => {
2409
+ const command = program.command(this.getName()).description(this.getDescription());
2410
+ const usage = this.getUsage();
2411
+ if (usage) {
2412
+ command.usage(usage);
2413
+ }
2414
+ this.getAliases().forEach((alias) => command.alias(alias));
2415
+ this.getOptions().forEach((option) => {
2416
+ const newOption = new Option(
2417
+ `${option.short}, ${option.long}`,
2418
+ option.description
2419
+ ).default(option.defaultValue);
2420
+ option.choices && option.choices.length > 0 && newOption.choices(option.choices);
2421
+ command.addOption(newOption);
2422
+ });
2423
+ this.getArguments().forEach(
2424
+ (argument) => command.argument(argument.name, argument.description)
2425
+ );
2426
+ command.action(async (...data) => {
2427
+ const argsCount = this.getArguments().length;
2428
+ const commandOptions = data[argsCount];
2429
+ const args = data.slice(0, argsCount);
2430
+ await this.action({ args, options: commandOptions });
2431
+ });
2432
+ this.getSubCommands().forEach((subCommand) => {
2433
+ subCommand.prepare(command);
2434
+ });
2435
+ };
2436
+ };
2437
+
2438
+ // src/commands/auth.command.ts
2439
+ var AuthCommand = class extends BaseCommand {
2440
+ getName() {
2441
+ return "auth";
2442
+ }
2443
+ getDescription() {
2444
+ return "Run plugin auth flows";
2445
+ }
2446
+ getOptions() {
2447
+ return [
2448
+ { short: "-p", long: "--plugin <id>", description: "Plugin id" },
2449
+ { short: "-t", long: "--tenant <id>", description: "Tenant id for auth" },
2450
+ {
2451
+ short: "-c",
2452
+ long: "--code <code>",
2453
+ description: "OAuth code to exchange"
2454
+ },
2455
+ {
2456
+ short: "-s",
2457
+ long: "--session <id>",
2458
+ description: "Session id for local auth state"
2459
+ },
2460
+ {
2461
+ short: "-C",
2462
+ long: "--credentials",
2463
+ description: "Show credential status"
2464
+ },
2465
+ {
2466
+ short: "-w",
2467
+ long: "--webhook",
2468
+ description: "Run webhook subscription setup"
2469
+ },
2470
+ {
2471
+ short: "-l",
2472
+ long: "--listen",
2473
+ description: "Listen for callback only"
2474
+ },
2475
+ {
2476
+ short: "-x",
2477
+ long: "--collect",
2478
+ description: "Collect auth response from listener"
2270
2479
  }
2271
- const { config } = await loadConfig({
2272
- configFile: resolvedPath,
2273
- dotenv: true,
2274
- jitiOptions: jitiOptions(cwd),
2275
- cwd
2276
- });
2277
- if ("corsair" in config && isCorsairInstance(config.corsair)) {
2278
- corsairInstance = config.corsair;
2279
- } else if ("default" in config && isCorsairInstance(config.default)) {
2280
- corsairInstance = config.default;
2281
- } else {
2282
- if (shouldThrowOnError) {
2283
- throw new Error(
2284
- `Couldn't read your Corsair instance in ${resolvedPath}. Make sure to export your Corsair instance as a variable named 'corsair' or as the default export.`
2285
- );
2286
- }
2287
- console.error(
2288
- `[#corsair]: Couldn't read your Corsair instance in ${resolvedPath}. Make sure to export your Corsair instance as a variable named 'corsair' or as the default export.`
2289
- );
2480
+ ];
2481
+ }
2482
+ async action({ options }) {
2483
+ const cwd = process.cwd();
2484
+ if (options.webhook) {
2485
+ if (!options.plugin) {
2486
+ console.error("[#corsair]: --webhook requires --plugin=<id>.");
2290
2487
  process.exit(1);
2291
2488
  }
2489
+ await runWebhookSubscription(cwd, options.plugin);
2490
+ return;
2292
2491
  }
2293
- if (!corsairInstance) {
2294
- for (const possiblePath of possiblePaths) {
2295
- try {
2296
- const { config } = await loadConfig({
2297
- configFile: possiblePath,
2298
- jitiOptions: jitiOptions(cwd),
2299
- cwd
2300
- });
2301
- const hasConfig = Object.keys(config).length > 0;
2302
- if (hasConfig) {
2303
- if ("corsair" in config && isCorsairInstance(config.corsair)) {
2304
- corsairInstance = config.corsair;
2305
- } else if ("default" in config && isCorsairInstance(config.default)) {
2306
- corsairInstance = config.default;
2307
- }
2308
- if (!corsairInstance) {
2309
- if (shouldThrowOnError) {
2310
- throw new Error(
2311
- "Couldn't read your Corsair instance. Make sure to export your Corsair instance as a variable named 'corsair' or as the default export."
2312
- );
2313
- }
2314
- console.error("[#corsair]: Couldn't read your Corsair instance.");
2315
- console.log("");
2316
- console.log(
2317
- "[#corsair]: Make sure to export your Corsair instance as a variable named 'corsair' or as the default export."
2318
- );
2319
- process.exit(1);
2320
- }
2321
- break;
2322
- }
2323
- } catch (e) {
2324
- if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
2325
- "This module cannot be imported from a Client Component module"
2326
- )) {
2327
- if (shouldThrowOnError) {
2328
- throw new Error(
2329
- `Please remove import 'server-only' from your corsair.ts file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2330
- );
2331
- }
2332
- console.error(
2333
- `Please remove import 'server-only' from your corsair.ts file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2334
- );
2335
- process.exit(1);
2336
- }
2337
- const msg = typeof e === "object" && e && "message" in e && typeof e.message === "string" ? e.message : String(e);
2338
- if (msg.includes("Could not locate the bindings file") || msg.includes("NODE_MODULE_VERSION") || msg.includes(".node")) {
2339
- if (shouldThrowOnError) {
2340
- throw new Error(
2341
- `Native module error in ${possiblePath}: ${msg}
2492
+ const { runAuth: runAuth2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
2493
+ await runAuth2({
2494
+ cwd,
2495
+ pluginId: options.plugin,
2496
+ tenantId: options.tenant,
2497
+ code: options.code,
2498
+ credentials: options.credentials,
2499
+ listen: options.listen,
2500
+ collect: options.collect,
2501
+ sessionId: options.session
2502
+ });
2503
+ }
2504
+ };
2342
2505
 
2343
- This is likely because a native Node.js addon (e.g. better-sqlite3) needs to be rebuilt for your current Node.js version. Try running:
2344
- npm rebuild
2345
- or reinstall your dependencies:
2346
- rm -rf node_modules && npm install`
2347
- );
2348
- }
2349
- console.error(
2350
- `[#corsair]: Error loading ${possiblePath}: Native module binding not found.`
2351
- );
2352
- console.log("");
2353
- console.log(
2354
- "[#corsair]: A native Node.js addon (e.g. better-sqlite3) needs to be rebuilt for your current Node.js version."
2355
- );
2356
- console.log("[#corsair]: Try running:");
2357
- console.log(" npm rebuild");
2358
- console.log("[#corsair]: Or reinstall your dependencies:");
2359
- console.log(" rm -rf node_modules && npm install");
2360
- process.exit(1);
2361
- }
2362
- if (shouldThrowOnError) {
2363
- throw e;
2364
- }
2365
- console.error(`[#corsair]: Error loading ${possiblePath}:`, msg);
2366
- process.exit(1);
2367
- }
2368
- }
2369
- }
2370
- if (!corsairInstance) {
2371
- if (shouldThrowOnError) {
2372
- throw new Error(
2373
- "Couldn't find corsair.ts in your project. Make sure you have a corsair.ts file in your project root or in src/, lib/, or server/ directories."
2374
- );
2506
+ // src/commands/list.command.ts
2507
+ init_corsair_instance();
2508
+ import { listOperations } from "corsair";
2509
+ var ListCommand = class extends BaseCommand {
2510
+ getName() {
2511
+ return "list";
2512
+ }
2513
+ getDescription() {
2514
+ return "List available operations";
2515
+ }
2516
+ getOptions() {
2517
+ return [
2518
+ {
2519
+ short: "-p",
2520
+ long: "--plugin <id>",
2521
+ description: "Filter by plugin id"
2522
+ },
2523
+ {
2524
+ short: "-t",
2525
+ long: "--type <api|webhooks|db>",
2526
+ description: "Filter by operation type"
2375
2527
  }
2376
- console.error("[#corsair]: Couldn't find corsair.ts in your project.");
2377
- console.log("");
2528
+ ];
2529
+ }
2530
+ async action({ options }) {
2531
+ const { plugin, type } = options;
2532
+ const instance = await getCorsairInstance({ cwd: process.cwd() });
2533
+ const result = listOperations(instance, {
2534
+ plugin,
2535
+ type
2536
+ });
2537
+ if (type === "db") {
2378
2538
  console.log(
2379
- "[#corsair]: Make sure you have a corsair.ts file in your project root or in src/, lib/, or server/ directories."
2380
- );
2381
- process.exit(1);
2382
- }
2383
- return corsairInstance;
2384
- } catch (e) {
2385
- if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
2386
- "This module cannot be imported from a Client Component module"
2387
- )) {
2388
- if (shouldThrowOnError) {
2389
- throw new Error(
2390
- `Please remove import 'server-only' from your corsair.ts file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2391
- );
2392
- }
2393
- console.error(
2394
- `Please remove import 'server-only' from your corsair.ts file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
2539
+ "[#corsair]: NOTE: Every DB query listed here has both .search() and .list() methods available.\n"
2395
2540
  );
2396
- process.exit(1);
2397
2541
  }
2398
- if (shouldThrowOnError) {
2399
- throw e;
2400
- }
2401
- console.error("Couldn't read your Corsair instance.", e);
2402
- process.exit(1);
2542
+ console.log(result);
2403
2543
  }
2404
- }
2405
- function resolveClient(instance, tenant) {
2406
- const obj = instance;
2407
- if ("withTenant" in obj && typeof obj.withTenant === "function") {
2408
- if (!tenant) {
2409
- console.error(
2410
- "[#corsair]: This is a multi-tenant instance. Pass --tenant=<id>."
2411
- );
2412
- process.exit(1);
2413
- }
2414
- return obj.withTenant(tenant);
2544
+ };
2545
+
2546
+ // src/commands/schema.command.ts
2547
+ init_corsair_instance();
2548
+ import { getSchema } from "corsair";
2549
+ var SchemaCommand = class extends BaseCommand {
2550
+ getName() {
2551
+ return "schema";
2415
2552
  }
2416
- return obj;
2417
- }
2418
- function navigateToEndpoint(client, path4) {
2419
- const parts = path4.split(".");
2420
- let current = client;
2421
- for (const part of parts) {
2422
- if (current === null || typeof current !== "object") return void 0;
2423
- current = current[part];
2424
- }
2425
- return typeof current === "function" ? current : void 0;
2426
- }
2427
- function parseListArgs(args) {
2428
- let plugin;
2429
- let type;
2430
- for (const arg of args) {
2431
- const eqIdx = arg.indexOf("=");
2432
- if (arg.startsWith("--") && eqIdx !== -1) {
2433
- const key = arg.slice(2, eqIdx);
2434
- const value = arg.slice(eqIdx + 1);
2435
- if (key === "plugin") {
2436
- plugin = value;
2437
- continue;
2438
- }
2439
- if (key === "type" && (value === "api" || value === "webhooks" || value === "db")) {
2440
- type = value;
2441
- continue;
2442
- }
2443
- }
2553
+ getDescription() {
2554
+ return "Show schema for a specific path";
2444
2555
  }
2445
- return { plugin, type };
2446
- }
2447
- function parseAuthArgs(args) {
2448
- let pluginId;
2449
- let tenantId;
2450
- let code;
2451
- let credentials = false;
2452
- let webhook = false;
2453
- let listen = false;
2454
- let collect = false;
2455
- let sessionId;
2456
- for (const arg of args) {
2457
- if (arg === "--credentials") {
2458
- credentials = true;
2459
- continue;
2460
- }
2461
- if (arg === "--webhook") {
2462
- webhook = true;
2463
- continue;
2464
- }
2465
- if (arg === "--listen") {
2466
- listen = true;
2467
- continue;
2468
- }
2469
- if (arg === "--collect") {
2470
- collect = true;
2471
- continue;
2556
+ getArguments() {
2557
+ return [{ name: "<path>", description: "Endpoint/webhook/db path" }];
2558
+ }
2559
+ async action({ args }) {
2560
+ const schemaPath = args[0];
2561
+ if (!schemaPath) {
2562
+ console.error("[#corsair]: Usage: corsair schema <path>");
2563
+ process.exit(1);
2472
2564
  }
2473
- const eqIdx = arg.indexOf("=");
2474
- if (arg.startsWith("--") && eqIdx !== -1) {
2475
- const key = arg.slice(2, eqIdx);
2476
- const value = arg.slice(eqIdx + 1);
2477
- if (key === "plugin") {
2478
- pluginId = value;
2479
- continue;
2480
- }
2481
- if (key === "tenant") {
2482
- tenantId = value;
2483
- continue;
2484
- }
2485
- if (key === "code") {
2486
- code = value;
2487
- continue;
2488
- }
2489
- if (key === "session") {
2490
- sessionId = value;
2491
- continue;
2565
+ const instance = await getCorsairInstance({ cwd: process.cwd() });
2566
+ const result = getSchema(instance, schemaPath);
2567
+ console.log(result);
2568
+ }
2569
+ };
2570
+
2571
+ // src/commands/script.command.ts
2572
+ init_corsair_instance();
2573
+ var AsyncFunction = Object.getPrototypeOf(async function() {
2574
+ }).constructor;
2575
+ var ScriptCommand = class extends BaseCommand {
2576
+ getName() {
2577
+ return "script";
2578
+ }
2579
+ getDescription() {
2580
+ return "Execute inline JavaScript with corsair injected";
2581
+ }
2582
+ getOptions() {
2583
+ return [
2584
+ {
2585
+ short: "-c",
2586
+ long: "--code <js>",
2587
+ description: "Async JavaScript body to execute"
2588
+ },
2589
+ {
2590
+ short: "-t",
2591
+ long: "--tenant <id>",
2592
+ description: "Tenant id for multi-tenant instances"
2492
2593
  }
2493
- }
2594
+ ];
2494
2595
  }
2495
- return {
2496
- pluginId,
2497
- tenantId,
2498
- code,
2499
- credentials,
2500
- webhook,
2501
- listen,
2502
- collect,
2503
- sessionId
2504
- };
2505
- }
2506
- function parseSetupArgs(args) {
2507
- let backfill = false;
2508
- let tenantId;
2509
- const credentials = {};
2510
- let currentPlugin = null;
2511
- for (let i = 0; i < args.length; i++) {
2512
- const arg = args[i];
2513
- if (arg === "--backfill" || arg === "-backfill") {
2514
- backfill = true;
2515
- currentPlugin = null;
2516
- continue;
2517
- }
2518
- if (arg === "--tenant" && args[i + 1]) {
2519
- tenantId = args[++i];
2520
- currentPlugin = null;
2521
- continue;
2522
- }
2523
- if (arg.startsWith("--tenant=")) {
2524
- tenantId = arg.slice("--tenant=".length);
2525
- currentPlugin = null;
2526
- continue;
2527
- }
2528
- if (arg.startsWith("--plugin=")) {
2529
- currentPlugin = arg.slice("--plugin=".length);
2530
- if (!credentials[currentPlugin]) credentials[currentPlugin] = {};
2531
- continue;
2596
+ async action({ options }) {
2597
+ const { code, tenant } = options;
2598
+ if (!code) {
2599
+ console.error('[#corsair]: Usage: corsair script --code "<js>"');
2600
+ process.exit(1);
2532
2601
  }
2533
- if (arg.startsWith("--")) {
2534
- continue;
2602
+ let fn;
2603
+ try {
2604
+ fn = new AsyncFunction("corsair", code);
2605
+ } catch (error) {
2606
+ this.exitWithScriptError(error);
2535
2607
  }
2536
- if (currentPlugin && arg.includes("=")) {
2537
- const eqIdx = arg.indexOf("=");
2538
- const field = arg.slice(0, eqIdx);
2539
- const value = arg.slice(eqIdx + 1);
2540
- credentials[currentPlugin][field] = value;
2608
+ const instance = await getCorsairInstance({ cwd: process.cwd() });
2609
+ const client = resolveClient(instance, tenant);
2610
+ try {
2611
+ const result = await fn(client);
2612
+ if (result !== void 0) console.log(JSON.stringify(result, null, 2));
2613
+ } catch (error) {
2614
+ this.exitWithScriptError(error);
2541
2615
  }
2542
2616
  }
2543
- return { backfill, tenantId, credentials };
2544
- }
2545
- function parseRunArgs(args) {
2546
- let endpointPath;
2547
- let input;
2548
- let tenant;
2549
- for (let i = 0; i < args.length; i++) {
2550
- const arg = args[i];
2551
- if (arg === "--tenant" && args[i + 1]) {
2552
- tenant = args[++i];
2553
- } else if (arg.startsWith("--tenant=")) {
2554
- tenant = arg.slice("--tenant=".length);
2555
- } else if (arg === "--input" && args[i + 1]) {
2556
- input = args[++i];
2557
- } else if (arg.startsWith("--input=")) {
2558
- input = arg.slice("--input=".length);
2559
- } else if (!arg.startsWith("-")) {
2560
- if (!endpointPath) endpointPath = arg;
2561
- else if (!input) input = arg;
2562
- }
2617
+ exitWithScriptError(error) {
2618
+ const msg = error instanceof Error ? error.message : String(error);
2619
+ console.error(`[#corsair]: ${msg.slice(0, 500)}`);
2620
+ process.exit(1);
2563
2621
  }
2564
- return { path: endpointPath, input, tenant };
2565
- }
2566
- function parseUiArgs(args) {
2567
- let port;
2568
- let open;
2569
- for (let i = 0; i < args.length; i++) {
2570
- const arg = args[i];
2571
- if (arg === "--no-open") {
2572
- open = false;
2573
- continue;
2574
- }
2575
- if (arg === "--open") {
2576
- open = true;
2577
- continue;
2578
- }
2579
- if (arg === "--port" && args[i + 1]) {
2580
- const next = args[++i];
2581
- if (next) {
2582
- const parsed = Number.parseInt(next, 10);
2583
- if (Number.isFinite(parsed)) port = parsed;
2622
+ };
2623
+
2624
+ // src/commands/setup.command.ts
2625
+ init_corsair_instance();
2626
+ import { setupCorsair } from "corsair";
2627
+ var SetupCommand = class extends BaseCommand {
2628
+ getName() {
2629
+ return "setup";
2630
+ }
2631
+ getDescription() {
2632
+ return "Initialize Corsair and set plugin credentials";
2633
+ }
2634
+ getOptions() {
2635
+ return [
2636
+ {
2637
+ short: "-b",
2638
+ long: "--backfill",
2639
+ description: "Seed data while initializing"
2640
+ },
2641
+ {
2642
+ short: "-t",
2643
+ long: "--tenant <id>",
2644
+ description: "Tenant id for multi-tenant setup"
2645
+ },
2646
+ {
2647
+ short: "-p",
2648
+ long: "--plugin <id>",
2649
+ description: "Plugin id for credentials"
2584
2650
  }
2585
- continue;
2586
- }
2587
- if (arg.startsWith("--port=")) {
2588
- const parsed = Number.parseInt(arg.slice("--port=".length), 10);
2589
- if (Number.isFinite(parsed)) port = parsed;
2590
- }
2651
+ ];
2591
2652
  }
2592
- return { port, open };
2593
- }
2594
- function parseScriptArgs(args) {
2595
- let code;
2596
- let tenant;
2597
- for (let i = 0; i < args.length; i++) {
2598
- const arg = args[i];
2599
- if (arg === "--code" && args[i + 1]) {
2600
- code = args[++i];
2601
- } else if (arg.startsWith("--code=")) {
2602
- code = arg.slice("--code=".length);
2603
- } else if (arg === "--tenant" && args[i + 1]) {
2604
- tenant = args[++i];
2605
- } else if (arg.startsWith("--tenant=")) {
2606
- tenant = arg.slice("--tenant=".length);
2607
- }
2653
+ getArguments() {
2654
+ return [
2655
+ {
2656
+ name: "[credentials...]",
2657
+ description: "Credential pairs like key=value"
2658
+ }
2659
+ ];
2608
2660
  }
2609
- return { code, tenant };
2610
- }
2611
- function printHelp() {
2612
- const lines = [
2613
- "Corsair CLI",
2614
- "",
2615
- "pnpm corsair setup [--tenant=<id>] Init (add -backfill to seed data)",
2616
- "pnpm corsair setup [--tenant=<id>] --plugin=<id> <field>=VALUE Set plugin credentials",
2617
- "pnpm corsair auth --plugin=<id> Start OAuth flow",
2618
- "pnpm corsair auth --plugin=<id> --code=<code> Exchange OAuth code for tokens",
2619
- "pnpm corsair auth --plugin=<id> --credentials Show credential status",
2620
- "pnpm corsair auth --plugin=<id> --webhook Set up webhook subscription",
2621
- " `pnpm corsair list --type=webhooks` to see webhook plugins",
2622
- "pnpm corsair list [--plugin=<id>] [--type=api|webhooks|db] List endpoint paths (tip: pipe to grep to filter)",
2623
- "pnpm corsair schema <path> Show schema for an endpoint/webhook/DB entity",
2624
- "pnpm corsair ui [--port=4317] [--no-open] Open the Corsair Studio dashboard (requires @corsair-dev/studio)",
2625
- 'pnpm corsair script --code "<js>" [--tenant=<id>]',
2626
- " corsair is injected; use return to output a value.",
2627
- " IMPORTANT: Always filter results inline \u2014 you are the consumer of the return value, so returning full list responses wastes tokens.",
2628
- " Bad: return await corsair.slack.api.users.list({})",
2629
- " Good: return (await corsair.slack.api.users.list({})).members.find(u => u.name === 'bob')?.id",
2630
- ...SHOW_RUN ? [" run <path> [input-json] [--tenant=<id>] Call an endpoint directly"] : []
2631
- ];
2632
- console.log(lines.join("\n"));
2633
- }
2634
- async function main() {
2635
- const cwd = process.cwd();
2636
- const args = process.argv.slice(2);
2637
- const command = args[0];
2638
- if (command === "setup") {
2639
- const { backfill, tenantId, credentials } = parseSetupArgs(args.slice(1));
2640
- const { setupCorsair } = await import("corsair/setup");
2661
+ async action({ options }) {
2662
+ const cwd = process.cwd();
2663
+ const backfill = options.backfill || this.hasLegacyBackfillFlag();
2664
+ const tenantId = options.tenant;
2641
2665
  const instance = await getCorsairInstance({ cwd });
2642
2666
  await setupCorsair(instance, {
2643
2667
  backfill,
2644
2668
  tenantId,
2645
- // credentials,
2646
2669
  caller: "cli"
2647
2670
  });
2648
- return;
2649
2671
  }
2650
- if (command === "auth") {
2651
- const authArgs = parseAuthArgs(args.slice(1));
2652
- if (authArgs.webhook) {
2653
- const pluginId = authArgs.pluginId;
2654
- if (!pluginId) {
2655
- console.error("[#corsair]: --webhook requires --plugin=<id>.");
2656
- process.exit(1);
2657
- }
2658
- if (pluginId === "outlook") {
2659
- const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2660
- await runOutlookSubscribe2({ cwd });
2661
- } else if (pluginId === "sharepoint") {
2662
- const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2663
- await runSharepointSubscribe2({ cwd });
2664
- } else if (pluginId === "teams") {
2665
- const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2666
- await runTeamsSubscribe2({ cwd });
2667
- } else if (pluginId === "onedrive") {
2668
- const { runOnedriveSubscribe: runOnedriveSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2669
- await runOnedriveSubscribe2({ cwd });
2670
- } else if (["gmail", "googledrive", "googlecalendar", "googlesheets"].includes(
2671
- pluginId
2672
- )) {
2673
- const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2674
- await runGoogleSubscribe2({ cwd, pluginId });
2675
- } else {
2676
- console.error(
2677
- `[#corsair]: Webhook subscription not supported for plugin '${pluginId}'.`
2678
- );
2679
- console.error(
2680
- "[#corsair]: Supported: outlook, sharepoint, teams, onedrive, gmail, googledrive, googlecalendar, googlesheets"
2681
- );
2682
- process.exit(1);
2683
- }
2684
- return;
2685
- }
2686
- const { runAuth: runAuth2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
2687
- await runAuth2({ cwd, ...authArgs });
2688
- return;
2672
+ hasLegacyBackfillFlag() {
2673
+ const setupIdx = process.argv.indexOf("setup");
2674
+ const rawArgs = setupIdx >= 0 ? process.argv.slice(setupIdx + 1) : [];
2675
+ return rawArgs.some((arg) => arg === "-backfill");
2689
2676
  }
2690
- if (command === "watch-renew") {
2691
- const { runGoogleSubscribe: runGoogleSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_google(), subscribe_google_exports));
2692
- await runGoogleSubscribe2({ cwd });
2693
- return;
2694
- }
2695
- if (command === "sharepoint-subscribe") {
2696
- const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2697
- await runSharepointSubscribe2({ cwd });
2698
- return;
2699
- }
2700
- if (command === "subscribe") {
2701
- const pluginArg = args.slice(1).find((a) => a.startsWith("--plugin="));
2702
- const pluginId = pluginArg ? pluginArg.slice("--plugin=".length) : void 0;
2703
- if (pluginId === "outlook") {
2704
- const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2705
- await runOutlookSubscribe2({ cwd });
2706
- return;
2707
- }
2708
- console.error(
2709
- `[#corsair]: Unknown plugin for subscribe: '${pluginId ?? "(none)"}'. Supported: outlook`
2710
- );
2711
- process.exit(1);
2677
+ };
2678
+
2679
+ // src/commands/studio.command.ts
2680
+ import path4 from "path";
2681
+ var StudioCommand = class extends BaseCommand {
2682
+ getName() {
2683
+ return "ui";
2712
2684
  }
2713
- if (command === "teams-subscribe") {
2714
- const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2715
- await runTeamsSubscribe2({ cwd });
2716
- return;
2685
+ getAliases() {
2686
+ return ["studio"];
2717
2687
  }
2718
- if (command === "list") {
2719
- const { plugin, type } = parseListArgs(args.slice(1));
2720
- const instance = await getCorsairInstance({ cwd });
2721
- const result = listOperations(instance, {
2722
- plugin,
2723
- type
2724
- });
2725
- if (type === "db") {
2726
- console.log(
2727
- "[#corsair]: NOTE: Every DB query listed here has both .search() and .list() methods available."
2728
- );
2729
- console.log("");
2730
- }
2731
- console.log(result);
2732
- return;
2733
- }
2734
- if (SHOW_RUN && command === "run") {
2735
- const { path: endpointPath, input, tenant } = parseRunArgs(args.slice(1));
2736
- if (!endpointPath) {
2737
- console.error("[#corsair]: Usage: corsair run <path> [input-json]");
2738
- console.error(
2739
- `[#corsair]: Example: corsair run slack.api.messages.post '{"channel":"C123","text":"hi"}'`
2740
- );
2741
- process.exit(1);
2742
- }
2743
- const instance = await getCorsairInstance({ cwd });
2744
- const client = resolveClient(instance, tenant);
2745
- const fn = navigateToEndpoint(client, endpointPath);
2746
- if (!fn) {
2747
- console.error(`[#corsair]: Could not find endpoint "${endpointPath}".`);
2748
- console.error(
2749
- "[#corsair]: Run `pnpm corsair list` to see available paths."
2750
- );
2751
- process.exit(1);
2752
- }
2753
- let parsedInput = {};
2754
- if (input) {
2755
- try {
2756
- parsedInput = JSON.parse(input);
2757
- } catch {
2758
- console.error(
2759
- "[#corsair]: Invalid JSON input. Make sure to quote the JSON string."
2760
- );
2761
- process.exit(1);
2762
- }
2763
- }
2764
- try {
2765
- const result = await fn(parsedInput);
2766
- console.log(JSON.stringify(result, null, 2));
2767
- } catch (e) {
2768
- const msg = e instanceof Error ? e.message : String(e);
2769
- console.error(`[#corsair]: ${msg.slice(0, 500)}`);
2770
- process.exit(1);
2771
- }
2772
- return;
2688
+ getDescription() {
2689
+ return "Start Corsair Studio";
2773
2690
  }
2774
- if (command === "script") {
2775
- const { code, tenant } = parseScriptArgs(args.slice(1));
2776
- if (!code) {
2777
- console.error('[#corsair]: Usage: corsair script --code "<js>"');
2778
- console.error(
2779
- `[#corsair]: Example: corsair script --code "const r = await corsair.slack.channels.list(); return r.channels.find(c => c.name === 'general')?.id"`
2780
- );
2781
- process.exit(1);
2782
- }
2783
- const instance = await getCorsairInstance({ cwd });
2784
- const client = resolveClient(instance, tenant);
2785
- const AsyncFunction = Object.getPrototypeOf(async function() {
2786
- }).constructor;
2787
- const fn = new AsyncFunction("corsair", code);
2788
- try {
2789
- const result = await fn(client);
2790
- if (result !== void 0) {
2791
- console.log(JSON.stringify(result, null, 2));
2691
+ getOptions() {
2692
+ return [
2693
+ {
2694
+ short: "-p",
2695
+ long: "--port <number>",
2696
+ description: "Port to start Studio on"
2697
+ },
2698
+ { short: "-o", long: "--open", description: "Open browser on launch" },
2699
+ {
2700
+ short: "-O",
2701
+ long: "--no-open",
2702
+ description: "Do not open browser on launch"
2792
2703
  }
2793
- } catch (e) {
2794
- const msg = e instanceof Error ? e.message : String(e);
2795
- console.error(`[#corsair]: ${msg.slice(0, 500)}`);
2796
- process.exit(1);
2797
- }
2798
- return;
2704
+ ];
2799
2705
  }
2800
- if (command === "ui" || command === "studio") {
2801
- const { port, open } = parseUiArgs(args.slice(1));
2706
+ async action({ options }) {
2707
+ const cwd = process.cwd();
2708
+ const port = options.port ? Number.parseInt(options.port, 10) : void 0;
2802
2709
  let startStudio;
2803
2710
  try {
2804
2711
  const { createRequire } = await import("module");
2805
2712
  const { pathToFileURL } = await import("url");
2806
- const req = createRequire(path3.join(cwd, "package.json"));
2713
+ const req = createRequire(path4.join(cwd, "package.json"));
2807
2714
  const resolvedPath = req.resolve("@corsair-dev/studio/server");
2808
2715
  const mod = await import(pathToFileURL(resolvedPath).href);
2809
2716
  const candidate = mod.start ?? mod.startStudio;
@@ -2811,41 +2718,219 @@ async function main() {
2811
2718
  throw new Error("@corsair-dev/studio/server did not export `start`.");
2812
2719
  }
2813
2720
  startStudio = candidate;
2814
- } catch (err) {
2815
- const msg = err instanceof Error ? err.message : String(err);
2721
+ } catch (error) {
2722
+ const msg = error instanceof Error ? error.message : String(error);
2816
2723
  if (msg.includes("Cannot find package") || msg.includes("Cannot find module") || msg.includes("ERR_MODULE_NOT_FOUND") || msg.includes("MODULE_NOT_FOUND")) {
2817
2724
  console.error("[#corsair]: Corsair Studio is not installed.");
2818
- console.error("[#corsair]: Install it with:");
2819
- console.error("");
2820
- console.error(" pnpm add -D @corsair-dev/studio");
2821
- console.error("");
2725
+ console.error(
2726
+ "[#corsair]: Install it with: pnpm add -D @corsair-dev/studio"
2727
+ );
2822
2728
  process.exit(1);
2823
2729
  }
2824
- throw err;
2730
+ throw error;
2825
2731
  }
2826
- await startStudio({ cwd, port, open });
2732
+ await startStudio({ cwd, port, open: options.open });
2827
2733
  await new Promise((resolve) => {
2828
2734
  const shutdown = () => resolve();
2829
2735
  process.once("SIGINT", shutdown);
2830
2736
  process.once("SIGTERM", shutdown);
2831
2737
  });
2832
- return;
2833
2738
  }
2834
- if (command === "schema") {
2835
- const schemaPath = args[1];
2836
- if (!schemaPath) {
2837
- console.error("[#corsair]: Usage: corsair schema <path>");
2739
+ };
2740
+
2741
+ // src/commands/subscribe/teams.command.ts
2742
+ var TeamsCommand = class extends BaseCommand {
2743
+ getName() {
2744
+ return "teams";
2745
+ }
2746
+ getDescription() {
2747
+ return "Subscribe Teams webhooks";
2748
+ }
2749
+ async action({}) {
2750
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2751
+ await runTeamsSubscribe2({ cwd: process.cwd() });
2752
+ }
2753
+ };
2754
+
2755
+ // src/commands/subscribe/sharepoint.command.ts
2756
+ init_sharepoint();
2757
+ var SharepointCommand = class extends BaseCommand {
2758
+ getName() {
2759
+ return "sharepoint";
2760
+ }
2761
+ getDescription() {
2762
+ return "Subscribe SharePoint webhooks";
2763
+ }
2764
+ async action({}) {
2765
+ await runSharepointSubscribe({ cwd: process.cwd() });
2766
+ }
2767
+ };
2768
+
2769
+ // src/commands/subscribe/outlook.command.ts
2770
+ init_subscribe_microsoft();
2771
+ var OutlookCommand = class extends BaseCommand {
2772
+ getName() {
2773
+ return "outlook";
2774
+ }
2775
+ getDescription() {
2776
+ return "Subscribe Outlook webhooks";
2777
+ }
2778
+ async action({}) {
2779
+ await runOutlookSubscribe({ cwd: process.cwd() });
2780
+ }
2781
+ };
2782
+
2783
+ // src/commands/subscribe/onedrive.command.ts
2784
+ var OnedriveCommand = class extends BaseCommand {
2785
+ getName() {
2786
+ return "onedrive";
2787
+ }
2788
+ getDescription() {
2789
+ return "Subscribe OneDrive webhooks";
2790
+ }
2791
+ async action({}) {
2792
+ const { runOnedriveSubscribe: runOnedriveSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2793
+ await runOnedriveSubscribe2({ cwd: process.cwd() });
2794
+ }
2795
+ };
2796
+
2797
+ // src/commands/subscribe.command.ts
2798
+ var SubscribeCommand = class extends BaseCommand {
2799
+ getName() {
2800
+ return "subscribe";
2801
+ }
2802
+ getDescription() {
2803
+ return "Subscribe to various kinds of webhooks";
2804
+ }
2805
+ getOptions() {
2806
+ return [
2807
+ {
2808
+ short: "-p",
2809
+ long: "--plugin <id>",
2810
+ description: "Plugin id (legacy: prefer `corsair subscribe <plugin>`)"
2811
+ }
2812
+ ];
2813
+ }
2814
+ getSubCommands() {
2815
+ return [
2816
+ new SharepointCommand(),
2817
+ new TeamsCommand(),
2818
+ new OutlookCommand(),
2819
+ new OnedriveCommand()
2820
+ ];
2821
+ }
2822
+ async action({ options }) {
2823
+ if (!options.plugin) {
2824
+ console.error(
2825
+ "Usage: corsair subscribe --plugin=<id> or corsair subscribe <plugin>"
2826
+ );
2838
2827
  console.error(
2839
- "[#corsair]: Example: corsair schema slack.api.messages.post"
2828
+ "[#corsair]: Supported: outlook, sharepoint, teams, onedrive"
2840
2829
  );
2841
2830
  process.exit(1);
2842
2831
  }
2843
- const instance = await getCorsairInstance({ cwd });
2844
- const result = getSchema(instance, schemaPath);
2845
- console.log(result);
2846
- return;
2832
+ if (options.plugin === "outlook") {
2833
+ const { runOutlookSubscribe: runOutlookSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2834
+ await runOutlookSubscribe2({ cwd: process.cwd() });
2835
+ return;
2836
+ }
2837
+ if (options.plugin === "sharepoint") {
2838
+ const { runSharepointSubscribe: runSharepointSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2839
+ await runSharepointSubscribe2({ cwd: process.cwd() });
2840
+ return;
2841
+ }
2842
+ if (options.plugin === "teams") {
2843
+ const { runTeamsSubscribe: runTeamsSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2844
+ await runTeamsSubscribe2({ cwd: process.cwd() });
2845
+ return;
2846
+ }
2847
+ if (options.plugin === "onedrive") {
2848
+ const { runOnedriveSubscribe: runOnedriveSubscribe2 } = await Promise.resolve().then(() => (init_subscribe_microsoft(), subscribe_microsoft_exports));
2849
+ await runOnedriveSubscribe2({ cwd: process.cwd() });
2850
+ return;
2851
+ }
2852
+ console.error(
2853
+ `[#corsair]: Unknown plugin for subscribe: '${options.plugin}'. Supported: outlook, sharepoint, teams, onedrive`
2854
+ );
2855
+ process.exit(1);
2856
+ }
2857
+ };
2858
+
2859
+ // src/commands/sharepoint-subscribe.command.ts
2860
+ var SharepointSubscribeCommand = class extends SharepointCommand {
2861
+ getName() {
2862
+ return "sharepoint-subscribe";
2863
+ }
2864
+ getDescription() {
2865
+ return "Subscribe SharePoint webhooks";
2847
2866
  }
2848
- printHelp();
2867
+ };
2868
+
2869
+ // src/commands/teams-subscribe.command.ts
2870
+ var TeamsSubscribeCommand = class extends TeamsCommand {
2871
+ getName() {
2872
+ return "teams-subscribe";
2873
+ }
2874
+ getDescription() {
2875
+ return "Subscribe Teams webhooks";
2876
+ }
2877
+ };
2878
+
2879
+ // src/commands/onedrive-subscribe.command.ts
2880
+ var OnedriveSubscribeCommand = class extends OnedriveCommand {
2881
+ getName() {
2882
+ return "onedrive-subscribe";
2883
+ }
2884
+ getDescription() {
2885
+ return "Subscribe OneDrive webhooks";
2886
+ }
2887
+ };
2888
+
2889
+ // src/commands/watch-renew.command.ts
2890
+ init_google();
2891
+ var WatchRenewCommand = class extends BaseCommand {
2892
+ getName() {
2893
+ return "watch-renew";
2894
+ }
2895
+ getDescription() {
2896
+ return "Renew Google webhook subscriptions";
2897
+ }
2898
+ async action({}) {
2899
+ await runGoogleSubscribe({ cwd: process.cwd() });
2900
+ }
2901
+ };
2902
+
2903
+ // src/index.ts
2904
+ init_corsair_instance();
2905
+ function createProgram() {
2906
+ const program = new Command();
2907
+ program.name("corsair");
2908
+ program.version(version, "-v, --version", "Output the current version");
2909
+ const COMMANDS = [
2910
+ new SetupCommand(),
2911
+ new AuthCommand(),
2912
+ new WatchRenewCommand(),
2913
+ new SubscribeCommand(),
2914
+ new SharepointSubscribeCommand(),
2915
+ new TeamsSubscribeCommand(),
2916
+ new OnedriveSubscribeCommand(),
2917
+ new ListCommand(),
2918
+ new SchemaCommand(),
2919
+ new ScriptCommand(),
2920
+ new StudioCommand()
2921
+ ];
2922
+ COMMANDS.forEach((command) => {
2923
+ command.prepare(program);
2924
+ });
2925
+ return program;
2926
+ }
2927
+ function normalizeLegacyArgs(argv) {
2928
+ return argv.map((arg, index) => {
2929
+ if (arg === "-backfill" && argv.slice(0, index).includes("setup")) {
2930
+ return "--backfill";
2931
+ }
2932
+ return arg;
2933
+ });
2849
2934
  }
2850
2935
  function detectIsMainModule() {
2851
2936
  const argv1 = process.argv[1];
@@ -2858,81 +2943,11 @@ function detectIsMainModule() {
2858
2943
  return import.meta.url === `file://${argv1.replace(/\\/g, "/")}`;
2859
2944
  }
2860
2945
  }
2861
- var possiblePaths, jitiOptions, isCorsairInstance, SHOW_RUN;
2862
- var init_index = __esm({
2863
- "index.ts"() {
2864
- init_get_tsconfig_info();
2865
- possiblePaths = [
2866
- "corsair.ts",
2867
- "corsair.tsx",
2868
- "corsair.js",
2869
- "corsair.jsx",
2870
- "src/corsair.ts",
2871
- "src/corsair.tsx",
2872
- "src/corsair.js",
2873
- "src/corsair.jsx",
2874
- "lib/corsair.ts",
2875
- "lib/corsair.tsx",
2876
- "lib/corsair.js",
2877
- "lib/corsair.jsx",
2878
- "server/corsair.ts",
2879
- "server/corsair.tsx",
2880
- "server/corsair.js",
2881
- "server/corsair.jsx",
2882
- "src/server/corsair.ts",
2883
- "src/server/corsair.tsx",
2884
- "src/server/corsair.js",
2885
- "src/server/corsair.jsx",
2886
- "app/corsair.ts",
2887
- "app/corsair.tsx",
2888
- "app/corsair.js",
2889
- "app/corsair.jsx",
2890
- "corsair/index.ts",
2891
- "corsair/index.tsx",
2892
- "corsair/index.js",
2893
- "corsair/index.jsx"
2894
- ];
2895
- jitiOptions = (cwd) => {
2896
- const alias = getPathAliases(cwd) || {};
2897
- return {
2898
- transformOptions: {
2899
- babel: {
2900
- presets: [
2901
- [
2902
- babelPresetTypeScript,
2903
- {
2904
- isTSX: true,
2905
- allExtensions: true
2906
- }
2907
- ],
2908
- [babelPresetReact, { runtime: "automatic" }]
2909
- ]
2910
- }
2911
- },
2912
- extensions: [".ts", ".tsx", ".js", ".jsx"],
2913
- alias
2914
- };
2915
- };
2916
- isCorsairInstance = (object) => {
2917
- if (typeof object !== "object" || object === null || Array.isArray(object)) {
2918
- return false;
2919
- }
2920
- if ("withTenant" in object && typeof object.withTenant === "function") {
2921
- return true;
2922
- }
2923
- return Object.keys(object).length > 0;
2924
- };
2925
- SHOW_RUN = false;
2926
- if (detectIsMainModule()) {
2927
- main().then(() => process.exit(0)).catch((e) => {
2928
- console.error(e);
2929
- process.exit(1);
2930
- });
2931
- }
2932
- }
2933
- });
2934
- init_index();
2946
+ if (detectIsMainModule()) {
2947
+ createProgram().parse(normalizeLegacyArgs(process.argv));
2948
+ }
2935
2949
  export {
2950
+ createProgram,
2936
2951
  findCorsairConfigPath,
2937
2952
  getCorsairInstance
2938
2953
  };