@burdenoff/be-sdk 2026.1130.3 → 2026.1201.1

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 (34) hide show
  1. package/README.md +6 -1
  2. package/dist/context/index.js +7 -2
  3. package/dist/context/index.js.map +1 -1
  4. package/dist/files/index.d.ts +2 -2
  5. package/dist/files/index.js +2 -2
  6. package/dist/{files-h5U-D2AF.js → files-BISdM0fh.js} +188 -28
  7. package/dist/files-BISdM0fh.js.map +1 -0
  8. package/dist/{bun-runtime-metrics-CPy5D6NT.js → incoming-request-span-DCou42Il.js} +56 -2
  9. package/dist/incoming-request-span-DCou42Il.js.map +1 -0
  10. package/dist/{index-8pUSoT85.d.ts → index-ieSQpD9r.d.ts} +26 -3
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.js +3 -3
  13. package/dist/prisma/index.js +2 -2
  14. package/dist/{prisma-Bo-C0XUv.js → prisma-D0f-THMv.js} +2 -2
  15. package/dist/{prisma-Bo-C0XUv.js.map → prisma-D0f-THMv.js.map} +1 -1
  16. package/dist/{sdk-7TBR987n.js → sdk-Oooulm2n.js} +22 -6
  17. package/dist/sdk-Oooulm2n.js.map +1 -0
  18. package/dist/server/index.js +5 -5
  19. package/dist/server/index.js.map +1 -1
  20. package/dist/{stub-DNkzpQvR.js → stub-CmVOE6ql.js} +2 -2
  21. package/dist/{stub-DNkzpQvR.js.map → stub-CmVOE6ql.js.map} +1 -1
  22. package/dist/telemetry/index.d.ts +40 -2
  23. package/dist/telemetry/index.js +3 -3
  24. package/dist/telemetry/index.js.map +1 -1
  25. package/dist/tracker/index.js +2 -2
  26. package/dist/{tracker-CDVYIoCb.js → tracker-CNF8TRpk.js} +2 -2
  27. package/dist/{tracker-CDVYIoCb.js.map → tracker-CNF8TRpk.js.map} +1 -1
  28. package/dist/{workspace-extension-BcMPoGWr.js → workspace-extension-feJYFO9e.js} +41 -8
  29. package/dist/workspace-extension-feJYFO9e.js.map +1 -0
  30. package/package.json +1 -1
  31. package/dist/bun-runtime-metrics-CPy5D6NT.js.map +0 -1
  32. package/dist/files-h5U-D2AF.js.map +0 -1
  33. package/dist/sdk-7TBR987n.js.map +0 -1
  34. package/dist/workspace-extension-BcMPoGWr.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"files-h5U-D2AF.js","names":[],"sources":["../src/files/types.ts","../src/files/errors.ts","../src/files/client.ts","../src/files/reference.ts","../src/files/index.ts"],"sourcesContent":["/**\n * Files client — shared types.\n *\n * wspace-files-svc is the one owner of workspace blobs. Product services never\n * presign S3 themselves or hold storage keys: they hand bytes to files-svc\n * through the internal workspace gateway and keep only the opaque `fileId`.\n * These types describe the wire shape the client reads from files-svc and the\n * projection it hands back to the service.\n */\nimport type { GraphQLRequestOptions, GraphQLResponse } from '../gateway/types.js';\n\n/** Actor types the gateway forwards in `x-actor-type`. */\nexport const FILE_ACTOR_TYPES = ['user', 'app', 'service', 'super_admin'] as const;\n\nexport type FileActorType = (typeof FILE_ACTOR_TYPES)[number];\n\n/**\n * The caller a file operation runs on behalf of (forwarded as `x-actor-*` /\n * `x-workspace-id`).\n *\n * Pass the END USER who asked for the operation, not the service: files-svc\n * records `actorId` as the uploader, scopes the File row to `workspaceId`, and\n * checks quota, folder access and read permission against that actor. A row\n * uploaded \"as the service\" belongs to nobody the workspace can see.\n */\nexport interface FileActor {\n /** `x-actor-id` — the user/app the gateway authenticated. */\n actorId: string;\n /** `x-workspace-id` — the workspace the File row belongs to. */\n workspaceId: string;\n /** `x-actor-type`; defaults to `user`. */\n actorType?: FileActorType;\n}\n\n/** `FileVisibility` enum members accepted by wspace-files-svc. */\nexport const FILE_VISIBILITIES = ['PRIVATE', 'PUBLIC', 'TEAM', 'WORKSPACE'] as const;\n\nexport type FileVisibility = (typeof FILE_VISIBILITIES)[number];\n\n/** `FileStatus` enum members returned by wspace-files-svc. */\nexport type FileStatus = 'ACTIVE' | 'ARCHIVED' | 'DELETED' | 'UPLOADING';\n\n/** `UploadType` chosen by files-svc for a session (it switches large files to MULTIPART). */\nexport type FileUploadType = 'DIRECT' | 'MULTIPART' | 'RESUMABLE';\n\n/** Bytes the client can upload. Node/Bun `Buffer` is a `Uint8Array`. */\nexport type FileBytes = Uint8Array | ArrayBuffer;\n\n/** Input for {@link FilesClient.uploadFile}. */\nexport interface UploadFileInput {\n /** File name shown in the workspace library, e.g. `soc2-evidence.pdf`. */\n fileName: string;\n /** The file contents. */\n data: FileBytes;\n /** MIME type, e.g. `application/pdf`. Sent as the PUT `Content-Type`. */\n mimeType: string;\n /** Extension without the dot. Default: taken from `fileName`, else `bin`. */\n extension?: string;\n /** Folder to file it in. The actor must be allowed to upload there. */\n folderId?: string | null;\n /** Description stored on the File row. */\n description?: string | null;\n /** Visibility. files-svc default is `PRIVATE`. */\n visibility?: FileVisibility;\n /**\n * Declare the SHA-256 of the bytes at initiate and complete, so files-svc can\n * verify what it stored. Default `true`.\n */\n declareSha256?: boolean;\n}\n\n/** What {@link FilesClient.uploadFile} returns: persist `fileId`, nothing else is needed. */\nexport interface StoredFile {\n fileId: string;\n name: string;\n mimeType: string;\n /** Size in bytes. */\n size: number;\n workspaceId: string;\n /** Lowercase hex SHA-256 when it was declared, else `null`. */\n sha256Hash: string | null;\n}\n\n/**\n * File metadata, read through the files graph's ROOT `getFile` field.\n *\n * Only scalars are selected: files-svc's `File` entity has no\n * `__resolveReference`, so federated sub-selections (folder, versions, …) are\n * deliberately not part of this shape.\n */\nexport interface FileMetadata {\n id: string;\n name: string;\n mimeType: string;\n extension: string;\n /** Size in bytes. */\n size: number;\n status: FileStatus;\n visibility: FileVisibility;\n workspaceId: string;\n folderId: string | null;\n uploadedById: string;\n description: string | null;\n sha256Hash: string | null;\n createdAt: Date | null;\n updatedAt: Date | null;\n /** Whether the actor may read the file (files-svc permission check). */\n canRead: boolean | null;\n /** Whether the actor may delete the file. */\n canDelete: boolean | null;\n}\n\n/** Options for {@link FilesClient.requireFile}. */\nexport interface RequireFileOptions {\n /** Reject files that are not `ACTIVE`. Default `true`. */\n requireActive?: boolean;\n /** Reject files the actor cannot read (`canRead !== true`). Default `true`. */\n requireReadable?: boolean;\n}\n\n/** Options for {@link FilesClient.getDownloadUrl}. */\nexport interface DownloadUrlOptions {\n /** URL lifetime in seconds, clamped to [60, 604800] (the S3 presign maximum). */\n expiresInSeconds?: number;\n}\n\n/** Options for {@link FilesClient.downloadFile}. */\nexport interface DownloadFileOptions {\n /** Refuse files larger than this many bytes. Default: the client's `maxDownloadBytes`. */\n maxBytes?: number;\n}\n\n/** What {@link FilesClient.downloadFile} returns. */\nexport interface DownloadedFile {\n bytes: Uint8Array;\n /** MIME type recorded by files-svc. */\n mimeType: string;\n name: string;\n size: number;\n}\n\n/**\n * Input for {@link FilesClient.createUploadSession}: a delegated upload, where\n * the service opens the files-svc session on the actor's behalf and hands the\n * presigned URL(s) to whoever holds the bytes (an agent, a CLI, a browser).\n */\nexport interface CreateUploadSessionInput {\n /** File name shown in the workspace library. */\n fileName: string;\n /** Exact size of the bytes the uploader will PUT. `completeUploadSession` must repeat it. */\n fileSize: number;\n /** MIME type. A DIRECT URL is signed for it, so the uploader must send it as `Content-Type`. */\n mimeType: string;\n /** Extension without the dot. Default: taken from `fileName`, else `bin`. */\n extension?: string;\n /** Lowercase hex SHA-256 the uploader declared; files-svc checks it again at completion. */\n sha256Hash?: string | null;\n /** Folder to file it in. The actor must be allowed to upload there. */\n folderId?: string | null;\n /** Visibility. files-svc default is `PRIVATE`. */\n visibility?: FileVisibility;\n}\n\n/** One presigned part of a MULTIPART {@link UploadSessionTicket}. */\nexport interface UploadSessionPart {\n /** 1-indexed part number. */\n partNumber: number;\n /** Presigned PUT URL for exactly the bytes `[offset, offset + length)`. */\n url: string;\n /** First byte of the part within the file. */\n offset: number;\n /** Number of bytes in the part. */\n length: number;\n}\n\n/**\n * An open files-svc upload session the caller hands to the uploader. Mint it per\n * upload; never persist the URLs (only `sessionId`).\n */\nexport interface UploadSessionTicket {\n sessionId: string;\n /** `DIRECT` → one PUT to `uploadUrl`; `MULTIPART` → one PUT per entry of `parts`. */\n uploadType: 'DIRECT' | 'MULTIPART';\n /** DIRECT only: the presigned PUT URL. `null` for MULTIPART. */\n uploadUrl: string | null;\n /** Headers the uploader must send on the DIRECT PUT (the signed `Content-Type`). Empty for MULTIPART parts. */\n requiredHeaders: Record<string, string>;\n /** MULTIPART only: every part, in order. Empty for DIRECT. */\n parts: UploadSessionPart[];\n partSize: number;\n totalParts: number;\n /** Size in bytes the session was opened for. */\n fileSize: number;\n /** The SHA-256 declared at initiate, or `null`. */\n sha256Hash: string | null;\n /** When files-svc expires the session, if it said. */\n expiresAt: Date | null;\n}\n\n/** An uploaded MULTIPART part: the ETag object storage returned for its PUT. */\nexport interface UploadedPart {\n partNumber: number;\n etag: string;\n}\n\n/** Input for {@link FilesClient.completeUploadSession}. */\nexport interface CompleteUploadSessionInput {\n /** Must equal the `fileSize` the session was opened with. */\n fileSize: number;\n /** Must equal the SHA-256 declared at initiate when one was declared. */\n sha256Hash?: string | null;\n /** Description stored on the File row. */\n description?: string | null;\n /** Folder to file it in (defaults to the one given at initiate). */\n folderId?: string | null;\n /** MULTIPART only: every part's ETag, registered before completion. */\n parts?: readonly UploadedPart[];\n}\n\n/** Options for {@link FilesClient.deleteFile}. */\nexport interface DeleteFileOptions {\n /** Hard delete (`permanentlyDeleteFile`) instead of moving to trash. Default `false`. */\n permanent?: boolean;\n}\n\n/** The slice of be-sdk's `GatewayClient` the files client needs (injectable for tests). */\nexport interface FilesTransport {\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n}\n\n/** `fetch`-compatible function used for the presigned PUT/GET legs (injectable for tests). */\nexport type FilesFetch = (url: string, init?: RequestInit) => Promise<Response>;\n\n/** `File` as selected over the wire (BigInt and DateTime arrive as strings). */\nexport interface RawFileMetadata {\n id: string;\n name: string;\n mimeType: string;\n extension: string;\n size: string | number;\n status: FileStatus;\n visibility: FileVisibility;\n workspaceId: string;\n folderId?: string | null;\n uploadedById: string;\n description?: string | null;\n sha256Hash?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n canRead?: boolean | null;\n canDelete?: boolean | null;\n}\n","/**\n * Files client — error type.\n *\n * Services map {@link FilesClientError} onto their own i18n GraphQL errors; the\n * `code` is stable so that mapping never parses messages. Upstream detail\n * (files-svc messages, storage status codes) lives in `details` for logging and\n * must not be returned to clients verbatim.\n */\nimport { GatewayError, type GraphQLError } from '../gateway/types.js';\n\nexport type FilesClientErrorCode =\n /** A required argument is empty or out of range. */\n | 'INVALID_INPUT'\n /** No actor/workspace on the request — files are always workspace-scoped. */\n | 'MISSING_CONTEXT'\n /** The file does not exist, is in another workspace, or the actor may not read it. */\n | 'NOT_FOUND'\n /** The workspace storage/file quota, or the per-upload size limit, rejected the upload. */\n | 'QUOTA_EXCEEDED'\n /** The bytes exceed the client's configured upload/download cap. */\n | 'TOO_LARGE'\n /** The presigned PUT/GET against object storage failed. */\n | 'STORAGE_ERROR'\n /** files-svc or the gateway failed, or answered without the expected payload. */\n | 'UPSTREAM_ERROR'\n /** The client was configured inconsistently (thrown at boot). */\n | 'CONFIGURATION_ERROR';\n\n/** GraphQL `extensions.code` each {@link FilesClientErrorCode} should surface as. */\nexport const FILES_CLIENT_GRAPHQL_CODES: Record<FilesClientErrorCode, string> = {\n INVALID_INPUT: 'BAD_USER_INPUT',\n MISSING_CONTEXT: 'UNAUTHENTICATED',\n // Never FORBIDDEN: a file the actor cannot see must be indistinguishable from one that does not exist.\n NOT_FOUND: 'NOT_FOUND',\n QUOTA_EXCEEDED: 'QUOTA_EXCEEDED',\n TOO_LARGE: 'BAD_USER_INPUT',\n STORAGE_ERROR: 'INTERNAL_SERVER_ERROR',\n UPSTREAM_ERROR: 'INTERNAL_SERVER_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_SERVER_ERROR',\n};\n\nexport class FilesClientError extends Error {\n readonly code: FilesClientErrorCode;\n readonly details: Record<string, unknown>;\n\n constructor(code: FilesClientErrorCode, message: string, details: Record<string, unknown> = {}) {\n super(message);\n this.name = 'FilesClientError';\n this.code = code;\n this.details = details;\n }\n\n /** The GraphQL `extensions.code` this error maps to. */\n get graphqlCode(): string {\n return FILES_CLIENT_GRAPHQL_CODES[this.code];\n }\n}\n\nexport function isFilesClientError(error: unknown): error is FilesClientError {\n return error instanceof FilesClientError;\n}\n\nconst NOT_FOUND_UPSTREAM_CODES = new Set(['NOT_FOUND', 'FORBIDDEN']);\nconst QUOTA_UPSTREAM_CODES = new Set(['QUOTA_EXCEEDED', 'QUOTA_EXHAUSTED', 'USAGE_LIMIT_EXCEEDED']);\nconst INVALID_UPSTREAM_CODES = new Set(['BAD_USER_INPUT', 'EXPIRED']);\n\nfunction upstreamCode(error: GraphQLError): string | null {\n const code = error.extensions?.['code'];\n return typeof code === 'string' ? code : null;\n}\n\n/** Classify files-svc GraphQL errors into a {@link FilesClientErrorCode}. */\nexport function classifyFilesErrors(errors: readonly GraphQLError[]): FilesClientErrorCode {\n const codes = errors.map(upstreamCode).filter((code): code is string => code !== null);\n if (codes.some((code) => QUOTA_UPSTREAM_CODES.has(code))) return 'QUOTA_EXCEEDED';\n if (codes.some((code) => NOT_FOUND_UPSTREAM_CODES.has(code))) return 'NOT_FOUND';\n if (codes.some((code) => INVALID_UPSTREAM_CODES.has(code))) return 'INVALID_INPUT';\n return 'UPSTREAM_ERROR';\n}\n\n/**\n * Normalise anything a files-svc call threw (a `GatewayError` carrying GraphQL\n * errors, a timeout, a network error, …) into a {@link FilesClientError}.\n */\nexport function toFilesClientError(error: unknown, operation: string): FilesClientError {\n if (error instanceof FilesClientError) return error;\n if (error instanceof GatewayError) {\n const graphqlErrors = error.graphqlErrors ?? [];\n const code = graphqlErrors.length > 0 ? classifyFilesErrors(graphqlErrors) : 'UPSTREAM_ERROR';\n return new FilesClientError(code, `wspace-files-svc ${operation} failed: ${error.message}`, {\n operation,\n gatewayErrorType: error.type,\n statusCode: error.statusCode,\n errors: graphqlErrors.map((graphqlError) => ({\n message: graphqlError.message,\n code: upstreamCode(graphqlError),\n })),\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc ${operation} failed: ${message}`, { operation });\n}\n","/**\n * FilesClient — store and read workspace blobs through wspace-files-svc.\n *\n * Module ownership makes wspace-files-svc the canonical owner of blobs, yet\n * services kept re-implementing storage: VibeControls hand-rolled SigV4 with\n * static S3 keys for security evidence, FluidGrids passed attachments between\n * nodes as base64, HealthyBowl carried its own three-step uploader. This class\n * is the shared client: a service hands it bytes and gets back an opaque\n * `fileId`, and resolves that id back to metadata, a short-lived download URL or\n * the bytes themselves.\n *\n * Every call is same-layer M2M through the internal workspace gateway\n * (`GatewayClient.internalQuery`, which signs the service JWT; the gateway adds\n * its own trusted token toward files-svc). The CALLER's actor and workspace are\n * forwarded explicitly, so the File row is owned by the user who asked for it,\n * shows up in their library, and files-svc applies quota, folder access and read\n * permission to that user. The internal gateway enforces neither `@rbac` nor\n * `@usage` for the product's own resolver, so the service must already have\n * authorized the action (its own `@rbac` plus a workspace-scoped row lookup).\n *\n * Upload is the files-svc protocol: `initiateUpload` → presigned PUT (DIRECT) or\n * per-part PUTs + `registerUploadedPart` (MULTIPART, which files-svc picks for\n * files over 5 MiB) → `completeUpload` with the same `fileSize` (required: it\n * must match the size declared at initiate). A failed upload aborts its session.\n *\n * @example\n * ```ts\n * import { FilesClient, toFileReference } from '@burdenoff/be-sdk/files';\n *\n * const files = new FilesClient({ serviceName: 'wspace-vibecontrols-svc' });\n *\n * const stored = await files.uploadFile(\n * { fileName: 'access-review.pdf', data: pdfBytes, mimeType: 'application/pdf', description: 'SOC 2 evidence' },\n * { actorId: ctx.actorId, workspaceId: ctx.workspaceId }\n * );\n * await db.securityEvidence.update({ where: { id }, data: { fileId: stored.fileId } });\n *\n * const url = await files.getDownloadUrl(evidence.fileId, actor, { expiresInSeconds: 300 });\n * ```\n */\nimport { createHash } from 'node:crypto';\n\nimport type { GraphQLResponse } from '../gateway/types.js';\n\nimport { FilesClientError, classifyFilesErrors, toFilesClientError } from './errors.js';\nimport type {\n CompleteUploadSessionInput,\n CreateUploadSessionInput,\n DeleteFileOptions,\n DownloadFileOptions,\n DownloadUrlOptions,\n DownloadedFile,\n FileActor,\n FileBytes,\n FileMetadata,\n FileUploadType,\n FilesFetch,\n FilesTransport,\n RawFileMetadata,\n RequireFileOptions,\n StoredFile,\n UploadFileInput,\n UploadSessionPart,\n UploadSessionTicket,\n UploadedPart,\n} from './types.js';\nimport { FILE_ACTOR_TYPES, FILE_VISIBILITIES } from './types.js';\n\nconst MIB = 1024 * 1024;\n\n/** S3 refuses presigned URLs that live longer than 7 days; files-svc 500s above it. */\nexport const MAX_DOWNLOAD_URL_TTL_SECONDS = 604_800;\n/** Shortest URL lifetime the client will request. */\nexport const MIN_DOWNLOAD_URL_TTL_SECONDS = 60;\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 15_000;\nconst DEFAULT_TRANSFER_TIMEOUT_MS = 120_000;\nconst DEFAULT_MAX_UPLOAD_BYTES = 100 * MIB;\nconst DEFAULT_MAX_DOWNLOAD_BYTES = 25 * MIB;\nconst DEFAULT_DOWNLOAD_URL_TTL_SECONDS = 3_600;\n/** TTL of the URL `downloadFile` mints for its own immediate GET. */\nconst INTERNAL_DOWNLOAD_URL_TTL_SECONDS = 300;\nconst PART_URL_BATCH_SIZE = 20;\nconst SHA256_HEX = /^[0-9a-f]{64}$/;\n\nconst FILE_FIELDS =\n 'id name mimeType extension size status visibility workspaceId folderId uploadedById description sha256Hash createdAt updatedAt canRead canDelete';\n\nconst INITIATE_UPLOAD = `mutation FilesClientInitiateUpload($input: InitiateUploadInput!) {\n initiateUpload(input: $input) {\n uploadUrl\n session { id uploadType partSize totalParts fileSize expiresAt }\n }\n}`;\n\nconst PART_URLS = `query FilesClientPartUploadUrls($sessionId: ID!, $partNumbers: [Int!]!) {\n getBatchPartUploadUrls(sessionId: $sessionId, partNumbers: $partNumbers) { partNumber url }\n}`;\n\nconst REGISTER_PART = `mutation FilesClientRegisterUploadedPart($input: UploadPartInput!) {\n registerUploadedPart(input: $input) { session { id uploadedParts } }\n}`;\n\nconst COMPLETE_UPLOAD = `mutation FilesClientCompleteUpload($input: CompleteUploadInput!) {\n completeUpload(input: $input) { fileId file { id name mimeType size workspaceId sha256Hash } }\n}`;\n\nconst ABORT_UPLOAD = `mutation FilesClientAbortUpload($sessionId: ID!) { abortUpload(sessionId: $sessionId) }`;\n\nconst GET_FILE = `query FilesClientGetFile($id: ID!) { getFile(id: $id) { ${FILE_FIELDS} } }`;\n\nconst GET_DOWNLOAD_URL = `query FilesClientGetFileDownloadUrl($id: ID!, $expiresIn: Int) {\n getFileDownloadUrl(id: $id, expiresIn: $expiresIn)\n}`;\n\nconst RESOLVE_FOR_DOWNLOAD = `query FilesClientResolveForDownload($id: ID!, $expiresIn: Int) {\n getFile(id: $id) { ${FILE_FIELDS} }\n getFileDownloadUrl(id: $id, expiresIn: $expiresIn)\n}`;\n\nconst DELETE_FILE = `mutation FilesClientDeleteFile($id: ID!) { deleteFile(id: $id) }`;\n\nconst PERMANENTLY_DELETE_FILE = `mutation FilesClientPermanentlyDeleteFile($id: ID!) { permanentlyDeleteFile(id: $id) }`;\n\nexport interface FilesClientOptions {\n /**\n * Gateway client, or a factory for one. Defaults to a lazily constructed be-sdk\n * `GatewayClient` (`layer: 'wspace'`, `serviceName` below, or the\n * `SERVICE_LAYER`/`SERVICE_NAME` env when `serviceName` is omitted).\n */\n client?: FilesTransport | (() => FilesTransport | Promise<FilesTransport>);\n /** Service name for the default GatewayClient, e.g. `wspace-vibecontrols-svc`. */\n serviceName?: string;\n /** `fetch` used for the presigned PUT/GET legs. Default: the global `fetch`. */\n fetch?: FilesFetch;\n /** Per-request timeout for files-svc GraphQL calls. Default 15s. */\n requestTimeoutMs?: number;\n /** Per-request timeout for each presigned PUT/GET. Default 120s. */\n transferTimeoutMs?: number;\n /** Largest upload accepted (the bytes are held in memory). Default 100 MiB. */\n maxUploadBytes?: number;\n /** Largest download accepted by `downloadFile`. Default 25 MiB. */\n maxDownloadBytes?: number;\n /** Default `getDownloadUrl` lifetime in seconds. Default 3600. */\n defaultDownloadUrlTtlSeconds?: number;\n}\n\ninterface InitiatedSession {\n id: string;\n uploadType: FileUploadType;\n partSize: number;\n totalParts: number;\n}\n\nfunction requireNonEmpty(value: string | null | undefined, field: string): string {\n const trimmed = typeof value === 'string' ? value.trim() : '';\n if (!trimmed) {\n throw new FilesClientError('INVALID_INPUT', `${field} is required`, { field });\n }\n return trimmed;\n}\n\nfunction requirePositiveInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new FilesClientError('CONFIGURATION_ERROR', `${field} must be a positive integer`, { field, value });\n }\n return value;\n}\n\nfunction toNumber(value: string | number, field: string): number {\n const parsed = typeof value === 'number' ? value : Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc returned an invalid ${field}`, { field, value });\n }\n return parsed;\n}\n\nfunction toDate(value: string | null | undefined): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/** A view over `data` backed by a plain `ArrayBuffer` (what `fetch` bodies accept). */\nfunction toBytes(data: FileBytes): Uint8Array<ArrayBuffer> {\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n const { buffer } = data;\n if (buffer instanceof ArrayBuffer) return new Uint8Array(buffer, data.byteOffset, data.byteLength);\n // SharedArrayBuffer-backed view: copy, since a shared buffer can change under the upload.\n return new Uint8Array(data);\n}\n\n/** Extension for `fileName` (`report.PDF` → `pdf`), or `bin` when it has none. */\nexport function fileExtensionOf(fileName: string): string {\n const base = fileName.trim().split(/[\\\\/]/).pop() ?? '';\n const dot = base.lastIndexOf('.');\n if (dot <= 0 || dot === base.length - 1) return 'bin';\n const extension = base\n .slice(dot + 1)\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '');\n return extension || 'bin';\n}\n\n/** Clamp a requested URL lifetime to what files-svc / S3 accept. */\nexport function clampDownloadUrlTtl(seconds: number | null | undefined, fallback: number): number {\n const value = seconds === null || seconds === undefined || !Number.isFinite(seconds) ? fallback : seconds;\n return Math.min(Math.max(Math.trunc(value), MIN_DOWNLOAD_URL_TTL_SECONDS), MAX_DOWNLOAD_URL_TTL_SECONDS);\n}\n\nfunction isHttpUrl(value: unknown): value is string {\n if (typeof value !== 'string' || value.length === 0) return false;\n try {\n const { protocol } = new URL(value);\n return protocol === 'https:' || protocol === 'http:';\n } catch {\n return false;\n }\n}\n\n/** Lowercase a declared SHA-256 and reject anything that is not 64 hex characters. */\nfunction normalizeSha256(value: string | null | undefined): string | null {\n if (value === null || value === undefined || value.trim() === '') return null;\n const normalized = value.trim().toLowerCase();\n if (!SHA256_HEX.test(normalized)) {\n throw new FilesClientError('INVALID_INPUT', 'sha256Hash must be 64 hex characters', { field: 'sha256Hash' });\n }\n return normalized;\n}\n\n/** Validate MULTIPART part ETags: positive, unique part numbers with a non-empty ETag, sorted. */\nfunction normalizeUploadedParts(parts: readonly UploadedPart[]): UploadedPart[] {\n const seen = new Set<number>();\n const normalized = parts.map((part) => {\n const etag = typeof part.etag === 'string' ? part.etag.trim() : '';\n if (!Number.isSafeInteger(part.partNumber) || part.partNumber <= 0 || seen.has(part.partNumber) || !etag) {\n throw new FilesClientError('INVALID_INPUT', 'parts must have unique positive part numbers and an ETag', {\n field: 'parts',\n partNumber: part.partNumber,\n });\n }\n seen.add(part.partNumber);\n return { partNumber: part.partNumber, etag };\n });\n return normalized.sort((a, b) => a.partNumber - b.partNumber);\n}\n\n/** Map a files-svc `File` selection onto {@link FileMetadata}. */\nexport function mapFileMetadata(raw: RawFileMetadata): FileMetadata {\n return {\n id: raw.id,\n name: raw.name,\n mimeType: raw.mimeType,\n extension: raw.extension,\n size: toNumber(raw.size, 'size'),\n status: raw.status,\n visibility: raw.visibility,\n workspaceId: raw.workspaceId,\n folderId: raw.folderId ?? null,\n uploadedById: raw.uploadedById,\n description: raw.description ?? null,\n sha256Hash: raw.sha256Hash ?? null,\n createdAt: toDate(raw.createdAt),\n updatedAt: toDate(raw.updatedAt),\n canRead: raw.canRead ?? null,\n canDelete: raw.canDelete ?? null,\n };\n}\n\nexport class FilesClient {\n private readonly clientOption: FilesClientOptions['client'];\n private readonly serviceName: string | undefined;\n private readonly fetchImpl: FilesFetch;\n private readonly requestTimeoutMs: number;\n private readonly transferTimeoutMs: number;\n private readonly maxUploadBytes: number;\n private readonly maxDownloadBytes: number;\n private readonly defaultDownloadUrlTtlSeconds: number;\n private clientPromise: Promise<FilesTransport> | null = null;\n\n constructor(options: FilesClientOptions = {}) {\n this.clientOption = options.client;\n this.serviceName = options.serviceName;\n this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));\n this.requestTimeoutMs = requirePositiveInteger(\n options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs'\n );\n this.transferTimeoutMs = requirePositiveInteger(\n options.transferTimeoutMs ?? DEFAULT_TRANSFER_TIMEOUT_MS,\n 'transferTimeoutMs'\n );\n this.maxUploadBytes = requirePositiveInteger(options.maxUploadBytes ?? DEFAULT_MAX_UPLOAD_BYTES, 'maxUploadBytes');\n this.maxDownloadBytes = requirePositiveInteger(\n options.maxDownloadBytes ?? DEFAULT_MAX_DOWNLOAD_BYTES,\n 'maxDownloadBytes'\n );\n const ttl = options.defaultDownloadUrlTtlSeconds ?? DEFAULT_DOWNLOAD_URL_TTL_SECONDS;\n if (!Number.isSafeInteger(ttl) || ttl < MIN_DOWNLOAD_URL_TTL_SECONDS || ttl > MAX_DOWNLOAD_URL_TTL_SECONDS) {\n throw new FilesClientError(\n 'CONFIGURATION_ERROR',\n `defaultDownloadUrlTtlSeconds must be between ${MIN_DOWNLOAD_URL_TTL_SECONDS} and ${MAX_DOWNLOAD_URL_TTL_SECONDS}`,\n { value: ttl }\n );\n }\n this.defaultDownloadUrlTtlSeconds = ttl;\n }\n\n // ── Upload ────────────────────────────────────────────────────────────\n\n /**\n * Store bytes in the actor's workspace file library and return the File's id.\n * Throws {@link FilesClientError}; on any failure after the session was opened\n * the session is aborted so no half-uploaded object is left behind.\n */\n async uploadFile(input: UploadFileInput, actor: FileActor): Promise<StoredFile> {\n const context = this.requireActor(actor);\n const fileName = requireNonEmpty(input.fileName, 'fileName');\n const mimeType = requireNonEmpty(input.mimeType, 'mimeType');\n const bytes = toBytes(input.data);\n if (bytes.byteLength === 0) {\n throw new FilesClientError('INVALID_INPUT', 'data must not be empty', { field: 'data' });\n }\n if (bytes.byteLength > this.maxUploadBytes) {\n throw new FilesClientError('TOO_LARGE', `File is larger than ${this.maxUploadBytes} bytes`, {\n size: bytes.byteLength,\n maxBytes: this.maxUploadBytes,\n });\n }\n if (input.visibility !== undefined && !FILE_VISIBILITIES.includes(input.visibility)) {\n throw new FilesClientError('INVALID_INPUT', `Unknown file visibility \"${String(input.visibility)}\"`, {\n field: 'visibility',\n });\n }\n const extension = input.extension?.trim()\n ? input.extension.trim().replace(/^\\./, '').toLowerCase()\n : fileExtensionOf(fileName);\n // `BigInt` travels as a string, and completeUpload must repeat exactly the value given to initiate.\n const fileSize = String(bytes.byteLength);\n const sha256Hash = input.declareSha256 === false ? null : createHash('sha256').update(bytes).digest('hex');\n const folderId = input.folderId?.trim() || undefined;\n\n const initiated = await this.request<{\n initiateUpload: {\n uploadUrl?: string | null;\n session?: {\n id: string;\n uploadType: FileUploadType;\n partSize: number | string;\n totalParts: number | string;\n } | null;\n } | null;\n }>(\n 'initiateUpload',\n INITIATE_UPLOAD,\n {\n input: {\n fileName,\n fileSize,\n mimeType,\n extension,\n ...(folderId ? { folderId } : {}),\n ...(input.visibility ? { visibility: input.visibility } : {}),\n ...(sha256Hash ? { sha256Hash } : {}),\n },\n },\n context\n );\n const rawSession = initiated.initiateUpload?.session;\n if (!rawSession?.id) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no session');\n }\n const session: InitiatedSession = {\n id: rawSession.id,\n uploadType: rawSession.uploadType,\n partSize: toNumber(rawSession.partSize, 'partSize'),\n totalParts: toNumber(rawSession.totalParts, 'totalParts'),\n };\n\n try {\n if (session.uploadType === 'MULTIPART') {\n await this.uploadParts(session, bytes, context);\n } else {\n await this.putDirect(initiated.initiateUpload?.uploadUrl, bytes, mimeType);\n }\n\n return await this.completeSession(\n session.id,\n {\n fileSize,\n fallbackName: fileName,\n fallbackMimeType: mimeType,\n fallbackSize: bytes.byteLength,\n sha256Hash,\n folderId,\n description: input.description ?? null,\n },\n context\n );\n } catch (error) {\n await this.abortQuietly(session.id, context);\n throw toFilesClientError(error, 'uploadFile');\n }\n }\n\n // ── Delegated upload ──────────────────────────────────────────────────\n\n /**\n * Open a files-svc upload session on the actor's behalf for bytes that\n * someone else holds (an agent, a CLI, a browser), and return the presigned\n * URL(s) to hand them. The uploader PUTs the bytes — one PUT to `uploadUrl`\n * for DIRECT, one PUT per `parts` entry for MULTIPART (files-svc picks\n * MULTIPART above 5 MiB) — and the service then calls\n * {@link completeUploadSession} with the same `fileSize` (and the part ETags)\n * to turn the session into a File. The service never sees the bytes and never\n * holds storage credentials.\n *\n * Throws {@link FilesClientError}. If files-svc opened the session but the\n * client cannot hand it out (an unsupported upload type, missing part URLs),\n * the session is aborted before the error is thrown.\n */\n async createUploadSession(input: CreateUploadSessionInput, actor: FileActor): Promise<UploadSessionTicket> {\n const context = this.requireActor(actor);\n const fileName = requireNonEmpty(input.fileName, 'fileName');\n const mimeType = requireNonEmpty(input.mimeType, 'mimeType');\n if (!Number.isSafeInteger(input.fileSize) || input.fileSize <= 0) {\n throw new FilesClientError('INVALID_INPUT', 'fileSize must be a positive integer', { field: 'fileSize' });\n }\n if (input.fileSize > this.maxUploadBytes) {\n throw new FilesClientError('TOO_LARGE', `File is larger than ${this.maxUploadBytes} bytes`, {\n size: input.fileSize,\n maxBytes: this.maxUploadBytes,\n });\n }\n if (input.visibility !== undefined && !FILE_VISIBILITIES.includes(input.visibility)) {\n throw new FilesClientError('INVALID_INPUT', `Unknown file visibility \"${String(input.visibility)}\"`, {\n field: 'visibility',\n });\n }\n const sha256Hash = normalizeSha256(input.sha256Hash);\n const extension = input.extension?.trim()\n ? input.extension.trim().replace(/^\\./, '').toLowerCase()\n : fileExtensionOf(fileName);\n const folderId = input.folderId?.trim() || undefined;\n\n const initiated = await this.request<{\n initiateUpload: {\n uploadUrl?: string | null;\n session?: {\n id: string;\n uploadType: FileUploadType;\n partSize: number | string;\n totalParts: number | string;\n expiresAt?: string | null;\n } | null;\n } | null;\n }>(\n 'initiateUpload',\n INITIATE_UPLOAD,\n {\n input: {\n fileName,\n fileSize: String(input.fileSize),\n mimeType,\n extension,\n ...(folderId ? { folderId } : {}),\n ...(input.visibility ? { visibility: input.visibility } : {}),\n ...(sha256Hash ? { sha256Hash } : {}),\n },\n },\n context\n );\n const rawSession = initiated.initiateUpload?.session;\n if (!rawSession?.id) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no session');\n }\n\n try {\n const partSize = toNumber(rawSession.partSize, 'partSize');\n const totalParts = toNumber(rawSession.totalParts, 'totalParts');\n const base = {\n sessionId: rawSession.id,\n partSize,\n totalParts,\n fileSize: input.fileSize,\n sha256Hash,\n expiresAt: toDate(rawSession.expiresAt),\n };\n if (rawSession.uploadType === 'MULTIPART') {\n const session: InitiatedSession = { id: rawSession.id, uploadType: 'MULTIPART', partSize, totalParts };\n this.assertMultipartPlan(session, input.fileSize);\n const parts = await this.presignParts(session, input.fileSize, context);\n return { ...base, uploadType: 'MULTIPART', uploadUrl: null, requiredHeaders: {}, parts };\n }\n if (rawSession.uploadType !== 'DIRECT') {\n throw new FilesClientError(\n 'UPSTREAM_ERROR',\n `wspace-files-svc opened an unsupported ${String(rawSession.uploadType)} session`,\n { sessionId: rawSession.id }\n );\n }\n const uploadUrl = initiated.initiateUpload?.uploadUrl;\n if (!isHttpUrl(uploadUrl)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no upload URL', {\n sessionId: rawSession.id,\n });\n }\n return { ...base, uploadType: 'DIRECT', uploadUrl, requiredHeaders: { 'Content-Type': mimeType }, parts: [] };\n } catch (error) {\n await this.abortQuietly(rawSession.id, context);\n throw toFilesClientError(error, 'createUploadSession');\n }\n }\n\n /**\n * Turn a session opened by {@link createUploadSession} into a File once the\n * uploader has PUT the bytes: registers the MULTIPART part ETags, then runs\n * `completeUpload` with the declared size (and SHA-256). files-svc verifies\n * the stored object; a size or checksum mismatch surfaces as `INVALID_INPUT`.\n * The session is left open on failure so the caller can retry or\n * {@link abortUploadSession} it.\n */\n async completeUploadSession(\n sessionId: string,\n input: CompleteUploadSessionInput,\n actor: FileActor\n ): Promise<StoredFile> {\n const context = this.requireActor(actor);\n const id = requireNonEmpty(sessionId, 'sessionId');\n if (!Number.isSafeInteger(input.fileSize) || input.fileSize <= 0) {\n throw new FilesClientError('INVALID_INPUT', 'fileSize must be a positive integer', { field: 'fileSize' });\n }\n const sha256Hash = normalizeSha256(input.sha256Hash);\n const parts = normalizeUploadedParts(input.parts ?? []);\n const folderId = input.folderId?.trim() || undefined;\n\n for (const part of parts) {\n await this.request(\n 'registerUploadedPart',\n REGISTER_PART,\n { input: { sessionId: id, partNumber: part.partNumber, etag: part.etag } },\n context\n );\n }\n return this.completeSession(\n id,\n {\n fileSize: String(input.fileSize),\n fallbackName: '',\n fallbackMimeType: '',\n fallbackSize: input.fileSize,\n sha256Hash,\n folderId,\n description: input.description ?? null,\n },\n context\n );\n }\n\n /** Abandon a session opened by {@link createUploadSession}. `true` when files-svc aborted it. */\n async abortUploadSession(sessionId: string, actor: FileActor): Promise<boolean> {\n const id = requireNonEmpty(sessionId, 'sessionId');\n const data = await this.request<{ abortUpload: boolean | null }>(\n 'abortUpload',\n ABORT_UPLOAD,\n { sessionId: id },\n actor\n );\n return data.abortUpload === true;\n }\n\n // ── Read ──────────────────────────────────────────────────────────────\n\n /** File metadata, or `null` when it does not exist or the actor cannot see it. */\n async getFile(fileId: string, actor: FileActor): Promise<FileMetadata | null> {\n const id = requireNonEmpty(fileId, 'fileId');\n try {\n const data = await this.request<{ getFile: RawFileMetadata | null }>('getFile', GET_FILE, { id }, actor);\n return data.getFile ? mapFileMetadata(data.getFile) : null;\n } catch (error) {\n if (error instanceof FilesClientError && error.code === 'NOT_FOUND') return null;\n throw error;\n }\n }\n\n /**\n * Prove that an opaque file id the caller supplied names a File in the actor's\n * workspace that they may read, before the service stores or acts on it.\n * Throws `NOT_FOUND` (never a permission error) otherwise.\n */\n async requireFile(fileId: string, actor: FileActor, options: RequireFileOptions = {}): Promise<FileMetadata> {\n const context = this.requireActor(actor);\n const file = await this.getFile(fileId, context);\n this.assertUsable(file, fileId, context, options);\n return file;\n }\n\n /**\n * A presigned download URL for the file, minted for the actor. Mint it when the\n * user opens the file; never persist it. The lifetime is clamped to\n * [60, 604800] seconds.\n */\n async getDownloadUrl(fileId: string, actor: FileActor, options: DownloadUrlOptions = {}): Promise<string> {\n const id = requireNonEmpty(fileId, 'fileId');\n const expiresIn = clampDownloadUrlTtl(options.expiresInSeconds, this.defaultDownloadUrlTtlSeconds);\n const data = await this.request<{ getFileDownloadUrl: string | null }>(\n 'getFileDownloadUrl',\n GET_DOWNLOAD_URL,\n { id, expiresIn },\n actor\n );\n if (!isHttpUrl(data.getFileDownloadUrl)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc returned no usable download URL', { fileId: id });\n }\n return data.getFileDownloadUrl;\n }\n\n /**\n * Fetch the file's bytes for server-side processing (vision models, parsers,\n * workflow nodes). Checks the file is active, readable by the actor and within\n * `maxBytes` before downloading, and verifies the downloaded size.\n */\n async downloadFile(fileId: string, actor: FileActor, options: DownloadFileOptions = {}): Promise<DownloadedFile> {\n const context = this.requireActor(actor);\n const id = requireNonEmpty(fileId, 'fileId');\n const maxBytes = options.maxBytes ?? this.maxDownloadBytes;\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new FilesClientError('INVALID_INPUT', 'maxBytes must be a positive integer', { field: 'maxBytes' });\n }\n\n const data = await this.request<{ getFile: RawFileMetadata | null; getFileDownloadUrl: string | null }>(\n 'downloadFile',\n RESOLVE_FOR_DOWNLOAD,\n { id, expiresIn: INTERNAL_DOWNLOAD_URL_TTL_SECONDS },\n context\n );\n const file = data.getFile ? mapFileMetadata(data.getFile) : null;\n this.assertUsable(file, id, context, {});\n if (file.size > maxBytes) {\n throw new FilesClientError('TOO_LARGE', `File is larger than ${maxBytes} bytes`, {\n fileId: id,\n size: file.size,\n maxBytes,\n });\n }\n const url = data.getFileDownloadUrl;\n if (!isHttpUrl(url)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc returned no usable download URL', { fileId: id });\n }\n\n const response = await this.transfer(url, { method: 'GET' }, 'download');\n const bytes = await this.readBounded(response, maxBytes, id);\n if (bytes.byteLength !== file.size) {\n throw new FilesClientError('STORAGE_ERROR', 'Downloaded size does not match the stored file size', {\n fileId: id,\n expected: file.size,\n actual: bytes.byteLength,\n });\n }\n return { bytes, mimeType: file.mimeType, name: file.name, size: bytes.byteLength };\n }\n\n /** {@link downloadFile} as base64, for payloads that must stay JSON (model inputs). */\n async downloadFileAsBase64(\n fileId: string,\n actor: FileActor,\n options: DownloadFileOptions = {}\n ): Promise<{ base64: string; mimeType: string; name: string; size: number }> {\n const file = await this.downloadFile(fileId, actor, options);\n return {\n base64: Buffer.from(file.bytes).toString('base64'),\n mimeType: file.mimeType,\n name: file.name,\n size: file.size,\n };\n }\n\n // ── Delete ────────────────────────────────────────────────────────────\n\n /** Move the file to trash (or hard-delete with `permanent`). `true` when files-svc deleted it. */\n async deleteFile(fileId: string, actor: FileActor, options: DeleteFileOptions = {}): Promise<boolean> {\n const id = requireNonEmpty(fileId, 'fileId');\n if (options.permanent) {\n const data = await this.request<{ permanentlyDeleteFile: boolean | null }>(\n 'permanentlyDeleteFile',\n PERMANENTLY_DELETE_FILE,\n { id },\n actor\n );\n return data.permanentlyDeleteFile === true;\n }\n const data = await this.request<{ deleteFile: boolean | null }>('deleteFile', DELETE_FILE, { id }, actor);\n return data.deleteFile === true;\n }\n\n // ── Upload legs ───────────────────────────────────────────────────────\n\n private async putDirect(\n uploadUrl: string | null | undefined,\n bytes: Uint8Array<ArrayBuffer>,\n mimeType: string\n ): Promise<void> {\n if (!isHttpUrl(uploadUrl)) {\n // files-svc returns a DIRECT uploadUrl for every non-multipart session; its absence\n // means the storage provider is misconfigured, not that a fallback is wanted.\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no upload URL');\n }\n // The presigned PUT is signed for this Content-Type, so it must match what initiate declared.\n await this.transfer(uploadUrl, { method: 'PUT', body: bytes, headers: { 'Content-Type': mimeType } }, 'upload');\n }\n\n private async uploadParts(\n session: InitiatedSession,\n bytes: Uint8Array<ArrayBuffer>,\n actor: FileActor\n ): Promise<void> {\n this.assertMultipartPlan(session, bytes.byteLength);\n\n for (let first = 1; first <= session.totalParts; first += PART_URL_BATCH_SIZE) {\n const partNumbers: number[] = [];\n for (let part = first; part < first + PART_URL_BATCH_SIZE && part <= session.totalParts; part += 1) {\n partNumbers.push(part);\n }\n const data = await this.request<{ getBatchPartUploadUrls: Array<{ partNumber: number; url: string }> | null }>(\n 'getBatchPartUploadUrls',\n PART_URLS,\n { sessionId: session.id, partNumbers },\n actor\n );\n const urls = new Map((data.getBatchPartUploadUrls ?? []).map((entry) => [entry.partNumber, entry.url]));\n\n for (const partNumber of partNumbers) {\n const url = urls.get(partNumber);\n if (!isHttpUrl(url)) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc returned no URL for part ${partNumber}`, {\n sessionId: session.id,\n partNumber,\n });\n }\n const start = (partNumber - 1) * session.partSize;\n const body = bytes.subarray(start, Math.min(start + session.partSize, bytes.byteLength));\n const response = await this.transfer(url, { method: 'PUT', body }, 'upload');\n const etag = response.headers.get('etag');\n if (!etag) {\n throw new FilesClientError('STORAGE_ERROR', `Object storage returned no ETag for part ${partNumber}`, {\n sessionId: session.id,\n partNumber,\n });\n }\n await this.request(\n 'registerUploadedPart',\n REGISTER_PART,\n { input: { sessionId: session.id, partNumber, etag } },\n actor\n );\n }\n }\n }\n\n private async completeSession(\n sessionId: string,\n args: {\n fileSize: string;\n fallbackName: string;\n fallbackMimeType: string;\n fallbackSize: number;\n sha256Hash: string | null;\n folderId: string | undefined;\n description: string | null;\n },\n actor: FileActor\n ): Promise<StoredFile> {\n const completed = await this.request<{\n completeUpload: {\n fileId?: string | null;\n file?: {\n id: string;\n name: string;\n mimeType: string;\n size: string | number;\n workspaceId: string;\n sha256Hash?: string | null;\n } | null;\n } | null;\n }>(\n 'completeUpload',\n COMPLETE_UPLOAD,\n {\n input: {\n sessionId,\n fileSize: args.fileSize,\n ...(args.folderId ? { folderId: args.folderId } : {}),\n ...(args.description ? { description: args.description } : {}),\n ...(args.sha256Hash ? { sha256Hash: args.sha256Hash } : {}),\n },\n },\n actor\n );\n const file = completed.completeUpload?.file;\n const fileId = completed.completeUpload?.fileId ?? file?.id;\n if (!fileId) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc completeUpload returned no fileId', {\n sessionId,\n });\n }\n return {\n fileId,\n name: file?.name ?? args.fallbackName,\n mimeType: file?.mimeType ?? args.fallbackMimeType,\n size: file ? toNumber(file.size, 'size') : args.fallbackSize,\n workspaceId: file?.workspaceId ?? actor.workspaceId,\n sha256Hash: file?.sha256Hash ?? args.sha256Hash,\n };\n }\n\n private assertMultipartPlan(session: InitiatedSession, size: number): void {\n if (session.partSize <= 0 || session.totalParts !== Math.ceil(size / session.partSize)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc returned an inconsistent multipart plan', {\n sessionId: session.id,\n partSize: session.partSize,\n totalParts: session.totalParts,\n size,\n });\n }\n }\n\n /** Presigned URL for every part, fetched in batches. */\n private async partUrls(session: InitiatedSession, actor: FileActor): Promise<Map<number, string>> {\n const urls = new Map<number, string>();\n for (let first = 1; first <= session.totalParts; first += PART_URL_BATCH_SIZE) {\n const partNumbers: number[] = [];\n for (let part = first; part < first + PART_URL_BATCH_SIZE && part <= session.totalParts; part += 1) {\n partNumbers.push(part);\n }\n const data = await this.request<{ getBatchPartUploadUrls: Array<{ partNumber: number; url: string }> | null }>(\n 'getBatchPartUploadUrls',\n PART_URLS,\n { sessionId: session.id, partNumbers },\n actor\n );\n for (const entry of data.getBatchPartUploadUrls ?? []) urls.set(entry.partNumber, entry.url);\n }\n return urls;\n }\n\n private async presignParts(session: InitiatedSession, size: number, actor: FileActor): Promise<UploadSessionPart[]> {\n const urls = await this.partUrls(session, actor);\n const parts: UploadSessionPart[] = [];\n for (let partNumber = 1; partNumber <= session.totalParts; partNumber += 1) {\n const url = urls.get(partNumber);\n if (!isHttpUrl(url)) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc returned no URL for part ${partNumber}`, {\n sessionId: session.id,\n partNumber,\n });\n }\n const offset = (partNumber - 1) * session.partSize;\n parts.push({\n partNumber,\n url,\n offset,\n length: Math.min(session.partSize, size - offset),\n });\n }\n return parts;\n }\n\n private async abortQuietly(sessionId: string, actor: FileActor): Promise<void> {\n try {\n await this.request('abortUpload', ABORT_UPLOAD, { sessionId }, actor);\n } catch {\n // Best effort: files-svc's upload reaper expires abandoned sessions anyway, and the\n // original failure is what the caller needs to see.\n }\n }\n\n // ── Transport ─────────────────────────────────────────────────────────\n\n private assertUsable(\n file: FileMetadata | null,\n fileId: string,\n actor: FileActor,\n options: RequireFileOptions\n ): asserts file is FileMetadata {\n const requireActive = options.requireActive ?? true;\n const requireReadable = options.requireReadable ?? true;\n if (\n !file ||\n file.id !== fileId.trim() ||\n file.workspaceId !== actor.workspaceId ||\n (requireActive && file.status !== 'ACTIVE') ||\n (requireReadable && file.canRead !== true)\n ) {\n throw new FilesClientError('NOT_FOUND', 'File not found', { fileId });\n }\n }\n\n private async transfer(url: string, init: RequestInit, leg: 'upload' | 'download'): Promise<Response> {\n let response: Response;\n try {\n response = await this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(this.transferTimeoutMs) });\n } catch (error) {\n throw new FilesClientError('STORAGE_ERROR', `Object storage ${leg} failed`, {\n leg,\n cause: error instanceof Error ? error.message : String(error),\n });\n }\n if (!response.ok) {\n throw new FilesClientError('STORAGE_ERROR', `Object storage ${leg} failed with HTTP ${response.status}`, {\n leg,\n status: response.status,\n });\n }\n return response;\n }\n\n private async readBounded(response: Response, maxBytes: number, fileId: string): Promise<Uint8Array> {\n const tooLarge = (): FilesClientError =>\n new FilesClientError('TOO_LARGE', `File is larger than ${maxBytes} bytes`, { fileId, maxBytes });\n\n const declared = Number(response.headers.get('content-length') ?? Number.NaN);\n if (Number.isFinite(declared) && declared > maxBytes) throw tooLarge();\n if (!response.body) {\n const buffer = new Uint8Array(await response.arrayBuffer());\n if (buffer.byteLength > maxBytes) throw tooLarge();\n return buffer;\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw tooLarge();\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n }\n\n private requireActor(actor: FileActor): FileActor {\n if (!actor.actorId?.trim() || !actor.workspaceId?.trim()) {\n throw new FilesClientError('MISSING_CONTEXT', 'File operations need an authenticated actor and a workspace');\n }\n if (actor.actorType !== undefined && !FILE_ACTOR_TYPES.includes(actor.actorType)) {\n throw new FilesClientError('MISSING_CONTEXT', `Unknown actor type \"${String(actor.actorType)}\"`);\n }\n return actor;\n }\n\n private getClient(): Promise<FilesTransport> {\n if (!this.clientPromise) {\n const option = this.clientOption;\n this.clientPromise = (async (): Promise<FilesTransport> => {\n try {\n if (typeof option === 'function') return await option();\n if (option) return option;\n // Dynamic import keeps the gateway client (and its JWT/crypto deps) out of\n // the static module graph of `@burdenoff/be-sdk/files` consumers.\n const gateway = await import('../gateway/client.js');\n if (this.serviceName) {\n return new gateway.GatewayClient({\n layer: 'wspace',\n serviceName: this.serviceName,\n serviceIdentity: this.serviceName,\n });\n }\n return gateway.createGatewayClientFromEnv();\n } catch (error) {\n throw new FilesClientError('CONFIGURATION_ERROR', 'Files gateway client is not configured', {\n cause: error instanceof Error ? error.message : String(error),\n });\n }\n })();\n // A failed construction (bad env) must not be cached forever.\n this.clientPromise.catch(() => {\n this.clientPromise = null;\n });\n }\n return this.clientPromise;\n }\n\n private async request<T>(\n operation: string,\n query: string,\n variables: Record<string, unknown>,\n actor: FileActor\n ): Promise<T> {\n const { actorId, workspaceId, actorType } = this.requireActor(actor);\n const client = await this.getClient();\n let response: GraphQLResponse<T>;\n try {\n response = await client.internalQuery<T>({\n query,\n variables,\n timeout: this.requestTimeoutMs,\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType ?? 'user',\n 'x-workspace-id': workspaceId,\n },\n });\n } catch (error) {\n throw toFilesClientError(error, operation);\n }\n if (response.errors?.length) {\n throw new FilesClientError(classifyFilesErrors(response.errors), `wspace-files-svc ${operation} failed`, {\n operation,\n errors: response.errors.map((error) => ({ message: error.message, code: error.extensions?.['code'] ?? null })),\n });\n }\n if (!response.data) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc ${operation} returned no data`, { operation });\n }\n return response.data;\n }\n}\n","/**\n * File references — the binary-data shape that travels instead of inline bytes.\n *\n * Workflow node outputs, attachments and evidence records should carry a small,\n * JSON-safe pointer to a wspace-files-svc File rather than a base64 payload: the\n * bytes stay in the workspace file library (quota-tracked, permission-checked),\n * and whoever needs them resolves the pointer with `FilesClient.downloadFile` or\n * `FilesClient.getDownloadUrl` on behalf of the current actor.\n */\nimport type { FileMetadata, StoredFile } from './types.js';\n\n/** Discriminator value of {@link FileReference.kind}. */\nexport const FILE_REFERENCE_KIND = 'burdenoff.file' as const;\n\n/** JSON-safe pointer to a File owned by wspace-files-svc. */\nexport interface FileReference {\n kind: typeof FILE_REFERENCE_KIND;\n fileId: string;\n name: string;\n mimeType: string;\n /** Size in bytes. */\n size: number;\n /** Lowercase hex SHA-256 when known. */\n sha256Hash: string | null;\n}\n\n/** Build a {@link FileReference} from an upload result or file metadata. */\nexport function toFileReference(file: StoredFile | FileMetadata): FileReference {\n return {\n kind: FILE_REFERENCE_KIND,\n fileId: 'fileId' in file ? file.fileId : file.id,\n name: file.name,\n mimeType: file.mimeType,\n size: file.size,\n sha256Hash: file.sha256Hash,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Type guard for a {@link FileReference} read back from JSON (node output, DB column, …). */\nexport function isFileReference(value: unknown): value is FileReference {\n if (!isRecord(value)) return false;\n const size = value['size'];\n const sha256Hash = value['sha256Hash'];\n return (\n value['kind'] === FILE_REFERENCE_KIND &&\n typeof value['fileId'] === 'string' &&\n value['fileId'].length > 0 &&\n typeof value['name'] === 'string' &&\n typeof value['mimeType'] === 'string' &&\n typeof size === 'number' &&\n Number.isSafeInteger(size) &&\n size >= 0 &&\n (sha256Hash === null || sha256Hash === undefined || typeof sha256Hash === 'string')\n );\n}\n","/**\n * @burdenoff/be-sdk/files\n *\n * Shared client for workspace blobs owned by wspace-files-svc. Services hand it\n * bytes and keep the opaque `fileId`; they never presign object storage or hold\n * storage credentials themselves.\n *\n * - {@link FilesClient} — upload (DIRECT and MULTIPART, size + SHA-256 declared),\n * metadata, reference validation, short-lived download URLs, bounded byte\n * downloads and delete, all on behalf of the calling actor over the internal\n * workspace gateway. Delegated uploads (`createUploadSession` →\n * `completeUploadSession`) hand presigned URLs to whoever holds the bytes.\n * - {@link FileReference} — the JSON-safe pointer that node outputs, attachments\n * and evidence rows carry instead of inline base64.\n *\n * @example\n * ```ts\n * import { FilesClient, toFileReference } from '@burdenoff/be-sdk/files';\n *\n * const files = new FilesClient({ serviceName: 'wspace-workflow-svc' });\n * const stored = await files.uploadFile({ fileName: 'invoice.pdf', data, mimeType: 'application/pdf' }, actor);\n * return { attachment: toFileReference(stored) };\n * ```\n */\n\nexport {\n FILE_ACTOR_TYPES,\n FILE_VISIBILITIES,\n type CompleteUploadSessionInput,\n type CreateUploadSessionInput,\n type DeleteFileOptions,\n type DownloadFileOptions,\n type DownloadUrlOptions,\n type DownloadedFile,\n type FileActor,\n type FileActorType,\n type FileBytes,\n type FileMetadata,\n type FileStatus,\n type FileUploadType,\n type FileVisibility,\n type FilesFetch,\n type FilesTransport,\n type RawFileMetadata,\n type RequireFileOptions,\n type StoredFile,\n type UploadFileInput,\n type UploadSessionPart,\n type UploadSessionTicket,\n type UploadedPart,\n} from './types.js';\n\nexport {\n FILES_CLIENT_GRAPHQL_CODES,\n FilesClientError,\n classifyFilesErrors,\n isFilesClientError,\n toFilesClientError,\n type FilesClientErrorCode,\n} from './errors.js';\n\nexport {\n FilesClient,\n MAX_DOWNLOAD_URL_TTL_SECONDS,\n MIN_DOWNLOAD_URL_TTL_SECONDS,\n clampDownloadUrlTtl,\n fileExtensionOf,\n mapFileMetadata,\n type FilesClientOptions,\n} from './client.js';\n\nexport { FILE_REFERENCE_KIND, isFileReference, toFileReference, type FileReference } from './reference.js';\n"],"mappings":";;;;;;AAYA,MAAa,mBAAmB;CAAC;CAAQ;CAAO;CAAW;AAAa;;AAuBxE,MAAa,oBAAoB;CAAC;CAAW;CAAU;CAAQ;AAAW;;;;;;;;;;;;ACN1E,MAAa,6BAAmE;CAC9E,eAAe;CACf,iBAAiB;CAEjB,WAAW;CACX,gBAAgB;CAChB,WAAW;CACX,eAAe;CACf,gBAAgB;CAChB,qBAAqB;AACvB;AAEA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,AAAS;CACT,AAAS;CAET,YAAY,MAA4B,SAAiB,UAAmC,CAAC,GAAG;EAC9F,MAAM,OAA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OAAO,MAAM,YAAY,YACzB,OAAO,MAAM,gBAAgB,YAC7B,OAAO,SAAS,YAChB,OAAO,cAAc,IAAI,KACzB,QAAQ,MACP,eAAe,QAAQ,eAAe,UAAa,OAAO,eAAe;AAE9E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sdk-7TBR987n.js","names":[],"sources":["../src/telemetry/instrumentations.ts","../src/telemetry/sdk.ts"],"sourcesContent":["/**\n * Which OpenTelemetry instrumentations `createOtelSdk` registers (BOFF-16818).\n *\n * `@opentelemetry/auto-instrumentations-node` imports every one of its ~39\n * bundled instrumentation packages as soon as it is loaded, whether or not a\n * service uses the library behind it, and each registers a module-load hook.\n * In a Bun GraphQL subgraph that costs about 13 MiB of RSS and 0.5–1.5 s of\n * start-up CPU for instrumentations that never produce a span. The fleet's\n * traces come from a short list of libraries, so by default be-sdk imports\n * only those packages, one by one, and never loads the meta package.\n *\n * Selection (first match wins):\n * 1. `BOFF_OTEL_INSTRUMENTATIONS=auto` → the full auto-instrumentations set.\n * 2. `BOFF_OTEL_INSTRUMENTATIONS=<comma list>` (`http,pg,…`) → exactly those.\n * 3. `OTEL_NODE_ENABLED_INSTRUMENTATIONS` or `OTEL_NODE_DISABLED_INSTRUMENTATIONS`\n * set → the full set, filtered by those standard variables as before.\n * 4. The caller injected `@opentelemetry/auto-instrumentations-node` through\n * `OtelSdkConfig.modules` (a `bun build --compile` binary that has no\n * `node_modules`) → the full set, as before.\n * 5. Otherwise → `DEFAULT_INSTRUMENTATIONS`.\n *\n * When none of the explicit packages can be loaded (a service that installs\n * only the meta package under an isolated linker), `createOtelSdk` falls back to\n * the full set, so a service never ends up with no instrumentation at all.\n */\n\n/** The env var that picks the instrumentation set (`auto` or a comma-separated list). */\nexport const INSTRUMENTATIONS_ENV = 'BOFF_OTEL_INSTRUMENTATIONS';\n\n/**\n * The libraries the fleet's traces and dashboards come from: outbound HTTP\n * (`http`, `undici` for `fetch`), Postgres through the Prisma pg adapter,\n * Redis/Valkey clients, GraphQL execution, pino log correlation, the AWS SDK\n * and DataLoader batches.\n */\nexport const DEFAULT_INSTRUMENTATIONS: readonly string[] = [\n 'http',\n 'undici',\n 'pg',\n 'ioredis',\n 'redis',\n 'graphql',\n 'pino',\n 'aws-sdk',\n 'dataloader',\n];\n\n/**\n * Export names that do not follow `<Pascal name>Instrumentation`. Any other\n * package is read through the first export whose name ends in `Instrumentation`.\n */\nconst EXPORT_NAMES: Readonly<Record<string, string>> = {\n http: 'HttpInstrumentation',\n undici: 'UndiciInstrumentation',\n pg: 'PgInstrumentation',\n ioredis: 'IORedisInstrumentation',\n redis: 'RedisInstrumentation',\n graphql: 'GraphQLInstrumentation',\n pino: 'PinoInstrumentation',\n 'aws-sdk': 'AwsInstrumentation',\n dataloader: 'DataloaderInstrumentation',\n};\n\n/** The package that holds the instrumentation called `name` (`pg` → `@opentelemetry/instrumentation-pg`). */\nexport const instrumentationPackage = (name: string): string => `@opentelemetry/instrumentation-${name}`;\n\nexport type InstrumentationPlan =\n { mode: 'auto'; reason: string } | { mode: 'explicit'; names: string[]; reason: string };\n\nconst parseList = (value: string): string[] => [\n ...new Set(\n value\n .split(',')\n .map((entry) => entry.trim().toLowerCase())\n .filter((entry) => entry.length > 0)\n ),\n];\n\nconst isSet = (value: string | undefined): boolean => value !== undefined && value.trim().length > 0;\n\n/** Decides between the full auto-instrumentations set and an explicit list (see the module comment). */\nexport function planInstrumentations(\n env: Readonly<Record<string, string | undefined>> = process.env,\n autoInjected = false\n): InstrumentationPlan {\n const raw = env[INSTRUMENTATIONS_ENV]?.trim() ?? '';\n if (raw.toLowerCase() === 'auto') return { mode: 'auto', reason: `${INSTRUMENTATIONS_ENV}=auto` };\n if (raw.length > 0) {\n const names = parseList(raw);\n if (names.length > 0) return { mode: 'explicit', names, reason: INSTRUMENTATIONS_ENV };\n }\n if (isSet(env['OTEL_NODE_ENABLED_INSTRUMENTATIONS']) || isSet(env['OTEL_NODE_DISABLED_INSTRUMENTATIONS'])) {\n return { mode: 'auto', reason: 'OTEL_NODE_{ENABLED,DISABLED}_INSTRUMENTATIONS is set' };\n }\n if (autoInjected) return { mode: 'auto', reason: 'auto-instrumentations-node was injected' };\n return { mode: 'explicit', names: [...DEFAULT_INSTRUMENTATIONS], reason: 'default list' };\n}\n\ntype InstrumentationClass = new (config?: Record<string, unknown>) => unknown;\n\n/** The instrumentation class a loaded package exports, or undefined when there is none. */\nexport function instrumentationClass(name: string, mod: unknown): InstrumentationClass | undefined {\n if (typeof mod !== 'object' || mod === null) return undefined;\n const exports = mod as Record<string, unknown>;\n const known = EXPORT_NAMES[name];\n const candidate =\n known !== undefined\n ? exports[known]\n : Object.entries(exports).find(\n ([key, value]) => key.endsWith('Instrumentation') && typeof value === 'function'\n )?.[1];\n // A class is a function at runtime; it is only ever called with `new` below.\n return typeof candidate === 'function' ? (candidate as InstrumentationClass) : undefined;\n}\n\nexport interface ExplicitInstrumentations {\n instances: unknown[];\n loaded: string[];\n /** `name: reason` for each instrumentation that could not be loaded or built. */\n missing: string[];\n}\n\n/**\n * Imports and instantiates each named instrumentation. A package that is not\n * installed or does not export an instrumentation is skipped and reported,\n * never fatal.\n */\nexport async function loadExplicitInstrumentations(\n names: readonly string[],\n load: (specifier: string) => Promise<unknown>\n): Promise<ExplicitInstrumentations> {\n const result: ExplicitInstrumentations = { instances: [], loaded: [], missing: [] };\n for (const name of names) {\n try {\n const Instrumentation = instrumentationClass(name, await load(instrumentationPackage(name)));\n if (Instrumentation === undefined) {\n result.missing.push(`${name}: no instrumentation export`);\n continue;\n }\n result.instances.push(new Instrumentation());\n result.loaded.push(name);\n } catch (error) {\n result.missing.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return result;\n}\n","/**\n * Thin wrapper that initializes `@opentelemetry/sdk-node` with the\n * OTLPTrace + OTLPMetric exporters and standard auto-instrumentations.\n *\n * All imports are dynamic so services that haven't installed sdk-node\n * still compile and run. The function resolves `undefined` when the SDK\n * isn't available, letting `bootstrapTelemetry` fall back gracefully.\n */\nimport { importOptionalPeer } from '../utils/import-optional-peer.js';\nimport { isBunRuntime } from './bun-runtime-metrics.js';\nimport type { TelemetryIdGenerator } from './id-generator.js';\nimport type { Boundary, Env } from './index.js';\nimport { loadExplicitInstrumentations, planInstrumentations } from './instrumentations.js';\n\nexport interface OtelSdkConfig {\n serviceName: string;\n serviceVersion: string;\n boundary: Boundary;\n module?: string;\n env: Env;\n otlpEndpoint: string;\n sampleRatio: number;\n /**\n * Optional trace/span id generator handed to NodeSDK's tracer provider.\n * Omitted means the SDK's default random generator.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name. A package found\n * here is used as is; any other one is loaded at runtime from the consumer's\n * `node_modules` through `importOptionalPeer`. A service built with\n * `bun build --compile` has no `node_modules` at runtime, so it imports the\n * packages statically and hands them in here.\n */\n modules?: OtelModules;\n}\n\n/** The OpenTelemetry packages `createOtelSdk` can load. */\nexport type OtelPeerPackage =\n | '@opentelemetry/api'\n | '@opentelemetry/auto-instrumentations-node'\n | '@opentelemetry/exporter-metrics-otlp-http'\n | '@opentelemetry/exporter-trace-otlp-http'\n | '@opentelemetry/resources'\n | '@opentelemetry/sdk-metrics'\n | '@opentelemetry/sdk-node'\n | '@opentelemetry/sdk-trace-base'\n | '@opentelemetry/semantic-conventions';\n\n/**\n * Module namespaces injected in place of runtime imports (see `OtelSdkConfig.modules`).\n * Single instrumentation packages (`@opentelemetry/instrumentation-pg`) can be\n * injected too; they are used when be-sdk registers its explicit list\n * (`./instrumentations.ts`).\n */\nexport type OtelModules = Partial<Record<OtelPeerPackage | InstrumentationPackage, unknown>>;\n\n/** A single OpenTelemetry instrumentation package. */\nexport type InstrumentationPackage = `@opentelemetry/instrumentation-${string}`;\n\nexport interface OtelSdkHandle {\n shutdown: () => Promise<void>;\n metricsEnabled: boolean;\n metricsDropReason?: string;\n /**\n * Where the configured ratio sampler came from, or `undefined` when no\n * sampler could be built and NodeSDK fell back to its own default sampler.\n */\n samplerSource?: SamplerSource;\n}\n\n/** The module a ratio sampler was built from (see `resolveSampler`). */\nexport type SamplerSource =\n 'injected @opentelemetry/sdk-trace-base' | '@opentelemetry/sdk-node tracing' | '@opentelemetry/sdk-trace-base';\n\ninterface SamplerModule {\n ParentBasedSampler: new (init: Record<string, unknown>) => unknown;\n TraceIdRatioBasedSampler: new (ratio: number) => unknown;\n}\n\nconst isSamplerModule = (mod: unknown): mod is SamplerModule => {\n if (typeof mod !== 'object' || mod === null) return false;\n const candidate = mod as Partial<Record<keyof SamplerModule, unknown>>;\n return typeof candidate.ParentBasedSampler === 'function' && typeof candidate.TraceIdRatioBasedSampler === 'function';\n};\n\nexport interface ResolveSamplerInput {\n /** The loaded `@opentelemetry/sdk-node` namespace. */\n sdkNode: unknown;\n /** An `@opentelemetry/sdk-trace-base` namespace passed in through `OtelSdkConfig.modules`. */\n injectedTraceBase?: unknown;\n /** Loads `@opentelemetry/sdk-trace-base` from the consumer's `node_modules`. */\n loadTraceBase: () => Promise<unknown>;\n sampleRatio: number;\n}\n\nexport interface ResolveSamplerResult {\n sampler: unknown;\n source?: SamplerSource;\n /** One entry per candidate that was missing or could not build a sampler. */\n failures: string[];\n}\n\nconst describeError = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * Builds `ParentBasedSampler(TraceIdRatioBasedSampler(ratio))`.\n *\n * Candidates, first that works wins:\n * 1. an `@opentelemetry/sdk-trace-base` namespace the caller injected;\n * 2. the `tracing` namespace `@opentelemetry/sdk-node` re-exports. It is the\n * sdk-trace copy NodeSDK itself was built against, so its\n * `@opentelemetry/core` always matches;\n * 3. the consumer's top-level `@opentelemetry/sdk-trace-base`.\n *\n * Candidate 3 alone used to be the only path. Services that also depend on\n * `@envelop/opentelemetry` (which asks for sdk-trace-base `^1.11.0`) get the\n * 1.x copy hoisted to the top level, and with `@opentelemetry/core` pinned to\n * 2.x that copy throws at load time (`TracesSamplerValues` is undefined). The\n * configured ratio was then ignored silently (CORE-48).\n *\n * Each candidate is constructed inside its own try, because a module can load\n * and still fail when its classes are instantiated.\n */\nexport async function resolveSampler(input: ResolveSamplerInput): Promise<ResolveSamplerResult> {\n const ratio = Math.min(1, Math.max(0, input.sampleRatio));\n const failures: string[] = [];\n const build = (mod: SamplerModule): unknown =>\n new mod.ParentBasedSampler({ root: new mod.TraceIdRatioBasedSampler(ratio) });\n\n const candidates: Array<{ source: SamplerSource; get: () => unknown }> = [];\n if (input.injectedTraceBase !== undefined) {\n candidates.push({ source: 'injected @opentelemetry/sdk-trace-base', get: () => input.injectedTraceBase });\n }\n candidates.push({\n source: '@opentelemetry/sdk-node tracing',\n get: () => (input.sdkNode as { tracing?: unknown } | null | undefined)?.tracing,\n });\n candidates.push({ source: '@opentelemetry/sdk-trace-base', get: input.loadTraceBase });\n\n for (const candidate of candidates) {\n try {\n const mod = await candidate.get();\n if (!isSamplerModule(mod)) {\n failures.push(`${candidate.source}: no ParentBasedSampler/TraceIdRatioBasedSampler export`);\n continue;\n }\n return { sampler: build(mod), source: candidate.source, failures };\n } catch (error) {\n failures.push(`${candidate.source}: ${describeError(error)}`);\n }\n }\n return { sampler: undefined, failures };\n}\n\n/** Per-instrumentation config handed to `getNodeAutoInstrumentations`, keyed by package name. */\nexport type AutoInstrumentationConfig = Record<string, { enabled: boolean }>;\n\n/** The name `OTEL_NODE_{ENABLED,DISABLED}_INSTRUMENTATIONS` use for `@opentelemetry/instrumentation-runtime-node`. */\nconst RUNTIME_NODE_INSTRUMENTATION = 'runtime-node';\n\n/** True when a comma-separated `OTEL_NODE_*_INSTRUMENTATIONS` value names `name` (parsed as auto-instrumentations-node does). */\nconst listsInstrumentation = (value: string | undefined, name: string): boolean =>\n value !== undefined && value.split(',').some((entry) => entry.trim() === name);\n\n/**\n * The config be-sdk hands to `getNodeAutoInstrumentations`.\n *\n * - `instrumentation-fs` is always off.\n * - `instrumentation-runtime-node` is off under Bun unless\n * `OTEL_NODE_ENABLED_INSTRUMENTATIONS` names `runtime-node` (BOFF-12287). On\n * every 60 s OTLP metric export it reads `v8.getHeapSpaceStatistics()`,\n * which Bun implements as a synchronous walk of the whole heap: a 0.1–1.4 s\n * block once a minute on the prod gateways, during which no request is\n * served. Event-loop lag stays visible through prom-client's\n * `nodejs_eventloop_lag_*`. Dropped: the OTel `v8js_*`,\n * `nodejs_eventloop_delay_*`, `nodejs_eventloop_utilization_*` and\n * `nodejs_eventloop_time_*` series, which no dashboard or alert reads.\n *\n * auto-instrumentations-node lets a programmatic `enabled: false` win over\n * both env vars, so the opt-in has to be checked here. Under Node nothing\n * changes: the env vars keep their usual meaning.\n */\nexport function autoInstrumentationConfig(\n env: Readonly<Record<string, string | undefined>> = process.env,\n bun: boolean = isBunRuntime()\n): AutoInstrumentationConfig {\n const config: AutoInstrumentationConfig = {\n '@opentelemetry/instrumentation-fs': { enabled: false },\n };\n if (bun && !listsInstrumentation(env['OTEL_NODE_ENABLED_INSTRUMENTATIONS'], RUNTIME_NODE_INSTRUMENTATION)) {\n config['@opentelemetry/instrumentation-runtime-node'] = { enabled: false };\n }\n return config;\n}\n\ntype Thenable = {\n then: (onfulfilled?: (value: void) => void, onrejected?: (reason: unknown) => void) => unknown;\n};\n\nconst isThenable = (value: unknown): value is Thenable => {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n};\n\nconst asyncDisposeMetricReader = async (metricReaderCandidate: unknown): Promise<void> => {\n const shutdown = (metricReaderCandidate as { shutdown?: () => void | Promise<void> }).shutdown;\n if (typeof shutdown === 'function') {\n const result = shutdown.call(metricReaderCandidate) as unknown;\n if (isThenable(result)) await result;\n }\n};\n\nexport async function createOtelSdk(cfg: OtelSdkConfig): Promise<OtelSdkHandle> {\n const load = (name: OtelPeerPackage): Promise<unknown> =>\n cfg.modules?.[name] !== undefined ? Promise.resolve(cfg.modules[name]) : importOptionalPeer(name);\n console.log('[sdk] importing @opentelemetry/sdk-node...');\n const sdkMod = (await load('@opentelemetry/sdk-node')) as {\n NodeSDK: new (init: Record<string, unknown>) => {\n start: () => void;\n shutdown: () => Promise<void>;\n };\n };\n\n console.log('[sdk] importing @opentelemetry/resources...');\n const resources = (await load('@opentelemetry/resources')) as {\n resourceFromAttributes: (attrs: Record<string, string | number>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/semantic-conventions...');\n const sem = (await load('@opentelemetry/semantic-conventions')) as Record<string, string>;\n\n console.log('[sdk] importing @opentelemetry/exporter-trace-otlp-http...');\n const traceExp = (await load('@opentelemetry/exporter-trace-otlp-http')) as {\n OTLPTraceExporter: new (init: Record<string, string>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/exporter-metrics-otlp-http...');\n let metricsExp: { OTLPMetricExporter?: new (init: Record<string, string>) => unknown } | undefined;\n try {\n metricsExp = (await load('@opentelemetry/exporter-metrics-otlp-http')) as typeof metricsExp;\n } catch {\n metricsExp = undefined;\n console.log('[sdk] metrics exporter not available (non-fatal)');\n }\n\n let metricReader: unknown;\n let metricsEnabled = false;\n let metricsDropReason: string | undefined;\n if (metricsExp?.OTLPMetricExporter) {\n try {\n const metricsSdk = (await load('@opentelemetry/sdk-metrics')) as {\n PeriodicExportingMetricReader: new (init: Record<string, unknown>) => unknown;\n };\n const candidate = new metricsSdk.PeriodicExportingMetricReader({\n exporter: new metricsExp.OTLPMetricExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/metrics`,\n }),\n });\n // Pre-flight API compatibility check. Some OTel package version\n // combinations construct `PeriodicExportingMetricReader` successfully\n // but lack `setMetricProducer` on the prototype chain (mixed\n // sdk-metrics versions, or runtime-specific class-inheritance\n // quirks — Bun has surfaced this in the past). Without the check,\n // `NodeSDK.start()` may register the global tracer provider BEFORE\n // it tries to call `setMetricProducer` and throws — leaving the\n // global tracer pointing at a half-initialized provider whose\n // span pipeline never drains. Skipping the metric reader when the\n // API isn't there avoids that whole failure mode in one pass.\n const setProducer = (candidate as { setMetricProducer?: unknown }).setMetricProducer;\n if (typeof setProducer === 'function') {\n metricReader = candidate;\n metricsEnabled = true;\n } else {\n metricsDropReason =\n 'setMetricProducer is not a function on PeriodicExportingMetricReader; skipping metrics path';\n await asyncDisposeMetricReader(candidate);\n metricReader = undefined;\n }\n } catch {\n if (metricsDropReason === undefined) {\n metricsDropReason = 'metric reader construction or compatibility check failed';\n }\n metricReader = undefined;\n }\n }\n\n const samplerResult = await resolveSampler({\n sdkNode: sdkMod,\n injectedTraceBase: cfg.modules?.['@opentelemetry/sdk-trace-base'],\n loadTraceBase: () => importOptionalPeer('@opentelemetry/sdk-trace-base'),\n sampleRatio: cfg.sampleRatio,\n });\n const sampler = samplerResult.sampler;\n if (samplerResult.source) {\n console.log(`[sdk] sampler built from ${samplerResult.source}`);\n } else {\n console.log(`[sdk] sampler not available (non-fatal): ${samplerResult.failures.join('; ')}`);\n }\n\n // Instrumentations: an explicit list by default, the full auto set on request\n // or as the fallback (BOFF-16818, see ./instrumentations.ts). All optional.\n let autoInstrumentations: unknown[] | undefined;\n const plan = planInstrumentations(\n process.env,\n cfg.modules?.['@opentelemetry/auto-instrumentations-node'] !== undefined\n );\n if (plan.mode === 'explicit') {\n const explicit = await loadExplicitInstrumentations(plan.names, (specifier) => {\n // instrumentationPackage() only ever builds `@opentelemetry/instrumentation-<name>`.\n const injected = cfg.modules?.[specifier as InstrumentationPackage];\n return injected !== undefined ? Promise.resolve(injected) : importOptionalPeer(specifier);\n });\n if (explicit.instances.length > 0) {\n autoInstrumentations = explicit.instances;\n console.log(`[sdk] instrumentations (${plan.reason}): ${explicit.loaded.join(',')}`);\n if (explicit.missing.length > 0) console.log(`[sdk] instrumentations skipped: ${explicit.missing.join('; ')}`);\n } else {\n console.log(\n `[sdk] none of the explicit instrumentations could be loaded (${explicit.missing.join('; ')}); ` +\n 'falling back to auto-instrumentations-node'\n );\n }\n } else {\n console.log(`[sdk] full auto-instrumentations set (${plan.reason})`);\n }\n if (autoInstrumentations === undefined) {\n try {\n console.log('[sdk] importing @opentelemetry/auto-instrumentations-node...');\n const auto = (await load('@opentelemetry/auto-instrumentations-node')) as {\n getNodeAutoInstrumentations: (cfg?: Record<string, unknown>) => unknown[];\n };\n const instrumentationConfig = autoInstrumentationConfig();\n autoInstrumentations = auto.getNodeAutoInstrumentations(instrumentationConfig);\n console.log('[sdk] auto-instrumentations loaded');\n if (instrumentationConfig['@opentelemetry/instrumentation-runtime-node']?.enabled === false) {\n console.log(\n '[sdk] runtime-node instrumentation off under Bun (its heap statistics stall the event loop); ' +\n 'list runtime-node in OTEL_NODE_ENABLED_INSTRUMENTATIONS to turn it on'\n );\n }\n } catch {\n autoInstrumentations = undefined;\n console.log('[sdk] auto-instrumentations not available (non-fatal)');\n }\n }\n\n const serviceNamespaceByBoundary: Record<Boundary, string> = {\n wspace: 'workspaces',\n global: 'tenant',\n gateway: 'gateways',\n };\n const resourceAttributes: Record<string, string> = {\n [sem['SEMRESATTRS_SERVICE_NAME'] ?? 'service.name']: cfg.serviceName,\n [sem['SEMRESATTRS_SERVICE_VERSION'] ?? 'service.version']: cfg.serviceVersion,\n [sem['SEMRESATTRS_SERVICE_NAMESPACE'] ?? 'service.namespace']: serviceNamespaceByBoundary[cfg.boundary],\n [sem['SEMRESATTRS_DEPLOYMENT_ENVIRONMENT'] ?? 'deployment.environment']: cfg.env,\n 'burdenoff.boundary': cfg.boundary,\n };\n if (cfg.module) resourceAttributes['burdenoff.module'] = cfg.module;\n const serviceInstanceId = process.env['POD_NAME'] ?? process.env['HOSTNAME'];\n if (serviceInstanceId) resourceAttributes['service.instance.id'] = serviceInstanceId;\n const clusterName = process.env['CLUSTER_NAME'];\n if (clusterName) {\n resourceAttributes['cluster'] = clusterName;\n resourceAttributes['k8s.cluster.name'] = clusterName;\n }\n\n const resource = resources.resourceFromAttributes(resourceAttributes);\n\n const traceExporter = new traceExp.OTLPTraceExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/traces`,\n });\n\n // Single NodeSDK, single start. The pre-flight `setMetricProducer`\n // check above means we never pass an incompatible metric reader into\n // NodeSDK construction — so we no longer need the prior catch+rebuild\n // fallback dance, which had its own side-effect: the failed first\n // NodeSDK could leave the global tracer provider partially registered,\n // and the second NodeSDK's `setGlobalTracerProvider` becomes a no-op\n // — meaning spans flow into the FIRST (broken) provider and never\n // reach the exporter. Eliminating the fallback eliminates that hazard.\n console.log('[sdk] constructing NodeSDK...');\n const nodeSdk = new sdkMod.NodeSDK({\n resource,\n traceExporter,\n ...(metricReader ? { metricReader } : {}),\n ...(sampler ? { sampler } : {}),\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(autoInstrumentations ? { instrumentations: autoInstrumentations } : {}),\n });\n console.log('[sdk] NodeSDK constructed, calling start()...');\n // NodeSDK.start() returns void in modern versions and Promise<void> in older\n // ones. Cast to a permissive thenable shape so awaiting works either way\n // without tripping `@typescript-eslint/await-thenable`.\n const startResult = nodeSdk.start() as unknown;\n if (isThenable(startResult)) {\n await startResult;\n }\n console.log('[sdk] NodeSDK started');\n\n // Stash the @opentelemetry/api reference for pino-logger's mixin.\n try {\n (globalThis as unknown as { __otelApi?: unknown }).__otelApi = await load('@opentelemetry/api');\n console.log('[sdk] @opentelemetry/api stashed for pino mixin');\n } catch {\n console.log('[sdk] @opentelemetry/api stash failed (non-fatal)');\n }\n\n console.log('[sdk] OTel SDK initialization complete');\n return {\n shutdown: async (): Promise<void> => nodeSdk.shutdown(),\n metricsEnabled,\n metricsDropReason,\n ...(samplerResult.source ? { samplerSource: samplerResult.source } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,uBAAuB;;;;;;;AAQpC,MAAa,2BAA8C;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAM,eAAiD;CACrD,MAAM;CACN,QAAQ;CACR,IAAI;CACJ,SAAS;CACT,OAAO;CACP,SAAS;CACT,MAAM;CACN,WAAW;CACX,YAAY;AACd;;AAGA,MAAa,0BAA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,WAAW,UAAU,uBAAuB,kBAAkB;CAEpE,MAAM,gBAAgB,IAAI,SAAS,kBAAkB,EACnD,KAAK,GAAG,IAAI,aAAa,QAAQ,OAAO,EAAE,EAAE,YAC9C,CAAC;CAUD,QAAQ,IAAI,+BAA+B;CAC3C,MAAM,UAAU,IAAI,OAAO,QAAQ;EACjC;EACA;EACA,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;EACvC,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAC7B,GAAI,IAAI,cAAc,EAAE,aAAa,IAAI,YAAY,IAAI,CAAC;EAC1D,GAAI,uBAAuB,EAAE,kBAAkB,qBAAqB,IAAI,CAAC;CAC3E,CAAC;CACD,QAAQ,IAAI,+CAA+C;CAI3D,MAAM,cAAc,QAAQ,MAAM;CAClC,IAAI,WAAW,WAAW,GACxB,MAAM;CAER,QAAQ,IAAI,uBAAuB;CAGnC,IAAI;EACF,AAAC,WAAkD,YAAY,MAAM,KAAK,oBAAoB;EAC9F,QAAQ,IAAI,iDAAiD;CAC/D,QAAQ;EACN,QAAQ,IAAI,mDAAmD;CACjE;CAEA,QAAQ,IAAI,wCAAwC;CACpD,OAAO;EACL,UAAU,YAA2B,QAAQ,SAAS;EACtD;EACA;EACA,GAAI,cAAc,SAAS,EAAE,eAAe,cAAc,OAAO,IAAI,CAAC;CACxE;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"workspace-extension-BcMPoGWr.js","names":[],"sources":["../src/prisma/transaction-context.ts","../src/prisma/workspace-extension.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { WorkspaceContext } from './workspace-extension.js';\n\ninterface TransactionScope {\n active: boolean;\n}\nconst contextFields = [\n 'workspaceId',\n 'tenantId',\n 'actorId',\n 'actorType',\n 'organizationId',\n 'projectId',\n 'appId',\n 'onBehalfOf',\n] as const;\n\nfunction sameContext(a: WorkspaceContext, b: WorkspaceContext): boolean {\n return contextFields.every((field) => a[field] === b[field]);\n}\n\n/**\n * Bun can assimilate a returned lazy thenable outside its async callback's ALS\n * scope. Bind only consumption of native PrismaPromises, never their creation:\n * the query stays cold and retains Prisma's brand/spec/continuation machinery.\n * This facade belongs to exactly one interactive callback, not the root client.\n */\nexport function bindTransactionContext<T extends object>(\n client: T,\n scope: TransactionScope,\n getWorkspaceContext: () => WorkspaceContext | undefined\n): T {\n const delegates = new WeakMap<object, object>();\n function bindOperation(value: unknown): unknown {\n if (!value || typeof value !== 'object' || Reflect.get(value, Symbol.toStringTag) !== 'PrismaPromise') return value;\n const sourceContext = getWorkspaceContext();\n const captured = sourceContext ? { ...sourceContext } : undefined;\n const restore = AsyncLocalStorage.snapshot();\n return new Proxy(value, {\n get(target, property, receiver) {\n const original = Reflect.get(target, property, receiver);\n if (typeof original !== 'function' || property === 'constructor') return original;\n return (...args: unknown[]) => {\n if (!scope.active)\n throw new Error('[WorkspaceExtension] Lazy operation belongs to a completed interactive transaction.');\n // snapshot() keeps ALS store references. Retain identity values too,\n // so mutating the original request object cannot retarget cold work.\n if (sourceContext && captured && !sameContext(sourceContext, captured)) {\n throw new Error('[WorkspaceExtension] Captured workspace/actor context changed before lazy execution.');\n }\n const current = getWorkspaceContext();\n if (captured && current && !sameContext(captured, current)) {\n throw new Error('[WorkspaceExtension] Lazy operation cannot cross workspace/actor context.');\n }\n // Interactive operations already belong to their native transaction.\n // Root batch promises are untouched; moving an itx promise into a new\n // batch must not replace that transaction or restore an old identity.\n if (property === 'requestTransaction')\n throw new Error('[WorkspaceExtension] Interactive operation cannot be rebound to another transaction.');\n return restore(() => {\n const result: unknown = Reflect.apply(original, target, args);\n // Fluent relation accessors return another cold PrismaPromise.\n // Capture that continuation too, without starting either query.\n return ['then', 'catch', 'finally'].includes(String(property)) ? result : bindOperation(result);\n });\n };\n },\n });\n }\n function facade(target: object, model: boolean): object {\n const existing = delegates.get(target);\n if (existing) return existing;\n const proxy = new Proxy(target, {\n get(object, property, receiver) {\n const value: unknown = Reflect.get(object, property, receiver);\n if (\n typeof value === 'function' &&\n (model || (typeof property === 'string' && !property.startsWith('_') && property !== 'constructor'))\n ) {\n return (...args: unknown[]) => bindOperation(Reflect.apply(value, object, args));\n }\n // Public custom client/model methods keep their native receiver; only\n // returned PrismaPromises are bound. Prisma model delegates are objects. Internal\n // metadata, symbols, fields, and the non-thenable client stay untouched.\n if (\n !model &&\n typeof property === 'string' &&\n !property.startsWith('_') &&\n !property.startsWith('$') &&\n value &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'findMany') === 'function'\n ) {\n return facade(value, true);\n }\n return value;\n },\n });\n delegates.set(target, proxy);\n return proxy;\n }\n return facade(client, false) as T;\n}\n","/**\n * Prisma Workspace Extension\n *\n * Automatically injects workspaceId into ALL Prisma operations using\n * request-scoped context from AsyncLocalStorage:\n *\n * **Write operations** (create, createMany, update, upsert):\n * - Auto-populates `workspaceId`, `tenantId`, `createdBy`, `updatedBy`, `context` JSON\n *\n * **Read operations** (findMany, findFirst, findUnique, count, aggregate, groupBy):\n * - Auto-injects `workspaceId` into the `where` clause for workspace isolation\n *\n * **Delete operations** (delete, deleteMany):\n * - Auto-injects `workspaceId` into the `where` clause to prevent cross-workspace deletion\n *\n * **Update where clause** (update, updateMany):\n * - Auto-injects `workspaceId` into the `where` clause to prevent cross-workspace updates\n *\n * **How it works:**\n * 1. The GraphQL server's buildContext extracts workspaceId from x-workspace-id header\n * 2. The workspace context store (AsyncLocalStorage) holds the current request's workspace info\n * 3. This Prisma extension intercepts ALL operations and auto-injects workspaceId\n *\n * **What gets auto-populated on writes:**\n * - `workspaceId` field (String or String?) - set from context if not explicitly provided\n * - `context` field (Json) - merged with workspace/actor info if not explicitly provided\n * - `tenantId` field (String or String?) - set from context if not explicitly provided\n * - `createdBy` / `updatedBy` fields - set from actor context if not explicitly provided\n *\n * **What gets auto-injected on reads/updates/deletes:**\n * - `workspaceId` in the `where` clause - ensures queries only access data within the workspace\n *\n * **No bound context (fail closed):**\n * The context is read from AsyncLocalStorage only. Work that runs outside a request scope (stream\n * consumers, timers, workers, startup jobs) has no context and never inherits another request's:\n * with `strictMode` (the default) such operations throw until the work binds a scope with\n * `withWorkspaceContext()` (one workspace) or `withSystemScope(reason, fn)` (explicitly\n * cross-workspace). `contextFallback: 'warn'` is a deprecated, time-limited migration aid.\n *\n * **Opt-out:**\n * - Explicitly providing `workspaceId` in the where/data will override auto-injection\n * - Pass `_skipWorkspaceInjection: true` in the query args to skip entirely\n * - Set `enableReadIsolation: false` in config to disable read-side injection only\n * - Add model names to `excludeModels` to skip specific models\n *\n * @module prisma/workspace-extension\n * @category Database\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { logger } from '../logger/index.js';\nimport type { InputJsonValue } from './context.js';\nimport { bindTransactionContext } from './transaction-context.js';\nimport type { AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport type { CfAccessCredentials } from '../types/index.js';\n\n// ============================================================================\n// Workspace Context Store (AsyncLocalStorage)\n// ============================================================================\n\n/**\n * Workspace context for the current request scope\n */\nexport interface WorkspaceContext {\n /** Workspace ID (from x-workspace-id header) */\n workspaceId?: string;\n /** Tenant ID (from x-tenant-id header or derived from workspace) */\n tenantId?: string;\n /** Actor ID (user/service/app performing the operation) */\n actorId?: string;\n /** Actor type (user, app, service, super_admin) */\n actorType?: string;\n /** Organization ID */\n organizationId?: string;\n /** Project ID */\n projectId?: string;\n /** App ID */\n appId?: string;\n /** On behalf of actor ID (for consent-based delegation) */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation runs under, when the gateway verified one\n * (BOFF-9649). `trackOperation` stamps it on every activity row written in the operation.\n */\n assistantSession?: AssistantSessionAttribution;\n /**\n * The Cloudflare Access credentials the request presented, bound by the SDK server together\n * with the rest of the request scope. Read only from the bound scope (never from the\n * deprecated warn-mode fallback) by `ContextManager.getCfAccessHeaders()`. Background work\n * bound with {@link withWorkspaceContext} or {@link withSystemScope} carries none.\n */\n cfAccess?: CfAccessCredentials;\n}\n\n/**\n * AsyncLocalStorage for workspace context\n * This is separate from the SDK's general ContextManager to allow\n * fine-grained control over workspace-specific context propagation.\n */\nconst workspaceContextStore = new AsyncLocalStorage<WorkspaceContext>();\n\n/**\n * How {@link getWorkspaceContext} behaves when no context is bound to the current async scope.\n *\n * - `'deny'` (default): resolve nothing. The workspace extension then applies `strictMode`\n * (throw) or, with `strictMode: false`, runs the operation without injection.\n * - `'warn'`: temporary migration aid. Resolve the context most recently passed to\n * {@link setWorkspaceContext} (the previous behaviour) and log a warning each time it is\n * used, so the remaining unbound call sites can be found and fixed.\n * **Deprecated; removed after {@link WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}.**\n */\nexport type WorkspaceContextFallbackMode = 'deny' | 'warn';\n\n/** Date after which the `'warn'` fallback mode is removed and `'deny'` is the only behaviour. */\nexport const WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE = '2027-01-08';\n\n/** Minimum interval between two warn-mode log lines (each line carries the count since the last). */\nconst FALLBACK_WARNING_INTERVAL_MS = 60_000;\n\n/** Upper bound on distinct system-scope reasons logged, so a computed reason cannot grow memory. */\nconst MAX_LOGGED_SYSTEM_SCOPE_REASONS = 256;\n\ninterface FallbackState {\n mode: WorkspaceContextFallbackMode;\n /** Last context passed to setWorkspaceContext. Only retained in 'warn' mode. */\n lastContext: WorkspaceContext | undefined;\n suppressedWarnings: number;\n lastWarningAt: number;\n}\n\nconst fallbackState: FallbackState = {\n mode: 'deny',\n lastContext: undefined,\n suppressedWarnings: 0,\n lastWarningAt: 0,\n};\n\n/**\n * Contexts created by {@link withSystemScope}. Membership, not a field, marks a system scope, so\n * a context built or spread from request data can never claim to be one.\n */\nconst systemScopeContexts = new WeakSet<WorkspaceContext>();\nconst systemScopeReasons = new WeakMap<WorkspaceContext, string>();\nconst loggedSystemScopeReasons = new Set<string>();\nlet systemScopeReasonCapLogged = false;\n\n/**\n * Select the fallback mode for this process. Called by {@link addWorkspaceExtension} from its\n * `contextFallback` option. `'warn'` is sticky for the life of the process: once any client asks\n * for it, a second client created later with the default cannot silently switch it back mid-flight.\n *\n * @internal\n */\nexport function configureWorkspaceContextFallback(mode: WorkspaceContextFallbackMode): void {\n if (mode !== 'deny' && mode !== 'warn') {\n throw new Error(`[WorkspaceExtension] Unknown contextFallback mode: ${String(mode)}`);\n }\n if (mode === 'warn' && fallbackState.mode !== 'warn') {\n fallbackState.mode = 'warn';\n logger.error(\n `[WorkspaceExtension] contextFallback 'warn' is enabled. Operations outside a bound workspace ` +\n `context will use the most recent request's context. This mode is deprecated and will be ` +\n `removed after ${WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}; bind context with ` +\n `withWorkspaceContext() or withSystemScope() instead.`\n );\n }\n}\n\n/** The fallback mode currently in effect for this process. */\nexport function getWorkspaceContextFallbackMode(): WorkspaceContextFallbackMode {\n return fallbackState.mode;\n}\n\n/**\n * Reset module-level context state (fallback mode, retained context, log dedupe).\n *\n * @internal For unit tests only.\n */\nexport function resetWorkspaceContextStateForTests(): void {\n fallbackState.mode = 'deny';\n fallbackState.lastContext = undefined;\n fallbackState.suppressedWarnings = 0;\n fallbackState.lastWarningAt = 0;\n loggedSystemScopeReasons.clear();\n systemScopeReasonCapLogged = false;\n}\n\nfunction warnFallbackUse(context: WorkspaceContext): void {\n const now = Date.now();\n if (now - fallbackState.lastWarningAt < FALLBACK_WARNING_INTERVAL_MS) {\n fallbackState.suppressedWarnings += 1;\n return;\n }\n const suppressed = fallbackState.suppressedWarnings;\n fallbackState.lastWarningAt = now;\n fallbackState.suppressedWarnings = 0;\n // The stack is only captured when a line is actually logged (at most once per interval).\n const callSite = new Error().stack?.split('\\n').slice(2, 8).join('\\n');\n logger.warn(\n `[WorkspaceExtension] Workspace context resolved from the shared fallback (no context bound to ` +\n `this async scope). This will fail closed after ${WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}.`,\n {\n fallbackWorkspaceId: context.workspaceId ?? 'NONE',\n suppressedSinceLastWarning: suppressed,\n callSite,\n }\n );\n}\n\n/**\n * Set workspace context for the current async scope.\n *\n * Uses `AsyncLocalStorage.enterWith()`, which binds the context to the CURRENT synchronous\n * execution and everything it schedules afterwards. It does not reach a caller that awaited the\n * function that called it, so request handlers should prefer {@link withWorkspaceContext}, which\n * binds a scope explicitly (the SDK server does this for GraphQL execution and REST endpoints).\n *\n * @param context - The workspace context for this request\n */\nexport function setWorkspaceContext(context: WorkspaceContext): void {\n workspaceContextStore.enterWith(context);\n // Only the deprecated warn mode keeps a module-level copy; the default retains nothing.\n fallbackState.lastContext = fallbackState.mode === 'warn' ? context : undefined;\n}\n\n/**\n * Get the workspace context bound to the current async scope.\n *\n * Fails closed: outside a bound scope (a background job, a stream consumer, a timer, or code\n * that lost its request scope) this returns `undefined`, unless the process opted into the\n * deprecated `contextFallback: 'warn'` mode.\n *\n * @returns The current workspace context, or undefined if none is bound\n */\nexport function getWorkspaceContext(): WorkspaceContext | undefined {\n const scoped = workspaceContextStore.getStore();\n if (scoped) return scoped;\n if (fallbackState.mode === 'warn' && fallbackState.lastContext) {\n warnFallbackUse(fallbackState.lastContext);\n return fallbackState.lastContext;\n }\n return undefined;\n}\n\n/**\n * The workspace context bound to the CURRENT async scope only. Never consults the deprecated\n * warn-mode fallback, whatever the process mode.\n *\n * Use it for values that must never leak between requests (for example the assistant-session\n * attribution on activity rows).\n */\nexport function getScopedWorkspaceContext(): WorkspaceContext | undefined {\n return workspaceContextStore.getStore();\n}\n\n/**\n * Get the bound workspace context and its workspaceId, or throw.\n *\n * Use in code that must only ever run for one workspace (resolvers, consumers that already\n * wrapped themselves in {@link withWorkspaceContext}) so a missing scope fails loudly at the\n * call site instead of deep inside a query. Reads only the scope bound to the current async\n * chain: the deprecated warn-mode fallback never satisfies it.\n *\n * @throws Error when no workspace is bound to the current async scope\n */\nexport function requireWorkspaceContext(): WorkspaceContext & { workspaceId: string } {\n const context = workspaceContextStore.getStore();\n if (!context?.workspaceId || isSystemScope(context)) {\n throw new Error(\n '[WorkspaceExtension] No workspace is bound to the current async scope. ' +\n 'Wrap the work in withWorkspaceContext({ workspaceId, ... }, fn).'\n );\n }\n return context as WorkspaceContext & { workspaceId: string };\n}\n\n/**\n * Run a function with a specific workspace context.\n * The context is isolated to this execution and its children.\n *\n * This is the explicit API for background work that acts for ONE workspace: a stream consumer\n * handling an event that names its workspace, a job row that stores its workspaceId, a\n * per-workspace loop inside a sweep. Pass `actorType: 'service'` (and the service as `actorId`)\n * when no user is behind the work, so audit columns say who acted.\n *\n * @param context - The workspace context\n * @param fn - The function to run\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * await withWorkspaceContext(\n * { workspaceId: event.workspaceId, actorId: 'wspace-tags-svc', actorType: 'service' },\n * async () => prisma.tag.updateMany({ where: { name }, data: { archived: true } })\n * );\n * ```\n */\nexport async function withWorkspaceContext<T>(context: WorkspaceContext, fn: () => Promise<T>): Promise<T> {\n return workspaceContextStore.run(context, fn);\n}\n\n/**\n * Run a synchronous function with a specific workspace context.\n */\nexport function withWorkspaceContextSync<T>(context: WorkspaceContext, fn: () => T): T {\n return workspaceContextStore.run(context, fn);\n}\n\n/**\n * Run a function in an explicit, audited system scope that is not tied to any workspace.\n *\n * Inside the scope the workspace extension injects nothing and does not apply `strictMode`:\n * reads see every workspace's rows and writes must set `workspaceId` themselves. Use it only for\n * genuinely cross-workspace work (retention sweeps, outbox relays, startup backfills), never to\n * silence a missing request context. Prefer one {@link withWorkspaceContext} per workspace when\n * the work can be split that way.\n *\n * Each distinct reason is logged once per process so the system scopes in use stay visible.\n * A {@link withWorkspaceContext} nested inside the scope rebinds to that workspace.\n *\n * @param reason - Short, static description of the work, e.g. `'retention-sweep'`. Required.\n * @param fn - The function to run\n *\n * @example\n * ```typescript\n * await withSystemScope('expired-session-sweep', () =>\n * prisma.session.deleteMany({ where: { expiresAt: { lt: new Date() } } })\n * );\n * ```\n */\nexport async function withSystemScope<T>(reason: string, fn: () => Promise<T>): Promise<T> {\n return workspaceContextStore.run(createSystemScopeContext(reason), fn);\n}\n\n/** Synchronous form of {@link withSystemScope}. */\nexport function withSystemScopeSync<T>(reason: string, fn: () => T): T {\n return workspaceContextStore.run(createSystemScopeContext(reason), fn);\n}\n\n/** Whether the given (or current) context is a system scope created by {@link withSystemScope}. */\nexport function isSystemScope(context: WorkspaceContext | undefined = workspaceContextStore.getStore()): boolean {\n return context !== undefined && systemScopeContexts.has(context);\n}\n\nfunction createSystemScopeContext(reason: string): WorkspaceContext {\n const trimmed = typeof reason === 'string' ? reason.trim() : '';\n if (!trimmed) {\n throw new Error('[WorkspaceExtension] withSystemScope requires a non-empty reason.');\n }\n const context: WorkspaceContext = Object.freeze({ actorType: 'service' });\n systemScopeContexts.add(context);\n systemScopeReasons.set(context, trimmed);\n return context;\n}\n\n/** Log the first operation run under each distinct system-scope reason. */\nfunction noteSystemScopeOperation(context: WorkspaceContext, model: string, operation: string): void {\n const reason = systemScopeReasons.get(context) ?? 'unknown';\n if (loggedSystemScopeReasons.has(reason)) return;\n if (loggedSystemScopeReasons.size >= MAX_LOGGED_SYSTEM_SCOPE_REASONS) {\n if (!systemScopeReasonCapLogged) {\n systemScopeReasonCapLogged = true;\n logger.warn(\n `[WorkspaceExtension] More than ${MAX_LOGGED_SYSTEM_SCOPE_REASONS} distinct system-scope reasons; ` +\n 'further new reasons are not logged. Reasons should be short static strings.',\n { reason, model, operation }\n );\n }\n return;\n }\n loggedSystemScopeReasons.add(reason);\n logger.info('[WorkspaceExtension] Operation running in an explicit system scope (no workspace injection)', {\n reason,\n model,\n operation,\n });\n}\n\n// ============================================================================\n// Extension Configuration\n// ============================================================================\n\n/**\n * Configuration for the workspace extension\n */\nexport interface WorkspaceExtensionConfig {\n /**\n * Enable automatic workspaceId injection on create/update\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Enable automatic workspaceId injection on read operations\n * (findMany, findFirst, findUnique, findFirstOrThrow, findUniqueOrThrow,\n * count, aggregate, groupBy)\n *\n * When enabled, every read query automatically includes `workspaceId`\n * in the `where` clause, preventing cross-workspace data leakage.\n *\n * @default true\n */\n enableReadIsolation?: boolean;\n\n /**\n * Enable automatic workspaceId injection on delete operations\n * (delete, deleteMany)\n *\n * When enabled, every delete operation automatically includes `workspaceId`\n * in the `where` clause, preventing cross-workspace deletion.\n *\n * @default true\n */\n enableDeleteIsolation?: boolean;\n\n /**\n * Enable automatic workspaceId injection into update/updateMany `where` clauses.\n *\n * When enabled, update operations automatically include `workspaceId`\n * in the `where` clause in addition to the `data` injection,\n * preventing cross-workspace updates.\n *\n * @default true\n */\n enableUpdateWhereIsolation?: boolean;\n\n /**\n * Automatically populate the `context` JSON field with workspace/actor info\n * @default true\n */\n populateContextJson?: boolean;\n\n /**\n * Automatically populate `createdBy` field on create operations\n * @default true\n */\n populateCreatedBy?: boolean;\n\n /**\n * Automatically populate `updatedBy` field on update operations\n * @default true\n */\n populateUpdatedBy?: boolean;\n\n /**\n * Automatically populate `tenantId` field from context\n * @default false (tenantId is typically derived from workspaceId at the DB level)\n */\n populateTenantId?: boolean;\n\n /**\n * Automatically populate the `onBehalfOf` field on create operations\n * (consent-based delegation tracking — defaults to the acting actor when no\n * delegation is present).\n *\n * Unlike `populateContextJson`/`populateCreatedBy`/`populateUpdatedBy`, this\n * has no per-model opt-out other than `excludeModels` (which also disables\n * RLS GUC tagging and isolation for that model). Set to `false` for services\n * whose Prisma models don't carry an `onBehalfOf` column — otherwise every\n * create on those models throws `Unknown argument onBehalfOf` from Prisma's\n * client-side validation.\n *\n * @default true\n */\n populateOnBehalfOf?: boolean;\n\n /**\n * Models to exclude from auto-injection (both reads and writes).\n * Use this for models that intentionally don't have workspaceId.\n *\n * Common exclusions: system tables, infra tables, global reference data.\n *\n * @default []\n */\n excludeModels?: string[];\n\n /**\n * Models to exclude from read isolation only.\n * These models will still get write-side injection (workspaceId on create)\n * but reads will NOT have workspaceId auto-injected into `where`.\n *\n * Use this for child/join tables where workspace scoping is inherited\n * through parent relations, or for models queried by ID that don't\n * have a workspaceId column.\n *\n * @default []\n */\n excludeModelsFromReadIsolation?: string[];\n\n /**\n * When true, throws an error if workspaceId is missing from context\n * for any non-excluded model operation. This prevents silent\n * workspace-unscoped queries that could leak data across workspaces.\n *\n * When false, operations without workspace context proceed without\n * workspaceId injection (legacy behavior).\n *\n * @default true\n */\n strictMode?: boolean;\n\n /**\n * Operations that are allowed without workspace context even in strict mode.\n * Use `Model.operation` format (e.g., `['Workspace.create', 'RevokedToken.findMany']`).\n *\n * Valid operation names: create, createMany, createManyAndReturn, update, updateMany,\n * upsert, findMany, findFirst, findFirstOrThrow, findUnique, findUniqueOrThrow,\n * count, aggregate, groupBy, delete, deleteMany.\n *\n * @default []\n */\n allowedUnguardedOperations?: string[];\n\n /**\n * What happens when an operation runs with no workspace context bound to its async scope.\n *\n * - `'deny'` (default): nothing is resolved, so `strictMode` throws (or, with\n * `strictMode: false`, the operation runs without injection). Background work must bind its\n * scope with `withWorkspaceContext()` or `withSystemScope()`.\n * - `'warn'`: deprecated migration aid. Reuse the context of the most recent request and log a\n * warning. Removed after {@link WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}. Once any client in\n * the process selects it, it stays on for that process.\n *\n * @default 'deny'\n */\n contextFallback?: WorkspaceContextFallbackMode;\n\n /**\n * Log injection events (useful for debugging)\n * @default false\n */\n debug?: boolean;\n\n /**\n * Tag the PostgreSQL connection with workspace attribution for pg_stat_activity visibility.\n *\n * When enabled, the first DB operation per workspace context sets:\n * `application_name = 'svc=<SERVICE_NAME>;ws=<workspaceId>'`\n *\n * This makes workspace-level query attribution visible in pg_stat_activity,\n * pg_locks, auto_explain, and monitoring tools without any schema changes.\n * Subsequent operations in the same request are deduplicated via WeakSet,\n * costing ~0 overhead after the first round-trip per request context.\n *\n * NOTE: This is a session-level SET so attribution may drift across ops\n * that reuse the same pooled connection from different requests. Use for\n * aggregate observability, not per-query forensics.\n *\n * @default false\n */\n enableApplicationNameTagging?: boolean;\n\n /**\n * Set the `app.workspace_id` GUC for Row Level Security enforcement.\n *\n * When enabled, every workspace-scoped operation runs with\n * `SET LOCAL app.workspace_id = '<workspaceId>'`\n * in effect (see \"Transactions\" below for how that is scoped).\n *\n * RLS policies using `current_setting('app.workspace_id', true)` then filter\n * rows by workspace, providing a defense-in-depth backstop to the application-\n * layer workspaceId injection in the WHERE clause.\n *\n * Pair with migrations that run per table:\n * `ALTER TABLE t ENABLE ROW LEVEL SECURITY;`\n * `CREATE POLICY ws_isolation ON t\n * USING (workspace_id = current_setting('app.workspace_id', true))\n * WITH CHECK (workspace_id = current_setting('app.workspace_id', true));`\n *\n * Fail-closed semantics: if the GUC is unset (NULL from missing_ok=true),\n * `workspace_id = NULL` is always false, so RLS returns no rows — leaking\n * nothing rather than everything.\n *\n * Transactions: a standalone operation runs in its own short transaction\n * (`SET LOCAL` + the operation). An operation on the `tx` client inside a\n * caller's `$transaction(async (tx) => …)`, including raw SQL, runs in the\n * caller's transaction, after one `set_config(..., true)` per transaction and\n * workspace, so it is atomic with the rest of that transaction and its row\n * locks are held until commit. `$transaction([...])` batches get the same\n * statement prepended (BOFF-8874).\n *\n * @default false\n */\n enableRlsGucTagging?: boolean;\n}\n\n/**\n * Default configuration. Exported so consumers/tests can spread over the\n * real defaults (`{ ...defaultWorkspaceExtensionConfig, populateOnBehalfOf: false }`)\n * instead of re-declaring every field.\n */\nexport const defaultWorkspaceExtensionConfig: Required<WorkspaceExtensionConfig> = {\n enabled: true,\n enableReadIsolation: true,\n enableDeleteIsolation: true,\n enableUpdateWhereIsolation: true,\n populateContextJson: true,\n populateCreatedBy: true,\n populateUpdatedBy: true,\n populateTenantId: false,\n populateOnBehalfOf: true,\n excludeModels: [],\n excludeModelsFromReadIsolation: [],\n strictMode: true,\n allowedUnguardedOperations: [],\n contextFallback: 'deny',\n debug: false,\n enableApplicationNameTagging: false,\n enableRlsGucTagging: false,\n};\n\n// ============================================================================\n// Data Injection Helpers\n// ============================================================================\n\n/**\n * Check if a field exists in the data object (including being set to null/undefined explicitly)\n */\nfunction hasField(data: Record<string, unknown>, field: string): boolean {\n return field in data;\n}\n\n/**\n * Inject workspace-related fields into create data.\n *\n * Exported (alongside `injectWhereWorkspaceId`) so consumers can unit-test\n * exactly what a given `WorkspaceExtensionConfig` injects for their own\n * Prisma schema — in particular, to verify `populateOnBehalfOf: false` /\n * `populateContextJson: false` actually suppress `onBehalfOf`/`context`\n * before wiring the extension against models that don't have those columns.\n */\nexport function injectCreateFields(\n data: Record<string, unknown>,\n wsCtx: WorkspaceContext,\n config: Required<WorkspaceExtensionConfig>\n): Record<string, unknown> {\n const injected = { ...data };\n\n // Inject workspaceId if not already provided\n if (wsCtx.workspaceId && !hasField(injected, 'workspaceId')) {\n injected['workspaceId'] = wsCtx.workspaceId;\n }\n\n // Inject tenantId if configured and not already provided\n if (config.populateTenantId && wsCtx.tenantId && !hasField(injected, 'tenantId')) {\n injected['tenantId'] = wsCtx.tenantId;\n }\n\n // Inject createdBy if configured and not already provided\n if (config.populateCreatedBy && wsCtx.actorId && !hasField(injected, 'createdBy')) {\n injected['createdBy'] = wsCtx.actorId;\n }\n\n // Inject updatedBy on create as well (initial value)\n if (config.populateUpdatedBy && wsCtx.actorId && !hasField(injected, 'updatedBy')) {\n injected['updatedBy'] = wsCtx.actorId;\n }\n\n // Inject onBehalfOf (for consent-based delegation tracking)\n // If onBehalfOf is in context (from consent), use it; otherwise defaults to actorId (self-action)\n if (config.populateOnBehalfOf && wsCtx.onBehalfOf && !hasField(injected, 'onBehalfOf')) {\n injected['onBehalfOf'] = wsCtx.onBehalfOf;\n } else if (config.populateOnBehalfOf && wsCtx.actorId && !hasField(injected, 'onBehalfOf')) {\n // Default to actorId if no delegation (self-action)\n injected['onBehalfOf'] = wsCtx.actorId;\n }\n\n // Populate context JSON field\n if (config.populateContextJson && !hasField(injected, 'context')) {\n const contextJson = buildContextJsonFromWorkspaceContext(wsCtx);\n if (contextJson) {\n injected['context'] = contextJson;\n }\n }\n\n return injected;\n}\n\n/**\n * Inject workspace-related fields into update data\n */\nfunction injectUpdateFields(\n data: Record<string, unknown>,\n wsCtx: WorkspaceContext,\n config: Required<WorkspaceExtensionConfig>\n): Record<string, unknown> {\n const injected = { ...data };\n\n // Inject updatedBy if configured and not already provided\n if (config.populateUpdatedBy && wsCtx.actorId && !hasField(injected, 'updatedBy')) {\n injected['updatedBy'] = wsCtx.actorId;\n }\n\n // Note: We intentionally do NOT auto-inject workspaceId on updates\n // because updates target existing records (workspaceId is immutable after creation)\n // and changing it would be a data integrity issue.\n\n return injected;\n}\n\n/**\n * Inject workspaceId into a where clause.\n * Only injects if workspaceId is available in context and not already present in where.\n *\n * For operations that may not have a where clause (e.g., findMany without filters),\n * creates a new where object with just workspaceId.\n */\nfunction injectWhereClause(\n where: Record<string, unknown> | undefined,\n wsCtx: WorkspaceContext\n): Record<string, unknown> | undefined {\n if (!wsCtx.workspaceId) return where;\n\n if (!where) {\n // No where clause exists, create one with just workspaceId\n return { workspaceId: wsCtx.workspaceId };\n }\n\n // Only inject if not already present\n if (!hasField(where, 'workspaceId')) {\n return { ...where, workspaceId: wsCtx.workspaceId };\n }\n\n return where;\n}\n\n/**\n * Build context JSON from workspace context\n */\nfunction buildContextJsonFromWorkspaceContext(wsCtx: WorkspaceContext): InputJsonValue | undefined {\n const context: Record<string, string> = {};\n\n if (wsCtx.workspaceId) context['workspaceId'] = wsCtx.workspaceId;\n if (wsCtx.actorId) context['userId'] = wsCtx.actorId;\n if (wsCtx.organizationId) context['organizationId'] = wsCtx.organizationId;\n if (wsCtx.projectId) context['projectId'] = wsCtx.projectId;\n if (wsCtx.appId) context['appId'] = wsCtx.appId;\n\n return Object.keys(context).length > 0 ? context : undefined;\n}\n\n/**\n * Inject workspaceId into where clause for read/update/delete operations.\n * This is a utility function exported for services that want to manually\n * add workspace scoping to their queries.\n *\n * @param where - The existing where clause\n * @param wsCtx - The workspace context (or auto-detected from AsyncLocalStorage)\n * @returns The where clause with workspaceId injected if not already present\n *\n * @example\n * ```typescript\n * import { injectWhereWorkspaceId, getWorkspaceContext } from '@burdenoff/be-sdk/prisma';\n *\n * const wsCtx = getWorkspaceContext();\n * const where = injectWhereWorkspaceId({ status: 'ACTIVE' }, wsCtx);\n * // Result: { status: 'ACTIVE', workspaceId: 'ws-123' }\n * ```\n */\nexport function injectWhereWorkspaceId(\n where: Record<string, unknown> | undefined,\n wsCtx?: WorkspaceContext\n): Record<string, unknown> | undefined {\n const ctx = wsCtx ?? getWorkspaceContext();\n if (!where || !ctx?.workspaceId) return where;\n\n // Only inject if not already present\n if (!hasField(where, 'workspaceId')) {\n return { ...where, workspaceId: ctx.workspaceId };\n }\n\n return where;\n}\n\n/**\n * Remove the _skipWorkspaceInjection flag from args before passing to Prisma.\n * Using a dedicated function avoids ESLint unused-variable warnings from destructuring.\n */\nfunction stripSkipFlag<T extends Record<string, unknown>>(args: T): Omit<T, '_skipWorkspaceInjection'> {\n const cleaned = { ...args };\n delete (cleaned as Record<string, unknown>)['_skipWorkspaceInjection'];\n return cleaned;\n}\n\n/**\n * Check if a model should be excluded from read isolation.\n * A model is excluded if it's in excludeModels OR excludeModelsFromReadIsolation.\n */\nfunction isExcludedFromReadIsolation(model: string, config: Required<WorkspaceExtensionConfig>): boolean {\n return config.excludeModels.includes(model) || config.excludeModelsFromReadIsolation.includes(model);\n}\n\n// ============================================================================\n// Operation Context Resolution\n// ============================================================================\n\n/**\n * Contexts synthesized from an operation's own arguments. They satisfy strict mode and\n * scope injection, but never set the RLS / connection tags: row-level security keeps\n * whatever the connection or caller transaction already carries, so it stays an\n * independent check on the explicit workspaceId instead of following it.\n */\nconst explicitArgumentContexts = new WeakSet<WorkspaceContext>();\n\n/** Read a non-empty string `workspaceId` set directly on a where/data object. */\nfunction readExplicitWorkspaceId(value: unknown): string | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const workspaceId = (value as Record<string, unknown>)['workspaceId'];\n return typeof workspaceId === 'string' && workspaceId.length > 0 ? workspaceId : undefined;\n}\n\n/**\n * The single workspace an operation's own arguments pin it to, if any.\n *\n * Only a plain string `workspaceId` at the top level of `where` (reads, updates, deletes) or\n * `data` (creates) counts. Filters such as `{ in: [...] }`, relation paths and compound unique\n * keys do not, and a `createMany` whose rows name different workspaces does not either: those\n * stay unresolved so strict mode still applies.\n *\n * @internal Exported for unit tests.\n */\nexport function explicitWorkspaceIdFromArgs(operation: string, args: Record<string, unknown>): string | undefined {\n switch (operation) {\n case 'create':\n return readExplicitWorkspaceId(args['data']);\n case 'createMany':\n case 'createManyAndReturn': {\n const data = args['data'];\n const rows = Array.isArray(data) ? data : [data];\n if (rows.length === 0) return undefined;\n const ids = rows.map(readExplicitWorkspaceId);\n const first = ids[0];\n return first !== undefined && ids.every((id) => id === first) ? first : undefined;\n }\n case 'upsert': {\n const fromWhere = readExplicitWorkspaceId(args['where']);\n if (!fromWhere) return undefined;\n const fromCreate = readExplicitWorkspaceId(args['create']);\n if (args['create'] && typeof args['create'] === 'object' && 'workspaceId' in args['create']) {\n return fromCreate === fromWhere ? fromWhere : undefined;\n }\n return fromWhere;\n }\n default:\n return readExplicitWorkspaceId(args['where']);\n }\n}\n\n/**\n * Resolve the workspace context for one model operation.\n *\n * 1. A context bound to the async scope always wins (request scopes, withWorkspaceContext,\n * withSystemScope). A bound request scope with no workspace stays without one, so strict\n * mode keeps rejecting workspace-less requests exactly as before.\n * 2. With NO scope bound (background work), an operation whose own arguments pin one\n * workspace (`where.workspaceId` / `data.workspaceId`) runs scoped to that workspace, with\n * no actor attributed. It does not set the RLS GUC or connection tag: under FORCE row-level\n * security such work still needs a bound scope. This is the explicit-argument path.\n * 3. Otherwise the deprecated warn-mode fallback, if the process opted in.\n * 4. Otherwise nothing: strict mode throws, non-strict runs without injection.\n */\nfunction resolveOperationContext(operation: string, args: Record<string, unknown>): WorkspaceContext | undefined {\n const scoped = workspaceContextStore.getStore();\n if (scoped) return scoped;\n const explicitWorkspaceId = explicitWorkspaceIdFromArgs(operation, args);\n if (explicitWorkspaceId) {\n const context: WorkspaceContext = { workspaceId: explicitWorkspaceId };\n explicitArgumentContexts.add(context);\n return context;\n }\n return getWorkspaceContext();\n}\n\n// ============================================================================\n// Strict Mode Enforcement\n// ============================================================================\n\n/**\n * Enforce strict mode: throw if workspace context is missing and the operation\n * is not explicitly allowed to run without it.\n *\n * @returns true if the operation should proceed without workspace injection (non-strict or allowed)\n * @throws Error if strict mode is enabled and the operation is not allowed\n */\nfunction enforceStrictMode(\n model: string,\n operation: string,\n wsCtx: WorkspaceContext | undefined,\n config: Required<WorkspaceExtensionConfig>\n): void {\n // If workspace context has a workspaceId, nothing to enforce\n if (wsCtx?.workspaceId) return;\n\n // An explicit system scope (withSystemScope) is the audited opt-out for cross-workspace work.\n if (isSystemScope(wsCtx)) {\n noteSystemScopeOperation(wsCtx as WorkspaceContext, model, operation);\n return;\n }\n\n // If strict mode is off, allow silently\n if (!config.strictMode) return;\n\n // Check if this specific operation is allowed without workspace context\n const opKey = `${model}.${operation}`;\n if (config.allowedUnguardedOperations.includes(opKey)) return;\n\n // Strict mode violation — throw\n throw new Error(\n `[WorkspaceExtension] Workspace context required for ${model}.${operation}. ` +\n `No workspaceId is bound to the current async scope` +\n (wsCtx ? '' : ' (background work must bind one explicitly)') +\n `. Either: ` +\n `(1) run the work inside withWorkspaceContext({ workspaceId, ... }, fn), ` +\n `(2) run genuinely cross-workspace work inside withSystemScope(reason, fn), ` +\n `(3) add \"${model}\" to excludeModels or \"${opKey}\" to allowedUnguardedOperations, or ` +\n `(4) pass _skipWorkspaceInjection: true in the query args.`\n );\n}\n\n// ============================================================================\n// Prisma Extension\n// ============================================================================\n\n/**\n * Standard args shape for operations with a `where` clause\n */\ninterface WhereArgs {\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Standard handler params from Prisma $extends\n */\ninterface ExtensionHandlerParams<TArgs> {\n model: string;\n args: TArgs;\n query: (args: unknown) => Promise<unknown>;\n /** Prisma-internal request params; `transaction` identifies a caller transaction. */\n __internalParams?: PrismaQueryInternalParams;\n}\n\n/** Handler params for top-level raw operations (`$queryRaw`, `$executeRaw`, …). */\ninterface RawOperationHandlerParams {\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n __internalParams?: PrismaQueryInternalParams;\n}\n\n/** Client surface the `$transaction` wrapper delegates to (the client one layer down). */\ntype TransactionDelegate = {\n $transaction: (input: unknown, options?: unknown) => Promise<unknown>;\n};\n\n/**\n * Add workspace extension to a Prisma client.\n *\n * This extension provides comprehensive workspace isolation by automatically\n * injecting workspaceId into ALL Prisma operations:\n *\n * **Writes**: Auto-populates workspaceId, tenantId, createdBy, updatedBy, context JSON\n * **Reads**: Auto-injects workspaceId into where clause (findMany, findFirst, etc.)\n * **Updates**: Auto-injects workspaceId into where clause + updatedBy into data\n * **Deletes**: Auto-injects workspaceId into where clause\n *\n * **Chain order matters**: Apply this extension AFTER the graph extension\n * (handled automatically by createDatabaseClient).\n *\n * @param baseClient - The Prisma client to extend\n * @param config - Extension configuration\n * @returns Extended Prisma client with workspace auto-injection\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { addWorkspaceExtension } from '@burdenoff/be-sdk/prisma';\n *\n * const baseClient = new PrismaClient({ adapter });\n * const client = addWorkspaceExtension(baseClient, {\n * populateContextJson: true,\n * populateCreatedBy: true,\n * enableReadIsolation: true,\n * debug: process.env.NODE_ENV === 'development',\n * excludeModels: ['CircuitBreakerState', 'SchedulerState'],\n * excludeModelsFromReadIsolation: ['Permission', 'RbacResourceType'],\n * });\n * ```\n */\n// ============================================================================\n// Connection Tagging (Phase 0.2)\n// ============================================================================\n\n/** Minimal Prisma raw-exec surface needed for SET application_name */\ntype RawPrismaForTagging = {\n $executeRawUnsafe: (query: string, ...values: unknown[]) => Promise<number>;\n};\n\n/**\n * WeakSet of contexts that have already had the connection tagged this request.\n * WorkspaceContext objects live only for the duration of a request, so entries\n * are automatically GC'd when the context goes out of scope — no manual cleanup.\n */\nconst taggedContexts = new WeakSet<WorkspaceContext>();\n\n/**\n * Tag the current Postgres connection with workspace attribution (once per context).\n * Sets `application_name = 'svc=<name>;ws=<workspaceId>'` at the session level.\n * Non-fatal: tagging failures are swallowed so the main operation still proceeds.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport async function maybeTagConnection(rawPrisma: RawPrismaForTagging, wsCtx: WorkspaceContext): Promise<void> {\n if (taggedContexts.has(wsCtx)) return;\n taggedContexts.add(wsCtx);\n // Strip non-safe chars; workspace IDs are UUIDs/CUIDs, service names are kebab-case\n const safeSvc = (process.env['SERVICE_NAME'] ?? 'svc').replace(/[^a-zA-Z0-9\\-_]/g, '');\n const safeWs = (wsCtx.workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n const tag = `svc=${safeSvc};ws=${safeWs}`;\n try {\n await rawPrisma.$executeRawUnsafe(`SET application_name = '${tag}'`);\n } catch {\n // Retry on the next operation if this one failed\n taggedContexts.delete(wsCtx);\n }\n}\n\n// ============================================================================\n// RLS GUC Tagging (Phase 3)\n// ============================================================================\n\n/**\n * WeakSet of contexts that have already had the RLS GUC set this request.\n */\nconst rlsTaggedContexts = new WeakSet<WorkspaceContext>();\n\n/**\n * Set `app.workspace_id` GUC for RLS enforcement (once per context, session-level).\n *\n * When set, RLS policies using `current_setting('app.workspace_id', true)` filter\n * rows to the current workspace. Non-fatal: failures are swallowed and retried on\n * the next operation via WeakSet entry removal.\n *\n * NOT used by the extension's operation handlers below (see\n * `runOperationWithRlsGuc`) — session-level `SET` is unsafe once traffic is routed\n * through PgBouncer in transaction-pooling mode (see that function's doc comment\n * for the full incident writeup, BOFF-5488). Kept as a standalone export, still\n * unit tested, for any caller that genuinely runs on an unpooled/session-pooled\n * connection where session-level `SET` is sufficient.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport async function maybeSetRlsGuc(rawPrisma: RawPrismaForTagging, wsCtx: WorkspaceContext): Promise<void> {\n if (rlsTaggedContexts.has(wsCtx)) return;\n rlsTaggedContexts.add(wsCtx);\n // Allow alphanumeric, hyphens, underscores — CUID/UUID safe, prevents SQL injection\n const safeWs = (wsCtx.workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n try {\n await rawPrisma.$executeRawUnsafe(`SET app.workspace_id = '${safeWs}'`);\n } catch {\n // Retry on the next operation if this one failed\n rlsTaggedContexts.delete(wsCtx);\n }\n}\n\n/**\n * A Prisma interactive-transaction client (`tx` inside `$transaction(async (tx) =>\n * …)`), typed with just enough surface for `runOperationWithRlsGuc`: raw SQL\n * execution, plus one delegate per model keyed by its Prisma Client property name\n * (e.g. `customer`, `driver`). The index signature is `unknown` (not a concrete\n * delegate shape) because this helper is generic across every model in the schema\n * — callers narrow and verify the specific delegate/method they need at runtime.\n */\ntype PrismaTxForRlsGuc = {\n $executeRawUnsafe: (query: string, ...values: unknown[]) => Promise<number>;\n [modelClientProperty: string]: unknown;\n};\n\n/** Minimal Prisma client surface needed to open an interactive transaction. */\ntype RawPrismaForRlsTransaction = {\n $transaction: <TResult>(fn: (tx: PrismaTxForRlsGuc) => Promise<TResult>) => Promise<TResult>;\n};\n\n/**\n * Prisma DMMF model name (e.g. `Customer`) -> Prisma Client delegate property\n * (e.g. `customer`). Matches Prisma's own client-generation rule: lower-case the\n * first character, leave the rest untouched.\n */\nfunction modelToClientProperty(model: string): string {\n return model.length > 0 ? model.charAt(0).toLowerCase() + model.slice(1) : model;\n}\n\n/**\n * Run a single Prisma operation with `app.workspace_id` set as a\n * **transaction-scoped** (`SET LOCAL`) GUC immediately ahead of it, so Postgres\n * RLS policies using `current_setting('app.workspace_id', true)` see the right\n * value for both the `USING` (read) and `WITH CHECK` (write) clauses.\n *\n * Session-level `SET` (`maybeSetRlsGuc` above, the original Phase 3\n * implementation) is NOT safe once traffic goes through PgBouncer in\n * **transaction pooling mode** — the mode configured on all four\n * `boff-pg-{global,wspace}-{alpha,prod}-cin` servers' built-in PgBouncer (see\n * infra-specs/current-architecture/02-database-postgres-age.md). PgBouncer hands\n * the physical backend connection back to the pool after every standalone\n * statement/implicit transaction, so a `SET` executed by one statement is not\n * guaranteed visible to the very next one, even over what looks like the same\n * logical client connection.\n *\n * This was exactly BOFF-5488: `wspace-movethewheels-svc`'s RLS Phase 3b (FORCE\n * ROW LEVEL SECURITY + a non-owner runtime role, `wspace_movethewheels_app`,\n * pointed at the pooled `:6432` connection) made the `ws_isolation` policy bind\n * for real, but the session-level `SET` from `maybeSetRlsGuc` was landing on a\n * different pooled backend connection than the write that followed it — so every\n * write failed `WITH CHECK` (`new row violates row-level security policy`) and\n * every read matched zero rows.\n *\n * A Prisma **interactive transaction** (`$transaction(async (tx) => …)`) pins one\n * physical connection for the callback's full duration — PgBouncer sees a single\n * unbroken `BEGIN … COMMIT` and cannot reassign the backend mid-transaction — so\n * `SET LOCAL` inside it is guaranteed visible to the operation issued right after\n * it in the same callback. Safe under transaction-mode pooling, session-mode\n * pooling, and with no pooler in front of Postgres at all. The extra round trip\n * (one interactive transaction instead of one direct call) only applies to\n * services that opt into `enableRlsGucTagging` — off by default.\n *\n * @internal Legacy exported helper retained for compatibility and its historical\n * tests. It reissues a model call and cannot preserve surrounding query hooks;\n * addWorkspaceExtension uses the continuation-based route below instead. Do not\n * call this helper from product code.\n */\nexport async function runOperationWithRlsGuc<TResult>(\n rootClient: RawPrismaForRlsTransaction,\n wsCtx: WorkspaceContext,\n model: string,\n operation: string,\n args: unknown\n): Promise<TResult> {\n const safeWs = (wsCtx.workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n const clientProperty = modelToClientProperty(model);\n return rootClient.$transaction(async (tx) => {\n await tx.$executeRawUnsafe(`SET LOCAL app.workspace_id = '${safeWs}'`);\n // `tx[clientProperty]` is typed `unknown` (see PrismaTxForRlsGuc) because this\n // helper is generic across every model; narrow to the minimal callable shape\n // needed and verify at runtime before invoking rather than trusting a cast.\n const delegate = tx[clientProperty] as Record<string, (opArgs: unknown) => Promise<TResult>> | undefined;\n const method = delegate?.[operation];\n if (typeof method !== 'function') {\n throw new Error(\n `[WorkspaceExtension] Unable to resolve ${model}.${operation} (client property \"${clientProperty}\") ` +\n 'on the interactive-transaction client for RLS GUC tagging.'\n );\n }\n return method(args);\n });\n}\n\n/** Minimal batch surface; both operations must stay lazy until Prisma binds them. */\ntype RawPrismaForRlsContinuation = {\n $executeRawUnsafe: (sql: string, ...values: unknown[]) => PendingRawStatement;\n $transaction: <TResult>(input: [PendingRawStatement, Promise<TResult>]) => Promise<[unknown, TResult]>;\n};\n\n/**\n * Keep the original query continuation, including later query extensions, inside\n * the GUC-tagged transaction. Reissuing a model call on the root client would\n * skip later hooks, or execute an earlier hook twice (BOFF-8874).\n */\nasync function runQueryWithRlsGuc<TResult>(\n rootClient: RawPrismaForRlsContinuation,\n wsCtx: WorkspaceContext,\n query: () => Promise<TResult>\n): Promise<TResult> {\n // Prisma types this as Promise, but its extension callback returns a lazy\n // PrismaPromise. Require the binding capability instead of falling back to an\n // independent model call or executing the query outside the transaction.\n const pendingQuery = query() as Promise<TResult> & { requestTransaction?: unknown };\n const pendingContext = rootClient.$executeRawUnsafe(\n \"SELECT set_config('app.workspace_id', $1, true), \" +\n \"set_config('statement_timeout', CASE \" +\n \"WHEN current_setting('statement_timeout')::interval > interval '0' \" +\n \"AND current_setting('statement_timeout')::interval < interval '5 seconds' \" +\n \"THEN current_setting('statement_timeout') ELSE '5000ms' END, true)\",\n sanitizeWorkspaceId(wsCtx.workspaceId)\n );\n if (\n typeof pendingQuery.requestTransaction !== 'function' ||\n typeof pendingContext.requestTransaction !== 'function'\n ) {\n throw new Error(\n '[WorkspaceExtension] RLS query continuation requires transaction-bindable PrismaPromises; ' +\n 'refusing the unsupported Prisma integration (BOFF-8874).'\n );\n }\n const [, result] = await rootClient.$transaction([pendingContext, pendingQuery]);\n return result;\n}\n\n// ============================================================================\n// Caller transactions (BOFF-8874)\n// ============================================================================\n//\n// `runOperationWithRlsGuc` above opens its OWN interactive transaction per\n// operation. That is right for a standalone call, but wrong when the operation is\n// issued on the `tx` client inside a caller's `prisma.$transaction(...)`: the\n// operation would commit on another connection, so the caller's transaction\n// would not be atomic and its `SELECT … FOR UPDATE` fences would run without the\n// GUC (matching no rows under FORCE RLS, so locking nothing).\n//\n// Inside a caller transaction the extension now runs the context statement\n// (`set_config(..., is_local => true)`, identical to `SET LOCAL`) on the caller's\n// transaction itself, once per transaction and workspace, and then executes the\n// operation in place. Batch transactions (`$transaction([...])`) get the same\n// statement prepended to the batch by the client-level `$transaction` wrapper in\n// `addWorkspaceExtension`. Outside any transaction nothing changes.\n\n/**\n * Prisma passes the transaction an operation belongs to on the query-extension\n * callback's `__internalParams.transaction`: `{ kind: 'itx', id, payload }` for an\n * interactive transaction, `{ kind: 'batch', … }` for `$transaction([...])`, and\n * nothing for a standalone call. The `live-pg` contract test pins this down\n * against the installed Prisma version.\n */\nexport interface PrismaQueryInternalParams {\n transaction?: unknown;\n}\n\n/** The caller transaction an operation runs in, if any. */\nexport type CallerTransaction = { kind: 'itx'; id: string; descriptor: object } | { kind: 'batch' };\n\n/**\n * Classify the transaction an extension callback is running in.\n *\n * Throws on a transaction descriptor this version does not understand rather\n * than guessing: running such an operation down the standalone path would\n * silently break the caller's atomicity again.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport function getCallerTransaction(\n internalParams: PrismaQueryInternalParams | undefined\n): CallerTransaction | undefined {\n const transaction = internalParams?.transaction;\n if (transaction === undefined || transaction === null) return undefined;\n if (typeof transaction === 'object') {\n const { kind, id } = transaction as { kind?: unknown; id?: unknown };\n if (kind === 'itx' && typeof id === 'string' && id.length > 0) {\n return { kind: 'itx', id, descriptor: transaction };\n }\n if (kind === 'batch') return { kind: 'batch' };\n }\n throw new Error(\n '[WorkspaceExtension] Unrecognised Prisma transaction descriptor on __internalParams.transaction; ' +\n 'refusing to run the operation outside the caller transaction. This Prisma version is not supported ' +\n 'by the be-sdk RLS transaction integration (BOFF-8874).'\n );\n}\n\n/** Same sanitisation as the standalone path: CUID/UUID-safe, prevents SQL injection. */\nfunction sanitizeWorkspaceId(workspaceId: string | undefined): string {\n return (workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n}\n\n/** Same tag `maybeTagConnection` sets: `svc=<SERVICE_NAME>;ws=<workspaceId>`. */\nfunction buildApplicationNameTag(wsCtx: WorkspaceContext): string {\n const safeSvc = (process.env['SERVICE_NAME'] ?? 'svc').replace(/[^a-zA-Z0-9\\-_]/g, '');\n return `svc=${safeSvc};ws=${sanitizeWorkspaceId(wsCtx.workspaceId)}`;\n}\n\n/** A single parameterised statement that sets the transaction-local context. */\nexport interface TransactionContextStatement {\n sql: string;\n params: string[];\n /** Identifies the values set, so a transaction only re-runs it when they change. */\n key: string;\n}\n\n/**\n * Build the transaction-local context statement for the enabled tagging modes,\n * or `undefined` when neither RLS GUC nor application_name tagging is on.\n * `set_config(name, value, true)` is exactly `SET LOCAL name = value`.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport function buildTransactionContextStatement(\n wsCtx: WorkspaceContext,\n config: Pick<Required<WorkspaceExtensionConfig>, 'enableRlsGucTagging' | 'enableApplicationNameTagging'>\n): TransactionContextStatement | undefined {\n const settings: string[] = [];\n const params: string[] = [];\n if (config.enableRlsGucTagging) {\n params.push(sanitizeWorkspaceId(wsCtx.workspaceId));\n settings.push(`set_config('app.workspace_id', $${params.length}, true)`);\n }\n if (config.enableApplicationNameTagging) {\n params.push(buildApplicationNameTag(wsCtx));\n settings.push(`set_config('application_name', $${params.length}, true)`);\n }\n if (settings.length === 0) return undefined;\n return { sql: `SELECT ${settings.join(', ')}`, params, key: params.join('\\u0000') };\n}\n\n/**\n * A raw Prisma statement before it runs. Prisma's lazy `PrismaPromise` exposes\n * `requestTransaction(descriptor)`, which is how `$transaction` binds statements to\n * a transaction; the extension uses it to run the context statement on the\n * caller's transaction instead of a pooled connection of its own.\n */\ntype PendingRawStatement = PromiseLike<number> & {\n requestTransaction?: (transaction: object) => PromiseLike<unknown>;\n};\n\n/** Unextended client surface for issuing the context statement. */\nexport type RawPrismaForCallerTransaction = {\n $executeRawUnsafe: (query: string, ...values: unknown[]) => PendingRawStatement;\n};\n\ninterface CallerTransactionState {\n /** Descriptor of the (possibly nested) transaction level the context was set on. */\n descriptor: object;\n key: string;\n ready: Promise<void>;\n inflight: number;\n}\n\n/**\n * Context already applied per caller transaction id. Bounded: an evicted entry\n * only costs one repeated context statement, never correctness.\n */\nconst MAX_TRACKED_CALLER_TRANSACTIONS = 4096;\nconst callerTransactionStates = new Map<string, CallerTransactionState>();\n\nfunction rememberCallerTransaction(id: string, state: CallerTransactionState): void {\n callerTransactionStates.delete(id);\n callerTransactionStates.set(id, state);\n if (callerTransactionStates.size > MAX_TRACKED_CALLER_TRANSACTIONS) {\n const oldest = callerTransactionStates.keys().next().value;\n if (oldest !== undefined) callerTransactionStates.delete(oldest);\n }\n}\n\nasync function applyCallerTransactionContext(\n rawPrisma: RawPrismaForCallerTransaction,\n descriptor: object,\n statement: TransactionContextStatement\n): Promise<void> {\n const pending = rawPrisma.$executeRawUnsafe(statement.sql, ...statement.params);\n if (typeof pending.requestTransaction !== 'function') {\n throw new Error(\n '[WorkspaceExtension] Cannot bind the RLS context statement to the caller transaction ' +\n '(PrismaPromise.requestTransaction is unavailable); refusing to run it on another connection (BOFF-8874).'\n );\n }\n await pending.requestTransaction(descriptor);\n}\n\n/**\n * Run `run` (the operation, already bound to the caller's interactive\n * transaction by Prisma) after making sure that transaction carries the\n * workspace context. The context statement runs on the caller's transaction,\n * once per transaction level and workspace: a later operation for the same\n * workspace costs no extra round trip, a workspace switch re-runs it, and so does\n * the first operation after entering or leaving a nested transaction (a\n * savepoint rollback reverts `SET LOCAL`, a release keeps it).\n *\n * Concurrent operations for *different* workspaces on one transaction cannot be\n * isolated from each other, so that case throws instead of risking one running\n * under the other's GUC.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport async function runOperationInCallerTransaction<TResult>(\n rawPrisma: RawPrismaForCallerTransaction,\n transaction: { id: string; descriptor: object },\n wsCtx: WorkspaceContext,\n config: Pick<Required<WorkspaceExtensionConfig>, 'enableRlsGucTagging' | 'enableApplicationNameTagging'>,\n run: () => Promise<TResult>\n): Promise<TResult> {\n const statement = buildTransactionContextStatement(wsCtx, config);\n if (!statement) return run();\n\n let state = callerTransactionStates.get(transaction.id);\n if (!state || state.descriptor !== transaction.descriptor || state.key !== statement.key) {\n if (state && state.inflight > 0 && state.key !== statement.key) {\n throw new Error(\n '[WorkspaceExtension] Concurrent operations for different workspaces inside one transaction are not ' +\n 'supported: the RLS context is per transaction. Await the other workspace’s operations first.'\n );\n }\n const next: CallerTransactionState = {\n descriptor: transaction.descriptor,\n key: statement.key,\n ready: applyCallerTransactionContext(rawPrisma, transaction.descriptor, statement),\n inflight: 0,\n };\n next.ready.catch(() => {\n if (callerTransactionStates.get(transaction.id) === next) callerTransactionStates.delete(transaction.id);\n });\n rememberCallerTransaction(transaction.id, next);\n state = next;\n }\n\n state.inflight += 1;\n try {\n await state.ready;\n return await run();\n } finally {\n state.inflight -= 1;\n }\n}\n\n/** @internal Test hook: forget all tracked caller transactions. */\nexport function resetCallerTransactionStateForTests(): void {\n callerTransactionStates.clear();\n}\n\nexport function addWorkspaceExtension<T>(baseClient: T, config?: WorkspaceExtensionConfig): T {\n const fullConfig: Required<WorkspaceExtensionConfig> = {\n ...defaultWorkspaceExtensionConfig,\n ...config,\n };\n\n if (!fullConfig.enabled) {\n logger.info('[WorkspaceExtension] Extension disabled by configuration');\n return baseClient;\n }\n\n configureWorkspaceContextFallback(fullConfig.contextFallback);\n\n // Capture the unwrapped client for connection tagging (pre-extension, avoids recursion)\n const rawPrisma = baseClient as unknown as RawPrismaForTagging;\n // Same unwrapped client, typed for a lazy query-continuation batch; no new pool.\n const rawPrismaForContinuations = baseClient as unknown as RawPrismaForRlsContinuation;\n // Capture the pre-wrapper transaction method, but preserve its final receiver\n // when invoked. Selecting $parent would discard query extensions added later.\n const transactionDelegate = (baseClient as unknown as TransactionDelegate).$transaction;\n // Same unwrapped client again, typed for binding the context statement to a\n // caller's transaction (see runOperationInCallerTransaction).\n const rawPrismaForCallerTransactions = baseClient as unknown as RawPrismaForCallerTransaction;\n const tagsTransactions = fullConfig.enableRlsGucTagging || fullConfig.enableApplicationNameTagging;\n\n /**\n * Execute an operation whose args have already been workspace-injected.\n *\n * - Inside a caller's interactive transaction: set the context on that\n * transaction (once) and run the operation in place, so it is atomic with\n * the rest of the caller's transaction and its locks last until commit.\n * - Inside a batch `$transaction([...])`: run in place; the `$transaction`\n * wrapper below prepended the context statement to the batch.\n * - Standalone: unchanged — session application_name tag, then the\n * operation in its own `SET LOCAL` transaction when RLS tagging is on.\n */\n const dispatch = async (\n params: { model: string; query: (args: unknown) => Promise<unknown>; __internalParams?: PrismaQueryInternalParams },\n wsCtx: WorkspaceContext,\n _operation: string,\n finalArgs: unknown\n ): Promise<unknown> => {\n // No tagging: nothing is set per operation, so every call runs in place\n // exactly as before (inside a caller transaction or not). An explicit-argument\n // context never tags either, so RLS stays independent of the arguments.\n if (!tagsTransactions || explicitArgumentContexts.has(wsCtx)) return params.query(finalArgs);\n const callerTransaction = getCallerTransaction(params.__internalParams);\n if (callerTransaction?.kind === 'itx') {\n return runOperationInCallerTransaction(rawPrismaForCallerTransactions, callerTransaction, wsCtx, fullConfig, () =>\n params.query(finalArgs)\n );\n }\n if (callerTransaction?.kind === 'batch') {\n return params.query(finalArgs);\n }\n if (fullConfig.enableApplicationNameTagging) {\n await maybeTagConnection(rawPrisma, wsCtx);\n }\n if (fullConfig.enableRlsGucTagging) {\n return runQueryWithRlsGuc(rawPrismaForContinuations, wsCtx, () => params.query(finalArgs));\n }\n return params.query(finalArgs);\n };\n\n /**\n * Raw SQL inside a caller's interactive transaction gets the same context, so\n * `SELECT … FOR UPDATE` fences and raw reads/writes see the caller's workspace\n * under FORCE RLS. Standalone raw SQL is unchanged (no context statement).\n */\n const rawOperation = async ({ args, query, __internalParams }: RawOperationHandlerParams): Promise<unknown> => {\n if (!tagsTransactions) return query(args);\n const callerTransaction = getCallerTransaction(__internalParams);\n if (callerTransaction?.kind !== 'itx') return query(args);\n const wsCtx = getWorkspaceContext();\n if (!wsCtx?.workspaceId) return query(args);\n return runOperationInCallerTransaction(rawPrismaForCallerTransactions, callerTransaction, wsCtx, fullConfig, () =>\n query(args)\n );\n };\n\n // Type assertion for Prisma client $extends\n const prismaClient = baseClient as { $extends: (args: unknown) => T };\n\n logger.info('[WorkspaceExtension] Workspace extension enabled', {\n populateContextJson: fullConfig.populateContextJson,\n populateCreatedBy: fullConfig.populateCreatedBy,\n populateUpdatedBy: fullConfig.populateUpdatedBy,\n populateTenantId: fullConfig.populateTenantId,\n enableReadIsolation: fullConfig.enableReadIsolation,\n enableDeleteIsolation: fullConfig.enableDeleteIsolation,\n enableUpdateWhereIsolation: fullConfig.enableUpdateWhereIsolation,\n strictMode: fullConfig.strictMode,\n excludeModels: fullConfig.excludeModels,\n excludeModelsFromReadIsolation: fullConfig.excludeModelsFromReadIsolation,\n allowedUnguardedOperations: fullConfig.allowedUnguardedOperations,\n contextFallback: getWorkspaceContextFallbackMode(),\n enableApplicationNameTagging: fullConfig.enableApplicationNameTagging,\n enableRlsGucTagging: fullConfig.enableRlsGucTagging,\n });\n\n // Raw SQL hooks only matter when a context statement exists to apply.\n const rawOperationHooks = tagsTransactions\n ? {\n $queryRaw: rawOperation,\n $executeRaw: rawOperation,\n $queryRawUnsafe: rawOperation,\n $executeRawUnsafe: rawOperation,\n $queryRawTyped: rawOperation,\n }\n : {};\n\n const withQueryHooks = prismaClient.$extends({\n query: {\n ...rawOperationHooks,\n $allModels: {\n // ================================================================\n // WRITE OPERATIONS - inject workspaceId into data\n // ================================================================\n\n async create({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n // Skip if model is excluded or injection is explicitly skipped\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('create', args);\n enforceStrictMode(model, 'create', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n // Inject fields into data\n const injectedData = injectCreateFields(args.data, wsCtx, fullConfig);\n\n if (fullConfig.debug) {\n const injectedKeys = Object.keys(injectedData).filter((k) => !(k in args.data));\n if (injectedKeys.length > 0) {\n logger.debug(`[WorkspaceExtension] ${model}.create - injected: ${injectedKeys.join(', ')}`, {\n workspaceId: wsCtx.workspaceId,\n actorId: wsCtx.actorId,\n });\n }\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: injectedData,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'create', finalArgs);\n },\n\n async createMany({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown> | Record<string, unknown>[];\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('createMany', args);\n enforceStrictMode(model, 'createMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n // Handle both single object and array\n const dataArray = Array.isArray(args.data) ? args.data : [args.data];\n const injectedData = dataArray.map((item) => injectCreateFields(item, wsCtx, fullConfig));\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: Array.isArray(args.data) ? injectedData : injectedData[0],\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'createMany', finalArgs);\n },\n\n async createManyAndReturn({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown> | Record<string, unknown>[];\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('createManyAndReturn', args);\n enforceStrictMode(model, 'createManyAndReturn', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const dataArray = Array.isArray(args.data) ? args.data : [args.data];\n const injectedData = dataArray.map((item) => injectCreateFields(item, wsCtx, fullConfig));\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: Array.isArray(args.data) ? injectedData : injectedData[0],\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'createManyAndReturn', finalArgs);\n },\n\n // ================================================================\n // UPDATE OPERATIONS - inject updatedBy into data + workspaceId into where\n // ================================================================\n\n async update({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown>;\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('update', args);\n enforceStrictMode(model, 'update', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedData = injectUpdateFields(args.data, wsCtx, fullConfig);\n\n // Inject workspaceId into where clause for update isolation\n let injectedWhere = args.where;\n if (fullConfig.enableUpdateWhereIsolation && !isExcludedFromReadIsolation(model, fullConfig)) {\n injectedWhere = injectWhereClause(args.where, wsCtx);\n }\n\n if (fullConfig.debug) {\n const injectedDataKeys = Object.keys(injectedData).filter((k) => !(k in args.data));\n const whereChanged = injectedWhere !== args.where;\n if (injectedDataKeys.length > 0 || whereChanged) {\n logger.debug(\n `[WorkspaceExtension] ${model}.update - injected data: ${injectedDataKeys.join(', ')}${whereChanged ? ', where: workspaceId' : ''}`\n );\n }\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: injectedData,\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'update', finalArgs);\n },\n\n async updateMany({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown>;\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('updateMany', args);\n enforceStrictMode(model, 'updateMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedData = injectUpdateFields(args.data, wsCtx, fullConfig);\n\n // Inject workspaceId into where clause for update isolation\n let injectedWhere = args.where;\n if (fullConfig.enableUpdateWhereIsolation && !isExcludedFromReadIsolation(model, fullConfig)) {\n injectedWhere = injectWhereClause(args.where, wsCtx);\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: injectedData,\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'updateMany', finalArgs);\n },\n\n async upsert({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n create: Record<string, unknown>;\n update: Record<string, unknown>;\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('upsert', args);\n enforceStrictMode(model, 'upsert', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedCreate = injectCreateFields(args.create, wsCtx, fullConfig);\n const injectedUpdate = injectUpdateFields(args.update, wsCtx, fullConfig);\n\n // Inject workspaceId into where clause for upsert isolation\n let injectedWhere = args.where;\n if (fullConfig.enableUpdateWhereIsolation && !isExcludedFromReadIsolation(model, fullConfig)) {\n injectedWhere = injectWhereClause(args.where, wsCtx);\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n create: injectedCreate,\n update: injectedUpdate,\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'upsert', finalArgs);\n },\n\n // ================================================================\n // READ OPERATIONS - inject workspaceId into where clause\n // ================================================================\n\n async findMany({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('findMany', args);\n enforceStrictMode(model, 'findMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findMany - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findMany', finalArgs);\n },\n\n async findFirst({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('findFirst', args);\n enforceStrictMode(model, 'findFirst', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findFirst - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findFirst', finalArgs);\n },\n\n async findFirstOrThrow({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('findFirstOrThrow', args);\n enforceStrictMode(model, 'findFirstOrThrow', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findFirstOrThrow - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findFirstOrThrow', finalArgs);\n },\n\n async findUnique({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('findUnique', args);\n enforceStrictMode(model, 'findUnique', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n // For findUnique, the where clause uses unique fields.\n // We inject workspaceId only if the where clause is a plain object\n // (compound unique keys with workspaceId are common and already include it).\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findUnique - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findUnique', finalArgs);\n },\n\n async findUniqueOrThrow({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('findUniqueOrThrow', args);\n enforceStrictMode(model, 'findUniqueOrThrow', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findUniqueOrThrow - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findUniqueOrThrow', finalArgs);\n },\n\n async count({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('count', args);\n enforceStrictMode(model, 'count', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.count - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'count', finalArgs);\n },\n\n async aggregate({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('aggregate', args);\n enforceStrictMode(model, 'aggregate', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.aggregate - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'aggregate', finalArgs);\n },\n\n async groupBy({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('groupBy', args);\n enforceStrictMode(model, 'groupBy', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.groupBy - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'groupBy', finalArgs);\n },\n\n // ================================================================\n // DELETE OPERATIONS - inject workspaceId into where clause\n // ================================================================\n\n async delete({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableDeleteIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('delete', args);\n enforceStrictMode(model, 'delete', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.delete - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'delete', finalArgs);\n },\n\n async deleteMany({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableDeleteIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = resolveOperationContext('deleteMany', args);\n enforceStrictMode(model, 'deleteMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.deleteMany - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'deleteMany', finalArgs);\n },\n },\n },\n });\n\n // Batch transactions: Prisma runs `$transaction([...])` members in one database\n // transaction, but an operation hook cannot add a statement to the batch. So\n // wrap `$transaction` itself and prepend the context statement; its result is\n // dropped so callers get exactly their own members' results. The function form\n // binds lazy consumption inside its callback; query hooks still apply RLS GUCs.\n // `$parent` is the client one extension layer down (the query-hooked client\n // above), so members and nested transactions keep every hook.\n const wrapped = withQueryHooks as unknown as { $extends: (args: unknown) => T };\n return wrapped.$extends({\n client: {\n $transaction(this: { $parent?: TransactionDelegate }, input: unknown, options?: unknown): Promise<unknown> {\n const parent = this.$parent;\n if (!parent) {\n throw new Error('[WorkspaceExtension] $transaction wrapper could not resolve its parent client.');\n }\n if (Array.isArray(input)) {\n const wsCtx = getWorkspaceContext();\n const statement =\n tagsTransactions && wsCtx?.workspaceId ? buildTransactionContextStatement(wsCtx, fullConfig) : undefined;\n if (statement) {\n const setContext = rawPrismaForCallerTransactions.$executeRawUnsafe(statement.sql, ...statement.params);\n return parent\n .$transaction([setContext, ...input], options)\n .then((results) => (Array.isArray(results) ? results.slice(1) : results));\n }\n }\n // The native delegate reads the final client's extension chain. Calling\n // it on $parent would silently omit later graph/audit query hooks.\n if (typeof input === 'function') {\n // Keep lazy returned operations in their originating callback context,\n // including Bun thenable assimilation after an awaited earlier query.\n const callback = input as (tx: object) => Promise<unknown>;\n return transactionDelegate.call(\n this,\n async (tx: object) => {\n const scope = { active: true };\n try {\n return await callback(bindTransactionContext(tx, scope, getWorkspaceContext));\n } finally {\n scope.active = false;\n }\n },\n options\n );\n }\n return transactionDelegate.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