@vercel/slack-bolt 1.7.3 → 1.7.5
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.
- package/dist/cli.js +17 -22
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +18 -24
- package/dist/cli.mjs.map +1 -1
- package/dist/index.d.mts +1 -4
- package/dist/index.d.ts +1 -4
- package/dist/index.js +3 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -6
- package/dist/index.mjs.map +1 -1
- package/dist/{preview-DS5gSBPc.js → preview-BDw2rRw6.js} +10 -19
- package/dist/{preview-DS5gSBPc.js.map → preview-BDw2rRw6.js.map} +1 -1
- package/dist/{preview-CMaJzzRK.mjs → preview-CzafLVhR.mjs} +10 -21
- package/dist/{preview-CMaJzzRK.mjs.map → preview-CzafLVhR.mjs.map} +1 -1
- package/dist/preview.d.mts +1 -6
- package/dist/preview.d.ts +1 -6
- package/dist/preview.js +1 -1
- package/dist/preview.mjs +1 -1
- package/package.json +11 -10
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["IncomingMessage","Socket","ServerResponse","LogLevel","ConsoleLogger","InstallProvider","ReceiverMultipleAckError","ReceiverAuthenticityError"],"sources":["../src/errors.ts","../src/oauth-adapters.ts","../src/index.ts"],"sourcesContent":["// Error messages constants\nexport const ERROR_MESSAGES = {\n // VercelReceiver errors\n SIGNING_SECRET_REQUIRED:\n \"SLACK_SIGNING_SECRET is required for VercelReceiver\",\n APP_NOT_INITIALIZED: \"App not initialized\",\n OAUTH_NOT_CONFIGURED:\n \"OAuth is not configured. Provide clientId, clientSecret, and stateSecret to enable OAuth.\",\n REQUEST_TIMEOUT: \"Request timeout\",\n EVENT_NOT_ACKNOWLEDGED: \"Event not acknowledged within timeout period\",\n\n // Header validation errors\n MISSING_REQUIRED_HEADER: (header: string) =>\n `Missing required header: ${header}`,\n\n // Generic fallback errors\n REQUEST_VERIFICATION_FAILED: \"Request verification failed\",\n INTERNAL_SERVER_ERROR: \"Internal server error\",\n INTERNAL_SERVER_ERROR_HANDLER: \"Internal Server Error\",\n ACKNOWLEDGMENT_ERROR: \"Error in acknowledgment handler\",\n CREATE_HANDLER_ERROR: \"Error in createHandler:\",\n\n // Error type names\n TYPES: {\n VERCEL_RECEIVER_ERROR: \"VercelReceiverError\",\n SIGNATURE_VERIFICATION_ERROR: \"SignatureVerificationError\",\n REQUEST_PARSING_ERROR: \"RequestParsingError\",\n UNEXPECTED_ERROR: \"UnexpectedError\",\n HANDLER_ERROR: \"HandlerError\",\n },\n} as const;\n\nexport class VercelReceiverError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number = 500,\n ) {\n super(message);\n this.name = ERROR_MESSAGES.TYPES.VERCEL_RECEIVER_ERROR;\n }\n}\n\nexport class RequestParsingError extends VercelReceiverError {\n constructor(message: string = \"Failed to parse request\") {\n super(message, 400);\n this.name = ERROR_MESSAGES.TYPES.REQUEST_PARSING_ERROR;\n }\n}\n\n/**\n * Determines the appropriate HTTP status code for a given error.\n * @param error The error to get status code for\n * @returns HTTP status code\n */\nexport function getStatusCode(error: unknown): number {\n if (error instanceof VercelReceiverError) {\n return error.statusCode;\n }\n\n // External error types from @slack/bolt\n if (error && typeof error === \"object\") {\n const errorName =\n error.constructor?.name || (error as { name?: string }).name;\n switch (errorName) {\n case \"ReceiverAuthenticityError\":\n return 401;\n case \"ReceiverMultipleAckError\":\n return 500;\n case \"RequestParsingError\":\n return 400;\n case \"SignatureVerificationError\":\n return 400;\n default:\n return 500;\n }\n }\n\n return 500;\n}\n\n/**\n * Gets the error message for response.\n * @param error The error to get message for\n * @returns Error message string\n */\nexport function getErrorMessage(error: unknown): string {\n if (error && typeof error === \"object\" && \"message\" in error) {\n return String(error.message);\n }\n return ERROR_MESSAGES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * Gets the error type for response.\n * @param error The error to get type for\n * @returns Error type string\n */\nexport function getErrorType(error: unknown): string {\n if (error && typeof error === \"object\") {\n const ctorName = (error as { constructor?: { name?: string } }).constructor\n ?.name;\n const nameProp = (error as { name?: string }).name;\n const errorName =\n ctorName ?? nameProp ?? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n // Use \"UnexpectedError\" for generic Error instances, otherwise use the actual name\n return errorName === \"Error\"\n ? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR\n : errorName;\n }\n return ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n}\n","/**\n * Minimal Web <-> Node HTTP adapters for @slack/oauth InstallProvider.\n *\n * These do NOT implement the full IncomingMessage/ServerResponse contract.\n * Only the methods actually called by InstallProvider are intercepted.\n * Do not reuse for other Node libraries without verifying which methods\n * they call.\n *\n * Targets @slack/oauth\\@3.0.5 InstallProvider internals.\n * Do not upgrade without running the integration tests.\n *\n * Bolt 5 consumers also have @slack/oauth\\@4 in their tree (Bolt's own copy).\n * That is fine: Bolt only reads `receiver.installer.authorize` as a plain\n * function, and the Installation/InstallationStore types are structurally\n * identical across 3.x and 4.x. The 3.0.5 pin is deliberate until Bolt 4\n * support is dropped, so Bolt 4 consumers keep a single copy.\n */\n\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nexport type ResponseCapture = ServerResponse & { toResponse(): Response };\n\n/**\n * Wraps a Web API Request as a minimal Node.js IncomingMessage\n * so it can be passed to @slack/oauth's InstallProvider methods.\n */\nexport function toIncomingMessage(req: Request): IncomingMessage {\n const url = new URL(req.url);\n // Dummy socket — satisfies the IncomingMessage constructor but is never connected.\n const msg = new IncomingMessage(new Socket());\n msg.url = url.pathname + url.search;\n msg.method = req.method;\n for (const [key, value] of req.headers.entries()) {\n msg.headers[key.toLowerCase()] = value;\n }\n\n if (req.body) {\n req\n .arrayBuffer()\n .then((buf) => {\n msg.push(Buffer.from(buf));\n msg.push(null);\n })\n .catch(() => msg.destroy());\n } else {\n msg.push(null);\n }\n\n return msg;\n}\n\n/**\n * Creates a fake ServerResponse that captures setHeader/writeHead/end calls\n * and converts them into a Web API Response.\n *\n * InstallProvider uses res.setHeader() for Location, Set-Cookie, Content-Type\n * and res.getHeader() to read back Set-Cookie before appending.\n */\nexport function createResponseCapture(): ResponseCapture {\n let statusCode = 200;\n const capturedHeaders: Record<string, string | string[]> = {};\n const chunks: Buffer[] = [];\n\n // Dummy socket/message pair — never connected, just satisfies the constructor.\n const res = new ServerResponse(new IncomingMessage(new Socket()));\n\n const originalSetHeader = res.setHeader.bind(res);\n res.setHeader = (\n name: string,\n value: string | number | readonly string[],\n ) => {\n const key = name.toLowerCase();\n if (Array.isArray(value)) {\n capturedHeaders[key] = [...value];\n } else {\n capturedHeaders[key] = String(value);\n }\n return originalSetHeader(name, value);\n };\n\n const originalGetHeader = res.getHeader.bind(res);\n res.getHeader = (name: string): string | number | string[] | undefined => {\n const val = capturedHeaders[name.toLowerCase()];\n if (val !== undefined) return val;\n return originalGetHeader(name);\n };\n\n const originalWriteHead = res.writeHead.bind(res);\n // writeHead has four overloads: (code), (code, message), (code, headers),\n // and (code, message, headers). We sniff for the first non-array object arg\n // to find the headers object in all cases.\n // biome-ignore lint/suspicious/noExplicitAny: writeHead has many overloads\n res.writeHead = (code: number, ...args: any[]) => {\n statusCode = code;\n const headersArg = args.find(\n (a) => a !== undefined && typeof a === \"object\" && !Array.isArray(a),\n ) as Record<string, string | string[]> | undefined;\n if (headersArg) {\n for (const [key, value] of Object.entries(headersArg)) {\n const lower = key.toLowerCase();\n capturedHeaders[lower] = value;\n }\n }\n return originalWriteHead(code, ...args);\n };\n\n const originalEnd = res.end.bind(res);\n // biome-ignore lint/suspicious/noExplicitAny: end has many overloads\n res.end = (chunk?: any, ...args: any[]) => {\n if (chunk !== undefined && chunk !== null) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return originalEnd(chunk, ...args);\n };\n\n (res as ResponseCapture).toResponse = () => {\n const body = chunks.length > 0 ? Buffer.concat(chunks).toString() : null;\n const webHeaders = new Headers();\n for (const [key, value] of Object.entries(capturedHeaders)) {\n if (Array.isArray(value)) {\n for (const v of value) webHeaders.append(key, v);\n } else {\n webHeaders.set(key, value);\n }\n }\n return new Response(body, { status: statusCode, headers: webHeaders });\n };\n\n return res as ResponseCapture;\n}\n","import {\n type AckFn,\n type App,\n type HTTPReceiverOptions,\n type Receiver,\n ReceiverAuthenticityError,\n type ReceiverEvent,\n ReceiverMultipleAckError,\n type StringIndexed,\n verifySlackRequest,\n} from \"@slack/bolt\";\nimport { ConsoleLogger, type Logger, LogLevel } from \"@slack/logger\";\nimport {\n type CallbackOptions,\n type InstallPathOptions,\n InstallProvider,\n type InstallProviderOptions,\n type InstallURLOptions,\n type StateStore,\n} from \"@slack/oauth\";\nimport { waitUntil } from \"@vercel/functions\";\nimport {\n ERROR_MESSAGES,\n getErrorMessage,\n getErrorType,\n getStatusCode,\n RequestParsingError,\n VercelReceiverError,\n} from \"./errors\";\nimport { createResponseCapture, toIncomingMessage } from \"./oauth-adapters\";\n\n// Types\n/**\n * A function to handle the request from the Slack app.\n * @param req - The request from the Slack app.\n * @returns A response object.\n */\nexport type VercelHandler = (req: Request) => Promise<Response>;\n\n/**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing, or undefined to continue.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: This hook is NOT called for `url_verification` challenge requests, which are\n * handled automatically before `beforeProcess` is invoked.\n *\n * @param req - A new Request with the raw body (the original request body was consumed during parsing)\n * @param body - The parsed request body\n * @returns A Response to short-circuit processing, or undefined to continue to Bolt\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver({\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * beforeProcess: async (req, body) => {\n * // Forward certain workspaces to a different service\n * if (body.team_id === 'T_ENTERPRISE') {\n * return fetch('https://enterprise-handler.example.com/slack', {\n * method: 'POST',\n * body: await req.text(),\n * headers: req.headers,\n * });\n * }\n * // Return undefined to continue normal Bolt processing\n * },\n * });\n * ```\n */\nexport type BeforeProcessFn = (\n req: Request,\n body: StringIndexed,\n) => Promise<Response | undefined> | Response | undefined;\n\n/**\n * A function that resolves scopes dynamically based on the request.\n * Useful for requesting different scopes based on team or user context.\n * @param req - The original request\n * @returns The scopes to request\n */\nexport type ScopesResolver = (req: Request) => Promise<string[]> | string[];\n\n/**\n * Configuration options for the VercelReceiver.\n * @property signingSecret - The signing secret for the Slack app.\n * @property signatureVerification - If true, verifies the Slack request signature.\n * @property logger - The logger to use for the VercelReceiver.\n * @property logLevel - The log level to use for the VercelReceiver.\n * @property customPropertiesExtractor - A function to extract custom properties from the request.\n */\n/**\n * Options for customizing the OAuth installer behavior.\n * Mirrors the relevant subset of HTTPReceiverInstallerOptions,\n * excluding path-related options (serverless uses file-based routing).\n */\nexport interface VercelInstallerOptions {\n directInstall?: boolean;\n renderHtmlForInstallPath?: (url: string) => string;\n stateStore?: StateStore;\n stateVerification?: boolean;\n legacyStateVerification?: boolean;\n stateCookieName?: string;\n stateCookieExpirationSeconds?: number;\n authVersion?: \"v1\" | \"v2\";\n clientOptions?: InstallProviderOptions[\"clientOptions\"];\n authorizationUrl?: string;\n metadata?: string;\n userScopes?: string[];\n installPathOptions?: InstallPathOptions;\n callbackOptions?: CallbackOptions;\n}\n\n/**\n * Configuration options for the VercelReceiver.\n */\nexport interface VercelReceiverOptions {\n /**\n * The signing secret for the Slack app.\n * @default process.env.SLACK_SIGNING_SECRET\n */\n signingSecret?: string;\n /**\n * If true, verifies the Slack request signature.\n * @default true\n */\n signatureVerification?: boolean;\n /**\n * The logger to use for the VercelReceiver.\n * @default new ConsoleLogger()\n */\n logger?: Logger;\n /**\n * The log level to use for the VercelReceiver.\n * @default LogLevel.INFO\n */\n logLevel?: LogLevel;\n /**\n * A function to extract custom properties from incoming events.\n * Called after body parsing, so the parsed body is available.\n * @default undefined\n * @returns An object with custom properties.\n */\n customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n /**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing (e.g., to forward to an external service),\n * or undefined to continue normal Bolt processing.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: Not called for `url_verification` challenge requests.\n * @default undefined\n */\n beforeProcess?: BeforeProcessFn;\n /**\n * The timeout in milliseconds for event acknowledgment.\n * @default 3001\n */\n ackTimeoutMs?: number;\n /**\n * Your app's client ID, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_ID\n */\n clientId?: string;\n /**\n * Your app's client secret, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_SECRET\n */\n clientSecret?: string;\n /**\n * Secret used to generate and verify the state parameter for OAuth CSRF protection.\n * Required unless a custom stateStore or stateVerification: false is provided.\n * @default process.env.SLACK_STATE_SECRET\n */\n stateSecret?: string;\n /**\n * The bot scopes to request during the OAuth flow.\n * Can be a static array or a function that resolves scopes dynamically\n * based on the request (e.g., to request different scopes for different teams).\n */\n scopes?: string[] | ScopesResolver;\n /**\n * The redirect URI registered with your Slack app for OAuth callbacks.\n */\n redirectUri?: string;\n /**\n * Storage backend for OAuth installations (tokens, team info, etc.).\n * Required for OAuth in serverless -- the default in-memory store does not persist.\n */\n installationStore?: InstallProviderOptions[\"installationStore\"];\n /**\n * Advanced options for the OAuth installer.\n */\n installerOptions?: VercelInstallerOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Compile-time shape assertions\n// Verify our types match Bolt's underlying shapes without coupling optionality.\n// If Bolt changes a type upstream, tsc breaks here -- not in user-land at runtime.\n// ---------------------------------------------------------------------------\ntype AssertShape<Source, Target> =\n NonNullable<Source> extends NonNullable<Target> ? true : never;\n\ntype _S1 = AssertShape<\n VercelReceiverOptions[\"clientId\"],\n HTTPReceiverOptions[\"clientId\"]\n>;\ntype _S2 = AssertShape<\n VercelReceiverOptions[\"clientSecret\"],\n HTTPReceiverOptions[\"clientSecret\"]\n>;\ntype _S3 = AssertShape<\n VercelReceiverOptions[\"stateSecret\"],\n HTTPReceiverOptions[\"stateSecret\"]\n>;\ntype _S4 = AssertShape<\n VercelReceiverOptions[\"scopes\"],\n HTTPReceiverOptions[\"scopes\"]\n>;\ntype _S5 = AssertShape<\n VercelReceiverOptions[\"redirectUri\"],\n HTTPReceiverOptions[\"redirectUri\"]\n>;\ntype _S6 = AssertShape<\n VercelReceiverOptions[\"installationStore\"],\n HTTPReceiverOptions[\"installationStore\"]\n>;\ntype _S7 = AssertShape<\n VercelInstallerOptions[\"stateVerification\"],\n InstallProviderOptions[\"stateVerification\"]\n>;\ntype _S8 = AssertShape<\n VercelInstallerOptions[\"callbackOptions\"],\n CallbackOptions\n>;\ntype _S9 = AssertShape<\n VercelInstallerOptions[\"stateStore\"],\n InstallProviderOptions[\"stateStore\"]\n>;\ntype _S10 = AssertShape<\n VercelInstallerOptions[\"authVersion\"],\n InstallProviderOptions[\"authVersion\"]\n>;\ntype _S11 = AssertShape<\n VercelInstallerOptions[\"userScopes\"],\n InstallURLOptions[\"userScopes\"]\n>;\ntype _S12 = AssertShape<\n VercelInstallerOptions[\"metadata\"],\n InstallURLOptions[\"metadata\"]\n>;\n\nconst LOG_PREFIX = \"[@vercel/slack-bolt]\";\nconst ACK_TIMEOUT_MS = 3001;\nconst SLACK_RETRY_NUM_HEADER = \"x-slack-retry-num\";\nconst SLACK_RETRY_REASON_HEADER = \"x-slack-retry-reason\";\nconst SLACK_TIMESTAMP_HEADER = \"x-slack-request-timestamp\";\nconst SLACK_SIGNATURE_HEADER = \"x-slack-signature\";\n\n/**\n * A Slack Bolt receiver implementation designed for Vercel's serverless environment.\n * Handles Slack events, interactions, and slash commands with automatic request verification,\n * background processing, and timeout management.\n *\n * @example\n * ```typescript\n * import { App } from '@slack/bolt';\n * import { VercelReceiver, createHandler } from '@vercel/slack-bolt';\n *\n * const receiver = new VercelReceiver();\n *\n * const app = new App({\n * receiver,\n * token: process.env.SLACK_BOT_TOKEN,\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * });\n * ```\n *\n */\nexport class VercelReceiver implements Receiver {\n private readonly signingSecret: string;\n private readonly signatureVerification: boolean;\n private readonly logger: Logger;\n private readonly customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n private readonly beforeProcess?: BeforeProcessFn;\n private readonly ackTimeoutMs: number;\n private app?: App;\n\n public installer?: InstallProvider;\n private installUrlOptions?: InstallURLOptions;\n private scopesResolver?: ScopesResolver;\n private installCallbackOptions?: CallbackOptions;\n private installPathOptions?: InstallPathOptions;\n private stateVerification?: boolean;\n\n /**\n * Gets the logger instance used by this receiver.\n * @returns The logger instance\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Creates a new VercelReceiver instance.\n *\n * @param options - Configuration options for the receiver\n * @throws {VercelReceiverError} When signing secret is not provided\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver();\n * ```\n */\n public constructor({\n signingSecret = process.env.SLACK_SIGNING_SECRET,\n signatureVerification = true,\n logger,\n logLevel = LogLevel.INFO,\n customPropertiesExtractor,\n beforeProcess,\n ackTimeoutMs = ACK_TIMEOUT_MS,\n clientId = process.env.SLACK_CLIENT_ID,\n clientSecret = process.env.SLACK_CLIENT_SECRET,\n stateSecret = process.env.SLACK_STATE_SECRET,\n scopes,\n redirectUri,\n installationStore,\n installerOptions = {},\n }: VercelReceiverOptions = {}) {\n if (!signingSecret) {\n throw new VercelReceiverError(ERROR_MESSAGES.SIGNING_SECRET_REQUIRED);\n }\n\n this.signingSecret = signingSecret;\n this.signatureVerification = signatureVerification;\n this.logger = this.createScopedLogger(\n logger ?? new ConsoleLogger(),\n logLevel,\n );\n this.customPropertiesExtractor = customPropertiesExtractor;\n this.beforeProcess = beforeProcess;\n this.ackTimeoutMs = ackTimeoutMs;\n\n this.stateVerification = installerOptions.stateVerification;\n\n if (\n clientId !== undefined &&\n clientSecret !== undefined &&\n (installerOptions.stateVerification === false ||\n stateSecret !== undefined ||\n installerOptions.stateStore !== undefined)\n ) {\n this.installer = new InstallProvider({\n clientId,\n clientSecret,\n stateSecret,\n installationStore,\n logger,\n logLevel,\n directInstall: installerOptions.directInstall,\n stateStore: installerOptions.stateStore,\n stateVerification: installerOptions.stateVerification,\n legacyStateVerification: installerOptions.legacyStateVerification,\n stateCookieName: installerOptions.stateCookieName,\n stateCookieExpirationSeconds:\n installerOptions.stateCookieExpirationSeconds,\n renderHtmlForInstallPath: installerOptions.renderHtmlForInstallPath,\n authVersion: installerOptions.authVersion ?? \"v2\",\n clientOptions: installerOptions.clientOptions,\n authorizationUrl: installerOptions.authorizationUrl,\n });\n\n // If scopes is a function, store it separately for dynamic resolution\n if (typeof scopes === \"function\") {\n this.scopesResolver = scopes;\n this.installUrlOptions = {\n scopes: [], // Will be resolved dynamically in handleInstall\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n } else {\n this.installUrlOptions = {\n scopes: scopes ?? [],\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n }\n this.installCallbackOptions = installerOptions.callbackOptions ?? {};\n this.installPathOptions = installerOptions.installPathOptions ?? {};\n }\n\n this.logger.debug(\"VercelReceiver initialized\");\n }\n\n /**\n * Initializes the receiver with a Slack Bolt app instance.\n * This method is called automatically by the Bolt framework.\n *\n * @param app - The Slack Bolt app instance\n */\n public init(app: App): void {\n this.app = app;\n this.logger.debug(\"App initialized in VercelReceiver\");\n }\n\n /**\n * Starts the receiver and returns a handler function for processing requests.\n * This method is called automatically by the Bolt framework.\n *\n * @returns A handler function that processes incoming Slack requests\n */\n public async start(): Promise<VercelHandler> {\n this.logger.debug(\"VercelReceiver started\");\n return this.toHandler();\n }\n\n /**\n * Stops the receiver. This method is called automatically by the Bolt framework.\n */\n public async stop(): Promise<void> {\n this.logger.debug(\"VercelReceiver stopped\");\n }\n\n /**\n * Handles requests to the OAuth install path.\n * Renders an \"Add to Slack\" page or redirects directly to Slack's authorize URL.\n */\n public handleInstall = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n // Resolve scopes dynamically if a resolver function was provided\n let installUrlOptions = this.installUrlOptions;\n if (this.scopesResolver && installUrlOptions) {\n const resolvedScopes = await this.scopesResolver(req);\n installUrlOptions = {\n ...installUrlOptions,\n scopes: resolvedScopes,\n };\n }\n\n await this.installer.handleInstallPath(\n nodeReq,\n capture,\n this.installPathOptions,\n installUrlOptions,\n );\n\n return capture.toResponse();\n };\n\n /**\n * Handles the OAuth redirect callback from Slack.\n * Exchanges the authorization code for tokens and stores the installation.\n */\n public handleCallback = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n if (this.stateVerification === false) {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n this.installUrlOptions,\n );\n } else {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n );\n }\n\n return capture.toResponse();\n };\n\n /**\n * Creates a handler function that processes incoming Slack requests.\n * This is the main entry point for handling Slack events in Vercel.\n * It is called automatically by the Bolt framework in the start() method.\n *\n * @returns A handler function compatible with Vercel's function signature\n */\n public toHandler(): VercelHandler {\n return async (req: Request): Promise<Response> => {\n try {\n const rawBody = await req.text();\n\n if (this.signatureVerification) {\n this.verifyRequest(req, rawBody);\n }\n\n const body = await this.parseRequestBody(req, rawBody);\n\n if (body.type === \"url_verification\") {\n this.logger.debug(\"Handling URL verification challenge\");\n return Response.json({ challenge: body.challenge });\n }\n\n // Allow beforeProcess to intercept and short-circuit processing.\n // We pass a new Request with the raw body since req.text() was already consumed.\n if (this.beforeProcess) {\n const reqWithBody = new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: rawBody,\n });\n const interceptResponse = await this.beforeProcess(reqWithBody, body);\n if (interceptResponse) {\n this.logger.debug(\"Request intercepted by beforeProcess\");\n return interceptResponse;\n }\n }\n\n return await this.handleSlackEvent(req, body);\n } catch (error) {\n return this.handleError(error);\n }\n };\n }\n\n private async parseRequestBody(\n req: Request,\n rawBody: string,\n ): Promise<StringIndexed> {\n const contentType = req.headers.get(\"content-type\");\n\n try {\n if (contentType === \"application/x-www-form-urlencoded\") {\n const parsedBody: StringIndexed = {};\n const params = new URLSearchParams(rawBody);\n\n for (const [key, value] of params.entries()) {\n parsedBody[key] = value;\n }\n\n if (typeof parsedBody.payload === \"string\") {\n return JSON.parse(parsedBody.payload);\n }\n return parsedBody;\n }\n if (contentType === \"application/json\") {\n return JSON.parse(rawBody);\n }\n\n this.logger.warn(`Unexpected content-type detected: ${contentType}`);\n\n return JSON.parse(rawBody);\n } catch (e) {\n throw new RequestParsingError(\n `Failed to parse body as JSON data for content-type: ${contentType}. Error: ${\n e instanceof Error ? e.message : String(e)\n }`,\n );\n }\n }\n\n private async handleSlackEvent(\n req: Request,\n body: StringIndexed,\n ): Promise<Response> {\n if (!this.app) {\n throw new VercelReceiverError(ERROR_MESSAGES.APP_NOT_INITIALIZED, 500);\n }\n\n let isAcknowledged = false;\n let responseResolver: (value: Response) => void;\n let responseRejecter: (error: Error) => void;\n\n const responsePromise = new Promise<Response>((resolve, reject) => {\n responseResolver = resolve;\n responseRejecter = reject;\n });\n\n // Slack requires an acknowledgment from your app within 3 seconds\n const timeoutId = setTimeout(() => {\n if (!isAcknowledged) {\n isAcknowledged = true;\n this.logger.error(ERROR_MESSAGES.EVENT_NOT_ACKNOWLEDGED);\n const error = new VercelReceiverError(\n ERROR_MESSAGES.REQUEST_TIMEOUT,\n 408,\n );\n responseRejecter(error);\n }\n }, this.ackTimeoutMs);\n\n // Create acknowledgment function\n const ackFn: AckFn<StringIndexed> = async (responseBody) => {\n this.logger.debug(`ack() call begins (body: ${responseBody})`);\n if (isAcknowledged) {\n throw new ReceiverMultipleAckError();\n }\n\n isAcknowledged = true;\n clearTimeout(timeoutId);\n\n try {\n let body: string | undefined;\n if (typeof responseBody === \"undefined\") {\n body = undefined;\n } else if (typeof responseBody === \"string\") {\n body = responseBody;\n } else {\n body = JSON.stringify(responseBody);\n }\n const response = new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n responseResolver(response);\n } catch (error) {\n this.logger.error(ERROR_MESSAGES.ACKNOWLEDGMENT_ERROR, error);\n responseRejecter(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n };\n\n const event = this.createSlackReceiverEvent({\n body,\n headers: req.headers,\n ack: ackFn,\n request: req,\n });\n\n // Process event in background using waitUntil from Vercel Functions\n // https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil\n waitUntil(\n this.app.processEvent(event).catch((error) => {\n return this.handleError(error);\n }),\n );\n\n try {\n return await responsePromise;\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n private verifyRequest(req: Request, body: string): void {\n const timestamp = req.headers.get(SLACK_TIMESTAMP_HEADER);\n const signature = req.headers.get(SLACK_SIGNATURE_HEADER);\n\n if (!signature) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_SIGNATURE_HEADER),\n );\n }\n\n if (!timestamp) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_TIMESTAMP_HEADER),\n );\n }\n\n try {\n verifySlackRequest({\n signingSecret: this.signingSecret,\n body,\n headers: {\n \"x-slack-signature\": signature,\n \"x-slack-request-timestamp\": Number.parseInt(timestamp, 10),\n },\n logger: this.logger,\n });\n } catch (error) {\n throw new ReceiverAuthenticityError(\n error instanceof Error\n ? error.message\n : \"Failed to verify request signature\",\n );\n }\n }\n\n private createSlackReceiverEvent({\n body,\n headers,\n ack,\n request,\n }: {\n body: StringIndexed;\n headers: Headers;\n ack: AckFn<StringIndexed>;\n request: Request;\n }): ReceiverEvent {\n const customProperties = this.customPropertiesExtractor\n ? this.customPropertiesExtractor(request, body)\n : {};\n\n const retryNum = headers.get(SLACK_RETRY_NUM_HEADER) || \"0\";\n\n const retryReason = headers.get(SLACK_RETRY_REASON_HEADER) || \"\";\n\n return {\n body,\n ack,\n retryNum: Number(retryNum),\n retryReason,\n customProperties,\n };\n }\n\n public handleError(error: unknown): Response {\n const errorMessage = getErrorMessage(error);\n const errorType = getErrorType(error);\n const errorStatusCode = getStatusCode(error);\n\n this.logger.error(error);\n return new Response(\n JSON.stringify({\n error: errorMessage,\n type: errorType,\n }),\n {\n status: errorStatusCode,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n }\n\n private createScopedLogger(logger: Logger, logLevel: LogLevel): Logger {\n logger.setLevel(logLevel);\n\n return {\n ...logger,\n error: (...args) => logger.error?.(LOG_PREFIX, ...args),\n warn: (...args) => logger.warn?.(LOG_PREFIX, ...args),\n info: (...args) => logger.info?.(LOG_PREFIX, ...args),\n debug: (...args) => logger.debug?.(LOG_PREFIX, ...args),\n setLevel: logger.setLevel,\n getLevel: logger.getLevel,\n };\n }\n}\n\n/**\n * Creates a Vercel-compatible handler function for a Slack Bolt app.\n * This is the recommended way to create handlers for deployment on Vercel.\n *\n * @param {App} app - The initialized Slack Bolt app instance.\n * @param {VercelReceiver} receiver - The VercelReceiver instance.\n * @returns {VercelHandler} A handler function compatible with Vercel's function signature.\n *\n * @example\n * ```typescript\n * // api/events.ts\n * import { createHandler } from '@vercel/slack-bolt';\n * import { app, receiver } from '../app';\n *\n * const handler = createHandler(app, receiver);\n *\n * export const POST = async (req: Request) => {\n * return handler(req);\n * };\n * ```\n *\n * @throws {Error} If app initialization fails.\n * @throws {VercelReceiverError} If request processing fails.\n */\nexport function createHandler(\n app: App,\n receiver: VercelReceiver,\n): VercelHandler {\n let initPromise: Promise<void> | null = null;\n\n return async (req: Request) => {\n try {\n if (!initPromise) {\n initPromise = app.init().catch((error) => {\n // Reset initPromise so subsequent requests can retry initialization\n initPromise = null;\n throw error;\n });\n }\n await initPromise;\n\n receiver.init(app);\n const handler = await receiver.start();\n return handler(req);\n } catch (error) {\n // if app.init fails, we use console.error instead of logger.error because the logger is not available\n console.error(ERROR_MESSAGES.CREATE_HANDLER_ERROR, error);\n return new Response(\n JSON.stringify({\n error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR_HANDLER,\n type: ERROR_MESSAGES.TYPES.HANDLER_ERROR,\n }),\n { status: 500, headers: { \"content-type\": \"application/json\" } },\n );\n }\n };\n}\n"],"mappings":";;;;;;;;AACA,MAAa,iBAAiB;CAE5B,yBACE;CACF,qBAAqB;CACrB,sBACE;CACF,iBAAiB;CACjB,wBAAwB;CAGxB,0BAA0B,WACxB,4BAA4B;CAG9B,6BAA6B;CAC7B,uBAAuB;CACvB,+BAA+B;CAC/B,sBAAsB;CACtB,sBAAsB;CAGtB,OAAO;EACL,uBAAuB;EACvB,8BAA8B;EAC9B,uBAAuB;EACvB,kBAAkB;EAClB,eAAe;CACjB;AACF;AAEA,IAAa,sBAAb,cAAyC,MAAM;CAG3B;CAFlB,YACE,SACA,aAAqC,KACrC;EACA,MAAM,OAAO;EAFG,KAAA,aAAA;EAGhB,KAAK,OAAO,eAAe,MAAM;CACnC;AACF;AAEA,IAAa,sBAAb,cAAyC,oBAAoB;CAC3D,YAAY,UAAkB,2BAA2B;EACvD,MAAM,SAAS,GAAG;EAClB,KAAK,OAAO,eAAe,MAAM;CACnC;AACF;;;;;;AAOA,SAAgB,cAAc,OAAwB;CACpD,IAAI,iBAAiB,qBACnB,OAAO,MAAM;CAIf,IAAI,SAAS,OAAO,UAAU,UAG5B,QADE,MAAM,aAAa,QAAS,MAA4B,MAC1D;EACE,KAAK,6BACH,OAAO;EACT,KAAK,4BACH,OAAO;EACT,KAAK,uBACH,OAAO;EACT,KAAK,8BACH,OAAO;EACT,SACE,OAAO;CACX;CAGF,OAAO;AACT;;;;;;AAOA,SAAgB,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AAO,MAAM,KAAK;EACvB,OAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,MAAM;EACR,CAAC,GACD;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;EAChD,CACF;CACF;CAEA,mBAA2B,QAAgB,UAA4B;EACrE,OAAO,SAAS,QAAQ;EAExB,OAAO;GACL,GAAG;GACH,QAAQ,GAAG,SAAS,OAAO,QAAQ,YAAY,GAAG,IAAI;GACtD,OAAO,GAAG,SAAS,OAAO,OAAO,YAAY,GAAG,IAAI;GACpD,OAAO,GAAG,SAAS,OAAO,OAAO,YAAY,GAAG,IAAI;GACpD,QAAQ,GAAG,SAAS,OAAO,QAAQ,YAAY,GAAG,IAAI;GACtD,UAAU,OAAO;GACjB,UAAU,OAAO;EACnB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,cACd,KACA,UACe;CACf,IAAI,cAAoC;CAExC,OAAO,OAAO,QAAiB;EAC7B,IAAI;GACF,IAAI,CAAC,aACH,cAAc,IAAI,KAAK,CAAC,CAAC,OAAO,UAAU;IAExC,cAAc;IACd,MAAM;GACR,CAAC;GAEH,MAAM;GAEN,SAAS,KAAK,GAAG;GAEjB,QAAO,MADe,SAAS,MAAM,EAAA,CACtB,GAAG;EACpB,SAAS,OAAO;GAEd,QAAQ,MAAM,eAAe,sBAAsB,KAAK;GACxD,OAAO,IAAI,SACT,KAAK,UAAU;IACb,OAAO,eAAe;IACtB,MAAM,eAAe,MAAM;GAC7B,CAAC,GACD;IAAE,QAAQ;IAAK,SAAS,EAAE,gBAAgB,mBAAmB;GAAE,CACjE;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["IncomingMessage","Socket","ServerResponse","LogLevel","ConsoleLogger","InstallProvider","ReceiverMultipleAckError","waitUntil","ReceiverAuthenticityError","verifySlackRequest"],"sources":["../src/errors.ts","../src/oauth-adapters.ts","../src/index.ts"],"sourcesContent":["// Error messages constants\nexport const ERROR_MESSAGES = {\n // VercelReceiver errors\n SIGNING_SECRET_REQUIRED:\n \"SLACK_SIGNING_SECRET is required for VercelReceiver\",\n APP_NOT_INITIALIZED: \"App not initialized\",\n OAUTH_NOT_CONFIGURED:\n \"OAuth is not configured. Provide clientId, clientSecret, and stateSecret to enable OAuth.\",\n REQUEST_TIMEOUT: \"Request timeout\",\n EVENT_NOT_ACKNOWLEDGED: \"Event not acknowledged within timeout period\",\n\n // Header validation errors\n MISSING_REQUIRED_HEADER: (header: string) =>\n `Missing required header: ${header}`,\n\n // Generic fallback errors\n REQUEST_VERIFICATION_FAILED: \"Request verification failed\",\n INTERNAL_SERVER_ERROR: \"Internal server error\",\n INTERNAL_SERVER_ERROR_HANDLER: \"Internal Server Error\",\n ACKNOWLEDGMENT_ERROR: \"Error in acknowledgment handler\",\n CREATE_HANDLER_ERROR: \"Error in createHandler:\",\n\n // Error type names\n TYPES: {\n VERCEL_RECEIVER_ERROR: \"VercelReceiverError\",\n SIGNATURE_VERIFICATION_ERROR: \"SignatureVerificationError\",\n REQUEST_PARSING_ERROR: \"RequestParsingError\",\n UNEXPECTED_ERROR: \"UnexpectedError\",\n HANDLER_ERROR: \"HandlerError\",\n },\n} as const;\n\nexport class VercelReceiverError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number = 500,\n ) {\n super(message);\n this.name = ERROR_MESSAGES.TYPES.VERCEL_RECEIVER_ERROR;\n }\n}\n\nexport class RequestParsingError extends VercelReceiverError {\n constructor(message: string = \"Failed to parse request\") {\n super(message, 400);\n this.name = ERROR_MESSAGES.TYPES.REQUEST_PARSING_ERROR;\n }\n}\n\n/**\n * Determines the appropriate HTTP status code for a given error.\n * @param error The error to get status code for\n * @returns HTTP status code\n */\nexport function getStatusCode(error: unknown): number {\n if (error instanceof VercelReceiverError) {\n return error.statusCode;\n }\n\n // External error types from @slack/bolt\n if (error && typeof error === \"object\") {\n const errorName =\n error.constructor?.name || (error as { name?: string }).name;\n switch (errorName) {\n case \"ReceiverAuthenticityError\":\n return 401;\n case \"ReceiverMultipleAckError\":\n return 500;\n case \"RequestParsingError\":\n return 400;\n case \"SignatureVerificationError\":\n return 400;\n default:\n return 500;\n }\n }\n\n return 500;\n}\n\n/**\n * Gets the error message for response.\n * @param error The error to get message for\n * @returns Error message string\n */\nexport function getErrorMessage(error: unknown): string {\n if (error && typeof error === \"object\" && \"message\" in error) {\n return String(error.message);\n }\n return ERROR_MESSAGES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * Gets the error type for response.\n * @param error The error to get type for\n * @returns Error type string\n */\nexport function getErrorType(error: unknown): string {\n if (error && typeof error === \"object\") {\n const ctorName = (error as { constructor?: { name?: string } }).constructor\n ?.name;\n const nameProp = (error as { name?: string }).name;\n const errorName =\n ctorName ?? nameProp ?? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n // Use \"UnexpectedError\" for generic Error instances, otherwise use the actual name\n return errorName === \"Error\"\n ? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR\n : errorName;\n }\n return ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n}\n","/**\n * Minimal Web <-> Node HTTP adapters for @slack/oauth InstallProvider.\n *\n * These do NOT implement the full IncomingMessage/ServerResponse contract.\n * Only the methods actually called by InstallProvider are intercepted.\n * Do not reuse for other Node libraries without verifying which methods\n * they call.\n *\n * Targets @slack/oauth\\@3.0.5 InstallProvider internals.\n * Do not upgrade without running the integration tests.\n *\n * Bolt 5 consumers also have @slack/oauth\\@4 in their tree (Bolt's own copy).\n * That is fine: Bolt only reads `receiver.installer.authorize` as a plain\n * function, and the Installation/InstallationStore types are structurally\n * identical across 3.x and 4.x. The 3.0.5 pin is deliberate until Bolt 4\n * support is dropped, so Bolt 4 consumers keep a single copy.\n */\n\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nexport type ResponseCapture = ServerResponse & { toResponse(): Response };\n\n/**\n * Wraps a Web API Request as a minimal Node.js IncomingMessage\n * so it can be passed to @slack/oauth's InstallProvider methods.\n */\nexport function toIncomingMessage(req: Request): IncomingMessage {\n const url = new URL(req.url);\n // Dummy socket — satisfies the IncomingMessage constructor but is never connected.\n const msg = new IncomingMessage(new Socket());\n msg.url = url.pathname + url.search;\n msg.method = req.method;\n for (const [key, value] of req.headers.entries()) {\n msg.headers[key.toLowerCase()] = value;\n }\n\n if (req.body) {\n req\n .arrayBuffer()\n .then((buf) => {\n msg.push(Buffer.from(buf));\n msg.push(null);\n })\n .catch(() => msg.destroy());\n } else {\n msg.push(null);\n }\n\n return msg;\n}\n\n/**\n * Creates a fake ServerResponse that captures setHeader/writeHead/end calls\n * and converts them into a Web API Response.\n *\n * InstallProvider uses res.setHeader() for Location, Set-Cookie, Content-Type\n * and res.getHeader() to read back Set-Cookie before appending.\n */\nexport function createResponseCapture(): ResponseCapture {\n let statusCode = 200;\n const capturedHeaders: Record<string, string | string[]> = {};\n const chunks: Buffer[] = [];\n\n // Dummy socket/message pair — never connected, just satisfies the constructor.\n const res = new ServerResponse(new IncomingMessage(new Socket()));\n\n const originalSetHeader = res.setHeader.bind(res);\n res.setHeader = (\n name: string,\n value: string | number | readonly string[],\n ) => {\n const key = name.toLowerCase();\n if (Array.isArray(value)) {\n capturedHeaders[key] = [...value];\n } else {\n capturedHeaders[key] = String(value);\n }\n return originalSetHeader(name, value);\n };\n\n const originalGetHeader = res.getHeader.bind(res);\n res.getHeader = (name: string): string | number | string[] | undefined => {\n const val = capturedHeaders[name.toLowerCase()];\n if (val !== undefined) return val;\n return originalGetHeader(name);\n };\n\n const originalWriteHead = res.writeHead.bind(res);\n // writeHead has four overloads: (code), (code, message), (code, headers),\n // and (code, message, headers). We sniff for the first non-array object arg\n // to find the headers object in all cases.\n // oxlint-disable-next-line typescript/no-explicit-any -- writeHead has many overloads\n res.writeHead = (code: number, ...args: any[]) => {\n statusCode = code;\n const headersArg = args.find(\n (a) => a !== undefined && typeof a === \"object\" && !Array.isArray(a),\n ) as Record<string, string | string[]> | undefined;\n if (headersArg) {\n for (const [key, value] of Object.entries(headersArg)) {\n const lower = key.toLowerCase();\n capturedHeaders[lower] = value;\n }\n }\n return originalWriteHead(code, ...args);\n };\n\n const originalEnd = res.end.bind(res);\n // oxlint-disable-next-line typescript/no-explicit-any -- end has many overloads\n res.end = (chunk?: any, ...args: any[]) => {\n if (chunk !== undefined && chunk !== null) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return originalEnd(chunk, ...args);\n };\n\n (res as ResponseCapture).toResponse = () => {\n const body = chunks.length > 0 ? Buffer.concat(chunks).toString() : null;\n const webHeaders = new Headers();\n for (const [key, value] of Object.entries(capturedHeaders)) {\n if (Array.isArray(value)) {\n for (const v of value) webHeaders.append(key, v);\n } else {\n webHeaders.set(key, value);\n }\n }\n return new Response(body, { status: statusCode, headers: webHeaders });\n };\n\n return res as ResponseCapture;\n}\n","import {\n type AckFn,\n type App,\n type HTTPReceiverOptions,\n type Receiver,\n ReceiverAuthenticityError,\n type ReceiverEvent,\n ReceiverMultipleAckError,\n type StringIndexed,\n verifySlackRequest,\n} from \"@slack/bolt\";\nimport { ConsoleLogger, type Logger, LogLevel } from \"@slack/logger\";\nimport {\n type CallbackOptions,\n type InstallPathOptions,\n InstallProvider,\n type InstallProviderOptions,\n type InstallURLOptions,\n type StateStore,\n} from \"@slack/oauth\";\nimport { waitUntil } from \"@vercel/functions\";\nimport {\n ERROR_MESSAGES,\n getErrorMessage,\n getErrorType,\n getStatusCode,\n RequestParsingError,\n VercelReceiverError,\n} from \"./errors\";\nimport { createResponseCapture, toIncomingMessage } from \"./oauth-adapters\";\n\n// Types\n/**\n * A function to handle the request from the Slack app.\n * @param req - The request from the Slack app.\n * @returns A response object.\n */\nexport type VercelHandler = (req: Request) => Promise<Response>;\n\n/**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing, or undefined to continue.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: This hook is NOT called for `url_verification` challenge requests, which are\n * handled automatically before `beforeProcess` is invoked.\n *\n * @param req - A new Request with the raw body (the original request body was consumed during parsing)\n * @param body - The parsed request body\n * @returns A Response to short-circuit processing, or undefined to continue to Bolt\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver({\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * beforeProcess: async (req, body) => {\n * // Forward certain workspaces to a different service\n * if (body.team_id === 'T_ENTERPRISE') {\n * return fetch('https://enterprise-handler.example.com/slack', {\n * method: 'POST',\n * body: await req.text(),\n * headers: req.headers,\n * });\n * }\n * // Return undefined to continue normal Bolt processing\n * },\n * });\n * ```\n */\nexport type BeforeProcessFn = (\n req: Request,\n body: StringIndexed,\n) => Promise<Response | undefined> | Response | undefined;\n\n/**\n * A function that resolves scopes dynamically based on the request.\n * Useful for requesting different scopes based on team or user context.\n * @param req - The original request\n * @returns The scopes to request\n */\nexport type ScopesResolver = (req: Request) => Promise<string[]> | string[];\n\n/**\n * Configuration options for the VercelReceiver.\n * @property signingSecret - The signing secret for the Slack app.\n * @property signatureVerification - If true, verifies the Slack request signature.\n * @property logger - The logger to use for the VercelReceiver.\n * @property logLevel - The log level to use for the VercelReceiver.\n * @property customPropertiesExtractor - A function to extract custom properties from the request.\n */\n/**\n * Options for customizing the OAuth installer behavior.\n * Mirrors the relevant subset of HTTPReceiverInstallerOptions,\n * excluding path-related options (serverless uses file-based routing).\n */\nexport interface VercelInstallerOptions {\n directInstall?: boolean;\n renderHtmlForInstallPath?: (url: string) => string;\n stateStore?: StateStore;\n stateVerification?: boolean;\n legacyStateVerification?: boolean;\n stateCookieName?: string;\n stateCookieExpirationSeconds?: number;\n authVersion?: \"v1\" | \"v2\";\n clientOptions?: InstallProviderOptions[\"clientOptions\"];\n authorizationUrl?: string;\n metadata?: string;\n userScopes?: string[];\n installPathOptions?: InstallPathOptions;\n callbackOptions?: CallbackOptions;\n}\n\n/**\n * Configuration options for the VercelReceiver.\n */\nexport interface VercelReceiverOptions {\n /**\n * The signing secret for the Slack app.\n * @default process.env.SLACK_SIGNING_SECRET\n */\n signingSecret?: string;\n /**\n * If true, verifies the Slack request signature.\n * @default true\n */\n signatureVerification?: boolean;\n /**\n * The logger to use for the VercelReceiver.\n * @default new ConsoleLogger()\n */\n logger?: Logger;\n /**\n * The log level to use for the VercelReceiver.\n * @default LogLevel.INFO\n */\n logLevel?: LogLevel;\n /**\n * A function to extract custom properties from incoming events.\n * Called after body parsing, so the parsed body is available.\n * @default undefined\n * @returns An object with custom properties.\n */\n customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n /**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing (e.g., to forward to an external service),\n * or undefined to continue normal Bolt processing.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: Not called for `url_verification` challenge requests.\n * @default undefined\n */\n beforeProcess?: BeforeProcessFn;\n /**\n * The timeout in milliseconds for event acknowledgment.\n * @default 3001\n */\n ackTimeoutMs?: number;\n /**\n * Your app's client ID, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_ID\n */\n clientId?: string;\n /**\n * Your app's client secret, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_SECRET\n */\n clientSecret?: string;\n /**\n * Secret used to generate and verify the state parameter for OAuth CSRF protection.\n * Required unless a custom stateStore or stateVerification: false is provided.\n * @default process.env.SLACK_STATE_SECRET\n */\n stateSecret?: string;\n /**\n * The bot scopes to request during the OAuth flow.\n * Can be a static array or a function that resolves scopes dynamically\n * based on the request (e.g., to request different scopes for different teams).\n */\n scopes?: string[] | ScopesResolver;\n /**\n * The redirect URI registered with your Slack app for OAuth callbacks.\n */\n redirectUri?: string;\n /**\n * Storage backend for OAuth installations (tokens, team info, etc.).\n * Required for OAuth in serverless -- the default in-memory store does not persist.\n */\n installationStore?: InstallProviderOptions[\"installationStore\"];\n /**\n * Advanced options for the OAuth installer.\n */\n installerOptions?: VercelInstallerOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Compile-time shape assertions\n// Verify our types match Bolt's underlying shapes without coupling optionality.\n// If Bolt changes a type upstream, tsc breaks here -- not in user-land at runtime.\n// ---------------------------------------------------------------------------\ntype AssertShape<Source, Target> =\n NonNullable<Source> extends NonNullable<Target> ? true : never;\n\ntype _S1 = AssertShape<\n VercelReceiverOptions[\"clientId\"],\n HTTPReceiverOptions[\"clientId\"]\n>;\ntype _S2 = AssertShape<\n VercelReceiverOptions[\"clientSecret\"],\n HTTPReceiverOptions[\"clientSecret\"]\n>;\ntype _S3 = AssertShape<\n VercelReceiverOptions[\"stateSecret\"],\n HTTPReceiverOptions[\"stateSecret\"]\n>;\ntype _S4 = AssertShape<\n VercelReceiverOptions[\"scopes\"],\n HTTPReceiverOptions[\"scopes\"]\n>;\ntype _S5 = AssertShape<\n VercelReceiverOptions[\"redirectUri\"],\n HTTPReceiverOptions[\"redirectUri\"]\n>;\ntype _S6 = AssertShape<\n VercelReceiverOptions[\"installationStore\"],\n HTTPReceiverOptions[\"installationStore\"]\n>;\ntype _S7 = AssertShape<\n VercelInstallerOptions[\"stateVerification\"],\n InstallProviderOptions[\"stateVerification\"]\n>;\ntype _S8 = AssertShape<\n VercelInstallerOptions[\"callbackOptions\"],\n CallbackOptions\n>;\ntype _S9 = AssertShape<\n VercelInstallerOptions[\"stateStore\"],\n InstallProviderOptions[\"stateStore\"]\n>;\ntype _S10 = AssertShape<\n VercelInstallerOptions[\"authVersion\"],\n InstallProviderOptions[\"authVersion\"]\n>;\ntype _S11 = AssertShape<\n VercelInstallerOptions[\"userScopes\"],\n InstallURLOptions[\"userScopes\"]\n>;\ntype _S12 = AssertShape<\n VercelInstallerOptions[\"metadata\"],\n InstallURLOptions[\"metadata\"]\n>;\n\nconst LOG_PREFIX = \"[@vercel/slack-bolt]\";\nconst ACK_TIMEOUT_MS = 3001;\nconst SLACK_RETRY_NUM_HEADER = \"x-slack-retry-num\";\nconst SLACK_RETRY_REASON_HEADER = \"x-slack-retry-reason\";\nconst SLACK_TIMESTAMP_HEADER = \"x-slack-request-timestamp\";\nconst SLACK_SIGNATURE_HEADER = \"x-slack-signature\";\n\n/**\n * A Slack Bolt receiver implementation designed for Vercel's serverless environment.\n * Handles Slack events, interactions, and slash commands with automatic request verification,\n * background processing, and timeout management.\n *\n * @example\n * ```typescript\n * import { App } from '@slack/bolt';\n * import { VercelReceiver, createHandler } from '@vercel/slack-bolt';\n *\n * const receiver = new VercelReceiver();\n *\n * const app = new App({\n * receiver,\n * token: process.env.SLACK_BOT_TOKEN,\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * });\n * ```\n *\n */\nexport class VercelReceiver implements Receiver {\n private readonly signingSecret: string;\n private readonly signatureVerification: boolean;\n private readonly logger: Logger;\n private readonly customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n private readonly beforeProcess?: BeforeProcessFn;\n private readonly ackTimeoutMs: number;\n private app?: App;\n\n public installer?: InstallProvider;\n private installUrlOptions?: InstallURLOptions;\n private scopesResolver?: ScopesResolver;\n private installCallbackOptions?: CallbackOptions;\n private installPathOptions?: InstallPathOptions;\n private stateVerification?: boolean;\n\n /**\n * Gets the logger instance used by this receiver.\n * @returns The logger instance\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Creates a new VercelReceiver instance.\n *\n * @param options - Configuration options for the receiver\n * @throws {VercelReceiverError} When signing secret is not provided\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver();\n * ```\n */\n public constructor({\n signingSecret = process.env.SLACK_SIGNING_SECRET,\n signatureVerification = true,\n logger,\n logLevel = LogLevel.INFO,\n customPropertiesExtractor,\n beforeProcess,\n ackTimeoutMs = ACK_TIMEOUT_MS,\n clientId = process.env.SLACK_CLIENT_ID,\n clientSecret = process.env.SLACK_CLIENT_SECRET,\n stateSecret = process.env.SLACK_STATE_SECRET,\n scopes,\n redirectUri,\n installationStore,\n installerOptions = {},\n }: VercelReceiverOptions = {}) {\n if (!signingSecret) {\n throw new VercelReceiverError(ERROR_MESSAGES.SIGNING_SECRET_REQUIRED);\n }\n\n this.signingSecret = signingSecret;\n this.signatureVerification = signatureVerification;\n this.logger = this.createScopedLogger(\n logger ?? new ConsoleLogger(),\n logLevel,\n );\n this.customPropertiesExtractor = customPropertiesExtractor;\n this.beforeProcess = beforeProcess;\n this.ackTimeoutMs = ackTimeoutMs;\n\n this.stateVerification = installerOptions.stateVerification;\n\n if (\n clientId !== undefined &&\n clientSecret !== undefined &&\n (installerOptions.stateVerification === false ||\n stateSecret !== undefined ||\n installerOptions.stateStore !== undefined)\n ) {\n this.installer = new InstallProvider({\n clientId,\n clientSecret,\n stateSecret,\n installationStore,\n logger,\n logLevel,\n directInstall: installerOptions.directInstall,\n stateStore: installerOptions.stateStore,\n stateVerification: installerOptions.stateVerification,\n legacyStateVerification: installerOptions.legacyStateVerification,\n stateCookieName: installerOptions.stateCookieName,\n stateCookieExpirationSeconds:\n installerOptions.stateCookieExpirationSeconds,\n renderHtmlForInstallPath: installerOptions.renderHtmlForInstallPath,\n authVersion: installerOptions.authVersion ?? \"v2\",\n clientOptions: installerOptions.clientOptions,\n authorizationUrl: installerOptions.authorizationUrl,\n });\n\n // If scopes is a function, store it separately for dynamic resolution\n if (typeof scopes === \"function\") {\n this.scopesResolver = scopes;\n this.installUrlOptions = {\n scopes: [], // Will be resolved dynamically in handleInstall\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n } else {\n this.installUrlOptions = {\n scopes: scopes ?? [],\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n }\n this.installCallbackOptions = installerOptions.callbackOptions ?? {};\n this.installPathOptions = installerOptions.installPathOptions ?? {};\n }\n\n this.logger.debug(\"VercelReceiver initialized\");\n }\n\n /**\n * Initializes the receiver with a Slack Bolt app instance.\n * This method is called automatically by the Bolt framework.\n *\n * @param app - The Slack Bolt app instance\n */\n public init(app: App): void {\n this.app = app;\n this.logger.debug(\"App initialized in VercelReceiver\");\n }\n\n /**\n * Starts the receiver and returns a handler function for processing requests.\n * This method is called automatically by the Bolt framework.\n *\n * @returns A handler function that processes incoming Slack requests\n */\n public async start(): Promise<VercelHandler> {\n this.logger.debug(\"VercelReceiver started\");\n return this.toHandler();\n }\n\n /**\n * Stops the receiver. This method is called automatically by the Bolt framework.\n */\n public async stop(): Promise<void> {\n this.logger.debug(\"VercelReceiver stopped\");\n }\n\n /**\n * Handles requests to the OAuth install path.\n * Renders an \"Add to Slack\" page or redirects directly to Slack's authorize URL.\n */\n public handleInstall = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n // Resolve scopes dynamically if a resolver function was provided\n let installUrlOptions = this.installUrlOptions;\n if (this.scopesResolver && installUrlOptions) {\n const resolvedScopes = await this.scopesResolver(req);\n installUrlOptions = {\n ...installUrlOptions,\n scopes: resolvedScopes,\n };\n }\n\n await this.installer.handleInstallPath(\n nodeReq,\n capture,\n this.installPathOptions,\n installUrlOptions,\n );\n\n return capture.toResponse();\n };\n\n /**\n * Handles the OAuth redirect callback from Slack.\n * Exchanges the authorization code for tokens and stores the installation.\n */\n public handleCallback = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n if (this.stateVerification === false) {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n this.installUrlOptions,\n );\n } else {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n );\n }\n\n return capture.toResponse();\n };\n\n /**\n * Creates a handler function that processes incoming Slack requests.\n * This is the main entry point for handling Slack events in Vercel.\n * It is called automatically by the Bolt framework in the start() method.\n *\n * @returns A handler function compatible with Vercel's function signature\n */\n public toHandler(): VercelHandler {\n return async (req: Request): Promise<Response> => {\n try {\n const rawBody = await req.text();\n\n if (this.signatureVerification) {\n this.verifyRequest(req, rawBody);\n }\n\n const body = await this.parseRequestBody(req, rawBody);\n\n if (body.type === \"url_verification\") {\n this.logger.debug(\"Handling URL verification challenge\");\n return Response.json({ challenge: body.challenge });\n }\n\n // Allow beforeProcess to intercept and short-circuit processing.\n // We pass a new Request with the raw body since req.text() was already consumed.\n if (this.beforeProcess) {\n const reqWithBody = new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: rawBody,\n });\n const interceptResponse = await this.beforeProcess(reqWithBody, body);\n if (interceptResponse) {\n this.logger.debug(\"Request intercepted by beforeProcess\");\n return interceptResponse;\n }\n }\n\n return await this.handleSlackEvent(req, body);\n } catch (error) {\n return this.handleError(error);\n }\n };\n }\n\n private async parseRequestBody(\n req: Request,\n rawBody: string,\n ): Promise<StringIndexed> {\n const contentType = req.headers.get(\"content-type\");\n\n try {\n if (contentType === \"application/x-www-form-urlencoded\") {\n const parsedBody: StringIndexed = {};\n const params = new URLSearchParams(rawBody);\n\n for (const [key, value] of params.entries()) {\n parsedBody[key] = value;\n }\n\n if (typeof parsedBody.payload === \"string\") {\n return JSON.parse(parsedBody.payload);\n }\n return parsedBody;\n }\n if (contentType === \"application/json\") {\n return JSON.parse(rawBody);\n }\n\n this.logger.warn(`Unexpected content-type detected: ${contentType}`);\n\n return JSON.parse(rawBody);\n } catch (e) {\n throw new RequestParsingError(\n `Failed to parse body as JSON data for content-type: ${contentType}. Error: ${\n e instanceof Error ? e.message : String(e)\n }`,\n );\n }\n }\n\n private async handleSlackEvent(\n req: Request,\n body: StringIndexed,\n ): Promise<Response> {\n if (!this.app) {\n throw new VercelReceiverError(ERROR_MESSAGES.APP_NOT_INITIALIZED, 500);\n }\n\n let isAcknowledged = false;\n let responseResolver: (value: Response) => void;\n let responseRejecter: (error: Error) => void;\n\n const responsePromise = new Promise<Response>((resolve, reject) => {\n responseResolver = resolve;\n responseRejecter = reject;\n });\n\n // Slack requires an acknowledgment from your app within 3 seconds\n const timeoutId = setTimeout(() => {\n if (!isAcknowledged) {\n isAcknowledged = true;\n this.logger.error(ERROR_MESSAGES.EVENT_NOT_ACKNOWLEDGED);\n const error = new VercelReceiverError(\n ERROR_MESSAGES.REQUEST_TIMEOUT,\n 408,\n );\n responseRejecter(error);\n }\n }, this.ackTimeoutMs);\n\n // Create acknowledgment function\n const ackFn: AckFn<StringIndexed> = async (responseBody) => {\n this.logger.debug(`ack() call begins (body: ${responseBody})`);\n if (isAcknowledged) {\n throw new ReceiverMultipleAckError();\n }\n\n isAcknowledged = true;\n clearTimeout(timeoutId);\n\n try {\n let body: string | undefined;\n if (typeof responseBody === \"undefined\") {\n body = undefined;\n } else if (typeof responseBody === \"string\") {\n body = responseBody;\n } else {\n body = JSON.stringify(responseBody);\n }\n const response = new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n responseResolver(response);\n } catch (error) {\n this.logger.error(ERROR_MESSAGES.ACKNOWLEDGMENT_ERROR, error);\n responseRejecter(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n };\n\n const event = this.createSlackReceiverEvent({\n body,\n headers: req.headers,\n ack: ackFn,\n request: req,\n });\n\n // Process event in background using waitUntil from Vercel Functions\n // https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil\n waitUntil(\n this.app.processEvent(event).catch((error) => {\n return this.handleError(error);\n }),\n );\n\n try {\n return await responsePromise;\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n private verifyRequest(req: Request, body: string): void {\n const timestamp = req.headers.get(SLACK_TIMESTAMP_HEADER);\n const signature = req.headers.get(SLACK_SIGNATURE_HEADER);\n\n if (!signature) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_SIGNATURE_HEADER),\n );\n }\n\n if (!timestamp) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_TIMESTAMP_HEADER),\n );\n }\n\n try {\n verifySlackRequest({\n signingSecret: this.signingSecret,\n body,\n headers: {\n \"x-slack-signature\": signature,\n \"x-slack-request-timestamp\": Number.parseInt(timestamp, 10),\n },\n logger: this.logger,\n });\n } catch (error) {\n throw new ReceiverAuthenticityError(\n error instanceof Error\n ? error.message\n : \"Failed to verify request signature\",\n );\n }\n }\n\n private createSlackReceiverEvent({\n body,\n headers,\n ack,\n request,\n }: {\n body: StringIndexed;\n headers: Headers;\n ack: AckFn<StringIndexed>;\n request: Request;\n }): ReceiverEvent {\n const customProperties = this.customPropertiesExtractor\n ? this.customPropertiesExtractor(request, body)\n : {};\n\n const retryNum = headers.get(SLACK_RETRY_NUM_HEADER) || \"0\";\n\n const retryReason = headers.get(SLACK_RETRY_REASON_HEADER) || \"\";\n\n return {\n body,\n ack,\n retryNum: Number(retryNum),\n retryReason,\n customProperties,\n };\n }\n\n public handleError(error: unknown): Response {\n const errorMessage = getErrorMessage(error);\n const errorType = getErrorType(error);\n const errorStatusCode = getStatusCode(error);\n\n this.logger.error(error);\n return new Response(\n JSON.stringify({\n error: errorMessage,\n type: errorType,\n }),\n {\n status: errorStatusCode,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n }\n\n private createScopedLogger(logger: Logger, logLevel: LogLevel): Logger {\n logger.setLevel(logLevel);\n\n return {\n ...logger,\n error: (...args) => logger.error?.(LOG_PREFIX, ...args),\n warn: (...args) => logger.warn?.(LOG_PREFIX, ...args),\n info: (...args) => logger.info?.(LOG_PREFIX, ...args),\n debug: (...args) => logger.debug?.(LOG_PREFIX, ...args),\n setLevel: logger.setLevel,\n getLevel: logger.getLevel,\n };\n }\n}\n\n/**\n * Creates a Vercel-compatible handler function for a Slack Bolt app.\n * This is the recommended way to create handlers for deployment on Vercel.\n *\n * @param {App} app - The initialized Slack Bolt app instance.\n * @param {VercelReceiver} receiver - The VercelReceiver instance.\n * @returns {VercelHandler} A handler function compatible with Vercel's function signature.\n *\n * @example\n * ```typescript\n * // api/events.ts\n * import { createHandler } from '@vercel/slack-bolt';\n * import { app, receiver } from '../app';\n *\n * const handler = createHandler(app, receiver);\n *\n * export const POST = async (req: Request) => {\n * return handler(req);\n * };\n * ```\n *\n * @throws {Error} If app initialization fails.\n * @throws {VercelReceiverError} If request processing fails.\n */\nexport function createHandler(\n app: App,\n receiver: VercelReceiver,\n): VercelHandler {\n let initPromise: Promise<void> | null = null;\n\n return async (req: Request) => {\n try {\n if (!initPromise) {\n initPromise = app.init().catch((error) => {\n // Reset initPromise so subsequent requests can retry initialization\n initPromise = null;\n throw error;\n });\n }\n await initPromise;\n\n receiver.init(app);\n const handler = await receiver.start();\n return handler(req);\n } catch (error) {\n // if app.init fails, we use console.error instead of logger.error because the logger is not available\n console.error(ERROR_MESSAGES.CREATE_HANDLER_ERROR, error);\n return new Response(\n JSON.stringify({\n error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR_HANDLER,\n type: ERROR_MESSAGES.TYPES.HANDLER_ERROR,\n }),\n { status: 500, headers: { \"content-type\": \"application/json\" } },\n );\n }\n };\n}\n"],"mappings":";;;;;;;;AACA,MAAa,iBAAiB;CAE5B,yBACE;CACF,qBAAqB;CACrB,sBACE;CACF,iBAAiB;CACjB,wBAAwB;CAGxB,0BAA0B,WACxB,4BAA4B;CAG9B,6BAA6B;CAC7B,uBAAuB;CACvB,+BAA+B;CAC/B,sBAAsB;CACtB,sBAAsB;CAGtB,OAAO;EACL,uBAAuB;EACvB,8BAA8B;EAC9B,uBAAuB;EACvB,kBAAkB;EAClB,eAAe;CACjB;AACF;AAEA,IAAa,sBAAb,cAAyC,MAAM;CAG3B;CAFlB,YACE,SACgB,aAAqB,KACrC;EACA,MAAM,OAAO;EAFG,KAAA,aAAA;EAGhB,KAAK,OAAO,eAAe,MAAM;CACnC;AACF;AAEA,IAAa,sBAAb,cAAyC,oBAAoB;CAC3D,YAAY,UAAkB,2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D,OAAO,IAAI,SACT,KAAK,UAAU;IACb,OAAO,eAAe;IACtB,MAAM,eAAe,MAAM;GAC7B,CAAC,GACD;IAAE,QAAQ;IAAK,SAAS,EAAE,gBAAgB,mBAAmB;GAAE,CACjE;EACF;CACF;AACF"}
|
package/dist/index.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { InstallProvider } from "@slack/oauth";
|
|
|
4
4
|
import { waitUntil } from "@vercel/functions";
|
|
5
5
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
6
6
|
import { Socket } from "node:net";
|
|
7
|
-
|
|
7
|
+
// src/errors.ts
|
|
8
8
|
const ERROR_MESSAGES = {
|
|
9
9
|
SIGNING_SECRET_REQUIRED: "SLACK_SIGNING_SECRET is required for VercelReceiver",
|
|
10
10
|
APP_NOT_INITIALIZED: "App not initialized",
|
|
@@ -78,8 +78,7 @@ function getErrorType(error) {
|
|
|
78
78
|
}
|
|
79
79
|
return ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;
|
|
80
80
|
}
|
|
81
|
-
|
|
82
|
-
//#region src/oauth-adapters.ts
|
|
81
|
+
// src/oauth-adapters.ts
|
|
83
82
|
/**
|
|
84
83
|
* Minimal Web <-> Node HTTP adapters for @slack/oauth InstallProvider.
|
|
85
84
|
*
|
|
@@ -166,8 +165,7 @@ function createResponseCapture() {
|
|
|
166
165
|
};
|
|
167
166
|
return res;
|
|
168
167
|
}
|
|
169
|
-
|
|
170
|
-
//#region src/index.ts
|
|
168
|
+
// src/index.ts
|
|
171
169
|
const LOG_PREFIX = "[@vercel/slack-bolt]";
|
|
172
170
|
const ACK_TIMEOUT_MS = 3001;
|
|
173
171
|
const SLACK_RETRY_NUM_HEADER = "x-slack-retry-num";
|
|
@@ -538,7 +536,6 @@ function createHandler(app, receiver) {
|
|
|
538
536
|
}
|
|
539
537
|
};
|
|
540
538
|
}
|
|
541
|
-
//#endregion
|
|
542
539
|
export { VercelReceiver, createHandler };
|
|
543
540
|
|
|
544
541
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/oauth-adapters.ts","../src/index.ts"],"sourcesContent":["// Error messages constants\nexport const ERROR_MESSAGES = {\n // VercelReceiver errors\n SIGNING_SECRET_REQUIRED:\n \"SLACK_SIGNING_SECRET is required for VercelReceiver\",\n APP_NOT_INITIALIZED: \"App not initialized\",\n OAUTH_NOT_CONFIGURED:\n \"OAuth is not configured. Provide clientId, clientSecret, and stateSecret to enable OAuth.\",\n REQUEST_TIMEOUT: \"Request timeout\",\n EVENT_NOT_ACKNOWLEDGED: \"Event not acknowledged within timeout period\",\n\n // Header validation errors\n MISSING_REQUIRED_HEADER: (header: string) =>\n `Missing required header: ${header}`,\n\n // Generic fallback errors\n REQUEST_VERIFICATION_FAILED: \"Request verification failed\",\n INTERNAL_SERVER_ERROR: \"Internal server error\",\n INTERNAL_SERVER_ERROR_HANDLER: \"Internal Server Error\",\n ACKNOWLEDGMENT_ERROR: \"Error in acknowledgment handler\",\n CREATE_HANDLER_ERROR: \"Error in createHandler:\",\n\n // Error type names\n TYPES: {\n VERCEL_RECEIVER_ERROR: \"VercelReceiverError\",\n SIGNATURE_VERIFICATION_ERROR: \"SignatureVerificationError\",\n REQUEST_PARSING_ERROR: \"RequestParsingError\",\n UNEXPECTED_ERROR: \"UnexpectedError\",\n HANDLER_ERROR: \"HandlerError\",\n },\n} as const;\n\nexport class VercelReceiverError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number = 500,\n ) {\n super(message);\n this.name = ERROR_MESSAGES.TYPES.VERCEL_RECEIVER_ERROR;\n }\n}\n\nexport class RequestParsingError extends VercelReceiverError {\n constructor(message: string = \"Failed to parse request\") {\n super(message, 400);\n this.name = ERROR_MESSAGES.TYPES.REQUEST_PARSING_ERROR;\n }\n}\n\n/**\n * Determines the appropriate HTTP status code for a given error.\n * @param error The error to get status code for\n * @returns HTTP status code\n */\nexport function getStatusCode(error: unknown): number {\n if (error instanceof VercelReceiverError) {\n return error.statusCode;\n }\n\n // External error types from @slack/bolt\n if (error && typeof error === \"object\") {\n const errorName =\n error.constructor?.name || (error as { name?: string }).name;\n switch (errorName) {\n case \"ReceiverAuthenticityError\":\n return 401;\n case \"ReceiverMultipleAckError\":\n return 500;\n case \"RequestParsingError\":\n return 400;\n case \"SignatureVerificationError\":\n return 400;\n default:\n return 500;\n }\n }\n\n return 500;\n}\n\n/**\n * Gets the error message for response.\n * @param error The error to get message for\n * @returns Error message string\n */\nexport function getErrorMessage(error: unknown): string {\n if (error && typeof error === \"object\" && \"message\" in error) {\n return String(error.message);\n }\n return ERROR_MESSAGES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * Gets the error type for response.\n * @param error The error to get type for\n * @returns Error type string\n */\nexport function getErrorType(error: unknown): string {\n if (error && typeof error === \"object\") {\n const ctorName = (error as { constructor?: { name?: string } }).constructor\n ?.name;\n const nameProp = (error as { name?: string }).name;\n const errorName =\n ctorName ?? nameProp ?? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n // Use \"UnexpectedError\" for generic Error instances, otherwise use the actual name\n return errorName === \"Error\"\n ? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR\n : errorName;\n }\n return ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n}\n","/**\n * Minimal Web <-> Node HTTP adapters for @slack/oauth InstallProvider.\n *\n * These do NOT implement the full IncomingMessage/ServerResponse contract.\n * Only the methods actually called by InstallProvider are intercepted.\n * Do not reuse for other Node libraries without verifying which methods\n * they call.\n *\n * Targets @slack/oauth\\@3.0.5 InstallProvider internals.\n * Do not upgrade without running the integration tests.\n *\n * Bolt 5 consumers also have @slack/oauth\\@4 in their tree (Bolt's own copy).\n * That is fine: Bolt only reads `receiver.installer.authorize` as a plain\n * function, and the Installation/InstallationStore types are structurally\n * identical across 3.x and 4.x. The 3.0.5 pin is deliberate until Bolt 4\n * support is dropped, so Bolt 4 consumers keep a single copy.\n */\n\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nexport type ResponseCapture = ServerResponse & { toResponse(): Response };\n\n/**\n * Wraps a Web API Request as a minimal Node.js IncomingMessage\n * so it can be passed to @slack/oauth's InstallProvider methods.\n */\nexport function toIncomingMessage(req: Request): IncomingMessage {\n const url = new URL(req.url);\n // Dummy socket — satisfies the IncomingMessage constructor but is never connected.\n const msg = new IncomingMessage(new Socket());\n msg.url = url.pathname + url.search;\n msg.method = req.method;\n for (const [key, value] of req.headers.entries()) {\n msg.headers[key.toLowerCase()] = value;\n }\n\n if (req.body) {\n req\n .arrayBuffer()\n .then((buf) => {\n msg.push(Buffer.from(buf));\n msg.push(null);\n })\n .catch(() => msg.destroy());\n } else {\n msg.push(null);\n }\n\n return msg;\n}\n\n/**\n * Creates a fake ServerResponse that captures setHeader/writeHead/end calls\n * and converts them into a Web API Response.\n *\n * InstallProvider uses res.setHeader() for Location, Set-Cookie, Content-Type\n * and res.getHeader() to read back Set-Cookie before appending.\n */\nexport function createResponseCapture(): ResponseCapture {\n let statusCode = 200;\n const capturedHeaders: Record<string, string | string[]> = {};\n const chunks: Buffer[] = [];\n\n // Dummy socket/message pair — never connected, just satisfies the constructor.\n const res = new ServerResponse(new IncomingMessage(new Socket()));\n\n const originalSetHeader = res.setHeader.bind(res);\n res.setHeader = (\n name: string,\n value: string | number | readonly string[],\n ) => {\n const key = name.toLowerCase();\n if (Array.isArray(value)) {\n capturedHeaders[key] = [...value];\n } else {\n capturedHeaders[key] = String(value);\n }\n return originalSetHeader(name, value);\n };\n\n const originalGetHeader = res.getHeader.bind(res);\n res.getHeader = (name: string): string | number | string[] | undefined => {\n const val = capturedHeaders[name.toLowerCase()];\n if (val !== undefined) return val;\n return originalGetHeader(name);\n };\n\n const originalWriteHead = res.writeHead.bind(res);\n // writeHead has four overloads: (code), (code, message), (code, headers),\n // and (code, message, headers). We sniff for the first non-array object arg\n // to find the headers object in all cases.\n // biome-ignore lint/suspicious/noExplicitAny: writeHead has many overloads\n res.writeHead = (code: number, ...args: any[]) => {\n statusCode = code;\n const headersArg = args.find(\n (a) => a !== undefined && typeof a === \"object\" && !Array.isArray(a),\n ) as Record<string, string | string[]> | undefined;\n if (headersArg) {\n for (const [key, value] of Object.entries(headersArg)) {\n const lower = key.toLowerCase();\n capturedHeaders[lower] = value;\n }\n }\n return originalWriteHead(code, ...args);\n };\n\n const originalEnd = res.end.bind(res);\n // biome-ignore lint/suspicious/noExplicitAny: end has many overloads\n res.end = (chunk?: any, ...args: any[]) => {\n if (chunk !== undefined && chunk !== null) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return originalEnd(chunk, ...args);\n };\n\n (res as ResponseCapture).toResponse = () => {\n const body = chunks.length > 0 ? Buffer.concat(chunks).toString() : null;\n const webHeaders = new Headers();\n for (const [key, value] of Object.entries(capturedHeaders)) {\n if (Array.isArray(value)) {\n for (const v of value) webHeaders.append(key, v);\n } else {\n webHeaders.set(key, value);\n }\n }\n return new Response(body, { status: statusCode, headers: webHeaders });\n };\n\n return res as ResponseCapture;\n}\n","import {\n type AckFn,\n type App,\n type HTTPReceiverOptions,\n type Receiver,\n ReceiverAuthenticityError,\n type ReceiverEvent,\n ReceiverMultipleAckError,\n type StringIndexed,\n verifySlackRequest,\n} from \"@slack/bolt\";\nimport { ConsoleLogger, type Logger, LogLevel } from \"@slack/logger\";\nimport {\n type CallbackOptions,\n type InstallPathOptions,\n InstallProvider,\n type InstallProviderOptions,\n type InstallURLOptions,\n type StateStore,\n} from \"@slack/oauth\";\nimport { waitUntil } from \"@vercel/functions\";\nimport {\n ERROR_MESSAGES,\n getErrorMessage,\n getErrorType,\n getStatusCode,\n RequestParsingError,\n VercelReceiverError,\n} from \"./errors\";\nimport { createResponseCapture, toIncomingMessage } from \"./oauth-adapters\";\n\n// Types\n/**\n * A function to handle the request from the Slack app.\n * @param req - The request from the Slack app.\n * @returns A response object.\n */\nexport type VercelHandler = (req: Request) => Promise<Response>;\n\n/**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing, or undefined to continue.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: This hook is NOT called for `url_verification` challenge requests, which are\n * handled automatically before `beforeProcess` is invoked.\n *\n * @param req - A new Request with the raw body (the original request body was consumed during parsing)\n * @param body - The parsed request body\n * @returns A Response to short-circuit processing, or undefined to continue to Bolt\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver({\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * beforeProcess: async (req, body) => {\n * // Forward certain workspaces to a different service\n * if (body.team_id === 'T_ENTERPRISE') {\n * return fetch('https://enterprise-handler.example.com/slack', {\n * method: 'POST',\n * body: await req.text(),\n * headers: req.headers,\n * });\n * }\n * // Return undefined to continue normal Bolt processing\n * },\n * });\n * ```\n */\nexport type BeforeProcessFn = (\n req: Request,\n body: StringIndexed,\n) => Promise<Response | undefined> | Response | undefined;\n\n/**\n * A function that resolves scopes dynamically based on the request.\n * Useful for requesting different scopes based on team or user context.\n * @param req - The original request\n * @returns The scopes to request\n */\nexport type ScopesResolver = (req: Request) => Promise<string[]> | string[];\n\n/**\n * Configuration options for the VercelReceiver.\n * @property signingSecret - The signing secret for the Slack app.\n * @property signatureVerification - If true, verifies the Slack request signature.\n * @property logger - The logger to use for the VercelReceiver.\n * @property logLevel - The log level to use for the VercelReceiver.\n * @property customPropertiesExtractor - A function to extract custom properties from the request.\n */\n/**\n * Options for customizing the OAuth installer behavior.\n * Mirrors the relevant subset of HTTPReceiverInstallerOptions,\n * excluding path-related options (serverless uses file-based routing).\n */\nexport interface VercelInstallerOptions {\n directInstall?: boolean;\n renderHtmlForInstallPath?: (url: string) => string;\n stateStore?: StateStore;\n stateVerification?: boolean;\n legacyStateVerification?: boolean;\n stateCookieName?: string;\n stateCookieExpirationSeconds?: number;\n authVersion?: \"v1\" | \"v2\";\n clientOptions?: InstallProviderOptions[\"clientOptions\"];\n authorizationUrl?: string;\n metadata?: string;\n userScopes?: string[];\n installPathOptions?: InstallPathOptions;\n callbackOptions?: CallbackOptions;\n}\n\n/**\n * Configuration options for the VercelReceiver.\n */\nexport interface VercelReceiverOptions {\n /**\n * The signing secret for the Slack app.\n * @default process.env.SLACK_SIGNING_SECRET\n */\n signingSecret?: string;\n /**\n * If true, verifies the Slack request signature.\n * @default true\n */\n signatureVerification?: boolean;\n /**\n * The logger to use for the VercelReceiver.\n * @default new ConsoleLogger()\n */\n logger?: Logger;\n /**\n * The log level to use for the VercelReceiver.\n * @default LogLevel.INFO\n */\n logLevel?: LogLevel;\n /**\n * A function to extract custom properties from incoming events.\n * Called after body parsing, so the parsed body is available.\n * @default undefined\n * @returns An object with custom properties.\n */\n customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n /**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing (e.g., to forward to an external service),\n * or undefined to continue normal Bolt processing.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: Not called for `url_verification` challenge requests.\n * @default undefined\n */\n beforeProcess?: BeforeProcessFn;\n /**\n * The timeout in milliseconds for event acknowledgment.\n * @default 3001\n */\n ackTimeoutMs?: number;\n /**\n * Your app's client ID, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_ID\n */\n clientId?: string;\n /**\n * Your app's client secret, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_SECRET\n */\n clientSecret?: string;\n /**\n * Secret used to generate and verify the state parameter for OAuth CSRF protection.\n * Required unless a custom stateStore or stateVerification: false is provided.\n * @default process.env.SLACK_STATE_SECRET\n */\n stateSecret?: string;\n /**\n * The bot scopes to request during the OAuth flow.\n * Can be a static array or a function that resolves scopes dynamically\n * based on the request (e.g., to request different scopes for different teams).\n */\n scopes?: string[] | ScopesResolver;\n /**\n * The redirect URI registered with your Slack app for OAuth callbacks.\n */\n redirectUri?: string;\n /**\n * Storage backend for OAuth installations (tokens, team info, etc.).\n * Required for OAuth in serverless -- the default in-memory store does not persist.\n */\n installationStore?: InstallProviderOptions[\"installationStore\"];\n /**\n * Advanced options for the OAuth installer.\n */\n installerOptions?: VercelInstallerOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Compile-time shape assertions\n// Verify our types match Bolt's underlying shapes without coupling optionality.\n// If Bolt changes a type upstream, tsc breaks here -- not in user-land at runtime.\n// ---------------------------------------------------------------------------\ntype AssertShape<Source, Target> =\n NonNullable<Source> extends NonNullable<Target> ? true : never;\n\ntype _S1 = AssertShape<\n VercelReceiverOptions[\"clientId\"],\n HTTPReceiverOptions[\"clientId\"]\n>;\ntype _S2 = AssertShape<\n VercelReceiverOptions[\"clientSecret\"],\n HTTPReceiverOptions[\"clientSecret\"]\n>;\ntype _S3 = AssertShape<\n VercelReceiverOptions[\"stateSecret\"],\n HTTPReceiverOptions[\"stateSecret\"]\n>;\ntype _S4 = AssertShape<\n VercelReceiverOptions[\"scopes\"],\n HTTPReceiverOptions[\"scopes\"]\n>;\ntype _S5 = AssertShape<\n VercelReceiverOptions[\"redirectUri\"],\n HTTPReceiverOptions[\"redirectUri\"]\n>;\ntype _S6 = AssertShape<\n VercelReceiverOptions[\"installationStore\"],\n HTTPReceiverOptions[\"installationStore\"]\n>;\ntype _S7 = AssertShape<\n VercelInstallerOptions[\"stateVerification\"],\n InstallProviderOptions[\"stateVerification\"]\n>;\ntype _S8 = AssertShape<\n VercelInstallerOptions[\"callbackOptions\"],\n CallbackOptions\n>;\ntype _S9 = AssertShape<\n VercelInstallerOptions[\"stateStore\"],\n InstallProviderOptions[\"stateStore\"]\n>;\ntype _S10 = AssertShape<\n VercelInstallerOptions[\"authVersion\"],\n InstallProviderOptions[\"authVersion\"]\n>;\ntype _S11 = AssertShape<\n VercelInstallerOptions[\"userScopes\"],\n InstallURLOptions[\"userScopes\"]\n>;\ntype _S12 = AssertShape<\n VercelInstallerOptions[\"metadata\"],\n InstallURLOptions[\"metadata\"]\n>;\n\nconst LOG_PREFIX = \"[@vercel/slack-bolt]\";\nconst ACK_TIMEOUT_MS = 3001;\nconst SLACK_RETRY_NUM_HEADER = \"x-slack-retry-num\";\nconst SLACK_RETRY_REASON_HEADER = \"x-slack-retry-reason\";\nconst SLACK_TIMESTAMP_HEADER = \"x-slack-request-timestamp\";\nconst SLACK_SIGNATURE_HEADER = \"x-slack-signature\";\n\n/**\n * A Slack Bolt receiver implementation designed for Vercel's serverless environment.\n * Handles Slack events, interactions, and slash commands with automatic request verification,\n * background processing, and timeout management.\n *\n * @example\n * ```typescript\n * import { App } from '@slack/bolt';\n * import { VercelReceiver, createHandler } from '@vercel/slack-bolt';\n *\n * const receiver = new VercelReceiver();\n *\n * const app = new App({\n * receiver,\n * token: process.env.SLACK_BOT_TOKEN,\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * });\n * ```\n *\n */\nexport class VercelReceiver implements Receiver {\n private readonly signingSecret: string;\n private readonly signatureVerification: boolean;\n private readonly logger: Logger;\n private readonly customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n private readonly beforeProcess?: BeforeProcessFn;\n private readonly ackTimeoutMs: number;\n private app?: App;\n\n public installer?: InstallProvider;\n private installUrlOptions?: InstallURLOptions;\n private scopesResolver?: ScopesResolver;\n private installCallbackOptions?: CallbackOptions;\n private installPathOptions?: InstallPathOptions;\n private stateVerification?: boolean;\n\n /**\n * Gets the logger instance used by this receiver.\n * @returns The logger instance\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Creates a new VercelReceiver instance.\n *\n * @param options - Configuration options for the receiver\n * @throws {VercelReceiverError} When signing secret is not provided\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver();\n * ```\n */\n public constructor({\n signingSecret = process.env.SLACK_SIGNING_SECRET,\n signatureVerification = true,\n logger,\n logLevel = LogLevel.INFO,\n customPropertiesExtractor,\n beforeProcess,\n ackTimeoutMs = ACK_TIMEOUT_MS,\n clientId = process.env.SLACK_CLIENT_ID,\n clientSecret = process.env.SLACK_CLIENT_SECRET,\n stateSecret = process.env.SLACK_STATE_SECRET,\n scopes,\n redirectUri,\n installationStore,\n installerOptions = {},\n }: VercelReceiverOptions = {}) {\n if (!signingSecret) {\n throw new VercelReceiverError(ERROR_MESSAGES.SIGNING_SECRET_REQUIRED);\n }\n\n this.signingSecret = signingSecret;\n this.signatureVerification = signatureVerification;\n this.logger = this.createScopedLogger(\n logger ?? new ConsoleLogger(),\n logLevel,\n );\n this.customPropertiesExtractor = customPropertiesExtractor;\n this.beforeProcess = beforeProcess;\n this.ackTimeoutMs = ackTimeoutMs;\n\n this.stateVerification = installerOptions.stateVerification;\n\n if (\n clientId !== undefined &&\n clientSecret !== undefined &&\n (installerOptions.stateVerification === false ||\n stateSecret !== undefined ||\n installerOptions.stateStore !== undefined)\n ) {\n this.installer = new InstallProvider({\n clientId,\n clientSecret,\n stateSecret,\n installationStore,\n logger,\n logLevel,\n directInstall: installerOptions.directInstall,\n stateStore: installerOptions.stateStore,\n stateVerification: installerOptions.stateVerification,\n legacyStateVerification: installerOptions.legacyStateVerification,\n stateCookieName: installerOptions.stateCookieName,\n stateCookieExpirationSeconds:\n installerOptions.stateCookieExpirationSeconds,\n renderHtmlForInstallPath: installerOptions.renderHtmlForInstallPath,\n authVersion: installerOptions.authVersion ?? \"v2\",\n clientOptions: installerOptions.clientOptions,\n authorizationUrl: installerOptions.authorizationUrl,\n });\n\n // If scopes is a function, store it separately for dynamic resolution\n if (typeof scopes === \"function\") {\n this.scopesResolver = scopes;\n this.installUrlOptions = {\n scopes: [], // Will be resolved dynamically in handleInstall\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n } else {\n this.installUrlOptions = {\n scopes: scopes ?? [],\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n }\n this.installCallbackOptions = installerOptions.callbackOptions ?? {};\n this.installPathOptions = installerOptions.installPathOptions ?? {};\n }\n\n this.logger.debug(\"VercelReceiver initialized\");\n }\n\n /**\n * Initializes the receiver with a Slack Bolt app instance.\n * This method is called automatically by the Bolt framework.\n *\n * @param app - The Slack Bolt app instance\n */\n public init(app: App): void {\n this.app = app;\n this.logger.debug(\"App initialized in VercelReceiver\");\n }\n\n /**\n * Starts the receiver and returns a handler function for processing requests.\n * This method is called automatically by the Bolt framework.\n *\n * @returns A handler function that processes incoming Slack requests\n */\n public async start(): Promise<VercelHandler> {\n this.logger.debug(\"VercelReceiver started\");\n return this.toHandler();\n }\n\n /**\n * Stops the receiver. This method is called automatically by the Bolt framework.\n */\n public async stop(): Promise<void> {\n this.logger.debug(\"VercelReceiver stopped\");\n }\n\n /**\n * Handles requests to the OAuth install path.\n * Renders an \"Add to Slack\" page or redirects directly to Slack's authorize URL.\n */\n public handleInstall = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n // Resolve scopes dynamically if a resolver function was provided\n let installUrlOptions = this.installUrlOptions;\n if (this.scopesResolver && installUrlOptions) {\n const resolvedScopes = await this.scopesResolver(req);\n installUrlOptions = {\n ...installUrlOptions,\n scopes: resolvedScopes,\n };\n }\n\n await this.installer.handleInstallPath(\n nodeReq,\n capture,\n this.installPathOptions,\n installUrlOptions,\n );\n\n return capture.toResponse();\n };\n\n /**\n * Handles the OAuth redirect callback from Slack.\n * Exchanges the authorization code for tokens and stores the installation.\n */\n public handleCallback = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n if (this.stateVerification === false) {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n this.installUrlOptions,\n );\n } else {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n );\n }\n\n return capture.toResponse();\n };\n\n /**\n * Creates a handler function that processes incoming Slack requests.\n * This is the main entry point for handling Slack events in Vercel.\n * It is called automatically by the Bolt framework in the start() method.\n *\n * @returns A handler function compatible with Vercel's function signature\n */\n public toHandler(): VercelHandler {\n return async (req: Request): Promise<Response> => {\n try {\n const rawBody = await req.text();\n\n if (this.signatureVerification) {\n this.verifyRequest(req, rawBody);\n }\n\n const body = await this.parseRequestBody(req, rawBody);\n\n if (body.type === \"url_verification\") {\n this.logger.debug(\"Handling URL verification challenge\");\n return Response.json({ challenge: body.challenge });\n }\n\n // Allow beforeProcess to intercept and short-circuit processing.\n // We pass a new Request with the raw body since req.text() was already consumed.\n if (this.beforeProcess) {\n const reqWithBody = new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: rawBody,\n });\n const interceptResponse = await this.beforeProcess(reqWithBody, body);\n if (interceptResponse) {\n this.logger.debug(\"Request intercepted by beforeProcess\");\n return interceptResponse;\n }\n }\n\n return await this.handleSlackEvent(req, body);\n } catch (error) {\n return this.handleError(error);\n }\n };\n }\n\n private async parseRequestBody(\n req: Request,\n rawBody: string,\n ): Promise<StringIndexed> {\n const contentType = req.headers.get(\"content-type\");\n\n try {\n if (contentType === \"application/x-www-form-urlencoded\") {\n const parsedBody: StringIndexed = {};\n const params = new URLSearchParams(rawBody);\n\n for (const [key, value] of params.entries()) {\n parsedBody[key] = value;\n }\n\n if (typeof parsedBody.payload === \"string\") {\n return JSON.parse(parsedBody.payload);\n }\n return parsedBody;\n }\n if (contentType === \"application/json\") {\n return JSON.parse(rawBody);\n }\n\n this.logger.warn(`Unexpected content-type detected: ${contentType}`);\n\n return JSON.parse(rawBody);\n } catch (e) {\n throw new RequestParsingError(\n `Failed to parse body as JSON data for content-type: ${contentType}. Error: ${\n e instanceof Error ? e.message : String(e)\n }`,\n );\n }\n }\n\n private async handleSlackEvent(\n req: Request,\n body: StringIndexed,\n ): Promise<Response> {\n if (!this.app) {\n throw new VercelReceiverError(ERROR_MESSAGES.APP_NOT_INITIALIZED, 500);\n }\n\n let isAcknowledged = false;\n let responseResolver: (value: Response) => void;\n let responseRejecter: (error: Error) => void;\n\n const responsePromise = new Promise<Response>((resolve, reject) => {\n responseResolver = resolve;\n responseRejecter = reject;\n });\n\n // Slack requires an acknowledgment from your app within 3 seconds\n const timeoutId = setTimeout(() => {\n if (!isAcknowledged) {\n isAcknowledged = true;\n this.logger.error(ERROR_MESSAGES.EVENT_NOT_ACKNOWLEDGED);\n const error = new VercelReceiverError(\n ERROR_MESSAGES.REQUEST_TIMEOUT,\n 408,\n );\n responseRejecter(error);\n }\n }, this.ackTimeoutMs);\n\n // Create acknowledgment function\n const ackFn: AckFn<StringIndexed> = async (responseBody) => {\n this.logger.debug(`ack() call begins (body: ${responseBody})`);\n if (isAcknowledged) {\n throw new ReceiverMultipleAckError();\n }\n\n isAcknowledged = true;\n clearTimeout(timeoutId);\n\n try {\n let body: string | undefined;\n if (typeof responseBody === \"undefined\") {\n body = undefined;\n } else if (typeof responseBody === \"string\") {\n body = responseBody;\n } else {\n body = JSON.stringify(responseBody);\n }\n const response = new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n responseResolver(response);\n } catch (error) {\n this.logger.error(ERROR_MESSAGES.ACKNOWLEDGMENT_ERROR, error);\n responseRejecter(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n };\n\n const event = this.createSlackReceiverEvent({\n body,\n headers: req.headers,\n ack: ackFn,\n request: req,\n });\n\n // Process event in background using waitUntil from Vercel Functions\n // https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil\n waitUntil(\n this.app.processEvent(event).catch((error) => {\n return this.handleError(error);\n }),\n );\n\n try {\n return await responsePromise;\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n private verifyRequest(req: Request, body: string): void {\n const timestamp = req.headers.get(SLACK_TIMESTAMP_HEADER);\n const signature = req.headers.get(SLACK_SIGNATURE_HEADER);\n\n if (!signature) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_SIGNATURE_HEADER),\n );\n }\n\n if (!timestamp) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_TIMESTAMP_HEADER),\n );\n }\n\n try {\n verifySlackRequest({\n signingSecret: this.signingSecret,\n body,\n headers: {\n \"x-slack-signature\": signature,\n \"x-slack-request-timestamp\": Number.parseInt(timestamp, 10),\n },\n logger: this.logger,\n });\n } catch (error) {\n throw new ReceiverAuthenticityError(\n error instanceof Error\n ? error.message\n : \"Failed to verify request signature\",\n );\n }\n }\n\n private createSlackReceiverEvent({\n body,\n headers,\n ack,\n request,\n }: {\n body: StringIndexed;\n headers: Headers;\n ack: AckFn<StringIndexed>;\n request: Request;\n }): ReceiverEvent {\n const customProperties = this.customPropertiesExtractor\n ? this.customPropertiesExtractor(request, body)\n : {};\n\n const retryNum = headers.get(SLACK_RETRY_NUM_HEADER) || \"0\";\n\n const retryReason = headers.get(SLACK_RETRY_REASON_HEADER) || \"\";\n\n return {\n body,\n ack,\n retryNum: Number(retryNum),\n retryReason,\n customProperties,\n };\n }\n\n public handleError(error: unknown): Response {\n const errorMessage = getErrorMessage(error);\n const errorType = getErrorType(error);\n const errorStatusCode = getStatusCode(error);\n\n this.logger.error(error);\n return new Response(\n JSON.stringify({\n error: errorMessage,\n type: errorType,\n }),\n {\n status: errorStatusCode,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n }\n\n private createScopedLogger(logger: Logger, logLevel: LogLevel): Logger {\n logger.setLevel(logLevel);\n\n return {\n ...logger,\n error: (...args) => logger.error?.(LOG_PREFIX, ...args),\n warn: (...args) => logger.warn?.(LOG_PREFIX, ...args),\n info: (...args) => logger.info?.(LOG_PREFIX, ...args),\n debug: (...args) => logger.debug?.(LOG_PREFIX, ...args),\n setLevel: logger.setLevel,\n getLevel: logger.getLevel,\n };\n }\n}\n\n/**\n * Creates a Vercel-compatible handler function for a Slack Bolt app.\n * This is the recommended way to create handlers for deployment on Vercel.\n *\n * @param {App} app - The initialized Slack Bolt app instance.\n * @param {VercelReceiver} receiver - The VercelReceiver instance.\n * @returns {VercelHandler} A handler function compatible with Vercel's function signature.\n *\n * @example\n * ```typescript\n * // api/events.ts\n * import { createHandler } from '@vercel/slack-bolt';\n * import { app, receiver } from '../app';\n *\n * const handler = createHandler(app, receiver);\n *\n * export const POST = async (req: Request) => {\n * return handler(req);\n * };\n * ```\n *\n * @throws {Error} If app initialization fails.\n * @throws {VercelReceiverError} If request processing fails.\n */\nexport function createHandler(\n app: App,\n receiver: VercelReceiver,\n): VercelHandler {\n let initPromise: Promise<void> | null = null;\n\n return async (req: Request) => {\n try {\n if (!initPromise) {\n initPromise = app.init().catch((error) => {\n // Reset initPromise so subsequent requests can retry initialization\n initPromise = null;\n throw error;\n });\n }\n await initPromise;\n\n receiver.init(app);\n const handler = await receiver.start();\n return handler(req);\n } catch (error) {\n // if app.init fails, we use console.error instead of logger.error because the logger is not available\n console.error(ERROR_MESSAGES.CREATE_HANDLER_ERROR, error);\n return new Response(\n JSON.stringify({\n error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR_HANDLER,\n type: ERROR_MESSAGES.TYPES.HANDLER_ERROR,\n }),\n { status: 500, headers: { \"content-type\": \"application/json\" } },\n );\n }\n };\n}\n"],"mappings":";;;;;;;AACA,MAAa,iBAAiB;CAE5B,yBACE;CACF,qBAAqB;CACrB,sBACE;CACF,iBAAiB;CACjB,wBAAwB;CAGxB,0BAA0B,WACxB,4BAA4B;CAG9B,6BAA6B;CAC7B,uBAAuB;CACvB,+BAA+B;CAC/B,sBAAsB;CACtB,sBAAsB;CAGtB,OAAO;EACL,uBAAuB;EACvB,8BAA8B;EAC9B,uBAAuB;EACvB,kBAAkB;EAClB,eAAe;CACjB;AACF;AAEA,IAAa,sBAAb,cAAyC,MAAM;CAG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AAK;GACxD,OAAO,IAAI,SACT,KAAK,UAAU;IACb,OAAO,eAAe;IACtB,MAAM,eAAe,MAAM;GAC7B,CAAC,GACD;IAAE,QAAQ;IAAK,SAAS,EAAE,gBAAgB,mBAAmB;GAAE,CACjE;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/oauth-adapters.ts","../src/index.ts"],"sourcesContent":["// Error messages constants\nexport const ERROR_MESSAGES = {\n // VercelReceiver errors\n SIGNING_SECRET_REQUIRED:\n \"SLACK_SIGNING_SECRET is required for VercelReceiver\",\n APP_NOT_INITIALIZED: \"App not initialized\",\n OAUTH_NOT_CONFIGURED:\n \"OAuth is not configured. Provide clientId, clientSecret, and stateSecret to enable OAuth.\",\n REQUEST_TIMEOUT: \"Request timeout\",\n EVENT_NOT_ACKNOWLEDGED: \"Event not acknowledged within timeout period\",\n\n // Header validation errors\n MISSING_REQUIRED_HEADER: (header: string) =>\n `Missing required header: ${header}`,\n\n // Generic fallback errors\n REQUEST_VERIFICATION_FAILED: \"Request verification failed\",\n INTERNAL_SERVER_ERROR: \"Internal server error\",\n INTERNAL_SERVER_ERROR_HANDLER: \"Internal Server Error\",\n ACKNOWLEDGMENT_ERROR: \"Error in acknowledgment handler\",\n CREATE_HANDLER_ERROR: \"Error in createHandler:\",\n\n // Error type names\n TYPES: {\n VERCEL_RECEIVER_ERROR: \"VercelReceiverError\",\n SIGNATURE_VERIFICATION_ERROR: \"SignatureVerificationError\",\n REQUEST_PARSING_ERROR: \"RequestParsingError\",\n UNEXPECTED_ERROR: \"UnexpectedError\",\n HANDLER_ERROR: \"HandlerError\",\n },\n} as const;\n\nexport class VercelReceiverError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number = 500,\n ) {\n super(message);\n this.name = ERROR_MESSAGES.TYPES.VERCEL_RECEIVER_ERROR;\n }\n}\n\nexport class RequestParsingError extends VercelReceiverError {\n constructor(message: string = \"Failed to parse request\") {\n super(message, 400);\n this.name = ERROR_MESSAGES.TYPES.REQUEST_PARSING_ERROR;\n }\n}\n\n/**\n * Determines the appropriate HTTP status code for a given error.\n * @param error The error to get status code for\n * @returns HTTP status code\n */\nexport function getStatusCode(error: unknown): number {\n if (error instanceof VercelReceiverError) {\n return error.statusCode;\n }\n\n // External error types from @slack/bolt\n if (error && typeof error === \"object\") {\n const errorName =\n error.constructor?.name || (error as { name?: string }).name;\n switch (errorName) {\n case \"ReceiverAuthenticityError\":\n return 401;\n case \"ReceiverMultipleAckError\":\n return 500;\n case \"RequestParsingError\":\n return 400;\n case \"SignatureVerificationError\":\n return 400;\n default:\n return 500;\n }\n }\n\n return 500;\n}\n\n/**\n * Gets the error message for response.\n * @param error The error to get message for\n * @returns Error message string\n */\nexport function getErrorMessage(error: unknown): string {\n if (error && typeof error === \"object\" && \"message\" in error) {\n return String(error.message);\n }\n return ERROR_MESSAGES.INTERNAL_SERVER_ERROR;\n}\n\n/**\n * Gets the error type for response.\n * @param error The error to get type for\n * @returns Error type string\n */\nexport function getErrorType(error: unknown): string {\n if (error && typeof error === \"object\") {\n const ctorName = (error as { constructor?: { name?: string } }).constructor\n ?.name;\n const nameProp = (error as { name?: string }).name;\n const errorName =\n ctorName ?? nameProp ?? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n // Use \"UnexpectedError\" for generic Error instances, otherwise use the actual name\n return errorName === \"Error\"\n ? ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR\n : errorName;\n }\n return ERROR_MESSAGES.TYPES.UNEXPECTED_ERROR;\n}\n","/**\n * Minimal Web <-> Node HTTP adapters for @slack/oauth InstallProvider.\n *\n * These do NOT implement the full IncomingMessage/ServerResponse contract.\n * Only the methods actually called by InstallProvider are intercepted.\n * Do not reuse for other Node libraries without verifying which methods\n * they call.\n *\n * Targets @slack/oauth\\@3.0.5 InstallProvider internals.\n * Do not upgrade without running the integration tests.\n *\n * Bolt 5 consumers also have @slack/oauth\\@4 in their tree (Bolt's own copy).\n * That is fine: Bolt only reads `receiver.installer.authorize` as a plain\n * function, and the Installation/InstallationStore types are structurally\n * identical across 3.x and 4.x. The 3.0.5 pin is deliberate until Bolt 4\n * support is dropped, so Bolt 4 consumers keep a single copy.\n */\n\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nexport type ResponseCapture = ServerResponse & { toResponse(): Response };\n\n/**\n * Wraps a Web API Request as a minimal Node.js IncomingMessage\n * so it can be passed to @slack/oauth's InstallProvider methods.\n */\nexport function toIncomingMessage(req: Request): IncomingMessage {\n const url = new URL(req.url);\n // Dummy socket — satisfies the IncomingMessage constructor but is never connected.\n const msg = new IncomingMessage(new Socket());\n msg.url = url.pathname + url.search;\n msg.method = req.method;\n for (const [key, value] of req.headers.entries()) {\n msg.headers[key.toLowerCase()] = value;\n }\n\n if (req.body) {\n req\n .arrayBuffer()\n .then((buf) => {\n msg.push(Buffer.from(buf));\n msg.push(null);\n })\n .catch(() => msg.destroy());\n } else {\n msg.push(null);\n }\n\n return msg;\n}\n\n/**\n * Creates a fake ServerResponse that captures setHeader/writeHead/end calls\n * and converts them into a Web API Response.\n *\n * InstallProvider uses res.setHeader() for Location, Set-Cookie, Content-Type\n * and res.getHeader() to read back Set-Cookie before appending.\n */\nexport function createResponseCapture(): ResponseCapture {\n let statusCode = 200;\n const capturedHeaders: Record<string, string | string[]> = {};\n const chunks: Buffer[] = [];\n\n // Dummy socket/message pair — never connected, just satisfies the constructor.\n const res = new ServerResponse(new IncomingMessage(new Socket()));\n\n const originalSetHeader = res.setHeader.bind(res);\n res.setHeader = (\n name: string,\n value: string | number | readonly string[],\n ) => {\n const key = name.toLowerCase();\n if (Array.isArray(value)) {\n capturedHeaders[key] = [...value];\n } else {\n capturedHeaders[key] = String(value);\n }\n return originalSetHeader(name, value);\n };\n\n const originalGetHeader = res.getHeader.bind(res);\n res.getHeader = (name: string): string | number | string[] | undefined => {\n const val = capturedHeaders[name.toLowerCase()];\n if (val !== undefined) return val;\n return originalGetHeader(name);\n };\n\n const originalWriteHead = res.writeHead.bind(res);\n // writeHead has four overloads: (code), (code, message), (code, headers),\n // and (code, message, headers). We sniff for the first non-array object arg\n // to find the headers object in all cases.\n // oxlint-disable-next-line typescript/no-explicit-any -- writeHead has many overloads\n res.writeHead = (code: number, ...args: any[]) => {\n statusCode = code;\n const headersArg = args.find(\n (a) => a !== undefined && typeof a === \"object\" && !Array.isArray(a),\n ) as Record<string, string | string[]> | undefined;\n if (headersArg) {\n for (const [key, value] of Object.entries(headersArg)) {\n const lower = key.toLowerCase();\n capturedHeaders[lower] = value;\n }\n }\n return originalWriteHead(code, ...args);\n };\n\n const originalEnd = res.end.bind(res);\n // oxlint-disable-next-line typescript/no-explicit-any -- end has many overloads\n res.end = (chunk?: any, ...args: any[]) => {\n if (chunk !== undefined && chunk !== null) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return originalEnd(chunk, ...args);\n };\n\n (res as ResponseCapture).toResponse = () => {\n const body = chunks.length > 0 ? Buffer.concat(chunks).toString() : null;\n const webHeaders = new Headers();\n for (const [key, value] of Object.entries(capturedHeaders)) {\n if (Array.isArray(value)) {\n for (const v of value) webHeaders.append(key, v);\n } else {\n webHeaders.set(key, value);\n }\n }\n return new Response(body, { status: statusCode, headers: webHeaders });\n };\n\n return res as ResponseCapture;\n}\n","import {\n type AckFn,\n type App,\n type HTTPReceiverOptions,\n type Receiver,\n ReceiverAuthenticityError,\n type ReceiverEvent,\n ReceiverMultipleAckError,\n type StringIndexed,\n verifySlackRequest,\n} from \"@slack/bolt\";\nimport { ConsoleLogger, type Logger, LogLevel } from \"@slack/logger\";\nimport {\n type CallbackOptions,\n type InstallPathOptions,\n InstallProvider,\n type InstallProviderOptions,\n type InstallURLOptions,\n type StateStore,\n} from \"@slack/oauth\";\nimport { waitUntil } from \"@vercel/functions\";\nimport {\n ERROR_MESSAGES,\n getErrorMessage,\n getErrorType,\n getStatusCode,\n RequestParsingError,\n VercelReceiverError,\n} from \"./errors\";\nimport { createResponseCapture, toIncomingMessage } from \"./oauth-adapters\";\n\n// Types\n/**\n * A function to handle the request from the Slack app.\n * @param req - The request from the Slack app.\n * @returns A response object.\n */\nexport type VercelHandler = (req: Request) => Promise<Response>;\n\n/**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing, or undefined to continue.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: This hook is NOT called for `url_verification` challenge requests, which are\n * handled automatically before `beforeProcess` is invoked.\n *\n * @param req - A new Request with the raw body (the original request body was consumed during parsing)\n * @param body - The parsed request body\n * @returns A Response to short-circuit processing, or undefined to continue to Bolt\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver({\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * beforeProcess: async (req, body) => {\n * // Forward certain workspaces to a different service\n * if (body.team_id === 'T_ENTERPRISE') {\n * return fetch('https://enterprise-handler.example.com/slack', {\n * method: 'POST',\n * body: await req.text(),\n * headers: req.headers,\n * });\n * }\n * // Return undefined to continue normal Bolt processing\n * },\n * });\n * ```\n */\nexport type BeforeProcessFn = (\n req: Request,\n body: StringIndexed,\n) => Promise<Response | undefined> | Response | undefined;\n\n/**\n * A function that resolves scopes dynamically based on the request.\n * Useful for requesting different scopes based on team or user context.\n * @param req - The original request\n * @returns The scopes to request\n */\nexport type ScopesResolver = (req: Request) => Promise<string[]> | string[];\n\n/**\n * Configuration options for the VercelReceiver.\n * @property signingSecret - The signing secret for the Slack app.\n * @property signatureVerification - If true, verifies the Slack request signature.\n * @property logger - The logger to use for the VercelReceiver.\n * @property logLevel - The log level to use for the VercelReceiver.\n * @property customPropertiesExtractor - A function to extract custom properties from the request.\n */\n/**\n * Options for customizing the OAuth installer behavior.\n * Mirrors the relevant subset of HTTPReceiverInstallerOptions,\n * excluding path-related options (serverless uses file-based routing).\n */\nexport interface VercelInstallerOptions {\n directInstall?: boolean;\n renderHtmlForInstallPath?: (url: string) => string;\n stateStore?: StateStore;\n stateVerification?: boolean;\n legacyStateVerification?: boolean;\n stateCookieName?: string;\n stateCookieExpirationSeconds?: number;\n authVersion?: \"v1\" | \"v2\";\n clientOptions?: InstallProviderOptions[\"clientOptions\"];\n authorizationUrl?: string;\n metadata?: string;\n userScopes?: string[];\n installPathOptions?: InstallPathOptions;\n callbackOptions?: CallbackOptions;\n}\n\n/**\n * Configuration options for the VercelReceiver.\n */\nexport interface VercelReceiverOptions {\n /**\n * The signing secret for the Slack app.\n * @default process.env.SLACK_SIGNING_SECRET\n */\n signingSecret?: string;\n /**\n * If true, verifies the Slack request signature.\n * @default true\n */\n signatureVerification?: boolean;\n /**\n * The logger to use for the VercelReceiver.\n * @default new ConsoleLogger()\n */\n logger?: Logger;\n /**\n * The log level to use for the VercelReceiver.\n * @default LogLevel.INFO\n */\n logLevel?: LogLevel;\n /**\n * A function to extract custom properties from incoming events.\n * Called after body parsing, so the parsed body is available.\n * @default undefined\n * @returns An object with custom properties.\n */\n customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n /**\n * A function that can intercept requests before they are processed by Bolt.\n * Return a Response to short-circuit processing (e.g., to forward to an external service),\n * or undefined to continue normal Bolt processing.\n *\n * Called after signature verification and body parsing, but before Bolt event handling.\n * Note: Not called for `url_verification` challenge requests.\n * @default undefined\n */\n beforeProcess?: BeforeProcessFn;\n /**\n * The timeout in milliseconds for event acknowledgment.\n * @default 3001\n */\n ackTimeoutMs?: number;\n /**\n * Your app's client ID, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_ID\n */\n clientId?: string;\n /**\n * Your app's client secret, found under Basic Information on api.slack.com.\n * Required for OAuth.\n * @default process.env.SLACK_CLIENT_SECRET\n */\n clientSecret?: string;\n /**\n * Secret used to generate and verify the state parameter for OAuth CSRF protection.\n * Required unless a custom stateStore or stateVerification: false is provided.\n * @default process.env.SLACK_STATE_SECRET\n */\n stateSecret?: string;\n /**\n * The bot scopes to request during the OAuth flow.\n * Can be a static array or a function that resolves scopes dynamically\n * based on the request (e.g., to request different scopes for different teams).\n */\n scopes?: string[] | ScopesResolver;\n /**\n * The redirect URI registered with your Slack app for OAuth callbacks.\n */\n redirectUri?: string;\n /**\n * Storage backend for OAuth installations (tokens, team info, etc.).\n * Required for OAuth in serverless -- the default in-memory store does not persist.\n */\n installationStore?: InstallProviderOptions[\"installationStore\"];\n /**\n * Advanced options for the OAuth installer.\n */\n installerOptions?: VercelInstallerOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Compile-time shape assertions\n// Verify our types match Bolt's underlying shapes without coupling optionality.\n// If Bolt changes a type upstream, tsc breaks here -- not in user-land at runtime.\n// ---------------------------------------------------------------------------\ntype AssertShape<Source, Target> =\n NonNullable<Source> extends NonNullable<Target> ? true : never;\n\ntype _S1 = AssertShape<\n VercelReceiverOptions[\"clientId\"],\n HTTPReceiverOptions[\"clientId\"]\n>;\ntype _S2 = AssertShape<\n VercelReceiverOptions[\"clientSecret\"],\n HTTPReceiverOptions[\"clientSecret\"]\n>;\ntype _S3 = AssertShape<\n VercelReceiverOptions[\"stateSecret\"],\n HTTPReceiverOptions[\"stateSecret\"]\n>;\ntype _S4 = AssertShape<\n VercelReceiverOptions[\"scopes\"],\n HTTPReceiverOptions[\"scopes\"]\n>;\ntype _S5 = AssertShape<\n VercelReceiverOptions[\"redirectUri\"],\n HTTPReceiverOptions[\"redirectUri\"]\n>;\ntype _S6 = AssertShape<\n VercelReceiverOptions[\"installationStore\"],\n HTTPReceiverOptions[\"installationStore\"]\n>;\ntype _S7 = AssertShape<\n VercelInstallerOptions[\"stateVerification\"],\n InstallProviderOptions[\"stateVerification\"]\n>;\ntype _S8 = AssertShape<\n VercelInstallerOptions[\"callbackOptions\"],\n CallbackOptions\n>;\ntype _S9 = AssertShape<\n VercelInstallerOptions[\"stateStore\"],\n InstallProviderOptions[\"stateStore\"]\n>;\ntype _S10 = AssertShape<\n VercelInstallerOptions[\"authVersion\"],\n InstallProviderOptions[\"authVersion\"]\n>;\ntype _S11 = AssertShape<\n VercelInstallerOptions[\"userScopes\"],\n InstallURLOptions[\"userScopes\"]\n>;\ntype _S12 = AssertShape<\n VercelInstallerOptions[\"metadata\"],\n InstallURLOptions[\"metadata\"]\n>;\n\nconst LOG_PREFIX = \"[@vercel/slack-bolt]\";\nconst ACK_TIMEOUT_MS = 3001;\nconst SLACK_RETRY_NUM_HEADER = \"x-slack-retry-num\";\nconst SLACK_RETRY_REASON_HEADER = \"x-slack-retry-reason\";\nconst SLACK_TIMESTAMP_HEADER = \"x-slack-request-timestamp\";\nconst SLACK_SIGNATURE_HEADER = \"x-slack-signature\";\n\n/**\n * A Slack Bolt receiver implementation designed for Vercel's serverless environment.\n * Handles Slack events, interactions, and slash commands with automatic request verification,\n * background processing, and timeout management.\n *\n * @example\n * ```typescript\n * import { App } from '@slack/bolt';\n * import { VercelReceiver, createHandler } from '@vercel/slack-bolt';\n *\n * const receiver = new VercelReceiver();\n *\n * const app = new App({\n * receiver,\n * token: process.env.SLACK_BOT_TOKEN,\n * signingSecret: process.env.SLACK_SIGNING_SECRET,\n * });\n * ```\n *\n */\nexport class VercelReceiver implements Receiver {\n private readonly signingSecret: string;\n private readonly signatureVerification: boolean;\n private readonly logger: Logger;\n private readonly customPropertiesExtractor?: (\n req: Request,\n body: StringIndexed,\n ) => StringIndexed;\n private readonly beforeProcess?: BeforeProcessFn;\n private readonly ackTimeoutMs: number;\n private app?: App;\n\n public installer?: InstallProvider;\n private installUrlOptions?: InstallURLOptions;\n private scopesResolver?: ScopesResolver;\n private installCallbackOptions?: CallbackOptions;\n private installPathOptions?: InstallPathOptions;\n private stateVerification?: boolean;\n\n /**\n * Gets the logger instance used by this receiver.\n * @returns The logger instance\n */\n public getLogger(): Logger {\n return this.logger;\n }\n\n /**\n * Creates a new VercelReceiver instance.\n *\n * @param options - Configuration options for the receiver\n * @throws {VercelReceiverError} When signing secret is not provided\n *\n * @example\n * ```typescript\n * const receiver = new VercelReceiver();\n * ```\n */\n public constructor({\n signingSecret = process.env.SLACK_SIGNING_SECRET,\n signatureVerification = true,\n logger,\n logLevel = LogLevel.INFO,\n customPropertiesExtractor,\n beforeProcess,\n ackTimeoutMs = ACK_TIMEOUT_MS,\n clientId = process.env.SLACK_CLIENT_ID,\n clientSecret = process.env.SLACK_CLIENT_SECRET,\n stateSecret = process.env.SLACK_STATE_SECRET,\n scopes,\n redirectUri,\n installationStore,\n installerOptions = {},\n }: VercelReceiverOptions = {}) {\n if (!signingSecret) {\n throw new VercelReceiverError(ERROR_MESSAGES.SIGNING_SECRET_REQUIRED);\n }\n\n this.signingSecret = signingSecret;\n this.signatureVerification = signatureVerification;\n this.logger = this.createScopedLogger(\n logger ?? new ConsoleLogger(),\n logLevel,\n );\n this.customPropertiesExtractor = customPropertiesExtractor;\n this.beforeProcess = beforeProcess;\n this.ackTimeoutMs = ackTimeoutMs;\n\n this.stateVerification = installerOptions.stateVerification;\n\n if (\n clientId !== undefined &&\n clientSecret !== undefined &&\n (installerOptions.stateVerification === false ||\n stateSecret !== undefined ||\n installerOptions.stateStore !== undefined)\n ) {\n this.installer = new InstallProvider({\n clientId,\n clientSecret,\n stateSecret,\n installationStore,\n logger,\n logLevel,\n directInstall: installerOptions.directInstall,\n stateStore: installerOptions.stateStore,\n stateVerification: installerOptions.stateVerification,\n legacyStateVerification: installerOptions.legacyStateVerification,\n stateCookieName: installerOptions.stateCookieName,\n stateCookieExpirationSeconds:\n installerOptions.stateCookieExpirationSeconds,\n renderHtmlForInstallPath: installerOptions.renderHtmlForInstallPath,\n authVersion: installerOptions.authVersion ?? \"v2\",\n clientOptions: installerOptions.clientOptions,\n authorizationUrl: installerOptions.authorizationUrl,\n });\n\n // If scopes is a function, store it separately for dynamic resolution\n if (typeof scopes === \"function\") {\n this.scopesResolver = scopes;\n this.installUrlOptions = {\n scopes: [], // Will be resolved dynamically in handleInstall\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n } else {\n this.installUrlOptions = {\n scopes: scopes ?? [],\n userScopes: installerOptions.userScopes,\n metadata: installerOptions.metadata,\n redirectUri,\n };\n }\n this.installCallbackOptions = installerOptions.callbackOptions ?? {};\n this.installPathOptions = installerOptions.installPathOptions ?? {};\n }\n\n this.logger.debug(\"VercelReceiver initialized\");\n }\n\n /**\n * Initializes the receiver with a Slack Bolt app instance.\n * This method is called automatically by the Bolt framework.\n *\n * @param app - The Slack Bolt app instance\n */\n public init(app: App): void {\n this.app = app;\n this.logger.debug(\"App initialized in VercelReceiver\");\n }\n\n /**\n * Starts the receiver and returns a handler function for processing requests.\n * This method is called automatically by the Bolt framework.\n *\n * @returns A handler function that processes incoming Slack requests\n */\n public async start(): Promise<VercelHandler> {\n this.logger.debug(\"VercelReceiver started\");\n return this.toHandler();\n }\n\n /**\n * Stops the receiver. This method is called automatically by the Bolt framework.\n */\n public async stop(): Promise<void> {\n this.logger.debug(\"VercelReceiver stopped\");\n }\n\n /**\n * Handles requests to the OAuth install path.\n * Renders an \"Add to Slack\" page or redirects directly to Slack's authorize URL.\n */\n public handleInstall = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n // Resolve scopes dynamically if a resolver function was provided\n let installUrlOptions = this.installUrlOptions;\n if (this.scopesResolver && installUrlOptions) {\n const resolvedScopes = await this.scopesResolver(req);\n installUrlOptions = {\n ...installUrlOptions,\n scopes: resolvedScopes,\n };\n }\n\n await this.installer.handleInstallPath(\n nodeReq,\n capture,\n this.installPathOptions,\n installUrlOptions,\n );\n\n return capture.toResponse();\n };\n\n /**\n * Handles the OAuth redirect callback from Slack.\n * Exchanges the authorization code for tokens and stores the installation.\n */\n public handleCallback = async (req: Request): Promise<Response> => {\n if (!this.installer) {\n throw new VercelReceiverError(ERROR_MESSAGES.OAUTH_NOT_CONFIGURED);\n }\n\n const nodeReq = toIncomingMessage(req);\n const capture = createResponseCapture();\n\n if (this.stateVerification === false) {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n this.installUrlOptions,\n );\n } else {\n await this.installer.handleCallback(\n nodeReq,\n capture,\n this.installCallbackOptions,\n );\n }\n\n return capture.toResponse();\n };\n\n /**\n * Creates a handler function that processes incoming Slack requests.\n * This is the main entry point for handling Slack events in Vercel.\n * It is called automatically by the Bolt framework in the start() method.\n *\n * @returns A handler function compatible with Vercel's function signature\n */\n public toHandler(): VercelHandler {\n return async (req: Request): Promise<Response> => {\n try {\n const rawBody = await req.text();\n\n if (this.signatureVerification) {\n this.verifyRequest(req, rawBody);\n }\n\n const body = await this.parseRequestBody(req, rawBody);\n\n if (body.type === \"url_verification\") {\n this.logger.debug(\"Handling URL verification challenge\");\n return Response.json({ challenge: body.challenge });\n }\n\n // Allow beforeProcess to intercept and short-circuit processing.\n // We pass a new Request with the raw body since req.text() was already consumed.\n if (this.beforeProcess) {\n const reqWithBody = new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: rawBody,\n });\n const interceptResponse = await this.beforeProcess(reqWithBody, body);\n if (interceptResponse) {\n this.logger.debug(\"Request intercepted by beforeProcess\");\n return interceptResponse;\n }\n }\n\n return await this.handleSlackEvent(req, body);\n } catch (error) {\n return this.handleError(error);\n }\n };\n }\n\n private async parseRequestBody(\n req: Request,\n rawBody: string,\n ): Promise<StringIndexed> {\n const contentType = req.headers.get(\"content-type\");\n\n try {\n if (contentType === \"application/x-www-form-urlencoded\") {\n const parsedBody: StringIndexed = {};\n const params = new URLSearchParams(rawBody);\n\n for (const [key, value] of params.entries()) {\n parsedBody[key] = value;\n }\n\n if (typeof parsedBody.payload === \"string\") {\n return JSON.parse(parsedBody.payload);\n }\n return parsedBody;\n }\n if (contentType === \"application/json\") {\n return JSON.parse(rawBody);\n }\n\n this.logger.warn(`Unexpected content-type detected: ${contentType}`);\n\n return JSON.parse(rawBody);\n } catch (e) {\n throw new RequestParsingError(\n `Failed to parse body as JSON data for content-type: ${contentType}. Error: ${\n e instanceof Error ? e.message : String(e)\n }`,\n );\n }\n }\n\n private async handleSlackEvent(\n req: Request,\n body: StringIndexed,\n ): Promise<Response> {\n if (!this.app) {\n throw new VercelReceiverError(ERROR_MESSAGES.APP_NOT_INITIALIZED, 500);\n }\n\n let isAcknowledged = false;\n let responseResolver: (value: Response) => void;\n let responseRejecter: (error: Error) => void;\n\n const responsePromise = new Promise<Response>((resolve, reject) => {\n responseResolver = resolve;\n responseRejecter = reject;\n });\n\n // Slack requires an acknowledgment from your app within 3 seconds\n const timeoutId = setTimeout(() => {\n if (!isAcknowledged) {\n isAcknowledged = true;\n this.logger.error(ERROR_MESSAGES.EVENT_NOT_ACKNOWLEDGED);\n const error = new VercelReceiverError(\n ERROR_MESSAGES.REQUEST_TIMEOUT,\n 408,\n );\n responseRejecter(error);\n }\n }, this.ackTimeoutMs);\n\n // Create acknowledgment function\n const ackFn: AckFn<StringIndexed> = async (responseBody) => {\n this.logger.debug(`ack() call begins (body: ${responseBody})`);\n if (isAcknowledged) {\n throw new ReceiverMultipleAckError();\n }\n\n isAcknowledged = true;\n clearTimeout(timeoutId);\n\n try {\n let body: string | undefined;\n if (typeof responseBody === \"undefined\") {\n body = undefined;\n } else if (typeof responseBody === \"string\") {\n body = responseBody;\n } else {\n body = JSON.stringify(responseBody);\n }\n const response = new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n responseResolver(response);\n } catch (error) {\n this.logger.error(ERROR_MESSAGES.ACKNOWLEDGMENT_ERROR, error);\n responseRejecter(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n };\n\n const event = this.createSlackReceiverEvent({\n body,\n headers: req.headers,\n ack: ackFn,\n request: req,\n });\n\n // Process event in background using waitUntil from Vercel Functions\n // https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil\n waitUntil(\n this.app.processEvent(event).catch((error) => {\n return this.handleError(error);\n }),\n );\n\n try {\n return await responsePromise;\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n private verifyRequest(req: Request, body: string): void {\n const timestamp = req.headers.get(SLACK_TIMESTAMP_HEADER);\n const signature = req.headers.get(SLACK_SIGNATURE_HEADER);\n\n if (!signature) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_SIGNATURE_HEADER),\n );\n }\n\n if (!timestamp) {\n throw new ReceiverAuthenticityError(\n ERROR_MESSAGES.MISSING_REQUIRED_HEADER(SLACK_TIMESTAMP_HEADER),\n );\n }\n\n try {\n verifySlackRequest({\n signingSecret: this.signingSecret,\n body,\n headers: {\n \"x-slack-signature\": signature,\n \"x-slack-request-timestamp\": Number.parseInt(timestamp, 10),\n },\n logger: this.logger,\n });\n } catch (error) {\n throw new ReceiverAuthenticityError(\n error instanceof Error\n ? error.message\n : \"Failed to verify request signature\",\n );\n }\n }\n\n private createSlackReceiverEvent({\n body,\n headers,\n ack,\n request,\n }: {\n body: StringIndexed;\n headers: Headers;\n ack: AckFn<StringIndexed>;\n request: Request;\n }): ReceiverEvent {\n const customProperties = this.customPropertiesExtractor\n ? this.customPropertiesExtractor(request, body)\n : {};\n\n const retryNum = headers.get(SLACK_RETRY_NUM_HEADER) || \"0\";\n\n const retryReason = headers.get(SLACK_RETRY_REASON_HEADER) || \"\";\n\n return {\n body,\n ack,\n retryNum: Number(retryNum),\n retryReason,\n customProperties,\n };\n }\n\n public handleError(error: unknown): Response {\n const errorMessage = getErrorMessage(error);\n const errorType = getErrorType(error);\n const errorStatusCode = getStatusCode(error);\n\n this.logger.error(error);\n return new Response(\n JSON.stringify({\n error: errorMessage,\n type: errorType,\n }),\n {\n status: errorStatusCode,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n }\n\n private createScopedLogger(logger: Logger, logLevel: LogLevel): Logger {\n logger.setLevel(logLevel);\n\n return {\n ...logger,\n error: (...args) => logger.error?.(LOG_PREFIX, ...args),\n warn: (...args) => logger.warn?.(LOG_PREFIX, ...args),\n info: (...args) => logger.info?.(LOG_PREFIX, ...args),\n debug: (...args) => logger.debug?.(LOG_PREFIX, ...args),\n setLevel: logger.setLevel,\n getLevel: logger.getLevel,\n };\n }\n}\n\n/**\n * Creates a Vercel-compatible handler function for a Slack Bolt app.\n * This is the recommended way to create handlers for deployment on Vercel.\n *\n * @param {App} app - The initialized Slack Bolt app instance.\n * @param {VercelReceiver} receiver - The VercelReceiver instance.\n * @returns {VercelHandler} A handler function compatible with Vercel's function signature.\n *\n * @example\n * ```typescript\n * // api/events.ts\n * import { createHandler } from '@vercel/slack-bolt';\n * import { app, receiver } from '../app';\n *\n * const handler = createHandler(app, receiver);\n *\n * export const POST = async (req: Request) => {\n * return handler(req);\n * };\n * ```\n *\n * @throws {Error} If app initialization fails.\n * @throws {VercelReceiverError} If request processing fails.\n */\nexport function createHandler(\n app: App,\n receiver: VercelReceiver,\n): VercelHandler {\n let initPromise: Promise<void> | null = null;\n\n return async (req: Request) => {\n try {\n if (!initPromise) {\n initPromise = app.init().catch((error) => {\n // Reset initPromise so subsequent requests can retry initialization\n initPromise = null;\n throw error;\n });\n }\n await initPromise;\n\n receiver.init(app);\n const handler = await receiver.start();\n return handler(req);\n } catch (error) {\n // if app.init fails, we use console.error instead of logger.error because the logger is not available\n console.error(ERROR_MESSAGES.CREATE_HANDLER_ERROR, error);\n return new Response(\n JSON.stringify({\n error: ERROR_MESSAGES.INTERNAL_SERVER_ERROR_HANDLER,\n type: ERROR_MESSAGES.TYPES.HANDLER_ERROR,\n }),\n { status: 500, headers: { \"content-type\": \"application/json\" } },\n );\n }\n };\n}\n"],"mappings":";;;;;;;AACA,MAAa,iBAAiB;CAE5B,yBACE;CACF,qBAAqB;CACrB,sBACE;CACF,iBAAiB;CACjB,wBAAwB;CAGxB,0BAA0B,WACxB,4BAA4B;CAG9B,6BAA6B;CAC7B,uBAAuB;CACvB,+BAA+B;CAC/B,sBAAsB;CACtB,sBAAsB;CAGtB,OAAO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S,KAAK,GAAG;GAEjB,QAAO,MADe,SAAS,MAAM,EAAA,CACtB,GAAG;EACpB,SAAS,OAAO;GAEd,QAAQ,MAAM,eAAe,sBAAsB,KAAK;GACxD,OAAO,IAAI,SACT,KAAK,UAAU;IACb,OAAO,eAAe;IACtB,MAAM,eAAe,MAAM;GAC7B,CAAC,GACD;IAAE,QAAQ;IAAK,SAAS,EAAE,gBAAgB,mBAAmB;GAAE,CACjE;EACF;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// \0rolldown/runtime.js
|
|
2
2
|
var __create = Object.create;
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -20,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
|
-
//#endregion
|
|
24
23
|
let node_fs = require("node:fs");
|
|
25
24
|
node_fs = __toESM(node_fs);
|
|
26
25
|
let node_path = require("node:path");
|
|
@@ -28,7 +27,7 @@ node_path = __toESM(node_path);
|
|
|
28
27
|
let yaml = require("yaml");
|
|
29
28
|
let node_crypto = require("node:crypto");
|
|
30
29
|
node_crypto = __toESM(node_crypto);
|
|
31
|
-
|
|
30
|
+
// src/internal/manifest/index.ts
|
|
32
31
|
function rewriteUrl(originalUrl, branchUrl, bypassSecret) {
|
|
33
32
|
const pathStart = originalUrl.indexOf("/", originalUrl.indexOf("//") + 2);
|
|
34
33
|
const pathAndQuery = pathStart !== -1 ? originalUrl.slice(pathStart) : "/";
|
|
@@ -84,8 +83,7 @@ function createNewManifest(params) {
|
|
|
84
83
|
if (manifest.features?.bot_user) manifest.features.bot_user.display_name = displayName;
|
|
85
84
|
return manifest;
|
|
86
85
|
}
|
|
87
|
-
|
|
88
|
-
//#region src/internal/manifest/parse.ts
|
|
86
|
+
// src/internal/manifest/parse.ts
|
|
89
87
|
function isYaml(filePath) {
|
|
90
88
|
const ext = node_path.default.extname(filePath).toLowerCase();
|
|
91
89
|
return ext === ".yaml" || ext === ".yml";
|
|
@@ -98,8 +96,7 @@ function stringifyManifest(manifest, filePath) {
|
|
|
98
96
|
if (isYaml(filePath)) return (0, yaml.stringify)(manifest);
|
|
99
97
|
return JSON.stringify(manifest, null, 2);
|
|
100
98
|
}
|
|
101
|
-
|
|
102
|
-
//#region src/internal/vercel/errors.ts
|
|
99
|
+
// src/internal/vercel/errors.ts
|
|
103
100
|
var HTTPError = class HTTPError extends Error {
|
|
104
101
|
status;
|
|
105
102
|
statusText;
|
|
@@ -141,8 +138,7 @@ var HTTPError = class HTTPError extends Error {
|
|
|
141
138
|
return error;
|
|
142
139
|
}
|
|
143
140
|
};
|
|
144
|
-
|
|
145
|
-
//#region src/internal/slack/errors.ts
|
|
141
|
+
// src/internal/slack/errors.ts
|
|
146
142
|
var SlackManifestCreateError = class extends Error {
|
|
147
143
|
errors;
|
|
148
144
|
constructor(message, errors) {
|
|
@@ -158,8 +154,7 @@ var SlackManifestUpdateError = class extends Error {
|
|
|
158
154
|
}
|
|
159
155
|
};
|
|
160
156
|
var SlackManifestExportError = class extends Error {};
|
|
161
|
-
|
|
162
|
-
//#region src/internal/slack/index.ts
|
|
157
|
+
// src/internal/slack/index.ts
|
|
163
158
|
async function createSlackApp({ token, manifest }) {
|
|
164
159
|
const response = await fetch("https://slack.com/api/apps.manifest.create", {
|
|
165
160
|
method: "POST",
|
|
@@ -325,8 +320,7 @@ async function installApp(params) {
|
|
|
325
320
|
userToken: data.api_access_tokens?.user
|
|
326
321
|
};
|
|
327
322
|
}
|
|
328
|
-
|
|
329
|
-
//#region src/internal/vercel/index.ts
|
|
323
|
+
// src/internal/vercel/index.ts
|
|
330
324
|
async function getProject({ projectId, token, teamId }) {
|
|
331
325
|
const url = new URL(`https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}`);
|
|
332
326
|
if (teamId) url.searchParams.set("teamId", teamId);
|
|
@@ -455,8 +449,7 @@ async function deleteEnvironmentVariable({ projectId, envId, token, teamId }) {
|
|
|
455
449
|
});
|
|
456
450
|
if (!response.ok) throw await HTTPError.fromResponse("Failed to delete environment variable", response);
|
|
457
451
|
}
|
|
458
|
-
|
|
459
|
-
//#region src/logger.ts
|
|
452
|
+
// src/logger.ts
|
|
460
453
|
function isDebug() {
|
|
461
454
|
return process.env.VERCEL_SLACK_DEBUG === "1" || process.env.VERCEL_SLACK_DEBUG === "true";
|
|
462
455
|
}
|
|
@@ -572,8 +565,7 @@ const startMessage = (version, branch, commit, appId) => {
|
|
|
572
565
|
if (appId) lines.push(` - App ID: ${appId}`);
|
|
573
566
|
return `${BOLD}${lines.join("\n")}${RESET}\n`;
|
|
574
567
|
};
|
|
575
|
-
|
|
576
|
-
//#region src/preview.ts
|
|
568
|
+
// src/preview.ts
|
|
577
569
|
const preview = async (params, context) => {
|
|
578
570
|
const { branch, projectId, deploymentUrl, teamId, commitAuthor, commitMessage: commitMsg, commitSha, slackAppId, slackConfigurationToken, slackServiceToken, manifestPath, vercelApiToken } = params;
|
|
579
571
|
const cli = context === "cli";
|
|
@@ -729,7 +721,6 @@ https://docs.slack.dev/authentication/tokens/#service`);
|
|
|
729
721
|
app
|
|
730
722
|
};
|
|
731
723
|
};
|
|
732
|
-
//#endregion
|
|
733
724
|
Object.defineProperty(exports, "__commonJSMin", {
|
|
734
725
|
enumerable: true,
|
|
735
726
|
get: function() {
|
|
@@ -833,4 +824,4 @@ Object.defineProperty(exports, "startMessage", {
|
|
|
833
824
|
}
|
|
834
825
|
});
|
|
835
826
|
|
|
836
|
-
//# sourceMappingURL=preview-
|
|
827
|
+
//# sourceMappingURL=preview-BDw2rRw6.js.map
|