prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState();
const authorizeUrl = generateAuthorizeUrl(stateValue, this.env);
return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " await this.socketModeClient.connect();\n }\n async disconnect(): Promise<void> {\n if (this.socketModeClient) {\n await this.socketModeClient.disconnect();\n }\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext", "score": 67.79161036251503 }, { "filename": "src/oauth/callback.ts", "retrieved_chunk": "export type OnStateValidationError = (\n startPath: string,\n req: Request\n) => Promise<Response>;\n// deno-lint-ignore require-await\nexport const defaultOnStateValidationError = async (\n startPath: string,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {", "score": 53.15916518065971 }, { "filename": "src/app.ts", "retrieved_chunk": " ): Promise<Response> {\n return await this.handleEventRequest(request, ctx);\n }\n async connect(): Promise<void> {\n if (!this.socketMode) {\n throw new ConfigError(\n \"Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!\"\n );\n }\n this.socketModeClient = new SocketModeClient(this);", "score": 50.275753781667525 }, { "filename": "src/app.ts", "retrieved_chunk": " ) {\n return handler;\n }\n return null;\n });\n return this;\n }\n async run(\n request: Request,\n ctx: ExecutionContext = new NoopExecutionContext()", "score": 47.8846203550341 }, { "filename": "src/oauth/state-store.ts", "retrieved_chunk": "export interface StateStore {\n issueNewState(): Promise<string>;\n consume(state: string): Promise<boolean>;\n}\nexport class NoStorageStateStore implements StateStore {\n // deno-lint-ignore require-await\n async issueNewState(): Promise<string> {\n return crypto.randomUUID();\n }\n // deno-lint-ignore require-await no-unused-vars", "score": 43.26435547087296 } ]
typescript
const authorizeUrl = generateAuthorizeUrl(stateValue, this.env);
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public
postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents];
#slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " public appLevelToken: string;\n public ws: WebSocket | undefined;\n constructor(\n // deno-lint-ignore no-explicit-any\n app: SlackApp<any>\n ) {\n if (!app.socketMode) {\n throw new ConfigError(\n \"socketMode: true must be set for running with Socket Mode\"\n );", "score": 75.96362592884009 }, { "filename": "src/request/payload/block-action.ts", "retrieved_chunk": " // deno-lint-ignore no-explicit-any\n container: any;\n // deno-lint-ignore no-explicit-any\n app_unfurl?: any;\n is_enterprise_install?: boolean;\n enterprise?: {\n id: string;\n name: string;\n };\n}", "score": 56.20407967460384 }, { "filename": "src/context/context.ts", "retrieved_chunk": " }\n }\n }\n }\n return extractTeamId(body);\n}\nexport function extractActorUserId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {", "score": 49.709162766876176 }, { "filename": "src/context/context.ts", "retrieved_chunk": " }\n }\n }\n return extractUserId(body);\n}\nexport function extractResponseUrl(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.response_url) {", "score": 47.093542794622465 }, { "filename": "src/request/payload/block-suggestion.ts", "retrieved_chunk": " name: string;\n team_id?: string;\n };\n token: string;\n // deno-lint-ignore no-explicit-any\n container: any;\n view?: DataSubmissionView;\n is_enterprise_install?: boolean;\n enterprise?: {\n id: string;", "score": 44.18056489040945 } ]
typescript
postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents];
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody )
=> SlackHandler<E, SlackEvent<string>> | null)[] = [];
#globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/request.ts", "retrieved_chunk": " context: PreAuthorizeSlackAppContext;\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>;\n retryNum?: number;\n retryReason?: string;\n rawBody: string;\n headers: Headers;\n}\nexport type PreAuthorizeSlackMiddlwareRequest<E extends SlackAppEnv> =\n SlackMiddlewareRequestBase<E> & {", "score": 31.655729626342772 }, { "filename": "src/context/context.ts", "retrieved_chunk": " }\n }\n }\n }\n return extractTeamId(body);\n}\nexport function extractActorUserId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {", "score": 29.892337451914493 }, { "filename": "src/context/context.ts", "retrieved_chunk": "}\nexport function extractActorEnterpriseId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n const eventTeamId = body.event?.user_team || body.event?.team;\n if (eventTeamId && eventTeamId.startsWith(\"E\")) {\n return eventTeamId;", "score": 29.45162231769946 }, { "filename": "src/context/context.ts", "retrieved_chunk": " }\n }\n }\n return extractUserId(body);\n}\nexport function extractResponseUrl(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.response_url) {", "score": 29.418770742809166 }, { "filename": "src/context/context.ts", "retrieved_chunk": " } else if (eventTeamId === body.team_id) {\n return body.enterprise_id;\n }\n }\n }\n return extractEnterpriseId(body);\n}\nexport function extractActorTeamId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>", "score": 28.240489709165697 } ]
typescript
=> SlackHandler<E, SlackEvent<string>> | null)[] = [];
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore =
options.stateStore ?? new NoStorageStateStore();
this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " if (!this.env.SLACK_SIGNING_SECRET) {\n throw new ConfigError(\n \"env.SLACK_SIGNING_SECRET is required to run your app on edge functions!\"\n );\n }\n this.signingSecret = this.env.SLACK_SIGNING_SECRET;\n }\n this.authorize = options.authorize ?? singleTeamAuthorize;\n this.routes = { events: options.routes?.events };\n }", "score": 87.32410127050582 }, { "filename": "src/app.ts", "retrieved_chunk": " }\n this.env = options.env;\n this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, {\n logLevel: this.env.SLACK_LOGGING_LEVEL,\n });\n this.appLevelToken = options.env.SLACK_APP_TOKEN;\n this.socketMode = options.socketMode ?? this.appLevelToken !== undefined;\n if (this.socketMode) {\n this.signingSecret = \"\";\n } else {", "score": 72.9847767403841 }, { "filename": "src/app.ts", "retrieved_chunk": " ) => SlackViewHandler<E, ViewClosed> | null)[] = [];\n constructor(options: SlackAppOptions<E>) {\n if (\n options.env.SLACK_BOT_TOKEN === undefined &&\n (options.authorize === undefined ||\n options.authorize === singleTeamAuthorize)\n ) {\n throw new ConfigError(\n \"When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead.\"\n );", "score": 60.659966274505834 }, { "filename": "src/app.ts", "retrieved_chunk": "export interface SlackAppOptions<\n E extends SlackEdgeAppEnv | SlackSocketModeAppEnv\n> {\n env: E;\n authorize?: Authorize<E>;\n routes?: {\n events: string;\n };\n socketMode?: boolean;\n}", "score": 40.83730715092442 }, { "filename": "src/response/response-body.ts", "retrieved_chunk": " label: AnyTextField;\n options: Option[];\n}\nexport interface OptionsResponse {\n options: Option[];\n}\nexport interface OptionGroupsResponse {\n option_groups: OptionGroup[];\n}\nexport type AnyOptionsResponse = OptionsResponse | OptionGroupsResponse;", "score": 38.37672531513593 } ]
typescript
options.stateStore ?? new NoStorageStateStore();
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody
) => SlackViewHandler<E, ViewSubmission> | null)[] = [];
#viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/request.ts", "retrieved_chunk": " context: PreAuthorizeSlackAppContext;\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>;\n retryNum?: number;\n retryReason?: string;\n rawBody: string;\n headers: Headers;\n}\nexport type PreAuthorizeSlackMiddlwareRequest<E extends SlackAppEnv> =\n SlackMiddlewareRequestBase<E> & {", "score": 33.52482633563021 }, { "filename": "src/context/context.ts", "retrieved_chunk": "}\nexport function extractActorEnterpriseId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n const eventTeamId = body.event?.user_team || body.event?.team;\n if (eventTeamId && eventTeamId.startsWith(\"E\")) {\n return eventTeamId;", "score": 30.233446465371706 }, { "filename": "src/context/context.ts", "retrieved_chunk": " }\n }\n }\n }\n return extractTeamId(body);\n}\nexport function extractActorUserId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {", "score": 27.97832726201984 }, { "filename": "src/context/context.ts", "retrieved_chunk": " }\n }\n }\n return extractUserId(body);\n}\nexport function extractResponseUrl(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.response_url) {", "score": 27.58401377037048 }, { "filename": "src/context/context.ts", "retrieved_chunk": " } else if (eventTeamId === body.team_id) {\n return body.enterprise_id;\n }\n }\n }\n return extractEnterpriseId(body);\n}\nexport function extractActorTeamId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>", "score": 27.0047894397872 } ]
typescript
) => SlackViewHandler<E, ViewSubmission> | null)[] = [];
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (
body.type || !body.command) {
return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 51.06313482033852 }, { "filename": "src/middleware/middleware.ts", "retrieved_chunk": " req: SlackMiddlwareRequest<E>\n) => Promise<SlackResponse | void>;", "score": 40.63358879796385 }, { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 36.36608191272424 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 35.70101210928788 }, { "filename": "src/request/request.ts", "retrieved_chunk": " payload: Payload;\n};\nexport type SlackRequestWithChannelId<\n E extends SlackAppEnv,\n Payload\n> = SlackMiddlwareRequest<E> & {\n context: SlackAppContextWithChannelId;\n payload: Payload;\n};\nexport type SlackRequestWithRespond<", "score": 31.296183647120454 } ]
typescript
body.type || !body.command) {
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, });
this.appLevelToken = options.env.SLACK_APP_TOKEN;
this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/oauth-app.ts", "retrieved_chunk": " routes: { events: options.routes?.events ?? \"/slack/events\" },\n });\n this.env = options.env;\n this.installationStore = options.installationStore;\n this.stateStore = options.stateStore ?? new NoStorageStateStore();\n this.oauth = {\n stateCookieName:\n options.oauth?.stateCookieName ?? \"slack-app-oauth-state\",\n onFailure: options.oauth?.onFailure ?? defaultOnFailure,\n onStateValidationError:", "score": 56.00769111473037 }, { "filename": "src/oauth-app.ts", "retrieved_chunk": " const client = new SlackAPIClient(undefined, {\n logLevel: this.env.SLACK_LOGGING_LEVEL,\n });\n let oauthAccess: OAuthV2AccessResponse | undefined;\n try {\n // Execute the installation process\n oauthAccess = await client.oauth.v2.access({\n client_id: this.env.SLACK_CLIENT_ID,\n client_secret: this.env.SLACK_CLIENT_SECRET,\n redirect_uri: this.oauth.redirectUri,", "score": 53.12849338679435 }, { "filename": "src/oauth-app.ts", "retrieved_chunk": " return await this.oidc.onFailure(\n this.routes.oidc.start,\n MissingCode,\n request\n );\n }\n try {\n const client = new SlackAPIClient(undefined, {\n logLevel: this.env.SLACK_LOGGING_LEVEL,\n });", "score": 51.30471399986368 }, { "filename": "src/oauth-app.ts", "retrieved_chunk": " options.oauth?.onStateValidationError ?? defaultOnStateValidationError,\n redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI,\n };\n if (options.oidc) {\n this.oidc = {\n stateCookieName: options.oidc.stateCookieName ?? \"slack-app-oidc-state\",\n onFailure: options.oidc.onFailure ?? defaultOnFailure,\n onStateValidationError:\n options.oidc.onStateValidationError ?? defaultOnStateValidationError,\n callback: defaultOpenIDConnectCallback(this.env),", "score": 50.26859451068226 }, { "filename": "src/oauth-app.ts", "retrieved_chunk": " redirectUri:\n options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI,\n };\n } else {\n this.oidc = undefined;\n }\n this.routes = options.routes\n ? options.routes\n : {\n events: \"/slack/events\",", "score": 49.91364237655844 } ]
typescript
this.appLevelToken = options.env.SLACK_APP_TOKEN;
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => {
if (body.type || !body.command) {
return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 53.889525770448984 }, { "filename": "src/middleware/middleware.ts", "retrieved_chunk": " req: SlackMiddlwareRequest<E>\n) => Promise<SlackResponse | void>;", "score": 40.63358879796385 }, { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 39.392111065390594 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 38.68488886320159 }, { "filename": "src/request/request.ts", "retrieved_chunk": " payload: Payload;\n};\nexport type SlackRequestWithChannelId<\n E extends SlackAppEnv,\n Payload\n> = SlackMiddlwareRequest<E> & {\n context: SlackAppContextWithChannelId;\n payload: Payload;\n};\nexport type SlackRequestWithRespond<", "score": 31.296183647120454 } ]
typescript
if (body.type || !body.command) {
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => {
if (body.type !== PayloadType.ViewSubmission || !body.view) {
return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 50.19854613371669 }, { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 43.7001521258483 }, { "filename": "src/middleware/middleware.ts", "retrieved_chunk": " req: SlackMiddlwareRequest<E>\n) => Promise<SlackResponse | void>;", "score": 40.63358879796385 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 38.68488886320159 }, { "filename": "src/request/request.ts", "retrieved_chunk": " E extends SlackAppEnv,\n Payload\n> = SlackMiddlwareRequest<E> & {\n context: SlackAppContextWithRespond;\n payload: Payload;\n};\nexport type SlackRequestWithOptionalRespond<\n E extends SlackAppEnv,\n Payload\n> = SlackMiddlwareRequest<E> & {", "score": 34.60900613277875 } ]
typescript
if (body.type !== PayloadType.ViewSubmission || !body.view) {
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class
SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> {
public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": "export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> {\n public env: E;\n public client: SlackAPIClient;\n public authorize: Authorize<E>;\n public routes: { events: string | undefined };\n public signingSecret: string;\n public appLevelToken: string | undefined;\n public socketMode: boolean;\n public socketModeClient: SocketModeClient | undefined;\n // deno-lint-ignore no-explicit-any", "score": 29.625163264309556 }, { "filename": "src/app.ts", "retrieved_chunk": "export interface SlackAppOptions<\n E extends SlackEdgeAppEnv | SlackSocketModeAppEnv\n> {\n env: E;\n authorize?: Authorize<E>;\n routes?: {\n events: string;\n };\n socketMode?: boolean;\n}", "score": 27.739429995605168 }, { "filename": "src/oauth/authorize-url-generator.ts", "retrieved_chunk": "import { SlackOAuthEnv } from \"../app-env\";\nexport function generateAuthorizeUrl<E extends SlackOAuthEnv>(\n state: string,\n env: E,\n team: string | undefined = undefined\n): string {\n let url = `https://slack.com/oauth/v2/authorize?state=${state}`;\n url += `&client_id=${env.SLACK_CLIENT_ID}`;\n url += `&scope=${env.SLACK_BOT_SCOPES}`;\n if (env.SLACK_USER_SCOPES) {", "score": 25.445590838687387 }, { "filename": "src/oauth/installation-store.ts", "retrieved_chunk": "import { SlackOAuthEnv } from \"../app-env\";\nimport { Authorize } from \"../authorization/authorize\";\nimport { Installation } from \"./installation\";\nexport interface InstallationStoreQuery {\n enterpriseId?: string;\n teamId?: string;\n userId?: string;\n isEnterpriseInstall?: boolean;\n}\nexport interface InstallationStore<E extends SlackOAuthEnv> {", "score": 23.230481964621738 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " tokens: {\n oauth?: string[];\n bot?: string[];\n };\n}\nexport interface UserChangeEvent extends SlackEvent<\"user_change\"> {\n type: \"user_change\";\n user: {\n id: string;\n team_id: string;", "score": 21.790531517707368 } ]
typescript
SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title>
{sortedSections.map((section, idx) => ( <Stack key={section.id}
p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " createCourseForm.reset();\n await courses.refetch();\n })}\n >\n <Stack>\n <TextInput\n withAsterisk\n label=\"Title\"\n required\n placeholder=\"name your course here\"", "score": 22.82779755638505 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 19.509045736824174 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " Grid,\n Button,\n Group,\n Modal,\n TextInput,\n Stack,\n Textarea,\n} from \"@mantine/core\";\nimport { useDisclosure } from \"@mantine/hooks\";\nimport { api } from \"~/utils/api\";", "score": 16.70691092824447 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " },\n data: {\n order: sectionTarget.order,\n },\n });\n await ctx.prisma.section.update({\n where: {\n id: input.sectionIdTarget,\n },\n data: {", "score": 13.064387201890904 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " order: sectionSource.order,\n },\n });\n }),\n createPresignedUrlForVideo: protectedProcedure\n .input(z.object({ sectionId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const section = await ctx.prisma.section.findUnique({\n where: {\n id: input.sectionId,", "score": 12.42914241932201 } ]
typescript
{sortedSections.map((section, idx) => ( <Stack key={section.id}
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> {
const stateValue = await this.stateStore.issueNewState();
const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " await this.socketModeClient.connect();\n }\n async disconnect(): Promise<void> {\n if (this.socketModeClient) {\n await this.socketModeClient.disconnect();\n }\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext", "score": 64.55201951214843 }, { "filename": "src/oauth/callback.ts", "retrieved_chunk": "export type OnStateValidationError = (\n startPath: string,\n req: Request\n) => Promise<Response>;\n// deno-lint-ignore require-await\nexport const defaultOnStateValidationError = async (\n startPath: string,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {", "score": 51.52836379829887 }, { "filename": "src/app.ts", "retrieved_chunk": " ) {\n return handler;\n }\n return null;\n });\n return this;\n }\n async run(\n request: Request,\n ctx: ExecutionContext = new NoopExecutionContext()", "score": 45.557911610109564 }, { "filename": "src/app.ts", "retrieved_chunk": " ): Promise<Response> {\n return await this.handleEventRequest(request, ctx);\n }\n async connect(): Promise<void> {\n if (!this.socketMode) {\n throw new ConfigError(\n \"Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!\"\n );\n }\n this.socketModeClient = new SocketModeClient(this);", "score": 45.2499952977388 }, { "filename": "src/oauth/state-store.ts", "retrieved_chunk": "export interface StateStore {\n issueNewState(): Promise<string>;\n consume(state: string): Promise<boolean>;\n}\nexport class NoStorageStateStore implements StateStore {\n // deno-lint-ignore require-await\n async issueNewState(): Promise<string> {\n return crypto.randomUUID();\n }\n // deno-lint-ignore require-await no-unused-vars", "score": 43.26435547087296 } ]
typescript
const stateValue = await this.stateStore.issueNewState();
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; }
if (isPostedMessageEvent(body.event)) {
let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/context/context.ts", "retrieved_chunk": " } else if (body.user_id) {\n return body.user_id;\n } else if (body.event) {\n return extractUserId(body.event);\n } else if (body.message) {\n return extractUserId(body.message);\n } else if (body.previous_message) {\n return extractUserId(body.previous_message);\n }\n return undefined;", "score": 45.92793076552978 }, { "filename": "src/context/context.ts", "retrieved_chunk": " return body.enterprise_id;\n } else if (\n body.team &&\n typeof body.team === \"object\" &&\n body.team.enterprise_id\n ) {\n return body.team.enterprise_id;\n } else if (body.event) {\n return extractEnterpriseId(body.event);\n }", "score": 43.056665141683524 }, { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n if (body.event) {\n if (extractActorEnterpriseId(body) && extractActorTeamId(body)) {\n // When both enterprise_id and team_id are not identified, we skip returning user_id too for safety\n return undefined;\n }\n return body.event.user || body.event.user_id;\n } else {\n return undefined;", "score": 42.76937125166345 }, { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.channel) {\n if (typeof body.channel === \"string\") {\n return body.channel;\n } else if (typeof body.channel === \"object\" && body.channel.id) {\n return body.channel.id;\n }\n } else if (body.channel_id) {\n return body.channel_id;\n } else if (body.event) {\n return extractChannelId(body.event);", "score": 42.44935618874477 }, { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": " if (req.body.event) {\n if (eventTypesToKeep.includes(req.body.event.type)) {\n return;\n }\n if (\n req.context.authorizeResult.botId === req.body.event.bot_id ||\n req.context.authorizeResult.botUserId === req.context.userId\n ) {\n return { status: 200, body: \"\" };\n }", "score": 42.07903871347103 } ]
typescript
if (isPostedMessageEvent(body.event)) {
import { type Course } from "@prisma/client"; import { type NextPage } from "next"; import Head from "next/head"; import { useForm } from "@mantine/form"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { Card as MantineCard, Image, Text, Flex, Grid, Button, Group, Modal, TextInput, Stack, Textarea, } from "@mantine/core"; import { useDisclosure } from "@mantine/hooks"; import { api } from "~/utils/api"; import Link from "next/link"; import { getImageUrl } from "~/utils/getImageUrl"; export function CourseCard({ course }: { course: Course }) { return ( <MantineCard shadow="sm" padding="lg" radius="md" withBorder> <MantineCard.Section> <Image src={getImageUrl(course.imageId)} height={160} alt="Norway" /> </MantineCard.Section> <Group position="apart" mt="md" mb="xs"> <Text weight={500}>{course.title}</Text> {/* <Badge color="pink" variant="light"> On Sale </Badge> */} </Group> <Text size="sm" color="dimmed"> {course.description} </Text> <Button component={Link} href={`/dashboard/courses/${course.id}`} variant="light" color="blue" fullWidth mt="md" radius="md" > Manage </Button> </MantineCard> ); } const Courses: NextPage = () => {
const courses = api.course.getCourses.useQuery();
const createCourseMutation = api.course.createCourse.useMutation(); const [ isCreateCourseModalOpen, { open: openCreateCourseModal, close: closeCreateCourseModal }, ] = useDisclosure(false); const createCourseForm = useForm({ initialValues: { title: "", description: "", }, }); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <Modal opened={isCreateCourseModalOpen} onClose={closeCreateCourseModal} title="Create Course" > <form onSubmit={createCourseForm.onSubmit(async (values) => { await createCourseMutation.mutateAsync(values); closeCreateCourseModal(); createCourseForm.reset(); await courses.refetch(); })} > <Stack> <TextInput withAsterisk label="Title" required placeholder="name your course here" {...createCourseForm.getInputProps("title")} /> <Textarea withAsterisk minRows={6} required label="Description" placeholder="describe your course a bit" {...createCourseForm.getInputProps("description")} /> </Stack> <Group position="right" mt="md"> <Button type="submit">Create Course</Button> </Group> </form> </Modal> <main> <AdminDashboardLayout> <Flex justify="space-between" align="center" direction="row"> <h1>Manage Courses</h1> <Button onClick={openCreateCourseModal}>Create Course</Button> </Flex> <Grid> {courses.data?.map((course) => ( <Grid.Col key={course.id} span={4}> <CourseCard course={course} /> </Grid.Col> ))} </Grid> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/index.tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " <Button\n type=\"submit\"\n variant=\"light\"\n color=\"blue\"\n mt=\"md\"\n radius=\"md\"\n >\n Create Section\n </Button>\n </Stack>", "score": 19.513783426076916 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " value={file}\n />\n <Button\n disabled={!file}\n type=\"submit\"\n variant=\"light\"\n color=\"blue\"\n mt=\"md\"\n radius=\"md\"\n >", "score": 18.61809599135089 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " <Button\n type=\"submit\"\n variant=\"light\"\n color=\"white\"\n mt=\"md\"\n radius=\"md\"\n onClick={async () => {\n const targetSection = sortedSections[idx - 1];\n if (!targetSection) return;\n await swapSections.mutateAsync({", "score": 17.103887739099825 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " <Button\n type=\"submit\"\n variant=\"light\"\n color=\"white\"\n mt=\"md\"\n radius=\"md\"\n onClick={async () => {\n const targetSection = sortedSections[idx + 1];\n if (!targetSection) return;\n await swapSections.mutateAsync({", "score": 17.103887739099825 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " type=\"submit\"\n variant=\"light\"\n color=\"red\"\n mt=\"md\"\n radius=\"md\"\n onClick={async () => {\n if (\n !confirm(\n \"are you sure you want to delete this section?\"\n )", "score": 14.031599786581172 } ]
typescript
const courses = api.course.getCourses.useQuery();
import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc"; import { S3Client } from "@aws-sdk/client-s3"; import { createPresignedPost } from "@aws-sdk/s3-presigned-post"; import { env } from "~/env.mjs"; import { TRPCError } from "@trpc/server"; import { v4 as uuidv4 } from "uuid"; const UPLOAD_MAX_FILE_SIZE = 1000000; const s3Client = new S3Client({ region: "us-east-1", endpoint: "http://localhost:9000", forcePathStyle: true, credentials: { accessKeyId: "S3RVER", secretAccessKey: "S3RVER", }, }); export const courseRouter = createTRPCRouter({ getCourseById: protectedProcedure .input( z.object({ courseId: z.string(), }) ) .query(({ ctx, input }) => { return ctx.prisma.course.findUnique({ where: { id: input.courseId, }, include: { sections: true, }, }); }), getCourses: protectedProcedure.query(({ ctx }) => { return ctx.prisma.course.findMany({ where: { userId: ctx.session.user.id, }, }); }), createCourse: protectedProcedure .input(z.object({ title: z.string(), description: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; const newCourse = await ctx.prisma.course.create({ data: { title: input.title, description: input.description, userId: userId, }, }); return newCourse; }), updateCourse: protectedProcedure .input(z.object({ title: z.string(), courseId: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; await ctx.prisma.course.updateMany({ where: { id: input.courseId, userId, }, data: { title: input.title, }, }); return { status: "updated" }; }), createPresignedUrl: protectedProcedure .input(z.object({ courseId: z.string() })) .mutation(async ({ ctx, input }) => { // const userId = ctx.session.user.id; const course = await ctx.prisma.course.findUnique({ where: { id: input.courseId, }, }); if (!course) { throw new TRPCError({ code: "NOT_FOUND", message: "the course does not exist", }); } const imageId = uuidv4(); await ctx.prisma.course.update({ where: { id: course.id, }, data: { imageId, }, }); return createPresignedPost(s3Client, { Bucket:
env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
key: imageId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), createSection: protectedProcedure .input(z.object({ courseId: z.string(), title: z.string() })) .mutation(async ({ ctx, input }) => { const videoId = uuidv4(); return await ctx.prisma.section.create({ data: { videoId, title: input.title, courseId: input.courseId, }, }); }), deleteSection: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.delete({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "section not found", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return section; }), swapSections: protectedProcedure .input( z.object({ sectionIdSource: z.string(), sectionIdTarget: z.string() }) ) .mutation(async ({ ctx, input }) => { const sectionSource = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdSource, }, }); if (!sectionSource) { throw new TRPCError({ code: "NOT_FOUND", message: "the source section does not exist", }); } const sectionTarget = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdTarget, }, }); if (!sectionTarget) { throw new TRPCError({ code: "NOT_FOUND", message: "the target section does not exist", }); } await ctx.prisma.section.update({ where: { id: input.sectionIdSource, }, data: { order: sectionTarget.order, }, }); await ctx.prisma.section.update({ where: { id: input.sectionIdTarget, }, data: { order: sectionSource.order, }, }); }), createPresignedUrlForVideo: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.findUnique({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "the section does not exist", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "the section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return createPresignedPost(s3Client, { Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: section.videoId, Fields: { key: section.videoId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), });
src/server/api/routers/course.ts
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/utils/getImageUrl.ts", "retrieved_chunk": "import { env } from \"~/env.mjs\";\nexport function getImageUrl(id: string) {\n return `http://localhost:9000/${env.NEXT_PUBLIC_S3_BUCKET_NAME}/${id}`;\n}", "score": 11.33054115801795 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " width=\"200\"\n alt=\"an image of the course\"\n src={getImageUrl(courseQuery.data.imageId)}\n />\n )}\n <Stack sx={{ flex: 1 }}>\n <form onSubmit={uploadImage}>\n <FileInput\n label=\"Course Image\"\n onChange={setFile}", "score": 9.556707038225051 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import Link from \"next/link\";\nimport { getImageUrl } from \"~/utils/getImageUrl\";\nexport function CourseCard({ course }: { course: Course }) {\n return (\n <MantineCard shadow=\"sm\" padding=\"lg\" radius=\"md\" withBorder>\n <MantineCard.Section>\n <Image src={getImageUrl(course.imageId)} height={160} alt=\"Norway\" />\n </MantineCard.Section>\n <Group position=\"apart\" mt=\"md\" mb=\"xs\">\n <Text weight={500}>{course.title}</Text>", "score": 6.2234798713799915 }, { "filename": "src/utils/api.ts", "retrieved_chunk": "import { type AppRouter } from \"~/server/api/root\";\nconst getBaseUrl = () => {\n if (typeof window !== \"undefined\") return \"\"; // browser should use relative url\n if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url\n return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost\n};\n/** A set of type-safe react-query hooks for your tRPC API. */\nexport const api = createTRPCNext<AppRouter>({\n config() {\n return {", "score": 4.944857708171796 }, { "filename": "src/server/auth.ts", "retrieved_chunk": " id: user.id,\n },\n }),\n },\n adapter: PrismaAdapter(prisma),\n providers: [\n GoogleProvider({\n clientId: env.GOOGLE_CLIENT_ID,\n clientSecret: env.GOOGLE_CLIENT_SECRET,\n }),", "score": 4.262274501166453 } ]
typescript
env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !==
PayloadType.EventsAPI || !body.event) {
return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": " if (req.body.event) {\n if (eventTypesToKeep.includes(req.body.event.type)) {\n return;\n }\n if (\n req.context.authorizeResult.botId === req.body.event.bot_id ||\n req.context.authorizeResult.botUserId === req.context.userId\n ) {\n return { status: 200, body: \"\" };\n }", "score": 37.918130525820594 }, { "filename": "src/context/context.ts", "retrieved_chunk": "}\nexport function extractActorEnterpriseId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n const eventTeamId = body.event?.user_team || body.event?.team;\n if (eventTeamId && eventTeamId.startsWith(\"E\")) {\n return eventTeamId;", "score": 33.75244630849777 }, { "filename": "src/context/context.ts", "retrieved_chunk": " return body.enterprise_id;\n } else if (\n body.team &&\n typeof body.team === \"object\" &&\n body.team.enterprise_id\n ) {\n return body.team.enterprise_id;\n } else if (body.event) {\n return extractEnterpriseId(body.event);\n }", "score": 31.775676377216406 }, { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.channel) {\n if (typeof body.channel === \"string\") {\n return body.channel;\n } else if (typeof body.channel === \"object\" && body.channel.id) {\n return body.channel.id;\n }\n } else if (body.channel_id) {\n return body.channel_id;\n } else if (body.event) {\n return extractChannelId(body.event);", "score": 31.46839434602121 }, { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n if (body.event) {\n if (extractActorEnterpriseId(body) && extractActorTeamId(body)) {\n // When both enterprise_id and team_id are not identified, we skip returning user_id too for safety\n return undefined;\n }\n return body.event.user || body.event.user_id;\n } else {\n return undefined;", "score": 31.336526396523382 } ]
typescript
PayloadType.EventsAPI || !body.event) {
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.
save(toInstallation(oauthAccess), request);
} catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/index.ts", "retrieved_chunk": "export * from \"./oauth/installation\";\nexport * from \"./oauth/installation-store\";\nexport * from \"./oauth/oauth-page-renderer\";\nexport * from \"./oauth/state-store\";\nexport * from \"./oidc/authorize-url-generator\";\nexport * from \"./oidc/callback\";\nexport * from \"./oidc/login\";\nexport * from \"./request/request-body\";\nexport * from \"./request/request-verification\";\nexport * from \"./request/request\";", "score": 27.38325195020688 }, { "filename": "src/app.ts", "retrieved_chunk": " ): Promise<Response> {\n return await this.handleEventRequest(request, ctx);\n }\n async connect(): Promise<void> {\n if (!this.socketMode) {\n throw new ConfigError(\n \"Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!\"\n );\n }\n this.socketModeClient = new SocketModeClient(this);", "score": 26.609308054885915 }, { "filename": "src/app.ts", "retrieved_chunk": " }\n }\n // Verify the request headers and body\n const isRequestSignatureVerified =\n this.socketMode ||\n (await verifySlackRequest(this.signingSecret, request.headers, rawBody));\n if (isRequestSignatureVerified) {\n // deno-lint-ignore no-explicit-any\n const body: Record<string, any> = await parseRequestBody(\n request.headers,", "score": 26.569872219434576 }, { "filename": "src/app.ts", "retrieved_chunk": " await this.socketModeClient.connect();\n }\n async disconnect(): Promise<void> {\n if (this.socketModeClient) {\n await this.socketModeClient.disconnect();\n }\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext", "score": 26.18546071056729 }, { "filename": "src/app.ts", "retrieved_chunk": " if (!this.env.SLACK_SIGNING_SECRET) {\n throw new ConfigError(\n \"env.SLACK_SIGNING_SECRET is required to run your app on edge functions!\"\n );\n }\n this.signingSecret = this.env.SLACK_SIGNING_SECRET;\n }\n this.authorize = options.authorize ?? singleTeamAuthorize;\n this.routes = { events: options.routes?.events };\n }", "score": 25.753463217705104 } ]
typescript
save(toInstallation(oauthAccess), request);
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections
.map((section, idx) => ( <Stack key={section.id}
p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " createCourseForm.reset();\n await courses.refetch();\n })}\n >\n <Stack>\n <TextInput\n withAsterisk\n label=\"Title\"\n required\n placeholder=\"name your course here\"", "score": 22.82779755638505 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 19.509045736824174 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " Grid,\n Button,\n Group,\n Modal,\n TextInput,\n Stack,\n Textarea,\n} from \"@mantine/core\";\nimport { useDisclosure } from \"@mantine/hooks\";\nimport { api } from \"~/utils/api\";", "score": 16.70691092824447 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " },\n data: {\n order: sectionTarget.order,\n },\n });\n await ctx.prisma.section.update({\n where: {\n id: input.sectionIdTarget,\n },\n data: {", "score": 13.064387201890904 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " order: sectionSource.order,\n },\n });\n }),\n createPresignedUrlForVideo: protectedProcedure\n .input(z.object({ sectionId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const section = await ctx.prisma.section.findUnique({\n where: {\n id: input.sectionId,", "score": 12.42914241932201 } ]
typescript
.map((section, idx) => ( <Stack key={section.id}
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src
={getImageUrl(courseQuery.data.imageId)}
/> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import Link from \"next/link\";\nimport { getImageUrl } from \"~/utils/getImageUrl\";\nexport function CourseCard({ course }: { course: Course }) {\n return (\n <MantineCard shadow=\"sm\" padding=\"lg\" radius=\"md\" withBorder>\n <MantineCard.Section>\n <Image src={getImageUrl(course.imageId)} height={160} alt=\"Norway\" />\n </MantineCard.Section>\n <Group position=\"apart\" mt=\"md\" mb=\"xs\">\n <Text weight={500}>{course.title}</Text>", "score": 18.21415097518419 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " <Menu.Target>\n <Group>\n <Avatar\n imageProps={{ referrerPolicy: \"no-referrer\" }}\n src={user.data.user.image}\n radius=\"xl\"\n />\n <Box sx={{ flex: 1 }}>\n <Text size=\"sm\" weight={500}>\n {user.data.user.name}", "score": 15.88399583705602 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " code: \"NOT_FOUND\",\n message: \"the course does not exist\",\n });\n }\n const imageId = uuidv4();\n await ctx.prisma.course.update({\n where: {\n id: course.id,\n },\n data: {", "score": 12.227872158023123 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 10.420639621041108 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 9.277512450173043 } ]
typescript
={getImageUrl(courseQuery.data.imageId)}
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) {
if (body.block_id && body.block_id !== constraints.block_id) {
return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.channel) {\n if (typeof body.channel === \"string\") {\n return body.channel;\n } else if (typeof body.channel === \"object\" && body.channel.id) {\n return body.channel.id;\n }\n } else if (body.channel_id) {\n return body.channel_id;\n } else if (body.event) {\n return extractChannelId(body.event);", "score": 66.25121943218355 }, { "filename": "src/context/context.ts", "retrieved_chunk": "): string | undefined {\n if (body.enterprise) {\n if (typeof body.enterprise === \"string\") {\n return body.enterprise;\n } else if (typeof body.enterprise === \"object\" && body.enterprise.id) {\n return body.enterprise.id;\n }\n } else if (body.authorizations && body.authorizations.length > 0) {\n return extractEnterpriseId(body.authorizations[0]);\n } else if (body.enterprise_id) {", "score": 64.39185739520245 }, { "filename": "src/context/context.ts", "retrieved_chunk": " // we should use .authorizations[0].team_id over .team_id\n return extractTeamId(body.authorizations[0]);\n } else if (body.team_id) {\n return body.team_id;\n } else if (body.user && typeof body.user === \"object\") {\n return body.user.team_id;\n } else if (body.view && typeof body.view === \"object\") {\n return body.view.team_id;\n }\n return undefined;", "score": 60.52877720202195 }, { "filename": "src/context/context.ts", "retrieved_chunk": " return body.enterprise_id;\n } else if (\n body.team &&\n typeof body.team === \"object\" &&\n body.team.enterprise_id\n ) {\n return body.team.enterprise_id;\n } else if (body.event) {\n return extractEnterpriseId(body.event);\n }", "score": 60.37220737618837 }, { "filename": "src/context/context.ts", "retrieved_chunk": " } else if (body.user_id) {\n return body.user_id;\n } else if (body.event) {\n return extractUserId(body.event);\n } else if (body.message) {\n return extractUserId(body.message);\n } else if (body.previous_message) {\n return extractUserId(body.previous_message);\n }\n return undefined;", "score": 54.95787965849257 } ]
typescript
if (body.block_id && body.block_id !== constraints.block_id) {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation
= api.course.updateCourse.useMutation();
const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "}\nconst Courses: NextPage = () => {\n const courses = api.course.getCourses.useQuery();\n const createCourseMutation = api.course.createCourse.useMutation();\n const [\n isCreateCourseModalOpen,\n { open: openCreateCourseModal, close: closeCreateCourseModal },\n ] = useDisclosure(false);\n const createCourseForm = useForm({\n initialValues: {", "score": 20.332331297425142 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " },\n });\n return newCourse;\n }),\n updateCourse: protectedProcedure\n .input(z.object({ title: z.string(), courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const userId = ctx.session.user.id;\n await ctx.prisma.course.updateMany({\n where: {", "score": 17.023824670809088 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " .input(z.object({ courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n // const userId = ctx.session.user.id;\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: input.courseId,\n },\n });\n if (!course) {\n throw new TRPCError({", "score": 15.608344546774514 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " z.object({\n courseId: z.string(),\n })\n )\n .query(({ ctx, input }) => {\n return ctx.prisma.course.findUnique({\n where: {\n id: input.courseId,\n },\n include: {", "score": 14.877442306384669 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " }\n if (!section.courseId) {\n throw new TRPCError({\n code: \"NOT_FOUND\",\n message: \"section has no course\",\n });\n }\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: section.courseId,", "score": 13.914877324897727 } ]
typescript
= api.course.updateCourse.useMutation();
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => {
if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) {
return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 60.98138985668975 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 60.82154882643605 }, { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 51.552408704653914 }, { "filename": "src/middleware/middleware.ts", "retrieved_chunk": " req: SlackMiddlwareRequest<E>\n) => Promise<SlackResponse | void>;", "score": 40.63358879796385 }, { "filename": "src/handler/options-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackOptionsResponse } from \"../response/response\";\nexport type OptionsAckResponse = SlackOptionsResponse;\nexport interface SlackOptionsHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<OptionsAckResponse>;\n // Note that a block_suggestion response must be done synchronously.\n // That's why we don't support lazy functions for the pattern.\n}", "score": 34.26523032569199 } ]
typescript
if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess
(data) {
updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/_app.tsx", "retrieved_chunk": "import \"~/styles/globals.css\";\nimport { useState } from \"react\";\nconst MyApp: AppType<{ session: Session | null }> = ({\n Component,\n pageProps: { session, ...pageProps },\n}) => {\n const preferredColorScheme = \"dark\"; //useColorScheme();\n const [colorScheme, setColorScheme] =\n useState<ColorScheme>(preferredColorScheme);\n const toggleColorScheme = (value?: ColorScheme) =>", "score": 26.317586459530375 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "}\nconst Courses: NextPage = () => {\n const courses = api.course.getCourses.useQuery();\n const createCourseMutation = api.course.createCourse.useMutation();\n const [\n isCreateCourseModalOpen,\n { open: openCreateCourseModal, close: closeCreateCourseModal },\n ] = useDisclosure(false);\n const createCourseForm = useForm({\n initialValues: {", "score": 12.860173626299844 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " error.cause instanceof ZodError ? error.cause.flatten() : null,\n },\n };\n },\n});\n/**\n * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)\n *\n * These are the pieces you use to build your tRPC API. You should import these a lot in the\n * \"/src/server/api/routers\" directory.", "score": 12.088714271904891 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " }\n if (!section.courseId) {\n throw new TRPCError({\n code: \"NOT_FOUND\",\n message: \"section has no course\",\n });\n }\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: section.courseId,", "score": 11.650200120180177 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " .input(z.object({ courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n // const userId = ctx.session.user.id;\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: input.courseId,\n },\n });\n if (!course) {\n throw new TRPCError({", "score": 11.39686304356386 } ]
typescript
(data) {
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !
body.actions || !body.actions[0] ) {
return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 28.858205320220485 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 25.80002672125517 }, { "filename": "src/context/context.ts", "retrieved_chunk": " const eventTeam = body.event.team;\n if (eventTeam) {\n if (eventTeam.startsWith(\"T\")) {\n return eventTeam;\n } else if (eventTeam.startsWith(\"E\")) {\n if (eventTeam === body.enterprise_id) {\n return body.team_id;\n } else if (eventTeam === body.context_enterprise_id) {\n return body.context_team_id;\n }", "score": 25.531886325400755 }, { "filename": "src/context/context.ts", "retrieved_chunk": "}\nexport function extractActorEnterpriseId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n const eventTeamId = body.event?.user_team || body.event?.team;\n if (eventTeamId && eventTeamId.startsWith(\"E\")) {\n return eventTeamId;", "score": 24.682019694347634 }, { "filename": "src/context/context.ts", "retrieved_chunk": "): string | undefined {\n if (body.enterprise) {\n if (typeof body.enterprise === \"string\") {\n return body.enterprise;\n } else if (typeof body.enterprise === \"object\" && body.enterprise.id) {\n return body.enterprise.id;\n }\n } else if (body.authorizations && body.authorizations.length > 0) {\n return extractEnterpriseId(body.authorizations[0]);\n } else if (body.enterprise_id) {", "score": 24.589739232211695 } ]
typescript
body.actions || !body.actions[0] ) {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const
updateCourseMutation = api.course.updateCourse.useMutation();
const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "}\nconst Courses: NextPage = () => {\n const courses = api.course.getCourses.useQuery();\n const createCourseMutation = api.course.createCourse.useMutation();\n const [\n isCreateCourseModalOpen,\n { open: openCreateCourseModal, close: closeCreateCourseModal },\n ] = useDisclosure(false);\n const createCourseForm = useForm({\n initialValues: {", "score": 20.332331297425142 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " },\n });\n return newCourse;\n }),\n updateCourse: protectedProcedure\n .input(z.object({ title: z.string(), courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const userId = ctx.session.user.id;\n await ctx.prisma.course.updateMany({\n where: {", "score": 17.023824670809088 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " .input(z.object({ courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n // const userId = ctx.session.user.id;\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: input.courseId,\n },\n });\n if (!course) {\n throw new TRPCError({", "score": 15.608344546774514 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " z.object({\n courseId: z.string(),\n })\n )\n .query(({ ctx, input }) => {\n return ctx.prisma.course.findUnique({\n where: {\n id: input.courseId,\n },\n include: {", "score": 14.877442306384669 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " }\n if (!section.courseId) {\n throw new TRPCError({\n code: \"NOT_FOUND\",\n message: \"section has no course\",\n });\n }\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: section.courseId,", "score": 13.914877324897727 } ]
typescript
updateCourseMutation = api.course.updateCourse.useMutation();
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.
EventsAPI || !body.event) {
return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": " if (req.body.event) {\n if (eventTypesToKeep.includes(req.body.event.type)) {\n return;\n }\n if (\n req.context.authorizeResult.botId === req.body.event.bot_id ||\n req.context.authorizeResult.botUserId === req.context.userId\n ) {\n return { status: 200, body: \"\" };\n }", "score": 37.918130525820594 }, { "filename": "src/context/context.ts", "retrieved_chunk": "}\nexport function extractActorEnterpriseId(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): string | undefined {\n if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n const eventTeamId = body.event?.user_team || body.event?.team;\n if (eventTeamId && eventTeamId.startsWith(\"E\")) {\n return eventTeamId;", "score": 33.75244630849777 }, { "filename": "src/context/context.ts", "retrieved_chunk": " return body.enterprise_id;\n } else if (\n body.team &&\n typeof body.team === \"object\" &&\n body.team.enterprise_id\n ) {\n return body.team.enterprise_id;\n } else if (body.event) {\n return extractEnterpriseId(body.event);\n }", "score": 31.775676377216406 }, { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.channel) {\n if (typeof body.channel === \"string\") {\n return body.channel;\n } else if (typeof body.channel === \"object\" && body.channel.id) {\n return body.channel.id;\n }\n } else if (body.channel_id) {\n return body.channel_id;\n } else if (body.event) {\n return extractChannelId(body.event);", "score": 31.46839434602121 }, { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n if (body.event) {\n if (extractActorEnterpriseId(body) && extractActorTeamId(body)) {\n // When both enterprise_id and team_id are not identified, we skip returning user_id too for safety\n return undefined;\n }\n return body.event.user || body.event.user_id;\n } else {\n return undefined;", "score": 31.336526396523382 } ]
typescript
EventsAPI || !body.event) {
import { type AppType } from "next/app"; import { type Session } from "next-auth"; import { SessionProvider } from "next-auth/react"; import { ColorScheme, ColorSchemeProvider, MantineProvider, } from "@mantine/core"; import { useColorScheme } from "@mantine/hooks"; import { api } from "~/utils/api"; import "~/styles/globals.css"; import { useState } from "react"; const MyApp: AppType<{ session: Session | null }> = ({ Component, pageProps: { session, ...pageProps }, }) => { const preferredColorScheme = "dark"; //useColorScheme(); const [colorScheme, setColorScheme] = useState<ColorScheme>(preferredColorScheme); const toggleColorScheme = (value?: ColorScheme) => setColorScheme(value || (colorScheme === "dark" ? "light" : "dark")); return ( <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme} > <MantineProvider withGlobalStyles withNormalizeCSS theme={{ colorScheme, }} > <SessionProvider session={session}> <Component {...pageProps} /> </SessionProvider> </MantineProvider> </ColorSchemeProvider> ); };
export default api.withTRPC(MyApp);
src/pages/_app.tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/api/authSSR.ts", "retrieved_chunk": "import { NextApiRequest, NextApiResponse } from \"next\";\nimport { getSession } from \"next-auth/react\";\nexport default async function handle(\n req: NextApiRequest,\n res: NextApiResponse\n) {\n const session = await getSession({ req });\n res.json({ data: { auth: !!session } });\n}", "score": 8.639838222357366 }, { "filename": "src/server/auth.ts", "retrieved_chunk": " * Options for NextAuth.js used to configure adapters, providers, callbacks, etc.\n *\n * @see https://next-auth.js.org/configuration/options\n */\nexport const authOptions: NextAuthOptions = {\n callbacks: {\n session: ({ session, user }) => ({\n ...session,\n user: {\n ...session.user,", "score": 8.036079457737635 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *", "score": 7.601008172168364 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * that goes through your tRPC endpoint.\n *\n * @see https://trpc.io/docs/context\n */\nexport const createTRPCContext = async (opts: CreateNextContextOptions) => {\n const { req, res } = opts;\n // Get the session from the server using the getServerSession wrapper function\n const session = await getServerAuthSession({ req, res });\n return createInnerTRPCContext({\n session,", "score": 6.652790742301691 }, { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 5.8628359632931195 } ]
typescript
export default api.withTRPC(MyApp);
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={
getImageUrl(courseQuery.data.imageId)}
/> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import Link from \"next/link\";\nimport { getImageUrl } from \"~/utils/getImageUrl\";\nexport function CourseCard({ course }: { course: Course }) {\n return (\n <MantineCard shadow=\"sm\" padding=\"lg\" radius=\"md\" withBorder>\n <MantineCard.Section>\n <Image src={getImageUrl(course.imageId)} height={160} alt=\"Norway\" />\n </MantineCard.Section>\n <Group position=\"apart\" mt=\"md\" mb=\"xs\">\n <Text weight={500}>{course.title}</Text>", "score": 18.21415097518419 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " <Menu.Target>\n <Group>\n <Avatar\n imageProps={{ referrerPolicy: \"no-referrer\" }}\n src={user.data.user.image}\n radius=\"xl\"\n />\n <Box sx={{ flex: 1 }}>\n <Text size=\"sm\" weight={500}>\n {user.data.user.name}", "score": 15.88399583705602 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " code: \"NOT_FOUND\",\n message: \"the course does not exist\",\n });\n }\n const imageId = uuidv4();\n await ctx.prisma.course.update({\n where: {\n id: course.id,\n },\n data: {", "score": 12.227872158023123 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 10.420639621041108 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 9.277512450173043 } ]
typescript
getImageUrl(courseQuery.data.imageId)}
import { type Course } from "@prisma/client"; import { type NextPage } from "next"; import Head from "next/head"; import { useForm } from "@mantine/form"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { Card as MantineCard, Image, Text, Flex, Grid, Button, Group, Modal, TextInput, Stack, Textarea, } from "@mantine/core"; import { useDisclosure } from "@mantine/hooks"; import { api } from "~/utils/api"; import Link from "next/link"; import { getImageUrl } from "~/utils/getImageUrl"; export function CourseCard({ course }: { course: Course }) { return ( <MantineCard shadow="sm" padding="lg" radius="md" withBorder> <MantineCard.Section> <Image src={getImageUrl(course.imageId)} height={160} alt="Norway" /> </MantineCard.Section> <Group position="apart" mt="md" mb="xs"> <Text weight={500}>{course.title}</Text> {/* <Badge color="pink" variant="light"> On Sale </Badge> */} </Group> <Text size="sm" color="dimmed"> {course.description} </Text> <Button component={Link} href={`/dashboard/courses/${course.id}`} variant="light" color="blue" fullWidth mt="md" radius="md" > Manage </Button> </MantineCard> ); } const Courses: NextPage = () => { const
courses = api.course.getCourses.useQuery();
const createCourseMutation = api.course.createCourse.useMutation(); const [ isCreateCourseModalOpen, { open: openCreateCourseModal, close: closeCreateCourseModal }, ] = useDisclosure(false); const createCourseForm = useForm({ initialValues: { title: "", description: "", }, }); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <Modal opened={isCreateCourseModalOpen} onClose={closeCreateCourseModal} title="Create Course" > <form onSubmit={createCourseForm.onSubmit(async (values) => { await createCourseMutation.mutateAsync(values); closeCreateCourseModal(); createCourseForm.reset(); await courses.refetch(); })} > <Stack> <TextInput withAsterisk label="Title" required placeholder="name your course here" {...createCourseForm.getInputProps("title")} /> <Textarea withAsterisk minRows={6} required label="Description" placeholder="describe your course a bit" {...createCourseForm.getInputProps("description")} /> </Stack> <Group position="right" mt="md"> <Button type="submit">Create Course</Button> </Group> </form> </Modal> <main> <AdminDashboardLayout> <Flex justify="space-between" align="center" direction="row"> <h1>Manage Courses</h1> <Button onClick={openCreateCourseModal}>Create Course</Button> </Flex> <Grid> {courses.data?.map((course) => ( <Grid.Col key={course.id} span={4}> <CourseCard course={course} /> </Grid.Col> ))} </Grid> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/index.tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " await fetch(url, {\n method: \"POST\",\n body: formData,\n });\n}\nconst Courses: NextPage = () => {\n const router = useRouter();\n const courseId = router.query.courseId as string;\n const updateCourseMutation = api.course.updateCourse.useMutation();\n const createSectionMutation = api.course.createSection.useMutation();", "score": 13.001621006017304 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " <Button\n type=\"submit\"\n variant=\"light\"\n color=\"blue\"\n mt=\"md\"\n radius=\"md\"\n >\n Create Section\n </Button>\n </Stack>", "score": 11.342824302984193 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " value={file}\n />\n <Button\n disabled={!file}\n type=\"submit\"\n variant=\"light\"\n color=\"blue\"\n mt=\"md\"\n radius=\"md\"\n >", "score": 10.447136868258168 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " });\n const newSectionForm = useForm({\n initialValues: {\n title: \"\",\n },\n });\n const [file, setFile] = useState<File | null>(null);\n const [newSection, setNewSection] = useState<File | null>(null);\n const courseQuery = api.course.getCourseById.useQuery(\n {", "score": 10.131252443288378 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " <Button\n type=\"submit\"\n variant=\"light\"\n color=\"white\"\n mt=\"md\"\n radius=\"md\"\n onClick={async () => {\n const targetSection = sortedSections[idx - 1];\n if (!targetSection) return;\n await swapSections.mutateAsync({", "score": 10.047021613174255 } ]
typescript
courses = api.course.getCourses.useQuery();
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { env } from "~/env.mjs"; import { prisma } from "~/server/db"; /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. * * @see https://next-auth.js.org/getting-started/typescript#module-augmentation */ declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; // ...other properties // role: UserRole; } & DefaultSession["user"]; } // interface User { // // ...other properties // // role: UserRole; // } } /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * * @see https://next-auth.js.org/configuration/options */ export const authOptions: NextAuthOptions = { callbacks: { session: ({ session, user }) => ({ ...session, user: { ...session.user, id: user.id, }, }), },
adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({
clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), /** * ...add more providers here. * * Most other providers require a bit more work than the Discord provider. For example, the * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account * model. Refer to the NextAuth.js docs for the provider you want to use. Example: * * @see https://next-auth.js.org/providers/github */ ], }; /** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); };
src/server/auth.ts
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " sections: true,\n },\n });\n }),\n getCourses: protectedProcedure.query(({ ctx }) => {\n return ctx.prisma.course.findMany({\n where: {\n userId: ctx.session.user.id,\n },\n });", "score": 17.648617952009175 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *", "score": 17.62576835790585 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " code: \"NOT_FOUND\",\n message: \"the section has no course\",\n });\n }\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: section.courseId,\n },\n });\n if (course?.userId !== ctx.session.user.id) {", "score": 16.124121483281883 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " .input(z.object({ courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n // const userId = ctx.session.user.id;\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: input.courseId,\n },\n });\n if (!course) {\n throw new TRPCError({", "score": 14.688053907549854 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " },\n });\n return newCourse;\n }),\n updateCourse: protectedProcedure\n .input(z.object({ title: z.string(), courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const userId = ctx.session.user.id;\n await ctx.prisma.course.updateMany({\n where: {", "score": 14.104125643655864 } ]
typescript
adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({
import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc"; import { S3Client } from "@aws-sdk/client-s3"; import { createPresignedPost } from "@aws-sdk/s3-presigned-post"; import { env } from "~/env.mjs"; import { TRPCError } from "@trpc/server"; import { v4 as uuidv4 } from "uuid"; const UPLOAD_MAX_FILE_SIZE = 1000000; const s3Client = new S3Client({ region: "us-east-1", endpoint: "http://localhost:9000", forcePathStyle: true, credentials: { accessKeyId: "S3RVER", secretAccessKey: "S3RVER", }, }); export const courseRouter = createTRPCRouter({ getCourseById: protectedProcedure .input( z.object({ courseId: z.string(), }) ) .query(({ ctx, input }) => { return ctx.prisma.course.findUnique({ where: { id: input.courseId, }, include: { sections: true, }, }); }), getCourses: protectedProcedure.query(({ ctx }) => { return ctx.prisma.course.findMany({ where: { userId: ctx.session.user.id, }, }); }), createCourse: protectedProcedure .input(z.object({ title: z.string(), description: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; const newCourse = await ctx.prisma.course.create({ data: { title: input.title, description: input.description, userId: userId, }, }); return newCourse; }), updateCourse: protectedProcedure .input(z.object({ title: z.string(), courseId: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; await ctx.prisma.course.updateMany({ where: { id: input.courseId, userId, }, data: { title: input.title, }, }); return { status: "updated" }; }), createPresignedUrl: protectedProcedure .input(z.object({ courseId: z.string() })) .mutation(async ({ ctx, input }) => { // const userId = ctx.session.user.id; const course = await ctx.prisma.course.findUnique({ where: { id: input.courseId, }, }); if (!course) { throw new TRPCError({ code: "NOT_FOUND", message: "the course does not exist", }); } const imageId = uuidv4(); await ctx.prisma.course.update({ where: { id: course.id, }, data: { imageId, }, }); return createPresignedPost(s3Client, {
Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
key: imageId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), createSection: protectedProcedure .input(z.object({ courseId: z.string(), title: z.string() })) .mutation(async ({ ctx, input }) => { const videoId = uuidv4(); return await ctx.prisma.section.create({ data: { videoId, title: input.title, courseId: input.courseId, }, }); }), deleteSection: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.delete({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "section not found", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return section; }), swapSections: protectedProcedure .input( z.object({ sectionIdSource: z.string(), sectionIdTarget: z.string() }) ) .mutation(async ({ ctx, input }) => { const sectionSource = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdSource, }, }); if (!sectionSource) { throw new TRPCError({ code: "NOT_FOUND", message: "the source section does not exist", }); } const sectionTarget = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdTarget, }, }); if (!sectionTarget) { throw new TRPCError({ code: "NOT_FOUND", message: "the target section does not exist", }); } await ctx.prisma.section.update({ where: { id: input.sectionIdSource, }, data: { order: sectionTarget.order, }, }); await ctx.prisma.section.update({ where: { id: input.sectionIdTarget, }, data: { order: sectionSource.order, }, }); }), createPresignedUrlForVideo: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.findUnique({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "the section does not exist", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "the section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return createPresignedPost(s3Client, { Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: section.videoId, Fields: { key: section.videoId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), });
src/server/api/routers/course.ts
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/utils/getImageUrl.ts", "retrieved_chunk": "import { env } from \"~/env.mjs\";\nexport function getImageUrl(id: string) {\n return `http://localhost:9000/${env.NEXT_PUBLIC_S3_BUCKET_NAME}/${id}`;\n}", "score": 18.759146168250794 }, { "filename": "src/server/auth.ts", "retrieved_chunk": " id: user.id,\n },\n }),\n },\n adapter: PrismaAdapter(prisma),\n providers: [\n GoogleProvider({\n clientId: env.GOOGLE_CLIENT_ID,\n clientSecret: env.GOOGLE_CLIENT_SECRET,\n }),", "score": 12.017228394067294 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " width=\"200\"\n alt=\"an image of the course\"\n src={getImageUrl(courseQuery.data.imageId)}\n />\n )}\n <Stack sx={{ flex: 1 }}>\n <form onSubmit={uploadImage}>\n <FileInput\n label=\"Course Image\"\n onChange={setFile}", "score": 11.502733459467015 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 10.104429237127329 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import Link from \"next/link\";\nimport { getImageUrl } from \"~/utils/getImageUrl\";\nexport function CourseCard({ course }: { course: Course }) {\n return (\n <MantineCard shadow=\"sm\" padding=\"lg\" radius=\"md\" withBorder>\n <MantineCard.Section>\n <Image src={getImageUrl(course.imageId)} height={160} alt=\"Norway\" />\n </MantineCard.Section>\n <Group position=\"apart\" mt=\"md\" mb=\"xs\">\n <Text weight={500}>{course.title}</Text>", "score": 9.183927603706982 } ]
typescript
Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
import '@logseq/libs'; import { OpenAI } from 'langchain/llms/openai'; import { PromptTemplate } from 'langchain/prompts'; import { CustomListOutputParser, StructuredOutputParser, } from 'langchain/output_parsers'; import * as presetPrompts from './prompts'; import { IPrompt, PromptOutputType } from './prompts/type'; import settings, { ISettings } from './settings'; import { getBlockContent } from './utils'; function getPrompts() { const { customPrompts } = logseq.settings as unknown as ISettings; const prompts = [...Object.values(presetPrompts)]; if (customPrompts.enable) { prompts.push(...customPrompts.prompts); } return prompts; } function main() { const { apiKey, basePath, model: modelName, tag: tagName, } = logseq.settings as unknown as ISettings; const tag = ` #${tagName}`; const prompts = getPrompts(); const model = new OpenAI( { openAIApiKey: apiKey, modelName, }, { basePath }, ); prompts.map(({ name, prompt: t, output, format }: IPrompt) => { logseq.Editor.registerSlashCommand( name, async ({ uuid }: { uuid: string }) => { const block = await logseq.Editor.getBlock(uuid, { includeChildren: true, }); if (!block) { return; } const content = await getBlockContent(block); const listed = Array.isArray(format); const structured = typeof format === 'object' && !listed; let parser; if (structured) { parser = StructuredOutputParser.fromNamesAndDescriptions( format as { [key: string]: string }, ); } else if (listed) { parser = new CustomListOutputParser({ separator: '\n' }); } const template = t.replace('{{text}}', '{content}'); const prompt = parser ? new PromptTemplate({ template: template + '\n{format_instructions}', inputVariables: ['content'], partialVariables: { format_instructions: parser.getFormatInstructions(), }, }) : new PromptTemplate({ template, inputVariables: ['content'], }); const input = await prompt.format({ content }); const response = await model.call(input); switch (output) { case PromptOutputType.property: { let content = `${block?.content}${tag}\n`; if (!parser) { content += `${name.toLowerCase()}:: ${response}`; } else if (structured) { content += `${name.toLowerCase()}:: `; const record = await parser.parse(response); content += Object.entries(record) .map(([key, value]) => `${key}: ${value}`) .join(' '); } else if (listed) { content += `${name.toLowerCase()}:: `; const list = (await parser.parse(response)) as string[]; content += list.join(', '); } await logseq.Editor.updateBlock(uuid, content); break; } case PromptOutputType.insert: { if (!parser) { await logseq.Editor.insertBlock(uuid, `${response}${tag}`); } else if (structured) { const record = await parser.parse(response); await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); for await (const [key, value] of Object.entries(record)) { await logseq.Editor.insertBlock(uuid, `${key}: ${value}`); } } else if (listed) { await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); const record = (await parser.parse(response)) as string[]; for await (const item of record) { await logseq.Editor.insertBlock(uuid, item); } } break; } case PromptOutputType.replace: await logseq.Editor.updateBlock(uuid, `${response}${tag}`); break; } }, ); logseq.onSettingsChanged(() => main()); }); }
logseq.useSettingsSchema(settings).ready(main).catch(console.error);
src/main.tsx
ahonn-logseq-plugin-ai-assistant-b7a08df
[ { "filename": "src/settings.ts", "retrieved_chunk": "import { SettingSchemaDesc } from '@logseq/libs/dist/LSPlugin.user';\nimport { IPrompt } from './prompts/type';\nexport interface ISettings {\n apiKey: string;\n basePath: string;\n model: string;\n tag: string;\n customPrompts: {\n enable: boolean;\n prompts: IPrompt[];", "score": 7.607169196730966 }, { "filename": "src/utils.ts", "retrieved_chunk": "import { BlockEntity } from '@logseq/libs/dist/LSPlugin.user';\nexport async function getBlockContent(block: BlockEntity) {\n let content = block.content ?? '';\n const childrens = [block.children];\n let level = 1;\n while (childrens.length > 0) {\n const children = childrens.shift();\n for (const child of children!) {\n content += '\\n' + '\\t'.repeat(level) + '- ' + (child as BlockEntity).content;\n }", "score": 4.348150675223977 }, { "filename": "src/settings.ts", "retrieved_chunk": " },\n];\nexport default settings;", "score": 3.4632638711433077 }, { "filename": "src/settings.ts", "retrieved_chunk": " };\n}\nconst settings: SettingSchemaDesc[] = [\n {\n key: 'apiKey',\n type: 'string',\n title: 'API Key',\n description: 'Enter your OpenAI API key.',\n default: '',\n },", "score": 2.4015333413037534 }, { "filename": "src/prompts/type.ts", "retrieved_chunk": "export interface IPrompt {\n name: string;\n prompt: string;\n output: PromptOutputType;\n format?: string | [] | { [key: string]: string };\n}\nexport enum PromptOutputType {\n property = 'property',\n replace = 'replace',\n insert = 'insert',", "score": 1.822524619400299 } ]
typescript
logseq.useSettingsSchema(settings).ready(main).catch(console.error);
import '@logseq/libs'; import { OpenAI } from 'langchain/llms/openai'; import { PromptTemplate } from 'langchain/prompts'; import { CustomListOutputParser, StructuredOutputParser, } from 'langchain/output_parsers'; import * as presetPrompts from './prompts'; import { IPrompt, PromptOutputType } from './prompts/type'; import settings, { ISettings } from './settings'; import { getBlockContent } from './utils'; function getPrompts() { const { customPrompts } = logseq.settings as unknown as ISettings; const prompts = [...Object.values(presetPrompts)]; if (customPrompts.enable) { prompts.push(...customPrompts.prompts); } return prompts; } function main() { const { apiKey, basePath, model: modelName, tag: tagName, } = logseq.settings as unknown as ISettings; const tag = ` #${tagName}`; const prompts = getPrompts(); const model = new OpenAI( { openAIApiKey: apiKey, modelName, }, { basePath }, ); prompts.map(({ name, prompt: t, output, format }: IPrompt) => { logseq.Editor.registerSlashCommand( name, async ({ uuid }: { uuid: string }) => { const block = await logseq.Editor.getBlock(uuid, { includeChildren: true, }); if (!block) { return; } const content = await getBlockContent(block); const listed = Array.isArray(format); const structured = typeof format === 'object' && !listed; let parser; if (structured) { parser = StructuredOutputParser.fromNamesAndDescriptions( format as { [key: string]: string }, ); } else if (listed) { parser = new CustomListOutputParser({ separator: '\n' }); } const template = t.replace('{{text}}', '{content}'); const prompt = parser ? new PromptTemplate({ template: template + '\n{format_instructions}', inputVariables: ['content'], partialVariables: { format_instructions: parser.getFormatInstructions(), }, }) : new PromptTemplate({ template, inputVariables: ['content'], }); const input = await prompt.format({ content }); const response = await model.call(input); switch (output) {
case PromptOutputType.property: {
let content = `${block?.content}${tag}\n`; if (!parser) { content += `${name.toLowerCase()}:: ${response}`; } else if (structured) { content += `${name.toLowerCase()}:: `; const record = await parser.parse(response); content += Object.entries(record) .map(([key, value]) => `${key}: ${value}`) .join(' '); } else if (listed) { content += `${name.toLowerCase()}:: `; const list = (await parser.parse(response)) as string[]; content += list.join(', '); } await logseq.Editor.updateBlock(uuid, content); break; } case PromptOutputType.insert: { if (!parser) { await logseq.Editor.insertBlock(uuid, `${response}${tag}`); } else if (structured) { const record = await parser.parse(response); await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); for await (const [key, value] of Object.entries(record)) { await logseq.Editor.insertBlock(uuid, `${key}: ${value}`); } } else if (listed) { await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); const record = (await parser.parse(response)) as string[]; for await (const item of record) { await logseq.Editor.insertBlock(uuid, item); } } break; } case PromptOutputType.replace: await logseq.Editor.updateBlock(uuid, `${response}${tag}`); break; } }, ); logseq.onSettingsChanged(() => main()); }); } logseq.useSettingsSchema(settings).ready(main).catch(console.error);
src/main.tsx
ahonn-logseq-plugin-ai-assistant-b7a08df
[ { "filename": "src/prompts/type.ts", "retrieved_chunk": "export interface IPrompt {\n name: string;\n prompt: string;\n output: PromptOutputType;\n format?: string | [] | { [key: string]: string };\n}\nexport enum PromptOutputType {\n property = 'property',\n replace = 'replace',\n insert = 'insert',", "score": 5.926364617781214 }, { "filename": "src/prompts/summarize.ts", "retrieved_chunk": "import { IPrompt, PromptOutputType } from './type';\nexport const Summarize: IPrompt = {\n name: 'Summarize',\n prompt: `\n Please provide a concise summary of the following text:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.property,", "score": 4.906717917446647 }, { "filename": "src/prompts/generate-ideas.ts", "retrieved_chunk": " format: [],\n};", "score": 3.6967423343664523 }, { "filename": "src/utils.ts", "retrieved_chunk": "import { BlockEntity } from '@logseq/libs/dist/LSPlugin.user';\nexport async function getBlockContent(block: BlockEntity) {\n let content = block.content ?? '';\n const childrens = [block.children];\n let level = 1;\n while (childrens.length > 0) {\n const children = childrens.shift();\n for (const child of children!) {\n content += '\\n' + '\\t'.repeat(level) + '- ' + (child as BlockEntity).content;\n }", "score": 3.0787002358025424 }, { "filename": "src/prompts/generate-ideas.ts", "retrieved_chunk": "import { IPrompt, PromptOutputType } from \"./type\";\nexport const GenerateIdeas: IPrompt = {\n name: 'Generate Ideas',\n prompt: `\n Please creative ideas related to the following topic:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.insert,", "score": 2.863177123914882 } ]
typescript
case PromptOutputType.property: {
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const
cookie = parseCookie(request.headers.get("Cookie") || "");
const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " const blobRequestBody = await request.blob();\n // We can safely assume the incoming request body is always text data\n const rawBody: string = await blobRequestBody.text();\n // For Request URL verification\n if (rawBody.includes(\"ssl_check=\")) {\n // Slack does not send the x-slack-signature header for this pattern.\n // Thus, we need to check the pattern before verifying a request.\n const bodyParams = new URLSearchParams(rawBody);\n if (bodyParams.get(\"ssl_check\") === \"1\" && bodyParams.get(\"token\")) {\n return new Response(\"\", { status: 200 });", "score": 29.63560323714361 }, { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " const request: Request = new Request(ws.url, {\n method: \"POST\",\n headers: new Headers({ \"content-type\": \"application/json\" }),\n body: new Blob([payload]).stream(),\n });\n const context: ExecutionContext = {\n // deno-lint-ignore require-await\n waitUntil: async (promise) => {\n promise\n .then((res) => {", "score": 29.53017056350518 }, { "filename": "src/request/request-verification.ts", "retrieved_chunk": "export async function verifySlackRequest(\n signingSecret: string,\n requsetHeaders: Headers,\n requestBody: string\n) {\n const timestampHeader = requsetHeaders.get(\"x-slack-request-timestamp\");\n if (!timestampHeader) {\n console.log(\"x-slack-request-timestamp header is missing!\");\n return false;\n }", "score": 27.894144108186552 }, { "filename": "src/app.ts", "retrieved_chunk": " }\n }\n // Verify the request headers and body\n const isRequestSignatureVerified =\n this.socketMode ||\n (await verifySlackRequest(this.signingSecret, request.headers, rawBody));\n if (isRequestSignatureVerified) {\n // deno-lint-ignore no-explicit-any\n const body: Record<string, any> = await parseRequestBody(\n request.headers,", "score": 26.011553473682863 }, { "filename": "src/app.ts", "retrieved_chunk": " // deno-lint-ignore no-unused-vars\n } catch (e) {\n // Ignore an exception here\n }\n const retryReason =\n request.headers.get(\"x-slack-retry-reason\") ?? body.retry_reason;\n const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = {\n body,\n rawBody,\n retryNum,", "score": 24.109787699461094 } ]
typescript
cookie = parseCookie(request.headers.get("Cookie") || "");
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState ||
!(await this.stateStore.consume(queryState)) ) {
if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " const blobRequestBody = await request.blob();\n // We can safely assume the incoming request body is always text data\n const rawBody: string = await blobRequestBody.text();\n // For Request URL verification\n if (rawBody.includes(\"ssl_check=\")) {\n // Slack does not send the x-slack-signature header for this pattern.\n // Thus, we need to check the pattern before verifying a request.\n const bodyParams = new URLSearchParams(rawBody);\n if (bodyParams.get(\"ssl_check\") === \"1\" && bodyParams.get(\"token\")) {\n return new Response(\"\", { status: 200 });", "score": 30.200165191109004 }, { "filename": "src/app.ts", "retrieved_chunk": " }\n }\n // Verify the request headers and body\n const isRequestSignatureVerified =\n this.socketMode ||\n (await verifySlackRequest(this.signingSecret, request.headers, rawBody));\n if (isRequestSignatureVerified) {\n // deno-lint-ignore no-explicit-any\n const body: Record<string, any> = await parseRequestBody(\n request.headers,", "score": 29.693222842433347 }, { "filename": "src/authorization/single-team-authorize.ts", "retrieved_chunk": " const client = new SlackAPIClient(botToken);\n try {\n const response: AuthTestResponse = await client.auth.test();\n const scopes = response.headers.get(\"x-oauth-scopes\") ?? \"\";\n return {\n botToken,\n enterpriseId: response.enterprise_id,\n teamId: response.team_id,\n team: response.team,\n url: response.url,", "score": 27.508335355462094 }, { "filename": "src/app.ts", "retrieved_chunk": " retryReason,\n context: builtBaseContext(body),\n env: this.env,\n headers: request.headers,\n };\n if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {\n console.log(`*** Received request body ***\\n ${prettyPrint(body)}`);\n }\n for (const middlware of this.preAuthorizeMiddleware) {\n const response = await middlware(preAuthorizeRequest);", "score": 25.906567676649985 }, { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " const request: Request = new Request(ws.url, {\n method: \"POST\",\n headers: new Headers({ \"content-type\": \"application/json\" }),\n body: new Blob([payload]).stream(),\n });\n const context: ExecutionContext = {\n // deno-lint-ignore require-await\n waitUntil: async (promise) => {\n promise\n .then((res) => {", "score": 24.414775807389542 } ]
typescript
!(await this.stateStore.consume(queryState)) ) {
import { SlackAPIClient, isDebugLogEnabled } from "slack-web-api-client"; import { SlackApp } from "../app"; import { ConfigError, SocketModeError } from "../errors"; import { ExecutionContext } from "../execution-context"; import { SlackSocketModeAppEnv } from "../app-env"; // TODO: Implement proper reconnection logic // TODO: Add connection monitor like 1st party SDKs do // TODO: Add Bun support (the runtime does not work well with Socket Mode) export class SocketModeClient { public app: SlackApp<SlackSocketModeAppEnv>; public appLevelToken: string; public ws: WebSocket | undefined; constructor( // deno-lint-ignore no-explicit-any app: SlackApp<any> ) { if (!app.socketMode) { throw new ConfigError( "socketMode: true must be set for running with Socket Mode" ); } if (!app.appLevelToken) { throw new ConfigError( "appLevelToken must be set for running with Socket Mode" ); } this.app = app as SlackApp<SlackSocketModeAppEnv>; this.appLevelToken = app.appLevelToken; console.warn( "WARNING: The Socket Mode support provided by slack-edge is still experimental and is not designed to handle reconnections for production-grade applications. It is recommended to use this mode only for local development and testing purposes." ); } async connect() { const client = new SlackAPIClient(this.appLevelToken); try { const newConnection = await client.apps.connections.open(); this.ws = new WebSocket(newConnection.url!); } catch (e) { throw new SocketModeError( `Failed to establish a new WSS connection: ${e}` ); } if (this.ws) { const ws = this.ws; // deno-lint-ignore require-await ws.onopen = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `Now the Socket Mode client is connected to Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onclose = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `The Socket Mode client is disconnected from Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onerror = async (e) => { // TODO: make this customizable console.error( `An error was thrown by the Socket Mode connection: ${e}` ); }; const app = this.app; ws.onmessage = async (ev) => { try { if ( ev.data && typeof ev.data === "string" && ev.data.startsWith("{") ) { const data = JSON.parse(ev.data); if (data.type === "hello") { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received hello data ***\n ${ev.data}`); } return; } const payload = JSON.stringify(data.payload); console.log(payload); const request: Request = new Request(ws.url, { method: "POST", headers: new Headers({ "content-type": "application/json" }), body: new Blob([payload]).stream(), }); const context: ExecutionContext = { // deno-lint-ignore require-await waitUntil: async (promise) => { promise .then
((res) => {
console.info(`Completed a lazy listener execution: ${res}`); }) .catch((err) => { console.error(`Failed to run a lazy listener: ${err}`); }); }, }; const response = await app.run(request, context); // deno-lint-ignore no-explicit-any let ack: any = { envelope_id: data.envelope_id }; if (response.body) { const contentType = response.headers.get("Content-Type"); if (contentType && contentType.startsWith("text/plain")) { const text = await response.text(); ack = { envelope_id: data.envelope_id, payload: { text } }; } else { const json = await response.json(); ack = { envelope_id: data.envelope_id, payload: { ...json } }; } } ws.send(JSON.stringify(ack)); } else { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received non-JSON data ***\n ${ev.data}`); } } } catch (e) { console.error(`Failed to handle a WebSocke message: ${e}`); } }; } } // deno-lint-ignore require-await async disconnect(): Promise<void> { if (this.ws) { this.ws.close(); this.ws = undefined; } } }
src/socket-mode/socket-mode-client.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/request-parser.ts", "retrieved_chunk": "// deno-lint-ignore require-await\nexport async function parseRequestBody(\n requestHeaders: Headers,\n requestBody: string\n): // deno-lint-ignore no-explicit-any\nPromise<Record<string, any>> {\n const contentType = requestHeaders.get(\"content-type\");\n if (\n contentType?.startsWith(\"application/json\") ||\n requestBody.startsWith(\"{\")", "score": 34.69371577073391 }, { "filename": "src/execution-context.ts", "retrieved_chunk": "export class NoopExecutionContext implements ExecutionContext {\n // deno-lint-ignore no-explicit-any\n waitUntil(promise: Promise<any>): void {\n promise.catch((reason) => {\n console.error(`Failed to run a lazy listener: ${reason}`);\n });\n }\n}", "score": 28.34785064958022 }, { "filename": "src/app.ts", "retrieved_chunk": " const client = new SlackAPIClient(context.botToken);\n context.say = async (params) =>\n await client.chat.postMessage({\n channel: context.channelId,\n ...params,\n });\n }\n if (authorizedContext.responseUrl) {\n const responseUrl = authorizedContext.responseUrl;\n // deno-lint-ignore require-await", "score": 27.19911380310148 }, { "filename": "src/oauth/callback.ts", "retrieved_chunk": "// deno-lint-ignore require-await\nexport const defaultOnFailure = async (\n startPath: string,\n reason: OAuthErrorCode,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {\n return new Response(renderErrorPage(startPath, reason), {\n status: 400,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },", "score": 23.847197770196377 }, { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": "import { PreAuthorizeMiddleware, Middleware } from \"./middleware\";\n// deno-lint-ignore require-await\nexport const urlVerification: PreAuthorizeMiddleware = async (req) => {\n if (req.body.type === \"url_verification\") {\n return { status: 200, body: req.body.challenge };\n }\n};\nconst eventTypesToKeep = [\"member_joined_channel\", \"member_left_channel\"];\n// deno-lint-ignore require-await\nexport const ignoringSelfEvents: Middleware = async (req) => {", "score": 23.820492936833524 } ]
typescript
((res) => {
// Copyright 2022 - 2023 The MathWorks, Inc. import { TextDocument } from 'vscode-languageserver-textdocument' import Indexer from './Indexer' import FileInfoIndex from './FileInfoIndex' const INDEXING_DELAY = 500 // Delay (in ms) after keystroke before attempting to re-index the document /** * Handles indexing a currently open document to gather data about classes, * functions, and variables. */ class DocumentIndexer { private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>() /** * Queues a document to be indexed. This handles debouncing so that * indexing is not performed on every keystroke. * * @param textDocument The document to be indexed */ queueIndexingForDocument (textDocument: TextDocument): void { const uri = textDocument.uri this.clearTimerForDocumentUri(uri) this.pendingFilesToIndex.set( uri, setTimeout(() => { this.indexDocument(textDocument) }, INDEXING_DELAY) // Specify timeout for debouncing, to avoid re-indexing every keystroke while a user types ) } /** * Indexes the document and caches the data. * * @param textDocument The document being indexed */ indexDocument (textDocument: TextDocument): void {
void Indexer.indexDocument(textDocument) }
/** * Clears any active indexing timers for the provided document URI. * * @param uri The document URI */ private clearTimerForDocumentUri (uri: string): void { const timerId = this.pendingFilesToIndex.get(uri) if (timerId != null) { clearTimeout(timerId) this.pendingFilesToIndex.delete(uri) } } /** * Ensure that @param textDocument is fully indexed and up to date by flushing any pending indexing tasks * and then forcing an index. This is intended to service requests like documentSymbols where returning * stale info could be confusing. * * @param textDocument The document to index */ async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> { const uri = textDocument.uri if (this.pendingFilesToIndex.has(uri)) { this.clearTimerForDocumentUri(uri) await Indexer.indexDocument(textDocument) } if (!FileInfoIndex.codeDataCache.has(uri)) { await Indexer.indexDocument(textDocument) } } } export default new DocumentIndexer()
src/indexing/DocumentIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the given TextDocument and caches the data.\n *\n * @param textDocument The document being indexed\n */\n async indexDocument (textDocument: TextDocument): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const rawCodeData = await this.getCodeData(textDocument.getText(), textDocument.uri, matlabConnection)", "score": 51.67519755391049 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " setTimeout(() => {\n void this.lintDocument(textDocument, connection)\n }, LINT_DELAY) // Specify timeout for debouncing, to avoid re-linting every keystroke while a user types\n )\n }\n /**\n * Lints the document and displays diagnostics.\n *\n * @param textDocument The document being linted\n * @param connection The language server connection", "score": 25.532020419178103 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 25.026261715098855 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " * that linting is not performed on every keystroke.\n *\n * @param textDocument The document to be linted\n * @param connection The language server connection\n */\n queueLintingForDocument (textDocument: TextDocument, connection: _Connection): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this._pendingFilesToLint.set(\n uri,", "score": 23.032289389982935 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " const parsedCodeData = FileInfoIndex.parseAndStoreCodeData(textDocument.uri, rawCodeData)\n void this.indexAdditionalClassData(parsedCodeData, matlabConnection, textDocument.uri)\n }\n /**\n * Indexes all M files within the given list of folders.\n *\n * @param folders A list of folder URIs to be indexed\n */\n indexFolders (folders: string[]): void {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()", "score": 22.383797525398798 } ]
typescript
void Indexer.indexDocument(textDocument) }
import { SlackAPIClient, isDebugLogEnabled } from "slack-web-api-client"; import { SlackApp } from "../app"; import { ConfigError, SocketModeError } from "../errors"; import { ExecutionContext } from "../execution-context"; import { SlackSocketModeAppEnv } from "../app-env"; // TODO: Implement proper reconnection logic // TODO: Add connection monitor like 1st party SDKs do // TODO: Add Bun support (the runtime does not work well with Socket Mode) export class SocketModeClient { public app: SlackApp<SlackSocketModeAppEnv>; public appLevelToken: string; public ws: WebSocket | undefined; constructor( // deno-lint-ignore no-explicit-any app: SlackApp<any> ) { if (!app.socketMode) { throw new ConfigError( "socketMode: true must be set for running with Socket Mode" ); } if (!app.appLevelToken) { throw new ConfigError( "appLevelToken must be set for running with Socket Mode" ); } this.app = app as SlackApp<SlackSocketModeAppEnv>; this.appLevelToken = app.appLevelToken; console.warn( "WARNING: The Socket Mode support provided by slack-edge is still experimental and is not designed to handle reconnections for production-grade applications. It is recommended to use this mode only for local development and testing purposes." ); } async connect() { const client = new SlackAPIClient(this.appLevelToken); try { const newConnection = await client.apps.connections.open(); this.ws = new WebSocket(newConnection.url!); } catch (e) { throw new SocketModeError( `Failed to establish a new WSS connection: ${e}` ); } if (this.ws) { const ws = this.ws; // deno-lint-ignore require-await ws.onopen = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `Now the Socket Mode client is connected to Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onclose = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `The Socket Mode client is disconnected from Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onerror = async (e) => { // TODO: make this customizable console.error( `An error was thrown by the Socket Mode connection: ${e}` ); }; const app = this.app; ws.onmessage = async (ev) => { try { if ( ev.data && typeof ev.data === "string" && ev.data.startsWith("{") ) { const data = JSON.parse(ev.data); if (data.type === "hello") { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received hello data ***\n ${ev.data}`); } return; } const payload = JSON.stringify(data.payload); console.log(payload); const request: Request = new Request(ws.url, { method: "POST", headers: new Headers({ "content-type": "application/json" }), body: new Blob([payload]).stream(), }); const context: ExecutionContext = { // deno-lint-ignore require-await
waitUntil: async (promise) => {
promise .then((res) => { console.info(`Completed a lazy listener execution: ${res}`); }) .catch((err) => { console.error(`Failed to run a lazy listener: ${err}`); }); }, }; const response = await app.run(request, context); // deno-lint-ignore no-explicit-any let ack: any = { envelope_id: data.envelope_id }; if (response.body) { const contentType = response.headers.get("Content-Type"); if (contentType && contentType.startsWith("text/plain")) { const text = await response.text(); ack = { envelope_id: data.envelope_id, payload: { text } }; } else { const json = await response.json(); ack = { envelope_id: data.envelope_id, payload: { ...json } }; } } ws.send(JSON.stringify(ack)); } else { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received non-JSON data ***\n ${ev.data}`); } } } catch (e) { console.error(`Failed to handle a WebSocke message: ${e}`); } }; } } // deno-lint-ignore require-await async disconnect(): Promise<void> { if (this.ws) { this.ws.close(); this.ws = undefined; } } }
src/socket-mode/socket-mode-client.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/request-parser.ts", "retrieved_chunk": " ) {\n return JSON.parse(requestBody);\n }\n const params = new URLSearchParams(requestBody);\n if (params.has(\"payload\")) {\n const payload = params.get(\"payload\")!;\n return JSON.parse(payload);\n }\n // deno-lint-ignore no-explicit-any\n const formBody: any = {};", "score": 46.14180958064287 }, { "filename": "src/request/request-parser.ts", "retrieved_chunk": "// deno-lint-ignore require-await\nexport async function parseRequestBody(\n requestHeaders: Headers,\n requestBody: string\n): // deno-lint-ignore no-explicit-any\nPromise<Record<string, any>> {\n const contentType = requestHeaders.get(\"content-type\");\n if (\n contentType?.startsWith(\"application/json\") ||\n requestBody.startsWith(\"{\")", "score": 37.55438544971695 }, { "filename": "src/oauth-app.ts", "retrieved_chunk": " async run(\n request: Request,\n ctx: ExecutionContext = new NoopExecutionContext()\n ): Promise<Response> {\n const url = new URL(request.url);\n if (request.method === \"GET\") {\n if (url.pathname === this.routes.oauth.start) {\n return await this.handleOAuthStartRequest(request);\n } else if (url.pathname === this.routes.oauth.callback) {\n return await this.handleOAuthCallbackRequest(request);", "score": 36.021462482809945 }, { "filename": "src/app.ts", "retrieved_chunk": " payload: body.event,\n ...baseRequest,\n };\n for (const matcher of this.#events) {\n const handler = matcher(payload);\n if (handler) {\n ctx.waitUntil(handler.lazy(slackRequest));\n const slackResponse = await handler.ack(slackRequest);\n if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {\n console.log(", "score": 34.23076206404129 }, { "filename": "src/oauth/callback.ts", "retrieved_chunk": "// deno-lint-ignore require-await\nexport const defaultOnFailure = async (\n startPath: string,\n reason: OAuthErrorCode,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {\n return new Response(renderErrorPage(startPath, reason), {\n status: 400,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },", "score": 33.96016236689685 } ]
typescript
waitUntil: async (promise) => {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return }
Indexer.indexFolders(folders.map(folder => folder.uri)) }
/** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> { const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace } } export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " const parsedCodeData = FileInfoIndex.parseAndStoreCodeData(textDocument.uri, rawCodeData)\n void this.indexAdditionalClassData(parsedCodeData, matlabConnection, textDocument.uri)\n }\n /**\n * Indexes all M files within the given list of folders.\n *\n * @param folders A list of folder URIs to be indexed\n */\n indexFolders (folders: string[]): void {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()", "score": 37.03987823294445 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " async getConfiguration (): Promise<Settings> {\n if (this.hasConfigurationCapability) {\n if (this.configuration == null) {\n this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings\n }\n return this.configuration\n }\n return this.globalSettings\n }\n /**", "score": 19.246351294960313 }, { "filename": "src/indexing/DocumentIndexer.ts", "retrieved_chunk": " * stale info could be confusing.\n *\n * @param textDocument The document to index\n */\n async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> {\n const uri = textDocument.uri\n if (this.pendingFilesToIndex.has(uri)) {\n this.clearTimerForDocumentUri(uri)\n await Indexer.indexDocument(textDocument)\n }", "score": 16.868275818346852 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " */\n async getOrCreateMatlabConnection (connection: _Connection): Promise<MatlabConnection | null> {\n // Check if there is already an active connection\n const activeConnection = this.getMatlabConnection()\n if (activeConnection != null) {\n return activeConnection\n }\n // No active connection - should create a connection if desired\n if (!(await this._isMatlabConnectionTimingNever())) {\n const matlabProcess = await this.connectToMatlab(connection)", "score": 15.810800957580923 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " // Convert file path to URI, which is used as an index when storing the code data\n const fileUri = URI.file(fileResults.filePath).toString()\n FileInfoIndex.parseAndStoreCodeData(fileUri, fileResults.codeData)\n })\n matlabConnection.publish(this.INDEX_FOLDERS_REQUEST_CHANNEL, {\n folders,\n requestId\n })\n }\n /**", "score": 14.171032206182337 } ]
typescript
Indexer.indexFolders(folders.map(folder => folder.uri)) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { TextDocument } from 'vscode-languageserver-textdocument' import Indexer from './Indexer' import FileInfoIndex from './FileInfoIndex' const INDEXING_DELAY = 500 // Delay (in ms) after keystroke before attempting to re-index the document /** * Handles indexing a currently open document to gather data about classes, * functions, and variables. */ class DocumentIndexer { private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>() /** * Queues a document to be indexed. This handles debouncing so that * indexing is not performed on every keystroke. * * @param textDocument The document to be indexed */ queueIndexingForDocument (textDocument: TextDocument): void { const uri = textDocument.uri this.clearTimerForDocumentUri(uri) this.pendingFilesToIndex.set( uri, setTimeout(() => { this.indexDocument(textDocument) }, INDEXING_DELAY) // Specify timeout for debouncing, to avoid re-indexing every keystroke while a user types ) } /** * Indexes the document and caches the data. * * @param textDocument The document being indexed */ indexDocument (textDocument: TextDocument): void { void
Indexer.indexDocument(textDocument) }
/** * Clears any active indexing timers for the provided document URI. * * @param uri The document URI */ private clearTimerForDocumentUri (uri: string): void { const timerId = this.pendingFilesToIndex.get(uri) if (timerId != null) { clearTimeout(timerId) this.pendingFilesToIndex.delete(uri) } } /** * Ensure that @param textDocument is fully indexed and up to date by flushing any pending indexing tasks * and then forcing an index. This is intended to service requests like documentSymbols where returning * stale info could be confusing. * * @param textDocument The document to index */ async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> { const uri = textDocument.uri if (this.pendingFilesToIndex.has(uri)) { this.clearTimerForDocumentUri(uri) await Indexer.indexDocument(textDocument) } if (!FileInfoIndex.codeDataCache.has(uri)) { await Indexer.indexDocument(textDocument) } } } export default new DocumentIndexer()
src/indexing/DocumentIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the given TextDocument and caches the data.\n *\n * @param textDocument The document being indexed\n */\n async indexDocument (textDocument: TextDocument): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const rawCodeData = await this.getCodeData(textDocument.getText(), textDocument.uri, matlabConnection)", "score": 51.67519755391049 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " setTimeout(() => {\n void this.lintDocument(textDocument, connection)\n }, LINT_DELAY) // Specify timeout for debouncing, to avoid re-linting every keystroke while a user types\n )\n }\n /**\n * Lints the document and displays diagnostics.\n *\n * @param textDocument The document being linted\n * @param connection The language server connection", "score": 25.532020419178103 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 25.026261715098855 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " * that linting is not performed on every keystroke.\n *\n * @param textDocument The document to be linted\n * @param connection The language server connection\n */\n queueLintingForDocument (textDocument: TextDocument, connection: _Connection): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this._pendingFilesToLint.set(\n uri,", "score": 23.032289389982935 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " const parsedCodeData = FileInfoIndex.parseAndStoreCodeData(textDocument.uri, rawCodeData)\n void this.indexAdditionalClassData(parsedCodeData, matlabConnection, textDocument.uri)\n }\n /**\n * Indexes all M files within the given list of folders.\n *\n * @param folders A list of folder URIs to be indexed\n */\n indexFolders (folders: string[]): void {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()", "score": 22.383797525398798 } ]
typescript
Indexer.indexDocument(textDocument) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> { const shouldIndexWorkspace = (
await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
} export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " *\n * @returns True if the MATLAB connection timing setting is set to never. Returns false otherwise.\n */\n private async _isMatlabConnectionTimingNever (): Promise<boolean> {\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n return connectionTiming === ConnectionTiming.Never\n }\n}\n/**\n * Represents a MATLAB process", "score": 38.905834241458194 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": " boolean: true,\n default: false,\n description: 'Whether or not the user\\'s workspace should be indexed.',\n requiresArg: false\n }).option(Argument.MatlabUrl, {\n type: 'string',\n description: 'URL for communicating with an existing MATLAB instance',\n requiresArg: true\n }).usage(\n 'Usage: $0 {--node-ipc | --stdio | --socket=socket} options\\n' +", "score": 29.77164702537801 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " async getConfiguration (): Promise<Settings> {\n if (this.hasConfigurationCapability) {\n if (this.configuration == null) {\n this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings\n }\n return this.configuration\n }\n return this.globalSettings\n }\n /**", "score": 28.756435457526504 }, { "filename": "src/providers/navigation/NavigationSupportProvider.ts", "retrieved_chunk": " }\n /**\n * Determines whether the given function should be visible from the given file URI.\n * The function is visible if it is contained within the same file, or is public.\n *\n * @param uri The file's URI\n * @param funcData The function data\n * @returns true if the function should be visible from the given URI; false otherwise\n */\n private isFunctionVisibleFromUri (uri: string, funcData: MatlabFunctionInfo): boolean {", "score": 24.94122244876444 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " }\n /**\n * Gets the command with which MATLAB should be launched.\n *\n * @param outFile The file in which MATLAB should output connection details\n * @returns The matlab launch command\n */\n private async _getMatlabLaunchCommand (outFile: string): Promise<{ command: string, args: string[] }> {\n const matlabInstallPath = (await ConfigurationManager.getConfiguration()).installPath\n let command = 'matlab'", "score": 24.780613337319295 } ]
typescript
await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.
onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
/** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 38.11050266142217 }, { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " private isWorkspaceIndexingSupported = false\n /**\n * Sets up workspace change listeners, if supported.\n *\n * @param capabilities The client capabilities, which contains information about\n * whether the client supports workspaces.\n */\n setupCallbacks (capabilities: ClientCapabilities): void {\n this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false\n if (!this.isWorkspaceIndexingSupported) {", "score": 34.49481932911889 }, { "filename": "src/server.ts", "retrieved_chunk": " triggerCharacters: ['(', ',']\n },\n documentSymbolProvider: true\n }\n }\n return initResult\n})\n// Handles the initialized notification\nconnection.onInitialized(() => {\n ConfigurationManager.setup(capabilities)", "score": 22.888189385662667 }, { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " // Workspace indexing not supported\n return\n }\n connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => {\n void this.handleWorkspaceFoldersAdded(params.added)\n })\n }\n /**\n * Attempts to index the files in the user's workspace.\n */", "score": 21.49695682983848 }, { "filename": "src/server.ts", "retrieved_chunk": "documentManager.onDidSave(params => {\n void LintingSupportProvider.lintDocument(params.document, connection)\n})\n// Handles changes to the text document\ndocumentManager.onDidChangeContent(params => {\n if (MatlabLifecycleManager.isMatlabReady()) {\n // Only want to lint on content changes when linting is being backed by MATLAB\n LintingSupportProvider.queueLintingForDocument(params.document, connection)\n DocumentIndexer.queueIndexingForDocument(params.document)\n }", "score": 21.361911256669 } ]
typescript
onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> {
const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
} export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": " boolean: true,\n default: false,\n description: 'Whether or not the user\\'s workspace should be indexed.',\n requiresArg: false\n }).option(Argument.MatlabUrl, {\n type: 'string',\n description: 'URL for communicating with an existing MATLAB instance',\n requiresArg: true\n }).usage(\n 'Usage: $0 {--node-ipc | --stdio | --socket=socket} options\\n' +", "score": 43.9896989324454 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " *\n * @returns True if the MATLAB connection timing setting is set to never. Returns false otherwise.\n */\n private async _isMatlabConnectionTimingNever (): Promise<boolean> {\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n return connectionTiming === ConnectionTiming.Never\n }\n}\n/**\n * Represents a MATLAB process", "score": 39.06787991107419 }, { "filename": "src/providers/navigation/NavigationSupportProvider.ts", "retrieved_chunk": " }\n /**\n * Determines whether the given function should be visible from the given file URI.\n * The function is visible if it is contained within the same file, or is public.\n *\n * @param uri The file's URI\n * @param funcData The function data\n * @returns true if the function should be visible from the given URI; false otherwise\n */\n private isFunctionVisibleFromUri (uri: string, funcData: MatlabFunctionInfo): boolean {", "score": 37.68476975775507 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " async getConfiguration (): Promise<Settings> {\n if (this.hasConfigurationCapability) {\n if (this.configuration == null) {\n this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings\n }\n return this.configuration\n }\n return this.globalSettings\n }\n /**", "score": 32.98200711188508 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " }\n /**\n * Gets the command with which MATLAB should be launched.\n *\n * @param outFile The file in which MATLAB should output connection details\n * @returns The matlab launch command\n */\n private async _getMatlabLaunchCommand (outFile: string): Promise<{ command: string, args: string[] }> {\n const matlabInstallPath = (await ConfigurationManager.getConfiguration()).installPath\n let command = 'matlab'", "score": 30.235512579294053 } ]
typescript
const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return } Indexer.indexFolders(folders.map
(folder => folder.uri)) }
/** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> { const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace } } export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " const parsedCodeData = FileInfoIndex.parseAndStoreCodeData(textDocument.uri, rawCodeData)\n void this.indexAdditionalClassData(parsedCodeData, matlabConnection, textDocument.uri)\n }\n /**\n * Indexes all M files within the given list of folders.\n *\n * @param folders A list of folder URIs to be indexed\n */\n indexFolders (folders: string[]): void {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()", "score": 35.24850477859459 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " async getConfiguration (): Promise<Settings> {\n if (this.hasConfigurationCapability) {\n if (this.configuration == null) {\n this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings\n }\n return this.configuration\n }\n return this.globalSettings\n }\n /**", "score": 14.616321794383966 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " // Convert file path to URI, which is used as an index when storing the code data\n const fileUri = URI.file(fileResults.filePath).toString()\n FileInfoIndex.parseAndStoreCodeData(fileUri, fileResults.codeData)\n })\n matlabConnection.publish(this.INDEX_FOLDERS_REQUEST_CHANNEL, {\n folders,\n requestId\n })\n }\n /**", "score": 14.171032206182337 }, { "filename": "src/providers/navigation/NavigationSupportProvider.ts", "retrieved_chunk": " * @returns The info about the desired function, or null if it cannot be found\n */\n private getFunctionDeclaration (codeData: MatlabCodeData, functionName: string): MatlabFunctionInfo | null {\n let functionDecl = codeData.functions.get(functionName)\n if (codeData.isClassDef && (functionDecl == null || functionDecl.isPrototype)) {\n // For classes, look in the methods list to better handle @folders\n functionDecl = codeData.classInfo?.methods.get(functionName) ?? functionDecl\n }\n return functionDecl ?? null\n }", "score": 13.485211378658375 }, { "filename": "src/indexing/DocumentIndexer.ts", "retrieved_chunk": " if (!FileInfoIndex.codeDataCache.has(uri)) {\n await Indexer.indexDocument(textDocument)\n }\n }\n}\nexport default new DocumentIndexer()", "score": 12.738627314791094 } ]
typescript
(folder => folder.uri)) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { TextDocument } from 'vscode-languageserver-textdocument' import Indexer from './Indexer' import FileInfoIndex from './FileInfoIndex' const INDEXING_DELAY = 500 // Delay (in ms) after keystroke before attempting to re-index the document /** * Handles indexing a currently open document to gather data about classes, * functions, and variables. */ class DocumentIndexer { private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>() /** * Queues a document to be indexed. This handles debouncing so that * indexing is not performed on every keystroke. * * @param textDocument The document to be indexed */ queueIndexingForDocument (textDocument: TextDocument): void { const uri = textDocument.uri this.clearTimerForDocumentUri(uri) this.pendingFilesToIndex.set( uri, setTimeout(() => { this.indexDocument(textDocument) }, INDEXING_DELAY) // Specify timeout for debouncing, to avoid re-indexing every keystroke while a user types ) } /** * Indexes the document and caches the data. * * @param textDocument The document being indexed */ indexDocument (textDocument: TextDocument): void { void Indexer.indexDocument(textDocument) } /** * Clears any active indexing timers for the provided document URI. * * @param uri The document URI */ private clearTimerForDocumentUri (uri: string): void { const timerId = this.pendingFilesToIndex.get(uri) if (timerId != null) { clearTimeout(timerId) this.pendingFilesToIndex.delete(uri) } } /** * Ensure that @param textDocument is fully indexed and up to date by flushing any pending indexing tasks * and then forcing an index. This is intended to service requests like documentSymbols where returning * stale info could be confusing. * * @param textDocument The document to index */ async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> { const uri = textDocument.uri if (this.pendingFilesToIndex.has(uri)) { this.clearTimerForDocumentUri(uri) await Indexer.indexDocument(textDocument) }
if (!FileInfoIndex.codeDataCache.has(uri)) {
await Indexer.indexDocument(textDocument) } } } export default new DocumentIndexer()
src/indexing/DocumentIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the given TextDocument and caches the data.\n *\n * @param textDocument The document being indexed\n */\n async indexDocument (textDocument: TextDocument): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const rawCodeData = await this.getCodeData(textDocument.getText(), textDocument.uri, matlabConnection)", "score": 42.86618387125171 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " * that linting is not performed on every keystroke.\n *\n * @param textDocument The document to be linted\n * @param connection The language server connection\n */\n queueLintingForDocument (textDocument: TextDocument, connection: _Connection): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this._pendingFilesToLint.set(\n uri,", "score": 41.09534611953527 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " */\n async lintDocument (textDocument: TextDocument, connection: _Connection): Promise<void> {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this.clearCodeActionsForDocumentUri(uri)\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n const isMatlabAvailable = (matlabConnection != null) && MatlabLifecycleManager.isMatlabReady()\n const fileName = URI.parse(uri).fsPath\n let lintData: string[] = []\n if (isMatlabAvailable) {", "score": 39.525723077197384 }, { "filename": "src/providers/navigation/NavigationSupportProvider.ts", "retrieved_chunk": " }\n // Ensure document index is up to date\n await DocumentIndexer.ensureDocumentIndexIsUpdated(textDocument)\n const codeData = FileInfoIndex.codeDataCache.get(uri)\n if (codeData == null) {\n reportTelemetry(requestType, 'No code data')\n return []\n }\n // Result symbols in documented\n const result: SymbolInformation[] = []", "score": 38.814942236620816 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " this._availableCodeActions.set(uri, lintResults.codeActions)\n // Report diagnostics\n void connection.sendDiagnostics({\n uri,\n diagnostics\n })\n }\n clearDiagnosticsForDocument (textDocument: TextDocument): void {\n void connection.sendDiagnostics({\n uri: textDocument.uri,", "score": 34.063062933688094 } ]
typescript
if (!FileInfoIndex.codeDataCache.has(uri)) {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void
connection.client.register(DidChangeConfigurationNotification.type) }
connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " private isWorkspaceIndexingSupported = false\n /**\n * Sets up workspace change listeners, if supported.\n *\n * @param capabilities The client capabilities, which contains information about\n * whether the client supports workspaces.\n */\n setupCallbacks (capabilities: ClientCapabilities): void {\n this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false\n if (!this.isWorkspaceIndexingSupported) {", "score": 53.897773516007945 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 42.10494127817227 }, { "filename": "src/server.ts", "retrieved_chunk": " triggerCharacters: ['(', ',']\n },\n documentSymbolProvider: true\n }\n }\n return initResult\n})\n// Handles the initialized notification\nconnection.onInitialized(() => {\n ConfigurationManager.setup(capabilities)", "score": 32.22306412674657 }, { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 23.891543139779813 }, { "filename": "src/server.ts", "retrieved_chunk": " const initResult: InitializeResult = {\n capabilities: {\n codeActionProvider: true,\n completionProvider: {\n triggerCharacters: [\n '.', // Struct/class properties, package names, etc.\n '(', // Function call\n ' ', // Command-style function call\n ',', // Function arguments\n '/', // File path", "score": 19.460023177202764 } ]
typescript
connection.client.register(DidChangeConfigurationNotification.type) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs =
getCliArgs() this.defaultConfiguration = {
installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " */\nclass MatlabProcess {\n private _matlabProcess?: ChildProcess\n private _matlabConnection: MatlabConnection | null = null\n private _matlabPid = 0\n private _isReady = false // Whether MATLAB is ready for communication\n isValid = true // Gets set to false when the process is terminated\n isExistingInstance = false\n constructor (private readonly _connection: _Connection) {}\n /**", "score": 29.02463636451273 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " *\n * Note: When MATLAB® is not connected, diagnostics are only updated when\n * the file is saved and suppressing warnings is not available.\n */\nclass LintingSupportProvider {\n private readonly LINTING_REQUEST_CHANNEL = '/matlabls/linting/request'\n private readonly LINTING_RESPONSE_CHANNEL = '/matlabls/linting/response'\n private readonly SUPPRESS_DIAGNOSTIC_REQUEST_CHANNEL = '/matlabls/linting/suppressdiagnostic/request'\n private readonly SUPPRESS_DIAGNOSTIC_RESPONSE_CHANNEL = '/matlabls/linting/suppressdiagnostic/response'\n private readonly SEVERITY_MAP = {", "score": 27.575017536703598 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " filePath: string\n codeData: RawCodeData\n}\nclass Indexer {\n private readonly INDEX_DOCUMENT_REQUEST_CHANNEL = '/matlabls/indexDocument/request'\n private readonly INDEX_DOCUMENT_RESPONSE_CHANNEL = '/matlabls/indexDocument/response/' // Needs to be appended with requestId\n private readonly INDEX_FOLDERS_REQUEST_CHANNEL = '/matlabls/indexFolders/request'\n private readonly INDEX_FOLDERS_RESPONSE_CHANNEL = '/matlabls/indexFolders/response/' // Needs to be appended with requestId\n private requestCt = 1\n /**", "score": 22.926188997418386 }, { "filename": "src/logging/Logger.ts", "retrieved_chunk": " private readonly matlabLogFile: string\n private _console: RemoteConsole | null = null\n constructor () {\n // Create Log Directory\n const pid = process.pid\n this._logDir = path.join(os.tmpdir(), `matlabls_${pid}`)\n if (fs.existsSync(this._logDir)) {\n let i = 1\n while (fs.existsSync(`${this._logDir}_${i}`)) { i++ }\n this._logDir = `${this._logDir}_${i}`", "score": 20.707720339410763 }, { "filename": "src/providers/navigation/PathResolver.ts", "retrieved_chunk": "interface ResolvedUri {\n name: string\n uri: string\n}\nclass PathResolver {\n private readonly REQUEST_CHANNEL = '/matlabls/navigation/resolvePath/request'\n private readonly RESPONSE_CHANNEL = '/matlabls/navigation/resolvePath/response'\n /**\n * Attempts to resolve the given names to the files in which the names are defined.\n * For example, 'MyClass' may be resolved to 'file:///path/to/MyClass.m'.", "score": 19.176550893632218 } ]
typescript
getCliArgs() this.defaultConfiguration = {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () {
const cliArgs = getCliArgs() this.defaultConfiguration = {
installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " */\nclass MatlabProcess {\n private _matlabProcess?: ChildProcess\n private _matlabConnection: MatlabConnection | null = null\n private _matlabPid = 0\n private _isReady = false // Whether MATLAB is ready for communication\n isValid = true // Gets set to false when the process is terminated\n isExistingInstance = false\n constructor (private readonly _connection: _Connection) {}\n /**", "score": 30.90385840565907 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " *\n * Note: When MATLAB® is not connected, diagnostics are only updated when\n * the file is saved and suppressing warnings is not available.\n */\nclass LintingSupportProvider {\n private readonly LINTING_REQUEST_CHANNEL = '/matlabls/linting/request'\n private readonly LINTING_RESPONSE_CHANNEL = '/matlabls/linting/response'\n private readonly SUPPRESS_DIAGNOSTIC_REQUEST_CHANNEL = '/matlabls/linting/suppressdiagnostic/request'\n private readonly SUPPRESS_DIAGNOSTIC_RESPONSE_CHANNEL = '/matlabls/linting/suppressdiagnostic/response'\n private readonly SEVERITY_MAP = {", "score": 29.224165058579736 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " filePath: string\n codeData: RawCodeData\n}\nclass Indexer {\n private readonly INDEX_DOCUMENT_REQUEST_CHANNEL = '/matlabls/indexDocument/request'\n private readonly INDEX_DOCUMENT_RESPONSE_CHANNEL = '/matlabls/indexDocument/response/' // Needs to be appended with requestId\n private readonly INDEX_FOLDERS_REQUEST_CHANNEL = '/matlabls/indexFolders/request'\n private readonly INDEX_FOLDERS_RESPONSE_CHANNEL = '/matlabls/indexFolders/response/' // Needs to be appended with requestId\n private requestCt = 1\n /**", "score": 24.70217365603281 }, { "filename": "src/providers/navigation/PathResolver.ts", "retrieved_chunk": "interface ResolvedUri {\n name: string\n uri: string\n}\nclass PathResolver {\n private readonly REQUEST_CHANNEL = '/matlabls/navigation/resolvePath/request'\n private readonly RESPONSE_CHANNEL = '/matlabls/navigation/resolvePath/response'\n /**\n * Attempts to resolve the given names to the files in which the names are defined.\n * For example, 'MyClass' may be resolved to 'file:///path/to/MyClass.m'.", "score": 20.87776874991923 }, { "filename": "src/logging/Logger.ts", "retrieved_chunk": " private readonly matlabLogFile: string\n private _console: RemoteConsole | null = null\n constructor () {\n // Create Log Directory\n const pid = process.pid\n this._logDir = path.join(os.tmpdir(), `matlabls_${pid}`)\n if (fs.existsSync(this._logDir)) {\n let i = 1\n while (fs.existsSync(`${this._logDir}_${i}`)) { i++ }\n this._logDir = `${this._logDir}_${i}`", "score": 20.707720339410763 } ]
typescript
const cliArgs = getCliArgs() this.defaultConfiguration = {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration
= await connection.workspace.getConfiguration('MATLAB') as Settings }
return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " }\n /**\n * Determines whether or not the workspace should be indexed.\n * The workspace should be indexed if the client supports workspaces, and if the\n * workspace indexing setting is true.\n *\n * @returns True if workspace indexing should occurr, false otherwise.\n */\n private async shouldIndexWorkspace (): Promise<boolean> {\n const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace", "score": 20.919105756782134 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " }\n /**\n * Gets the command with which MATLAB should be launched.\n *\n * @param outFile The file in which MATLAB should output connection details\n * @returns The matlab launch command\n */\n private async _getMatlabLaunchCommand (outFile: string): Promise<{ command: string, args: string[] }> {\n const matlabInstallPath = (await ConfigurationManager.getConfiguration()).installPath\n let command = 'matlab'", "score": 20.611902381136577 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " *\n * @returns True if the MATLAB connection timing setting is set to never. Returns false otherwise.\n */\n private async _isMatlabConnectionTimingNever (): Promise<boolean> {\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n return connectionTiming === ConnectionTiming.Never\n }\n}\n/**\n * Represents a MATLAB process", "score": 20.077713451956498 }, { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 18.572274976725172 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " private readonly _matlabLifecycleCallbacks: MatlabLifecycleCallback[] = []\n /**\n * Connects to MATLAB.\n *\n * @param connection The language server connection\n * @returns The MATLAB process\n */\n async connectToMatlab (connection: _Connection): Promise<MatlabProcess> {\n if (this._shouldConnectToExistingMatlab()) {\n return await this._connectToExistingMatlab(connection)", "score": 17.748998221962545 } ]
typescript
= await connection.workspace.getConfiguration('MATLAB') as Settings }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ExecuteCommandParams, Range, TextDocuments, _Connection } from 'vscode-languageserver' import { TextDocument } from 'vscode-languageserver-textdocument' import LintingSupportProvider from '../linting/LintingSupportProvider' interface LintSuppressionArgs { id: string range: Range uri: string } export const MatlabLSCommands = { MLINT_SUPPRESS_ON_LINE: 'matlabls.lint.suppress.line', MLINT_SUPPRESS_IN_FILE: 'matlabls.lint.suppress.file' } /** * Handles requests to execute commands */ class ExecuteCommandProvider { /** * Handles command execution requests. * * @param params Parameters from the onExecuteCommand request * @param documentManager The text document manager * @param connection The language server connection */ async handleExecuteCommand (params: ExecuteCommandParams, documentManager: TextDocuments<TextDocument>, connection: _Connection): Promise<void> { switch (params.command) { case MatlabLSCommands.MLINT_SUPPRESS_ON_LINE: case MatlabLSCommands.MLINT_SUPPRESS_IN_FILE: void this.handleLintingSuppression(params, documentManager, connection) } } /** * Handles command to suppress a linting diagnostic. * * @param params Parameters from the onExecuteCommand request * @param documentManager The text document manager * @param connection The language server connection */ private async handleLintingSuppression (params: ExecuteCommandParams, documentManager: TextDocuments<TextDocument>, connection: _Connection): Promise<void> { const args = params.arguments?.[0] as LintSuppressionArgs const range = args.range const uri = args.uri const doc = documentManager.get(uri) if (doc == null) { return } const shouldSuppressThroughoutFile = params.command === MatlabLSCommands.MLINT_SUPPRESS_IN_FILE LintingSupportProvider
.suppressDiagnostic(doc, range, args.id, shouldSuppressThroughoutFile) }
} export default new ExecuteCommandProvider()
src/providers/lspCommands/ExecuteCommandProvider.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/providers/completion/CompletionSupportProvider.ts", "retrieved_chunk": " * @returns An array of possible completions\n */\n async handleCompletionRequest (params: CompletionParams, documentManager: TextDocuments<TextDocument>): Promise<CompletionList> {\n const doc = documentManager.get(params.textDocument.uri)\n if (doc == null) {\n return CompletionList.create()\n }\n const completionData = await this.retrieveCompletionData(doc, params.position)\n return this.parseCompletionItems(completionData)\n }", "score": 32.63160972066508 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " /**\n * Attempt to suppress a diagnostic.\n *\n * @param textDocument The document\n * @param range The range of the diagnostic being suppress\n * @param id The diagnostic's ID\n * @param shouldSuppressThroughoutFile Whether or not to suppress the diagnostic throughout the entire file\n */\n suppressDiagnostic (textDocument: TextDocument, range: Range, id: string, shouldSuppressThroughoutFile: boolean): void {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()", "score": 32.62776805036677 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " uri\n }\n ))\n // Add suppress-in-file option\n commands.push(Command.create(\n `Suppress message ${diagnosticCode} in this file`,\n MatlabLSCommands.MLINT_SUPPRESS_IN_FILE,\n {\n id: diagnosticCode,\n range: diagnostic.range,", "score": 29.91978463845227 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " }\n const argsFromSettings = ConfigurationManager.getArgument(Argument.MatlabLaunchCommandArguments) ?? null\n if (argsFromSettings != null) {\n args.push(argsFromSettings)\n }\n return {\n command,\n args\n }\n }", "score": 28.343723323281335 }, { "filename": "src/providers/completion/CompletionSupportProvider.ts", "retrieved_chunk": " /**\n * Handles a request for function signature help.\n *\n * @param params Parameters from the onSignatureHelp request\n * @param documentManager The text document manager\n * @returns The signature help, or null if no signature help is available\n */\n async handleSignatureHelpRequest (params: SignatureHelpParams, documentManager: TextDocuments<TextDocument>): Promise<SignatureHelp | null> {\n const doc = documentManager.get(params.textDocument.uri)\n if (doc == null) {", "score": 27.480183633048416 } ]
typescript
.suppressDiagnostic(doc, range, args.id, shouldSuppressThroughoutFile) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection
.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
/** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 38.11050266142217 }, { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " private isWorkspaceIndexingSupported = false\n /**\n * Sets up workspace change listeners, if supported.\n *\n * @param capabilities The client capabilities, which contains information about\n * whether the client supports workspaces.\n */\n setupCallbacks (capabilities: ClientCapabilities): void {\n this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false\n if (!this.isWorkspaceIndexingSupported) {", "score": 34.49481932911889 }, { "filename": "src/server.ts", "retrieved_chunk": " triggerCharacters: ['(', ',']\n },\n documentSymbolProvider: true\n }\n }\n return initResult\n})\n// Handles the initialized notification\nconnection.onInitialized(() => {\n ConfigurationManager.setup(capabilities)", "score": 22.888189385662667 }, { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " // Workspace indexing not supported\n return\n }\n connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => {\n void this.handleWorkspaceFoldersAdded(params.added)\n })\n }\n /**\n * Attempts to index the files in the user's workspace.\n */", "score": 21.49695682983848 }, { "filename": "src/server.ts", "retrieved_chunk": "documentManager.onDidSave(params => {\n void LintingSupportProvider.lintDocument(params.document, connection)\n})\n// Handles changes to the text document\ndocumentManager.onDidChangeContent(params => {\n if (MatlabLifecycleManager.isMatlabReady()) {\n // Only want to lint on content changes when linting is being backed by MATLAB\n LintingSupportProvider.queueLintingForDocument(params.document, connection)\n DocumentIndexer.queueIndexingForDocument(params.document)\n }", "score": 21.361911256669 } ]
typescript
.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath)
const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (!shouldWriteDTS) return\n\tconst config = getPrettierConfig(dtsFilepath)\n\tconst formatted = formatDTS(dtsFilepath, dts, config)\n\tcontext.sys.writeFile(dtsFilepath, formatted)\n\treturn dtsFilepath\n\tfunction addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {\n\t\tconst { name } = config\n\t\tlet field = queryType.getFields()[name]\n\t\tif (!field) {\n\t\t\tfield = mutationType.getFields()[name]", "score": 47.6235323273946 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}", "score": 23.28317265540906 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t}\n\tserviceFacts.set(fileKey, thisFact)\n\tconst dtsFilename = filename.endsWith(\".ts\") ? filename.replace(\".ts\", \".d.ts\") : filename.replace(\".js\", \".d.ts\")\n\tconst dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename)\n\t// Some manual formatting tweaks so we align with Redwood's setup more\n\tconst dts = fileDTS\n\t\t.getText()\n\t\t.replace(`from \"graphql\";`, `from \"graphql\";\\n`)\n\t\t.replace(`from \"@redwoodjs/graphql-server/dist/types\";`, `from \"@redwoodjs/graphql-server/dist/types\";\\n`)\n\tconst shouldWriteDTS = !!dts.trim().length", "score": 21.413157440442976 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "import * as graphql from \"graphql\"\nimport { AppContext } from \"./context.js\"\nimport { formatDTS, getPrettierConfig } from \"./formatDTS.js\"\nimport { getCodeFactsForJSTSFileAtPath } from \"./serviceFile.codefacts.js\"\nimport { CodeFacts, ModelResolverFacts, ResolverFuncFact } from \"./typeFacts.js\"\nimport { TypeMapper, typeMapper } from \"./typeMap.js\"\nimport { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from \"./utils.js\"\nexport const lookAtServiceFile = (file: string, context: AppContext) => {\n\tconst { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition", "score": 20.280902945513592 }, { "filename": "src/run.ts", "retrieved_chunk": "import { CodeFacts, FieldFacts } from \"./typeFacts.js\"\nexport function run(\n\tappRoot: string,\n\ttypesRoot: string,\n\tconfig: { deleteOldGraphQLDTS?: boolean; runESLint?: boolean; sys?: typescript.System } = {}\n) {\n\tconst sys = config.sys ?? typescript.sys\n\tconst project = new Project({ useInMemoryFileSystem: true })\n\tlet gqlSchema: graphql.GraphQLSchema | undefined\n\tconst getGraphQLSDLFromFile = (settings: AppContext[\"pathSettings\"]) => {", "score": 18.348113635947485 } ]
typescript
const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath
function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t})\n\t\t})\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}", "score": 53.57110580415736 }, { "filename": "src/tests/features/preferPromiseFnWhenKnown.test.ts", "retrieved_chunk": "\tconst { vfsMap } = getDTSFilesForRun({ sdl, gamesService, prismaSchema })\n\tconst dts = vfsMap.get(\"/types/games.d.ts\")!\n\texpect(dts.trim()).toMatchInlineSnapshot(`\n\t\t\"import type { Game as PGame } from \\\\\"@prisma/client\\\\\";\n\t\timport type { GraphQLResolveInfo } from \\\\\"graphql\\\\\";\n\t\timport type { RedwoodGraphQLContext } from \\\\\"@redwoodjs/graphql-server/dist/types\\\\\";\n\t\timport type { Game as RTGame } from \\\\\"./shared-return-types\\\\\";\n\t\timport type { Query } from \\\\\"./shared-schema-types\\\\\";\n\t\t/** SDL: gameSync: Game */\n\t\texport interface GameSyncResolver {", "score": 53.10480639286826 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t}))\n\t\t)\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}\nfunction createSharedReturnPositionSchemaFile(context: AppContext) {\n\tconst { gql, prisma, fieldFacts } = context", "score": 52.08819597508079 }, { "filename": "src/tests/features/returnTypePositionsWhichPreferPrisma.test.ts", "retrieved_chunk": "\tconst dts = vfsMap.get(\"/types/games.d.ts\")!\n\texpect(dts.trimStart()).toMatchInlineSnapshot(\n\t\t`\n\t\t\"import type { Game as PGame } from \\\\\"@prisma/client\\\\\";\n\t\timport type { GraphQLResolveInfo } from \\\\\"graphql\\\\\";\n\t\timport type { RedwoodGraphQLContext } from \\\\\"@redwoodjs/graphql-server/dist/types\\\\\";\n\t\timport type { Game as RTGame } from \\\\\"./shared-return-types\\\\\";\n\t\timport type { Query } from \\\\\"./shared-schema-types\\\\\";\n\t\t/** SDL: game: Game */\n\t\texport interface GameResolver {", "score": 51.703935336574276 }, { "filename": "src/tests/vendor/soccersage-output/seasons.d.ts", "retrieved_chunk": "import type { CreateSeasonInput, UpdateSeasonInput } from \"./shared-schema-types\";\nimport type { Season as RTSeason, Prediction as RTPrediction } from \"./shared-return-types\";\nimport type { Prediction as PPrediction, Season as PSeason } from \"@prisma/client\";\nimport type { GraphQLResolveInfo } from \"graphql\";\nimport type { RedwoodGraphQLContext } from \"@redwoodjs/graphql-server/dist/functions/types\";\n/** SDL: seasons: [Season!]! */\nexport interface SeasonsResolver {\n (args?: object, obj?: { root: object, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }): RTSeason[] | Promise<RTSeason[]> | (() => Promise<RTSeason[]>);\n}\n/** SDL: season(id: Int!): Season */", "score": 36.94564840113404 } ]
typescript
function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers)
rootResolvers.forEach((v) => {
const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\tconst referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true })\n\tconst vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported())\n\tconst resolverContainers = vars.filter(varStartsWithUppercase)\n\tconst queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v))\n\tqueryOrMutationResolvers.forEach((v) => {\n\t\tconst parent = \"maybe_query_mutation\"\n\t\tconst facts = getResolverInformationForDeclaration(v.getInitializer())\n\t\t// Start making facts about the services\n\t\tconst fact: ModelResolverFacts = fileFact[parent] ?? {\n\t\t\ttypeName: parent,", "score": 38.99998908732739 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "\thasGenericArg: boolean\n\t/** Individual resolvers found for this model */\n\tresolvers: Map<string, ResolverFuncFact>\n\t/** The name (or lack of) for the GraphQL type which we are mapping */\n\ttypeName: string | \"maybe_query_mutation\"\n}\nexport interface ResolverFuncFact {\n\t/** How many args are defined? */\n\tfuncArgCount: number\n\t/** Is it declared as an async fn */", "score": 36.99098492570374 }, { "filename": "src/context.ts", "retrieved_chunk": "\t/** An implementation of the TypeScript system, this can be grabbed pretty\n\t * easily from the typescript import, or you can use your own like tsvfs in browsers.\n\t */\n\tsys: System\n\t/** ts-morph is used to abstract over the typescript compiler API, this project file\n\t * is a slightly augmented version of the typescript Project api.\n\t */\n\ttsProject: tsMorph.Project\n}", "score": 36.0161116716384 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 31.788105404807535 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 30.339945172631356 } ]
typescript
rootResolvers.forEach((v) => {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const
args = createAndReferOrInlineArgsForField(field, {
name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/utils.ts", "retrieved_chunk": "\t\tnoSeparateType?: true\n\t}\n) => {\n\tconst inlineArgs = inlineArgsForField(field, config)\n\tif (!inlineArgs) return undefined\n\tif (inlineArgs.length < 120) return inlineArgs\n\tconst argsInterface = config.file.addInterface({\n\t\tname: `${config.name}Args`,\n\t\tisExported: true,\n\t})", "score": 35.58648427079362 }, { "filename": "src/utils.ts", "retrieved_chunk": "export const inlineArgsForField = (field: graphql.GraphQLField<unknown, unknown>, config: { mapper: TypeMapper[\"map\"] }) => {\n\treturn field.args.length\n\t\t? // Always use an args obj\n\t\t `{${field.args\n\t\t\t\t.map((f) => {\n\t\t\t\t\tconst type = config.mapper(f.type, {})\n\t\t\t\t\tif (!type) throw new Error(`No type for ${f.name} on ${field.name}!`)\n\t\t\t\t\tconst q = type.includes(\"undefined\") ? \"?\" : \"\"\n\t\t\t\t\tconst displayType = type.replace(\"| undefined\", \"\")\n\t\t\t\t\treturn `${f.name}${q}: ${displayType}`", "score": 33.454372611999055 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\tconst field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = {\n\t\t\t\t\t\t\tname: fieldName,\n\t\t\t\t\t\t\ttype: mapper.map(type, { preferNullOverUndefined: true }),\n\t\t\t\t\t\t\tdocs,\n\t\t\t\t\t\t\thasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma),\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn field\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})", "score": 32.110560112424096 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t\t\t\t})\n\t\t\t\t.join(\", \")}}`\n\t\t: undefined\n}\nexport const createAndReferOrInlineArgsForField = (\n\tfield: graphql.GraphQLField<unknown, unknown>,\n\tconfig: {\n\t\tfile: tsMorph.SourceFile\n\t\tmapper: TypeMapper[\"map\"]\n\t\tname: string", "score": 31.663999614306043 }, { "filename": "src/utils.ts", "retrieved_chunk": "\tfield.args.forEach((a) => {\n\t\targsInterface.addProperty({\n\t\t\tname: a.name,\n\t\t\ttype: config.mapper(a.type, {}),\n\t\t})\n\t})\n\treturn `${config.name}Args`\n}", "score": 27.724018618299 } ]
typescript
args = createAndReferOrInlineArgsForField(field, {
import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { varStartsWithUppercase } from "./utils.js" export const getCodeFactsForJSTSFileAtPath = (file: string, context: AppContext) => { const { pathSettings: settings } = context const fileKey = file.replace(settings.apiServicesPath, "") // const priorFacts = serviceInfo.get(fileKey) const fileFact: CodeFacts = {} const fileContents = context.sys.readFile(file) const referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true }) const vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported()) const resolverContainers = vars.filter(varStartsWithUppercase) const queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v)) queryOrMutationResolvers.forEach((v) => { const parent = "maybe_query_mutation" const facts = getResolverInformationForDeclaration(v.getInitializer()) // Start making facts about the services const fact: ModelResolverFacts = fileFact[parent] ?? { typeName: parent, resolvers: new Map(), hasGenericArg: false, } fact.resolvers.set(v.getName(), { name: v.getName(), ...facts }) fileFact[parent] = fact }) // Next all the capital consts resolverContainers.forEach((c) => { addCustomTypeResolvers(c) }) return fileFact function addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) { const declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations() declarations.forEach((d) => { const name = d.getName() // only do it if the first letter is a capital if (!name.match(/^[A-Z]/)) return const type = d.getType() const hasGenericArg = type.getText().includes("<") // Start making facts about the services const fact: ModelResolverFacts = fileFact[name] ?? { typeName: name, resolvers: new Map(), hasGenericArg, } // Grab the const Thing = { ... } const obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression) if (!obj) { throw new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`) } obj.getProperties().forEach((p) => { if (p.isKind(tsMorph.SyntaxKind.SpreadAssignment)) { return } if (p.isKind(tsMorph.SyntaxKind.PropertyAssignment) && p.hasInitializer()) { const name = p.getName() fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p.getInitializerOrThrow()) }) } if (p.isKind(tsMorph.SyntaxKind.FunctionDeclaration) && p.getName()) { const name = p.getName() // @ts-expect-error - lets let this go for now fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p) }) } }) fileFact[d.getName()] = fact }) } }
const getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, "name"> => {
// Who knows what folks could do, lets not crash if (!initialiser) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } } // resolver is a fn if (initialiser.isKind(tsMorph.SyntaxKind.ArrowFunction) || initialiser.isKind(tsMorph.SyntaxKind.FunctionExpression)) { return { funcArgCount: initialiser.getParameters().length, isFunc: true, isAsync: initialiser.isAsync(), isUnknown: false, isObjLiteral: false, } } // resolver is a raw obj if ( initialiser.isKind(tsMorph.SyntaxKind.ObjectLiteralExpression) || initialiser.isKind(tsMorph.SyntaxKind.StringLiteral) || initialiser.isKind(tsMorph.SyntaxKind.NumericLiteral) || initialiser.isKind(tsMorph.SyntaxKind.TrueKeyword) || initialiser.isKind(tsMorph.SyntaxKind.FalseKeyword) || initialiser.isKind(tsMorph.SyntaxKind.NullKeyword) || initialiser.isKind(tsMorph.SyntaxKind.UndefinedKeyword) ) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: false, isObjLiteral: true, } } // who knows return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } }
src/serviceFile.codefacts.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/prismaModeller.ts", "retrieved_chunk": "\t\t\tb.properties.forEach((p) => {\n\t\t\t\tif (p.type === \"comment\") {\n\t\t\t\t\tleadingFieldComments.push(p.text.replace(\"/// \", \"\").replace(\"// \", \"\"))\n\t\t\t\t} else if (p.type === \"break\") {\n\t\t\t\t\tleadingFieldComments.push(\"\")\n\t\t\t\t} else if (p.type === \"attribute\" || p.type === \"field\") {\n\t\t\t\t\tproperties.set(p.name, {\n\t\t\t\t\t\tleadingComments: leadingFieldComments.join(\"\\n\"),\n\t\t\t\t\t\tproperty: p,\n\t\t\t\t\t})", "score": 24.344384775643654 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\texternalTSFile.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: `@prisma/client`,\n\t\t\tnamedImports: allPrismaModels.map((p) => `${p} as P${p}`),\n\t\t})\n\t\tallPrismaModels.forEach((p) => {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tisExported: true,\n\t\t\t\tname: p,\n\t\t\t\ttype: `P${p}`,", "score": 21.711959911067005 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t}\n\t\tconst interfaceDeclaration = fileDTS.addInterface({\n\t\t\tname: `${capitalizeFirstLetter(config.name)}Resolver`,\n\t\t\tisExported: true,\n\t\t\tdocs: field.astNode\n\t\t\t\t? [\"SDL: \" + graphql.print(field.astNode)]\n\t\t\t\t: [\"@deprecated: Could not find this field in the schema for Mutation or Query\"],\n\t\t})\n\t\tconst args = createAndReferOrInlineArgsForField(field, {\n\t\t\tname: interfaceDeclaration.getName(),", "score": 20.65819533948084 }, { "filename": "src/utils.ts", "retrieved_chunk": "import * as graphql from \"graphql\"\nimport * as tsMorph from \"ts-morph\"\nimport { TypeMapper } from \"./typeMap.js\"\nexport const varStartsWithUppercase = (v: tsMorph.VariableDeclaration) => v.getName()[0].startsWith(v.getName()[0].toUpperCase())\nexport const nameDoesNotStartsWithUnderscore = (v: tsMorph.VariableDeclaration) => !v.getName()[0].startsWith(\"_\")\nexport const capitalizeFirstLetter = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)\nexport const variableDeclarationIsAsync = (vd: tsMorph.VariableDeclaration) => {\n\tconst res = !!vd.getFirstChildByKind(tsMorph.SyntaxKind.AsyncKeyword)\n\treturn res\n}", "score": 19.842131307851275 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "\thasGenericArg: boolean\n\t/** Individual resolvers found for this model */\n\tresolvers: Map<string, ResolverFuncFact>\n\t/** The name (or lack of) for the GraphQL type which we are mapping */\n\ttypeName: string | \"maybe_query_mutation\"\n}\nexport interface ResolverFuncFact {\n\t/** How many args are defined? */\n\tfuncArgCount: number\n\t/** Is it declared as an async fn */", "score": 19.078142708224092 } ]
typescript
const getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, "name"> => {
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath)
const serviceFilesToLookAt = serviceFiles.filter((file) => {
if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) { const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 53.92856985340142 }, { "filename": "src/tests/testRunner.ts", "retrieved_chunk": "\tconst project = new Project({ useInMemoryFileSystem: true })\n\tconst vfsMap = new Map<string, string>()\n\tconst vfs = createSystem(vfsMap)\n\tconst appContext: AppContext = {\n\t\tgql: schema,\n\t\tprisma: prismaModeller(prisma),\n\t\ttsProject: project,\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tpathSettings: {", "score": 46.943805498356866 }, { "filename": "src/run.ts", "retrieved_chunk": "\tgetGraphQLSDLFromFile(settings)\n\tgetPrismaSchemaFromFile(settings)\n\tif (!gqlSchema) throw new Error(\"No GraphQL Schema was created during setup\")\n\tconst appContext: AppContext = {\n\t\tgql: gqlSchema,\n\t\tprisma: prismaSchema,\n\t\ttsProject: project,\n\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tpathSettings: settings,", "score": 43.623702720352945 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}", "score": 42.3658903500518 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 40.0086192259373 } ]
typescript
const serviceFilesToLookAt = serviceFiles.filter((file) => {
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => { if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) {
const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) }
return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {\n\t\tlookAtServiceFile(path, appContext)\n\t}\n\tcreateSharedSchemaFiles(appContext)\n\t// console.log(`Updated`, typesRoot)\n\tif (config.runESLint) {\n\t\t// console.log(\"Running ESLint...\")\n\t\t// const process = Deno.run({\n\t\t// \tcwd: appRoot,", "score": 76.01656091112757 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 32.38148263834826 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 26.010721043661803 }, { "filename": "src/tests/features/returnTypePositionsWhichPreferPrisma.test.ts", "retrieved_chunk": "\tconst dts = vfsMap.get(\"/types/games.d.ts\")!\n\texpect(dts.trimStart()).toMatchInlineSnapshot(\n\t\t`\n\t\t\"import type { Game as PGame } from \\\\\"@prisma/client\\\\\";\n\t\timport type { GraphQLResolveInfo } from \\\\\"graphql\\\\\";\n\t\timport type { RedwoodGraphQLContext } from \\\\\"@redwoodjs/graphql-server/dist/types\\\\\";\n\t\timport type { Game as RTGame } from \\\\\"./shared-return-types\\\\\";\n\t\timport type { Query } from \\\\\"./shared-schema-types\\\\\";\n\t\t/** SDL: game: Game */\n\t\texport interface GameResolver {", "score": 25.70529862708579 }, { "filename": "src/tests/features/preferPromiseFnWhenKnown.test.ts", "retrieved_chunk": "\tconst { vfsMap } = getDTSFilesForRun({ sdl, gamesService, prismaSchema })\n\tconst dts = vfsMap.get(\"/types/games.d.ts\")!\n\texpect(dts.trim()).toMatchInlineSnapshot(`\n\t\t\"import type { Game as PGame } from \\\\\"@prisma/client\\\\\";\n\t\timport type { GraphQLResolveInfo } from \\\\\"graphql\\\\\";\n\t\timport type { RedwoodGraphQLContext } from \\\\\"@redwoodjs/graphql-server/dist/types\\\\\";\n\t\timport type { Game as RTGame } from \\\\\"./shared-return-types\\\\\";\n\t\timport type { Query } from \\\\\"./shared-schema-types\\\\\";\n\t\t/** SDL: gameSync: Game */\n\t\texport interface GameSyncResolver {", "score": 24.912627046460923 } ]
typescript
const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) }
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles
.filter((file) => {
if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) { const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 52.99812936068905 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}", "score": 42.3658903500518 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 40.0086192259373 }, { "filename": "src/tests/testRunner.ts", "retrieved_chunk": "\tconst project = new Project({ useInMemoryFileSystem: true })\n\tconst vfsMap = new Map<string, string>()\n\tconst vfs = createSystem(vfsMap)\n\tconst appContext: AppContext = {\n\t\tgql: schema,\n\t\tprisma: prismaModeller(prisma),\n\t\ttsProject: project,\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tpathSettings: {", "score": 29.26209828343724 }, { "filename": "src/run.ts", "retrieved_chunk": "\tgetGraphQLSDLFromFile(settings)\n\tgetPrismaSchemaFromFile(settings)\n\tif (!gqlSchema) throw new Error(\"No GraphQL Schema was created during setup\")\n\tconst appContext: AppContext = {\n\t\tgql: gqlSchema,\n\t\tprisma: prismaSchema,\n\t\ttsProject: project,\n\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tpathSettings: settings,", "score": 27.396964500486497 } ]
typescript
.filter((file) => {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */
function addCustomTypeModel(modelFacts: ModelResolverFacts) {
const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "// the type in the SDL and not have to worry about type mis-matches because the thing\n// you returned does not include those functions.\n// This gets particularly valuable when you want to return a union type, an interface, \n// or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.)\n`\n\t)\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}", "score": 20.806324274224725 }, { "filename": "src/typeMap.ts", "retrieved_chunk": "\t\ttype: graphql.GraphQLType,\n\t\tmapConfig: {\n\t\t\tparentWasNotNull?: true\n\t\t\tpreferNullOverUndefined?: true\n\t\t\ttypenamePrefix?: string\n\t\t}\n\t): string | undefined => {\n\t\tconst prefix = mapConfig.typenamePrefix ?? \"\"\n\t\t// The AST for GQL uses a parent node to indicate the !, we need the opposite\n\t\t// for TS which uses '| undefined' after.", "score": 19.145275234011873 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 18.776432485677965 }, { "filename": "src/types.ts", "retrieved_chunk": "import type { System } from \"typescript\"\nexport interface SDLCodeGenOptions {\n\t/** We'll use the one which comes with TypeScript if one isn't given */\n\tsystem?: System\n}\n// These are directly ported from Redwood at\n// packages/project-config/src/paths.ts\n// Slightly amended to reduce the constraints on the Redwood team to make changes to this obj!\ninterface NodeTargetPaths {\n\tbase: string", "score": 17.646972906818633 }, { "filename": "src/tests/vendor/soccersage-output/predictions.d.ts", "retrieved_chunk": "export interface PredictionsResolver {\n (args?: object, obj?: { root: object, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }): RTPrediction[] | Promise<RTPrediction[]> | (() => Promise<RTPrediction[]>);\n}\n/** SDL: myPredictions: [Prediction!]! */\nexport interface MyPredictionsResolver {\n (args: object, obj: { root: object, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }): RTPrediction[] | Promise<RTPrediction[]> | (() => Promise<RTPrediction[]>);\n}\n/** SDL: prediction(id: Int!): Prediction */\nexport interface PredictionResolver {\n (args: { id: number }, obj?: { root: object, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }): RTPrediction | null | Promise<RTPrediction | null> | (() => Promise<RTPrediction | null>);", "score": 17.063873275429664 } ]
typescript
function addCustomTypeModel(modelFacts: ModelResolverFacts) {
import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { type StytchAuthMethods } from '~/types/stytch'; import { trpc } from '~/utils/trpc'; import { VerifyOtp } from './VerifyOtp'; import { Button } from './Button'; import { Input } from './Input'; const formSchema = z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }); type FormSchemaType = z.infer<typeof formSchema>; export function LoginEmail(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) { const { data, mutateAsync } = trpc.auth.loginEmail.useMutation(); const { handleSubmit, register, getValues, setError, formState: { errors, isSubmitting }, } = useForm<FormSchemaType>({ resolver: zodResolver(formSchema), }); if (data?.methodId) { return <VerifyOtp methodValue={getValues('email')} methodId={data.methodId} />; } return ( <form className='flex w-full flex-col gap-y-4 rounded bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]' onSubmit={handleSubmit((values) => mutateAsync({ email: values.email }).catch((err) => { setError('root', { message: err.message }); }), )} > <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1> <div> <Input aria-label='Email' placeholder='[email protected]' type='email' autoCapitalize='off' autoCorrect='off' spellCheck='false' inputMode='email' className='rounded' {...register('email')} /> {errors.email && <span className='mt-2 block text-left text-sm text-red-800'>{errors.email?.message}</span>} </div>
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
{!data?.methodId && ( <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_sms')}> Or use phone number </button> )} {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>} {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */} <div className='text-neutral-4 text-xs text-neutral-600'> By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '} <span className='underline'>Privacy Policy</span>. </div> </form> ); }
src/components/LoginEmail.tsx
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " {errors.phone && <span className='mt-2 block text-left text-sm text-red-800'>{errors.phone?.message}</span>}\n </div>\n <Button isLoading={isSubmitting} type='submit'>\n Continue\n </Button>\n {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}\n {!data?.methodId && (\n <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_email')}>\n Or use email address\n </button>", "score": 109.67732792668467 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </div>\n <Button isLoading={isSubmitting || isSubmitSuccessful} type='submit'>\n Continue\n </Button>\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n </form>\n );\n}", "score": 79.27956571496983 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </p>\n <div>\n <input\n className='w-full border p-3'\n aria-label='6-Digit Code'\n type='text'\n inputMode='numeric'\n {...register('code')}\n />\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.code?.message}</span>}", "score": 62.398932545560605 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " )}\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */}\n <div className='text-neutral-4 text-xs text-neutral-600'>\n By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '}\n <span className='underline'>Privacy Policy</span>.\n </div>\n </form>\n );\n}", "score": 47.78849954963385 }, { "filename": "src/server/routers/auth.ts", "retrieved_chunk": "const SESSION_DURATION_MINUTES = 43200;\n// SESSION_DURATION_SECONDS is used to set the age of the cookie that we set in the user's browser.\nconst SESSION_DURATION_SECONDS = SESSION_DURATION_MINUTES * 60;\nexport const authRouter = router({\n // This route is used to send an OTP via email to a user.\n loginEmail: publicProcedure\n .input(\n z.object({\n email: z.string().email('Invalid email address').min(1, 'Email address is required'),\n }),", "score": 39.803932752510185 } ]
typescript
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename }
function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) {
if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/utils.ts", "retrieved_chunk": "\t\t\t\t})\n\t\t\t\t.join(\", \")}}`\n\t\t: undefined\n}\nexport const createAndReferOrInlineArgsForField = (\n\tfield: graphql.GraphQLField<unknown, unknown>,\n\tconfig: {\n\t\tfile: tsMorph.SourceFile\n\t\tmapper: TypeMapper[\"map\"]\n\t\tname: string", "score": 40.10917140370093 }, { "filename": "src/utils.ts", "retrieved_chunk": "export const inlineArgsForField = (field: graphql.GraphQLField<unknown, unknown>, config: { mapper: TypeMapper[\"map\"] }) => {\n\treturn field.args.length\n\t\t? // Always use an args obj\n\t\t `{${field.args\n\t\t\t\t.map((f) => {\n\t\t\t\t\tconst type = config.mapper(f.type, {})\n\t\t\t\t\tif (!type) throw new Error(`No type for ${f.name} on ${field.name}!`)\n\t\t\t\t\tconst q = type.includes(\"undefined\") ? \"?\" : \"\"\n\t\t\t\t\tconst displayType = type.replace(\"| undefined\", \"\")\n\t\t\t\t\treturn `${f.name}${q}: ${displayType}`", "score": 36.390107627352315 }, { "filename": "src/prismaModeller.ts", "retrieved_chunk": "\t\t\tb.properties.forEach((p) => {\n\t\t\t\tif (p.type === \"comment\") {\n\t\t\t\t\tleadingFieldComments.push(p.text.replace(\"/// \", \"\").replace(\"// \", \"\"))\n\t\t\t\t} else if (p.type === \"break\") {\n\t\t\t\t\tleadingFieldComments.push(\"\")\n\t\t\t\t} else if (p.type === \"attribute\" || p.type === \"field\") {\n\t\t\t\t\tproperties.set(p.name, {\n\t\t\t\t\t\tleadingComments: leadingFieldComments.join(\"\\n\"),\n\t\t\t\t\t\tproperty: p,\n\t\t\t\t\t})", "score": 19.55271713298405 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t\tnoSeparateType?: true\n\t}\n) => {\n\tconst inlineArgs = inlineArgsForField(field, config)\n\tif (!inlineArgs) return undefined\n\tif (inlineArgs.length < 120) return inlineArgs\n\tconst argsInterface = config.file.addInterface({\n\t\tname: `${config.name}Args`,\n\t\tisExported: true,\n\t})", "score": 18.476741075573525 }, { "filename": "src/typeMap.ts", "retrieved_chunk": "\t\t\t}\n\t\t\tif (graphql.isUnionType(type)) {\n\t\t\t\tconst types = type.getTypes()\n\t\t\t\treturn types.map((t) => map(t, mapConfig)).join(\" | \")\n\t\t\t}\n\t\t\tif (graphql.isEnumType(type)) {\n\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\tif (graphql.isInputObjectType(type)) {\n\t\t\t\treferencedGraphQLTypes.add(type.name)", "score": 17.796376475782846 } ]
typescript
function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) {
import { TRPCError } from '@trpc/server'; import { deleteCookie, setCookie } from 'cookies-next'; import { parsePhoneNumber } from 'react-phone-number-input'; import { StytchError } from 'stytch'; import { z } from 'zod'; import { protectedProcedure, publicProcedure, router } from '~/server/trpc'; import { VALID_PHONE_NUMBER } from '~/utils/regex'; import { STYTCH_SUPPORTED_SMS_COUNTRIES } from '~/utils/phone-countries'; // Change these values to adjust the length of a user's session. 30 day sessions, like we use here, is usually a good default, // but you may find a shorter or longer duration to work better for your app. const SESSION_DURATION_MINUTES = 43200; // SESSION_DURATION_SECONDS is used to set the age of the cookie that we set in the user's browser. const SESSION_DURATION_SECONDS = SESSION_DURATION_MINUTES * 60; export const authRouter = router({ // This route is used to send an OTP via email to a user. loginEmail: publicProcedure .input( z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, a signup email will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.email.loginOrCreate({ email: input.email, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.email_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route is used to send an SMS OTP to a user. loginSms: publicProcedure .input( z.object({ phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { const phoneNumber = parsePhoneNumber(input.phone); if (!phoneNumber?.country || !STYTCH_SUPPORTED_SMS_COUNTRIES.includes(phoneNumber.country)) { throw new TRPCError({ code: 'BAD_REQUEST', message: `Sorry, we don't support sms login for your country yet.`, }); } try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, an SMS will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.sms.loginOrCreate({ phone_number: input.phone, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.phone_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route handles authenticating an OTP as input by the user and adding custom claims to their resulting session. authenticateOtp: publicProcedure .input( z.object({ code: z.string().length(6, 'OTP must be 6 digits'), methodId: z.string(), }), ) .output( z.object({ id: z.string(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. OTP Authenticate step; here we'll validate that the OTP + Method (phone_id or email_id) are valid and belong to // the same user who initiated the login flow. const authenticateResponse = await ctx.stytch.otps.authenticate({ code: input.code, method_id: input.methodId, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 2. Get the user from your Prisma database. // // Here you could also include any other business logic, e.g. firing logs in your own stack, on successful completion of the login flow. const dbUser = await ctx.prisma.user.findUniqueOrThrow({ where: { stytchUserId: authenticateResponse.user.user_id }, select: { id: true, }, }); // Examples of business logic you might want to include on successful user creation: // // Create a Stripe customer for the user. // await ctx.stripe.customers.create({ name: authenticateResponse.user.name.first_name }); // // Subscribe the user to a mailing list. // await ctx.mailchimp.lists.addListMember("list_id", { email_address: authenticateResponse.user.emails[0].email, status: "subscribed" }); // 3. Optional: Add custom claims to the session. These claims will be available in the JWT returned by Stytch. // // Alternatively this can also be accomplished via a custom JWT template set in the Stytch Dashboard if there are values you want on // all JWTs issued for your sessions. const sessionResponse = await ctx.stytch.sessions.authenticate({ // Here we add the Prisma user ID to the session as a custom claim. session_custom_claims: { db_user_id: dbUser.id }, session_jwt: authenticateResponse.session_jwt, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 4. Set the session JWT as a cookie in the user's browser. setCookie('session_jwt', sessionResponse.session_jwt, { req: ctx.req, res: ctx.res, httpOnly: true, maxAge: SESSION_DURATION_SECONDS, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', }); return { id: dbUser.id, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route logs a user out of their session by revoking it with Stytch. // // Note, because JWTs are valid for their lifetime (here we've set it to 30 days), the JWT would still // locally parse, i.e. using an open source JWT parsing library, as valid. We always encourage you to // authenticate a session with Stytch's API directly to ensure that it is still valid.
logout: protectedProcedure.mutation(async ({ ctx }) => {
await ctx.stytch.sessions.revoke({ session_id: ctx.session.session_id }); deleteCookie('session_jwt', { req: ctx.req, res: ctx.res }); return { success: true }; }), });
src/server/routers/auth.ts
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/middleware.ts", "retrieved_chunk": " // If there is a JWT, we need to verify it with Stytch to make sure it is valid and take the appropriate action.\n if (jwtToken) {\n // Authenticate the JWT with Stytch; this will tell us if the session is still valid.\n try {\n const stytch = loadStytch();\n await stytch.sessions.authenticateJwt(jwtToken);\n // If the session is valid and they are on the login screen, redirect them to the profile screen.\n if (pathname === '/login') {\n return NextResponse.redirect(new URL('/profile', req.url));\n }", "score": 68.19583294944759 }, { "filename": "src/utils/regex.ts", "retrieved_chunk": "// This regex is used to validate that the phone number entered by the user is valid.\nexport const VALID_PHONE_NUMBER = /^[\\+]?[(]?[0-9]{3}[)]?[-\\s\\.]?[0-9]{3}[-\\s\\.]?[0-9]{4,6}$/;", "score": 36.491066678209684 }, { "filename": "src/server/trpc.ts", "retrieved_chunk": " }\n if (!ctx.session) {\n throw new TRPCError({ code: 'UNAUTHORIZED' });\n }\n return next({\n ctx: {\n session: ctx.session,\n req: ctx.req,\n res: ctx.res,\n },", "score": 29.56067201585449 }, { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": " {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */}\n <div className='text-neutral-4 text-xs text-neutral-600'>\n By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '}\n <span className='underline'>Privacy Policy</span>.\n </div>\n </form>\n );\n}", "score": 28.38257628464229 }, { "filename": "src/utils/phone-countries.ts", "retrieved_chunk": "import { Country } from 'react-phone-number-input';\n/**\n * These are the countries that Stytch supports at the time of writing\n * https://stytch.com/docs/passcodes#unsupported-countries.\n *\n * This list is used to populate the country dropdown on the phone number input\n * in the login form. Simply remove any countries that you don't want to support. You may\n * want to limit support due to cost, fraud, or because you do not do business in that country.\n **/\nexport const STYTCH_SUPPORTED_SMS_COUNTRIES: Country[] = [", "score": 25.516059574570924 } ]
typescript
logout: protectedProcedure.mutation(async ({ ctx }) => {
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => { if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files
const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) {
const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {\n\t\tlookAtServiceFile(path, appContext)\n\t}\n\tcreateSharedSchemaFiles(appContext)\n\t// console.log(`Updated`, typesRoot)\n\tif (config.runESLint) {\n\t\t// console.log(\"Running ESLint...\")\n\t\t// const process = Deno.run({\n\t\t// \tcwd: appRoot,", "score": 64.17898894279864 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 64.04424971719129 }, { "filename": "src/context.ts", "retrieved_chunk": "\t/** A global set of facts about resolvers focused from the GQL side */\n\tfieldFacts: Map<string, FieldFacts>\n\t/** When we emit .d.ts files, it runs the ts formatter over the file first - you can override the default settings */\n\tformatCodeSettings?: FormatCodeSettings\n\t/** So you can override the formatter */\n\tgql: graphql.GraphQLSchema\n\t/** POSXIY- fn not built into System */\n\tjoin: (...paths: string[]) => string\n\t/** Where to find particular files */\n\tpathSettings: {", "score": 38.11809532486147 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`)\n\tif (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`)\n\t// This isn't good enough, needs to be relative to api/src/services\n\tconst fileKey = file.replace(settings.apiServicesPath, \"\")\n\tconst thisFact: CodeFacts = {}\n\tconst filename = context.basename(file)\n\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\tconst queryType = gql.getQueryType()!\n\tif (!queryType) throw new Error(\"No query type\")\n\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion", "score": 35.43106292949431 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "import * as tsMorph from \"ts-morph\"\nimport { AppContext } from \"./context.js\"\nimport { CodeFacts, ModelResolverFacts, ResolverFuncFact } from \"./typeFacts.js\"\nimport { varStartsWithUppercase } from \"./utils.js\"\nexport const getCodeFactsForJSTSFileAtPath = (file: string, context: AppContext) => {\n\tconst { pathSettings: settings } = context\n\tconst fileKey = file.replace(settings.apiServicesPath, \"\")\n\t// const priorFacts = serviceInfo.get(fileKey)\n\tconst fileFact: CodeFacts = {}\n\tconst fileContents = context.sys.readFile(file)", "score": 34.11101781396951 } ]
typescript
const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) {
import { TRPCError } from '@trpc/server'; import { deleteCookie, setCookie } from 'cookies-next'; import { parsePhoneNumber } from 'react-phone-number-input'; import { StytchError } from 'stytch'; import { z } from 'zod'; import { protectedProcedure, publicProcedure, router } from '~/server/trpc'; import { VALID_PHONE_NUMBER } from '~/utils/regex'; import { STYTCH_SUPPORTED_SMS_COUNTRIES } from '~/utils/phone-countries'; // Change these values to adjust the length of a user's session. 30 day sessions, like we use here, is usually a good default, // but you may find a shorter or longer duration to work better for your app. const SESSION_DURATION_MINUTES = 43200; // SESSION_DURATION_SECONDS is used to set the age of the cookie that we set in the user's browser. const SESSION_DURATION_SECONDS = SESSION_DURATION_MINUTES * 60; export const authRouter = router({ // This route is used to send an OTP via email to a user. loginEmail: publicProcedure .input( z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, a signup email will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.email.loginOrCreate({ email: input.email, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.email_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route is used to send an SMS OTP to a user. loginSms: publicProcedure .input( z.object({ phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { const phoneNumber = parsePhoneNumber(input.phone);
if (!phoneNumber?.country || !STYTCH_SUPPORTED_SMS_COUNTRIES.includes(phoneNumber.country)) {
throw new TRPCError({ code: 'BAD_REQUEST', message: `Sorry, we don't support sms login for your country yet.`, }); } try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, an SMS will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.sms.loginOrCreate({ phone_number: input.phone, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.phone_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route handles authenticating an OTP as input by the user and adding custom claims to their resulting session. authenticateOtp: publicProcedure .input( z.object({ code: z.string().length(6, 'OTP must be 6 digits'), methodId: z.string(), }), ) .output( z.object({ id: z.string(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. OTP Authenticate step; here we'll validate that the OTP + Method (phone_id or email_id) are valid and belong to // the same user who initiated the login flow. const authenticateResponse = await ctx.stytch.otps.authenticate({ code: input.code, method_id: input.methodId, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 2. Get the user from your Prisma database. // // Here you could also include any other business logic, e.g. firing logs in your own stack, on successful completion of the login flow. const dbUser = await ctx.prisma.user.findUniqueOrThrow({ where: { stytchUserId: authenticateResponse.user.user_id }, select: { id: true, }, }); // Examples of business logic you might want to include on successful user creation: // // Create a Stripe customer for the user. // await ctx.stripe.customers.create({ name: authenticateResponse.user.name.first_name }); // // Subscribe the user to a mailing list. // await ctx.mailchimp.lists.addListMember("list_id", { email_address: authenticateResponse.user.emails[0].email, status: "subscribed" }); // 3. Optional: Add custom claims to the session. These claims will be available in the JWT returned by Stytch. // // Alternatively this can also be accomplished via a custom JWT template set in the Stytch Dashboard if there are values you want on // all JWTs issued for your sessions. const sessionResponse = await ctx.stytch.sessions.authenticate({ // Here we add the Prisma user ID to the session as a custom claim. session_custom_claims: { db_user_id: dbUser.id }, session_jwt: authenticateResponse.session_jwt, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 4. Set the session JWT as a cookie in the user's browser. setCookie('session_jwt', sessionResponse.session_jwt, { req: ctx.req, res: ctx.res, httpOnly: true, maxAge: SESSION_DURATION_SECONDS, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', }); return { id: dbUser.id, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route logs a user out of their session by revoking it with Stytch. // // Note, because JWTs are valid for their lifetime (here we've set it to 30 days), the JWT would still // locally parse, i.e. using an open source JWT parsing library, as valid. We always encourage you to // authenticate a session with Stytch's API directly to ensure that it is still valid. logout: protectedProcedure.mutation(async ({ ctx }) => { await ctx.stytch.sessions.revoke({ session_id: ctx.session.session_id }); deleteCookie('session_jwt', { req: ctx.req, res: ctx.res }); return { success: true }; }), });
src/server/routers/auth.ts
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": "import { useRouter } from 'next/router';\nimport { useForm } from 'react-hook-form';\nimport { z } from 'zod';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { trpc } from '~/utils/trpc';\nimport { Button } from './Button';\nconst formSchema = z.object({\n code: z.string().length(6, 'OTP must be 6 digits'),\n});\ntype FormSchemaType = z.infer<typeof formSchema>;", "score": 17.64589563694574 }, { "filename": "src/utils/phone-countries.ts", "retrieved_chunk": "import { Country } from 'react-phone-number-input';\n/**\n * These are the countries that Stytch supports at the time of writing\n * https://stytch.com/docs/passcodes#unsupported-countries.\n *\n * This list is used to populate the country dropdown on the phone number input\n * in the login form. Simply remove any countries that you don't want to support. You may\n * want to limit support due to cost, fraud, or because you do not do business in that country.\n **/\nexport const STYTCH_SUPPORTED_SMS_COUNTRIES: Country[] = [", "score": 17.428206330659584 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'),\n});\ntype FormSchemaType = z.infer<typeof formSchema>;\nexport function LoginSms(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) {\n const { data, mutateAsync } = trpc.auth.loginSms.useMutation();\n const {\n handleSubmit,\n getValues,\n setError,\n control,", "score": 16.052404930126457 }, { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": "import { useForm } from 'react-hook-form';\nimport { z } from 'zod';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { type StytchAuthMethods } from '~/types/stytch';\nimport { trpc } from '~/utils/trpc';\nimport { VerifyOtp } from './VerifyOtp';\nimport { Button } from './Button';\nimport { Input } from './Input';\nconst formSchema = z.object({\n email: z.string().email('Invalid email address').min(1, 'Email address is required'),", "score": 15.62702163066721 }, { "filename": "src/components/PhoneInput.tsx", "retrieved_chunk": "import React from 'react';\nimport { type Control } from 'react-hook-form';\nimport PhoneInputWithCountry from 'react-phone-number-input/react-hook-form';\nimport flags from 'react-phone-number-input/flags';\nimport clsx from 'clsx';\nimport { STYTCH_SUPPORTED_SMS_COUNTRIES } from '~/utils/phone-countries';\nimport { Input } from './Input';\nimport 'react-phone-number-input/style.css';\nexport function PhoneInput(props: { control: Control<{ phone: string }, any> }) {\n const { control } = props;", "score": 14.901427103085487 } ]
typescript
if (!phoneNumber?.country || !STYTCH_SUPPORTED_SMS_COUNTRIES.includes(phoneNumber.country)) {
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases(
scalars.map((s) => ({
name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) } function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/typeMap.ts", "retrieved_chunk": "\t\treferencedPrismaModels.clear()\n\t}\n\tconst getReferencedGraphQLThingsInMapping = () => {\n\t\treturn {\n\t\t\ttypes: [...referencedGraphQLTypes.keys()],\n\t\t\tscalars: [...customScalars.keys()],\n\t\t\tprisma: [...referencedPrismaModels.keys()],\n\t\t}\n\t}\n\tconst map = (", "score": 32.195272996414474 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (aliases.length) {\n\t\tfileDTS.addTypeAliases(\n\t\t\taliases.map((s) => ({\n\t\t\t\tname: s,\n\t\t\t\ttype: \"any\",\n\t\t\t}))\n\t\t)\n\t}\n\tconst prismases = [\n\t\t...new Set([", "score": 28.084977354361484 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\tif (!model) return\n\t\tconst skip = [\"maybe_query_mutation\", queryType.name, mutationType.name]\n\t\tif (skip.includes(model.typeName)) return\n\t\taddCustomTypeModel(model)\n\t})\n\t// Set up the module imports at the top\n\tconst sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping()\n\tconst sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL]\n\tconst sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping()\n\tconst aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])]", "score": 25.748760696398303 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t\t\t\t})\n\t\t\t\t.join(\", \")}}`\n\t\t: undefined\n}\nexport const createAndReferOrInlineArgsForField = (\n\tfield: graphql.GraphQLField<unknown, unknown>,\n\tconfig: {\n\t\tfile: tsMorph.SourceFile\n\t\tmapper: TypeMapper[\"map\"]\n\t\tname: string", "score": 16.52937973367413 }, { "filename": "src/utils.ts", "retrieved_chunk": "export const inlineArgsForField = (field: graphql.GraphQLField<unknown, unknown>, config: { mapper: TypeMapper[\"map\"] }) => {\n\treturn field.args.length\n\t\t? // Always use an args obj\n\t\t `{${field.args\n\t\t\t\t.map((f) => {\n\t\t\t\t\tconst type = config.mapper(f.type, {})\n\t\t\t\t\tif (!type) throw new Error(`No type for ${f.name} on ${field.name}!`)\n\t\t\t\t\tconst q = type.includes(\"undefined\") ? \"?\" : \"\"\n\t\t\t\t\tconst displayType = type.replace(\"| undefined\", \"\")\n\t\t\t\t\treturn `${f.name}${q}: ${displayType}`", "score": 14.691422917200406 } ]
typescript
scalars.map((s) => ({
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`,
namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\texternalTSFile.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: `@prisma/client`,\n\t\t\tnamedImports: allPrismaModels.map((p) => `${p} as P${p}`),\n\t\t})\n\t\tallPrismaModels.forEach((p) => {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tisExported: true,\n\t\t\t\tname: p,\n\t\t\t\ttype: `P${p}`,", "score": 36.71739479997905 }, { "filename": "src/typeMap.ts", "retrieved_chunk": "\t\t\t}\n\t\t\tif (graphql.isUnionType(type)) {\n\t\t\t\tconst types = type.getTypes()\n\t\t\t\treturn types.map((t) => map(t, mapConfig)).join(\" | \")\n\t\t\t}\n\t\t\tif (graphql.isEnumType(type)) {\n\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\tif (graphql.isInputObjectType(type)) {\n\t\t\t\treferencedGraphQLTypes.add(type.name)", "score": 28.846980242208748 }, { "filename": "src/tests/serviceFile.test.ts", "retrieved_chunk": "export const game = () => {}\nexport function game2() {}\n `\n\t)\n\texpect(vfsMap.has(\"/types/example.d.ts\")).toBeFalsy()\n\tlookAtServiceFile(\"/api/src/services/example.ts\", appContext)\n\t// this isn't really very useful as a test, but it proves it doesn't crash?\n})\nit(\"generates useful service facts from a (truncated) real file\", () => {\n\tconst { appContext, vfsMap } = getDTSFilesForRun({})", "score": 23.226905935020067 }, { "filename": "src/run.ts", "retrieved_chunk": "\t}\n\tconst settings: AppContext[\"pathSettings\"] = {\n\t\troot: appRoot,\n\t\tgraphQLSchemaPath: join(appRoot, \".redwood\", \"schema.graphql\"),\n\t\tapiServicesPath: join(appRoot, \"api\", \"src\", \"services\"),\n\t\tprismaDSLPath: join(appRoot, \"api\", \"db\", \"schema.prisma\"),\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: typesRoot,\n\t}", "score": 18.405903697326966 }, { "filename": "src/index.ts", "retrieved_chunk": "\tconst pathSettings: AppContext[\"pathSettings\"] = {\n\t\troot: paths.base,\n\t\tapiServicesPath: paths.api.services,\n\t\tprismaDSLPath: paths.api.dbSchema,\n\t\tgraphQLSchemaPath: paths.generated.schema,\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: paths.api.types,\n\t}\n\tconst project = new Project({ useInMemoryFileSystem: true })", "score": 17.881252169004554 } ]
typescript
namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { type StytchAuthMethods } from '~/types/stytch'; import { trpc } from '~/utils/trpc'; import { VerifyOtp } from './VerifyOtp'; import { Button } from './Button'; import { Input } from './Input'; const formSchema = z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }); type FormSchemaType = z.infer<typeof formSchema>; export function LoginEmail(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) { const { data, mutateAsync } = trpc.auth.loginEmail.useMutation(); const { handleSubmit, register, getValues, setError, formState: { errors, isSubmitting }, } = useForm<FormSchemaType>({ resolver: zodResolver(formSchema), }); if (data?.methodId) { return <VerifyOtp methodValue={getValues('email')} methodId={data.methodId} />; } return ( <form className='flex w-full flex-col gap-y-4 rounded bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]' onSubmit={handleSubmit((values) => mutateAsync({ email: values.email }).catch((err) => { setError('root', { message: err.message }); }), )} > <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1> <div> <Input aria-label='Email' placeholder='[email protected]' type='email' autoCapitalize='off' autoCorrect='off' spellCheck='false' inputMode='email' className='rounded' {...register('email')} /> {errors.email && <span className='mt-2 block text-left text-sm text-red-800'>{errors.email?.message}</span>} </div> <
Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
{!data?.methodId && ( <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_sms')}> Or use phone number </button> )} {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>} {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */} <div className='text-neutral-4 text-xs text-neutral-600'> By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '} <span className='underline'>Privacy Policy</span>. </div> </form> ); }
src/components/LoginEmail.tsx
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " {errors.phone && <span className='mt-2 block text-left text-sm text-red-800'>{errors.phone?.message}</span>}\n </div>\n <Button isLoading={isSubmitting} type='submit'>\n Continue\n </Button>\n {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}\n {!data?.methodId && (\n <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_email')}>\n Or use email address\n </button>", "score": 107.50432103454561 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </div>\n <Button isLoading={isSubmitting || isSubmitSuccessful} type='submit'>\n Continue\n </Button>\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n </form>\n );\n}", "score": 79.27956571496983 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </p>\n <div>\n <input\n className='w-full border p-3'\n aria-label='6-Digit Code'\n type='text'\n inputMode='numeric'\n {...register('code')}\n />\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.code?.message}</span>}", "score": 58.183896840039516 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " )}\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */}\n <div className='text-neutral-4 text-xs text-neutral-600'>\n By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '}\n <span className='underline'>Privacy Policy</span>.\n </div>\n </form>\n );\n}", "score": 47.78849954963385 }, { "filename": "src/server/routers/auth.ts", "retrieved_chunk": "const SESSION_DURATION_MINUTES = 43200;\n// SESSION_DURATION_SECONDS is used to set the age of the cookie that we set in the user's browser.\nconst SESSION_DURATION_SECONDS = SESSION_DURATION_MINUTES * 60;\nexport const authRouter = router({\n // This route is used to send an OTP via email to a user.\n loginEmail: publicProcedure\n .input(\n z.object({\n email: z.string().email('Invalid email address').min(1, 'Email address is required'),\n }),", "score": 35.25657016555148 } ]
typescript
Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports
: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\texternalTSFile.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: `@prisma/client`,\n\t\t\tnamedImports: allPrismaModels.map((p) => `${p} as P${p}`),\n\t\t})\n\t\tallPrismaModels.forEach((p) => {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tisExported: true,\n\t\t\t\tname: p,\n\t\t\t\ttype: `P${p}`,", "score": 31.05696449473965 }, { "filename": "src/typeMap.ts", "retrieved_chunk": "\t\t\t}\n\t\t\tif (graphql.isUnionType(type)) {\n\t\t\t\tconst types = type.getTypes()\n\t\t\t\treturn types.map((t) => map(t, mapConfig)).join(\" | \")\n\t\t\t}\n\t\t\tif (graphql.isEnumType(type)) {\n\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\tif (graphql.isInputObjectType(type)) {\n\t\t\t\treferencedGraphQLTypes.add(type.name)", "score": 28.846980242208748 }, { "filename": "src/tests/serviceFile.test.ts", "retrieved_chunk": "export const game = () => {}\nexport function game2() {}\n `\n\t)\n\texpect(vfsMap.has(\"/types/example.d.ts\")).toBeFalsy()\n\tlookAtServiceFile(\"/api/src/services/example.ts\", appContext)\n\t// this isn't really very useful as a test, but it proves it doesn't crash?\n})\nit(\"generates useful service facts from a (truncated) real file\", () => {\n\tconst { appContext, vfsMap } = getDTSFilesForRun({})", "score": 23.226905935020067 }, { "filename": "src/run.ts", "retrieved_chunk": "\t}\n\tconst settings: AppContext[\"pathSettings\"] = {\n\t\troot: appRoot,\n\t\tgraphQLSchemaPath: join(appRoot, \".redwood\", \"schema.graphql\"),\n\t\tapiServicesPath: join(appRoot, \"api\", \"src\", \"services\"),\n\t\tprismaDSLPath: join(appRoot, \"api\", \"db\", \"schema.prisma\"),\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: typesRoot,\n\t}", "score": 18.405903697326966 }, { "filename": "src/index.ts", "retrieved_chunk": "\tconst pathSettings: AppContext[\"pathSettings\"] = {\n\t\troot: paths.base,\n\t\tapiServicesPath: paths.api.services,\n\t\tprismaDSLPath: paths.api.dbSchema,\n\t\tgraphQLSchemaPath: paths.generated.schema,\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: paths.api.types,\n\t}\n\tconst project = new Project({ useInMemoryFileSystem: true })", "score": 17.881252169004554 } ]
typescript
: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { type StytchAuthMethods } from '~/types/stytch'; import { trpc } from '~/utils/trpc'; import { VALID_PHONE_NUMBER } from '~/utils/regex'; import { Button } from './Button'; import { PhoneInput } from './PhoneInput'; import { VerifyOtp } from './VerifyOtp'; const formSchema = z.object({ phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'), }); type FormSchemaType = z.infer<typeof formSchema>; export function LoginSms(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) { const { data, mutateAsync } = trpc.auth.loginSms.useMutation(); const { handleSubmit, getValues, setError, control, formState: { errors, isSubmitting }, } = useForm<FormSchemaType>({ resolver: zodResolver(formSchema), }); if (data?.methodId) { return <VerifyOtp methodValue={getValues('phone')} methodId={data.methodId} />; } return ( <form className='flex w-full flex-col gap-y-4 rounded-lg bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]' onSubmit={handleSubmit((values) => mutateAsync({ phone: values.phone }).catch((err) => { setError('root', { message: err.message }); }), )} > <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1> <p className='text-neutral-600'>Sign in to your account to continue.</p> <div> <PhoneInput control={control} /> {errors.phone && <span className='mt-2 block text-left text-sm text-red-800'>{errors.phone?.message}</span>} </div>
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}
{!data?.methodId && ( <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_email')}> Or use email address </button> )} {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>} {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */} <div className='text-neutral-4 text-xs text-neutral-600'> By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '} <span className='underline'>Privacy Policy</span>. </div> </form> ); }
src/components/LoginSms.tsx
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": " <Button isLoading={isSubmitting} type='submit'>\n Continue\n </Button>\n {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}\n {!data?.methodId && (\n <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_sms')}>\n Or use phone number\n </button>\n )}\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}", "score": 109.66884099283578 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </div>\n <Button isLoading={isSubmitting || isSubmitSuccessful} type='submit'>\n Continue\n </Button>\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n </form>\n );\n}", "score": 92.38427129446467 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </p>\n <div>\n <input\n className='w-full border p-3'\n aria-label='6-Digit Code'\n type='text'\n inputMode='numeric'\n {...register('code')}\n />\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.code?.message}</span>}", "score": 74.57763023726497 }, { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": " type='email'\n autoCapitalize='off'\n autoCorrect='off'\n spellCheck='false'\n inputMode='email'\n className='rounded'\n {...register('email')}\n />\n {errors.email && <span className='mt-2 block text-left text-sm text-red-800'>{errors.email?.message}</span>}\n </div>", "score": 68.50885007115983 }, { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": " mutateAsync({ email: values.email }).catch((err) => {\n setError('root', { message: err.message });\n }),\n )}\n >\n <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1>\n <div>\n <Input\n aria-label='Email'\n placeholder='[email protected]'", "score": 60.055904473837124 } ]
typescript
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.
sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => {
if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) { const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 52.99812936068905 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}", "score": 42.3658903500518 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 40.0086192259373 }, { "filename": "src/tests/testRunner.ts", "retrieved_chunk": "\tconst project = new Project({ useInMemoryFileSystem: true })\n\tconst vfsMap = new Map<string, string>()\n\tconst vfs = createSystem(vfsMap)\n\tconst appContext: AppContext = {\n\t\tgql: schema,\n\t\tprisma: prismaModeller(prisma),\n\t\ttsProject: project,\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tpathSettings: {", "score": 29.26209828343724 }, { "filename": "src/run.ts", "retrieved_chunk": "\tgetGraphQLSDLFromFile(settings)\n\tgetPrismaSchemaFromFile(settings)\n\tif (!gqlSchema) throw new Error(\"No GraphQL Schema was created during setup\")\n\tconst appContext: AppContext = {\n\t\tgql: gqlSchema,\n\t\tprisma: prismaSchema,\n\t\ttsProject: project,\n\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tpathSettings: settings,", "score": 27.396964500486497 } ]
typescript
sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => {
import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { varStartsWithUppercase } from "./utils.js" export const getCodeFactsForJSTSFileAtPath = (file: string, context: AppContext) => { const { pathSettings: settings } = context const fileKey = file.replace(settings.apiServicesPath, "") // const priorFacts = serviceInfo.get(fileKey) const fileFact: CodeFacts = {} const fileContents = context.sys.readFile(file) const referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true }) const vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported()) const resolverContainers = vars.filter(varStartsWithUppercase) const queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v)) queryOrMutationResolvers.forEach((v) => { const parent = "maybe_query_mutation" const facts = getResolverInformationForDeclaration(v.getInitializer()) // Start making facts about the services const fact: ModelResolverFacts = fileFact[parent] ?? { typeName: parent, resolvers: new Map(), hasGenericArg: false, } fact.resolvers.set(v.getName(), { name: v.getName(), ...facts }) fileFact[parent] = fact }) // Next all the capital consts resolverContainers.forEach((c) => { addCustomTypeResolvers(c) }) return fileFact function addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) { const declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations() declarations.forEach((d) => { const name = d.getName() // only do it if the first letter is a capital if (!name.match(/^[A-Z]/)) return const type = d.getType() const hasGenericArg = type.getText().includes("<") // Start making facts about the services
const fact: ModelResolverFacts = fileFact[name] ?? {
typeName: name, resolvers: new Map(), hasGenericArg, } // Grab the const Thing = { ... } const obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression) if (!obj) { throw new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`) } obj.getProperties().forEach((p) => { if (p.isKind(tsMorph.SyntaxKind.SpreadAssignment)) { return } if (p.isKind(tsMorph.SyntaxKind.PropertyAssignment) && p.hasInitializer()) { const name = p.getName() fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p.getInitializerOrThrow()) }) } if (p.isKind(tsMorph.SyntaxKind.FunctionDeclaration) && p.getName()) { const name = p.getName() // @ts-expect-error - lets let this go for now fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p) }) } }) fileFact[d.getName()] = fact }) } } const getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, "name"> => { // Who knows what folks could do, lets not crash if (!initialiser) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } } // resolver is a fn if (initialiser.isKind(tsMorph.SyntaxKind.ArrowFunction) || initialiser.isKind(tsMorph.SyntaxKind.FunctionExpression)) { return { funcArgCount: initialiser.getParameters().length, isFunc: true, isAsync: initialiser.isAsync(), isUnknown: false, isObjLiteral: false, } } // resolver is a raw obj if ( initialiser.isKind(tsMorph.SyntaxKind.ObjectLiteralExpression) || initialiser.isKind(tsMorph.SyntaxKind.StringLiteral) || initialiser.isKind(tsMorph.SyntaxKind.NumericLiteral) || initialiser.isKind(tsMorph.SyntaxKind.TrueKeyword) || initialiser.isKind(tsMorph.SyntaxKind.FalseKeyword) || initialiser.isKind(tsMorph.SyntaxKind.NullKeyword) || initialiser.isKind(tsMorph.SyntaxKind.UndefinedKeyword) ) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: false, isObjLiteral: true, } } // who knows return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } }
src/serviceFile.codefacts.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tfunction addCustomTypeModel(modelFacts: ModelResolverFacts) {\n\t\tconst modelName = modelFacts.typeName\n\t\textraPrismaReferences.add(modelName)\n\t\t// Make an interface, this is the version we are replacing from graphql-codegen:\n\t\t// Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>;\n\t\tconst gqlType = gql.getType(modelName)\n\t\tif (!gqlType) {\n\t\t\t// throw new Error(`Could not find a GraphQL type named ${d.getName()}`);\n\t\t\tfileDTS.addStatements(`\\n// ${modelName} does not exist in the schema`)\n\t\t\treturn", "score": 32.27725270876292 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\tconst parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined\n\t\t\tif (parentName) {\n\t\t\t\taddDefinitionsForTopLevelResolvers(parentName, v)\n\t\t\t} else {\n\t\t\t\t// Add warning about unused resolver\n\t\t\t\tfileDTS.addStatements(`\\n// ${v.name} does not exist on Query or Mutation`)\n\t\t\t}\n\t\t})\n\t// Add the root function declarations\n\tObject.values(fileFacts).forEach((model) => {", "score": 29.77147283380249 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t// The file we'll be creating in-memory throughout this fn\n\tconst fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, \"\", { overwrite: true })\n\t// Basically if a top level resolver reference Query or Mutation\n\tconst knownSpecialCasesForGraphQL = new Set<string>()\n\t// Add the root function declarations\n\tconst rootResolvers = fileFacts.maybe_query_mutation?.resolvers\n\tif (rootResolvers)\n\t\trootResolvers.forEach((v) => {\n\t\t\tconst isQuery = v.name in queryType.getFields()\n\t\t\tconst isMutation = v.name in mutationType.getFields()", "score": 29.706530302688417 }, { "filename": "src/context.ts", "retrieved_chunk": "\t/** A global set of facts about resolvers focused from the GQL side */\n\tfieldFacts: Map<string, FieldFacts>\n\t/** When we emit .d.ts files, it runs the ts formatter over the file first - you can override the default settings */\n\tformatCodeSettings?: FormatCodeSettings\n\t/** So you can override the formatter */\n\tgql: graphql.GraphQLSchema\n\t/** POSXIY- fn not built into System */\n\tjoin: (...paths: string[]) => string\n\t/** Where to find particular files */\n\tpathSettings: {", "score": 27.09346690857913 }, { "filename": "src/tests/serviceFile.test.ts", "retrieved_chunk": "export const game = () => {}\nexport function game2() {}\n `\n\t)\n\texpect(vfsMap.has(\"/types/example.d.ts\")).toBeFalsy()\n\tlookAtServiceFile(\"/api/src/services/example.ts\", appContext)\n\t// this isn't really very useful as a test, but it proves it doesn't crash?\n})\nit(\"generates useful service facts from a (truncated) real file\", () => {\n\tconst { appContext, vfsMap } = getDTSFilesForRun({})", "score": 26.094864578461593 } ]
typescript
const fact: ModelResolverFacts = fileFact[name] ?? {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config)
context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t})\n\t\t})\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}", "score": 53.57110580415736 }, { "filename": "src/tests/features/preferPromiseFnWhenKnown.test.ts", "retrieved_chunk": "\tconst { vfsMap } = getDTSFilesForRun({ sdl, gamesService, prismaSchema })\n\tconst dts = vfsMap.get(\"/types/games.d.ts\")!\n\texpect(dts.trim()).toMatchInlineSnapshot(`\n\t\t\"import type { Game as PGame } from \\\\\"@prisma/client\\\\\";\n\t\timport type { GraphQLResolveInfo } from \\\\\"graphql\\\\\";\n\t\timport type { RedwoodGraphQLContext } from \\\\\"@redwoodjs/graphql-server/dist/types\\\\\";\n\t\timport type { Game as RTGame } from \\\\\"./shared-return-types\\\\\";\n\t\timport type { Query } from \\\\\"./shared-schema-types\\\\\";\n\t\t/** SDL: gameSync: Game */\n\t\texport interface GameSyncResolver {", "score": 53.10480639286826 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t}))\n\t\t)\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}\nfunction createSharedReturnPositionSchemaFile(context: AppContext) {\n\tconst { gql, prisma, fieldFacts } = context", "score": 52.08819597508079 }, { "filename": "src/tests/features/returnTypePositionsWhichPreferPrisma.test.ts", "retrieved_chunk": "\tconst dts = vfsMap.get(\"/types/games.d.ts\")!\n\texpect(dts.trimStart()).toMatchInlineSnapshot(\n\t\t`\n\t\t\"import type { Game as PGame } from \\\\\"@prisma/client\\\\\";\n\t\timport type { GraphQLResolveInfo } from \\\\\"graphql\\\\\";\n\t\timport type { RedwoodGraphQLContext } from \\\\\"@redwoodjs/graphql-server/dist/types\\\\\";\n\t\timport type { Game as RTGame } from \\\\\"./shared-return-types\\\\\";\n\t\timport type { Query } from \\\\\"./shared-schema-types\\\\\";\n\t\t/** SDL: game: Game */\n\t\texport interface GameResolver {", "score": 51.703935336574276 }, { "filename": "src/tests/vendor/soccersage-output/seasons.d.ts", "retrieved_chunk": "import type { CreateSeasonInput, UpdateSeasonInput } from \"./shared-schema-types\";\nimport type { Season as RTSeason, Prediction as RTPrediction } from \"./shared-return-types\";\nimport type { Prediction as PPrediction, Season as PSeason } from \"@prisma/client\";\nimport type { GraphQLResolveInfo } from \"graphql\";\nimport type { RedwoodGraphQLContext } from \"@redwoodjs/graphql-server/dist/functions/types\";\n/** SDL: seasons: [Season!]! */\nexport interface SeasonsResolver {\n (args?: object, obj?: { root: object, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }): RTSeason[] | Promise<RTSeason[]> | (() => Promise<RTSeason[]>);\n}\n/** SDL: season(id: Int!): Season */", "score": 36.94564840113404 } ]
typescript
context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) {
const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>;
const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/typeFacts.ts", "retrieved_chunk": "\thasGenericArg: boolean\n\t/** Individual resolvers found for this model */\n\tresolvers: Map<string, ResolverFuncFact>\n\t/** The name (or lack of) for the GraphQL type which we are mapping */\n\ttypeName: string | \"maybe_query_mutation\"\n}\nexport interface ResolverFuncFact {\n\t/** How many args are defined? */\n\tfuncArgCount: number\n\t/** Is it declared as an async fn */", "score": 29.852737352839732 }, { "filename": "src/context.ts", "retrieved_chunk": "\t/** An implementation of the TypeScript system, this can be grabbed pretty\n\t * easily from the typescript import, or you can use your own like tsvfs in browsers.\n\t */\n\tsys: System\n\t/** ts-morph is used to abstract over the typescript compiler API, this project file\n\t * is a slightly augmented version of the typescript Project api.\n\t */\n\ttsProject: tsMorph.Project\n}", "score": 28.736866588215864 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 27.56060813090091 }, { "filename": "src/types.ts", "retrieved_chunk": "import type { System } from \"typescript\"\nexport interface SDLCodeGenOptions {\n\t/** We'll use the one which comes with TypeScript if one isn't given */\n\tsystem?: System\n}\n// These are directly ported from Redwood at\n// packages/project-config/src/paths.ts\n// Slightly amended to reduce the constraints on the Redwood team to make changes to this obj!\ninterface NodeTargetPaths {\n\tbase: string", "score": 27.07443316109728 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "// the type in the SDL and not have to worry about type mis-matches because the thing\n// you returned does not include those functions.\n// This gets particularly valuable when you want to return a union type, an interface, \n// or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.)\n`\n\t)\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}", "score": 26.914030938773756 } ]
typescript
const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>;
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath) const formatted
= formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (!shouldWriteDTS) return\n\tconst config = getPrettierConfig(dtsFilepath)\n\tconst formatted = formatDTS(dtsFilepath, dts, config)\n\tcontext.sys.writeFile(dtsFilepath, formatted)\n\treturn dtsFilepath\n\tfunction addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {\n\t\tconst { name } = config\n\t\tlet field = queryType.getFields()[name]\n\t\tif (!field) {\n\t\t\tfield = mutationType.getFields()[name]", "score": 45.767897787644955 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}", "score": 23.28317265540906 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "import * as graphql from \"graphql\"\nimport { AppContext } from \"./context.js\"\nimport { formatDTS, getPrettierConfig } from \"./formatDTS.js\"\nimport { getCodeFactsForJSTSFileAtPath } from \"./serviceFile.codefacts.js\"\nimport { CodeFacts, ModelResolverFacts, ResolverFuncFact } from \"./typeFacts.js\"\nimport { TypeMapper, typeMapper } from \"./typeMap.js\"\nimport { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from \"./utils.js\"\nexport const lookAtServiceFile = (file: string, context: AppContext) => {\n\tconst { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition", "score": 20.280902945513592 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t}\n\tserviceFacts.set(fileKey, thisFact)\n\tconst dtsFilename = filename.endsWith(\".ts\") ? filename.replace(\".ts\", \".d.ts\") : filename.replace(\".js\", \".d.ts\")\n\tconst dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename)\n\t// Some manual formatting tweaks so we align with Redwood's setup more\n\tconst dts = fileDTS\n\t\t.getText()\n\t\t.replace(`from \"graphql\";`, `from \"graphql\";\\n`)\n\t\t.replace(`from \"@redwoodjs/graphql-server/dist/types\";`, `from \"@redwoodjs/graphql-server/dist/types\";\\n`)\n\tconst shouldWriteDTS = !!dts.trim().length", "score": 18.39789789389552 }, { "filename": "src/run.ts", "retrieved_chunk": "import { CodeFacts, FieldFacts } from \"./typeFacts.js\"\nexport function run(\n\tappRoot: string,\n\ttypesRoot: string,\n\tconfig: { deleteOldGraphQLDTS?: boolean; runESLint?: boolean; sys?: typescript.System } = {}\n) {\n\tconst sys = config.sys ?? typescript.sys\n\tconst project = new Project({ useInMemoryFileSystem: true })\n\tlet gqlSchema: graphql.GraphQLSchema | undefined\n\tconst getGraphQLSDLFromFile = (settings: AppContext[\"pathSettings\"]) => {", "score": 18.348113635947485 } ]
typescript
= formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file
modelFacts.resolvers.forEach((resolver) => {
const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/typeFacts.ts", "retrieved_chunk": "\thasGenericArg: boolean\n\t/** Individual resolvers found for this model */\n\tresolvers: Map<string, ResolverFuncFact>\n\t/** The name (or lack of) for the GraphQL type which we are mapping */\n\ttypeName: string | \"maybe_query_mutation\"\n}\nexport interface ResolverFuncFact {\n\t/** How many args are defined? */\n\tfuncArgCount: number\n\t/** Is it declared as an async fn */", "score": 51.62861984107644 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 46.21955149736491 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tresolvers: new Map(),\n\t\t\thasGenericArg: false,\n\t\t}\n\t\tfact.resolvers.set(v.getName(), { name: v.getName(), ...facts })\n\t\tfileFact[parent] = fact\n\t})\n\t// Next all the capital consts\n\tresolverContainers.forEach((c) => {\n\t\taddCustomTypeResolvers(c)\n\t})", "score": 44.95333660872686 }, { "filename": "src/tests/features/warnOnSuperfluousResolvers.test.ts", "retrieved_chunk": "import { expect, it } from \"vitest\"\nimport { getDTSFilesForRun, graphql, prisma } from \"../testRunner.js\"\nit(\"It prints a warning, and doesn't crash when you have resolvers which exist but are not on the parent\", () => {\n\tconst prismaSchema = prisma`\nmodel Game {\n id Int @id @default(autoincrement())\n homeTeamID Int\n awayTeamID Int\n}\n`", "score": 36.55777867213621 }, { "filename": "src/typeMap.ts", "retrieved_chunk": "\t\ttype: graphql.GraphQLType,\n\t\tmapConfig: {\n\t\t\tparentWasNotNull?: true\n\t\t\tpreferNullOverUndefined?: true\n\t\t\ttypenamePrefix?: string\n\t\t}\n\t): string | undefined => {\n\t\tconst prefix = mapConfig.typenamePrefix ?? \"\"\n\t\t// The AST for GQL uses a parent node to indicate the !, we need the opposite\n\t\t// for TS which uses '| undefined' after.", "score": 34.24844366480463 } ]
typescript
modelFacts.resolvers.forEach((resolver) => {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args =
createAndReferOrInlineArgsForField(field, {
name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/utils.ts", "retrieved_chunk": "\t\tnoSeparateType?: true\n\t}\n) => {\n\tconst inlineArgs = inlineArgsForField(field, config)\n\tif (!inlineArgs) return undefined\n\tif (inlineArgs.length < 120) return inlineArgs\n\tconst argsInterface = config.file.addInterface({\n\t\tname: `${config.name}Args`,\n\t\tisExported: true,\n\t})", "score": 35.58648427079362 }, { "filename": "src/utils.ts", "retrieved_chunk": "export const inlineArgsForField = (field: graphql.GraphQLField<unknown, unknown>, config: { mapper: TypeMapper[\"map\"] }) => {\n\treturn field.args.length\n\t\t? // Always use an args obj\n\t\t `{${field.args\n\t\t\t\t.map((f) => {\n\t\t\t\t\tconst type = config.mapper(f.type, {})\n\t\t\t\t\tif (!type) throw new Error(`No type for ${f.name} on ${field.name}!`)\n\t\t\t\t\tconst q = type.includes(\"undefined\") ? \"?\" : \"\"\n\t\t\t\t\tconst displayType = type.replace(\"| undefined\", \"\")\n\t\t\t\t\treturn `${f.name}${q}: ${displayType}`", "score": 33.454372611999055 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\tconst field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = {\n\t\t\t\t\t\t\tname: fieldName,\n\t\t\t\t\t\t\ttype: mapper.map(type, { preferNullOverUndefined: true }),\n\t\t\t\t\t\t\tdocs,\n\t\t\t\t\t\t\thasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma),\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn field\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})", "score": 32.110560112424096 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t\t\t\t})\n\t\t\t\t.join(\", \")}}`\n\t\t: undefined\n}\nexport const createAndReferOrInlineArgsForField = (\n\tfield: graphql.GraphQLField<unknown, unknown>,\n\tconfig: {\n\t\tfile: tsMorph.SourceFile\n\t\tmapper: TypeMapper[\"map\"]\n\t\tname: string", "score": 31.663999614306043 }, { "filename": "src/utils.ts", "retrieved_chunk": "\tfield.args.forEach((a) => {\n\t\targsInterface.addProperty({\n\t\t\tname: a.name,\n\t\t\ttype: config.mapper(a.type, {}),\n\t\t})\n\t})\n\treturn `${config.name}Args`\n}", "score": 27.724018618299 } ]
typescript
createAndReferOrInlineArgsForField(field, {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const
hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({
name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/tests/vendor/soccersage.io-main/api/src/services/predictions/predictions.ts", "retrieved_chunk": " // re-retrieval of game data for each prediction.\n // Other options to consider if/when more users join:\n // 1. - Query for all predictions in a season and all games in a season concurrently.\n // a. - This is still not as performant as possible, but would reduce duplicate data and retain live standings.\n // 2. - Store standings in a separate schema, and have a CRON job that updates them once an hour.\n // a. - This would allow for a much more performant solution, but would remove the ability to have live standings.\n const predictions = await db.prediction.findMany({\n where: { seasonId },\n include: {\n game: true,", "score": 29.52900649181514 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tconst fact: ModelResolverFacts = fileFact[name] ?? {\n\t\t\t\ttypeName: name,\n\t\t\t\tresolvers: new Map(),\n\t\t\t\thasGenericArg,\n\t\t\t}\n\t\t\t// Grab the const Thing = { ... }\n\t\t\tconst obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression)\n\t\t\tif (!obj) {\n\t\t\t\tthrow new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`)\n\t\t\t}", "score": 23.116391108554655 }, { "filename": "src/tests/vendor/soccersage-output/shared-return-types.d.ts", "retrieved_chunk": "import type { Game as PGame, Prediction as PPrediction, Season as PSeason, Team as PTeam, User as PUser } from \"@prisma/client\";\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend\n// the type in the SDL and not have to worry about type mis-matches because the thing\n// you returned does not include those functions.\n// This gets particularly useful when you want to return a union type, an interface, \n// or a model where the prisma model is nested pretty deeply (connections, for example.)\nexport interface CreateGameInput {\n __typename?: \"CreateGameInput\";", "score": 22.876571678546487 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "// the type in the SDL and not have to worry about type mis-matches because the thing\n// you returned does not include those functions.\n// This gets particularly valuable when you want to return a union type, an interface, \n// or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.)\n`\n\t)\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}", "score": 21.7889869274095 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\tif (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) {\n\t\t\t// This is slower than it could be, use the add many at once api\n\t\t\tconst docs = []\n\t\t\tif (pType?.leadingComments) {\n\t\t\t\tdocs.push(pType.leadingComments)\n\t\t\t}\n\t\t\tif (type.description) {\n\t\t\t\tdocs.push(type.description)\n\t\t\t}\n\t\t\texternalTSFile.addInterface({", "score": 21.13297161870373 } ]
typescript
hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({
import { scrapeContent } from "../../scraper/pornhub/pornhubSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; const sorting = ["mr", "mv", "tr", "lg"]; export async function searchPornhub(req: Request, res: Response) { try { /** * @api {get} /pornhub/search Search pornhub videos * @apiName Search pornhub * @apiGroup pornhub * @apiDescription Search pornhub videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * @apiParam {String} [sort=mr] Sort by * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/pornhub/search?key=milf * curl -i https://lust.scathach.id/pornhub/search?key=milf&page=2&sort=mr * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/pornhub/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/pornhub/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; const sort = req.query.sort as string; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); let url; if (!sort) url =
`${c.PORNHUB}/video/search?search=${spacer(key)}`;
else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`; else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`; console.log(url); const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/pornhub/pornhubSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 98.919650264194 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 98.919650264194 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 98.919650264194 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 97.8510795043313 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 97.8510795043313 } ]
typescript
`${c.PORNHUB}/video/search?search=${spacer(key)}`;
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config)
context.sys.writeFile(fullPath, formatted) }
function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (!shouldWriteDTS) return\n\tconst config = getPrettierConfig(dtsFilepath)\n\tconst formatted = formatDTS(dtsFilepath, dts, config)\n\tcontext.sys.writeFile(dtsFilepath, formatted)\n\treturn dtsFilepath\n\tfunction addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {\n\t\tconst { name } = config\n\t\tlet field = queryType.getFields()[name]\n\t\tif (!field) {\n\t\t\tfield = mutationType.getFields()[name]", "score": 47.6235323273946 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}", "score": 23.28317265540906 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t}\n\tserviceFacts.set(fileKey, thisFact)\n\tconst dtsFilename = filename.endsWith(\".ts\") ? filename.replace(\".ts\", \".d.ts\") : filename.replace(\".js\", \".d.ts\")\n\tconst dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename)\n\t// Some manual formatting tweaks so we align with Redwood's setup more\n\tconst dts = fileDTS\n\t\t.getText()\n\t\t.replace(`from \"graphql\";`, `from \"graphql\";\\n`)\n\t\t.replace(`from \"@redwoodjs/graphql-server/dist/types\";`, `from \"@redwoodjs/graphql-server/dist/types\";\\n`)\n\tconst shouldWriteDTS = !!dts.trim().length", "score": 21.413157440442976 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "import * as graphql from \"graphql\"\nimport { AppContext } from \"./context.js\"\nimport { formatDTS, getPrettierConfig } from \"./formatDTS.js\"\nimport { getCodeFactsForJSTSFileAtPath } from \"./serviceFile.codefacts.js\"\nimport { CodeFacts, ModelResolverFacts, ResolverFuncFact } from \"./typeFacts.js\"\nimport { TypeMapper, typeMapper } from \"./typeMap.js\"\nimport { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from \"./utils.js\"\nexport const lookAtServiceFile = (file: string, context: AppContext) => {\n\tconst { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition", "score": 20.280902945513592 }, { "filename": "src/run.ts", "retrieved_chunk": "import { CodeFacts, FieldFacts } from \"./typeFacts.js\"\nexport function run(\n\tappRoot: string,\n\ttypesRoot: string,\n\tconfig: { deleteOldGraphQLDTS?: boolean; runESLint?: boolean; sys?: typescript.System } = {}\n) {\n\tconst sys = config.sys ?? typescript.sys\n\tconst project = new Project({ useInMemoryFileSystem: true })\n\tlet gqlSchema: graphql.GraphQLSchema | undefined\n\tconst getGraphQLSDLFromFile = (settings: AppContext[\"pathSettings\"]) => {", "score": 18.348113635947485 } ]
typescript
context.sys.writeFile(fullPath, formatted) }
import { Request, Response } from "express"; import { scrapeContent } from "../../scraper/pornhub/pornhubGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; export async function randomPornhub(req: Request, res: Response) { try { /** * @api {get} /pornhub/random Random pornhub video * @apiName Random pornhub * @apiGroup pornhub * @apiDescription Gets random pornhub video * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/pornhub/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/pornhub/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/pornhub/random") as resp: * print(await resp.json()) * */ const
url = `${c.PORNHUB}/video/random`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/pornhub/pornhubRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/pornhub/pornhubGetRelated.ts", "retrieved_chunk": " * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/get?id=ph63c4e1dc48fe7\") as resp:\n * print(await resp.json())\n */\n const url = `${c.PORNHUB}/view_video.php?viewkey=${id}`;\n const data = await scrapeContent(url);\n logger.info({", "score": 58.60686834554006 }, { "filename": "src/controller/pornhub/pornhubGet.ts", "retrieved_chunk": " * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/get?id=ph63c4e1dc48fe7\") as resp:\n * print(await resp.json())\n */\n const url = `${c.PORNHUB}/view_video.php?viewkey=${id}`;\n const data = await scrapeContent(url);\n logger.info({", "score": 58.60686834554006 }, { "filename": "src/controller/redtube/redtubeRandom.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.REDTUBE);\n const $ = load(resolve);", "score": 55.55729524789697 }, { "filename": "src/controller/xvideos/xvideosRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.XVIDEOS);\n const $ = load(resolve);\n const search = $(\"div.thumb-under\")\n .find(\"a\")", "score": 54.79669526425773 }, { "filename": "src/controller/xnxx/xnxxRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(\"https://www.xnxx.com/search/random/random\");\n const $ = load(resolve);\n const search = $(\"div.mozaique > div\")\n .map((i, el) => {", "score": 54.67229386573682 } ]
typescript
url = `${c.PORNHUB}/video/random`;
import * as graphql from "graphql" import { AppContext } from "./context.js" export type TypeMapper = ReturnType<typeof typeMapper> export const typeMapper = (context: AppContext, config: { preferPrismaModels?: true }) => { const referencedGraphQLTypes = new Set<string>() const referencedPrismaModels = new Set<string>() const customScalars = new Set<string>() const clear = () => { referencedGraphQLTypes.clear() customScalars.clear() referencedPrismaModels.clear() } const getReferencedGraphQLThingsInMapping = () => { return { types: [...referencedGraphQLTypes.keys()], scalars: [...customScalars.keys()], prisma: [...referencedPrismaModels.keys()], } } const map = ( type: graphql.GraphQLType, mapConfig: { parentWasNotNull?: true preferNullOverUndefined?: true typenamePrefix?: string } ): string | undefined => { const prefix = mapConfig.typenamePrefix ?? "" // The AST for GQL uses a parent node to indicate the !, we need the opposite // for TS which uses '| undefined' after. if (graphql.isNonNullType(type)) { return map(type.ofType, { parentWasNotNull: true, ...mapConfig }) } // So we can add the | undefined const getInner = () => { if (graphql.isListType(type)) { const typeStr = map(type.ofType, mapConfig) if (!typeStr) return "any" if (graphql.isNonNullType(type.ofType)) { return `${typeStr}[]` } else { return `Array<${typeStr}>` } } if (graphql.isScalarType(type)) { switch (type.toString()) { case "Int": return "number" case "Float": return "number" case "String": return "string" case "Boolean": return "boolean" } customScalars.add(type.name) return type.name } if (graphql.isObjectType(type)) { if (config
.preferPrismaModels && context.prisma.has(type.name)) {
referencedPrismaModels.add(type.name) return "P" + type.name } else { // GraphQL only type referencedGraphQLTypes.add(type.name) return prefix + type.name } } if (graphql.isInterfaceType(type)) { return prefix + type.name } if (graphql.isUnionType(type)) { const types = type.getTypes() return types.map((t) => map(t, mapConfig)).join(" | ") } if (graphql.isEnumType(type)) { return prefix + type.name } if (graphql.isInputObjectType(type)) { referencedGraphQLTypes.add(type.name) return prefix + type.name } // eslint-disable-next-line @typescript-eslint/restrict-template-expressions throw new Error(`Unknown type ${type} - ${JSON.stringify(type, null, 2)}`) } const suffix = mapConfig.parentWasNotNull ? "" : mapConfig.preferNullOverUndefined ? "| null" : " | undefined" return getInner() + suffix } return { map, clear, getReferencedGraphQLThingsInMapping } }
src/typeMap.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)\n\t\tif (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) {\n\t\t\t// Return straight away if we have a matching type in the prisma schema\n\t\t\t// as we dont need it\n\t\t\tif (pType) {\n\t\t\t\ttypesToImport.push(name)", "score": 26.413873253576277 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\t}\n\t\t\t\t\t\treturn field\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\tif (graphql.isEnumType(type)) {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tname: type.name,\n\t\t\t\ttype:", "score": 22.527390265067126 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, \"\")\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}\n\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)", "score": 21.65251486417352 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\tfile: fileDTS,\n\t\t\tmapper: externalMapper.map,\n\t\t})\n\t\tif (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name)\n\t\tif (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name)\n\t\tconst argsParam = args ?? \"object\"\n\t\tconst returnType = returnTypeForResolver(returnTypeMapper, field, config)\n\t\tinterfaceDeclaration.addCallSignature({\n\t\t\tparameters: [\n\t\t\t\t{ name: \"args\", type: argsParam, hasQuestionToken: config.funcArgCount < 1 },", "score": 21.2428586569724 }, { "filename": "src/utils.ts", "retrieved_chunk": "export const inlineArgsForField = (field: graphql.GraphQLField<unknown, unknown>, config: { mapper: TypeMapper[\"map\"] }) => {\n\treturn field.args.length\n\t\t? // Always use an args obj\n\t\t `{${field.args\n\t\t\t\t.map((f) => {\n\t\t\t\t\tconst type = config.mapper(f.type, {})\n\t\t\t\t\tif (!type) throw new Error(`No type for ${f.name} on ${field.name}!`)\n\t\t\t\t\tconst q = type.includes(\"undefined\") ? \"?\" : \"\"\n\t\t\t\t\tconst displayType = type.replace(\"| undefined\", \"\")\n\t\t\t\t\treturn `${f.name}${q}: ${displayType}`", "score": 20.250770336104672 } ]
typescript
.preferPrismaModels && context.prisma.has(type.name)) {
import { scrapeContent } from "../../scraper/pornhub/pornhubSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; const sorting = ["mr", "mv", "tr", "lg"]; export async function searchPornhub(req: Request, res: Response) { try { /** * @api {get} /pornhub/search Search pornhub videos * @apiName Search pornhub * @apiGroup pornhub * @apiDescription Search pornhub videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * @apiParam {String} [sort=mr] Sort by * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/pornhub/search?key=milf * curl -i https://lust.scathach.id/pornhub/search?key=milf&page=2&sort=mr * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/pornhub/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/pornhub/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; const sort = req.query.sort as string; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); let url;
if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;
else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`; else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`; console.log(url); const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/pornhub/pornhubSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 120.3209991545255 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 120.3209991545255 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 120.3209991545255 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 119.25242839466279 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 119.25242839466279 } ]
typescript
if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;
import { scrapeContent } from "../../scraper/redtube/redtubeGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; import { Request, Response } from "express"; import { load } from "cheerio"; import LustPress from "../../LustPress"; const lust = new LustPress(); export async function randomRedtube(req: Request, res: Response) { try { /** * @api {get} /redtube/random Get random redtube * @apiName Get random redtube * @apiGroup redtube * @apiDescription Get a random redtube video * * @apiParam {String} id Video ID * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/redtube/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/redtube/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/redtube/random") as resp: * print(await resp.json()) */
const resolve = await lust.fetchBody(c.REDTUBE);
const $ = load(resolve); const search = $("a.video_link") .map((i, el) => { return $(el).attr("href"); }).get(); const random = Math.floor(Math.random() * search.length); const url = c.REDTUBE + search[random]; const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/redtube/redtubeRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/redtube/redtubeGet.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/get?id=42763661\") as resp:\n * print(await resp.json())\n */\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);", "score": 68.95752692488409 }, { "filename": "src/controller/xvideos/xvideosRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.XVIDEOS);\n const $ = load(resolve);\n const search = $(\"div.thumb-under\")\n .find(\"a\")", "score": 61.66271296439395 }, { "filename": "src/controller/youporn/youpornRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.YOUPORN}`);\n const $ = load(resolve);\n const search = $(\"a[href^='/watch/']\")\n .map((i, el) => {", "score": 61.12195467646738 }, { "filename": "src/controller/xnxx/xnxxRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(\"https://www.xnxx.com/search/random/random\");\n const $ = load(resolve);\n const search = $(\"div.mozaique > div\")\n .map((i, el) => {", "score": 59.689946385357956 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;", "score": 58.535083335165076 } ]
typescript
const resolve = await lust.fetchBody(c.REDTUBE);
import { scrapeContent } from "../../scraper/xnxx/xnxxGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; import { Request, Response } from "express"; import { load } from "cheerio"; import LustPress from "../../LustPress"; const lust = new LustPress(); export async function randomXnxx(req: Request, res: Response) { try { /** * @api {get} /xnxx/random Get random xnxx * @apiName Get random xnxx * @apiGroup xnxx * @apiDescription Get a random xnxx video * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xnxx/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xnxx/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xnxx/random") as resp: * print(await resp.json()) */ const resolve = await lust.fetchBody("https://www.xnxx.com/search/random/random"); const $ = load(resolve); const search = $("div.mozaique > div") .map((i, el) => { return $(el).find("a").attr("href"); }).get(); const random = Math.floor(Math.random() * search.length); const
url = c.XNXX + search[random];
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xnxx/xnxxRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/redtube/redtubeRandom.ts", "retrieved_chunk": " const search = $(\"a.video_link\")\n .map((i, el) => {\n return $(el).attr(\"href\");\n }).get();\n const random = Math.floor(Math.random() * search.length);\n const url = c.REDTUBE + search[random];\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,\n query: req.query,", "score": 72.13484269302486 }, { "filename": "src/controller/youporn/youpornRandom.ts", "retrieved_chunk": " return $(el).attr(\"href\");\n }).get();\n const random = Math.floor(Math.random() * search.length);\n const url = c.YOUPORN + search[random];\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,\n query: req.query,\n method: req.method,\n ip: req.ip,", "score": 64.62211140482907 }, { "filename": "src/controller/xvideos/xvideosRandom.ts", "retrieved_chunk": " .map((i, el) => $(el).attr(\"href\"))\n .get();\n const filtered = search.filter((el) => el.includes(\"/video\"));\n const filtered_ = filtered.filter((el) => !el.includes(\"THUMBNUM\"));\n const random = Math.floor(Math.random() * filtered_.length);\n const url = c.XVIDEOS + filtered[random];\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,\n query: req.query,", "score": 63.52327976111233 }, { "filename": "src/controller/xhamster/xhamsterRandom.ts", "retrieved_chunk": " .get();\n const search_ = search.map((el) => el.replace(c.XHAMSTER, \"\"));\n const random = Math.floor(Math.random() * search_.length);\n const url = c.XHAMSTER + search_[random];\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,\n query: req.query,\n method: req.method,\n ip: req.ip,", "score": 59.217463290588384 }, { "filename": "src/controller/youporn/youpornRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.YOUPORN}`);\n const $ = load(resolve);\n const search = $(\"a[href^='/watch/']\")\n .map((i, el) => {", "score": 51.86613155635024 } ]
typescript
url = c.XNXX + search[random];
import { scrapeContent } from "../../scraper/xhamster/xhamsterSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXhamster(req: Request, res: Response) { try { /** * @api {get} /xhamster/search Search xhamster videos * @apiName Search xhamster * @apiGroup xhamster * @apiDescription Search xhamster videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xhamster/search?key=milf * curl -i https://lust.scathach.id/xhamster/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xhamster/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xhamster/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); const
url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xhamster/xhamsterSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 131.6886413289896 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 131.6886413289896 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 130.61672068401506 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 130.61672068401506 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " const sort = req.query.sort as string;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");\n let url;\n if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;\n else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`;\n else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`;\n console.log(url);\n const data = await scrapeContent(url);\n logger.info({", "score": 102.27728380397464 } ]
typescript
url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
import { scrapeContent } from "../../scraper/redtube/redtubeSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchRedtube(req: Request, res: Response) { try { /** * @api {get} /redtube/search Search redtube videos * @apiName Search redtube * @apiGroup redtube * @apiDescription Search redtube videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/redtube/search?key=milf * curl -i https://lust.scathach.id/redtube/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/redtube/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/redtube/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number");
const url = `${c.REDTUBE}/?search=${spacer(key)}&page=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/redtube/redtubeSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 134.9344802104979 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 134.9344802104979 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 133.86255956552336 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 133.86255956552336 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " const sort = req.query.sort as string;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");\n let url;\n if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;\n else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`;\n else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`;\n console.log(url);\n const data = await scrapeContent(url);\n logger.info({", "score": 102.27724966713521 } ]
typescript
const url = `${c.REDTUBE}/?search=${spacer(key)}&page=${page}`;
import { scrapeContent } from "../../scraper/xhamster/xhamsterSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXhamster(req: Request, res: Response) { try { /** * @api {get} /xhamster/search Search xhamster videos * @apiName Search xhamster * @apiGroup xhamster * @apiDescription Search xhamster videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xhamster/search?key=milf * curl -i https://lust.scathach.id/xhamster/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xhamster/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xhamster/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number");
const url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xhamster/xhamsterSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 134.93452615850873 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 134.93452615850873 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 133.86260551353416 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 133.86260551353416 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " const sort = req.query.sort as string;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");\n let url;\n if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;\n else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`;\n else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`;\n console.log(url);\n const data = await scrapeContent(url);\n logger.info({", "score": 102.27728380397464 } ]
typescript
const url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
import { scrapeContent } from "../../scraper/xnxx/xnxxSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXnxx(req: Request, res: Response) { try { /** * @api {get} /xnxx/search Search xnxx videos * @apiName Search xnxx * @apiGroup xnxx * @apiDescription Search xnxx videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=0] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xnxx/search?key=milf * curl -i https://lust.scathach.id/xnxx/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xnxx/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xnxx/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 0; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); const url =
`${c.XNXX}/search/${spacer(key)}/${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xnxx/xnxxSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 128.51696307038105 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 126.73996544180227 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 126.73996544180227 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 126.73996544180227 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " const sort = req.query.sort as string;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");\n let url;\n if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;\n else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`;\n else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`;\n console.log(url);\n const data = await scrapeContent(url);\n logger.info({", "score": 98.10737831948641 } ]
typescript
`${c.XNXX}/search/${spacer(key)}/${page}`;
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log =
createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" );
const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath) ? readTypedJsonSync<IsolateConfig>(configFilePath) : {}; const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved; log.debug("Using configuration:", inspectValue(config)); __config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/index.ts", "retrieved_chunk": " */\n const targetPackageDir = config.targetPackagePath\n ? path.join(process.cwd(), config.targetPackagePath)\n : process.cwd();\n /**\n * We want a trailing slash here. Functionally it doesn't matter, but it makes\n * the relative paths more correct in the debug output.\n */\n const workspaceRootDir = config.targetPackagePath\n ? process.cwd()", "score": 30.66229705689511 }, { "filename": "src/utils/pack.ts", "retrieved_chunk": " `The response from pack could not be resolved to an existing file: ${filePath}`\n );\n } else {\n log.debug(`Packed (temp)/${fileName}`);\n }\n process.chdir(previousCwd);\n /**\n * Return the path anyway even if it doesn't validate. A later stage will wait\n * for the file to occur still. Not sure if this makes sense. Maybe we should\n * stop at the validation error...", "score": 25.29075516073468 }, { "filename": "src/helpers/get-build-output-dir.ts", "retrieved_chunk": " return path.join(targetPackageDir, outDir);\n } else {\n throw new Error(outdent`\n Failed to find outDir in tsconfig. If you are executing isolate from the root of a monorepo you should specify the buildDirName in isolate.config.json.\n `);\n }\n } else {\n log.warn(\"Failed to find tsconfig at:\", tsconfigPath);\n throw new Error(outdent`\n Failed to infer the build output directory from either the isolate config buildDirName or a Typescript config file. See the documentation on how to configure one of these options.", "score": 25.070359654871556 }, { "filename": "src/index.ts", "retrieved_chunk": "#!/usr/bin/env node\n/**\n * For PNPM the hashbang at the top of the script was not required, but Yarn 3\n * did not seem to execute without it.\n */\n/**\n * A word about used terminology:\n *\n * The various package managers, while being very similar, seem to use a\n * different definition for the term \"workspace\". If you want to read the code", "score": 23.607093370499733 }, { "filename": "src/helpers/process-lockfile.ts", "retrieved_chunk": "}\n/**\n * Adapt the lockfile and write it to the isolate directory. Because we keep the\n * structure of packages in the isolate directory the same as they were in the\n * monorepo, the lockfile is largely still correct. The only things that need to\n * be done is to remove the root dependencies and devDependencies, and rename\n * the path to the target package to act as the new root.\n */\nexport function processLockfile({\n workspaceRootDir,", "score": 22.65952575920938 } ]
typescript
createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" );
import { scrapeContent } from "../../scraper/xvideos/xvideosGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; import { Request, Response } from "express"; import { load } from "cheerio"; import LustPress from "../../LustPress"; const lust = new LustPress(); export async function randomXvideos(req: Request, res: Response) { try { /** * @api {get} /xvideos/random Get random xvideos * @apiName Get random xvideos * @apiGroup xvideos * @apiDescription Get a random xvideos video * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xvideos/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xvideos/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xvideos/random") as resp: * print(await resp.json()) */ const resolve = await
lust.fetchBody(c.XVIDEOS);
const $ = load(resolve); const search = $("div.thumb-under") .find("a") .map((i, el) => $(el).attr("href")) .get(); const filtered = search.filter((el) => el.includes("/video")); const filtered_ = filtered.filter((el) => !el.includes("THUMBNUM")); const random = Math.floor(Math.random() * filtered_.length); const url = c.XVIDEOS + filtered[random]; const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xvideos/xvideosRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/redtube/redtubeRandom.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.REDTUBE);\n const $ = load(resolve);", "score": 70.63072343427994 }, { "filename": "src/controller/youporn/youpornRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.YOUPORN}`);\n const $ = load(resolve);\n const search = $(\"a[href^='/watch/']\")\n .map((i, el) => {", "score": 61.07330186323901 }, { "filename": "src/controller/redtube/redtubeGet.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/get?id=42763661\") as resp:\n * print(await resp.json())\n */\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);", "score": 60.5779403475648 }, { "filename": "src/controller/xnxx/xnxxRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(\"https://www.xnxx.com/search/random/random\");\n const $ = load(resolve);\n const search = $(\"div.mozaique > div\")\n .map((i, el) => {", "score": 59.64209121661324 }, { "filename": "src/controller/xvideos/xvideosGet.ts", "retrieved_chunk": " * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/get?id=video73564387/cute_hentai_maid_with_pink_hair_fucking_uncensored_\") as resp:\n * print(await resp.json())\n */\n const url = `${c.XVIDEOS}/${id}`;\n const data = await scrapeContent(url);\n logger.info({", "score": 59.45052246113882 } ]
typescript
lust.fetchBody(c.XVIDEOS);
import fs from "fs-extra"; import { globSync } from "glob"; import path from "node:path"; import { createLogger, readTypedJson } from "~/utils"; import { getConfig } from "./config"; import { findPackagesGlobs } from "./find-packages-globs"; export type PackageManifest = { name: string; packageManager?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; main: string; module?: string; exports?: Record<string, { require: string; import: string }>; files: string[]; version?: string; typings?: string; scripts?: Record<string, string>; }; export type WorkspacePackageInfo = { absoluteDir: string; /** * The path of the package relative to the workspace root. This is the path * referenced in the lock file. */ rootRelativeDir: string; /** * The package.json file contents */ manifest: PackageManifest; }; export type PackagesRegistry = Record<string, WorkspacePackageInfo>; /** * Build a list of all packages in the workspace, depending on the package * manager used, with a possible override from the config file. The list contains * the manifest with some directory info mapped by module name. */ export async function createPackagesRegistry( workspaceRootDir: string, workspacePackagesOverride: string[] | undefined ): Promise<PackagesRegistry> { const log = createLogger(getConfig().logLevel); if (workspacePackagesOverride) { log.debug( `Override workspace packages via config: ${workspacePackagesOverride}` ); } const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir); const cwd = process.cwd(); process.chdir(workspaceRootDir); const allPackages = packagesGlobs .flatMap((glob) => globSync(glob)) /** * Make sure to filter any loose files that might hang around. */ .filter((dir) => fs.lstatSync(dir).isDirectory()); const registry: PackagesRegistry = ( await Promise.all(
allPackages.map(async (rootRelativeDir) => {
const manifestPath = path.join(rootRelativeDir, "package.json"); if (!fs.existsSync(manifestPath)) { log.warn( `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file` ); return; } else { log.debug(`Registering package ./${rootRelativeDir}`); const manifest = await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") ); return { manifest, rootRelativeDir, absoluteDir: path.join(workspaceRootDir, rootRelativeDir), }; } }) ) ).reduce<PackagesRegistry>((acc, info) => { if (info) { acc[info.manifest.name] = info; } return acc; }, {}); process.chdir(cwd); return registry; }
src/helpers/create-packages-registry.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/unpack-dependencies.ts", "retrieved_chunk": " isolateDir: string\n) {\n const log = createLogger(getConfig().logLevel);\n await Promise.all(\n Object.entries(packedFilesByName).map(async ([packageName, filePath]) => {\n const dir = packagesRegistry[packageName].rootRelativeDir;\n const unpackDir = join(tmpDir, dir);\n log.debug(\"Unpacking\", `(temp)/${path.basename(filePath)}`);\n await unpack(filePath, unpackDir);\n const destinationDir = join(isolateDir, dir);", "score": 25.869224232973636 }, { "filename": "src/helpers/adapt-manifest-files.ts", "retrieved_chunk": " packagesRegistry: PackagesRegistry,\n isolateDir: string\n) {\n await Promise.all(\n localDependencies.map(async (packageName) => {\n const { manifest, rootRelativeDir } = packagesRegistry[packageName];\n const outputManifest = adaptManifestWorkspaceDeps(\n { manifest, packagesRegistry, parentRootRelativeDir: rootRelativeDir },\n { includeDevDependencies: getConfig().includeDevDependencies }\n );", "score": 20.337470111174284 }, { "filename": "src/helpers/list-local-dependencies.ts", "retrieved_chunk": "import { PackageManifest, PackagesRegistry } from \"./create-packages-registry\";\n/**\n * Recursively list the packages from dependencies (and optionally\n * devDependencies) that are found in the workspace.\n *\n * Here we do not need to rely on packages being declared as \"workspace:\" in the\n * manifest. We can simply compare the package names with the list of packages\n * that were found via the workspace glob patterns and added to the registry.\n */\nexport function listLocalDependencies(", "score": 13.062025631808748 }, { "filename": "src/helpers/list-local-dependencies.ts", "retrieved_chunk": " ]\n : Object.keys(manifest.dependencies ?? {})\n ).filter((name) => allWorkspacePackageNames.includes(name));\n const nestedLocalDependencies = localDependencyPackageNames.flatMap(\n (packageName) =>\n listLocalDependencies(\n packagesRegistry[packageName].manifest,\n packagesRegistry,\n { includeDevDependencies }\n )", "score": 13.038620926329385 }, { "filename": "src/index.ts", "retrieved_chunk": " * it might be good to know that I consider the workspace to be the monorepo\n * itself, in other words, the overall structure that holds all the packages.\n */\nimport fs from \"fs-extra\";\nimport assert from \"node:assert\";\nimport path from \"node:path\";\nimport sourceMaps from \"source-map-support\";\nimport {\n PackageManifest,\n adaptManifestFiles,", "score": 12.60266884537621 } ]
typescript
allPackages.map(async (rootRelativeDir) => {
import { scrapeContent } from "../../scraper/xvideos/xvideosSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXvideos(req: Request, res: Response) { try { /** * @api {get} /xvideos/search Search xvideos videos * @apiName Search xvideos * @apiGroup xvideos * @apiDescription Search xvideos videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=0] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xvideos/search?key=milf * curl -i https://lust.scathach.id/xvideos/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xvideos/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xvideos/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 0; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); const url = `${c
.XVIDEOS}/?k=${spacer(key)}&p=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xvideos/xvideosSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 127.47570300263838 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 125.69880609123949 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 125.69880609123949 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 125.69880609123949 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " const sort = req.query.sort as string;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");\n let url;\n if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;\n else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`;\n else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`;\n console.log(url);\n const data = await scrapeContent(url);\n logger.info({", "score": 95.81988379565384 } ]
typescript
.XVIDEOS}/?k=${spacer(key)}&p=${page}`;
import assert from "node:assert"; import { createLogger, pack } from "~/utils"; import { getConfig } from "./config"; import { PackagesRegistry } from "./create-packages-registry"; import { usePackageManager } from "./detect-package-manager"; /** * Pack dependencies so that we extract only the files that are supposed to be * published by the packages. * * @returns A map of package names to the path of the packed file */ export async function packDependencies({ /** * All packages found in the monorepo by workspaces declaration */ packagesRegistry, /** * The package names that appear to be local dependencies */ localDependencies, /** * The directory where the isolated package and all its dependencies will end * up. This is also the directory from where the package will be deployed. By * default it is a subfolder in targetPackageDir called "isolate" but you can * configure it. */ packDestinationDir, }: { packagesRegistry: PackagesRegistry; localDependencies: string[]; packDestinationDir: string; }) { const config = getConfig(); const log = createLogger(config.logLevel); const packedFileByName: Record<string, string> = {}; const { name, version } = usePackageManager(); const versionMajor = parseInt(version.split(".")[0], 10); const usePnpmPack = !config.avoidPnpmPack && name === "pnpm" && versionMajor >= 8; if (usePnpmPack) { log.debug("Using PNPM pack instead of NPM pack"); } for (const dependency of localDependencies) { const def = packagesRegistry[dependency]; assert(dependency, `Failed to find package definition for ${dependency}`); const { name } = def.manifest; /** * If this dependency has already been packed, we skip it. It could happen * because we are packing workspace dependencies recursively. */ if (packedFileByName[name]) { log.debug(`Skipping ${name} because it has already been packed`); continue; }
packedFileByName[name] = await pack( def.absoluteDir, packDestinationDir, usePnpmPack );
} return packedFileByName; }
src/helpers/pack-dependencies.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/index.ts", "retrieved_chunk": " packageManager.version\n );\n /**\n * Disable lock files for PNPM because they are not yet supported.\n */\n if (packageManager.name === \"pnpm\") {\n config.excludeLockfile = true;\n }\n /**\n * Build a packages registry so we can find the workspace packages by name and", "score": 12.174844604240846 }, { "filename": "src/helpers/detect-package-manager.ts", "retrieved_chunk": " `Manifest declares ${name} to be the packageManager, but failed to find ${lockfileName} in workspace root`\n );\n return { name, version };\n}\nfunction inferFromFiles(workspaceRoot: string): PackageManager {\n for (const name of supportedPackageManagerNames) {\n const lockfileName = getLockfileFileName(name);\n if (fs.existsSync(path.join(workspaceRoot, lockfileName))) {\n return { name, version: getVersion(name) };\n }", "score": 11.520301923943826 }, { "filename": "src/utils/pack.ts", "retrieved_chunk": " const stdout = usePnpmPack\n ? await new Promise<string>((resolve, reject) => {\n exec(\n `pnpm pack --pack-destination ${dstDir}`,\n execOptions,\n (err, stdout, stderr) => {\n if (err) {\n log.error(stderr);\n return reject(err);\n }", "score": 10.961725088739938 }, { "filename": "src/index.ts", "retrieved_chunk": " */\n await processLockfile({\n workspaceRootDir,\n targetPackageName: targetPackageManifest.name,\n isolateDir,\n packagesRegistry,\n });\n }\n /**\n * If there is an .npmrc file in the workspace root, copy it to the", "score": 10.1007848126746 }, { "filename": "src/helpers/detect-package-manager.ts", "retrieved_chunk": " PackageManagerName,\n string,\n ];\n assert(\n supportedPackageManagerNames.includes(name),\n `Package manager \"${name}\" is not currently supported`\n );\n const lockfileName = getLockfileFileName(name);\n assert(\n fs.existsSync(path.join(workspaceRoot, lockfileName)),", "score": 10.015855137275187 } ]
typescript
packedFileByName[name] = await pack( def.absoluteDir, packDestinationDir, usePnpmPack );
import { scrapeContent } from "../../scraper/xnxx/xnxxSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXnxx(req: Request, res: Response) { try { /** * @api {get} /xnxx/search Search xnxx videos * @apiName Search xnxx * @apiGroup xnxx * @apiDescription Search xnxx videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=0] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xnxx/search?key=milf * curl -i https://lust.scathach.id/xnxx/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xnxx/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xnxx/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 0; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number");
const url = `${c.XNXX}/search/${spacer(key)}/${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xnxx/xnxxSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 131.76299434414918 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 129.9859967155704 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 129.9859967155704 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 129.9859967155704 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " const sort = req.query.sort as string;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");\n let url;\n if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;\n else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`;\n else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`;\n console.log(url);\n const data = await scrapeContent(url);\n logger.info({", "score": 98.10737831948641 } ]
typescript
const url = `${c.XNXX}/search/${spacer(key)}/${page}`;
import fs from "fs-extra"; import { globSync } from "glob"; import path from "node:path"; import { createLogger, readTypedJson } from "~/utils"; import { getConfig } from "./config"; import { findPackagesGlobs } from "./find-packages-globs"; export type PackageManifest = { name: string; packageManager?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; main: string; module?: string; exports?: Record<string, { require: string; import: string }>; files: string[]; version?: string; typings?: string; scripts?: Record<string, string>; }; export type WorkspacePackageInfo = { absoluteDir: string; /** * The path of the package relative to the workspace root. This is the path * referenced in the lock file. */ rootRelativeDir: string; /** * The package.json file contents */ manifest: PackageManifest; }; export type PackagesRegistry = Record<string, WorkspacePackageInfo>; /** * Build a list of all packages in the workspace, depending on the package * manager used, with a possible override from the config file. The list contains * the manifest with some directory info mapped by module name. */ export async function createPackagesRegistry( workspaceRootDir: string, workspacePackagesOverride: string[] | undefined ): Promise<PackagesRegistry> { const log = createLogger(getConfig().logLevel); if (workspacePackagesOverride) { log.debug( `Override workspace packages via config: ${workspacePackagesOverride}` ); } const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir); const cwd = process.cwd(); process.chdir(workspaceRootDir); const allPackages = packagesGlobs .flatMap((glob) => globSync(glob)) /** * Make sure to filter any loose files that might hang around. */ .filter((dir) => fs.lstatSync(dir).isDirectory()); const registry: PackagesRegistry = ( await Promise.all( allPackages.map(async (rootRelativeDir) => { const manifestPath = path.join(rootRelativeDir, "package.json"); if (!fs.existsSync(manifestPath)) { log.warn( `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file` ); return; } else { log.debug(`Registering package ./${rootRelativeDir}`); const manifest =
await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") );
return { manifest, rootRelativeDir, absoluteDir: path.join(workspaceRootDir, rootRelativeDir), }; } }) ) ).reduce<PackagesRegistry>((acc, info) => { if (info) { acc[info.manifest.name] = info; } return acc; }, {}); process.chdir(cwd); return registry; }
src/helpers/create-packages-registry.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/adapt-manifest-files.ts", "retrieved_chunk": " await fs.writeFile(\n path.join(isolateDir, rootRelativeDir, \"package.json\"),\n JSON.stringify(outputManifest, null, 2)\n );\n })\n );\n}", "score": 25.18270728287888 }, { "filename": "src/helpers/patch-workspace-entries.ts", "retrieved_chunk": " *\n * For consistency we also write the other file paths starting with\n * ./, but it doesn't seem to be necessary for any package manager.\n */\n const relativePath = parentRootRelativeDir\n ? path.relative(parentRootRelativeDir, `./${def.rootRelativeDir}`)\n : `./${def.rootRelativeDir}`;\n const linkPath = `file:${relativePath}`;\n log.debug(`Linking dependency ${key} to ${linkPath}`);\n return [key, linkPath];", "score": 23.965931726577377 }, { "filename": "src/index.ts", "retrieved_chunk": " await fs.ensureDir(isolateDir);\n const tmpDir = path.join(isolateDir, \"__tmp\");\n await fs.ensureDir(tmpDir);\n const targetPackageManifest = await readTypedJson<PackageManifest>(\n path.join(targetPackageDir, \"package.json\")\n );\n const packageManager = detectPackageManager(workspaceRootDir);\n log.debug(\n \"Detected package manager\",\n packageManager.name,", "score": 19.83302056729015 }, { "filename": "src/index.ts", "retrieved_chunk": "async function start() {\n const __dirname = getDirname(import.meta.url);\n const thisPackageManifest = await readTypedJson<PackageManifest>(\n path.join(path.join(__dirname, \"..\", \"package.json\"))\n );\n log.debug(\"Running isolate-package version\", thisPackageManifest.version);\n /**\n * If a targetPackagePath is set, we assume the configuration lives in the\n * root of the workspace. If targetPackagePath is undefined (the default), we\n * assume that the configuration lives in the target package directory.", "score": 18.276190290123257 }, { "filename": "src/helpers/adapt-manifest-files.ts", "retrieved_chunk": " packagesRegistry: PackagesRegistry,\n isolateDir: string\n) {\n await Promise.all(\n localDependencies.map(async (packageName) => {\n const { manifest, rootRelativeDir } = packagesRegistry[packageName];\n const outputManifest = adaptManifestWorkspaceDeps(\n { manifest, packagesRegistry, parentRootRelativeDir: rootRelativeDir },\n { includeDevDependencies: getConfig().includeDevDependencies }\n );", "score": 18.073163968631565 } ]
typescript
await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") );
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log = createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" ); const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath)
? readTypedJsonSync<IsolateConfig>(configFilePath) : {};
const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved; log.debug("Using configuration:", inspectValue(config)); __config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/index.ts", "retrieved_chunk": " */\n const targetPackageDir = config.targetPackagePath\n ? path.join(process.cwd(), config.targetPackagePath)\n : process.cwd();\n /**\n * We want a trailing slash here. Functionally it doesn't matter, but it makes\n * the relative paths more correct in the debug output.\n */\n const workspaceRootDir = config.targetPackagePath\n ? process.cwd()", "score": 20.87326365915822 }, { "filename": "src/helpers/create-packages-registry.ts", "retrieved_chunk": "): Promise<PackagesRegistry> {\n const log = createLogger(getConfig().logLevel);\n if (workspacePackagesOverride) {\n log.debug(\n `Override workspace packages via config: ${workspacePackagesOverride}`\n );\n }\n const packagesGlobs =\n workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir);\n const cwd = process.cwd();", "score": 18.972124946192988 }, { "filename": "src/index.ts", "retrieved_chunk": " );\n const isolateDir = path.join(targetPackageDir, config.isolateDirName);\n log.debug(\n \"Isolate output directory\",\n getRootRelativePath(isolateDir, workspaceRootDir)\n );\n if (fs.existsSync(isolateDir)) {\n await fs.remove(isolateDir);\n log.debug(\"Cleaned the existing isolate output directory\");\n }", "score": 15.39109674954001 }, { "filename": "src/utils/pack.ts", "retrieved_chunk": " const execOptions = {\n maxBuffer: 10 * 1024 * 1024,\n };\n const log = createLogger(getConfig().logLevel);\n const previousCwd = process.cwd();\n process.chdir(srcDir);\n /**\n * PNPM pack seems to be a lot faster than NPM pack, so when PNPM is detected\n * we use that instead.\n */", "score": 14.987607050403218 }, { "filename": "src/helpers/detect-package-manager.ts", "retrieved_chunk": "import fs from \"fs-extra\";\nimport assert from \"node:assert\";\nimport { execSync } from \"node:child_process\";\nimport path from \"node:path\";\nimport { createLogger, readTypedJsonSync } from \"~/utils\";\nimport { getConfig } from \"./config\";\nimport { PackageManifest } from \"./create-packages-registry\";\nimport { getLockfileFileName } from \"./process-lockfile\";\nconst supportedPackageManagerNames = [\"pnpm\", \"yarn\", \"npm\"] as const;\nexport type PackageManagerName = (typeof supportedPackageManagerNames)[number];", "score": 14.448782665835294 } ]
typescript
? readTypedJsonSync<IsolateConfig>(configFilePath) : {};
import fs from "fs-extra"; import { globSync } from "glob"; import path from "node:path"; import { createLogger, readTypedJson } from "~/utils"; import { getConfig } from "./config"; import { findPackagesGlobs } from "./find-packages-globs"; export type PackageManifest = { name: string; packageManager?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; main: string; module?: string; exports?: Record<string, { require: string; import: string }>; files: string[]; version?: string; typings?: string; scripts?: Record<string, string>; }; export type WorkspacePackageInfo = { absoluteDir: string; /** * The path of the package relative to the workspace root. This is the path * referenced in the lock file. */ rootRelativeDir: string; /** * The package.json file contents */ manifest: PackageManifest; }; export type PackagesRegistry = Record<string, WorkspacePackageInfo>; /** * Build a list of all packages in the workspace, depending on the package * manager used, with a possible override from the config file. The list contains * the manifest with some directory info mapped by module name. */ export async function createPackagesRegistry( workspaceRootDir: string, workspacePackagesOverride: string[] | undefined ): Promise<PackagesRegistry> { const log = createLogger(getConfig().logLevel); if (workspacePackagesOverride) { log.debug( `Override workspace packages via config: ${workspacePackagesOverride}` ); } const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir); const cwd = process.cwd(); process.chdir(workspaceRootDir); const allPackages = packagesGlobs .flatMap((glob) => globSync(glob)) /** * Make sure to filter any loose files that might hang around. */ .filter
((dir) => fs.lstatSync(dir).isDirectory());
const registry: PackagesRegistry = ( await Promise.all( allPackages.map(async (rootRelativeDir) => { const manifestPath = path.join(rootRelativeDir, "package.json"); if (!fs.existsSync(manifestPath)) { log.warn( `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file` ); return; } else { log.debug(`Registering package ./${rootRelativeDir}`); const manifest = await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") ); return { manifest, rootRelativeDir, absoluteDir: path.join(workspaceRootDir, rootRelativeDir), }; } }) ) ).reduce<PackagesRegistry>((acc, info) => { if (info) { acc[info.manifest.name] = info; } return acc; }, {}); process.chdir(cwd); return registry; }
src/helpers/create-packages-registry.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/index.ts", "retrieved_chunk": " */\n const targetPackageDir = config.targetPackagePath\n ? path.join(process.cwd(), config.targetPackagePath)\n : process.cwd();\n /**\n * We want a trailing slash here. Functionally it doesn't matter, but it makes\n * the relative paths more correct in the debug output.\n */\n const workspaceRootDir = config.targetPackagePath\n ? process.cwd()", "score": 22.569774361623427 }, { "filename": "src/utils/pack.ts", "retrieved_chunk": " const execOptions = {\n maxBuffer: 10 * 1024 * 1024,\n };\n const log = createLogger(getConfig().logLevel);\n const previousCwd = process.cwd();\n process.chdir(srcDir);\n /**\n * PNPM pack seems to be a lot faster than NPM pack, so when PNPM is detected\n * we use that instead.\n */", "score": 20.38781852077576 }, { "filename": "src/helpers/config.ts", "retrieved_chunk": " const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME);\n log.debug(`Attempting to load config from ${configFilePath}`);\n const configFromFile = fs.existsSync(configFilePath)\n ? readTypedJsonSync<IsolateConfig>(configFilePath)\n : {};\n const foreignKeys = Object.keys(configFromFile).filter(\n (key) => !validConfigKeys.includes(key)\n );\n if (!isEmpty(foreignKeys)) {\n log.warn(`Found invalid config settings:`, foreignKeys.join(\", \"));", "score": 17.67349986438474 }, { "filename": "src/helpers/list-local-dependencies.ts", "retrieved_chunk": " ]\n : Object.keys(manifest.dependencies ?? {})\n ).filter((name) => allWorkspacePackageNames.includes(name));\n const nestedLocalDependencies = localDependencyPackageNames.flatMap(\n (packageName) =>\n listLocalDependencies(\n packagesRegistry[packageName].manifest,\n packagesRegistry,\n { includeDevDependencies }\n )", "score": 13.038620926329383 }, { "filename": "src/helpers/unpack-dependencies.ts", "retrieved_chunk": " isolateDir: string\n) {\n const log = createLogger(getConfig().logLevel);\n await Promise.all(\n Object.entries(packedFilesByName).map(async ([packageName, filePath]) => {\n const dir = packagesRegistry[packageName].rootRelativeDir;\n const unpackDir = join(tmpDir, dir);\n log.debug(\"Unpacking\", `(temp)/${path.basename(filePath)}`);\n await unpack(filePath, unpackDir);\n const destinationDir = join(isolateDir, dir);", "score": 12.62273353533864 } ]
typescript
((dir) => fs.lstatSync(dir).isDirectory());
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log = createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" ); const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath) ? readTypedJsonSync<IsolateConfig>(configFilePath) : {}; const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved;
log.debug("Using configuration:", inspectValue(config));
__config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/get-build-output-dir.ts", "retrieved_chunk": " return path.join(targetPackageDir, config.buildDirName);\n }\n const tsconfigPath = path.join(targetPackageDir, config.tsconfigPath);\n if (fs.existsSync(tsconfigPath)) {\n log.debug(\"Found tsconfig at:\", config.tsconfigPath);\n const tsconfig = await readTypedJson<{\n compilerOptions?: { outDir?: string };\n }>(tsconfigPath);\n const outDir = tsconfig.compilerOptions?.outDir;\n if (outDir) {", "score": 16.804760539260037 }, { "filename": "src/helpers/get-build-output-dir.ts", "retrieved_chunk": "import fs from \"fs-extra\";\nimport path from \"node:path\";\nimport outdent from \"outdent\";\nimport { getConfig } from \"~/helpers\";\nimport { createLogger, readTypedJson } from \"~/utils\";\nexport async function getBuildOutputDir(targetPackageDir: string) {\n const config = getConfig();\n const log = createLogger(getConfig().logLevel);\n if (config.buildDirName) {\n log.debug(\"Using buildDirName from config:\", config.buildDirName);", "score": 14.331540250693479 }, { "filename": "src/index.ts", "retrieved_chunk": " await adaptTargetPackageManifest(\n targetPackageManifest,\n packagesRegistry,\n isolateDir\n );\n if (config.excludeLockfile) {\n log.warn(\"Excluding the lockfile from the isolate output\");\n } else {\n /**\n * Copy and adapt the lockfile", "score": 11.265682039588036 }, { "filename": "src/index.ts", "retrieved_chunk": " );\n const isolateDir = path.join(targetPackageDir, config.isolateDirName);\n log.debug(\n \"Isolate output directory\",\n getRootRelativePath(isolateDir, workspaceRootDir)\n );\n if (fs.existsSync(isolateDir)) {\n await fs.remove(isolateDir);\n log.debug(\"Cleaned the existing isolate output directory\");\n }", "score": 10.933340191871144 }, { "filename": "src/index.ts", "retrieved_chunk": " * isolate because the settings there could affect how the lockfile is\n * resolved. Note that .npmrc is used by both NPM and PNPM for configuration.\n *\n * See also: https://pnpm.io/npmrc\n */\n const npmrcPath = path.join(workspaceRootDir, \".npmrc\");\n if (fs.existsSync(npmrcPath)) {\n fs.copyFileSync(npmrcPath, path.join(isolateDir, \".npmrc\"));\n log.debug(\"Copied .npmrc file to the isolate output\");\n }", "score": 10.24895876601925 } ]
typescript
log.debug("Using configuration:", inspectValue(config));
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log = createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" ); const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath) ?
readTypedJsonSync<IsolateConfig>(configFilePath) : {};
const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved; log.debug("Using configuration:", inspectValue(config)); __config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/create-packages-registry.ts", "retrieved_chunk": "): Promise<PackagesRegistry> {\n const log = createLogger(getConfig().logLevel);\n if (workspacePackagesOverride) {\n log.debug(\n `Override workspace packages via config: ${workspacePackagesOverride}`\n );\n }\n const packagesGlobs =\n workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir);\n const cwd = process.cwd();", "score": 18.972124946192988 }, { "filename": "src/index.ts", "retrieved_chunk": " */\n const targetPackageDir = config.targetPackagePath\n ? path.join(process.cwd(), config.targetPackagePath)\n : process.cwd();\n /**\n * We want a trailing slash here. Functionally it doesn't matter, but it makes\n * the relative paths more correct in the debug output.\n */\n const workspaceRootDir = config.targetPackagePath\n ? process.cwd()", "score": 18.66295206652629 }, { "filename": "src/utils/pack.ts", "retrieved_chunk": " const execOptions = {\n maxBuffer: 10 * 1024 * 1024,\n };\n const log = createLogger(getConfig().logLevel);\n const previousCwd = process.cwd();\n process.chdir(srcDir);\n /**\n * PNPM pack seems to be a lot faster than NPM pack, so when PNPM is detected\n * we use that instead.\n */", "score": 14.987607050403218 }, { "filename": "src/helpers/detect-package-manager.ts", "retrieved_chunk": "import fs from \"fs-extra\";\nimport assert from \"node:assert\";\nimport { execSync } from \"node:child_process\";\nimport path from \"node:path\";\nimport { createLogger, readTypedJsonSync } from \"~/utils\";\nimport { getConfig } from \"./config\";\nimport { PackageManifest } from \"./create-packages-registry\";\nimport { getLockfileFileName } from \"./process-lockfile\";\nconst supportedPackageManagerNames = [\"pnpm\", \"yarn\", \"npm\"] as const;\nexport type PackageManagerName = (typeof supportedPackageManagerNames)[number];", "score": 14.448782665835294 }, { "filename": "src/helpers/detect-package-manager.ts", "retrieved_chunk": "function inferFromManifest(workspaceRoot: string) {\n const log = createLogger(getConfig().logLevel);\n const rootManifest = readTypedJsonSync<PackageManifest>(\n path.join(workspaceRoot, \"package.json\")\n );\n if (!rootManifest.packageManager) {\n log.debug(\"No packageManager field found in root manifest\");\n return;\n }\n const [name, version = \"*\"] = rootManifest.packageManager.split(\"@\") as [", "score": 12.778706024004093 } ]
typescript
readTypedJsonSync<IsolateConfig>(configFilePath) : {};