@superinterface/server 1.1.6 → 1.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/build-manifest.json +2 -2
- package/.next/cache/.tsbuildinfo +1 -1
- package/.next/cache/eslint/.cache_btwyo7 +1 -1
- package/.next/fallback-build-manifest.json +2 -2
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/api/workspaces/[workspaceId]/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +1 -1
- package/.next/server/chunks/[root-of-the-server]__0a426407._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0a426407._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__0c1bc5ed._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__0c1bc5ed._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__1a7a04d0._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__1a7a04d0._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__2945c9e9._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__2945c9e9._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__315f084a._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__315f084a._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__42ed6203._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__42ed6203._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__4c8c04a2._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__4c8c04a2._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__4e536bc0._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__4e536bc0._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__583a7f1c._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__583a7f1c._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__5abf1160._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__5abf1160._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__5aedcd8a._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__5aedcd8a._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__62d958e7._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__62d958e7._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__630959e5._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__630959e5._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__83461316._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__83461316._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__9a611d42._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__9a611d42._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__a9fab3b2._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__a9fab3b2._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__b10ec83e._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__b10ec83e._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__c1629392._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__c1629392._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__e73543af._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__e73543af._.js.map +1 -1
- package/.next/server/chunks/[root-of-the-server]__e8127a36._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__e8127a36._.js.map +1 -1
- package/.next/server/chunks/c4f00_next_dist_esm_build_templates_app-route_f952d9ab.js +1 -1
- package/.next/server/chunks/c4f00_next_dist_esm_build_templates_app-route_f952d9ab.js.map +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/trace +1 -1
- package/dist/app/api/messages/buildRoute.d.ts.map +1 -1
- package/dist/app/api/messages/buildRoute.js +1 -3
- package/dist/lib/cache/cacheHeaders.d.ts.map +1 -1
- package/dist/lib/cache/cacheHeaders.js +1 -1
- package/package.json +1 -1
- /package/.next/static/{8ere9Febbau5NxxQazJbz → 25Kcgl6uIxdBmkSgq8yP-}/_buildManifest.js +0 -0
- /package/.next/static/{8ere9Febbau5NxxQazJbz → 25Kcgl6uIxdBmkSgq8yP-}/_clientMiddlewareManifest.json +0 -0
- /package/.next/static/{8ere9Febbau5NxxQazJbz → 25Kcgl6uIxdBmkSgq8yP-}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/cache/cacheHeaders.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/getApiKey.ts","turbopack:///[project]/supercorp/superinterface/node_modules/radash/src/typed.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/organizationApiKeys/getOrganizationApiKey.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/formatApiKeyName.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/serializeApiKey.ts","turbopack:///[project]/supercorp/superinterface/node_modules/next/dist/esm/build/templates/app-route.js","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/api-keys/route.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/api-keys/buildRoute.ts"],"sourcesContent":["export const cacheHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n}\n","import { ApiKeyType, ApiKey, type PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getApiKey = async ({\n authorization,\n type,\n prisma,\n}: {\n authorization: string | null\n type: ApiKeyType\n prisma: PrismaClient\n}): Promise<ApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, apiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(apiKeyValue)) {\n return null\n }\n\n return prisma.apiKey.findFirst({\n where: { type, value: apiKeyValue },\n })\n}\n","export const isSymbol = (value: any): value is symbol => {\n return !!value && value.constructor === Symbol\n}\n\nexport const isArray = Array.isArray\n\nexport const isObject = (value: any): value is object => {\n return !!value && value.constructor === Object\n}\n\n/**\n * Checks if the given value is primitive.\n *\n * Primitive Types: number , string , boolean , symbol, bigint, undefined, null\n *\n * @param {*} value value to check\n * @returns {boolean} result\n */\nexport const isPrimitive = (value: any): boolean => {\n return (\n value === undefined ||\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function')\n )\n}\n\nexport const isFunction = (value: any): value is Function => {\n return !!(value && value.constructor && value.call && value.apply)\n}\n\nexport const isString = (value: any): value is string => {\n return typeof value === 'string' || value instanceof String\n}\n\nexport const isInt = (value: any): value is number => {\n return isNumber(value) && value % 1 === 0\n}\n\nexport const isFloat = (value: any): value is number => {\n return isNumber(value) && value % 1 !== 0\n}\n\nexport const isNumber = (value: any): value is number => {\n try {\n return Number(value) === value\n } catch {\n return false\n }\n}\n\nexport const isDate = (value: any): value is Date => {\n return Object.prototype.toString.call(value) === '[object Date]'\n}\n\n/**\n * This is really a _best guess_ promise checking. You\n * should probably use Promise.resolve(value) to be 100%\n * sure you're handling it correctly.\n */\nexport const isPromise = (value: any): value is Promise<any> => {\n if (!value) return false\n if (!value.then) return false\n if (!isFunction(value.then)) return false\n return true\n}\n\nexport const isEmpty = (value: any) => {\n if (value === true || value === false) return true\n if (value === null || value === undefined) return true\n if (isNumber(value)) return value === 0\n if (isDate(value)) return isNaN(value.getTime())\n if (isFunction(value)) return false\n if (isSymbol(value)) return false\n const length = (value as any).length\n if (isNumber(length)) return length === 0\n const size = (value as any).size\n if (isNumber(size)) return size === 0\n const keys = Object.keys(value).length\n return keys === 0\n}\n\nexport const isEqual = <TType>(x: TType, y: TType): boolean => {\n if (Object.is(x, y)) return true\n if (x instanceof Date && y instanceof Date) {\n return x.getTime() === y.getTime()\n }\n if (x instanceof RegExp && y instanceof RegExp) {\n return x.toString() === y.toString()\n }\n if (\n typeof x !== 'object' ||\n x === null ||\n typeof y !== 'object' ||\n y === null\n ) {\n return false\n }\n const keysX = Reflect.ownKeys(x as unknown as object) as (keyof typeof x)[]\n const keysY = Reflect.ownKeys(y as unknown as object)\n if (keysX.length !== keysY.length) return false\n for (let i = 0; i < keysX.length; i++) {\n if (!Reflect.has(y as unknown as object, keysX[i])) return false\n if (!isEqual(x[keysX[i]], y[keysX[i]])) return false\n }\n return true\n}\n","import type { OrganizationApiKey, PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getOrganizationApiKey = async ({\n authorization,\n prisma,\n}: {\n authorization: string | null\n prisma: PrismaClient\n}): Promise<OrganizationApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, organizationApiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(organizationApiKeyValue)) {\n return null\n }\n\n return prisma.organizationApiKey.findFirst({\n where: { value: organizationApiKeyValue },\n })\n}\n","import { isEmpty } from 'radash'\n\nexport const formatApiKeyName = ({\n name,\n}: {\n name: string | undefined | null\n}) => {\n if (isEmpty(name)) {\n return 'Untitled API key'\n }\n\n return name ?? 'Untitled API key'\n}\n","import type { ApiKey } from '@prisma/client'\nimport { formatApiKeyName } from '@/lib/apiKeys/formatApiKeyName'\n\nexport const serializeApiKey = ({ apiKey }: { apiKey: ApiKey }) => ({\n id: apiKey.id,\n type: apiKey.type,\n name: formatApiKeyName({ name: apiKey.name }),\n value: apiKey.value,\n createdAt: apiKey.createdAt.toISOString(),\n updatedAt: apiKey.updatedAt.toISOString(),\n})\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { getRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/api-keys/route\",\n pathname: \"/api/api-keys\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/supercorp/superinterface/packages/server/src/app/api/api-keys/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n var _nextConfig_experimental;\n let srcPage = \"/api/api-keys/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isRevalidate = isIsr && !supportsDynamicResponse;\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const context = {\n params,\n prerenderManifest,\n renderOpts: {\n experimental: {\n cacheComponents: Boolean(nextConfig.experimental.cacheComponents),\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n supportsDynamicResponse,\n incrementalCache: getRequestMeta(req, 'incrementalCache'),\n cacheLifeProfiles: (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.cacheLife,\n isRevalidate,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n } else {\n span.updateName(`${method} ${req.url}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!getRequestMeta(req, 'minimalMode') && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n }, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!getRequestMeta(req, 'minimalMode')) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (activeSpan) {\n await handleResponse(activeSpan);\n } else {\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${req.url}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse));\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n });\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import { prisma } from '@/lib/prisma'\nimport { buildGET, buildPOST, buildOPTIONS } from './buildRoute'\n\nexport const GET = buildGET({\n prisma,\n})\n\nexport const POST = buildPOST({\n prisma,\n})\n\nexport const OPTIONS = buildOPTIONS()\n","import { headers } from 'next/headers'\nimport { ApiKeyType, type PrismaClient } from '@prisma/client'\nimport { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { cacheHeaders } from '@/lib/cache/cacheHeaders'\nimport { serializeApiKey } from '@/lib/apiKeys/serializeApiKey'\nimport { getApiKey } from '@/lib/apiKeys/getApiKey'\nimport { getOrganizationApiKey } from '@/lib/organizationApiKeys/getOrganizationApiKey'\n\nexport const buildGET =\n ({ prisma }: { prisma: PrismaClient }) =>\n async () => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const privateApiKey = await getApiKey({\n type: ApiKeyType.PRIVATE,\n authorization,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const apiKeys = await prisma.apiKey.findMany({\n where: {\n type: ApiKeyType.PUBLIC,\n workspaceId: privateApiKey.workspaceId,\n },\n })\n\n return NextResponse.json(\n {\n apiKeys: apiKeys.map((apiKey) => serializeApiKey({ apiKey })),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildPOST =\n ({ prisma }: { prisma: PrismaClient }) =>\n async (request: Request) => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const body = await request.json().catch(() => null)\n\n const organizationApiKey = await getOrganizationApiKey({\n authorization,\n prisma,\n })\n\n if (organizationApiKey) {\n const createSchemaOrganizationApiKey = z.object({\n name: z.string().min(1).optional(),\n type: z.nativeEnum(ApiKeyType),\n workspaceId: z.string().min(1).optional(),\n })\n\n const parsedOrganizationApiKey =\n createSchemaOrganizationApiKey.safeParse(body)\n\n if (!parsedOrganizationApiKey.success) {\n return NextResponse.json({ error: 'Invalid body' }, { status: 400 })\n }\n\n const workspace = await prisma.workspace.findUnique({\n where: {\n id: parsedOrganizationApiKey.data.workspaceId,\n organizationId: organizationApiKey.organizationId,\n },\n })\n\n if (!workspace) {\n return NextResponse.json(\n { error: 'Invalid workspace' },\n { status: 400 },\n )\n }\n\n const apiKey = await prisma.apiKey.create({\n data: {\n type: parsedOrganizationApiKey.data.type,\n name: parsedOrganizationApiKey.data.name,\n workspaceId: workspace.id,\n },\n })\n\n return NextResponse.json(\n {\n apiKey: serializeApiKey({ apiKey }),\n },\n { headers: cacheHeaders },\n )\n }\n\n const privateApiKey = await getApiKey({\n type: ApiKeyType.PRIVATE,\n authorization,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const createSchema = z.object({\n name: z.string().min(1).optional(),\n })\n\n const parsed = createSchema.safeParse(body)\n\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid body' }, { status: 400 })\n }\n\n const { name } = parsed.data\n\n const workspaceId = privateApiKey.workspaceId\n\n const apiKey = await prisma.apiKey.create({\n data: {\n type: ApiKeyType.PUBLIC,\n name,\n workspaceId,\n },\n })\n\n return NextResponse.json(\n {\n apiKey: serializeApiKey({ apiKey }),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildOPTIONS = () => () =>\n NextResponse.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List":[6]}
|
|
1
|
+
{"version":3,"sources":["turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/cache/cacheHeaders.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/getApiKey.ts","turbopack:///[project]/supercorp/superinterface/node_modules/radash/src/typed.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/organizationApiKeys/getOrganizationApiKey.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/formatApiKeyName.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/apiKeys/serializeApiKey.ts","turbopack:///[project]/supercorp/superinterface/node_modules/next/dist/esm/build/templates/app-route.js","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/api-keys/route.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/api-keys/buildRoute.ts"],"sourcesContent":["export const cacheHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Content-Type, Authorization, X-Requested-With, Accept',\n}\n","import { ApiKeyType, ApiKey, type PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getApiKey = async ({\n authorization,\n type,\n prisma,\n}: {\n authorization: string | null\n type: ApiKeyType\n prisma: PrismaClient\n}): Promise<ApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, apiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(apiKeyValue)) {\n return null\n }\n\n return prisma.apiKey.findFirst({\n where: { type, value: apiKeyValue },\n })\n}\n","export const isSymbol = (value: any): value is symbol => {\n return !!value && value.constructor === Symbol\n}\n\nexport const isArray = Array.isArray\n\nexport const isObject = (value: any): value is object => {\n return !!value && value.constructor === Object\n}\n\n/**\n * Checks if the given value is primitive.\n *\n * Primitive Types: number , string , boolean , symbol, bigint, undefined, null\n *\n * @param {*} value value to check\n * @returns {boolean} result\n */\nexport const isPrimitive = (value: any): boolean => {\n return (\n value === undefined ||\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function')\n )\n}\n\nexport const isFunction = (value: any): value is Function => {\n return !!(value && value.constructor && value.call && value.apply)\n}\n\nexport const isString = (value: any): value is string => {\n return typeof value === 'string' || value instanceof String\n}\n\nexport const isInt = (value: any): value is number => {\n return isNumber(value) && value % 1 === 0\n}\n\nexport const isFloat = (value: any): value is number => {\n return isNumber(value) && value % 1 !== 0\n}\n\nexport const isNumber = (value: any): value is number => {\n try {\n return Number(value) === value\n } catch {\n return false\n }\n}\n\nexport const isDate = (value: any): value is Date => {\n return Object.prototype.toString.call(value) === '[object Date]'\n}\n\n/**\n * This is really a _best guess_ promise checking. You\n * should probably use Promise.resolve(value) to be 100%\n * sure you're handling it correctly.\n */\nexport const isPromise = (value: any): value is Promise<any> => {\n if (!value) return false\n if (!value.then) return false\n if (!isFunction(value.then)) return false\n return true\n}\n\nexport const isEmpty = (value: any) => {\n if (value === true || value === false) return true\n if (value === null || value === undefined) return true\n if (isNumber(value)) return value === 0\n if (isDate(value)) return isNaN(value.getTime())\n if (isFunction(value)) return false\n if (isSymbol(value)) return false\n const length = (value as any).length\n if (isNumber(length)) return length === 0\n const size = (value as any).size\n if (isNumber(size)) return size === 0\n const keys = Object.keys(value).length\n return keys === 0\n}\n\nexport const isEqual = <TType>(x: TType, y: TType): boolean => {\n if (Object.is(x, y)) return true\n if (x instanceof Date && y instanceof Date) {\n return x.getTime() === y.getTime()\n }\n if (x instanceof RegExp && y instanceof RegExp) {\n return x.toString() === y.toString()\n }\n if (\n typeof x !== 'object' ||\n x === null ||\n typeof y !== 'object' ||\n y === null\n ) {\n return false\n }\n const keysX = Reflect.ownKeys(x as unknown as object) as (keyof typeof x)[]\n const keysY = Reflect.ownKeys(y as unknown as object)\n if (keysX.length !== keysY.length) return false\n for (let i = 0; i < keysX.length; i++) {\n if (!Reflect.has(y as unknown as object, keysX[i])) return false\n if (!isEqual(x[keysX[i]], y[keysX[i]])) return false\n }\n return true\n}\n","import type { OrganizationApiKey, PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getOrganizationApiKey = async ({\n authorization,\n prisma,\n}: {\n authorization: string | null\n prisma: PrismaClient\n}): Promise<OrganizationApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, organizationApiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(organizationApiKeyValue)) {\n return null\n }\n\n return prisma.organizationApiKey.findFirst({\n where: { value: organizationApiKeyValue },\n })\n}\n","import { isEmpty } from 'radash'\n\nexport const formatApiKeyName = ({\n name,\n}: {\n name: string | undefined | null\n}) => {\n if (isEmpty(name)) {\n return 'Untitled API key'\n }\n\n return name ?? 'Untitled API key'\n}\n","import type { ApiKey } from '@prisma/client'\nimport { formatApiKeyName } from '@/lib/apiKeys/formatApiKeyName'\n\nexport const serializeApiKey = ({ apiKey }: { apiKey: ApiKey }) => ({\n id: apiKey.id,\n type: apiKey.type,\n name: formatApiKeyName({ name: apiKey.name }),\n value: apiKey.value,\n createdAt: apiKey.createdAt.toISOString(),\n updatedAt: apiKey.updatedAt.toISOString(),\n})\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { getRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/api-keys/route\",\n pathname: \"/api/api-keys\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/supercorp/superinterface/packages/server/src/app/api/api-keys/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n var _nextConfig_experimental;\n let srcPage = \"/api/api-keys/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isRevalidate = isIsr && !supportsDynamicResponse;\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const context = {\n params,\n prerenderManifest,\n renderOpts: {\n experimental: {\n cacheComponents: Boolean(nextConfig.experimental.cacheComponents),\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n supportsDynamicResponse,\n incrementalCache: getRequestMeta(req, 'incrementalCache'),\n cacheLifeProfiles: (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.cacheLife,\n isRevalidate,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n } else {\n span.updateName(`${method} ${req.url}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!getRequestMeta(req, 'minimalMode') && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n }, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!getRequestMeta(req, 'minimalMode')) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (activeSpan) {\n await handleResponse(activeSpan);\n } else {\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${req.url}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse));\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n });\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import { prisma } from '@/lib/prisma'\nimport { buildGET, buildPOST, buildOPTIONS } from './buildRoute'\n\nexport const GET = buildGET({\n prisma,\n})\n\nexport const POST = buildPOST({\n prisma,\n})\n\nexport const OPTIONS = buildOPTIONS()\n","import { headers } from 'next/headers'\nimport { ApiKeyType, type PrismaClient } from '@prisma/client'\nimport { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { cacheHeaders } from '@/lib/cache/cacheHeaders'\nimport { serializeApiKey } from '@/lib/apiKeys/serializeApiKey'\nimport { getApiKey } from '@/lib/apiKeys/getApiKey'\nimport { getOrganizationApiKey } from '@/lib/organizationApiKeys/getOrganizationApiKey'\n\nexport const buildGET =\n ({ prisma }: { prisma: PrismaClient }) =>\n async () => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const privateApiKey = await getApiKey({\n type: ApiKeyType.PRIVATE,\n authorization,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const apiKeys = await prisma.apiKey.findMany({\n where: {\n type: ApiKeyType.PUBLIC,\n workspaceId: privateApiKey.workspaceId,\n },\n })\n\n return NextResponse.json(\n {\n apiKeys: apiKeys.map((apiKey) => serializeApiKey({ apiKey })),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildPOST =\n ({ prisma }: { prisma: PrismaClient }) =>\n async (request: Request) => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const body = await request.json().catch(() => null)\n\n const organizationApiKey = await getOrganizationApiKey({\n authorization,\n prisma,\n })\n\n if (organizationApiKey) {\n const createSchemaOrganizationApiKey = z.object({\n name: z.string().min(1).optional(),\n type: z.nativeEnum(ApiKeyType),\n workspaceId: z.string().min(1).optional(),\n })\n\n const parsedOrganizationApiKey =\n createSchemaOrganizationApiKey.safeParse(body)\n\n if (!parsedOrganizationApiKey.success) {\n return NextResponse.json({ error: 'Invalid body' }, { status: 400 })\n }\n\n const workspace = await prisma.workspace.findUnique({\n where: {\n id: parsedOrganizationApiKey.data.workspaceId,\n organizationId: organizationApiKey.organizationId,\n },\n })\n\n if (!workspace) {\n return NextResponse.json(\n { error: 'Invalid workspace' },\n { status: 400 },\n )\n }\n\n const apiKey = await prisma.apiKey.create({\n data: {\n type: parsedOrganizationApiKey.data.type,\n name: parsedOrganizationApiKey.data.name,\n workspaceId: workspace.id,\n },\n })\n\n return NextResponse.json(\n {\n apiKey: serializeApiKey({ apiKey }),\n },\n { headers: cacheHeaders },\n )\n }\n\n const privateApiKey = await getApiKey({\n type: ApiKeyType.PRIVATE,\n authorization,\n prisma,\n })\n\n if (!privateApiKey) {\n return NextResponse.json({ error: 'Invalid api key' }, { status: 400 })\n }\n\n const createSchema = z.object({\n name: z.string().min(1).optional(),\n })\n\n const parsed = createSchema.safeParse(body)\n\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid body' }, { status: 400 })\n }\n\n const { name } = parsed.data\n\n const workspaceId = privateApiKey.workspaceId\n\n const apiKey = await prisma.apiKey.create({\n data: {\n type: ApiKeyType.PUBLIC,\n name,\n workspaceId,\n },\n })\n\n return NextResponse.json(\n {\n apiKey: serializeApiKey({ apiKey }),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildOPTIONS = () => () =>\n NextResponse.json(\n {},\n {\n headers: cacheHeaders,\n },\n )\n"],"names":[],"mappings":"6jCAAO,IAAM,EAAe,CAC1B,8BAA+B,IAC/B,+BAAgC,kCAChC,+BACE,uDACJ,mDCJA,IAAA,EAAA,EAAA,CAAA,CAAA,OAEO,IAAM,EAAY,MAAO,CAC9B,eAAa,MACb,CAAI,QACJ,CAAM,CAKP,IACC,GAAI,CAAC,EACH,OAAO,KAGT,CAJoB,EAId,EAAG,EAAY,CAAG,EAAc,K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Q,GAAG,CAAC,gBAAiB,CAAA,EAAA,EAAA,qBAAA,AAAqB,EAAC,EAAW,YAAY,GAE9E,MAAM,CAAA,EAAA,EAAA,YAAY,AAAZ,EAAa,EAAa,EAAa,IAAI,SAAS,EAAW,KAAK,CAAC,IAAI,CAAE,SAC7E,EACA,OAAQ,EAAW,KAAK,CAAC,MAAM,EAAI,GACvC,IACO,IACX,EAGI,EACA,MAAM,EAAe,EADT,CAGZ,MAAM,EAAO,qBAAqB,CAAC,EAAI,OAAO,CAAE,IAAI,EAAO,KAAK,CAAC,EAAA,cAAc,CAAC,aAAa,CAAE,CACvF,SAAU,CAAA,EAAG,EAAO,CAAC,EAAE,EAAI,GAAG,CAAA,CAAE,CAChC,KAAM,EAAA,QAAQ,CAAC,MAAM,CACrB,WAAY,CACR,cAAe,EACf,cAAe,EAAI,GAAG,AAC1B,CACJ,EAAG,GAEf,CAAE,MAAO,EAAK,CAcV,GAbI,AAAE,CAAD,YAAgB,EAAA,eAAe,EAChC,CADmC,KAC7B,EAAY,cAAc,CAAC,EAAK,EAAK,CACvC,WAAY,aACZ,UAAW,EACX,UAAW,QACX,iBAAkB,CAAA,EAAA,EAAA,mBAAA,AAAmB,EAAC,cAClC,uBACA,CACJ,EACJ,GAIA,EAAO,MAAM,EAKjB,OAHA,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,KAAM,CAC5D,OAAQ,GACZ,IACO,IACX,CACJ,EAEA,qCAAqC","ignoreList":[6]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
module.exports=[18622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},24725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},20635,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/action-async-storage.external.js",()=>require("next/dist/server/app-render/action-async-storage.external.js"))},93695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},30611,e=>{"use strict";e.s(["cacheHeaders",()=>t]);let t={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type"}},52198,e=>{"use strict";e.s(["getOrganizationApiKey",()=>r]);var t=e.i(55897);let r=async({authorization:e,prisma:r})=>{if(!e)return null;let[,a]=e.split("Bearer ");return(0,t.validate)(a)?r.organizationApiKey.findFirst({where:{value:a}}):null}},81277,e=>{"use strict";e.s(["serializeApiWorkspace",()=>t]);let t=({workspace:e})=>({id:e.id,name:e.name,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()})},38870,e=>{"use strict";e.s([])},9669,e=>{"use strict";e.s(["handler",()=>z,"patchFetch",()=>I,"routeModule",()=>j,"serverHooks",()=>b,"workAsyncStorage",()=>P,"workUnitAsyncStorage",()=>S],9669);var t=e.i(5865),r=e.i(43877),a=e.i(77767),n=e.i(92562),s=e.i(66256),i=e.i(5270),o=e.i(90231),l=e.i(82677),d=e.i(51081),p=e.i(89822),u=e.i(9124),c=e.i(39147),h=e.i(40568),x=e.i(87188),
|
|
1
|
+
module.exports=[18622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},24725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},20635,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/action-async-storage.external.js",()=>require("next/dist/server/app-render/action-async-storage.external.js"))},93695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},30611,e=>{"use strict";e.s(["cacheHeaders",()=>t]);let t={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept"}},52198,e=>{"use strict";e.s(["getOrganizationApiKey",()=>r]);var t=e.i(55897);let r=async({authorization:e,prisma:r})=>{if(!e)return null;let[,a]=e.split("Bearer ");return(0,t.validate)(a)?r.organizationApiKey.findFirst({where:{value:a}}):null}},81277,e=>{"use strict";e.s(["serializeApiWorkspace",()=>t]);let t=({workspace:e})=>({id:e.id,name:e.name,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()})},38870,e=>{"use strict";e.s([])},9669,e=>{"use strict";e.s(["handler",()=>z,"patchFetch",()=>I,"routeModule",()=>j,"serverHooks",()=>b,"workAsyncStorage",()=>P,"workUnitAsyncStorage",()=>S],9669);var t=e.i(5865),r=e.i(43877),a=e.i(77767),n=e.i(92562),s=e.i(66256),i=e.i(5270),o=e.i(90231),l=e.i(82677),d=e.i(51081),p=e.i(89822),u=e.i(9124),c=e.i(39147),h=e.i(40568),x=e.i(87188),R=e.i(93695);e.i(57132);var g=e.i(80739);e.s(["GET",()=>N,"OPTIONS",()=>k,"POST",()=>O,"createWorkspaceSchema",()=>C],85212),e.s(["GET",()=>N,"OPTIONS",()=>k,"POST",()=>O],40342);var v=e.i(24493),w=e.i(11053),f=e.i(49493),m=e.i(13669),A=e.i(30611),E=e.i(81277),y=e.i(52198);let C=m.z.object({name:m.z.string().optional()}),N=(({prisma:e})=>async()=>{let t=(await (0,w.headers)()).get("authorization");if(!t)return f.NextResponse.json({error:"No authorization header found"},{status:400});let r=await (0,y.getOrganizationApiKey)({authorization:t,prisma:e});if(!r)return f.NextResponse.json({error:"Invalid organization api key"},{status:400});let a=await e.workspace.findMany({where:{organizationId:r.organizationId}});return f.NextResponse.json({workspaces:a.map(e=>(0,E.serializeApiWorkspace)({workspace:e}))},{headers:A.cacheHeaders})})({prisma:v.prisma}),O=(({prisma:e,createWorkspace:t=({parsedData:e,organization:t,prisma:r})=>r.workspace.create({data:{name:e.name??"",organizationId:t.id}})})=>async r=>{let a=(await (0,w.headers)()).get("authorization");if(!a)return f.NextResponse.json({error:"No authorization header found"},{status:400});let n=await (0,y.getOrganizationApiKey)({authorization:a,prisma:e});if(!n)return f.NextResponse.json({error:"Invalid organization api key"},{status:400});let s=await r.json(),i=C.safeParse(s);if(!i.success)return f.NextResponse.json({error:"Invalid payload"},{status:400});let o=await e.organization.findUnique({where:{id:n.organizationId}});if(!o)return f.NextResponse.json({error:"Organization not found"},{status:404});let l=await t({parsedData:i.data,organization:o,prisma:e});return f.NextResponse.json({workspace:(0,E.serializeApiWorkspace)({workspace:l})},{headers:A.cacheHeaders})})({prisma:v.prisma}),k=()=>f.NextResponse.json({},{headers:A.cacheHeaders});e.i(40342);var T=e.i(85212);let j=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/workspaces/route",pathname:"/api/workspaces",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/supercorp/superinterface/packages/server/src/app/api/workspaces/route.ts",nextConfigOutput:"",userland:T}),{workAsyncStorage:P,workUnitAsyncStorage:S,serverHooks:b}=j;function I(){return(0,a.patchFetch)({workAsyncStorage:P,workUnitAsyncStorage:S})}async function z(e,t,a){var v;let w="/api/workspaces/route";w=w.replace(/\/index$/,"")||"/";let f=await j.prepare(e,t,{srcPage:w,multiZoneDraftMode:!1});if(!f)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:m,params:A,nextConfig:E,isDraftMode:y,prerenderManifest:C,routerServerContext:N,isOnDemandRevalidate:O,revalidateOnlyGenerated:k,resolvedPathname:T}=f,P=(0,i.normalizeAppPath)(w),S=!!(C.dynamicRoutes[P]||C.routes[T]);if(S&&!y){let e=!!C.routes[T],t=C.dynamicRoutes[P];if(t&&!1===t.fallback&&!e)throw new R.NoFallbackError}let b=null;!S||j.isDev||y||(b="/index"===(b=T)?"/":b);let I=!0===j.isDev||!S,z=S&&!I,q=e.method||"GET",H=(0,s.getTracer)(),_=H.getActiveScopeSpan(),U={params:A,prerenderManifest:C,renderOpts:{experimental:{cacheComponents:!!E.experimental.cacheComponents,authInterrupts:!!E.experimental.authInterrupts},supportsDynamicResponse:I,incrementalCache:(0,n.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:null==(v=E.experimental)?void 0:v.cacheLife,isRevalidate:z,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a)=>j.onRequestError(e,t,a,N)},sharedContext:{buildId:m}},M=new o.NodeNextRequest(e),D=new o.NodeNextResponse(t),K=l.NextRequestAdapter.fromNodeNextRequest(M,(0,l.signalFromNodeResponse)(t));try{let i=async r=>j.handle(K,U).finally(()=>{if(!r)return;r.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let a=H.getRootSpanAttributes();if(!a)return;if(a.get("next.span_type")!==d.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${a.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=a.get("next.route");if(n){let e=`${q} ${n}`;r.setAttributes({"next.route":n,"http.route":n,"next.span_name":e}),r.updateName(e)}else r.updateName(`${q} ${e.url}`)}),o=async s=>{var o,l;let d=async({previousCacheEntry:r})=>{try{if(!(0,n.getRequestMeta)(e,"minimalMode")&&O&&k&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await i(s);e.fetchMetrics=U.renderOpts.fetchMetrics;let l=U.renderOpts.pendingWaitUntil;l&&a.waitUntil&&(a.waitUntil(l),l=void 0);let d=U.renderOpts.collectedTags;if(!S)return await (0,u.sendResponse)(M,D,o,U.renderOpts.pendingWaitUntil),null;{let e=await o.blob(),t=(0,c.toNodeOutgoingHttpHeaders)(o.headers);d&&(t[x.NEXT_CACHE_TAGS_HEADER]=d),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==U.renderOpts.collectedRevalidate&&!(U.renderOpts.collectedRevalidate>=x.INFINITE_CACHE)&&U.renderOpts.collectedRevalidate,a=void 0===U.renderOpts.collectedExpire||U.renderOpts.collectedExpire>=x.INFINITE_CACHE?void 0:U.renderOpts.collectedExpire;return{value:{kind:g.CachedRouteKind.APP_ROUTE,status:o.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await j.onRequestError(e,t,{routerKind:"App Router",routePath:w,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isRevalidate:z,isOnDemandRevalidate:O})},N),t}},R=await j.handleResponse({req:e,nextConfig:E,cacheKey:b,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:C,isRoutePPREnabled:!1,isOnDemandRevalidate:O,revalidateOnlyGenerated:k,responseGenerator:d,waitUntil:a.waitUntil});if(!S)return null;if((null==R||null==(o=R.value)?void 0:o.kind)!==g.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==R||null==(l=R.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,n.getRequestMeta)(e,"minimalMode")||t.setHeader("x-nextjs-cache",O?"REVALIDATED":R.isMiss?"MISS":R.isStale?"STALE":"HIT"),y&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let v=(0,c.fromNodeOutgoingHttpHeaders)(R.value.headers);return(0,n.getRequestMeta)(e,"minimalMode")&&S||v.delete(x.NEXT_CACHE_TAGS_HEADER),!R.cacheControl||t.getHeader("Cache-Control")||v.get("Cache-Control")||v.set("Cache-Control",(0,h.getCacheControlHeader)(R.cacheControl)),await (0,u.sendResponse)(M,D,new Response(R.value.body,{headers:v,status:R.value.status||200})),null};_?await o(_):await H.withPropagatedContext(e.headers,()=>H.trace(d.BaseServerSpan.handleRequest,{spanName:`${q} ${e.url}`,kind:s.SpanKind.SERVER,attributes:{"http.method":q,"http.target":e.url}},o))}catch(t){if(t instanceof R.NoFallbackError||await j.onRequestError(e,t,{routerKind:"App Router",routePath:P,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isRevalidate:z,isOnDemandRevalidate:O})}),S)throw t;return await (0,u.sendResponse)(M,D,new Response(null,{status:500})),null}}}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=%5Broot-of-the-server%5D__c1629392._.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/cache/cacheHeaders.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/organizationApiKeys/getOrganizationApiKey.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/workspaces/serializeApiWorkspace.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/workspaces/route.ts","turbopack:///[project]/supercorp/superinterface/node_modules/next/dist/esm/build/templates/app-route.js","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/workspaces/buildRoute.ts"],"sourcesContent":["export const cacheHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n}\n","import type { OrganizationApiKey, PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getOrganizationApiKey = async ({\n authorization,\n prisma,\n}: {\n authorization: string | null\n prisma: PrismaClient\n}): Promise<OrganizationApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, organizationApiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(organizationApiKeyValue)) {\n return null\n }\n\n return prisma.organizationApiKey.findFirst({\n where: { value: organizationApiKeyValue },\n })\n}\n","import type { Workspace } from '@prisma/client'\n\nexport const serializeApiWorkspace = ({\n workspace,\n}: {\n workspace: Workspace\n}) => ({\n id: workspace.id,\n name: workspace.name,\n createdAt: workspace.createdAt.toISOString(),\n updatedAt: workspace.updatedAt.toISOString(),\n})\n","import { prisma } from '@/lib/prisma'\nimport {\n buildGET,\n buildOPTIONS,\n buildPOST,\n createWorkspaceSchema,\n} from './buildRoute'\n\nexport { createWorkspaceSchema }\n\nexport const GET = buildGET({ prisma })\n\nexport const POST = buildPOST({ prisma })\n\nexport const OPTIONS = buildOPTIONS()\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { getRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/workspaces/route\",\n pathname: \"/api/workspaces\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/supercorp/superinterface/packages/server/src/app/api/workspaces/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n var _nextConfig_experimental;\n let srcPage = \"/api/workspaces/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isRevalidate = isIsr && !supportsDynamicResponse;\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const context = {\n params,\n prerenderManifest,\n renderOpts: {\n experimental: {\n cacheComponents: Boolean(nextConfig.experimental.cacheComponents),\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n supportsDynamicResponse,\n incrementalCache: getRequestMeta(req, 'incrementalCache'),\n cacheLifeProfiles: (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.cacheLife,\n isRevalidate,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n } else {\n span.updateName(`${method} ${req.url}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!getRequestMeta(req, 'minimalMode') && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n }, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!getRequestMeta(req, 'minimalMode')) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (activeSpan) {\n await handleResponse(activeSpan);\n } else {\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${req.url}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse));\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n });\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import type { Organization, Workspace, PrismaClient } from '@prisma/client'\nimport { headers } from 'next/headers'\nimport { NextResponse, type NextRequest } from 'next/server'\nimport { z } from 'zod'\nimport { cacheHeaders } from '@/lib/cache/cacheHeaders'\nimport { serializeApiWorkspace } from '@/lib/workspaces/serializeApiWorkspace'\nimport { getOrganizationApiKey } from '@/lib/organizationApiKeys/getOrganizationApiKey'\n\nconst createWorkspaceSchema = z.object({\n name: z.string().optional(),\n})\n\nexport const buildGET =\n ({ prisma }: { prisma: PrismaClient }) =>\n async () => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const organizationApiKey = await getOrganizationApiKey({\n authorization,\n prisma,\n })\n\n if (!organizationApiKey) {\n return NextResponse.json(\n { error: 'Invalid organization api key' },\n { status: 400 },\n )\n }\n\n const workspaces = await prisma.workspace.findMany({\n where: {\n organizationId: organizationApiKey.organizationId,\n },\n })\n\n return NextResponse.json(\n {\n workspaces: workspaces.map((workspace) =>\n serializeApiWorkspace({ workspace }),\n ),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildPOST =\n ({\n prisma,\n createWorkspace = ({\n parsedData,\n organization,\n prisma,\n }: {\n parsedData: z.infer<typeof createWorkspaceSchema>\n organization: Organization\n prisma: PrismaClient\n }) =>\n prisma.workspace.create({\n data: {\n name: parsedData.name ?? '',\n organizationId: organization.id,\n },\n }),\n }: {\n prisma: PrismaClient\n createWorkspace?: ({\n parsedData,\n organization,\n prisma,\n }: {\n parsedData: z.infer<typeof createWorkspaceSchema>\n organization: Organization\n prisma: PrismaClient\n }) => Promise<Workspace>\n }) =>\n async (request: NextRequest) => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const organizationApiKey = await getOrganizationApiKey({\n authorization,\n prisma,\n })\n\n if (!organizationApiKey) {\n return NextResponse.json(\n { error: 'Invalid organization api key' },\n { status: 400 },\n )\n }\n\n const body = await request.json()\n const parsed = createWorkspaceSchema.safeParse(body)\n\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n\n const organization = await prisma.organization.findUnique({\n where: {\n id: organizationApiKey.organizationId,\n },\n })\n\n if (!organization) {\n return NextResponse.json(\n { error: 'Organization not found' },\n { status: 404 },\n )\n }\n\n const workspace = await createWorkspace({\n parsedData: parsed.data,\n organization,\n prisma,\n })\n\n return NextResponse.json(\n {\n workspace: serializeApiWorkspace({ workspace }),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildOPTIONS = () => () =>\n NextResponse.json(\n {},\n {\n headers: cacheHeaders,\n },\n )\n\nexport { createWorkspaceSchema }\n"],"names":[],"mappings":"6jCAAO,IAAM,EAAe,CAC1B,8BAA+B,IAC/B,+BAAgC,kCAChC,+BAAgC,cAClC,+DCHA,IAAA,EAAA,EAAA,CAAA,CAAA,OAEO,IAAM,EAAwB,MAAO,eAC1C,CAAa,QACb,CAAM,CAIP,IACC,GAAI,CAAC,EACH,OAAO,KAGT,CAJoB,EAId,EAAG,EAAwB,CAAG,EAAc,KAAK,CAAC,iBAExD,AAAK,CAAA,EAAA,CAAD,CAAC,QAAA,AAAQ,EAAC,GAIP,EAAO,kBAAkB,CAAC,EAJO,OAIE,CAAC,CACzC,MAAO,CAAE,MAAO,CAAwB,CAC1C,GALS,IAMX,+DCrBO,IAAM,EAAwB,CAAC,WACpC,CAAS,CAGV,GAAK,CAAC,CACL,GAAI,EAAU,EAAE,CAChB,KAAM,EAAU,IAAI,CACpB,UAAW,EAAU,SAAS,CAAC,WAAW,GAC1C,UAAW,EAAU,SAAS,CAAC,WAAW,GAC5C,CAAC,qMEXD,IAAA,EAAA,EAAA,CAAA,CAAA,MACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAA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AAiB,CAAA,EAAA,EAAA,qBAAA,AAAqB,EAAC,EAAW,YAAY,GAE9E,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,EAAW,KAAK,CAAC,IAAI,CAAE,SAC7E,EACA,OAAQ,EAAW,KAAK,CAAC,MAAM,EAAI,GACvC,IACO,IACX,EAGI,EACA,MAAM,EAAe,EADT,CAGZ,MAAM,EAAO,qBAAqB,CAAC,EAAI,OAAO,CAAE,IAAI,EAAO,KAAK,CAAC,EAAA,cAAc,CAAC,aAAa,CAAE,CACvF,SAAU,CAAA,EAAG,EAAO,CAAC,EAAE,EAAI,GAAG,CAAA,CAAE,CAChC,KAAM,EAAA,QAAQ,CAAC,MAAM,CACrB,WAAY,CACR,cAAe,EACf,cAAe,EAAI,GAAG,AAC1B,CACJ,EAAG,GAEf,CAAE,MAAO,EAAK,CAcV,GAbI,AAAE,CAAD,YAAgB,EAAA,eAAe,EAChC,CADmC,KAC7B,EAAY,cAAc,CAAC,EAAK,EAAK,CACvC,WAAY,aACZ,UAAW,EACX,UAAW,QACX,iBAAkB,CAAA,EAAA,EAAA,mBAAA,AAAmB,EAAC,cAClC,uBACA,CACJ,EACJ,GAIA,EAAO,MAAM,EAKjB,OAHA,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,KAAM,CAC5D,OAAQ,GACZ,IACO,IACX,CACJ,EAEA,qCAAqC","ignoreList":[4]}
|
|
1
|
+
{"version":3,"sources":["turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/cache/cacheHeaders.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/organizationApiKeys/getOrganizationApiKey.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/lib/workspaces/serializeApiWorkspace.ts","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/workspaces/route.ts","turbopack:///[project]/supercorp/superinterface/node_modules/next/dist/esm/build/templates/app-route.js","turbopack:///[project]/supercorp/superinterface/packages/server/src/app/api/workspaces/buildRoute.ts"],"sourcesContent":["export const cacheHeaders = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Content-Type, Authorization, X-Requested-With, Accept',\n}\n","import type { OrganizationApiKey, PrismaClient } from '@prisma/client'\nimport { validate } from 'uuid'\n\nexport const getOrganizationApiKey = async ({\n authorization,\n prisma,\n}: {\n authorization: string | null\n prisma: PrismaClient\n}): Promise<OrganizationApiKey | null> => {\n if (!authorization) {\n return null\n }\n\n const [, organizationApiKeyValue] = authorization.split('Bearer ')\n\n if (!validate(organizationApiKeyValue)) {\n return null\n }\n\n return prisma.organizationApiKey.findFirst({\n where: { value: organizationApiKeyValue },\n })\n}\n","import type { Workspace } from '@prisma/client'\n\nexport const serializeApiWorkspace = ({\n workspace,\n}: {\n workspace: Workspace\n}) => ({\n id: workspace.id,\n name: workspace.name,\n createdAt: workspace.createdAt.toISOString(),\n updatedAt: workspace.updatedAt.toISOString(),\n})\n","import { prisma } from '@/lib/prisma'\nimport {\n buildGET,\n buildOPTIONS,\n buildPOST,\n createWorkspaceSchema,\n} from './buildRoute'\n\nexport { createWorkspaceSchema }\n\nexport const GET = buildGET({ prisma })\n\nexport const POST = buildPOST({ prisma })\n\nexport const OPTIONS = buildOPTIONS()\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { getRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/workspaces/route\",\n pathname: \"/api/workspaces\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/supercorp/superinterface/packages/server/src/app/api/workspaces/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n var _nextConfig_experimental;\n let srcPage = \"/api/workspaces/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isRevalidate = isIsr && !supportsDynamicResponse;\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const context = {\n params,\n prerenderManifest,\n renderOpts: {\n experimental: {\n cacheComponents: Boolean(nextConfig.experimental.cacheComponents),\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n supportsDynamicResponse,\n incrementalCache: getRequestMeta(req, 'incrementalCache'),\n cacheLifeProfiles: (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.cacheLife,\n isRevalidate,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext)=>routeModule.onRequestError(req, error, errorContext, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n } else {\n span.updateName(`${method} ${req.url}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!getRequestMeta(req, 'minimalMode') && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n }, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!getRequestMeta(req, 'minimalMode')) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(getRequestMeta(req, 'minimalMode') && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (activeSpan) {\n await handleResponse(activeSpan);\n } else {\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${req.url}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse));\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isRevalidate,\n isOnDemandRevalidate\n })\n });\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import type { Organization, Workspace, PrismaClient } from '@prisma/client'\nimport { headers } from 'next/headers'\nimport { NextResponse, type NextRequest } from 'next/server'\nimport { z } from 'zod'\nimport { cacheHeaders } from '@/lib/cache/cacheHeaders'\nimport { serializeApiWorkspace } from '@/lib/workspaces/serializeApiWorkspace'\nimport { getOrganizationApiKey } from '@/lib/organizationApiKeys/getOrganizationApiKey'\n\nconst createWorkspaceSchema = z.object({\n name: z.string().optional(),\n})\n\nexport const buildGET =\n ({ prisma }: { prisma: PrismaClient }) =>\n async () => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const organizationApiKey = await getOrganizationApiKey({\n authorization,\n prisma,\n })\n\n if (!organizationApiKey) {\n return NextResponse.json(\n { error: 'Invalid organization api key' },\n { status: 400 },\n )\n }\n\n const workspaces = await prisma.workspace.findMany({\n where: {\n organizationId: organizationApiKey.organizationId,\n },\n })\n\n return NextResponse.json(\n {\n workspaces: workspaces.map((workspace) =>\n serializeApiWorkspace({ workspace }),\n ),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildPOST =\n ({\n prisma,\n createWorkspace = ({\n parsedData,\n organization,\n prisma,\n }: {\n parsedData: z.infer<typeof createWorkspaceSchema>\n organization: Organization\n prisma: PrismaClient\n }) =>\n prisma.workspace.create({\n data: {\n name: parsedData.name ?? '',\n organizationId: organization.id,\n },\n }),\n }: {\n prisma: PrismaClient\n createWorkspace?: ({\n parsedData,\n organization,\n prisma,\n }: {\n parsedData: z.infer<typeof createWorkspaceSchema>\n organization: Organization\n prisma: PrismaClient\n }) => Promise<Workspace>\n }) =>\n async (request: NextRequest) => {\n const headersList = await headers()\n const authorization = headersList.get('authorization')\n\n if (!authorization) {\n return NextResponse.json(\n { error: 'No authorization header found' },\n { status: 400 },\n )\n }\n\n const organizationApiKey = await getOrganizationApiKey({\n authorization,\n prisma,\n })\n\n if (!organizationApiKey) {\n return NextResponse.json(\n { error: 'Invalid organization api key' },\n { status: 400 },\n )\n }\n\n const body = await request.json()\n const parsed = createWorkspaceSchema.safeParse(body)\n\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n\n const organization = await prisma.organization.findUnique({\n where: {\n id: organizationApiKey.organizationId,\n },\n })\n\n if (!organization) {\n return NextResponse.json(\n { error: 'Organization not found' },\n { status: 404 },\n )\n }\n\n const workspace = await createWorkspace({\n parsedData: parsed.data,\n organization,\n prisma,\n })\n\n return NextResponse.json(\n {\n workspace: serializeApiWorkspace({ workspace }),\n },\n { headers: cacheHeaders },\n )\n }\n\nexport const buildOPTIONS = () => () =>\n NextResponse.json(\n {},\n {\n headers: cacheHeaders,\n },\n )\n\nexport { createWorkspaceSchema }\n"],"names":[],"mappings":"6jCAAO,IAAM,EAAe,CAC1B,8BAA+B,IAC/B,+BAAgC,kCAChC,+BACE,uDACJ,+DCJA,IAAA,EAAA,EAAA,CAAA,CAAA,OAEO,IAAM,EAAwB,MAAO,eAC1C,CAAa,QACb,CAAM,CAIP,IACC,GAAI,CAAC,EACH,OAAO,KAGT,CAJoB,EAId,EAAG,EAAwB,CAAG,EAAc,KAAK,CAAC,iBAExD,AAAK,CAAA,EAAA,CAAD,CAAC,QAAA,AAAQ,EAAC,GAIP,EAAO,kBAAkB,CAAC,EAJO,OAIE,CAAC,CACzC,MAAO,CAAE,MAAO,CAAwB,CAC1C,GALS,IAMX,+DCrBO,IAAM,EAAwB,CAAC,WACpC,CAAS,CAGV,GAAK,CAAC,CACL,GAAI,EAAU,EAAE,CAChB,KAAM,EAAU,IAAI,CACpB,UAAW,EA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led/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},24725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},20635,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/action-async-storage.external.js",()=>require("next/dist/server/app-render/action-async-storage.external.js"))},93695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},30611,e=>{"use strict";e.s(["cacheHeaders",()=>t]);let t={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type"}},88122,e=>{"use strict";e.s(["getApiKey",()=>r]);var t=e.i(55897);let r=async({authorization:e,type:r,prisma:s})=>{if(!e)return null;let[,a]=e.split("Bearer ");return(0,t.validate)(a)?s.apiKey.findFirst({where:{type:r,value:a}}):null}},45027,77009,e=>{"use strict";e.s(["getMcpServerLabel",()=>r],45027),e.s(["normalizeMcpServerName",()=>t],77009);let t=e=>e.replace(/[^a-zA-Z0-9-]/g,"-"),r=({id:e,name:r})=>{if(r){let e=t(r);if(e)return e}return`mcp-server-${e}`}},67083,e=>{"use strict";e.s(["isJSON",()=>t]);let t=e=>{try{return JSON.parse(e),!0}catch(e){return!1}}},40145,1065,24822,e=>{"use strict";e.s(["serializeApiMcpServer",()=>t],40145);let t=({mcpServer:e})=>({id:e.id,name:e.name,description:e.description,transportType:e.transportType,sseTransport:e.sseTransport?(({sseTransport:e})=>({id:e.id,url:e.url,headers:e.headers,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))({sseTransport:e.sseTransport}):null,httpTransport:e.httpTransport?(({httpTransport:e})=>({id:e.id,url:e.url,headers:e.headers,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))({httpTransport:e.httpTransport}):null,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()});e.s(["mcpServerSchema",()=>d],1065);var r=e.i(13669),s=e.i(29173),a=e.i(67083);let n=r.z.object({command:r.z.string().min(1),args:r.z.string().min(1)}),i=r.z.object({url:r.z.string().min(1).url(),headers:r.z.string().min(1).refine(a.isJSON,{message:"Must be a valid JSON string."})}),o=r.z.object({url:r.z.string().min(1).url(),headers:r.z.string().min(1).refine(a.isJSON,{message:"Must be a valid JSON string."})}),p=r.z.string().min(1).optional().nullable(),l=r.z.string().min(1).optional().nullable(),d=r.z.object({name:p,description:l,transportType:r.z.nativeEnum(s.TransportType).refine(e=>e!==s.TransportType.STDIO,{message:`transportType cannot be ${s.TransportType.STDIO}`}),sseTransport:i.nullable().optional(),httpTransport:o.nullable().optional()}).superRefine((e,t)=>{if(e.transportType===s.TransportType.STDIO){t.addIssue({code:r.z.ZodIssueCode.custom,message:`Transport type ${s.TransportType.STDIO} is not allowed.`});let a=n.safeParse(e.stdioTransport);a.success||a.error.issues.forEach(e=>t.addIssue({...e,path:["stdioTransport",...e.path]}))}else if(e.transportType===s.TransportType.SSE){let r=i.safeParse(e.sseTransport);if(r.success)return;r.error.issues.forEach(e=>t.addIssue({...e,path:["sseTransport",...e.path]}))}else if(e.transportType===s.TransportType.HTTP){let r=o.safeParse(e.httpTransport);if(r.success)return;r.error.issues.forEach(e=>t.addIssue({...e,path:["httpTransport",...e.path]}))}});e.s(["isMcpServerLabelTaken",()=>h],24822);var u=e.i(45027),c=e.i(77009);let h=async({prisma:e,assistantId:t,label:r,excludeMcpServerId:s})=>{let a=await e.mcpServer.findMany({where:{assistantId:t,...s?{NOT:{id:s}}:{}},select:{id:!0,name:!0}}),n=(0,c.normalizeMcpServerName)(r);if(!/[a-zA-Z0-9]/.test(n))return!1;let i=n.toLowerCase();return a.some(e=>{let t=e.name?(0,c.normalizeMcpServerName)(e.name):null;if(t&&/[a-zA-Z0-9]/.test(t)&&t.toLowerCase()===i)return!0;let r=(0,u.getMcpServerLabel)({id:e.id,name:e.name}),s=(0,c.normalizeMcpServerName)(r);return/[a-zA-Z0-9]/.test(s)&&s.toLowerCase()===i})}},56584,e=>{"use strict";e.s([])},56410,e=>{"use strict";e.s(["handler",()=>H,"patchFetch",()=>k,"routeModule",()=>P,"serverHooks",()=>M,"workAsyncStorage",()=>j,"workUnitAsyncStorage",()=>z],56410);var t=e.i(5865),r=e.i(43877),s=e.i(77767),a=e.i(92562),n=e.i(66256),i=e.i(5270),o=e.i(90231),p=e.i(82677),l=e.i(51081),d=e.i(89822),u=e.i(9124),c=e.i(39147),h=e.i(40568),m=e.i(87188),v=e.i(93695);e.i(57132);var T=e.i(80739);e.s(["GET",()=>O,"OPTIONS",()=>I,"POST",()=>C],14823);var f=e.i(24493),x=e.i(49493),g=e.i(29173),y=e.i(11053),R=e.i(30611),S=e.i(88122),w=e.i(40145),A=e.i(1065),N=e.i(77009),E=e.i(24822);let O=(({prisma:e})=>async(t,r)=>{let{assistantId:s}=await r.params,a=(await (0,y.headers)()).get("authorization");if(!a)return x.NextResponse.json({error:"No authorization header found"},{status:400});let n=await (0,S.getApiKey)({type:g.ApiKeyType.PRIVATE,authorization:a,prisma:e});if(!n)return x.NextResponse.json({error:"Invalid api key"},{status:400});let i=await e.assistant.findFirst({where:{id:s,workspaceId:n.workspaceId},include:{mcpServers:{include:{stdioTransport:!0,sseTransport:!0,httpTransport:!0},orderBy:{createdAt:"desc"}}}});return i?x.NextResponse.json({mcpServers:i.mcpServers.map(e=>(0,w.serializeApiMcpServer)({mcpServer:e}))},{headers:R.cacheHeaders}):x.NextResponse.json({error:"No assistant found"},{status:400})})({prisma:f.prisma}),C=(({prisma:e})=>async(t,r)=>{let{assistantId:s}=await r.params,a=(await (0,y.headers)()).get("authorization");if(!a)return x.NextResponse.json({error:"No authorization header found"},{status:400});let n=await (0,S.getApiKey)({authorization:a,type:g.ApiKeyType.PRIVATE,prisma:e});if(!n)return x.NextResponse.json({error:"Invalid api key"},{status:400});let i=await t.json(),o=A.mcpServerSchema.safeParse(i);if(!o.success)return x.NextResponse.json({error:"Invalid payload"},{status:400});let{transportType:p,sseTransport:l,httpTransport:d,name:u,description:c}=o.data,h=n.workspaceId;if(!await e.assistant.findFirst({where:{id:s,workspaceId:h}}))return x.NextResponse.json({error:"No assistant found"},{status:400});if("string"==typeof u){let t=(0,N.normalizeMcpServerName)(u);if(!/[a-zA-Z0-9]/.test(t))return x.NextResponse.json({error:"Invalid MCP server name. Use letters, numbers, spaces, or hyphens."},{status:400});if(await (0,E.isMcpServerLabelTaken)({prisma:e,assistantId:s,label:t}))return x.NextResponse.json({error:"An MCP server with that name already exists."},{status:400})}let m=await e.mcpServer.create({data:{transportType:p,...p===g.TransportType.SSE?{sseTransport:{create:{url:l.url,headers:JSON.parse(l.headers)}}}:{},...p===g.TransportType.HTTP?{httpTransport:{create:{url:d.url,headers:JSON.parse(d.headers)}}}:{},...void 0!==u?{name:u}:{},...void 0!==c?{description:c}:{},assistant:{connect:{id:s,workspaceId:h}}},include:{stdioTransport:!0,sseTransport:!0,httpTransport:!0}});return x.NextResponse.json({mcpServer:(0,w.serializeApiMcpServer)({mcpServer:m})},{headers:R.cacheHeaders})})({prisma:f.prisma}),I=()=>x.NextResponse.json({},{headers:R.cacheHeaders});var b=e.i(14823);let P=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/assistants/[assistantId]/mcp-servers/route",pathname:"/api/assistants/[assistantId]/mcp-servers",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/route.ts",nextConfigOutput:"",userland:b}),{workAsyncStorage:j,workUnitAsyncStorage:z,serverHooks:M}=P;function k(){return(0,s.patchFetch)({workAsyncStorage:j,workUnitAsyncStorage:z})}async function H(e,t,s){var f;let x="/api/assistants/[assistantId]/mcp-servers/route";x=x.replace(/\/index$/,"")||"/";let g=await P.prepare(e,t,{srcPage:x,multiZoneDraftMode:!1});if(!g)return t.statusCode=400,t.end("Bad Request"),null==s.waitUntil||s.waitUntil.call(s,Promise.resolve()),null;let{buildId:y,params:R,nextConfig:S,isDraftMode:w,prerenderManifest:A,routerServerContext:N,isOnDemandRevalidate:E,revalidateOnlyGenerated:O,resolvedPathname:C}=g,I=(0,i.normalizeAppPath)(x),b=!!(A.dynamicRoutes[I]||A.routes[C]);if(b&&!w){let e=!!A.routes[C],t=A.dynamicRoutes[I];if(t&&!1===t.fallback&&!e)throw new v.NoFallbackError}let j=null;!b||P.isDev||w||(j="/index"===(j=C)?"/":j);let z=!0===P.isDev||!b,M=b&&!z,k=e.method||"GET",H=(0,n.getTracer)(),q=H.getActiveScopeSpan(),_={params:R,prerenderManifest:A,renderOpts:{experimental:{cacheComponents:!!S.experimental.cacheComponents,authInterrupts:!!S.experimental.authInterrupts},supportsDynamicResponse:z,incrementalCache:(0,a.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:null==(f=S.experimental)?void 0:f.cacheLife,isRevalidate:M,waitUntil:s.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,s)=>P.onRequestError(e,t,s,N)},sharedContext:{buildId:y}},U=new o.NodeNextRequest(e),D=new o.NodeNextResponse(t),K=p.NextRequestAdapter.fromNodeNextRequest(U,(0,p.signalFromNodeResponse)(t));try{let i=async r=>P.handle(K,_).finally(()=>{if(!r)return;r.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let s=H.getRootSpanAttributes();if(!s)return;if(s.get("next.span_type")!==l.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${s.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=s.get("next.route");if(a){let e=`${k} ${a}`;r.setAttributes({"next.route":a,"http.route":a,"next.span_name":e}),r.updateName(e)}else r.updateName(`${k} ${e.url}`)}),o=async n=>{var o,p;let l=async({previousCacheEntry:r})=>{try{if(!(0,a.getRequestMeta)(e,"minimalMode")&&E&&O&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await i(n);e.fetchMetrics=_.renderOpts.fetchMetrics;let p=_.renderOpts.pendingWaitUntil;p&&s.waitUntil&&(s.waitUntil(p),p=void 0);let l=_.renderOpts.collectedTags;if(!b)return await (0,u.sendResponse)(U,D,o,_.renderOpts.pendingWaitUntil),null;{let e=await o.blob(),t=(0,c.toNodeOutgoingHttpHeaders)(o.headers);l&&(t[m.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==_.renderOpts.collectedRevalidate&&!(_.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&_.renderOpts.collectedRevalidate,s=void 0===_.renderOpts.collectedExpire||_.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:_.renderOpts.collectedExpire;return{value:{kind:T.CachedRouteKind.APP_ROUTE,status:o.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:s}}}}catch(t){throw(null==r?void 0:r.isStale)&&await P.onRequestError(e,t,{routerKind:"App Router",routePath:x,routeType:"route",revalidateReason:(0,d.getRevalidateReason)({isRevalidate:M,isOnDemandRevalidate:E})},N),t}},v=await P.handleResponse({req:e,nextConfig:S,cacheKey:j,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:A,isRoutePPREnabled:!1,isOnDemandRevalidate:E,revalidateOnlyGenerated:O,responseGenerator:l,waitUntil:s.waitUntil});if(!b)return null;if((null==v||null==(o=v.value)?void 0:o.kind)!==T.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==v||null==(p=v.value)?void 0:p.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,a.getRequestMeta)(e,"minimalMode")||t.setHeader("x-nextjs-cache",E?"REVALIDATED":v.isMiss?"MISS":v.isStale?"STALE":"HIT"),w&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let f=(0,c.fromNodeOutgoingHttpHeaders)(v.value.headers);return(0,a.getRequestMeta)(e,"minimalMode")&&b||f.delete(m.NEXT_CACHE_TAGS_HEADER),!v.cacheControl||t.getHeader("Cache-Control")||f.get("Cache-Control")||f.set("Cache-Control",(0,h.getCacheControlHeader)(v.cacheControl)),await (0,u.sendResponse)(U,D,new Response(v.value.body,{headers:f,status:v.value.status||200})),null};q?await o(q):await H.withPropagatedContext(e.headers,()=>H.trace(l.BaseServerSpan.handleRequest,{spanName:`${k} ${e.url}`,kind:n.SpanKind.SERVER,attributes:{"http.method":k,"http.target":e.url}},o))}catch(t){if(t instanceof v.NoFallbackError||await P.onRequestError(e,t,{routerKind:"App Router",routePath:I,routeType:"route",revalidateReason:(0,d.getRevalidateReason)({isRevalidate:M,isOnDemandRevalidate:E})}),b)throw t;return await (0,u.sendResponse)(U,D,new Response(null,{status:500})),null}}}];
|
|
1
|
+
module.exports=[18622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},24725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},20635,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/action-async-storage.external.js",()=>require("next/dist/server/app-render/action-async-storage.external.js"))},93695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},30611,e=>{"use strict";e.s(["cacheHeaders",()=>t]);let t={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept"}},88122,e=>{"use strict";e.s(["getApiKey",()=>r]);var t=e.i(55897);let r=async({authorization:e,type:r,prisma:s})=>{if(!e)return null;let[,a]=e.split("Bearer ");return(0,t.validate)(a)?s.apiKey.findFirst({where:{type:r,value:a}}):null}},45027,77009,e=>{"use strict";e.s(["getMcpServerLabel",()=>r],45027),e.s(["normalizeMcpServerName",()=>t],77009);let t=e=>e.replace(/[^a-zA-Z0-9-]/g,"-"),r=({id:e,name:r})=>{if(r){let e=t(r);if(e)return e}return`mcp-server-${e}`}},67083,e=>{"use strict";e.s(["isJSON",()=>t]);let t=e=>{try{return JSON.parse(e),!0}catch(e){return!1}}},40145,1065,24822,e=>{"use strict";e.s(["serializeApiMcpServer",()=>t],40145);let t=({mcpServer:e})=>({id:e.id,name:e.name,description:e.description,transportType:e.transportType,sseTransport:e.sseTransport?(({sseTransport:e})=>({id:e.id,url:e.url,headers:e.headers,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))({sseTransport:e.sseTransport}):null,httpTransport:e.httpTransport?(({httpTransport:e})=>({id:e.id,url:e.url,headers:e.headers,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))({httpTransport:e.httpTransport}):null,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()});e.s(["mcpServerSchema",()=>d],1065);var r=e.i(13669),s=e.i(29173),a=e.i(67083);let n=r.z.object({command:r.z.string().min(1),args:r.z.string().min(1)}),i=r.z.object({url:r.z.string().min(1).url(),headers:r.z.string().min(1).refine(a.isJSON,{message:"Must be a valid JSON string."})}),o=r.z.object({url:r.z.string().min(1).url(),headers:r.z.string().min(1).refine(a.isJSON,{message:"Must be a valid JSON string."})}),p=r.z.string().min(1).optional().nullable(),l=r.z.string().min(1).optional().nullable(),d=r.z.object({name:p,description:l,transportType:r.z.nativeEnum(s.TransportType).refine(e=>e!==s.TransportType.STDIO,{message:`transportType cannot be ${s.TransportType.STDIO}`}),sseTransport:i.nullable().optional(),httpTransport:o.nullable().optional()}).superRefine((e,t)=>{if(e.transportType===s.TransportType.STDIO){t.addIssue({code:r.z.ZodIssueCode.custom,message:`Transport type ${s.TransportType.STDIO} is not allowed.`});let a=n.safeParse(e.stdioTransport);a.success||a.error.issues.forEach(e=>t.addIssue({...e,path:["stdioTransport",...e.path]}))}else if(e.transportType===s.TransportType.SSE){let r=i.safeParse(e.sseTransport);if(r.success)return;r.error.issues.forEach(e=>t.addIssue({...e,path:["sseTransport",...e.path]}))}else if(e.transportType===s.TransportType.HTTP){let r=o.safeParse(e.httpTransport);if(r.success)return;r.error.issues.forEach(e=>t.addIssue({...e,path:["httpTransport",...e.path]}))}});e.s(["isMcpServerLabelTaken",()=>h],24822);var u=e.i(45027),c=e.i(77009);let h=async({prisma:e,assistantId:t,label:r,excludeMcpServerId:s})=>{let a=await e.mcpServer.findMany({where:{assistantId:t,...s?{NOT:{id:s}}:{}},select:{id:!0,name:!0}}),n=(0,c.normalizeMcpServerName)(r);if(!/[a-zA-Z0-9]/.test(n))return!1;let i=n.toLowerCase();return a.some(e=>{let t=e.name?(0,c.normalizeMcpServerName)(e.name):null;if(t&&/[a-zA-Z0-9]/.test(t)&&t.toLowerCase()===i)return!0;let r=(0,u.getMcpServerLabel)({id:e.id,name:e.name}),s=(0,c.normalizeMcpServerName)(r);return/[a-zA-Z0-9]/.test(s)&&s.toLowerCase()===i})}},56584,e=>{"use strict";e.s([])},56410,e=>{"use strict";e.s(["handler",()=>H,"patchFetch",()=>k,"routeModule",()=>P,"serverHooks",()=>M,"workAsyncStorage",()=>j,"workUnitAsyncStorage",()=>z],56410);var t=e.i(5865),r=e.i(43877),s=e.i(77767),a=e.i(92562),n=e.i(66256),i=e.i(5270),o=e.i(90231),p=e.i(82677),l=e.i(51081),d=e.i(89822),u=e.i(9124),c=e.i(39147),h=e.i(40568),m=e.i(87188),v=e.i(93695);e.i(57132);var T=e.i(80739);e.s(["GET",()=>O,"OPTIONS",()=>I,"POST",()=>C],14823);var f=e.i(24493),x=e.i(49493),g=e.i(29173),y=e.i(11053),R=e.i(30611),S=e.i(88122),A=e.i(40145),w=e.i(1065),N=e.i(77009),E=e.i(24822);let O=(({prisma:e})=>async(t,r)=>{let{assistantId:s}=await r.params,a=(await (0,y.headers)()).get("authorization");if(!a)return x.NextResponse.json({error:"No authorization header found"},{status:400});let n=await (0,S.getApiKey)({type:g.ApiKeyType.PRIVATE,authorization:a,prisma:e});if(!n)return x.NextResponse.json({error:"Invalid api key"},{status:400});let i=await e.assistant.findFirst({where:{id:s,workspaceId:n.workspaceId},include:{mcpServers:{include:{stdioTransport:!0,sseTransport:!0,httpTransport:!0},orderBy:{createdAt:"desc"}}}});return i?x.NextResponse.json({mcpServers:i.mcpServers.map(e=>(0,A.serializeApiMcpServer)({mcpServer:e}))},{headers:R.cacheHeaders}):x.NextResponse.json({error:"No assistant found"},{status:400})})({prisma:f.prisma}),C=(({prisma:e})=>async(t,r)=>{let{assistantId:s}=await r.params,a=(await (0,y.headers)()).get("authorization");if(!a)return x.NextResponse.json({error:"No authorization header found"},{status:400});let n=await (0,S.getApiKey)({authorization:a,type:g.ApiKeyType.PRIVATE,prisma:e});if(!n)return x.NextResponse.json({error:"Invalid api key"},{status:400});let i=await t.json(),o=w.mcpServerSchema.safeParse(i);if(!o.success)return x.NextResponse.json({error:"Invalid payload"},{status:400});let{transportType:p,sseTransport:l,httpTransport:d,name:u,description:c}=o.data,h=n.workspaceId;if(!await e.assistant.findFirst({where:{id:s,workspaceId:h}}))return x.NextResponse.json({error:"No assistant found"},{status:400});if("string"==typeof u){let t=(0,N.normalizeMcpServerName)(u);if(!/[a-zA-Z0-9]/.test(t))return x.NextResponse.json({error:"Invalid MCP server name. Use letters, numbers, spaces, or hyphens."},{status:400});if(await (0,E.isMcpServerLabelTaken)({prisma:e,assistantId:s,label:t}))return x.NextResponse.json({error:"An MCP server with that name already exists."},{status:400})}let m=await e.mcpServer.create({data:{transportType:p,...p===g.TransportType.SSE?{sseTransport:{create:{url:l.url,headers:JSON.parse(l.headers)}}}:{},...p===g.TransportType.HTTP?{httpTransport:{create:{url:d.url,headers:JSON.parse(d.headers)}}}:{},...void 0!==u?{name:u}:{},...void 0!==c?{description:c}:{},assistant:{connect:{id:s,workspaceId:h}}},include:{stdioTransport:!0,sseTransport:!0,httpTransport:!0}});return x.NextResponse.json({mcpServer:(0,A.serializeApiMcpServer)({mcpServer:m})},{headers:R.cacheHeaders})})({prisma:f.prisma}),I=()=>x.NextResponse.json({},{headers:R.cacheHeaders});var b=e.i(14823);let P=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/assistants/[assistantId]/mcp-servers/route",pathname:"/api/assistants/[assistantId]/mcp-servers",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/supercorp/superinterface/packages/server/src/app/api/assistants/[assistantId]/mcp-servers/route.ts",nextConfigOutput:"",userland:b}),{workAsyncStorage:j,workUnitAsyncStorage:z,serverHooks:M}=P;function k(){return(0,s.patchFetch)({workAsyncStorage:j,workUnitAsyncStorage:z})}async function H(e,t,s){var f;let x="/api/assistants/[assistantId]/mcp-servers/route";x=x.replace(/\/index$/,"")||"/";let g=await P.prepare(e,t,{srcPage:x,multiZoneDraftMode:!1});if(!g)return t.statusCode=400,t.end("Bad Request"),null==s.waitUntil||s.waitUntil.call(s,Promise.resolve()),null;let{buildId:y,params:R,nextConfig:S,isDraftMode:A,prerenderManifest:w,routerServerContext:N,isOnDemandRevalidate:E,revalidateOnlyGenerated:O,resolvedPathname:C}=g,I=(0,i.normalizeAppPath)(x),b=!!(w.dynamicRoutes[I]||w.routes[C]);if(b&&!A){let e=!!w.routes[C],t=w.dynamicRoutes[I];if(t&&!1===t.fallback&&!e)throw new v.NoFallbackError}let j=null;!b||P.isDev||A||(j="/index"===(j=C)?"/":j);let z=!0===P.isDev||!b,M=b&&!z,k=e.method||"GET",H=(0,n.getTracer)(),q=H.getActiveScopeSpan(),_={params:R,prerenderManifest:w,renderOpts:{experimental:{cacheComponents:!!S.experimental.cacheComponents,authInterrupts:!!S.experimental.authInterrupts},supportsDynamicResponse:z,incrementalCache:(0,a.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:null==(f=S.experimental)?void 0:f.cacheLife,isRevalidate:M,waitUntil:s.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,s)=>P.onRequestError(e,t,s,N)},sharedContext:{buildId:y}},U=new o.NodeNextRequest(e),D=new o.NodeNextResponse(t),K=p.NextRequestAdapter.fromNodeNextRequest(U,(0,p.signalFromNodeResponse)(t));try{let i=async r=>P.handle(K,_).finally(()=>{if(!r)return;r.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let s=H.getRootSpanAttributes();if(!s)return;if(s.get("next.span_type")!==l.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${s.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=s.get("next.route");if(a){let e=`${k} ${a}`;r.setAttributes({"next.route":a,"http.route":a,"next.span_name":e}),r.updateName(e)}else r.updateName(`${k} ${e.url}`)}),o=async n=>{var o,p;let l=async({previousCacheEntry:r})=>{try{if(!(0,a.getRequestMeta)(e,"minimalMode")&&E&&O&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let o=await i(n);e.fetchMetrics=_.renderOpts.fetchMetrics;let p=_.renderOpts.pendingWaitUntil;p&&s.waitUntil&&(s.waitUntil(p),p=void 0);let l=_.renderOpts.collectedTags;if(!b)return await (0,u.sendResponse)(U,D,o,_.renderOpts.pendingWaitUntil),null;{let e=await o.blob(),t=(0,c.toNodeOutgoingHttpHeaders)(o.headers);l&&(t[m.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==_.renderOpts.collectedRevalidate&&!(_.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&_.renderOpts.collectedRevalidate,s=void 0===_.renderOpts.collectedExpire||_.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:_.renderOpts.collectedExpire;return{value:{kind:T.CachedRouteKind.APP_ROUTE,status:o.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:s}}}}catch(t){throw(null==r?void 0:r.isStale)&&await P.onRequestError(e,t,{routerKind:"App Router",routePath:x,routeType:"route",revalidateReason:(0,d.getRevalidateReason)({isRevalidate:M,isOnDemandRevalidate:E})},N),t}},v=await P.handleResponse({req:e,nextConfig:S,cacheKey:j,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:w,isRoutePPREnabled:!1,isOnDemandRevalidate:E,revalidateOnlyGenerated:O,responseGenerator:l,waitUntil:s.waitUntil});if(!b)return null;if((null==v||null==(o=v.value)?void 0:o.kind)!==T.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==v||null==(p=v.value)?void 0:p.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,a.getRequestMeta)(e,"minimalMode")||t.setHeader("x-nextjs-cache",E?"REVALIDATED":v.isMiss?"MISS":v.isStale?"STALE":"HIT"),A&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let f=(0,c.fromNodeOutgoingHttpHeaders)(v.value.headers);return(0,a.getRequestMeta)(e,"minimalMode")&&b||f.delete(m.NEXT_CACHE_TAGS_HEADER),!v.cacheControl||t.getHeader("Cache-Control")||f.get("Cache-Control")||f.set("Cache-Control",(0,h.getCacheControlHeader)(v.cacheControl)),await (0,u.sendResponse)(U,D,new Response(v.value.body,{headers:f,status:v.value.status||200})),null};q?await o(q):await H.withPropagatedContext(e.headers,()=>H.trace(l.BaseServerSpan.handleRequest,{spanName:`${k} ${e.url}`,kind:n.SpanKind.SERVER,attributes:{"http.method":k,"http.target":e.url}},o))}catch(t){if(t instanceof v.NoFallbackError||await P.onRequestError(e,t,{routerKind:"App Router",routePath:I,routeType:"route",revalidateReason:(0,d.getRevalidateReason)({isRevalidate:M,isOnDemandRevalidate:E})}),b)throw t;return await (0,u.sendResponse)(U,D,new Response(null,{status:500})),null}}}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=%5Broot-of-the-server%5D__e73543af._.js.map
|