{"version":3,"sources":["../src/utils/errors.ts","../src/schemas/invocation.ts","../src/schemas/events.ts","../src/runtime/index.ts","../src/runtime/loop.ts","../src/runtime/registry.ts","../src/utils/env.ts","../src/define/helpers.ts","../src/define/index.ts","../src/index.ts"],"names":["FunctionNotFoundInRegistryError","message","GetNextInvocationError","PostResultError","PostErrorError","FunctionInvocationContextSessionDetails","z","FunctionInvocationContext","RuntimeEventPayload","RuntimeClient","registry","runtimeApi","__publicField","response","requestId","traceId","text","parsedData","safeParseResult","event","name","result","error","runtimeError","formatRuntimeError","type","stack","waitForAndHandleInvocation","runtimeClient","handleFatalError","functionName","functionDefinition","runInvocationLoop","handleProductionFailure","FunctionRegistry","handler","config","params","context","foundDefinition","handlerResult","EnvironmentManager","processEnv","getOrDefault","env","key","dflt","val","writeManifestToDisk","manifest","manifestsDir","isFirstInvocation","existsSync","rmSync","mkdirSync","persistedManifest","buildPersistedFunctionManifest","writeFileSync","join","parametersSchema","configWithoutSchema","processedConfig","buildPersistedJsonSchema","input","defineFn","functionsRegistry","environmentManager","handleInvocationLoopFailure"],"mappings":";;;;;;;;;;0KAAO,IAAMA,CAAAA,CAAN,cAA8C,KAAM,CACzD,WAAA,CAAYC,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaC,CAAAA,CAAN,cAAqC,KAAM,CAChD,WAAA,CAAYD,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaE,CAAAA,CAAN,cAA8B,KAAM,CACzC,WAAA,CAAYF,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaG,CAAAA,CAAN,cAA6B,KAAM,CACxC,WAAA,CAAYH,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CCnBO,IAAMI,CAAAA,CAA0CC,kBAAAA,CAAE,WAAA,CAAY,CACnE,EAAA,CAAIA,kBAAAA,CAAE,MAAA,EAAO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A,CAAQ,IAAA,CAAK,CAAC,EAChB,CAEI4C,CAAAA,CAAmB,KAAA,GAAU,SAAA,EAC/BlC,CAAAA,CAAkBJ,CAAAA,CAAeuC,CAA2B,CAAA,CAAE,KAAA,CAC3D7C,CAAAA,EAAmB,CAClB,OAAA,CAAQ,KAAA,CAAM,sBAAA,CAAwBA,CAAK,CAAA,CAC3C,OAAA,CAAQ,IAAA,CAAK,CAAC,EAChB,CACF,CAAA","file":"index.cjs","sourcesContent":["export class FunctionNotFoundInRegistryError extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n\nexport class GetNextInvocationError extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n\nexport class PostResultError extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n\nexport class PostErrorError extends Error {\n  constructor(message: string) {\n    super(message);\n  }\n}\n","import z from \"zod\";\n\n// Allow in additional fields without needing to update the SDK version\nexport const FunctionInvocationContextSessionDetails = z.looseObject({\n  id: z.string(),\n  connectUrl: z.string(),\n});\n\nexport type FunctionInvocationContextSessionDetails = z.infer<\n  typeof FunctionInvocationContextSessionDetails\n>;\n\n// Allow in additional fields without needing to update the SDK version\nexport const FunctionInvocationContext = z.looseObject({\n  session: FunctionInvocationContextSessionDetails,\n  secrets: z.record(z.string().min(1), z.string()).default({}),\n});\n\nexport type FunctionInvocationContext = z.infer<\n  typeof FunctionInvocationContext\n>;\n","import z from \"zod\";\nimport { FunctionInvocationContext } from \"./invocation.js\";\n\nexport const RuntimeEventPayload = z.object({\n  functionName: z.string().min(1),\n  params: z.looseObject({}), // Allow passthrough of unknown (all) keys\n  context: FunctionInvocationContext,\n});\n\nexport type RuntimeEventPayload = z.infer<typeof RuntimeEventPayload>;\n\nexport const RuntimeEvent = z.object({\n  requestId: z.string().min(1),\n  event: RuntimeEventPayload,\n});\n\nexport type RuntimeEvent = z.infer<typeof RuntimeEvent>;\n\nexport const RuntimeError = z.object({\n  errorMessage: z.string().min(1),\n  errorType: z.string().min(1),\n  stackTrace: z.array(z.string().min(1)),\n});\n\nexport type RuntimeError = z.infer<typeof RuntimeError>;\n","import type { FunctionRegistry } from \"../runtime/registry.js\";\nimport {\n  GetNextInvocationError,\n  PostErrorError,\n  PostResultError,\n} from \"../utils/errors.js\";\nimport {\n  RuntimeError,\n  RuntimeEvent,\n  RuntimeEventPayload,\n} from \"../schemas/events.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\n\nexport interface IRuntimeClient {\n  waitForNextInvocation(): Promise<RuntimeEvent>;\n  getFunctionDefinitionByName(name: string): FunctionManifest<unknown> | null;\n\n  executeFunction(\n    event: RuntimeEventPayload,\n  ): Promise<FunctionHandlerCallbackReturnValue>;\n\n  handleSuccess(\n    requestId: string,\n    result: FunctionHandlerCallbackReturnValue,\n  ): Promise<void>;\n\n  handleFailure(requestId: string, error: unknown): Promise<void>;\n}\n\nexport class RuntimeClient implements IRuntimeClient {\n  private runtimeApi: string;\n  private baseUrl: string;\n  private registry: FunctionRegistry;\n\n  constructor(registry: FunctionRegistry, runtimeApi: string) {\n    this.runtimeApi = runtimeApi;\n    this.baseUrl = `http://${this.runtimeApi}/2018-06-01/runtime`;\n    this.registry = registry;\n  }\n\n  public async waitForNextInvocation(): Promise<RuntimeEvent> {\n    const response = await fetch(`${this.baseUrl}/invocation/next`);\n    if (!response.ok) {\n      throw new GetNextInvocationError(\n        `Next invocation failed: ${response.status} ${response.statusText}`,\n      );\n    }\n\n    const requestId =\n      response.headers.get(\"Lambda-Runtime-Aws-Request-Id\") || \"unknown\";\n    const traceId = response.headers.get(\"Lambda-Runtime-Trace-Id\");\n\n    // This is to allow the X-Ray SDK to trace across invocations\n    if (traceId) {\n      process.env[\"_X_AMZN_TRACE_ID\"] = traceId;\n    }\n\n    const text = await response.text();\n    const parsedData = JSON.parse(text);\n\n    const safeParseResult = RuntimeEventPayload.safeParse(parsedData);\n    if (!safeParseResult.success) {\n      // TODO: type error\n      throw new Error(\"Failed to parse event into runtime event\");\n    }\n\n    const event = safeParseResult.data;\n    return { requestId, event };\n  }\n\n  public getFunctionDefinitionByName(\n    name: string,\n  ): FunctionManifest<unknown> | null {\n    return this.registry.getByName(name);\n  }\n\n  public executeFunction(\n    event: RuntimeEventPayload,\n  ): Promise<FunctionHandlerCallbackReturnValue> {\n    return this.registry.execute(\n      event.functionName,\n      event.params ?? {},\n      event.context,\n    );\n  }\n\n  public async handleSuccess(\n    requestId: string,\n    result: FunctionHandlerCallbackReturnValue,\n  ): Promise<void> {\n    const response = await fetch(\n      `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/response`,\n      {\n        method: \"POST\",\n        headers: { \"content-type\": \"application/json\" },\n        body: JSON.stringify(result),\n      },\n    );\n\n    if (!response.ok) {\n      throw new PostResultError(\n        `Failed to post response: ${response.status} ${response.statusText}`,\n      );\n    }\n  }\n\n  public async handleFailure(requestId: string, error: unknown): Promise<void> {\n    const runtimeError = formatRuntimeError(error);\n\n    const response = await fetch(\n      `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/error`,\n      {\n        method: \"POST\",\n        headers: { \"content-type\": \"application/json\" },\n        body: JSON.stringify(runtimeError),\n      },\n    );\n\n    if (!response.ok) {\n      throw new PostErrorError(\n        `Failed to post error: ${response.status} ${response.statusText}`,\n      );\n    }\n  }\n}\n\nfunction formatRuntimeError(error: unknown): RuntimeError {\n  if (error instanceof Error) {\n    return {\n      errorMessage: error.message,\n      errorType: error.name,\n      stackTrace: error.stack?.split(\"/n\") ?? [],\n    };\n  }\n\n  let message = \"An unknown error occurred\";\n  let type = \"UnknownError\";\n  let stack = [] as string[];\n\n  if (typeof error === \"string\") {\n    return {\n      errorMessage: error,\n      errorType: type,\n      stackTrace: stack,\n    };\n  }\n\n  if (typeof error !== \"object\" || error === null) {\n    return {\n      errorMessage: String(error),\n      errorType: type,\n      stackTrace: stack,\n    };\n  }\n\n  if (\"message\" in error && typeof error.message === \"string\") {\n    message = error.message;\n  }\n\n  if (\"name\" in error && typeof error.name === \"string\") {\n    type = error.name;\n  }\n\n  if (\n    \"stack\" in error &&\n    Array.isArray(error.stack) &&\n    typeof error.stack[0] === \"string\"\n  ) {\n    stack = error.stack;\n  }\n\n  return {\n    errorMessage: message,\n    errorType: type,\n    stackTrace: stack,\n  };\n}\n","import type { IRuntimeClient } from \"./index.js\";\n\nexport async function waitForAndHandleInvocation(\n  runtimeClient: IRuntimeClient,\n  handleFatalError: (error: unknown) => void,\n) {\n  // Any errors caught by this block will be considered fatal system errors\n  try {\n    const { requestId, event } = await runtimeClient.waitForNextInvocation();\n    console.log(`Received invocation with requestId: ${requestId}`);\n    const { functionName } = event;\n\n    // Validate that the specified function is in the registry.\n    // If not, throw a system error as this means we've set up the DB wrong\n    // and that the system thinks that function is here when it's not.\n    // NOTE: If the user finds a way to circumvent the SDK setup intentionally,\n    // NOTE: we could see this error when the DB is correct.\n    const functionDefinition =\n      runtimeClient.getFunctionDefinitionByName(functionName);\n\n    console.log(\n      `Found definition for \"${functionName}\": ${JSON.stringify(functionDefinition)}`,\n    );\n\n    // TODO: type this error\n    if (!functionDefinition) {\n      throw new Error(`Function \"${functionName}\" not found in registry`);\n    }\n\n    // Any errors caught by this block will be considered user code errors\n    let result;\n    try {\n      console.log(`Executing function: ${functionName}`);\n      result = await runtimeClient.executeFunction(event);\n      console.log(`Received result: ${JSON.stringify(result)}`);\n    } catch (error: unknown) {\n      console.error(\"Handler error:\", error);\n      await runtimeClient.handleFailure(requestId, error);\n      return; // This invocation is done - don't call handleSuccess\n    }\n\n    await runtimeClient.handleSuccess(requestId, result);\n    console.log(`Function \"${functionName}\" completed successfully`);\n  } catch (error: unknown) {\n    console.error(\"Fatal error in runtime loop:\", error);\n    handleFatalError(error);\n  }\n}\n\nexport async function runInvocationLoop(\n  runtimeClient: IRuntimeClient,\n  handleProductionFailure: (error: unknown) => void,\n): Promise<void> {\n  while (true) {\n    await waitForAndHandleInvocation(runtimeClient, handleProductionFailure);\n  }\n}\n","import { FunctionNotFoundInRegistryError } from \"../utils/errors.js\";\n\nimport type { FunctionInvocationContext } from \"../schemas/invocation.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport interface IFunctionRegistry {\n  register<S extends JSONSchemaInput>(\n    name: FunctionManifest<S>[\"name\"],\n    handler: FunctionManifest<S>[\"handler\"],\n    config: FunctionManifest<S>[\"config\"],\n  ): void;\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n  getByName(name: string): FunctionManifest<any> | null;\n\n  execute(\n    name: string,\n    params: object,\n    context: FunctionInvocationContext,\n  ): Promise<FunctionHandlerCallbackReturnValue>;\n\n  get size(): number;\n}\n\nexport class FunctionRegistry implements IFunctionRegistry {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n  private _functions = new Map<string, FunctionManifest<any>>();\n\n  register<S extends JSONSchemaInput>(\n    name: FunctionManifest<S>[\"name\"],\n    handler: FunctionManifest<S>[\"handler\"],\n    config: FunctionManifest<S>[\"config\"],\n  ) {\n    this._functions.set(name, {\n      name,\n      handler,\n      config,\n    });\n  }\n\n  public getByName(name: string): FunctionManifest<unknown> | null {\n    return this._functions.get(name) ?? null;\n  }\n\n  async execute(\n    name: string,\n    params: object,\n    context: FunctionInvocationContext,\n  ) {\n    const foundDefinition = this._functions.get(name);\n    if (!foundDefinition) {\n      throw new FunctionNotFoundInRegistryError(\n        `Couldn't find function with name \"${name}\" in registry`,\n      );\n    }\n\n    const handlerResult = await foundDefinition.handler(context, params);\n\n    // TODO: Remove when we have a better structured logging story\n    console.log(\"handlerResult\", handlerResult);\n\n    return handlerResult;\n  }\n\n  get size() {\n    return this._functions.size;\n  }\n}\n","export interface IEnvironmentManager {\n  get environment(): string;\n  get runtimeApi(): string;\n  get phase(): string;\n}\n\nexport class EnvironmentManager {\n  /// Whether we're running these locally or deployed (\"production\").\n  /// Locally we are more forgiving on failures, and will change logging.\n  private _environment: \"local\" | \"production\";\n\n  /// The URL that is used to alert the runtime to the status of the invocation.\n  /// Locally this will point to the URL of the dev server being run, in prod this\n  /// will point to the runtime's internal endpoints.\n  private _runtimeApi: string;\n\n  /// We need to handle running a function differently than we handle\n  /// deploying a function. The \"runtime\" phase is when we're trying to\n  /// run a function by name (either locally or in prod). The \"build\"\n  /// phase is when we're generating local manifest files to send to\n  /// the Browserbase API. Defaults to runtime phase.\n  private _phase: \"runtime\" | \"introspect\";\n\n  constructor(processEnv: NodeJS.ProcessEnv) {\n    this._environment = getOrDefault<typeof this._environment>(\n      processEnv,\n      \"NODE_ENV\",\n      \"local\",\n    );\n\n    this._runtimeApi = getOrDefault<typeof this._runtimeApi>(\n      processEnv,\n      \"AWS_LAMBDA_RUNTIME_API\",\n      \"127.0.0.1:14113\",\n    );\n\n    this._phase = getOrDefault<typeof this._phase>(\n      processEnv,\n      \"BB_FUNCTIONS_PHASE\",\n      \"runtime\",\n    );\n  }\n\n  get environment() {\n    return this._environment;\n  }\n\n  get runtimeApi() {\n    return this._runtimeApi;\n  }\n\n  get phase() {\n    return this._phase;\n  }\n}\n\nfunction getOrDefault<T>(env: NodeJS.ProcessEnv, key: string, dflt: T): T {\n  const val = env[key];\n  if (!val) {\n    return dflt;\n  }\n  return val as T;\n}\n","import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport z from \"zod\";\n\nimport type {\n  FunctionManifest,\n  PersistedFunctionManifest,\n} from \"../types/definition.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport function writeManifestToDisk<S extends JSONSchemaInput>(\n  manifest: FunctionManifest<S>,\n  manifestsDir: string,\n  isFirstInvocation: boolean,\n) {\n  if (isFirstInvocation) {\n    // Clear manifests directory if it exists to remove stale menifests\n    if (existsSync(manifestsDir)) {\n      rmSync(manifestsDir, { recursive: true });\n    }\n\n    mkdirSync(manifestsDir, { recursive: true });\n  }\n\n  const persistedManifest = buildPersistedFunctionManifest(manifest);\n\n  writeFileSync(\n    join(manifestsDir, `${manifest.name}.json`),\n    JSON.stringify(persistedManifest, null, 2),\n  );\n}\n\nexport function buildPersistedFunctionManifest<S extends JSONSchemaInput>(\n  manifest: FunctionManifest<S>,\n): PersistedFunctionManifest<S> {\n  const { name, config } = manifest;\n  const { parametersSchema, ...configWithoutSchema } = config;\n\n  const processedConfig: PersistedFunctionManifest<S>[\"config\"] = {\n    ...configWithoutSchema,\n  };\n\n  if (parametersSchema) {\n    processedConfig.parametersSchema =\n      buildPersistedJsonSchema(parametersSchema);\n  }\n\n  const processedManifest: PersistedFunctionManifest<S> = {\n    name,\n    config: processedConfig,\n  };\n\n  return processedManifest;\n}\n\nexport function buildPersistedJsonSchema(input: JSONSchemaInput): object {\n  if (input instanceof z.ZodObject) {\n    return z.toJSONSchema(input);\n  }\n\n  return {};\n}\n","import { join } from \"node:path\";\n\nimport type { FunctionConfiguration } from \"../types/definition.js\";\nimport type { FunctionHandler } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nimport { writeManifestToDisk } from \"./helpers.js\";\n\n// Singleton imports\nimport { environmentManager, functionsRegistry } from \"../index.js\";\n\n/// TODO: Write good documentation here\nexport function defineFn<S extends JSONSchemaInput = unknown>(\n  name: string,\n  handler: FunctionHandler<S>,\n  config: FunctionConfiguration<S> = {},\n): void {\n  functionsRegistry.register(name, handler, config);\n\n  if (\n    // The CLI needs \"local\" to know how to create sessions with\n    // non-default configurations during the local dev flow\n    environmentManager.phase === \"introspect\" ||\n    environmentManager.environment === \"local\"\n  ) {\n    const manifestsDir = join(\n      process.cwd(),\n      \".browserbase\",\n      \"functions\",\n      \"manifests\",\n    );\n\n    const isFirstInvocation = functionsRegistry.size === 1;\n\n    writeManifestToDisk(\n      { name, handler, config },\n      manifestsDir,\n      isFirstInvocation,\n    );\n  }\n}\n","import { RuntimeClient } from \"./runtime/index.js\";\nimport { runInvocationLoop } from \"./runtime/loop.js\";\nimport { FunctionRegistry } from \"./runtime/registry.js\";\nimport { EnvironmentManager } from \"./utils/env.js\";\n\nexport { defineFn } from \"./define/index.js\";\n\nexport const environmentManager = new EnvironmentManager(process.env);\nexport const functionsRegistry = new FunctionRegistry();\nexport const runtimeClient = new RuntimeClient(\n  functionsRegistry,\n  environmentManager.runtimeApi,\n);\n\nfunction handleInvocationLoopFailure(error: unknown): void {\n  console.error(\"Received fatal error from invocation loop\", error);\n  process.exit(1);\n}\n// We only want to listen for invocations iff we're in the \"runtime\" phase\nif (environmentManager.phase === \"runtime\") {\n  runInvocationLoop(runtimeClient, handleInvocationLoopFailure).catch(\n    (error: unknown) => {\n      console.error(\"Fatal runtime error:\", error);\n      process.exit(1);\n    },\n  );\n}\n"]}