@buildspacestudio/sdk 0.2.2 → 0.4.0

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.
Files changed (106) hide show
  1. package/README.md +126 -0
  2. package/dist/auth/index.cjs +259 -0
  3. package/dist/auth/index.cjs.map +1 -0
  4. package/dist/auth/index.d.cts +3 -0
  5. package/dist/auth/index.d.ts +3 -5
  6. package/dist/auth/index.js +255 -2
  7. package/dist/auth/index.js.map +1 -1
  8. package/dist/billing/index.cjs +226 -0
  9. package/dist/billing/index.cjs.map +1 -0
  10. package/dist/billing/index.d.cts +60 -0
  11. package/dist/billing/index.d.ts +60 -0
  12. package/dist/billing/index.js +222 -0
  13. package/dist/billing/index.js.map +1 -0
  14. package/dist/client/index.cjs +558 -0
  15. package/dist/client/index.cjs.map +1 -0
  16. package/dist/client/index.d.cts +89 -0
  17. package/dist/client/index.d.ts +12 -7
  18. package/dist/client/index.js +546 -105
  19. package/dist/client/index.js.map +1 -1
  20. package/dist/client-BYUWUiGZ.d.cts +143 -0
  21. package/dist/{auth/client.d.ts → client-ByNR5EZz.d.ts} +7 -5
  22. package/dist/client-D0vypxWb.d.cts +58 -0
  23. package/dist/{auth/client.js → client-D7bqvGJv.d.cts} +27 -30
  24. package/dist/{events/client.d.ts → client-DbGRRMt7.d.ts} +5 -3
  25. package/dist/client-d7kX5WfR.d.ts +143 -0
  26. package/dist/events/index.cjs +131 -0
  27. package/dist/events/index.cjs.map +1 -0
  28. package/dist/events/{server.d.ts → index.d.cts} +7 -4
  29. package/dist/events/index.d.ts +59 -4
  30. package/dist/events/index.js +127 -2
  31. package/dist/events/index.js.map +1 -1
  32. package/dist/http-D2gXpNpr.d.cts +100 -0
  33. package/dist/http-D2gXpNpr.d.ts +100 -0
  34. package/dist/index.cjs +1029 -0
  35. package/dist/index.cjs.map +1 -0
  36. package/dist/index.d.cts +92 -0
  37. package/dist/index.d.ts +21 -15
  38. package/dist/index.js +1010 -106
  39. package/dist/index.js.map +1 -1
  40. package/dist/next/index.cjs +183 -0
  41. package/dist/next/index.cjs.map +1 -0
  42. package/dist/next/index.d.cts +164 -0
  43. package/dist/next/index.d.ts +164 -0
  44. package/dist/next/index.js +172 -0
  45. package/dist/next/index.js.map +1 -0
  46. package/dist/notifications/index.cjs +56 -0
  47. package/dist/notifications/index.cjs.map +1 -0
  48. package/dist/notifications/{server.d.ts → index.d.cts} +8 -6
  49. package/dist/notifications/index.d.ts +79 -3
  50. package/dist/notifications/index.js +53 -1
  51. package/dist/notifications/index.js.map +1 -1
  52. package/dist/react/index.cjs +120 -0
  53. package/dist/react/index.cjs.map +1 -0
  54. package/dist/react/index.d.cts +567 -0
  55. package/dist/react/index.d.ts +567 -0
  56. package/dist/react/index.js +92 -0
  57. package/dist/react/index.js.map +1 -0
  58. package/dist/server-CoPDzSUP.d.cts +117 -0
  59. package/dist/{auth/server.d.ts → server-Suq3tZZC.d.ts} +8 -6
  60. package/dist/storage/index.cjs +213 -0
  61. package/dist/storage/index.cjs.map +1 -0
  62. package/dist/storage/index.d.cts +195 -0
  63. package/dist/storage/index.d.ts +195 -5
  64. package/dist/storage/index.js +209 -2
  65. package/dist/storage/index.js.map +1 -1
  66. package/package.json +124 -16
  67. package/dist/auth/client.d.ts.map +0 -1
  68. package/dist/auth/client.js.map +0 -1
  69. package/dist/auth/index.d.ts.map +0 -1
  70. package/dist/auth/server.d.ts.map +0 -1
  71. package/dist/auth/server.js +0 -148
  72. package/dist/auth/server.js.map +0 -1
  73. package/dist/client/index.d.ts.map +0 -1
  74. package/dist/config.d.ts +0 -40
  75. package/dist/config.d.ts.map +0 -1
  76. package/dist/config.js +0 -27
  77. package/dist/config.js.map +0 -1
  78. package/dist/errors.d.ts +0 -31
  79. package/dist/errors.d.ts.map +0 -1
  80. package/dist/errors.js +0 -30
  81. package/dist/errors.js.map +0 -1
  82. package/dist/events/client.d.ts.map +0 -1
  83. package/dist/events/client.js +0 -97
  84. package/dist/events/client.js.map +0 -1
  85. package/dist/events/index.d.ts.map +0 -1
  86. package/dist/events/server.d.ts.map +0 -1
  87. package/dist/events/server.js +0 -65
  88. package/dist/events/server.js.map +0 -1
  89. package/dist/http.d.ts +0 -39
  90. package/dist/http.d.ts.map +0 -1
  91. package/dist/http.js +0 -74
  92. package/dist/http.js.map +0 -1
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/notifications/index.d.ts.map +0 -1
  95. package/dist/notifications/server.d.ts.map +0 -1
  96. package/dist/notifications/server.js +0 -73
  97. package/dist/notifications/server.js.map +0 -1
  98. package/dist/storage/client.d.ts +0 -91
  99. package/dist/storage/client.d.ts.map +0 -1
  100. package/dist/storage/client.js +0 -117
  101. package/dist/storage/client.js.map +0 -1
  102. package/dist/storage/index.d.ts.map +0 -1
  103. package/dist/storage/server.d.ts +0 -104
  104. package/dist/storage/server.d.ts.map +0 -1
  105. package/dist/storage/server.js +0 -104
  106. package/dist/storage/server.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAClE,OAAO,EAAyB,aAAa,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAEnD,cAAc,QAAQ,CAAC;AAGvB,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAE1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,UAAU;IACG,SAAS,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AAC,YAAY,EAAE,CAAC;IAChC,CAAC;IAED;;;;;OAKG;IACH,UAAU,CAAC,YAAoB;QAC7B,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;IAC1C,CAAC;CACF;AAED,OAAO,EAAE,UAAU,EAAE,CAAC;AACtB,eAAe,UAAU,CAAC"}
1
+ {"version":3,"sources":["../src/auth/client.ts","../src/errors.ts","../src/auth/server.ts","../src/billing/shared.ts","../src/billing/client.ts","../src/billing/server.ts","../src/config.ts","../src/events/client.ts","../src/events/server.ts","../src/http.ts","../src/notifications/server.ts","../src/storage/client.ts","../src/storage/server.ts","../src/index.ts"],"names":["forwardedHost","forwardedProto"],"mappings":";AA0CO,IAAM,sBAAN,MAA0B;AAAA,EACd,SAAA;AAAA,EAEjB,YAAY,SAAA,EAA0B;AACpC,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,aAAa,IAAA,EAAgC;AAC3C,IAAA,MAAM,MAAM,IAAI,GAAA,CAAI,UAAA,EAAY,IAAA,CAAK,UAAU,QAAQ,CAAA;AAEvD,IAAA,IAAI,KAAK,OAAA,EAAS;AAChB,MAAA,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,KAAA,EAAO,IAAA,CAAK,OAAO,CAAA;AAAA,IAC1C;AAEA,IAAA,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,cAAA,EAAgB,IAAA,CAAK,WAAW,CAAA;AACrD,IAAA,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,WAAA,EAAa,IAAA,CAAK,UAAU,GAAG,CAAA;AAEpD,IAAA,IAAI,KAAK,GAAA,EAAK;AACZ,MAAA,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,KAAA,EAAO,IAAA,CAAK,GAAG,CAAA;AAAA,IACtC;AAEA,IAAA,OAAO,IAAI,QAAA,EAAS;AAAA,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EAGA,IAAI,aAAA,GAA8C;AAChD,IAAA,IAAA,CAAK,cAAA,KAAmB,IAAI,4BAAA,CAA6B,IAAA,CAAK,SAAS,CAAA;AACvE,IAAA,OAAO,IAAA,CAAK,cAAA;AAAA,EACd;AAAA;AAAA,EAGA,YAAA,GAAqB;AACnB,IAAA,IAAA,CAAK,UAAU,YAAA,EAAa;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,WAAW,YAAA,EAA4B;AACrC,IAAA,IAAA,CAAK,SAAA,CAAU,WAAW,YAAY,CAAA;AAAA,EACxC;AACF;AAGA,IAAO,WAAA,GAAQ","file":"index.js","sourcesContent":["import type { HttpTransport } from \"../http\";\n\n/** Options for generating a sign-in URL. */\nexport interface SignInUrlOptions {\n /** App slug to scope the login to a specific creator app. */\n appSlug?: string;\n /** Environment to authenticate against. */\n env?: \"dev\" | \"prod\";\n /** URL to redirect the user to after authentication completes. */\n redirectUri: string;\n}\n\n/** Options for generating a sign-up URL. */\nexport interface SignUpUrlOptions {\n /** App slug to scope the registration to a specific creator app. */\n appSlug?: string;\n /** Environment to authenticate against. */\n env?: \"dev\" | \"prod\";\n /** URL to redirect the user to after registration completes. */\n redirectUri: string;\n}\n\n/**\n * Client-side authentication methods for generating login URLs.\n *\n * Access via `buildspace.auth` on the client SDK, or `buildspace.authClient`\n * on the server SDK when you need to generate URLs from server-side code.\n *\n * @example\n * ```ts\n * import { createClient } from \"@buildspacestudio/sdk/client\";\n *\n * const buildspace = createClient(process.env.NEXT_PUBLIC_BUILDSPACE_KEY!);\n *\n * const signInUrl = buildspace.auth.getSignInUrl({\n * redirectUri: \"https://yourapp.com/auth/callback\",\n * });\n *\n * // Use in a link or redirect\n * window.location.href = signInUrl;\n * ```\n */\nexport class AuthClientNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Build a URL that redirects the user to the Buildspace sign-in page.\n *\n * After the user authenticates, they are redirected back to `redirectUri`\n * with a `?code=` parameter that can be exchanged for tokens via\n * `buildspace.auth.handleCallback()` on the server.\n *\n * @param opts - Sign-in URL options.\n * @returns The full sign-in URL as a string.\n */\n getSignInUrl(opts: SignInUrlOptions): string {\n const url = new URL(\"/sign-in\", this.transport.loginUrl);\n\n if (opts.appSlug) {\n url.searchParams.set(\"app\", opts.appSlug);\n }\n\n url.searchParams.set(\"redirect_uri\", opts.redirectUri);\n url.searchParams.set(\"client_id\", this.transport.key);\n\n if (opts.env) {\n url.searchParams.set(\"env\", opts.env);\n }\n\n return url.toString();\n }\n\n /**\n * Build a URL that redirects the user to the Buildspace sign-up page.\n *\n * Works identically to {@link getSignInUrl} but directs the user to the\n * registration flow instead.\n *\n * @param opts - Sign-up URL options.\n * @returns The full sign-up URL as a string.\n */\n getSignUpUrl(opts: SignUpUrlOptions): string {\n const url = new URL(\"/sign-up\", this.transport.loginUrl);\n\n if (opts.appSlug) {\n url.searchParams.set(\"app\", opts.appSlug);\n }\n\n url.searchParams.set(\"redirect_uri\", opts.redirectUri);\n url.searchParams.set(\"client_id\", this.transport.key);\n\n if (opts.env) {\n url.searchParams.set(\"env\", opts.env);\n }\n\n return url.toString();\n }\n}\n","/** Services available in the Buildspace platform. */\nexport type BuildspaceService = \"auth\" | \"billing\" | \"events\" | \"notifications\" | \"storage\";\n\n/**\n * Error thrown by all Buildspace SDK methods on failure.\n *\n * @example\n * ```ts\n * try {\n * await buildspace.auth.getSession(token);\n * } catch (err) {\n * if (err instanceof BuildspaceError) {\n * console.error(err.service, err.code, err.status, err.message);\n * }\n * }\n * ```\n */\nexport class BuildspaceError extends Error {\n /** Machine-readable error code, e.g. `\"auth/invalid-token\"`. */\n readonly code: string;\n /** Which service produced the error. */\n readonly service: BuildspaceService;\n /** HTTP status code from the API. */\n readonly status: number;\n\n constructor({\n code,\n message,\n service,\n status,\n }: {\n code: string;\n message: string;\n service: BuildspaceService;\n status: number;\n }) {\n super(message);\n this.name = \"BuildspaceError\";\n this.code = code;\n this.service = service;\n this.status = status;\n }\n}\n","import { BuildspaceError } from \"../errors\";\nimport type { HttpTransport } from \"../http\";\n\n/** A Buildspace user returned from auth endpoints. */\nexport interface AuthUser {\n /** The user's email address. */\n email: string;\n /** Unique user identifier. */\n id: string;\n /** The user's display name, or `null` if not set. */\n name: string | null;\n}\n\n/**\n * An active session for an authenticated user.\n *\n * Returned by {@link AuthServerNamespace.getSession}.\n */\nexport interface AuthSession {\n /** The app this session belongs to, or `null` for platform-level sessions. */\n appId: string | null;\n /** The authenticated user. */\n user: AuthUser;\n}\n\n/**\n * Token response returned after a successful OAuth callback exchange.\n *\n * Returned by {@link AuthServerNamespace.handleCallback}.\n */\nexport interface TokenResponse {\n /** The access token to use for authenticated requests. */\n access_token: string;\n /** Token lifetime in seconds. */\n expires_in: number;\n /** Always `\"bearer\"`. */\n token_type: \"bearer\";\n /** The authenticated user. */\n user: AuthUser;\n}\n\nconst LOOPBACK_HOSTS = new Set([\"127.0.0.1\", \"localhost\", \"::1\", \"0.0.0.0\"]);\nconst FORWARDED_HOST_RE = /host=\"?([^;\"]+)\"?/i;\nconst FORWARDED_PROTO_RE = /proto=\"?([^;\"]+)\"?/i;\n\nfunction getFirstForwardedValue(value: string | null): string | null {\n if (!value) {\n return null;\n }\n\n return (\n value\n .split(\",\")\n .map((part) => part.trim())\n .find(Boolean) ?? null\n );\n}\n\nfunction stripPort(host: string): string {\n if (host.startsWith(\"[\") && host.includes(\"]\")) {\n return host.slice(1, host.indexOf(\"]\"));\n }\n\n const colonIndex = host.indexOf(\":\");\n return colonIndex >= 0 ? host.slice(0, colonIndex) : host;\n}\n\nfunction isPrivateIpv4(hostname: string): boolean {\n const parts = hostname.split(\".\").map((part) => Number(part));\n if (parts.length !== 4 || parts.some((part) => Number.isNaN(part) || part < 0 || part > 255)) {\n return false;\n }\n\n return (\n parts[0] === 10 ||\n (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||\n (parts[0] === 192 && parts[1] === 168)\n );\n}\n\nfunction isInternalHostname(hostname: string): boolean {\n const normalized = hostname.toLowerCase();\n\n return (\n LOOPBACK_HOSTS.has(normalized) ||\n normalized.endsWith(\".local\") ||\n normalized.endsWith(\".internal\") ||\n isPrivateIpv4(normalized)\n );\n}\n\nfunction getForwardedOrigin(request: Request): string | null {\n const forwarded = getFirstForwardedValue(request.headers.get(\"forwarded\"));\n if (forwarded) {\n const forwardedHost = forwarded.match(FORWARDED_HOST_RE)?.[1]?.trim();\n const forwardedProto = forwarded.match(FORWARDED_PROTO_RE)?.[1]?.trim();\n\n if (forwardedHost && forwardedProto) {\n return `${forwardedProto}://${forwardedHost}`;\n }\n }\n\n const forwardedHost = getFirstForwardedValue(request.headers.get(\"x-forwarded-host\"));\n const forwardedProto = getFirstForwardedValue(request.headers.get(\"x-forwarded-proto\"));\n\n if (forwardedHost && forwardedProto) {\n return `${forwardedProto}://${forwardedHost}`;\n }\n\n return null;\n}\n\nfunction resolveDefaultRedirectUri(request: Request | URL | string, url: URL): string {\n if (!(request instanceof Request)) {\n return `${url.origin}${url.pathname}`;\n }\n\n const forwardedOrigin = getForwardedOrigin(request);\n if (forwardedOrigin) {\n return `${forwardedOrigin}${url.pathname}`;\n }\n\n const hostHeader = request.headers.get(\"host\")?.trim();\n if (hostHeader && !isInternalHostname(stripPort(hostHeader))) {\n return `${url.protocol}//${hostHeader}${url.pathname}`;\n }\n\n if (!isInternalHostname(url.hostname)) {\n return `${url.origin}${url.pathname}`;\n }\n\n return `${url.origin}${url.pathname}`;\n}\n\n/**\n * Server-side authentication methods.\n *\n * Access via `buildspace.auth` on the server SDK.\n *\n * @example\n * ```ts\n * import Buildspace from \"@buildspacestudio/sdk\";\n *\n * const buildspace = new Buildspace(process.env.BUILDSPACE_SECRET_KEY!);\n *\n * // Handle OAuth callback\n * const tokens = await buildspace.auth.handleCallback(request);\n *\n * // Verify a session\n * const session = await buildspace.auth.getSession(sessionToken);\n *\n * // Sign out\n * await buildspace.auth.signOut(sessionToken);\n * ```\n */\nexport class AuthServerNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Retrieve the session associated with a token.\n *\n * Returns the {@link AuthSession} if valid, or `null` if the token is\n * expired, revoked, or invalid (401/404).\n *\n * @throws {BuildspaceError} On unexpected server errors (5xx, network issues).\n */\n async getSession(sessionToken: string): Promise<AuthSession | null> {\n try {\n return await this.transport.request<AuthSession>({\n service: \"auth\",\n path: \"/v1/auth/session\",\n headers: { \"X-Session-Token\": sessionToken },\n });\n } catch (error) {\n if (error instanceof BuildspaceError && (error.status === 401 || error.status === 404)) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Exchange an OAuth authorization code for tokens.\n *\n * Extracts the `code` query parameter from the callback URL and exchanges\n * it with the Buildspace API for an access token and user info.\n *\n * @param request - The incoming callback request. Accepts a `Request` object,\n * a `URL`, or a raw URL string containing the `?code=` parameter.\n * @param opts - Optional settings.\n * @param opts.redirectUri - Override the redirect URI sent to the token endpoint.\n * Defaults to the origin + pathname of the callback URL.\n * @returns The token response containing `access_token`, `expires_in`, and `user`.\n *\n * @throws {BuildspaceError} If the code exchange fails (invalid code, expired, etc.).\n *\n * @example\n * ```ts\n * // Next.js Route Handler\n * export async function GET(request: Request) {\n * const { access_token, user } = await buildspace.auth.handleCallback(request);\n * // Store access_token as a session cookie\n * }\n * ```\n */\n handleCallback(\n request: Request | URL | string,\n opts?: { redirectUri?: string }\n ): Promise<TokenResponse> {\n let url: URL;\n if (typeof request === \"string\") {\n url = new URL(request);\n } else if (request instanceof URL) {\n url = request;\n } else {\n url = new URL(request.url);\n }\n\n const code = url.searchParams.get(\"code\");\n if (!code) {\n throw new BuildspaceError({\n service: \"auth\",\n status: 400,\n code: \"auth/missing-code\",\n message: \"No auth code found in callback URL. Expected ?code= parameter.\",\n });\n }\n\n const redirectUri = opts?.redirectUri ?? resolveDefaultRedirectUri(request, url);\n\n return this.transport.request<TokenResponse>({\n service: \"auth\",\n path: \"/v1/auth/token\",\n method: \"POST\",\n body: {\n code,\n redirect_uri: redirectUri,\n },\n });\n }\n\n /**\n * Revoke a specific session token.\n *\n * @param sessionToken - The token to revoke.\n * @throws {BuildspaceError} If the revocation fails.\n */\n async revokeSession(sessionToken: string): Promise<void> {\n await this.transport.request<void>({\n service: \"auth\",\n path: \"/v1/auth/session\",\n method: \"DELETE\",\n headers: { \"X-Session-Token\": sessionToken },\n });\n }\n\n /**\n * Sign the user out by revoking the session and clearing the SDK's stored token.\n *\n * If the session is already expired or not found, the error is silently\n * ignored and the local session is still cleared.\n *\n * @param sessionToken - Token to revoke. If omitted, uses the token\n * previously set via `buildspace.setSession()`.\n */\n async signOut(sessionToken?: string): Promise<void> {\n const token = sessionToken ?? this.transport.getSessionToken();\n\n try {\n if (token) {\n await this.revokeSession(token);\n }\n } catch (error) {\n if (\n !(\n error instanceof BuildspaceError &&\n error.service === \"auth\" &&\n (error.status === 401 || error.status === 404)\n )\n ) {\n throw error;\n }\n } finally {\n this.transport.clearSession();\n }\n }\n}\n","export interface BillingProduct {\n active: boolean;\n createdAt: string;\n description: string | null;\n id: string;\n name: string;\n}\n\nexport interface BillingPrice {\n active: boolean;\n amountCents: number | null;\n createdAt: string;\n currency: string;\n id: string;\n interval: string | null;\n lookupKey: string | null;\n productId: string;\n productName: string;\n type: \"one_time\" | \"recurring\" | \"metered\";\n}\n\nexport interface CreateServerCheckoutOptions {\n appUserId?: string;\n cancelUrl: string;\n checkoutRequestId?: string;\n lookupKey?: string;\n metadata?: Record<string, string>;\n priceId?: string;\n quantity?: number;\n successUrl: string;\n userId?: string;\n}\n\nexport interface CreateClientCheckoutOptions {\n cancelUrl: string;\n checkoutRequestId?: string;\n lookupKey?: string;\n metadata?: Record<string, string>;\n priceId?: string;\n quantity?: number;\n successUrl: string;\n}\n\nexport interface BillingCheckoutResponse {\n id?: string;\n stripe_checkout_session_id: string;\n url: string;\n}\n\nexport interface BillingPortalResponse {\n url: string;\n}\n\nexport interface BillingSubscriptionResponse {\n subscription: {\n cancelAtPeriodEnd: boolean;\n currentPeriodEnd: string | null;\n id: string;\n status: string;\n } | null;\n}\n\nexport interface BillingEntitlementsResponse {\n active: boolean;\n subscription: { currentPeriodEnd: string | null; id: string; status: string } | null;\n}\n\nexport type BillingMode = \"test\" | \"live\";\n\nexport type BillingConfigStatus = \"disabled\" | \"setup_required\" | \"active\" | \"paused\";\n\nexport interface BillingStatusResponse {\n enabled: boolean;\n mode: BillingMode | null;\n status: BillingConfigStatus | null;\n testMode: boolean;\n}\n\n/**\n * True when the app environment is wired to a Stripe test-mode account.\n *\n * Use this to render a \"Test mode\" banner in your app — payments aren't real\n * charges, and end-buyers should not be expected to enter real card details.\n */\nexport function shouldShowTestBanner(status: BillingStatusResponse): boolean {\n return status.testMode;\n}\n\nexport interface CreateServerPortalSessionOptions {\n appUserId?: string;\n returnUrl: string;\n userId?: string;\n}\n\nexport interface CreateClientPortalSessionOptions {\n returnUrl: string;\n}\n\nexport function billingIdentityQuery(opts?: { appUserId?: string; userId?: string }) {\n return { app_user_id: opts?.appUserId, user_id: opts?.userId };\n}\n\nexport function checkoutRequestBody(\n opts: CreateServerCheckoutOptions | CreateClientCheckoutOptions\n) {\n return {\n app_user_id: \"appUserId\" in opts ? opts.appUserId : undefined,\n cancel_url: opts.cancelUrl,\n checkout_request_id: opts.checkoutRequestId,\n lookup_key: opts.lookupKey,\n metadata: opts.metadata,\n price_id: opts.priceId,\n quantity: opts.quantity,\n success_url: opts.successUrl,\n user_id: \"userId\" in opts ? opts.userId : undefined,\n };\n}\n\nexport function portalRequestBody(\n opts: CreateServerPortalSessionOptions | CreateClientPortalSessionOptions\n) {\n return {\n app_user_id: \"appUserId\" in opts ? opts.appUserId : undefined,\n return_url: opts.returnUrl,\n user_id: \"userId\" in opts ? opts.userId : undefined,\n };\n}\n","import type { HttpTransport } from \"../http\";\nimport {\n type BillingEntitlementsResponse,\n type BillingPortalResponse,\n type BillingPrice,\n type BillingProduct,\n type BillingStatusResponse,\n type BillingSubscriptionResponse,\n type CreateClientCheckoutOptions,\n type CreateClientPortalSessionOptions,\n checkoutRequestBody,\n portalRequestBody,\n} from \"./shared\";\n\nfunction redirectTo(url: string): void {\n const browser = globalThis as typeof globalThis & {\n window?: { location: { href: string } };\n };\n if (!browser.window?.location) {\n throw new Error(\"redirectToCheckout can only be used in a browser environment\");\n }\n browser.window.location.href = url;\n}\n\nexport class BillingClientNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Read whether billing is enabled for the app environment tied to this\n * publishable key, and whether the connected Stripe account is in test or\n * live mode.\n *\n * Render a \"Test mode\" banner in your app whenever `testMode` is true.\n */\n getStatus(): Promise<BillingStatusResponse> {\n return this.transport.request<BillingStatusResponse>({\n service: \"billing\",\n path: \"/v1/billing/status\",\n });\n }\n\n /**\n * List the active billing products for the app environment tied to this\n * publishable key.\n */\n listProducts(): Promise<{ products: BillingProduct[] }> {\n return this.transport.request<{ products: BillingProduct[] }>({\n service: \"billing\",\n path: \"/v1/billing/products\",\n });\n }\n\n /**\n * List the active billing prices for the app environment tied to this\n * publishable key.\n */\n listPrices(): Promise<{ prices: BillingPrice[] }> {\n return this.transport.request<{ prices: BillingPrice[] }>({\n service: \"billing\",\n path: \"/v1/billing/prices\",\n });\n }\n\n /**\n * Create a Checkout Session for the signed-in browser user and redirect to\n * the Stripe-hosted Checkout page.\n *\n * This method depends on a Buildspace session being available through\n * `setSession()` or your app's authenticated request context.\n */\n async redirectToCheckout(opts: CreateClientCheckoutOptions): Promise<void> {\n const checkout = await this.transport.request<{ url: string }>({\n service: \"billing\",\n path: \"/v1/billing/checkout\",\n method: \"POST\",\n body: checkoutRequestBody(opts),\n });\n redirectTo(checkout.url);\n }\n\n /**\n * Open the Stripe-hosted customer portal for the signed-in browser user.\n */\n async redirectToPortal(opts: CreateClientPortalSessionOptions): Promise<void> {\n const portal = await this.transport.request<BillingPortalResponse>({\n service: \"billing\",\n path: \"/v1/billing/portal\",\n method: \"POST\",\n body: portalRequestBody(opts),\n });\n redirectTo(portal.url);\n }\n\n /**\n * Discoverable alias for redirectToPortal — opens the Stripe-hosted customer\n * portal so the signed-in user can manage their subscription, payment method,\n * and invoices.\n */\n manageSubscription(opts: CreateClientPortalSessionOptions): Promise<void> {\n return this.redirectToPortal(opts);\n }\n\n /**\n * Read the current subscription state for the signed-in browser user.\n */\n getSubscription(): Promise<BillingSubscriptionResponse> {\n return this.transport.request<BillingSubscriptionResponse>({\n service: \"billing\",\n path: \"/v1/billing/subscription\",\n });\n }\n\n /**\n * Read the current paid entitlement state for the signed-in browser user.\n */\n getEntitlements(): Promise<BillingEntitlementsResponse> {\n return this.transport.request<BillingEntitlementsResponse>({\n service: \"billing\",\n path: \"/v1/billing/entitlements\",\n });\n }\n}\n","import type { HttpTransport } from \"../http\";\nimport {\n type BillingCheckoutResponse,\n type BillingEntitlementsResponse,\n type BillingPortalResponse,\n type BillingPrice,\n type BillingProduct,\n type BillingStatusResponse,\n type BillingSubscriptionResponse,\n billingIdentityQuery,\n type CreateServerCheckoutOptions,\n type CreateServerPortalSessionOptions,\n checkoutRequestBody,\n portalRequestBody,\n} from \"./shared\";\n\nexport type {\n BillingCheckoutResponse,\n BillingEntitlementsResponse,\n BillingPortalResponse,\n BillingPrice,\n BillingProduct,\n BillingStatusResponse,\n BillingSubscriptionResponse,\n CreateServerCheckoutOptions,\n CreateServerPortalSessionOptions,\n} from \"./shared\";\nexport { shouldShowTestBanner } from \"./shared\";\n\nexport class BillingServerNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Read whether billing is enabled for the app environment tied to this API\n * key, and whether the connected Stripe account is in test or live mode.\n *\n * Render a \"Test mode\" banner in your app whenever `testMode` is true.\n */\n getStatus(): Promise<BillingStatusResponse> {\n return this.transport.request<BillingStatusResponse>({\n service: \"billing\",\n path: \"/v1/billing/status\",\n });\n }\n\n /**\n * List the active billing products configured for the app environment tied to\n * this API key.\n */\n listProducts(): Promise<{ products: BillingProduct[] }> {\n return this.transport.request<{ products: BillingProduct[] }>({\n service: \"billing\",\n path: \"/v1/billing/products\",\n });\n }\n\n /**\n * List the active billing prices configured for the app environment tied to\n * this API key.\n */\n listPrices(): Promise<{ prices: BillingPrice[] }> {\n return this.transport.request<{ prices: BillingPrice[] }>({\n service: \"billing\",\n path: \"/v1/billing/prices\",\n });\n }\n\n /**\n * Create a Stripe Checkout Session on the creator's connected Stripe account.\n *\n * Use `userId` for Buildspace-authenticated users, or `appUserId` when your\n * app uses its own auth system and you want Buildspace to track billing state\n * against an app-defined user id.\n */\n createCheckout(opts: CreateServerCheckoutOptions): Promise<BillingCheckoutResponse> {\n return this.transport.request<BillingCheckoutResponse>({\n service: \"billing\",\n path: \"/v1/billing/checkout\",\n method: \"POST\",\n body: checkoutRequestBody(opts),\n });\n }\n\n /**\n * Create a Stripe-hosted customer portal session for the specified billing\n * identity.\n */\n createPortalSession(opts: CreateServerPortalSessionOptions): Promise<BillingPortalResponse> {\n return this.transport.request<BillingPortalResponse>({\n service: \"billing\",\n path: \"/v1/billing/portal\",\n method: \"POST\",\n body: portalRequestBody(opts),\n });\n }\n\n /**\n * Read the current subscription state for a Buildspace user or app-defined\n * billing identity.\n */\n getSubscription(opts?: {\n appUserId?: string;\n userId?: string;\n }): Promise<BillingSubscriptionResponse> {\n return this.transport.request<BillingSubscriptionResponse>({\n service: \"billing\",\n path: \"/v1/billing/subscription\",\n query: billingIdentityQuery(opts),\n });\n }\n\n /**\n * Read the current paid entitlement state for a Buildspace user or app-defined\n * billing identity.\n */\n getEntitlements(opts?: {\n appUserId?: string;\n userId?: string;\n }): Promise<BillingEntitlementsResponse> {\n return this.transport.request<BillingEntitlementsResponse>({\n service: \"billing\",\n path: \"/v1/billing/entitlements\",\n query: billingIdentityQuery(opts),\n });\n }\n}\n","export const DEFAULT_BASE_URL = \"https://api.buildspace.studio\";\nexport const DEFAULT_LOGIN_URL = \"https://login.buildspace.studio\";\nexport const DEFAULT_API_VERSION = \"2025-06-01\";\n\nexport type ClientMode = \"server\" | \"client\";\n\n/** Configuration options for the server SDK (`new Buildspace()`). */\nexport interface BuildspaceConfig {\n /** Base URL of the Buildspace API. Defaults to `\"https://api.buildspace.studio\"`. */\n baseUrl?: string;\n /** Custom `fetch` implementation (useful for testing or edge runtimes). */\n fetch?: typeof fetch;\n /** Base URL of the Buildspace login service. Defaults to `\"https://login.buildspace.studio\"`. */\n loginUrl?: string;\n /** API version string sent via the `X-Buildspace-Version` header. Defaults to `\"2025-06-01\"`. */\n version?: string;\n}\n\n/** Configuration for client-side event batching behavior. */\nexport interface EventsBatchingConfig {\n /** How often queued events are flushed to the API, in milliseconds. Defaults to `5000`. */\n flushInterval?: number;\n /** Maximum number of events to queue before an automatic flush. Defaults to `20`. */\n maxBatchSize?: number;\n}\n\n/** Configuration options for the client SDK (`createClient()`). */\nexport interface BuildspaceClientConfig extends BuildspaceConfig {\n /** Options for client-side event batching. */\n events?: EventsBatchingConfig;\n}\n\nexport interface ResolvedConfig {\n baseUrl: string;\n fetch: typeof fetch;\n loginUrl: string;\n mode: ClientMode;\n version: string;\n}\n\nexport function resolveConfig(mode: ClientMode, config: BuildspaceConfig = {}): ResolvedConfig {\n return {\n mode,\n baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,\n loginUrl: config.loginUrl ?? DEFAULT_LOGIN_URL,\n version: config.version ?? DEFAULT_API_VERSION,\n fetch: config.fetch ?? fetch,\n };\n}\n\nfunction formatMode(mode: ClientMode): string {\n return mode === \"server\" ? \"server SDK\" : \"client SDK\";\n}\n\nexport function validateApiKey({ mode, key }: { key: string; mode: ClientMode }): void {\n if (!key) {\n throw new Error(`Missing API key. The ${formatMode(mode)} requires a valid Buildspace key.`);\n }\n\n if (mode === \"server\" && !key.startsWith(\"bs_sec_\")) {\n throw new Error(\n \"The server SDK requires a secret key (bs_sec_*). Use createClient() from '@buildspacestudio/sdk/client' for browser usage with publishable keys.\"\n );\n }\n\n if (mode === \"client\" && !key.startsWith(\"bs_pub_\")) {\n throw new Error(\n \"The client SDK requires a publishable key (bs_pub_*). Use new Buildspace() from '@buildspacestudio/sdk' for server usage with secret keys.\"\n );\n }\n}\n","import type { HttpTransport } from \"../http\";\n\ninterface QueuedEvent {\n actor_id?: string;\n event: string;\n properties?: Record<string, unknown>;\n timestamp: string;\n}\n\n/**\n * Client-side event tracking with automatic batching.\n *\n * Events are queued in memory and flushed to the API in batches,\n * either on a timer or when the batch size limit is reached.\n *\n * Access via `buildspace.events` on the client SDK.\n *\n * @example\n * ```ts\n * // Fire and forget — events are queued automatically\n * buildspace.events.track(\"button.clicked\", { label: \"upgrade\" });\n *\n * // Flush before page unload\n * await buildspace.events.flush();\n *\n * // Graceful shutdown (clears timer, flushes remaining)\n * await buildspace.events.shutdown();\n * ```\n */\nexport class EventsClientNamespace {\n private readonly queue: QueuedEvent[] = [];\n private readonly transport: HttpTransport;\n private timer: ReturnType<typeof setInterval> | null = null;\n\n constructor(\n transport: HttpTransport,\n config: { flushInterval?: number; maxBatchSize?: number } = {}\n ) {\n this.transport = transport;\n const flushInterval = config.flushInterval ?? 5000;\n this.maxBatchSize = config.maxBatchSize ?? 20;\n this.timer = setInterval(() => {\n this.flush().catch(() => {\n // best effort flush for background timer\n });\n }, flushInterval);\n }\n\n private readonly maxBatchSize: number;\n\n /**\n * Queue an event for batched delivery.\n *\n * This method is synchronous and returns immediately. Events are\n * automatically flushed when the batch size is reached or on the\n * configured interval.\n *\n * @param event - Event name, e.g. `\"button.clicked\"`.\n * @param properties - Arbitrary key-value data to attach.\n * @param actorId - Identifier of the user or entity that triggered the event.\n */\n track(event: string, properties?: Record<string, unknown>, actorId?: string): void {\n this.queue.push({\n event,\n properties,\n actor_id: actorId,\n timestamp: new Date().toISOString(),\n });\n\n if (this.queue.length >= this.maxBatchSize) {\n this.flush().catch(() => {\n // best effort flush on max batch size\n });\n }\n }\n\n /**\n * Send all queued events to the API immediately.\n *\n * If the flush fails, events are re-queued for the next attempt.\n */\n async flush(): Promise<void> {\n if (this.queue.length === 0) {\n return;\n }\n\n const batch = this.queue.splice(0, this.queue.length);\n\n try {\n await this.transport.request<void>({\n service: \"events\",\n path: \"/v1/events/batch\",\n method: \"POST\",\n keepalive: true,\n body: { events: batch },\n });\n } catch {\n this.queue.unshift(...batch);\n throw new Error(\"Failed to flush events batch.\");\n }\n }\n\n /**\n * Stop the automatic flush timer and send any remaining events.\n *\n * Call this during app shutdown or cleanup to ensure no events are lost.\n */\n async shutdown(): Promise<void> {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n\n await this.flush();\n }\n}\n","import type { HttpTransport } from \"../http\";\n\n/** An event to include in a batch tracking call. */\nexport interface ServerTrackedEvent {\n /** Identifier of the user or entity that triggered the event. */\n actor_id?: string;\n /** Event name, e.g. `\"user.signed_up\"` or `\"page.viewed\"`. */\n event: string;\n /** Arbitrary key-value data attached to the event. */\n properties?: Record<string, unknown>;\n /** ISO 8601 timestamp. Auto-filled with `new Date().toISOString()` if omitted. */\n timestamp?: string;\n}\n\n/**\n * Server-side event tracking methods.\n *\n * Access via `buildspace.events` on the server SDK.\n *\n * @example\n * ```ts\n * // Track a single event\n * await buildspace.events.track(\"user.signed_up\", { plan: \"pro\" }, userId);\n *\n * // Batch track multiple events\n * await buildspace.events.batchTrack([\n * { event: \"page.viewed\", properties: { path: \"/home\" }, actor_id: userId },\n * ]);\n * ```\n */\nexport class EventsServerNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Track a single event.\n *\n * @param event - Event name, e.g. `\"user.signed_up\"`.\n * @param properties - Arbitrary key-value data to attach to the event.\n * @param actorId - Identifier of the user or entity that triggered the event.\n * @returns The ID of the created event.\n */\n track(\n event: string,\n properties?: Record<string, unknown>,\n actorId?: string\n ): Promise<{ event_id: string }> {\n return this.transport.request<{ event_id: string }>({\n service: \"events\",\n path: \"/v1/events\",\n method: \"POST\",\n body: {\n event,\n properties,\n actor_id: actorId,\n timestamp: new Date().toISOString(),\n },\n });\n }\n\n /**\n * Track multiple events in a single request.\n *\n * Events without a `timestamp` are automatically timestamped.\n *\n * @param events - Array of events to track.\n * @returns The count and IDs of created events.\n */\n batchTrack(events: ServerTrackedEvent[]): Promise<{ count: number; event_ids: string[] }> {\n return this.transport.request<{ count: number; event_ids: string[] }>({\n service: \"events\",\n path: \"/v1/events/batch\",\n method: \"POST\",\n body: {\n events: events.map((event) => ({\n ...event,\n timestamp: event.timestamp ?? new Date().toISOString(),\n })),\n },\n });\n }\n}\n","import { type ClientMode, type ResolvedConfig, validateApiKey } from \"./config\";\nimport { BuildspaceError, type BuildspaceService } from \"./errors\";\n\ninterface RequestOptions {\n body?: unknown;\n headers?: Record<string, string>;\n keepalive?: boolean;\n method?: string;\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n service: BuildspaceService;\n}\n\n/**\n * Low-level HTTP transport used internally by all SDK namespaces.\n *\n * Handles authentication headers, API versioning, session tokens,\n * and consistent error mapping to {@link BuildspaceError}.\n */\nexport class HttpTransport {\n readonly baseUrl: string;\n readonly fetcher: typeof fetch;\n readonly key: string;\n readonly loginUrl: string;\n readonly mode: ClientMode;\n readonly version: string;\n private sessionToken: string | null = null;\n\n constructor({ key, resolvedConfig }: { key: string; resolvedConfig: ResolvedConfig }) {\n validateApiKey({ mode: resolvedConfig.mode, key });\n this.key = key;\n this.mode = resolvedConfig.mode;\n this.baseUrl = resolvedConfig.baseUrl;\n this.loginUrl = resolvedConfig.loginUrl;\n this.version = resolvedConfig.version;\n this.fetcher = resolvedConfig.fetch;\n }\n\n /** Remove the stored session token. */\n clearSession(): void {\n this.sessionToken = null;\n }\n\n /** Return the current session token, or `null` if none is set. */\n getSessionToken(): string | null {\n return this.sessionToken;\n }\n\n /** Store a session token that will be sent as `X-Session-Token` on subsequent requests. */\n setSession(sessionToken: string): void {\n this.sessionToken = sessionToken;\n }\n\n async request<T>({\n service,\n path,\n method = \"GET\",\n query,\n body,\n headers,\n keepalive,\n }: RequestOptions): Promise<T> {\n const url = new URL(path, this.baseUrl);\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n const response = await this.fetcher(url.toString(), {\n method,\n keepalive,\n headers: {\n Authorization: `Bearer ${this.key}`,\n \"Content-Type\": \"application/json\",\n \"X-Buildspace-Version\": this.version,\n ...(this.sessionToken ? { \"X-Session-Token\": this.sessionToken } : {}),\n ...headers,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n if (!response.ok) {\n const payload = (await response.json().catch(() => null)) as {\n code?: string;\n error?: string;\n message?: string;\n } | null;\n\n throw new BuildspaceError({\n service,\n status: response.status,\n code: payload?.code ?? `${service}/http-${response.status}`,\n message: payload?.error ?? payload?.message ?? response.statusText,\n });\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json() as Promise<T>;\n }\n}\n","import type { HttpTransport } from \"../http\";\n\n/** Options for sending a custom email. */\nexport interface SendOptions {\n /** HTML body of the email. */\n html: string;\n /** Arbitrary metadata to attach to the notification for tracking. */\n metadata?: Record<string, unknown>;\n /** Reply-to email address. */\n replyTo?: string;\n /** Email subject line. */\n subject: string;\n /** Plain-text fallback body. Recommended for email accessibility. */\n text?: string;\n /** Recipient email address, or an array of addresses for multiple recipients. */\n to: string | string[];\n}\n\n/** Options for sending a template-based email. */\nexport interface SendTemplateOptions {\n /** Arbitrary metadata to attach to the notification for tracking. */\n metadata?: Record<string, unknown>;\n /** Recipient email address, or an array of addresses. */\n to: string | string[];\n /** Template variable substitutions, e.g. `{ firstName: \"Alex\" }`. */\n variables?: Record<string, string>;\n}\n\n/** Result of a successfully sent notification. */\nexport interface SendResult {\n /** Buildspace notification ID. */\n id: string;\n /** Underlying email provider's message ID, if available. */\n providerMessageId?: string;\n}\n\n/**\n * Server-side notification methods for sending transactional emails.\n *\n * Access via `buildspace.notifications` on the server SDK.\n * **Not available on the client SDK** — calling `buildspace.notifications`\n * on the client throws a `BuildspaceError`.\n *\n * @example\n * ```ts\n * // Send a custom email\n * await buildspace.notifications.send({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * html: \"<h1>You're in!</h1>\",\n * });\n *\n * // Send from a saved template\n * await buildspace.notifications.sendTemplate(\"welcome-email\", {\n * to: \"user@example.com\",\n * variables: { firstName: \"Alex\" },\n * });\n * ```\n */\nexport class NotificationsServerNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Send a custom email with inline HTML content.\n *\n * @param opts - Email content and recipient options.\n * @returns The notification ID and optional provider message ID.\n */\n send(opts: SendOptions): Promise<SendResult> {\n return this.transport.request<SendResult>({\n service: \"notifications\",\n path: \"/v1/notifications/send\",\n method: \"POST\",\n body: {\n to: opts.to,\n subject: opts.subject,\n html: opts.html,\n text: opts.text,\n reply_to: opts.replyTo,\n metadata: opts.metadata,\n },\n });\n }\n\n /**\n * Send an email using a pre-configured template.\n *\n * Templates are created in the Buildspace Creator Studio.\n *\n * @param templateSlug - The slug of the template to use, e.g. `\"welcome-email\"`.\n * @param opts - Recipient and template variable options.\n * @returns The notification ID and optional provider message ID.\n */\n sendTemplate(templateSlug: string, opts: SendTemplateOptions): Promise<SendResult> {\n return this.transport.request<SendResult>({\n service: \"notifications\",\n path: \"/v1/notifications/send-template\",\n method: \"POST\",\n body: {\n template: templateSlug,\n to: opts.to,\n variables: opts.variables,\n metadata: opts.metadata,\n },\n });\n }\n}\n","import { BuildspaceError } from \"../errors\";\nimport type { HttpTransport } from \"../http\";\nimport type { StorageObject } from \"./server\";\n\n/** Options for uploading a file from the client. */\nexport interface UploadOptions {\n /** MIME type override. If omitted, inferred from the `File` object or defaults to `\"application/octet-stream\"`. */\n contentType?: string;\n /** Storage path/key for the file, e.g. `\"avatars/user-123.png\"`. */\n path: string;\n}\n\n/** Result of a successful client-side file upload. */\nexport interface UploadResponse {\n /** The resolved storage key. */\n key: string;\n /** File size in bytes. */\n size: number;\n /** Signed download URL for the uploaded file. */\n url: string;\n}\n\n/** Result of requesting a signed download URL. */\nexport interface GetUrlResponse {\n /** URL lifetime in seconds, if applicable. */\n expiresIn?: number;\n /** The storage key of the object. */\n key: string;\n /** The signed download URL. */\n url: string;\n}\n\n/**\n * Client-side storage methods for uploading and managing files.\n *\n * Access via `buildspace.storage` on the client SDK.\n *\n * @example\n * ```ts\n * // Upload a file (handles signed URL + PUT automatically)\n * const { key, url } = await buildspace.storage.upload(file, {\n * path: \"avatars/user-123.png\",\n * });\n *\n * // Get a download URL for an existing file\n * const { url } = await buildspace.storage.getUrl(key);\n * ```\n */\nexport class StorageClientNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Upload a `File` or `Blob` to Buildspace storage.\n *\n * This method handles the full upload flow:\n * 1. Requests a pre-signed upload URL from the API\n * 2. Uploads the file directly to the storage provider\n * 3. Returns a signed download URL for the uploaded file\n *\n * @param file - The file or blob to upload.\n * @param opts - Upload options including the storage path.\n * @returns The storage key, file size, and a signed download URL.\n *\n * @throws {BuildspaceError} If the upload URL request or the direct upload fails.\n */\n async upload(file: File | Blob, opts: UploadOptions): Promise<UploadResponse> {\n const contentType =\n opts.contentType ?? (file instanceof File ? file.type : \"application/octet-stream\");\n\n const signed = await this.transport.request<{ key: string; upload_url: string }>({\n service: \"storage\",\n path: \"/v1/storage/upload\",\n method: \"POST\",\n body: {\n path: opts.path,\n content_type: contentType,\n size: file.size,\n },\n });\n\n const response = await this.transport.fetcher(signed.upload_url, {\n method: \"PUT\",\n headers: { \"Content-Type\": contentType },\n body: file,\n });\n\n if (!response.ok) {\n throw new BuildspaceError({\n service: \"storage\",\n status: response.status,\n code: \"storage/upload-failed\",\n message: `Direct upload failed: ${response.statusText}`,\n });\n }\n\n const { url } = await this.getUrl(signed.key);\n\n return {\n key: signed.key,\n size: file.size,\n url,\n };\n }\n\n /**\n * Get a time-limited signed URL for downloading a stored file.\n *\n * @param key - The storage key of the object.\n * @param opts - Optional settings.\n * @param opts.expiresIn - URL lifetime in seconds.\n */\n getUrl(key: string, opts?: { expiresIn?: number }): Promise<GetUrlResponse> {\n return this.transport.request<GetUrlResponse>({\n service: \"storage\",\n path: \"/v1/storage/url\",\n query: {\n key,\n expires_in: opts?.expiresIn,\n },\n });\n }\n\n /**\n * List stored objects, optionally filtered by key prefix.\n *\n * @param prefix - Only return objects whose key starts with this prefix.\n * @param opts - Pagination options.\n */\n list(\n prefix?: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<{ objects: StorageObject[] }> {\n return this.transport.request<{ objects: StorageObject[] }>({\n service: \"storage\",\n path: \"/v1/storage/objects\",\n query: {\n prefix,\n limit: opts?.limit,\n offset: opts?.offset,\n },\n });\n }\n\n /**\n * Delete a stored object by key.\n *\n * @param key - The storage key of the object to delete.\n */\n async delete(key: string): Promise<void> {\n await this.transport.request<void>({\n service: \"storage\",\n path: \"/v1/storage/object\",\n method: \"DELETE\",\n body: { key },\n });\n }\n}\n","import type { HttpTransport } from \"../http\";\n\n/** Options for requesting a pre-signed upload URL on the server. */\nexport interface ServerUploadOptions {\n /** MIME type of the file, e.g. `\"image/png\"`. */\n contentType: string;\n /** Storage path/key for the file, e.g. `\"avatars/user-123.png\"`. */\n key: string;\n /** File size in bytes. */\n size: number;\n}\n\n/** Metadata for a stored object. */\nexport interface StorageObject {\n /** MIME type of the stored file. */\n contentType: string;\n /** ISO 8601 timestamp of when the object was created. */\n createdAt: string;\n /** Unique object identifier. */\n id: string;\n /** Storage key/path of the object. */\n key: string;\n /** File size in bytes. */\n size: number;\n /** ID of the user who uploaded the object, or `null` if uploaded via server key. */\n uploadedBy: string | null;\n}\n\n/**\n * Server-side storage methods for managing file uploads and downloads.\n *\n * Access via `buildspace.storage` on the server SDK.\n *\n * @example\n * ```ts\n * // Get a pre-signed upload URL\n * const { upload_url, key } = await buildspace.storage.getUploadUrl({\n * key: \"avatars/user-123.png\",\n * contentType: \"image/png\",\n * size: file.size,\n * });\n *\n * // Upload directly to the signed URL\n * await fetch(upload_url, { method: \"PUT\", body: file });\n *\n * // Get a signed download URL\n * const { url } = await buildspace.storage.getSignedUrl(key);\n * ```\n */\nexport class StorageServerNamespace {\n private readonly transport: HttpTransport;\n\n constructor(transport: HttpTransport) {\n this.transport = transport;\n }\n\n /**\n * Request a pre-signed URL for direct file upload.\n *\n * @param opts - Upload options including the storage key, content type, and file size.\n * @returns The signed upload URL, the resolved key, and expiry time in seconds.\n */\n getUploadUrl(\n opts: ServerUploadOptions\n ): Promise<{ expires_in: number; key: string; upload_url: string }> {\n return this.transport.request<{ expires_in: number; key: string; upload_url: string }>({\n service: \"storage\",\n path: \"/v1/storage/upload\",\n method: \"POST\",\n body: {\n path: opts.key,\n content_type: opts.contentType,\n size: opts.size,\n },\n });\n }\n\n /**\n * Get a time-limited signed URL for downloading a stored file.\n *\n * @param key - The storage key of the object.\n * @param opts - Optional settings.\n * @param opts.expiresIn - URL lifetime in seconds. Uses server default if omitted.\n */\n getSignedUrl(\n key: string,\n opts?: { expiresIn?: number }\n ): Promise<{ expiresIn?: number; key: string; url: string }> {\n return this.transport.request<{ expiresIn?: number; key: string; url: string }>({\n service: \"storage\",\n path: \"/v1/storage/url\",\n query: {\n key,\n expires_in: opts?.expiresIn,\n },\n });\n }\n\n /**\n * List stored objects, optionally filtered by key prefix.\n *\n * @param prefix - Only return objects whose key starts with this prefix, e.g. `\"avatars/\"`.\n * @param opts - Pagination options.\n */\n list(\n prefix?: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<{ objects: StorageObject[] }> {\n return this.transport.request<{ objects: StorageObject[] }>({\n service: \"storage\",\n path: \"/v1/storage/objects\",\n query: {\n prefix,\n limit: opts?.limit,\n offset: opts?.offset,\n },\n });\n }\n\n /**\n * Delete a stored object by key.\n *\n * @param key - The storage key of the object to delete.\n */\n async delete(key: string): Promise<void> {\n await this.transport.request<void>({\n service: \"storage\",\n path: \"/v1/storage/object\",\n method: \"DELETE\",\n body: { key },\n });\n }\n\n /**\n * Get current storage usage statistics for the app.\n *\n * @returns Byte counts and object count.\n */\n getUsage(): Promise<{\n maxStorageBytes: number;\n objectCount: number;\n storageBytes: number;\n }> {\n return this.transport.request<{\n maxStorageBytes: number;\n objectCount: number;\n storageBytes: number;\n }>({\n service: \"storage\",\n path: \"/v1/storage/usage\",\n });\n }\n}\n","import { AuthClientNamespace, AuthServerNamespace } from \"./auth\";\nimport { BillingServerNamespace } from \"./billing\";\nimport { type BuildspaceConfig, resolveConfig } from \"./config\";\nimport { EventsServerNamespace } from \"./events\";\nimport { HttpTransport } from \"./http\";\nimport { NotificationsServerNamespace } from \"./notifications\";\nimport { StorageServerNamespace } from \"./storage\";\n\nexport * from \"./auth\";\nexport * from \"./billing\";\nexport type { BuildspaceClientConfig, BuildspaceConfig } from \"./config\";\nexport type { BuildspaceService } from \"./errors\";\nexport { BuildspaceError } from \"./errors\";\nexport * from \"./events\";\nexport * from \"./notifications\";\nexport * from \"./storage\";\n\n/**\n * Buildspace server SDK — use with a secret key (`bs_sec_*`).\n *\n * Provides access to all Buildspace services: auth, events, storage,\n * and notifications. For client-side (browser) usage, use\n * `createClient()` from `@buildspacestudio/sdk/client` instead.\n *\n * @example\n * ```ts\n * import Buildspace from \"@buildspacestudio/sdk\";\n *\n * const buildspace = new Buildspace(process.env.BUILDSPACE_SECRET_KEY!);\n *\n * // Verify a session\n * const session = await buildspace.auth.getSession(sessionToken);\n *\n * // Track an event\n * await buildspace.events.track(\"user.signed_up\", { plan: \"pro\" }, userId);\n *\n * // Upload a file\n * const { upload_url } = await buildspace.storage.getUploadUrl({\n * key: \"avatars/user-123.png\",\n * contentType: \"image/png\",\n * size: fileSize,\n * });\n *\n * // Send an email\n * await buildspace.notifications.send({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * html: \"<h1>You're in!</h1>\",\n * });\n * ```\n */\nclass Buildspace {\n private readonly transport: HttpTransport;\n private _auth: AuthServerNamespace | null = null;\n private _billing: BillingServerNamespace | null = null;\n private _events: EventsServerNamespace | null = null;\n private _notifications: NotificationsServerNamespace | null = null;\n private _publicAuth: AuthClientNamespace | null = null;\n private _storage: StorageServerNamespace | null = null;\n\n /**\n * Create a new server SDK instance.\n *\n * @param secretKey - Your Buildspace secret key (starts with `bs_sec_`).\n * @param config - Optional configuration overrides.\n */\n constructor(secretKey: string, config: BuildspaceConfig = {}) {\n this.transport = new HttpTransport({\n key: secretKey,\n resolvedConfig: resolveConfig(\"server\", config),\n });\n }\n\n /** Server-side auth: session verification, OAuth callback handling, sign-out. */\n get auth(): AuthServerNamespace {\n this._auth ??= new AuthServerNamespace(this.transport);\n return this._auth;\n }\n\n /**\n * Client-style auth helpers available on the server (e.g. generating sign-in URLs\n * in server-rendered pages). For full server auth, use {@link auth}.\n */\n get authClient(): AuthClientNamespace {\n this._publicAuth ??= new AuthClientNamespace(this.transport);\n return this._publicAuth;\n }\n\n /** Server-side event tracking. */\n get events(): EventsServerNamespace {\n this._events ??= new EventsServerNamespace(this.transport);\n return this._events;\n }\n\n /** Server-side billing: Checkout, Portal, subscriptions, and entitlements. */\n get billing(): BillingServerNamespace {\n this._billing ??= new BillingServerNamespace(this.transport);\n return this._billing;\n }\n\n /** Server-side file storage: upload URLs, signed downloads, listing, deletion. */\n get storage(): StorageServerNamespace {\n this._storage ??= new StorageServerNamespace(this.transport);\n return this._storage;\n }\n\n /** Server-side transactional email notifications. */\n get notifications(): NotificationsServerNamespace {\n this._notifications ??= new NotificationsServerNamespace(this.transport);\n return this._notifications;\n }\n\n /** Clear the stored session token. */\n clearSession(): void {\n this.transport.clearSession();\n }\n\n /**\n * Set a session token that will be sent as `X-Session-Token` on all\n * subsequent API requests.\n *\n * @param sessionToken - The session token to attach to requests.\n */\n setSession(sessionToken: string): void {\n this.transport.setSession(sessionToken);\n }\n}\n\nexport { Buildspace };\nexport default Buildspace;\n"]}
@@ -0,0 +1,183 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var BuildspaceError = class extends Error {
5
+ /** Machine-readable error code, e.g. `"auth/invalid-token"`. */
6
+ code;
7
+ /** Which service produced the error. */
8
+ service;
9
+ /** HTTP status code from the API. */
10
+ status;
11
+ constructor({
12
+ code,
13
+ message,
14
+ service,
15
+ status
16
+ }) {
17
+ super(message);
18
+ this.name = "BuildspaceError";
19
+ this.code = code;
20
+ this.service = service;
21
+ this.status = status;
22
+ }
23
+ };
24
+
25
+ // src/next/index.ts
26
+ var SESSION_COOKIE_NAME = "bs_session";
27
+ function isSecureDefault() {
28
+ return globalThis.process?.env?.NODE_ENV !== "development";
29
+ }
30
+ function serializeSessionCookie(value, maxAge, opts) {
31
+ const parts = [
32
+ `${SESSION_COOKIE_NAME}=${value}`,
33
+ `Path=${opts?.path ?? "/"}`,
34
+ "HttpOnly",
35
+ `SameSite=${opts?.sameSite === "strict" ? "Strict" : opts?.sameSite === "none" ? "None" : "Lax"}`
36
+ ];
37
+ if (maxAge !== null) {
38
+ parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);
39
+ }
40
+ if (opts?.secure ?? isSecureDefault()) {
41
+ parts.push("Secure");
42
+ }
43
+ if (opts?.domain) {
44
+ parts.push(`Domain=${opts.domain}`);
45
+ }
46
+ return parts.join("; ");
47
+ }
48
+ function buildSessionCookie(token, maxAgeSeconds, opts) {
49
+ return serializeSessionCookie(token, maxAgeSeconds, opts);
50
+ }
51
+ function buildClearSessionCookie(opts) {
52
+ return serializeSessionCookie("", 0, opts);
53
+ }
54
+ function parseCookieHeader(header, name) {
55
+ for (const part of header.split(";")) {
56
+ const eq = part.indexOf("=");
57
+ if (eq === -1) {
58
+ continue;
59
+ }
60
+ if (part.slice(0, eq).trim() === name) {
61
+ return part.slice(eq + 1).trim();
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+ function getSessionToken(source) {
67
+ if (source instanceof Request) {
68
+ const header = source.headers.get("cookie");
69
+ return header ? parseCookieHeader(header, SESSION_COOKIE_NAME) : null;
70
+ }
71
+ const cookie = source.get(SESSION_COOKIE_NAME);
72
+ if (!cookie) {
73
+ return null;
74
+ }
75
+ const value = typeof cookie === "string" ? cookie : cookie.value;
76
+ return value || null;
77
+ }
78
+ async function getSession(client, source) {
79
+ const token = getSessionToken(source);
80
+ if (!token) {
81
+ return null;
82
+ }
83
+ try {
84
+ const session = await client.auth.getSession(token);
85
+ return session ? { ...session, token } : null;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ async function requireSession(client, source) {
91
+ const session = await getSession(client, source);
92
+ if (!session) {
93
+ throw new BuildspaceError({
94
+ service: "auth",
95
+ status: 401,
96
+ code: "auth/session-required",
97
+ message: "No valid session. The bs_session cookie is missing, expired, or revoked."
98
+ });
99
+ }
100
+ return session;
101
+ }
102
+ function createAuthCallback(client, options) {
103
+ return async (request) => {
104
+ let tokens;
105
+ try {
106
+ tokens = await client.auth.handleCallback(request);
107
+ } catch (error) {
108
+ if (options?.onError) {
109
+ return await options.onError(error, request);
110
+ }
111
+ throw error;
112
+ }
113
+ if (options?.onSignIn) {
114
+ try {
115
+ await options.onSignIn({
116
+ accessToken: tokens.access_token,
117
+ request,
118
+ user: tokens.user
119
+ });
120
+ } catch (error) {
121
+ console.error("[buildspace] onSignIn hook failed", error);
122
+ }
123
+ }
124
+ return new Response(null, {
125
+ status: 303,
126
+ headers: {
127
+ Location: options?.redirectTo ?? "/",
128
+ "Set-Cookie": buildSessionCookie(tokens.access_token, tokens.expires_in, options?.cookie)
129
+ }
130
+ });
131
+ };
132
+ }
133
+ function createLogoutRoute(client, options) {
134
+ return async (request) => {
135
+ const token = getSessionToken(request);
136
+ if (token) {
137
+ try {
138
+ await client.auth.signOut(token);
139
+ } catch (error) {
140
+ console.error("[buildspace] session revoke failed during logout", error);
141
+ }
142
+ }
143
+ return new Response(JSON.stringify({ ok: true }), {
144
+ status: 200,
145
+ headers: {
146
+ "Content-Type": "application/json",
147
+ "Set-Cookie": buildClearSessionCookie(options?.cookie)
148
+ }
149
+ });
150
+ };
151
+ }
152
+ function createSessionRoute(client) {
153
+ return async (request) => {
154
+ const session = await getSession(client, request);
155
+ const publicSession = session ? { appId: session.appId, user: session.user } : null;
156
+ return new Response(JSON.stringify({ session: publicSession }), {
157
+ status: 200,
158
+ headers: { "Content-Type": "application/json" }
159
+ });
160
+ };
161
+ }
162
+ function createSessionCookieGuard(options) {
163
+ return (request) => {
164
+ if (getSessionToken(request)) {
165
+ return;
166
+ }
167
+ const target = new URL(options?.redirectTo ?? "/", new URL(request.url).origin);
168
+ return Response.redirect(target.toString(), 307);
169
+ };
170
+ }
171
+
172
+ exports.SESSION_COOKIE_NAME = SESSION_COOKIE_NAME;
173
+ exports.buildClearSessionCookie = buildClearSessionCookie;
174
+ exports.buildSessionCookie = buildSessionCookie;
175
+ exports.createAuthCallback = createAuthCallback;
176
+ exports.createLogoutRoute = createLogoutRoute;
177
+ exports.createSessionCookieGuard = createSessionCookieGuard;
178
+ exports.createSessionRoute = createSessionRoute;
179
+ exports.getSession = getSession;
180
+ exports.getSessionToken = getSessionToken;
181
+ exports.requireSession = requireSession;
182
+ //# sourceMappingURL=index.cjs.map
183
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors.ts","../../src/next/index.ts"],"names":[],"mappings":";;;AAiBO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA;AAAA,EAEhC,IAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EAET,WAAA,CAAY;AAAA,IACV,IAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA;AAAA,GACF,EAKG;AACD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,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I,IAAA;AAE/E,IAAA,OAAO,IAAI,SAAS,IAAA,CAAK,SAAA,CAAU,EAAE,OAAA,EAAS,aAAA,EAAe,CAAA,EAAG;AAAA,MAC9D,MAAA,EAAQ,GAAA;AAAA,MACR,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA;AAAmB,KAC/C,CAAA;AAAA,EACH,CAAA;AACF;AAkBO,SAAS,yBAAyB,OAAA,EAGM;AAC7C,EAAA,OAAO,CAAC,OAAA,KAA2C;AACjD,IAAA,IAAI,eAAA,CAAgB,OAAO,CAAA,EAAG;AAC5B,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,OAAA,EAAS,UAAA,IAAc,GAAA,EAAK,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,CAAE,MAAM,CAAA;AAC9E,IAAA,OAAO,QAAA,CAAS,QAAA,CAAS,MAAA,CAAO,QAAA,IAAY,GAAG,CAAA;AAAA,EACjD,CAAA;AACF","file":"index.cjs","sourcesContent":["/** Services available in the Buildspace platform. */\nexport type BuildspaceService = \"auth\" | \"billing\" | \"events\" | \"notifications\" | \"storage\";\n\n/**\n * Error thrown by all Buildspace SDK methods on failure.\n *\n * @example\n * ```ts\n * try {\n * await buildspace.auth.getSession(token);\n * } catch (err) {\n * if (err instanceof BuildspaceError) {\n * console.error(err.service, err.code, err.status, err.message);\n * }\n * }\n * ```\n */\nexport class BuildspaceError extends Error {\n /** Machine-readable error code, e.g. `\"auth/invalid-token\"`. */\n readonly code: string;\n /** Which service produced the error. */\n readonly service: BuildspaceService;\n /** HTTP status code from the API. */\n readonly status: number;\n\n constructor({\n code,\n message,\n service,\n status,\n }: {\n code: string;\n message: string;\n service: BuildspaceService;\n status: number;\n }) {\n super(message);\n this.name = \"BuildspaceError\";\n this.code = code;\n this.service = service;\n this.status = status;\n }\n}\n","import type { AuthSession, AuthUser, TokenResponse } from \"../auth\";\nimport { BuildspaceError } from \"../errors\";\n\n/**\n * Framework adapter for Next.js (and any framework using web-standard\n * `Request`/`Response` route handlers).\n *\n * Replaces the auth glue every creator app used to hand-roll: the OAuth\n * callback route, logout + session routes, a cookie-aware `getSession()`,\n * and a middleware cookie guard — all standardized on the `bs_session`\n * cookie.\n *\n * @example\n * ```ts\n * // app/api/auth/callback/route.ts\n * import { createAuthCallback } from \"@buildspacestudio/sdk/next\";\n * import { getServerClient } from \"@/lib/buildspace\";\n *\n * export const GET = createAuthCallback(getServerClient(), { redirectTo: \"/dashboard\" });\n * ```\n */\n\n/** The session cookie name shared by every Buildspace app. */\nexport const SESSION_COOKIE_NAME = \"bs_session\";\n\n/** The minimal server-client surface the adapter needs (a `Buildspace` instance). */\nexport interface AuthServerClient {\n auth: {\n getSession(sessionToken: string): Promise<AuthSession | null>;\n handleCallback(\n request: Request | URL | string,\n opts?: { redirectUri?: string }\n ): Promise<TokenResponse>;\n signOut(sessionToken?: string): Promise<void>;\n };\n}\n\n/** Options controlling the `bs_session` cookie attributes. */\nexport interface SessionCookieOptions {\n /** Cookie domain. Omitted by default (host-only cookie). */\n domain?: string;\n /** Cookie path. Defaults to `/`. */\n path?: string;\n /** SameSite attribute. Defaults to `Lax`. */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /** Set the `Secure` attribute. Defaults to `true` outside development. */\n secure?: boolean;\n}\n\nfunction isSecureDefault(): boolean {\n return (\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n ?.NODE_ENV !== \"development\"\n );\n}\n\nfunction serializeSessionCookie(\n value: string,\n maxAge: number | null,\n opts?: SessionCookieOptions\n): string {\n const parts = [\n `${SESSION_COOKIE_NAME}=${value}`,\n `Path=${opts?.path ?? \"/\"}`,\n \"HttpOnly\",\n `SameSite=${opts?.sameSite === \"strict\" ? \"Strict\" : opts?.sameSite === \"none\" ? \"None\" : \"Lax\"}`,\n ];\n\n if (maxAge !== null) {\n parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);\n }\n\n if (opts?.secure ?? isSecureDefault()) {\n parts.push(\"Secure\");\n }\n\n if (opts?.domain) {\n parts.push(`Domain=${opts.domain}`);\n }\n\n return parts.join(\"; \");\n}\n\n/** Build a `Set-Cookie` header value that stores the session token. */\nexport function buildSessionCookie(\n token: string,\n maxAgeSeconds: number,\n opts?: SessionCookieOptions\n): string {\n return serializeSessionCookie(token, maxAgeSeconds, opts);\n}\n\n/** Build a `Set-Cookie` header value that clears the session cookie. */\nexport function buildClearSessionCookie(opts?: SessionCookieOptions): string {\n return serializeSessionCookie(\"\", 0, opts);\n}\n\n/**\n * Anything the adapter can read the session cookie from: a web `Request`,\n * or a cookie store with a `get(name)` method (e.g. the object returned by\n * Next.js `cookies()` in Server Components and Route Handlers).\n */\nexport type SessionCookieSource =\n | Request\n | {\n get(name: string): { value: string } | string | null | undefined;\n };\n\nfunction parseCookieHeader(header: string, name: string): string | null {\n for (const part of header.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n\n if (part.slice(0, eq).trim() === name) {\n return part.slice(eq + 1).trim();\n }\n }\n\n return null;\n}\n\n/** Read the raw session token from a request or cookie store, or `null`. */\nexport function getSessionToken(source: SessionCookieSource): string | null {\n if (source instanceof Request) {\n const header = source.headers.get(\"cookie\");\n return header ? parseCookieHeader(header, SESSION_COOKIE_NAME) : null;\n }\n\n const cookie = source.get(SESSION_COOKIE_NAME);\n if (!cookie) {\n return null;\n }\n\n const value = typeof cookie === \"string\" ? cookie : cookie.value;\n return value || null;\n}\n\n/** An {@link AuthSession} plus the raw token it was resolved from. */\nexport type SessionWithToken = AuthSession & { token: string };\n\n/**\n * Cookie-aware session lookup.\n *\n * Reads the `bs_session` cookie from the given source and verifies it with\n * the Buildspace API. Returns `null` when there is no cookie or the token\n * is expired/revoked. Network/5xx errors also resolve to `null` so a blip\n * never crashes rendering — sign-in state degrades to \"signed out\".\n *\n * @example\n * ```ts\n * // Server Component\n * import { cookies } from \"next/headers\";\n * const session = await getSession(getServerClient(), await cookies());\n * ```\n */\nexport async function getSession(\n client: AuthServerClient,\n source: SessionCookieSource\n): Promise<SessionWithToken | null> {\n const token = getSessionToken(source);\n if (!token) {\n return null;\n }\n\n try {\n const session = await client.auth.getSession(token);\n return session ? { ...session, token } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Like {@link getSession} but throws a `BuildspaceError` (401) when there is\n * no valid session. Use in route handlers and server actions that must only\n * run for signed-in users.\n */\nexport async function requireSession(\n client: AuthServerClient,\n source: SessionCookieSource\n): Promise<SessionWithToken> {\n const session = await getSession(client, source);\n if (!session) {\n throw new BuildspaceError({\n service: \"auth\",\n status: 401,\n code: \"auth/session-required\",\n message: \"No valid session. The bs_session cookie is missing, expired, or revoked.\",\n });\n }\n\n return session;\n}\n\n/** Options for {@link createAuthCallback}. */\nexport interface CreateAuthCallbackOptions {\n /** Cookie attribute overrides. */\n cookie?: SessionCookieOptions;\n /**\n * Called when the code exchange fails. Return a `Response` to control the\n * error page; by default the error is rethrown (surfacing your framework's\n * error handling).\n */\n onError?: (error: unknown, request: Request) => Response | Promise<Response>;\n /**\n * Signup/sign-in side effects (mirror the user into your DB, send a\n * welcome email, track an event). Failures are logged and never break\n * login.\n */\n onSignIn?: (ctx: {\n accessToken: string;\n request: Request;\n user: AuthUser;\n }) => void | Promise<void>;\n /** Where to send the user after login. Defaults to `/`. */\n redirectTo?: string;\n}\n\n/**\n * Create the OAuth callback route handler.\n *\n * Exchanges the `?code=` for tokens, runs your `onSignIn` hook, stores the\n * access token in the `bs_session` cookie (with `expires_in` as `Max-Age`),\n * and redirects to `redirectTo`.\n *\n * @example\n * ```ts\n * // app/api/auth/callback/route.ts\n * export const GET = createAuthCallback(getServerClient(), {\n * redirectTo: \"/dashboard\",\n * onSignIn: async ({ user }) => upsertUser(user),\n * });\n * ```\n */\nexport function createAuthCallback(\n client: AuthServerClient,\n options?: CreateAuthCallbackOptions\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n let tokens: TokenResponse;\n try {\n tokens = await client.auth.handleCallback(request);\n } catch (error) {\n if (options?.onError) {\n return await options.onError(error, request);\n }\n throw error;\n }\n\n if (options?.onSignIn) {\n try {\n await options.onSignIn({\n accessToken: tokens.access_token,\n request,\n user: tokens.user,\n });\n } catch (error) {\n console.error(\"[buildspace] onSignIn hook failed\", error);\n }\n }\n\n return new Response(null, {\n status: 303,\n headers: {\n Location: options?.redirectTo ?? \"/\",\n \"Set-Cookie\": buildSessionCookie(tokens.access_token, tokens.expires_in, options?.cookie),\n },\n });\n };\n}\n\n/**\n * Create the logout route handler (`POST /api/auth/logout`).\n *\n * Revokes the session with the Buildspace API (already-expired sessions are\n * ignored) and clears the `bs_session` cookie.\n */\nexport function createLogoutRoute(\n client: AuthServerClient,\n options?: { cookie?: SessionCookieOptions }\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const token = getSessionToken(request);\n\n if (token) {\n try {\n await client.auth.signOut(token);\n } catch (error) {\n console.error(\"[buildspace] session revoke failed during logout\", error);\n }\n }\n\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Set-Cookie\": buildClearSessionCookie(options?.cookie),\n },\n });\n };\n}\n\n/**\n * Create the session route handler (`GET /api/auth/session`).\n *\n * Returns `{ session }` for the current cookie, with the raw token omitted —\n * this response is safe to expose to the browser.\n */\nexport function createSessionRoute(\n client: AuthServerClient\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const session = await getSession(client, request);\n const publicSession = session ? { appId: session.appId, user: session.user } : null;\n\n return new Response(JSON.stringify({ session: publicSession }), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n };\n}\n\n/**\n * Middleware helper: redirect requests that don't carry a session cookie.\n *\n * This is a fast presence check (no API call — middleware runs on every\n * matched request); route handlers and pages must still verify the session\n * with {@link getSession}.\n *\n * @example\n * ```ts\n * // middleware.ts / proxy.ts\n * import { createSessionCookieGuard } from \"@buildspacestudio/sdk/next\";\n *\n * export const proxy = createSessionCookieGuard({ redirectTo: \"/\" });\n * export const config = { matcher: [\"/dashboard/:path*\"] };\n * ```\n */\nexport function createSessionCookieGuard(options?: {\n /** Where to send signed-out users. Defaults to `/`. */\n redirectTo?: string;\n}): (request: Request) => Response | undefined {\n return (request: Request): Response | undefined => {\n if (getSessionToken(request)) {\n return;\n }\n\n const target = new URL(options?.redirectTo ?? \"/\", new URL(request.url).origin);\n return Response.redirect(target.toString(), 307);\n };\n}\n"]}
@@ -0,0 +1,164 @@
1
+ import { a as AuthSession, T as TokenResponse, b as AuthUser } from '../server-CoPDzSUP.cjs';
2
+ import '../http-D2gXpNpr.cjs';
3
+
4
+ /**
5
+ * Framework adapter for Next.js (and any framework using web-standard
6
+ * `Request`/`Response` route handlers).
7
+ *
8
+ * Replaces the auth glue every creator app used to hand-roll: the OAuth
9
+ * callback route, logout + session routes, a cookie-aware `getSession()`,
10
+ * and a middleware cookie guard — all standardized on the `bs_session`
11
+ * cookie.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * // app/api/auth/callback/route.ts
16
+ * import { createAuthCallback } from "@buildspacestudio/sdk/next";
17
+ * import { getServerClient } from "@/lib/buildspace";
18
+ *
19
+ * export const GET = createAuthCallback(getServerClient(), { redirectTo: "/dashboard" });
20
+ * ```
21
+ */
22
+ /** The session cookie name shared by every Buildspace app. */
23
+ declare const SESSION_COOKIE_NAME = "bs_session";
24
+ /** The minimal server-client surface the adapter needs (a `Buildspace` instance). */
25
+ interface AuthServerClient {
26
+ auth: {
27
+ getSession(sessionToken: string): Promise<AuthSession | null>;
28
+ handleCallback(request: Request | URL | string, opts?: {
29
+ redirectUri?: string;
30
+ }): Promise<TokenResponse>;
31
+ signOut(sessionToken?: string): Promise<void>;
32
+ };
33
+ }
34
+ /** Options controlling the `bs_session` cookie attributes. */
35
+ interface SessionCookieOptions {
36
+ /** Cookie domain. Omitted by default (host-only cookie). */
37
+ domain?: string;
38
+ /** Cookie path. Defaults to `/`. */
39
+ path?: string;
40
+ /** SameSite attribute. Defaults to `Lax`. */
41
+ sameSite?: "lax" | "strict" | "none";
42
+ /** Set the `Secure` attribute. Defaults to `true` outside development. */
43
+ secure?: boolean;
44
+ }
45
+ /** Build a `Set-Cookie` header value that stores the session token. */
46
+ declare function buildSessionCookie(token: string, maxAgeSeconds: number, opts?: SessionCookieOptions): string;
47
+ /** Build a `Set-Cookie` header value that clears the session cookie. */
48
+ declare function buildClearSessionCookie(opts?: SessionCookieOptions): string;
49
+ /**
50
+ * Anything the adapter can read the session cookie from: a web `Request`,
51
+ * or a cookie store with a `get(name)` method (e.g. the object returned by
52
+ * Next.js `cookies()` in Server Components and Route Handlers).
53
+ */
54
+ type SessionCookieSource = Request | {
55
+ get(name: string): {
56
+ value: string;
57
+ } | string | null | undefined;
58
+ };
59
+ /** Read the raw session token from a request or cookie store, or `null`. */
60
+ declare function getSessionToken(source: SessionCookieSource): string | null;
61
+ /** An {@link AuthSession} plus the raw token it was resolved from. */
62
+ type SessionWithToken = AuthSession & {
63
+ token: string;
64
+ };
65
+ /**
66
+ * Cookie-aware session lookup.
67
+ *
68
+ * Reads the `bs_session` cookie from the given source and verifies it with
69
+ * the Buildspace API. Returns `null` when there is no cookie or the token
70
+ * is expired/revoked. Network/5xx errors also resolve to `null` so a blip
71
+ * never crashes rendering — sign-in state degrades to "signed out".
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * // Server Component
76
+ * import { cookies } from "next/headers";
77
+ * const session = await getSession(getServerClient(), await cookies());
78
+ * ```
79
+ */
80
+ declare function getSession(client: AuthServerClient, source: SessionCookieSource): Promise<SessionWithToken | null>;
81
+ /**
82
+ * Like {@link getSession} but throws a `BuildspaceError` (401) when there is
83
+ * no valid session. Use in route handlers and server actions that must only
84
+ * run for signed-in users.
85
+ */
86
+ declare function requireSession(client: AuthServerClient, source: SessionCookieSource): Promise<SessionWithToken>;
87
+ /** Options for {@link createAuthCallback}. */
88
+ interface CreateAuthCallbackOptions {
89
+ /** Cookie attribute overrides. */
90
+ cookie?: SessionCookieOptions;
91
+ /**
92
+ * Called when the code exchange fails. Return a `Response` to control the
93
+ * error page; by default the error is rethrown (surfacing your framework's
94
+ * error handling).
95
+ */
96
+ onError?: (error: unknown, request: Request) => Response | Promise<Response>;
97
+ /**
98
+ * Signup/sign-in side effects (mirror the user into your DB, send a
99
+ * welcome email, track an event). Failures are logged and never break
100
+ * login.
101
+ */
102
+ onSignIn?: (ctx: {
103
+ accessToken: string;
104
+ request: Request;
105
+ user: AuthUser;
106
+ }) => void | Promise<void>;
107
+ /** Where to send the user after login. Defaults to `/`. */
108
+ redirectTo?: string;
109
+ }
110
+ /**
111
+ * Create the OAuth callback route handler.
112
+ *
113
+ * Exchanges the `?code=` for tokens, runs your `onSignIn` hook, stores the
114
+ * access token in the `bs_session` cookie (with `expires_in` as `Max-Age`),
115
+ * and redirects to `redirectTo`.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * // app/api/auth/callback/route.ts
120
+ * export const GET = createAuthCallback(getServerClient(), {
121
+ * redirectTo: "/dashboard",
122
+ * onSignIn: async ({ user }) => upsertUser(user),
123
+ * });
124
+ * ```
125
+ */
126
+ declare function createAuthCallback(client: AuthServerClient, options?: CreateAuthCallbackOptions): (request: Request) => Promise<Response>;
127
+ /**
128
+ * Create the logout route handler (`POST /api/auth/logout`).
129
+ *
130
+ * Revokes the session with the Buildspace API (already-expired sessions are
131
+ * ignored) and clears the `bs_session` cookie.
132
+ */
133
+ declare function createLogoutRoute(client: AuthServerClient, options?: {
134
+ cookie?: SessionCookieOptions;
135
+ }): (request: Request) => Promise<Response>;
136
+ /**
137
+ * Create the session route handler (`GET /api/auth/session`).
138
+ *
139
+ * Returns `{ session }` for the current cookie, with the raw token omitted —
140
+ * this response is safe to expose to the browser.
141
+ */
142
+ declare function createSessionRoute(client: AuthServerClient): (request: Request) => Promise<Response>;
143
+ /**
144
+ * Middleware helper: redirect requests that don't carry a session cookie.
145
+ *
146
+ * This is a fast presence check (no API call — middleware runs on every
147
+ * matched request); route handlers and pages must still verify the session
148
+ * with {@link getSession}.
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * // middleware.ts / proxy.ts
153
+ * import { createSessionCookieGuard } from "@buildspacestudio/sdk/next";
154
+ *
155
+ * export const proxy = createSessionCookieGuard({ redirectTo: "/" });
156
+ * export const config = { matcher: ["/dashboard/:path*"] };
157
+ * ```
158
+ */
159
+ declare function createSessionCookieGuard(options?: {
160
+ /** Where to send signed-out users. Defaults to `/`. */
161
+ redirectTo?: string;
162
+ }): (request: Request) => Response | undefined;
163
+
164
+ export { type AuthServerClient, type CreateAuthCallbackOptions, SESSION_COOKIE_NAME, type SessionCookieOptions, type SessionCookieSource, type SessionWithToken, buildClearSessionCookie, buildSessionCookie, createAuthCallback, createLogoutRoute, createSessionCookieGuard, createSessionRoute, getSession, getSessionToken, requireSession };