@vercel/slack-bolt 1.4.0 → 1.4.2

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.
@@ -0,0 +1,794 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let node_fs = require("node:fs");
25
+ node_fs = __toESM(node_fs);
26
+ let node_path = require("node:path");
27
+ node_path = __toESM(node_path);
28
+ let yaml = require("yaml");
29
+ let node_crypto = require("node:crypto");
30
+ node_crypto = __toESM(node_crypto);
31
+ //#region src/internal/manifest/index.ts
32
+ function rewriteUrl(originalUrl, branchUrl, bypassSecret) {
33
+ const pathStart = originalUrl.indexOf("/", originalUrl.indexOf("//") + 2);
34
+ const pathAndQuery = pathStart !== -1 ? originalUrl.slice(pathStart) : "/";
35
+ const url = new URL(pathAndQuery, `https://${branchUrl}`);
36
+ if (bypassSecret) url.searchParams.set("x-vercel-protection-bypass", bypassSecret);
37
+ return url.toString();
38
+ }
39
+ function createManifestDescription(params) {
40
+ const shortSha = params.commitSha?.slice(0, 7) ?? "unknown";
41
+ const safeCommitMsg = params.commitMessage ?? "";
42
+ const safeCommitAuthor = params.commitAuthor ?? "unknown";
43
+ const deploymentInfo = `\n:globe_with_meridians: *Deployment URL:* ${params.branchUrl}\n:seedling: *Branch:* ${params.branch}\n:technologist: *Commit:* ${shortSha} ${safeCommitMsg}\n:bust_in_silhouette: *Last updated by:* ${safeCommitAuthor}\n\n_Automatically created by ▲ Vercel_\n`;
44
+ const maxLongDesc = 4e3;
45
+ const combined = params.existingDescription + deploymentInfo;
46
+ let longDescription;
47
+ if (combined.length > maxLongDesc) {
48
+ const available = Math.max(0, maxLongDesc - deploymentInfo.length);
49
+ longDescription = (params.existingDescription.slice(0, available) + deploymentInfo).slice(0, maxLongDesc);
50
+ } else longDescription = combined;
51
+ const maxDisplayName = 35;
52
+ const cleanBranch = params.branch.replace(/^refs\/heads\//, "").replace(/\//g, "-");
53
+ let displayName = `${params.existingName} (${cleanBranch})`;
54
+ if (displayName.length > maxDisplayName) {
55
+ const prefix = `${params.existingName} (`;
56
+ const suffix = ")";
57
+ const availableForBranch = maxDisplayName - prefix.length - 1;
58
+ displayName = availableForBranch > 0 ? `${prefix}${cleanBranch.slice(0, availableForBranch)}${suffix}` : displayName.slice(0, maxDisplayName);
59
+ }
60
+ return {
61
+ longDescription,
62
+ displayName
63
+ };
64
+ }
65
+ function createNewManifest(params) {
66
+ const manifest = structuredClone(params.originalManifest);
67
+ if (manifest.settings?.event_subscriptions?.request_url) manifest.settings.event_subscriptions.request_url = rewriteUrl(manifest.settings.event_subscriptions.request_url, params.branchUrl, params.bypassSecret);
68
+ if (manifest.settings?.interactivity?.request_url) manifest.settings.interactivity.request_url = rewriteUrl(manifest.settings.interactivity.request_url, params.branchUrl, params.bypassSecret);
69
+ if (manifest.features?.slash_commands) {
70
+ for (const cmd of manifest.features.slash_commands) if (cmd.url) cmd.url = rewriteUrl(cmd.url, params.branchUrl, params.bypassSecret);
71
+ }
72
+ if (manifest.oauth_config?.redirect_urls) manifest.oauth_config.redirect_urls = manifest.oauth_config.redirect_urls.map((originalUrl) => rewriteUrl(originalUrl, params.branchUrl));
73
+ const { longDescription, displayName } = createManifestDescription({
74
+ existingDescription: manifest.display_information.long_description ?? "",
75
+ existingName: manifest.features?.bot_user?.display_name ?? manifest.display_information.name,
76
+ branchUrl: params.branchUrl,
77
+ branch: params.branch,
78
+ commitSha: params.commitSha,
79
+ commitMessage: params.commitMessage,
80
+ commitAuthor: params.commitAuthor
81
+ });
82
+ manifest.display_information.long_description = longDescription;
83
+ manifest.display_information.name = displayName;
84
+ if (manifest.features?.bot_user) manifest.features.bot_user.display_name = displayName;
85
+ return manifest;
86
+ }
87
+ //#endregion
88
+ //#region src/internal/manifest/parse.ts
89
+ function isYaml(filePath) {
90
+ const ext = node_path.default.extname(filePath).toLowerCase();
91
+ return ext === ".yaml" || ext === ".yml";
92
+ }
93
+ function parseManifest(raw, filePath) {
94
+ if (isYaml(filePath)) return (0, yaml.parse)(raw);
95
+ return JSON.parse(raw);
96
+ }
97
+ function stringifyManifest(manifest, filePath) {
98
+ if (isYaml(filePath)) return (0, yaml.stringify)(manifest);
99
+ return JSON.stringify(manifest, null, 2);
100
+ }
101
+ //#endregion
102
+ //#region src/internal/vercel/errors.ts
103
+ var HTTPError = class HTTPError extends Error {
104
+ constructor(message, status, statusText, body) {
105
+ const parts = [`${message}: ${status} ${statusText}`];
106
+ if (body) parts.push(body);
107
+ super(parts.join(" - "));
108
+ this.status = status;
109
+ this.statusText = statusText;
110
+ this.body = body;
111
+ }
112
+ static async fromResponse(message, response) {
113
+ let body;
114
+ try {
115
+ const text = await response.text();
116
+ if (text) body = text;
117
+ } catch {}
118
+ return new HTTPError(message, response.status, response.statusText, body);
119
+ }
120
+ };
121
+ //#endregion
122
+ //#region src/internal/slack/errors.ts
123
+ var SlackManifestCreateError = class extends Error {
124
+ constructor(message, errors) {
125
+ super(message);
126
+ this.errors = errors;
127
+ }
128
+ };
129
+ var SlackManifestUpdateError = class extends Error {
130
+ constructor(message, errors) {
131
+ super(message);
132
+ this.errors = errors;
133
+ }
134
+ };
135
+ var SlackManifestExportError = class extends Error {};
136
+ //#endregion
137
+ //#region src/internal/slack/index.ts
138
+ async function createSlackApp({ token, manifest }) {
139
+ const response = await fetch("https://slack.com/api/apps.manifest.create", {
140
+ method: "POST",
141
+ headers: {
142
+ Authorization: `Bearer ${token}`,
143
+ "Content-Type": "application/json; charset=utf-8"
144
+ },
145
+ body: JSON.stringify({ manifest: JSON.stringify(manifest) })
146
+ });
147
+ if (!response.ok) throw new HTTPError("Failed to create Slack app", response.status, response.statusText);
148
+ const data = await response.json();
149
+ if (!data.ok) throw new SlackManifestCreateError(data?.error ?? "Unknown error", data?.errors);
150
+ return data;
151
+ }
152
+ async function updateSlackApp({ token, appId, manifest }) {
153
+ const response = await fetch("https://slack.com/api/apps.manifest.update", {
154
+ method: "POST",
155
+ headers: {
156
+ Authorization: `Bearer ${token}`,
157
+ "Content-Type": "application/json; charset=utf-8"
158
+ },
159
+ body: JSON.stringify({
160
+ app_id: appId,
161
+ manifest: JSON.stringify(manifest)
162
+ })
163
+ });
164
+ if (!response.ok) throw new HTTPError("Failed to update Slack app", response.status, response.statusText);
165
+ const data = await response.json();
166
+ if (!data.ok) throw new SlackManifestUpdateError(data?.error ?? "Unknown error", data?.errors);
167
+ return data;
168
+ }
169
+ async function exportSlackApp({ token, appId }) {
170
+ const response = await fetch("https://slack.com/api/apps.manifest.export", {
171
+ method: "POST",
172
+ headers: {
173
+ Authorization: `Bearer ${token}`,
174
+ "Content-Type": "application/json; charset=utf-8"
175
+ },
176
+ body: JSON.stringify({ app_id: appId })
177
+ });
178
+ if (!response.ok) throw new HTTPError("Failed to export Slack app", response.status, response.statusText);
179
+ const data = await response.json();
180
+ if (!data.ok) throw new SlackManifestExportError(data?.error ?? "Unknown error");
181
+ return data;
182
+ }
183
+ async function upsertSlackApp({ token, appId, manifest }) {
184
+ if (appId) try {
185
+ await exportSlackApp({
186
+ token,
187
+ appId
188
+ });
189
+ return {
190
+ isNew: false,
191
+ app: await updateSlackApp({
192
+ token,
193
+ appId,
194
+ manifest
195
+ })
196
+ };
197
+ } catch {}
198
+ return {
199
+ isNew: true,
200
+ app: await createSlackApp({
201
+ token,
202
+ manifest
203
+ })
204
+ };
205
+ }
206
+ async function deleteSlackApp({ token, appId }) {
207
+ const response = await fetch("https://slack.com/api/apps.manifest.delete", {
208
+ method: "POST",
209
+ headers: {
210
+ Authorization: `Bearer ${token}`,
211
+ "Content-Type": "application/json; charset=utf-8"
212
+ },
213
+ body: JSON.stringify({ app_id: appId })
214
+ });
215
+ if (!response.ok) throw new HTTPError("Failed to delete Slack app", response.status, response.statusText);
216
+ const data = await response.json();
217
+ if (!data.ok) throw new Error(data.error ?? "Unknown error");
218
+ }
219
+ async function rotateConfigToken({ refreshToken }) {
220
+ const response = await fetch("https://slack.com/api/tooling.tokens.rotate", {
221
+ method: "POST",
222
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
223
+ body: new URLSearchParams({ refresh_token: refreshToken })
224
+ });
225
+ if (!response.ok) throw new HTTPError("Failed to rotate configuration token", response.status, response.statusText);
226
+ const data = await response.json();
227
+ if (!data.ok || !data.token || !data.refresh_token) throw new Error(data.error ?? "Unknown error rotating token");
228
+ return {
229
+ token: data.token,
230
+ refreshToken: data.refresh_token,
231
+ exp: data.exp ?? 0
232
+ };
233
+ }
234
+ async function authTest({ token }) {
235
+ const response = await fetch("https://slack.com/api/auth.test", {
236
+ method: "POST",
237
+ headers: {
238
+ Authorization: `Bearer ${token}`,
239
+ "Content-Type": "application/json; charset=utf-8"
240
+ }
241
+ });
242
+ if (!response.ok) throw new HTTPError("Auth test failed", response.status, response.statusText);
243
+ const data = await response.json();
244
+ if (!data.ok) throw new Error(data.error ?? "Unknown error");
245
+ return {
246
+ userId: data.user_id ?? "",
247
+ teamId: data.team_id ?? ""
248
+ };
249
+ }
250
+ async function verifyServiceTokenAccess(params) {
251
+ try {
252
+ await exportSlackApp({
253
+ token: params.serviceToken,
254
+ appId: params.appId
255
+ });
256
+ return { hasAccess: true };
257
+ } catch {
258
+ return { hasAccess: false };
259
+ }
260
+ }
261
+ async function installApp(params) {
262
+ const { serviceToken, appId, botScopes, outgoingDomains } = params;
263
+ if (!serviceToken) return { status: "missing_service_token" };
264
+ const response = await fetch("https://slack.com/api/apps.developerInstall", {
265
+ method: "POST",
266
+ headers: {
267
+ Authorization: `Bearer ${serviceToken}`,
268
+ "Content-Type": "application/json; charset=utf-8"
269
+ },
270
+ body: JSON.stringify({
271
+ app_id: appId,
272
+ bot_scopes: botScopes,
273
+ outgoing_domains: outgoingDomains ?? []
274
+ })
275
+ });
276
+ if (!response.ok) return {
277
+ status: "slack_api_error",
278
+ error: response.statusText
279
+ };
280
+ const data = await response.json();
281
+ if (data.error) switch (data.error) {
282
+ case "app_approval_request_eligible": return { status: "app_approval_request_eligible" };
283
+ case "app_approval_request_pending": return { status: "app_approval_request_pending" };
284
+ case "app_approval_request_denied": return { status: "app_approval_request_denied" };
285
+ case "invalid_app_id":
286
+ if (serviceToken) {
287
+ const { hasAccess } = await verifyServiceTokenAccess({
288
+ serviceToken,
289
+ appId
290
+ });
291
+ if (!hasAccess) return { status: "no_access" };
292
+ }
293
+ return { status: "invalid_app_id" };
294
+ default: return { status: "unknown_error" };
295
+ }
296
+ return {
297
+ status: "installed",
298
+ botToken: data.api_access_tokens?.bot,
299
+ appLevelToken: data.api_access_tokens?.app_level,
300
+ userToken: data.api_access_tokens?.user
301
+ };
302
+ }
303
+ //#endregion
304
+ //#region src/internal/vercel/index.ts
305
+ async function getProject({ projectId, token, teamId }) {
306
+ const url = new URL(`https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}`);
307
+ if (teamId) url.searchParams.set("teamId", teamId);
308
+ const response = await fetch(url, {
309
+ method: "GET",
310
+ headers: { Authorization: `Bearer ${token}` }
311
+ });
312
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to access Vercel project", response);
313
+ }
314
+ async function updateProtectionBypass({ projectId, token, teamId }) {
315
+ const newSecret = node_crypto.default.randomBytes(16).toString("hex");
316
+ const note = "Created by @vercel/slack-bolt";
317
+ const url = new URL(`https://api.vercel.com/v1/projects/${encodeURIComponent(projectId)}/protection-bypass`);
318
+ if (teamId) url.searchParams.set("teamId", teamId);
319
+ const response = await fetch(url, {
320
+ method: "PATCH",
321
+ headers: {
322
+ Authorization: `Bearer ${token}`,
323
+ "Content-Type": "application/json"
324
+ },
325
+ body: JSON.stringify({ generate: {
326
+ secret: newSecret,
327
+ note
328
+ } })
329
+ });
330
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to update protection bypass", response);
331
+ return newSecret;
332
+ }
333
+ async function addEnvironmentVariables({ projectId, token, teamId, envs, upsert = true }) {
334
+ const url = new URL(`https://api.vercel.com/v10/projects/${encodeURIComponent(projectId)}/env`);
335
+ if (teamId) url.searchParams.set("teamId", teamId);
336
+ if (upsert) url.searchParams.set("upsert", "true");
337
+ const response = await fetch(url, {
338
+ method: "POST",
339
+ headers: {
340
+ Authorization: `Bearer ${token}`,
341
+ "Content-Type": "application/json"
342
+ },
343
+ body: JSON.stringify(envs)
344
+ });
345
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to create environment variables", response);
346
+ return response.json();
347
+ }
348
+ async function cancelDeployment({ deploymentId, token, teamId }) {
349
+ const url = new URL(`https://api.vercel.com/v12/deployments/${encodeURIComponent(deploymentId)}/cancel`);
350
+ if (teamId) url.searchParams.set("teamId", teamId);
351
+ const response = await fetch(url, {
352
+ method: "PATCH",
353
+ headers: { Authorization: `Bearer ${token}` }
354
+ });
355
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to cancel deployment", response);
356
+ }
357
+ async function createDeployment({ deploymentId, projectId, token, teamId }) {
358
+ const url = new URL("https://api.vercel.com/v13/deployments");
359
+ if (teamId) url.searchParams.set("teamId", teamId);
360
+ url.searchParams.set("forceNew", "1");
361
+ const response = await fetch(url, {
362
+ method: "POST",
363
+ headers: {
364
+ Authorization: `Bearer ${token}`,
365
+ "Content-Type": "application/json"
366
+ },
367
+ body: JSON.stringify({
368
+ deploymentId,
369
+ name: projectId,
370
+ project: projectId
371
+ })
372
+ });
373
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to create deployment", response);
374
+ const data = await response.json();
375
+ return {
376
+ id: data.id,
377
+ url: data.url
378
+ };
379
+ }
380
+ async function getActiveBranches({ projectId, token, teamId }) {
381
+ const params = new URLSearchParams({
382
+ active: "1",
383
+ limit: "100"
384
+ });
385
+ if (teamId) params.set("teamId", teamId);
386
+ const response = await fetch(`https://api.vercel.com/v5/projects/${encodeURIComponent(projectId)}/branches?${params}`, { headers: { Authorization: `Bearer ${token}` } });
387
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to fetch active branches", response);
388
+ const data = await response.json();
389
+ return new Set(data.branches?.map((b) => b.branch) ?? []);
390
+ }
391
+ async function getEnvironmentVariables({ projectId, token, teamId }) {
392
+ const url = new URL(`https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env`);
393
+ if (teamId) url.searchParams.set("teamId", teamId);
394
+ const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
395
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to fetch environment variables", response);
396
+ return (await response.json()).envs ?? [];
397
+ }
398
+ async function getEnvironmentVariable({ projectId, envId, token, teamId }) {
399
+ const url = new URL(`https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(envId)}`);
400
+ if (teamId) url.searchParams.set("teamId", teamId);
401
+ const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
402
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to fetch environment variable", response);
403
+ return (await response.json()).value ?? null;
404
+ }
405
+ async function deleteEnvironmentVariable({ projectId, envId, token, teamId }) {
406
+ const url = new URL(`https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(envId)}`);
407
+ if (teamId) url.searchParams.set("teamId", teamId);
408
+ const response = await fetch(url, {
409
+ method: "DELETE",
410
+ headers: { Authorization: `Bearer ${token}` }
411
+ });
412
+ if (!response.ok) throw await HTTPError.fromResponse("Failed to delete environment variable", response);
413
+ }
414
+ //#endregion
415
+ //#region src/logger.ts
416
+ function isDebug() {
417
+ return process.env.VERCEL_SLACK_DEBUG === "1" || process.env.VERCEL_SLACK_DEBUG === "true";
418
+ }
419
+ const BOLD = "\x1B[1m";
420
+ const RESET = "\x1B[0m";
421
+ const DIM = "\x1B[2m";
422
+ const GREEN = "\x1B[32m";
423
+ const YELLOW = "\x1B[33m";
424
+ const log = {
425
+ step: (msg) => console.log(` ${msg} ...`),
426
+ success: (msg) => console.log(`${GREEN}✓${RESET} ${msg}`),
427
+ info: (msg) => console.log(` ${msg}`),
428
+ warning: (msg) => console.log(`${YELLOW}⚠${RESET} ${msg}`),
429
+ error: (...args) => console.error(...args),
430
+ debug: (...args) => {
431
+ if (isDebug()) {
432
+ const msg = args.map((a) => typeof a === "string" ? a : String(a)).join(" ");
433
+ console.debug(`${DIM}${msg}${RESET}`);
434
+ }
435
+ }
436
+ };
437
+ const REDACTED_HEADERS = new Set(["authorization"]);
438
+ /**
439
+ * Keys whose values should be redacted when logging request/response bodies.
440
+ * Matches are case-insensitive and checked against the lowercased key.
441
+ */
442
+ const SENSITIVE_BODY_KEYS = new Set([
443
+ "token",
444
+ "bot",
445
+ "app_level",
446
+ "user",
447
+ "secret",
448
+ "client_secret",
449
+ "signing_secret",
450
+ "verification_token",
451
+ "bot_token",
452
+ "user_token",
453
+ "app_level_token",
454
+ "value",
455
+ "access_token",
456
+ "refresh_token",
457
+ "password"
458
+ ]);
459
+ /**
460
+ * Key name fragments — if any of these appear in a key name (case-insensitive),
461
+ * the value is redacted.
462
+ */
463
+ const SENSITIVE_KEY_PATTERNS = [
464
+ "token",
465
+ "secret",
466
+ "password",
467
+ "credential"
468
+ ];
469
+ function isSensitiveKey(key) {
470
+ const lower = key.toLowerCase();
471
+ if (SENSITIVE_BODY_KEYS.has(lower)) return true;
472
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => lower.includes(pattern));
473
+ }
474
+ function redactValue(value) {
475
+ if (value.length <= 4) return "****";
476
+ return `****${value.slice(-4)}`;
477
+ }
478
+ function redactSensitiveFields(obj) {
479
+ if (Array.isArray(obj)) return obj.map((item) => redactSensitiveFields(item));
480
+ if (obj !== null && typeof obj === "object") {
481
+ const result = {};
482
+ for (const [key, val] of Object.entries(obj)) if (isSensitiveKey(key) && typeof val === "string") result[key] = redactValue(val);
483
+ else result[key] = redactSensitiveFields(val);
484
+ return result;
485
+ }
486
+ return obj;
487
+ }
488
+ function redactBody(body) {
489
+ try {
490
+ const redacted = redactSensitiveFields(JSON.parse(body));
491
+ return JSON.stringify(redacted);
492
+ } catch {
493
+ return `<non-JSON body, ${body.length} bytes>`;
494
+ }
495
+ }
496
+ function formatHeaders(headers) {
497
+ const redacted = (headers instanceof Headers ? [...headers.entries()] : Object.entries(headers ?? {})).map(([k, v]) => REDACTED_HEADERS.has(k.toLowerCase()) ? [k, `****${v.slice(-4)}`] : [k, v]);
498
+ return JSON.stringify(Object.fromEntries(redacted));
499
+ }
500
+ function enableFetchDebugLogging() {
501
+ if (globalThis.fetch.__debugPatched) return;
502
+ const originalFetch = globalThis.fetch;
503
+ const patched = async (input, init) => {
504
+ const method = init?.method ?? "GET";
505
+ const url = input instanceof Request ? input.url : input.toString();
506
+ const start = performance.now();
507
+ log.debug(`-> ${method} ${url}`);
508
+ log.debug(` headers: ${formatHeaders(init?.headers)}`);
509
+ if (typeof init?.body === "string") log.debug(` body: ${redactBody(init.body)}`);
510
+ const response = await originalFetch(input, init);
511
+ const ms = (performance.now() - start).toFixed(0);
512
+ log.debug(`<- ${response.status} ${response.statusText} (${ms}ms)`);
513
+ log.debug(` headers: ${formatHeaders(response.headers)}`);
514
+ const clone = response.clone();
515
+ try {
516
+ const body = await clone.text();
517
+ if (body) log.debug(` body: ${redactBody(body)}`);
518
+ } catch {}
519
+ return response;
520
+ };
521
+ patched.__debugPatched = true;
522
+ globalThis.fetch = patched;
523
+ }
524
+ const startMessage = (version, branch, commit, appId) => {
525
+ const lines = [`▲ @vercel/slack-bolt ${version ?? ""}`];
526
+ if (branch) lines.push(` - Branch: ${branch}`);
527
+ if (commit) lines.push(` - Commit: ${commit.slice(0, 7)}`);
528
+ if (appId) lines.push(` - App ID: ${appId}`);
529
+ return `${BOLD}${lines.join("\n")}${RESET}\n`;
530
+ };
531
+ //#endregion
532
+ //#region src/preview.ts
533
+ const preview = async (params, context) => {
534
+ const { branch, projectId, deploymentUrl, teamId, commitAuthor, commitMessage: commitMsg, commitSha, slackAppId, slackConfigurationToken, slackServiceToken, manifestPath, vercelApiToken } = params;
535
+ const cli = context === "cli";
536
+ const branchUrl = params.branchUrl ?? deploymentUrl;
537
+ let bypassSecret = params.automationBypassSecret;
538
+ if (!bypassSecret) {
539
+ if (cli) log.step("Generating automation bypass secret");
540
+ bypassSecret = await updateProtectionBypass({
541
+ projectId,
542
+ token: vercelApiToken,
543
+ teamId
544
+ });
545
+ if (cli) log.success("Automation bypass secret generated");
546
+ }
547
+ if (cli) log.step(`Reading manifest from ${manifestPath}`);
548
+ const manifest = parseManifest(node_fs.default.readFileSync(node_path.default.join(process.cwd(), manifestPath), "utf8"), manifestPath);
549
+ const newManifest = createNewManifest({
550
+ originalManifest: manifest,
551
+ branchUrl,
552
+ bypassSecret,
553
+ branch,
554
+ commitSha,
555
+ commitMessage: commitMsg,
556
+ commitAuthor
557
+ });
558
+ node_fs.default.writeFileSync(node_path.default.join(process.cwd(), manifestPath), stringifyManifest(newManifest, manifestPath), "utf8");
559
+ if (cli) log.success(`Manifest updated for ${branchUrl}`);
560
+ if (cli) log.step("Creating or updating Slack app");
561
+ const { isNew, app } = await upsertSlackApp({
562
+ token: slackConfigurationToken,
563
+ appId: slackAppId,
564
+ manifest: newManifest
565
+ });
566
+ if (isNew) {
567
+ const credentialEnvs = [];
568
+ if (app.app_id) credentialEnvs.push({
569
+ key: "SLACK_APP_ID",
570
+ value: app.app_id,
571
+ type: "encrypted",
572
+ target: ["preview"],
573
+ gitBranch: branch,
574
+ comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
575
+ });
576
+ if (app.credentials?.client_id) credentialEnvs.push({
577
+ key: "SLACK_CLIENT_ID",
578
+ value: app.credentials.client_id,
579
+ type: "encrypted",
580
+ target: ["preview"],
581
+ gitBranch: branch,
582
+ comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
583
+ });
584
+ if (app.credentials?.client_secret) credentialEnvs.push({
585
+ key: "SLACK_CLIENT_SECRET",
586
+ value: app.credentials.client_secret,
587
+ type: "encrypted",
588
+ target: ["preview"],
589
+ gitBranch: branch,
590
+ comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
591
+ });
592
+ if (app.credentials?.signing_secret) credentialEnvs.push({
593
+ key: "SLACK_SIGNING_SECRET",
594
+ value: app.credentials.signing_secret,
595
+ type: "encrypted",
596
+ target: ["preview"],
597
+ gitBranch: branch,
598
+ comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
599
+ });
600
+ if (credentialEnvs.length > 0) await addEnvironmentVariables({
601
+ projectId,
602
+ token: vercelApiToken,
603
+ teamId,
604
+ envs: credentialEnvs
605
+ });
606
+ }
607
+ if (cli) log.success(`${isNew ? "Created" : "Updated"} Slack app ${app.app_id}`);
608
+ if (cli) log.step("Installing Slack app");
609
+ const { status, botToken, appLevelToken, userToken } = await installApp({
610
+ serviceToken: slackServiceToken,
611
+ appId: app.app_id,
612
+ botScopes: manifest.oauth_config?.scopes?.bot ?? []
613
+ });
614
+ if (isNew) {
615
+ const tokenEnvs = [];
616
+ if (botToken) tokenEnvs.push({
617
+ key: "SLACK_BOT_TOKEN",
618
+ value: botToken,
619
+ type: "encrypted",
620
+ target: ["preview"],
621
+ gitBranch: branch,
622
+ comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
623
+ });
624
+ if (appLevelToken) tokenEnvs.push({
625
+ key: "SLACK_APP_LEVEL_TOKEN",
626
+ value: appLevelToken,
627
+ type: "encrypted",
628
+ target: ["preview"],
629
+ gitBranch: branch,
630
+ comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
631
+ });
632
+ if (userToken) tokenEnvs.push({
633
+ key: "SLACK_USER_TOKEN",
634
+ value: userToken,
635
+ type: "encrypted",
636
+ target: ["preview"],
637
+ gitBranch: branch,
638
+ comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
639
+ });
640
+ if (tokenEnvs.length > 0) await addEnvironmentVariables({
641
+ projectId,
642
+ token: vercelApiToken,
643
+ teamId,
644
+ envs: tokenEnvs
645
+ });
646
+ }
647
+ if (cli) {
648
+ switch (status) {
649
+ case "missing_service_token":
650
+ log.warning("SLACK_SERVICE_TOKEN is not set — app must be installed manually");
651
+ log.info("https://docs.slack.dev/authentication/tokens/#service");
652
+ break;
653
+ case "installed":
654
+ log.success(`Installed Slack app ${app.app_id}`);
655
+ break;
656
+ case "app_approval_request_eligible":
657
+ log.warning("App requires approval before it can be installed");
658
+ break;
659
+ case "app_approval_request_pending":
660
+ log.warning("App is pending approval before it can be installed");
661
+ break;
662
+ case "app_approval_request_denied":
663
+ log.warning("App approval request was denied");
664
+ break;
665
+ case "no_access":
666
+ log.warning(`SLACK_SERVICE_TOKEN does not have access to app ${app.app_id}. This usually means the service token and configuration token were created by different users. Ensure both tokens are generated by the same Slack user.
667
+ https://docs.slack.dev/authentication/tokens/#service`);
668
+ break;
669
+ case "invalid_app_id":
670
+ log.warning("Invalid app ID. This is a bug in the @vercel/slack-bolt package. Please open an issue at https://github.com/vercel/slack-bolt/issues");
671
+ break;
672
+ case "slack_api_error":
673
+ log.warning("Slack API error while installing the app");
674
+ break;
675
+ case "unknown_error":
676
+ log.warning("Unknown error while installing the app");
677
+ break;
678
+ }
679
+ console.log();
680
+ if (app.app_id) log.info(`View app: https://api.slack.com/apps/${app.app_id}`);
681
+ if (isNew && app.oauth_authorize_url) log.info(`Install URL: ${app.oauth_authorize_url}`);
682
+ console.log();
683
+ }
684
+ return {
685
+ isNew,
686
+ installStatus: status,
687
+ app
688
+ };
689
+ };
690
+ //#endregion
691
+ Object.defineProperty(exports, "__commonJSMin", {
692
+ enumerable: true,
693
+ get: function() {
694
+ return __commonJSMin;
695
+ }
696
+ });
697
+ Object.defineProperty(exports, "__toESM", {
698
+ enumerable: true,
699
+ get: function() {
700
+ return __toESM;
701
+ }
702
+ });
703
+ Object.defineProperty(exports, "addEnvironmentVariables", {
704
+ enumerable: true,
705
+ get: function() {
706
+ return addEnvironmentVariables;
707
+ }
708
+ });
709
+ Object.defineProperty(exports, "authTest", {
710
+ enumerable: true,
711
+ get: function() {
712
+ return authTest;
713
+ }
714
+ });
715
+ Object.defineProperty(exports, "cancelDeployment", {
716
+ enumerable: true,
717
+ get: function() {
718
+ return cancelDeployment;
719
+ }
720
+ });
721
+ Object.defineProperty(exports, "createDeployment", {
722
+ enumerable: true,
723
+ get: function() {
724
+ return createDeployment;
725
+ }
726
+ });
727
+ Object.defineProperty(exports, "deleteEnvironmentVariable", {
728
+ enumerable: true,
729
+ get: function() {
730
+ return deleteEnvironmentVariable;
731
+ }
732
+ });
733
+ Object.defineProperty(exports, "deleteSlackApp", {
734
+ enumerable: true,
735
+ get: function() {
736
+ return deleteSlackApp;
737
+ }
738
+ });
739
+ Object.defineProperty(exports, "enableFetchDebugLogging", {
740
+ enumerable: true,
741
+ get: function() {
742
+ return enableFetchDebugLogging;
743
+ }
744
+ });
745
+ Object.defineProperty(exports, "getActiveBranches", {
746
+ enumerable: true,
747
+ get: function() {
748
+ return getActiveBranches;
749
+ }
750
+ });
751
+ Object.defineProperty(exports, "getEnvironmentVariable", {
752
+ enumerable: true,
753
+ get: function() {
754
+ return getEnvironmentVariable;
755
+ }
756
+ });
757
+ Object.defineProperty(exports, "getEnvironmentVariables", {
758
+ enumerable: true,
759
+ get: function() {
760
+ return getEnvironmentVariables;
761
+ }
762
+ });
763
+ Object.defineProperty(exports, "getProject", {
764
+ enumerable: true,
765
+ get: function() {
766
+ return getProject;
767
+ }
768
+ });
769
+ Object.defineProperty(exports, "log", {
770
+ enumerable: true,
771
+ get: function() {
772
+ return log;
773
+ }
774
+ });
775
+ Object.defineProperty(exports, "preview", {
776
+ enumerable: true,
777
+ get: function() {
778
+ return preview;
779
+ }
780
+ });
781
+ Object.defineProperty(exports, "rotateConfigToken", {
782
+ enumerable: true,
783
+ get: function() {
784
+ return rotateConfigToken;
785
+ }
786
+ });
787
+ Object.defineProperty(exports, "startMessage", {
788
+ enumerable: true,
789
+ get: function() {
790
+ return startMessage;
791
+ }
792
+ });
793
+
794
+ //# sourceMappingURL=preview-DeqpNNn_.js.map